-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathwriter.py
More file actions
445 lines (387 loc) · 18.2 KB
/
Copy pathwriter.py
File metadata and controls
445 lines (387 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import bases
import line_shapes
import numpy as np
import matplotlib.pyplot as plt
import os
from tqdm.auto import tqdm
import glob
import json
def get_attributes(spell_data):
level = spell_data['level']
range = spell_data['range']
school = spell_data['school']['name']
duration = spell_data['duration']
concentration = spell_data["concentration"]
ritual = spell_data["ritual"]
if "damage" in spell_data.keys():
if "damage_type" in spell_data["damage"].keys():
dtype = spell_data['damage']['damage_type']['name']
else:
dtype = "None"
else:
dtype = "None"
if "area_of_effect" in spell_data.keys():
area_of_effect = spell_data['area_of_effect']
area_of_effect = f'{area_of_effect["type"]} ({area_of_effect["size"]})'
else:
area_of_effect = "None"
return(level,range,area_of_effect,dtype,school,duration,concentration,ritual)
def get_spell(spell_name,spell_dir = "spells/"):
files = glob.glob(f"{spell_dir}{spell_name}.json")
if len(files) == 0:
raise LookupError(f"Could not find {spell_dir}{spell_name}.json")
elif len(files) > 1:
raise LookupError(f'Found too many results for {spell_name}. Got {files}')
with open(files[0]) as f:
data = json.load(f)
f.close()
return(data)
cmap = plt.get_cmap('viridis')
#---------Functions for creating unique binary numbers------
def cycle_list(l,loops = 1):
n = len(l)
for t in range(loops):
l = [l[(i+1) % n] for i in range(n)]
return(l)
def generate_unique_combinations(L):
combinations = generate_binary_strings(L)
non_repeating = [combinations[0]]
for i in tqdm(range(len(combinations)),desc = "Genearting Unique Binary Numbers"):
ref = list(combinations[i])
N = len(ref)
test = 0
for j in range(len(non_repeating)):
for n in range(N):
if cycle_list(list(non_repeating[j]),loops = n+1) == ref:
test += 1
if test == 0:
non_repeating.append(combinations[i])
for i in np.arange(len(non_repeating)):
non_repeating[i] = [int(s) for s in list(non_repeating[i])]
return(non_repeating)
def genbin(n, bs = ''):
if n-1:
genbin(n-1, bs + '0')
genbin(n-1, bs + '1')
else:
print('1' + bs)
def generate_binary_strings(bit_count):
binary_strings = []
def genbin(n, bs=''):
if len(bs) == n:
binary_strings.append(bs)
else:
genbin(n, bs + '0')
genbin(n, bs + '1')
genbin(bit_count)
return binary_strings
#-------Functions for drawing runes
def decode_shape(in_array,k=1,point_color = 'k',on_color = 'darkred',off_color = "grey",
label = None,base_fn = bases.polygon,base_kwargs = [],
shape_fn = line_shapes.straight,shape_kwargs = [],
plot_base = False):
#decodes a single array into a given base, use plot_base = True if you are plotting it on its own
n = len(in_array)
x,y = base_fn(n,*base_kwargs)
if plot_base == True:
plt.scatter(x[1:],y[1:],s = 70,facecolors = 'none', edgecolors = point_color)
plt.scatter(x[0],y[0],s = 70,facecolors = point_color, edgecolors = point_color)
plt.axis('off')
plt.axis('scaled')
for i,elem in enumerate(in_array):
P = [x[i],y[i]]
Q = [x[(i+k)%n],y[(i+k)%n]]
X,Y = shape_fn(P,Q,*shape_kwargs)
if elem == 0:
plt.plot(X,Y,color = off_color,ls = "--",linewidth=0.25)
elif elem == 1:
plt.plot(X,Y,color = on_color,ls = "-",label = label if i == np.where(in_array == 1)[0][0] else None,
linewidth = 2)
else:
print(f'elem {elem} at index {i} is not valid, input being skipped')
def draw_multiple_inputs(in_array,
base_fn = bases.polygon,base_kwargs = [],
shape_fn = line_shapes.straight,shape_kwargs = [],
point_color = 'k',labels = [],legend = False,colors = [],
legend_loc = "upper left",annotate = False):
#draws multiple inputs on a single base
if isinstance(colors,list) and len(colors) == 0:
colors = [point_color]*in_array.shape[0]
elif isinstance(colors,str):
colors = [colors]*in_array.shape[0]
n = in_array.shape[1]
x,y = base_fn(n,*base_kwargs)
plt.scatter(x[1:],y[1:],s = 70,facecolors = 'none', edgecolors = point_color)
plt.scatter(x[0],y[0],s = 70,facecolors = point_color, edgecolors = point_color)
if annotate:
for i in range(len(x)):
plt.annotate(str(i),(x[i]+0.1,y[i]+0.1))
if len(labels) != in_array.shape[0]:
labels = [None]*in_array.shape[0]
for i,k in enumerate(range(in_array.shape[0])):
decode_shape(in_array[i],k = k+1,base_fn = base_fn,base_kwargs = base_kwargs,
shape_fn = shape_fn,shape_kwargs = shape_kwargs,label = labels[i],on_color = colors[i])
if labels[0] != None and legend == True:
plt.legend(loc = legend_loc,fontsize = 10)
plt.axis('off')
plt.axis('scaled')
def load_attribute(fname):
with open(fname,"r") as f:
data = f.readlines()
f.close()
data = [d.replace("\n","").lower() for d in data]
return(data)
def draw_spell(level,rang,area,dtype,school,title = None,
savename = "output.png",legend = False,
base_fn = bases.polygon,base_kwargs = [],
shape_fn = line_shapes.straight,shape_kwargs = [],
colors = [],legend_loc = "upper left",breakdown = False):
#draws a spell given certain values by comparing it to input txt
ranges = load_attribute("Attributes/range.txt")
levels = load_attribute("Attributes/levels.txt")
area_types = load_attribute("Attributes/area_types.txt")
dtypes = load_attribute("Attributes/damage_types.txt")
schools = load_attribute("Attributes/school.txt")
i_range = ranges.index(rang)
i_levels = levels.index(str(level))
i_area = area_types.index(area)
i_dtype = dtypes.index(dtype)
i_school = schools.index(school)
attributes = [i_levels,i_school,i_dtype,i_area,i_range]
labels = [f"level: {level}",
f"school: {school}",
f"damage type: {dtype}",
f"range: {rang}",
f"area_type: {area}"]
N = 2*len(attributes)+1
if len(colors) == 0 and breakdown == True:
colors = [cmap(i/len(attributes)) for i in range(len(attributes))]
if not os.path.isdir("Uniques/"):
os.makedirs("Uniques/")
if os.path.isfile(f'Uniques/{N}.npy'):
non_repeating = np.load(f'Uniques/{N}.npy')
else:
non_repeating = generate_unique_combinations(N)
non_repeating = np.array(non_repeating)
np.save(f"Uniques/{N}.npy",non_repeating)
input_array = np.array([non_repeating[i] for i in attributes])#note +1 s.t. 0th option is always open for empty input
#print(input_array)
draw_multiple_inputs(input_array,labels = labels,legend = legend,
base_fn = base_fn,base_kwargs = base_kwargs,
shape_fn = shape_fn,shape_kwargs = shape_kwargs,
colors = colors,legend_loc = legend_loc)
plt.title(title,fontsize = "80")
if savename is not None:
plt.savefig(savename,transparent = False, bbox_inches='tight')
plt.clf()
else:
plt.show()
def draw_spell_2(level,rang,area,dtype,school,duration,concentration,ritual,title = None,
savename = "output.png",legend = False,
base_fn = bases.polygon,base_kwargs = [],
shape_fn = line_shapes.straight,shape_kwargs = [],
colors = [],legend_loc = "upper left",breakdown = False,
base_dir = "",return_input_array = False,spell_shift = None,
annotate = False):
#draws a spell given certain values by comparing it to input txt
ranges = load_attribute(base_dir +"Attributes/range.txt")
levels = load_attribute(base_dir +"Attributes/levels.txt")
area_types = load_attribute(base_dir +"Attributes/area_types.txt")
dtypes = load_attribute(base_dir +"Attributes/damage_types.txt")
schools = load_attribute(base_dir +"Attributes/school.txt")
durations = load_attribute(base_dir +"Attributes/duration.txt")
area_types[0] = "none"
dtypes[0] = "none"
i_range = ranges.index(rang.lower())
i_levels = levels.index(str(level).lower())
i_area = area_types.index(area.lower())
i_dtype = dtypes.index(dtype.lower())
i_school = schools.index(school.lower())
i_duration = durations.index(duration.lower())
attributes = [i_levels,i_school,i_dtype,i_area,i_range,i_duration]
att_len = [len(levels),len(schools),len(dtypes),len(area_types),len(ranges),len(durations)]
labels = [f"level: {level}",
f"school: {school}",
f"damage type: {dtype}",
f"range: {rang}",
f"area_type: {area}",
f'duration: {duration}']
N = 2*len(attributes)+1
if len(colors) == 0 and breakdown == True:
colors = [cmap(i/len(attributes)) for i in range(len(attributes))]
elif len(colors) == 0:
colors = 'k'
if not os.path.isdir(base_dir +"Uniques/"):
os.makedirs(base_dir +"Uniques/")
if os.path.isfile(base_dir +f'Uniques/{N}.npy'):
non_repeating = np.load(base_dir +f'Uniques/{N}.npy')
else:
non_repeating = generate_unique_combinations(N)
non_repeating = np.array(non_repeating)
np.save(base_dir +f"Uniques/{N}.npy",non_repeating)
non_repeating_att = [np.round(np.linspace(0, len(non_repeating) - 1, al)).astype(int) for al in att_len]
#input_array = np.array([non_repeating[non_repeating_att[j]][i] for j,i in enumerate(attributes)])#note +1 s.t. 0th option is always open for empty input
input_array = np.array([non_repeating[i] for j,i in enumerate(attributes)])
print(input_array)
if spell_shift is not None:
if isinstance(spell_shift,int):
spell_shift = [spell_shift]*13
assert len(spell_shift) == 13, f"spell_shift has {len(spell_shift)} values not 13"
for i in range(13):
input_array[:,i] = np.array(cycle_list(list(input_array[:,i]),spell_shift[i]))
if return_input_array:
return(input_array)
draw_multiple_inputs(input_array,labels = labels,legend = legend,
base_fn = base_fn,base_kwargs = base_kwargs,
shape_fn = shape_fn,shape_kwargs = shape_kwargs,
colors = colors,legend_loc = legend_loc,annotate = annotate)
if concentration:
plt.plot(0,0,"",markersize = 10,marker = ".",color = colors)
if ritual:
plt.plot(0,0,"",markersize = 10,marker = ".",color= colors)
plt.plot(0,0,"",markersize = 20,marker = "o",color=colors,mfc='none',linewidth = 10)
plt.title(title)
if savename is not None:
plt.savefig(savename,transparent = False, bbox_inches='tight')
plt.clf()
else:
plt.show()
#to run if the file is called
def draw_attribute(level = None,rang = None, area = None,
savename = "output.png",legend = False,
dtype = None, school = None,duration = None,
base_fn = bases.polygon,base_kwargs = [],
shape_fn = line_shapes.straight,shape_kwargs = [],
colors = [],legend_loc = "upper left",breakdown = False,
title = None):
ranges = load_attribute("Attributes/range.txt")
levels = load_attribute("Attributes/levels.txt")
area_types = load_attribute("Attributes/area_types.txt")
dtypes = load_attribute("Attributes/damage_types.txt")
schools = load_attribute("Attributes/school.txt")
durations = load_attribute("Attributes/duration.txt")
i_range,i_levels,i_school,i_dtype,i_area,i_duration = 0,0,0,0,0,0
if rang is not None:
i_range = ranges.index(rang)
elif level is not None:
i_levels = levels.index(str(level))
elif area is not None:
i_area = area_types.index(area)
elif dtype is not None:
i_dtype = dtypes.index(dtype)
elif school is not None:
i_school = schools.index(school)
elif duration is not None:
i_duration = durations.index(duration)
attributes = [i_levels,i_school,i_dtype,i_area,i_range,i_duration]
labels = [f"level: {level}",
f"school: {school}",
f"damage type: {dtype}",
f"range: {rang}",
f"area_type: {area}",
f"duration: {duration}"]
N = 2*len(attributes)+1
if isinstance(colors,list) and len(colors) == 0 and breakdown == True:
colors = [cmap(i/len(attributes)) for i in range(len(attributes))]
if not os.path.isdir("Uniques/"):
os.makedirs("Uniques/")
if os.path.isfile(f'Uniques/{N}.npy'):
non_repeating = np.load(f'Uniques/{N}.npy')
else:
non_repeating = generate_unique_combinations(N)
non_repeating = np.array(non_repeating)
np.save(f"Uniques/{N}.npy",non_repeating)
input_array = []
for j,i in enumerate(attributes):
input_array.append(non_repeating[i])
input_array = np.array(input_array)#note +1 s.t. 0th option is always open for empty input
#print(input_array)
draw_multiple_inputs(input_array,labels = labels,legend = legend,
base_fn = base_fn,base_kwargs = base_kwargs,
shape_fn = shape_fn,shape_kwargs = shape_kwargs,
colors = colors,legend_loc = legend_loc)
plt.title(title,fontsize = 30)
if savename is not None:
plt.savefig(savename,dpi = 250,transparent = True, bbox_inches='tight')
plt.clf()
else:
plt.show()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-spell_name",help = "spell name",default = "fireball")
parser.add_argument("-level",help = "necessary input: level of the spell",
default = "3")
parser.add_argument("-range",help = "necessary input: range of the spell",
default = "150 feet")
parser.add_argument("-area",help = "necessary input: area type of the spell",
default = "sphere (30)")
parser.add_argument("-dtype",help = "necessary input: dtype of the spell",
default = "fire")
parser.add_argument("-school",help = "necessary input: school of the spell",
default = "evocation")
parser.add_argument("-duration",help = "Duration of the spell",
default = "Instantaneous")
parser.add_argument("--title",help = "title in plot",
default = None)
parser.add_argument("--savename",help = "savename of file",
default = "output.png")
parser.add_argument("-concentration",help = "include with --new if spell is concentration",action = "store_true")
parser.add_argument("-ritual",help = "include with --new if spell is a ritual",action = "store_true")
parser.add_argument("--new",help = "Option to use the new 13 point system",action = "store_true")
parser.add_argument("--legend",help = "bool to print legend or not",action='store_true')
parser.add_argument("--breakdown",help = "bool to control whether to breakdown the lines with colour",action='store_true')
parser.add_argument("-ah", "--arg_help",
help = "Prints the available options for the chosen attributes",
action=argparse.BooleanOptionalAction)
parser.add_argument("-c","--custom",help = "Run the non-standard code",action = 'store_true')
args = parser.parse_args()
if args.arg_help:
if args.range:
print("--------Range--------")
print("\n".join(load_attribute("Attributes/range.txt")))
if args.level:
print("--------Level--------")
print("\n".join(load_attribute("Attributes/levels.txt")))
if args.area:
print("--------Area--------")
print("\n".join(load_attribute("Attributes/area_types.txt")))
if args.dtype:
print("--------Damage Types--------")
print("\n".join(load_attribute("Attributes/damage_types.txt")))
if args.school:
print("--------School--------")
print("\n".join(load_attribute("Attributes/school.txt")))
else:
if not args.custom:
if not args.new:
draw_spell(level=args.level.lower(),rang=args.range.lower(),
area=args.area.lower(),dtype=args.dtype.lower(),
school=args.school.lower(),
title = args.title,legend = args.legend,
breakdown = args.breakdown,savename = args.savename)
plt.clf()
else:
draw_spell_2(level = args.level.lower(),rang = args.range.lower(),
area = args.area.lower(),dtype=args.dtype.lower(),
school = args.school.lower(),duration = args.duration.lower(),
concentration=args.concentration,ritual=args.ritual,title =args.title,
savename = args.savename,legend = args.legend,
breakdown = args.breakdown)
plt.clf()
else:
print("here")
base = bases.polygon
spellname = args.spell_name
spell_data = get_spell(spellname,"G:/python_backup/Python/SpellWriting2/spells/")
attr = get_attributes(spell_data)
print(attr)
draw_spell_2(*attr,title = spellname,
savename = "output.png",legend = False,
base_fn = base,base_kwargs = [],
shape_fn = line_shapes.non_centre_circle,shape_kwargs = [10],
colors = [],legend_loc = "upper left",breakdown = False,
base_dir = "",return_input_array = False,
spell_shift = np.random.randint(0,13,size = (13,)),
annotate = True
)