forked from SmilingZero/BlazeBlack2ReduxWiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pokemonDocWriter.py
498 lines (454 loc) · 20.2 KB
/
pokemonDocWriter.py
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import os
import json
import csv
from collections import OrderedDict
from difflib import SequenceMatcher
def unnest(d, keys=[]):
result = []
for k, v in d.items():
if isinstance(v, dict):
result.extend(unnest(v, keys + [k]))
else:
result.append(tuple(keys + [k, v]))
return result
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
pokemonIndexFile = './data/pokemonIndexList.csv'
with open(pokemonIndexFile, 'r', encoding='utf-8-sig') as indexFile:
reader = csv.reader(indexFile)
pokemonNumberMap = { row[2]: f"{int(row[1]):03}" for row in reader}
detailedMoveListFile = 'scrapedJSON/ref/moves_with_descriptions.json'
with open(detailedMoveListFile) as f:
detailedMoveList = json.load(f)
pokemonEncounterLocations = 'scrapedJSON/ref/pokemonEncounters.json'
with open(pokemonEncounterLocations) as f:
pokemonEncounters = json.load(f)
with open('locationLinkDict.json', mode = 'r') as f:
locationLinks = json.load(f)
def getTypeIncludes():
typesFolder = 'docs/img/type/'
typeFiles = os.listdir(typesFolder)
includeText = ''
for i, fname in enumerate(typeFiles):
typestring = fname.replace('.png', '')
typeInclude = "[{type}]: ../img/type/{fid}\n".format(type=typestring, fid=fname)
includeText += typeInclude
return includeText
def getSpeciesTypeString(typeList):
individualTypeStrings = ['![][{typename}]'.format(typename=s.lower()) for s in typeList]
return '<br>'.join(individualTypeStrings)
def getTopLevelHeader(pkmnInformation):
number = pkmnInformation['Number']
natDexNumber = f"{number:03}"
speciesName = pkmnInformation['Name']
formMarkerInd = speciesName.find('-')
if formMarkerInd != -1 and speciesName != 'Ho-Oh':
speciesName = speciesName[:formMarkerInd].strip()
headerText = "{number} - {speciesname}".format(number = natDexNumber, speciesname = speciesName)
return headerText
def getDefensesTable(defense):
tableHeader = '\n| ' + ' | '.join(defense.keys()) + ' |\n'
separator = '|: ' + ' :|: '.join(['---' for i in defense.keys()]) + ' :|\n'
def getCol(v):
if len(v) == 0:
return ' '
else:
return '<br>'.join(['![][{type}]'.format(type = i.lower()) for i in v])+'<br>'
contentRow = '| ' + ' | '.join([getCol(v) for k,v in defense.items()]) + ' |\n'
return tableHeader+separator+contentRow+'\n'
pokemonImageLookup = './data/speciesImageLookup.json'
with open(pokemonImageLookup, 'r') as f:
speciesImageLookup = json.load(f)
def getSpecies(mon):
hyphenInd = mon.find('-')
if('♂' in mon):
form = 'base'
species= 'nidoranu2642'
elif '♀' in mon:
form = 'base'
species= 'nidoranu2640'
elif 'Porygon-Z' == mon:
form = 'base'
species = 'porygonz'
elif 'Ho-Oh' == mon:
species = 'hooh'
form = 'base'
else:
if hyphenInd == -1:
form = 'base'
species = mon.lower().strip()
else:
form = mon[hyphenInd+1:].strip().lower()
species = mon[:hyphenInd].strip().lower()
species = "".join([ c if c.isalnum() else "" for c in species ])
return species, form
def getPokemonImage(name, form):
num = speciesImageLookup[name.lower()]['NatDexNum']
natDexNumber = f"{num:03}"
imString = "![][{nm}_{f}]".format(nm=natDexNumber, f = form)
fname = speciesImageLookup[name.lower()][form]
pkmnInclude = "[{nm}_{f}]: ../img/animated/{fid}\n".format(nm=natDexNumber, f = form, fid=fname)
return pkmnInclude, imString
def getEvolutionSection(evol):
def evolString(entry):
toMon = entry['To']
method = entry['Method']
if method == 'Happiness':
method = 'Level up with max happiness'
outString = '- [{toMon}]: {method}'.format(toMon=toMon, method = method)
return outString
def includeString(evol):
toMon = evol['To']
return '[{mon}]: ../{num}/'.format(mon=toMon, num=pokemonNumberMap[toMon])
content = [evolString(entry) for entry in evol]
incl = [includeString(entry) for entry in evol]
return '\n'.join(incl)+'\n', \
'\n'.join(content)+'\n'
def getSpriteTypeTable(name, form, type):
pkmnInclude, imString = getPokemonImage(name,form)
tableHeader = '\n| ' + ' | '.join([' ', 'Type']) + ' |\n'
separator = '|: ' + ' :|: '.join(['---' for i in [' ', ' ']]) + ' :|\n'
contentRow = '|' + '<br>'+imString + '|' + getSpeciesTypeString(type) + '|'
return pkmnInclude, tableHeader+separator+contentRow+ '\n\n'
def getAbilityTable(abi):
allHeaders = ['Ability 1', 'Ability 2', 'Hidden Ability']
header = '| ' + ' | '.join(allHeaders[0:len(abi)]) + ' |\n'
separator = '|: ' + ' :|: '.join(['---']*len(abi)) + ' :|\n'
content = '| ' + ' | '.join(abi) + ' |\n\n'
return header + separator + content
def getStatTable(l_stats):
stats = l_stats[0]
if len(l_stats) > 1:
vanilla_stats = l_stats[1]
stat_diff = { k: stats[k]-vanilla_stats[k] for k in stats.keys()}
else:
stat_diff = { 0 for k in stats.keys()}
cols = [i for i in stats.keys()]
cols.append('BST')
def get_header(t,d,w):
if d == 0:
return f"<th style=\"width:{w}%;align:center;vertical-align: middle;\">{t}</th>"
if d > 0:
s_diff_tag = 'sup'
s_color = 'green'
s_align = 'bottom'
d = '+' + str(d)
else:
s_diff_tag = 'sub'
s_color = 'red'
s_align = 'top'
return f"<th style=\"width:{w}%;align:center;vertical-align: middle;color:{s_color};\">{t}<{s_diff_tag} style = \"line-height:0px;vertical-align: 5px;font-size: 10px;color:{s_color}\">{d}</{s_diff_tag}></th>"
def getContentString(s,d,w):
if d == 0:
return f"<td style=\"width:{w}%;align:center;vertical-align: bottom;\">{s}</td>"
if d > 0:
s_diff_tag = 'sup'
s_color = 'green'
d = '+' + str(d)
else:
s_diff_tag = 'sub'
s_color = 'red'
return f"<td style=\"width:{w}%;align:center;vertical-align: middle;\">{s}<{s_diff_tag} style = \"color:{s_color}\">{d}</{s_diff_tag}></td>"
content = [v for i,v in enumerate(stats.values())]
content.append(sum(content))
diff = [v for i,v in enumerate(stat_diff.values())]
diff.append(sum(diff))
width = [14, 14, 14, 14, 14, 14, 16]
html_headers = [get_header(cols[t], diff[t], width[t]) for t in range(len(cols))]
html_content = [getContentString(content[i],0,width[i]) for i in range(len(content))]
header_row = "<tr>{h}</tr>".format(h=''.join(html_headers))
content_row = "<tr>{h}</tr>".format(h=''.join(html_content))
table_string = f'<table>{header_row}\n{content_row}</table>\n\n'
return table_string
def getItemString(itemList):
content = ['- {i}%: {j}'.format(i = item[0], j = item[1]) for item in itemList.items()]
return '\n'.join(content)+'\n'
def getMoveData(movename):
return [i for i in detailedMoveList if i['Name'].lower().replace(' ', '') == movename.lower().replace(' ', '')][0]
def getTMtable(moveList):
def getTmDict(move):
movedata = getMoveData(move['Name'])
movedata['Machine'] = move['Machine']
return movedata
tmData = {i : getTmDict(move) for i, move in enumerate(moveList) }
tableColumns = ['Machine', 'Name', 'Power', 'Accuracy', 'PP' ,'Type', 'Damage Class', 'Effect']
tableHeader = '| ' + ' | '.join(tableColumns) + ' |\n'
separator = '|: ' + ' :|: '.join(['---']*len(tableColumns)) + ' :|\n'
def makeTMRow(tm):
row = '| ' + \
str(tm['Machine']) + ' | ' + \
tm['Name'] + ' | ' +\
str(tm['Power']) + ' | ' +\
str(tm['Accuracy']) + ' | ' +\
str(tm['PP']) + ' | ' +\
'![]['+tm['Type'].lower()+']' + ' | ' +\
'![]['+tm['Damage Class'].lower()+']' + ' | ' +\
'Priority: {prio}. {effect}'.format(prio = tm['Priority'], effect = str(tm['Effect']).replace('\n', '<br>')) + ' |'
return row
contentRows = [makeTMRow(data) for i,data in tmData.items()]
return '', tableHeader+separator+'\n'.join(contentRows) +'\n\n'
def getLevelUpTable(moveList):
def getLvlUpDict(move):
movedata = getMoveData(move['Move'])
movedata['Level'] = move['Level']
return movedata
lvlUpData =[ {i : getLvlUpDict(move)} for i, move in enumerate(moveList) ]
tableColumns = ['Level', 'Name', 'Power', 'Accuracy', 'PP' ,'Type', 'Damage Class', 'Effect']
tableHeader = '| ' + ' | '.join(tableColumns) + ' |\n'
separator = '|: ' + ' :|: '.join(['---']*len(tableColumns)) + ' :|\n'
def makeLevelRow(i,level):
level = level [i]
row = '| ' + \
str(level['Level']) + ' | ' + \
level['Name'] + ' | ' +\
str(level['Power']) + ' | ' +\
str(level['Accuracy']) + ' | ' +\
str(level['PP']) + ' | ' +\
'![]['+level['Type'].lower()+']' + ' | ' +\
'![]['+level['Damage Class'].lower()+']' + ' | ' +\
'Priority: {prio}. {effect}'.format(prio = level['Priority'], effect = str(level['Effect']).replace('\n', '<br>')) + ' |'
return row
contentRows = [makeLevelRow(i,data) for i,data in enumerate(lvlUpData)]
return '', tableHeader+separator+'\n'.join(contentRows) +'\n\n'
def getTutorTable(moveList):
def getTutorDict(move):
movedata = getMoveData(move)
return movedata
tutorData = {i : getTutorDict(move) for i, move in enumerate(moveList) }
tableColumns = [' ', 'Name', 'Power', 'Accuracy', 'PP' ,'Type', 'Damage Class','Effect']
tableHeader = '| ' + ' | '.join(tableColumns) + ' |\n'
separator = '|: ' + ' :|: '.join(['---']*len(tableColumns)) + ' :|\n'
def makeLevelRow(level):
row = '| ' + \
'Tutor' + ' | ' + \
level['Name'] + ' | ' +\
str(level['Power']) + ' | ' +\
str(level['Accuracy']) + ' | ' +\
str(level['PP']) + ' | ' +\
'![]['+level['Type'].lower()+']' + ' | ' +\
'![]['+level['Damage Class'].lower()+']' + ' | ' +\
'Priority: {prio}. {effect}'.format(prio = level['Priority'], effect = str(level['Effect']).replace('\n', '<br>')) + ' |'
return row
contentRows = [makeLevelRow(data) for i,data in tutorData.items()]
return '', tableHeader+separator+'\n'.join(contentRows) +'\n\n'
def getPreEvoMoveSection(moveList):
tableColumns = ['Species', 'Method', 'Move']
tableHeader = '| ' + ' | '.join(tableColumns) + ' |\n'
separator = '|: ' + ' :|: '.join(['---']*len(tableColumns)) + ' :|\n'
def makeRow(entry):
row = '| {species} | {method} | {move} |'.format(species = entry[0], method = entry[1], move = entry[2])
return row
contentRows = [makeRow(data) for data in moveList]
return '', tableHeader+separator+'\n'.join(contentRows) +'\n\n'
def getPokemonMarkdown(pkmnInformation):
headerText = getTopLevelHeader(pkmnInformation=pkmnInformation[0])
if len(pkmnInformation)==1:
bodyIncludes, bodyText = getSingleFormMarkdown(pkmnInformation[0])
else:
bodyText = ''
formIncludes = []
for ind,form in enumerate(pkmnInformation):
incl, formText = getMultiFormMarkdown(form, ind)
bodyText+= formText+'\n'
[formIncludes.append(i) for i in incl]
tmpIncludes = '\n'.join(formIncludes)
bodyIncludes = "\n".join(list(OrderedDict.fromkeys(tmpIncludes.split("\n"))))
markdownText = '#' + headerText + '\n' + bodyText
includeText = '--8<-- "includes/abilities.md"\n\n' + getTypeIncludes() + bodyIncludes + '\n'
encounterIncl, encounterTable = getEncounters(pkmnInformation[0]['Name'])
if encounterTable != '':
markdownText += '\n## Encounter Locations\n\n'
markdownText += encounterTable +'\n'
includeText+=encounterIncl + '\n'
markdownText += includeText
number = pkmnInformation[0]['Number']
natDexNumber = f"{number:03}"
outfilename = natDexNumber+'.md'
linkText = '- {htext}: pokemons/{fname}\n'.format(htext=headerText, fname = outfilename)
return linkText, outfilename, markdownText
def getEncounters(species):
if(species != 'Ho-Oh' and '-' in species):
formInd = species.find('-')
species = species[:formInd].strip()
def getSpeciesFromKey(k):
formInd = k.find('-')
if formInd !=-1:
return k[:formInd].strip()
return k
wildEncounterKeys = [key for key in pokemonEncounters.keys() if species.lower() == getSpeciesFromKey(key).lower()]
if len(wildEncounterKeys) == 0:
return '',''
def getForm(k):
formInd = k.find('-')
if formInd !=1:
return k[formInd+1:].strip()
return None
encounterList = []
if(len(wildEncounterKeys))>1:
pokemonEncountersSubset = { getForm(k):pokemonEncounters[k] for k in wildEncounterKeys}
else:
pokemonEncountersSubset = pokemonEncounters[wildEncounterKeys[0]]
def getPlaceLinkText(place):
return '[{name}]'.format(name = place)
def getPlaceLinkIncl(place):
locationLinkKeys = list(locationLinks.keys())
keysInPlace = [i for i in locationLinkKeys if i in place]
locationSimilarity = [similar(place.lower(), i.lower()) for i in keysInPlace]
maxIndex = locationSimilarity.index(max(locationSimilarity))
mostSimilarLocation = keysInPlace[maxIndex]
# print(place, ',',mostSimilarLocation)
return '[{name}]: ../../wildareas/{fname}'.format(name = place, fname = locationLinks[mostSimilarLocation].replace('.md', '/'))
placeInclude = []
unnested_encounters = unnest(pokemonEncountersSubset)
unnested_encounters.sort(key = lambda item: tuple(i for i in item))
if len(wildEncounterKeys) > 1:
for row in unnested_encounters:
form = row[0]
location = row[1]
data = row[-1]
remaining_row = list(row)
[remaining_row.pop(i) for i in [-1, 1, 0]]
add_list = [[form, getPlaceLinkText(location), *remaining_row,e['Level'], round(e['Spawn Percent'],2)] for e in data]
encounterList.extend(add_list)
placeInclude.append(getPlaceLinkIncl(location))
else:
for row in unnested_encounters:
data = row[-1]
location = row[0]
remaining_row = list(row)
remaining_row.pop(0)
remaining_row.pop(-1)
add_list = [[getPlaceLinkText(location), *remaining_row,e['Level'], round(e['Spawn Percent'],2)] for e in data]
encounterList.extend(add_list)
placeInclude.append(getPlaceLinkIncl(location))
placeInclude = '\n'.join(list(set(placeInclude)))
n_cols = [len(e) for e in encounterList]
max_cols = max(n_cols)
colNames = [' ']*max_cols
colNames[-2] = 'Level'
colNames[-1] = 'Spawn Percent'
colNames[0] = 'Location'
if len(wildEncounterKeys) > 1:
colNames[0] = 'Form'
colNames[1] = 'Location'
adjusted_encounter_list = []
for row in encounterList:
this_length = len(row)
missing_cols = max_cols - this_length
row_list = list(row)
[row_list.insert(-2,' ') for i in range(missing_cols)]
adjusted_encounter_list.append(row_list)
topRow = '| ' + ' | '.join(colNames) + ' |\n'
separator = '|: ' + ' :|: '.join(['--']*len(colNames)) + ' :|\n'
content = ['| ' + ' | '.join([str(i) for i in row]) + ' |\n' for row in adjusted_encounter_list]
tableString = topRow + separator + ''.join(content)
return placeInclude,tableString
def getSingleFormMarkdown(pkmnInformation):
bodyText = ''
bodyIncludes = ''
number = pkmnInformation['Number']
species, form = getSpecies(pkmnInformation['Name'])
pkmnInclude, tableString = getSpriteTypeTable(species,form = 'base', type = pkmnInformation['TYPE'])
abilityTable = getAbilityTable(pkmnInformation['Ability'])
stats = [pkmnInformation['STATS']]
if 'VANILLA STATS' in pkmnInformation.keys():
stats.append(pkmnInformation['VANILLA STATS'])
bstTable = getStatTable(stats)
bodyText+=tableString
bodyText+='## Defenses\n\n'
bodyText+= getDefensesTable(pkmnInformation['Defenses'])
bodyText+= '## Ability\n\n'
bodyText+=abilityTable
bodyText+='## Stats\n\n'
bodyText+=bstTable
bodyIncludes+=pkmnInclude
if len(pkmnInformation['Items']) > 0:
bodyText+= '## Wild Hold Items\n'
bodyText += getItemString(pkmnInformation['Items'])
if len(pkmnInformation['Level Up Moves']) >0:
bodyText += '## Level Up Moves\n'
lvlUpIncludes, levelUpTable = getLevelUpTable(pkmnInformation['Level Up Moves'])
bodyText+= levelUpTable
if len(pkmnInformation['TM Moves']) >0:
bodyText += '## TM Moves\n'
tmIncludes, tmTable = getTMtable(pkmnInformation['TM Moves'])
bodyText+= tmTable
if len(pkmnInformation['Tutor Moves']) >0:
bodyText += '## Tutor Moves\n'
tutorIncludes, tutorTable = getTutorTable(pkmnInformation['Tutor Moves'])
bodyText+= tutorTable
if len(pkmnInformation['Evolutions'])>0:
bodyText += '## Evolution\n'
evolInclude, evolString = getEvolutionSection(pkmnInformation['Evolutions'])
bodyText += evolString
bodyIncludes += evolInclude
if 'Pre-Evolution Moves' in pkmnInformation.keys() and len(pkmnInformation['Pre-Evolution Moves'])>0:
bodyText += '## Pre-Evolution Moves\n'
preEvoIncl, preEvoString = getPreEvoMoveSection(pkmnInformation['Pre-Evolution Moves'])
bodyText += preEvoString
bodyIncludes += preEvoIncl
return bodyIncludes, bodyText
def getSubsectionHeader(pkmnName):
speciesName = pkmnName
formMarkerInd = speciesName.find('-')
if formMarkerInd == -1:
headerName = speciesName
else:
headerName = speciesName[formMarkerInd:].replace('-','').strip()
return '## {n}\n\n'.format(n=headerName)
def getMultiFormMarkdown(pkmn,form):
bodyText = ''
bodyIncludes = []
number = pkmn['Number']
formHeader = getSubsectionHeader(pkmn['Name'])
bodyText+=formHeader
species, form = getSpecies(pkmn['Name'])
pkmnInclude, tableString = getSpriteTypeTable(species,form = form, type = pkmn['TYPE'])
bodyText+= tableString
bodyIncludes.append(pkmnInclude)
def isValid(item):
if(item is None):
return False
if type(item) is not int and len(item) == 0:
return False
return True
formKeys = [f for f in pkmn.keys() if isValid(pkmn[f])]
if 'Defenses' in formKeys:
bodyText+='### Defenses\n'
bodyText+= getDefensesTable(pkmn['Defenses'])
if 'Ability' in formKeys:
bodyText+='### Ability\n'
bodyText+=getAbilityTable(pkmn['Ability'])
if 'STATS' in formKeys:
bodyText+='### Stats\n'
stats = [pkmn['STATS']]
if 'VANILLA STATS' in pkmn.keys():
stats.append(pkmn['VANILLA STATS'])
bstTable = getStatTable(stats)
bodyText+= bstTable
if 'Items' in formKeys:
bodyText+='### Wild Hold Items\n'
bodyText+= getItemString(pkmn['Items'])
if 'Level Up Moves' in formKeys:
bodyText += '### Level Up Moves\n'
incl, string = getLevelUpTable(pkmn['Level Up Moves'])
bodyText += string
if 'TM Moves' in formKeys:
bodyText += '### TM Moves\n'
incl, string = getTMtable(pkmn['TM Moves'])
bodyText += string
if 'Tutor Moves' in formKeys:
bodyText += '### Tutor Moves\n'
incl, string = getTutorTable(pkmn['Tutor Moves'])
bodyText += string
if 'Evolutions' in formKeys:
bodyText += '### Evolutions\n'
evolIncl, evolString = getEvolutionSection(pkmn['Evolutions'])
bodyText += evolString
bodyIncludes.append(evolIncl)
if 'Pre-Evolution Moves' in formKeys:
bodyText += '### Pre-Evolution Moves\n'
preEvoIncl, preEvoString = getPreEvoMoveSection(pkmn['Pre-Evolutions Moves'])
bodyText += preEvoString
bodyIncludes.append(preEvoIncl)
return bodyIncludes, bodyText