#!/usr/bin/env python3 import json import re import utils import attacks class Creature(dict): def getBonus(self, ability): return (self['stats'][ability] - 10) // 2 def processMonster(data, weapons, armors, spells): names2names = {'ac': 'Armor Class', 'hp': 'Hit Points', 'speed': 'Speed', 'saves': 'Saving Throws', 'd_resistances': 'Damage Resistances?', 'd_vulnerabilities': 'Damage Vulnerabilities', 'd_immunities': 'Damage Immunities', 'c_immunities': 'Condition Immunities', 'senses': 'Senses', 'langs': 'Languages', 'skills': 'Skills'} desc = Creature() desc['entry'] = 'creatures' for name in names2names: m = re.search('(\*\*{}\.?\*\*)(.*)'.format(names2names[name]), data) if m: desc[name] = m.group(2).strip() else: desc[name] = "" for name in ['d_resistances', 'd_vulnerabilities', 'd_immunities', 'c_immunities']: # Formatted a, b, c[; d, e, and f from nonmagical attacks[ that aren't g]] # Blerg. Also can be "not made with g weapons" # Maybe without the a, b, c part parts = [desc[name]] if '; ' in desc[name]: parts = desc[name].split('; ') desc[name] = [] for part in parts: part = part.strip().lower() # Look for "nonmagical", and "that aren't x" qualifiers = [] if 'nonmagical' in part: qualifiers.append('nonmagical') if 'that aren\'t' in part: qualifiers.append('non-' + re.search('(?<=that aren\'t ).*$', part).group(0)) if 'not made with ' in part: qualifiers.append('non-' + re.search('(?<=not made with )\w*', part).group(0)) for typ in re.findall('([a-z]+(?=,)|^[a-z]+$|(?<=, )[a-z]+$|(?<=and )[a-z]+(?= from)|(?<=and )[a-z]+(?= \(from))', part): desc[name].append({'type': typ, 'qualifiers': qualifiers}) # Calc things about hp hitdieMatch = re.search('(\d+)d(\d+)', desc['hp']) desc['hit_die_count'] = int(hitdieMatch.group(1)) desc['hit_die_sides'] = int(hitdieMatch.group(2)) del desc['hp'] desc['name'] = re.search('(?<=name: ).*', data).group(0).strip() desc['type'] = re.search('(?<=type: ).*', data).group(0).strip() desc['cr'] = float(re.search('(?<=cr: ).*', data).group(0).strip()) description = re.search('(?<=_).*(?=_)', data).group(0).strip() desc['size'] = description.split(' ')[0] desc['alignment'] = description.split(', ')[-1] desc['stats'] = {ability: int(score.strip().split(' ')[0]) for ability, score in zip(['str', 'dex', 'con', 'int', 'wis', 'cha'], re.findall('(?<=\|) *\d.*?(?=\|)', data))} desc['inventory'] = [] # Fill with weapons and armor desc['observant'] = False # maybe set to true later # Add a few null-valued items that will be set when the creature is first generated desc['givenName'] = 'NAME' desc['hpMax'] = -1 desc['hp'] = -1 # Modify ac stuff desc['natural_armor'] = {'name': '', 'bonus': 0} correctAC = int(desc['ac'].split(' ')[0] if ' ' in desc['ac'] else desc['ac']) natural = '' armorBonus = 0 armor = re.search('(?<=\().*(?=\))', desc['ac']) if armor: armor = armor.group(0).lower() if ',' in armor: armor = armor.split(',') else: armor = [armor] for a in armor: a = a.strip() # If it has "armor" in it, remove that a = re.search('^(.*?)(?: armor)?$', a).group(1) #print('Working with {}'.format(a)) if a == 'natural' or a == 'patchwork' or 'scraps' in a: natural = a continue if 'with' in a: continue # Search for it in armors found = False for armorDict in armors: if armorDict['name'] == a: found = True bonus = armorDict['ac'] typ = armorDict['armor_type'] #desc['inventory'].append(armorDict) desc['inventory'].append({'entry': 'item', 'name': a, 'type': 'armor', 'text': '{} armor'.format(a)}) break if not found: print('Cound not identify armor: {}'.format(a)) continue #else: # print('Found {} armor {} (bonus = {})'.format(typ, name, bonus)) if typ == 'light': armorBonus = bonus + desc.getBonus('dex') elif typ == 'medium': armorBonus = bonus + min(2, desc.getBonus('dex')) elif typ == 'heavy': armorBonus = bonus elif typ == 'misc' or typ == 'shield': armorBonus += bonus if armorBonus == 0 and not natural: # Got through all that and came up dry armorBonus = 10 + desc.getBonus('dex') if natural: desc['natural_armor'] = {'name': natural, 'bonus': correctAC - armorBonus} elif armorBonus != correctAC: print('Got a bad result for {}: armor string is {}, but we calculated {}'.format(desc['name'], desc['ac'], armorBonus)) del desc['ac'] # Search for a description section desc['text'] = '' description = re.search('(?s)(?<={}).*?(?=###|$)'.format('### Description'), data) if description: desc['text'] = description.group(0).strip() else: # Try looking for the last entry (**something**) with an empty line and then one or more paragraphs before end of file description = re.search('(?s)(?<=\*\*).*\n\n(.*?)(?=###|$)', data) if description: #print(f'Found description without a header for {desc["name"]}') desc['text'] = description.group(1).strip() # Next do sections names2sectHeads = {'feature': '\*\*Challenge\*\*', 'action': '### Actions', 'legendary_action': '### Legendary Actions', 'reaction': '### Reactions'} # We put them all in "features" list desc['features'] = [] for name in names2sectHeads: section = re.search('(?s)(?<={}).*?(?=###|$)'.format(names2sectHeads[name]), data) if section: # There might be a special section text as the first new line after the header #text = re.match('(?s)(\s*\w[^\*].*?)([\r\n]+[\*#]|$)', '\n'.join(section.group(0).split('\n')[1:])) #if text and re.search('\w', text.group(1)): # desc[name]['_text'] = text.group(1).strip() for m in re.findall('(?s)\n\*\*(.*?)\.?\*\*(.*?)(?=\n\*\*|\n\n|$)', section.group(0)): desc['features'].append({'entry': 'feature', 'name': m[0].lower(), 'text': m[1].strip(), 'type': name}) # Next, simplify and codify a few things # Guess the proficiency bonus desc['prof'] = int(max(0, (desc['cr']-1) // 4) + 2) # Now convert skills, saves, and attacks to be based on proficiency and abilities rather than raw numbers skillStr = desc['skills'] desc['skills'] = {} # Map skill to plurality of proficiency if skillStr: for skill in skillStr.split(','): skillName, skillBonus, ability = utils.procSkill(skill) abilityBonus = desc.getBonus(ability) profTimes = (skillBonus - abilityBonus) / desc['prof'] if round(profTimes) != profTimes: print('Things came out funny for {}; skill {} has bonus {}, but proficiency is {} and the relevant ability ({}) gets {}'.format(desc['name'], skillName, skillBonus, desc['prof'], ability, desc.getBonus(ability))) desc['skills'][skillName] = round(profTimes) savesStr = desc['saves'] desc['saves'] = [] if savesStr: for save in savesStr.split(', '): ability = save.split(' ')[0].lower() if int(save.split('+')[1]) != desc.getBonus(ability) + desc['prof']: print('Things came out funny for {}; {} save has bonus {}, but proficiency is {} and the relevant ability ({}) gets {}'.format(desc['name'], ability, int(save.split('+')[1]), desc['prof'], ability, desc.getBonus(ability))) desc['saves'].append(ability) for action in desc['features']: if re.match('.*Attack:', action['text']): attacks.procAttackAction(desc, action, weapons) elif 'spellcasting' in action['name']: attacks.procSpellAction(desc, action, spells) # Remove weapon actions from features (they were just added to inventory) desc['features'] = [a for a in desc['features'] if 'attack' not in a or a['attack']['weapon_type'] == 'unknown'] # Get rid of precalculated passive perception # It's always the last item in senses passivePercep = int(desc['senses'].split(' ')[-1]) shouldBe = 10 + desc.getBonus('wis') if 'Perception' in desc['skills']: shouldBe += desc['skills']['Perception'] * desc['prof'] if passivePercep != shouldBe: if(passivePercep - 5 == shouldBe): desc['observant'] = True else: print('Passive perception didn\'t come out right for {}: is {}, but should be {}'.format(desc['name'], passivePercep, shouldBe)) desc['senses'] = desc['senses'].split(', ')[:-1] return desc from pathlib import Path weapons = utils.getWeapons() armors = utils.getArmor() spells = utils.getSpells() def dumpStuff(stuff, destDir): Path(destDir).mkdir(parents=True, exist_ok=True) for thing in stuff: with open(destDir + '/' + thing['name'].replace(' ', '_').replace('/', '') + '.json', 'w') as f: json.dump(thing, f, indent=2) dumpStuff(weapons, 'parsed/weapons/') dumpStuff(armors, 'parsed/armor/') dumpStuff(spells, 'parsed/spells/') for monster in Path(utils.docsLoc + '/gamemaster_rules/monsters/').glob('*.md'): #print('Processing {}'.format(monster)) if monster.name == 'index.md': continue with monster.open() as f: data = f.read() Path('parsed/creatures/').mkdir(exist_ok=True) with open('parsed/creatures/' + monster.stem + '.json', 'w') as f: json.dump(processMonster(data, weapons, armors, spells), f, indent=2)