267 lines
15 KiB
Python
267 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Build the two D10 Roll20 sheets from explicit models and skill YAML."""
|
|
import argparse
|
|
import hashlib
|
|
import html
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
|
|
import yaml
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DATA = ROOT / 'data'
|
|
IDENT = re.compile(r'^[A-Za-z][A-Za-z0-9_-]*$')
|
|
COLOR = re.compile(r'^#[0-9a-fA-F]{6}$')
|
|
TABS = (('core', 'Personnage'), ('skills', 'Compétences'),
|
|
('combat', 'Combat'), ('other', 'Autres'))
|
|
|
|
|
|
def read_yaml(path):
|
|
return yaml.safe_load(path.read_text(encoding='utf-8'))
|
|
|
|
|
|
def ident(value):
|
|
if not isinstance(value, str) or not IDENT.fullmatch(value):
|
|
raise ValueError(f'invalid Roll20 identifier: {value!r}')
|
|
return value
|
|
|
|
|
|
def esc(value):
|
|
return html.escape(str(value), quote=True)
|
|
|
|
|
|
def validate(model, skills, theme):
|
|
if model.get('version') != 1:
|
|
raise ValueError('unsupported model version')
|
|
for color in theme.values():
|
|
if not isinstance(color, str) or not COLOR.fullmatch(color):
|
|
raise ValueError(f'invalid theme color: {color!r}')
|
|
for required in ('background', 'panel', 'ink', 'accent', 'border'):
|
|
if required not in theme:
|
|
raise ValueError(f'missing theme color: {required}')
|
|
fields = set()
|
|
for item in model['attributes'] + model['resources']:
|
|
key = ident(item['id'])
|
|
if key in fields:
|
|
raise ValueError(f'duplicate field: {key}')
|
|
fields.add(key)
|
|
for item in model.get('combat', []):
|
|
key = ident(item['id'])
|
|
if key in fields:
|
|
raise ValueError(f'duplicate field: {key}')
|
|
fields.add(key)
|
|
for location in model.get('health_locations', []):
|
|
ident(location)
|
|
if not isinstance(model.get('weapons', 0), int) or not 0 <= model.get('weapons', 0) <= 10:
|
|
raise ValueError('weapons must be an integer from 0 to 10')
|
|
sections = skills['sections']
|
|
if not isinstance(sections, list) or not sections:
|
|
raise ValueError('skills need sections')
|
|
generated_fields = set()
|
|
for section in sections:
|
|
for group in section['groups']:
|
|
prefix = ''.join(c for c in group['name'].replace(' ', '') if c.isascii() and c.isalpha()).lower()
|
|
if not prefix:
|
|
raise ValueError(f'group has no usable identifier: {group["name"]!r}')
|
|
seen = set()
|
|
for skill in group.get('skills', []):
|
|
key = ident(skill['id'])
|
|
if key in seen:
|
|
raise ValueError(f'duplicate skill in {group["name"]}: {key}')
|
|
seen.add(key)
|
|
stem = f'{prefix}_skilllevel_{key}'
|
|
if stem in generated_fields:
|
|
raise ValueError(f'duplicate generated skill field: {stem}')
|
|
generated_fields.add(stem)
|
|
if skill.get('parent') and skill['parent'] not in seen:
|
|
raise ValueError(f'unknown or later parent for {key}')
|
|
for block in model['repeating']:
|
|
ident(block['id'])
|
|
for field in block['fields']:
|
|
ident(field)
|
|
|
|
|
|
def roll(label, threshold):
|
|
expression = f'{threshold}-1d@{{dice}}cs1cf@{{dice}}'
|
|
value = ('&{template:d10skillcheck} '
|
|
'{{name=@{character_name}}} '
|
|
f'{{{{roll_name={label}}}}} '
|
|
'{{dice_name=@{dice}}} '
|
|
f'{{{{threshold=[[{threshold}]]}}}} '
|
|
f'{{{{result=[[{expression}]]}}}}')
|
|
return f'<button type="roll" class="sheet-roll" value="{esc(value)}" title="Lancer {esc(label)}">Jet</button>'
|
|
|
|
|
|
def render_skill(group, skill, variant):
|
|
# Cyberpunk names follow the original generator's subgroup prefix and ID.
|
|
prefix = ''.join(c for c in group['name'].replace(' ', '') if c.isascii() and c.isalpha()).lower()
|
|
if variant == 'base':
|
|
stem = f'general_skilllevel_{skill["id"]}'
|
|
name_field = skill['name']
|
|
else:
|
|
stem = f'{prefix}_skilllevel_{skill["id"]}'
|
|
name_field = skill['name']
|
|
threshold = f'@{{{stem}}}+@{{skill_{prefix}_attribute_select_{skill["id"]}}}'
|
|
if skill.get('parent'):
|
|
threshold += f'+@{{{prefix}_skilllevel_{skill["parent"]}}}'
|
|
options = [('Force', 'For'), ('Agilite', 'Agi'), ('Perception', 'Per'),
|
|
('Charisme', 'Cha'), ('Intelligence', 'Int'), ('Volonte', 'Vol'),
|
|
(('Psyche' if variant == 'base' else 'Accred'), ('Psy' if variant == 'base' else 'Acc')),
|
|
('Chance', 'Chn')]
|
|
selector = f'skill_{prefix}_attribute_select_{skill["id"]}'
|
|
choices = ''.join(f'<option value="@{{base-{key}}}+@{{exal-{key}}}">{esc(short)}</option>' for key, short in options)
|
|
depth = ' sheet-subskill' if skill.get('parent') else ''
|
|
return (f'<div class="sheet-skill-row{depth}"><span class="sheet-skill-name">{esc(name_field)}</span>'
|
|
f'<select name="attr_{selector}" title="Caractéristique">{choices}</select>'
|
|
f'<input type="number" name="attr_{stem}" value="0" min="0" title="Niveau">'
|
|
f'<input type="number" name="attr_{prefix}_skillcost_{skill["id"]}" value="0" min="0" title="Coût">'
|
|
f'{roll(name_field, threshold)}</div>')
|
|
|
|
|
|
def render(model, skills, variant, theme_name, theme):
|
|
parts = [f'<div class="sheet-d10 sheet-theme-{esc(theme_name)}">',
|
|
'<header class="sheet-hero"><div class="sheet-hero-mark">D10</div>',
|
|
f'<div class="sheet-hero-main"><span class="sheet-eyebrow">Feuille de personnage</span><h1>{esc(model["title"])}</h1>',
|
|
'<div class="sheet-identity"><label>Nom <input type="text" name="attr_character_name"></label>',
|
|
'<label>Origine <input type="text" name="attr_character_race"></label></div></div>',
|
|
'<label class="sheet-die-choice">Dé de jeu <select name="attr_dice">' + ''.join(
|
|
f'<option value="{n}"{" selected" if n == 10 else ""}>d{n}</option>'
|
|
for n in (4, 6, 8, 10, 12, 20)) + '</select></label></header>',
|
|
'<input type="hidden" class="sheet-tab-state" name="attr_d10_tab" value="core">',
|
|
'<nav class="sheet-tab-nav" aria-label="Sections de la feuille">',
|
|
*(f'<button type="action" class="sheet-tab-button sheet-tab-{key}" name="act_tab_{key}">{label}</button>'
|
|
for key, label in TABS),
|
|
'</nav><div class="sheet-page sheet-page-core">',
|
|
'<section class="sheet-panel"><div class="sheet-section-title"><span>01</span><h2>Caractéristiques</h2></div>',
|
|
'<div class="sheet-stat-grid">']
|
|
for item in model['attributes']:
|
|
key = item['id']
|
|
threshold = f'(@{{base-{key}}}+@{{exal-{key}}})*2'
|
|
parts.append(f'<div class="sheet-stat"><strong>{esc(item["name"])}</strong>'
|
|
f'<label>Base<input type="number" name="attr_base-{key}" value="0" title="Base"></label>'
|
|
f'<label>Bonus<input type="number" name="attr_exal-{key}" value="0" title="Bonus"></label>'
|
|
f'{roll(item["name"], threshold)}</div>')
|
|
parts.append('</div></section><section class="sheet-panel"><div class="sheet-section-title"><span>02</span><h2>Ressources</h2></div><div class="sheet-resource-grid">')
|
|
for item in model['resources']:
|
|
key = item['id']
|
|
parts.append(f'<div class="sheet-resource"><strong>{esc(item["name"])}</strong>'
|
|
f'<label>Actuel<input type="number" name="attr_{key}" value="0" title="Actuel"></label>'
|
|
f'<span>/</span><label>Maximum<input type="number" name="attr_{key}_maximum" value="0" title="Maximum"></label></div>')
|
|
if model.get('health_locations'):
|
|
parts.append('</div><h3 class="sheet-subheading">Localisations</h3><div class="sheet-location-head"><span>Zone</span><span>PV</span><span>Protection</span><span>Intégrité</span></div><div class="sheet-locations">')
|
|
for location in model['health_locations']:
|
|
parts.append(f'<div class="sheet-location"><strong>{esc(location.replace("_", " "))}</strong>'
|
|
f'<input type="number" name="attr_Life_Points_{location}" value="0" title="PV">'
|
|
f'<input type="number" name="attr_Armor_Protection_Points_{location}" value="0" title="Protection">'
|
|
f'<input type="number" name="attr_Armor_Integrity_Points_{location}" value="0" title="Intégrité"></div>')
|
|
parts.append('</div>')
|
|
else:
|
|
parts.append('</div>')
|
|
parts.append('</section></div><div class="sheet-page sheet-page-combat"><section class="sheet-panel"><div class="sheet-section-title"><span>03</span><h2>Combat</h2></div><div class="sheet-combat-grid">')
|
|
for item in model.get('combat', []):
|
|
parts.append(f'<label class="sheet-combat-field">{esc(item["name"])}'
|
|
f'<input type="number" name="attr_{esc(item["id"])}" value="0"></label>')
|
|
parts.append('</div><div class="sheet-combat-actions"><span>Jets de combat</span>')
|
|
parts.append(roll('Initiative', '@{base-Agilite}+@{exal-Agilite}+@{Initiative}'))
|
|
parts.append(roll('Attaque', '@{general_attack_threshold}'))
|
|
parts.append('</div><h3 class="sheet-subheading">Armes équipées</h3><div class="sheet-weapon-grid">')
|
|
for number in range(1, model.get('weapons', 0) + 1):
|
|
parts.append(f'<div class="sheet-weapon"><span>Arme {number}</span>'
|
|
f'<input type="text" name="attr_general_item_weapon{number}_name" title="Nom">'
|
|
f'<input type="number" name="attr_general_item_weapon{number}" value="0" title="Dégâts">'
|
|
f'<input type="checkbox" name="attr_item_weapon{number}_activation" value="1" title="Équipée"></div>')
|
|
parts.append('</div></section></div><div class="sheet-page sheet-page-skills"><section class="sheet-panel"><div class="sheet-section-title"><span>04</span><h2>Compétences</h2></div>')
|
|
for section in skills['sections']:
|
|
parts.append(f'<h3 class="sheet-subheading">{esc(section["name"])}</h3>')
|
|
for group in section['groups']:
|
|
parts.append(f'<div class="sheet-skill-group"><h4>{esc(group["name"])}</h4>'
|
|
'<div class="sheet-skill-head"><span>Compétence</span><span>Carac.</span><span>Niveau</span><span>Coût</span><span>Jet</span></div>')
|
|
parts.extend(render_skill(group, skill, variant) for skill in group.get('skills', []))
|
|
parts.append('</div>')
|
|
parts.append('</section></div><div class="sheet-page sheet-page-other"><section class="sheet-panel"><div class="sheet-section-title"><span>05</span><h2>Autres</h2></div>')
|
|
for block in model['repeating']:
|
|
parts.append(f'<details><summary>{esc(block["name"])}</summary>'
|
|
f'<fieldset class="repeating_{esc(block["id"])}">')
|
|
for field in block['fields']:
|
|
kind = 'number' if field in ('skilllevel', 'skillcost', 'quantity', 'damage') else 'text'
|
|
parts.append(f'<label>{esc(field)} <input type="{kind}" name="attr_{esc(field)}"></label>')
|
|
if 'skilllevel' in block['fields']:
|
|
options = ''.join(
|
|
f'<option value="@{{base-{item["id"]}}}+@{{exal-{item["id"]}}}">{esc(item["name"])}</option>'
|
|
for item in model['attributes'])
|
|
parts.append(f'<select name="attr_attribute_select">{options}</select>')
|
|
parts.append(roll('@{skillname}', '@{skilllevel}+@{attribute_select}'))
|
|
parts.append('</fieldset></details>')
|
|
parts.append('</section></div></div>')
|
|
html_text = '\n'.join(parts) + '\n'
|
|
css = '.sheet-d10, .sheet-rolltemplate-d10skillcheck {\n' + '\n'.join(
|
|
f' --d10-{key}: {value};' for key, value in theme.items()) + '\n}\n'
|
|
css += (ROOT / 'templates' / 'sheet.css').read_text(encoding='utf-8')
|
|
html_text += '''<rolltemplate class="sheet-rolltemplate-d10skillcheck">
|
|
<div><strong>{{name}}</strong> — {{roll_name}}</div>
|
|
<div>Seuil: {{threshold}} · Résultat: {{result}}</div>
|
|
</rolltemplate>
|
|
'''
|
|
html_text += '<script type="text/worker">\n'
|
|
html_text += ''.join(
|
|
f'on("clicked:tab_{key}", function () {{ setAttrs({{d10_tab: "{key}"}}); }});\n'
|
|
for key, _ in TABS)
|
|
html_text += '</script>\n'
|
|
return html_text, css
|
|
|
|
|
|
def build(variant, theme_name, output, check=False):
|
|
source = read_yaml(DATA / 'sheet_model.yaml')
|
|
themes = read_yaml(DATA / 'themes.yaml')['themes']
|
|
if variant not in source['variants']:
|
|
raise ValueError(f'unknown variant: {variant}')
|
|
if theme_name not in themes:
|
|
raise ValueError(f'unknown theme: {theme_name}')
|
|
model = source['variants'][variant]
|
|
skills = read_yaml(DATA / model['skills'])
|
|
theme = themes[theme_name]
|
|
validate({**model, 'version': source['version']}, skills, theme)
|
|
html_text, css = render(model, skills, variant, theme_name, theme)
|
|
manifest = {'html': 'sheet.html', 'css': 'sheet.css', 'authors': 'Dandaedre',
|
|
'roll20userid': '1067910', 'instructions': f'{model["title"]} generated from D10 YAML'}
|
|
translation = {}
|
|
files = {'sheet.html': html_text, 'sheet.css': css,
|
|
'sheet.json': json.dumps(manifest, ensure_ascii=False, indent=2) + '\n',
|
|
'translation.json': json.dumps(translation, indent=2) + '\n'}
|
|
files['build-info.json'] = json.dumps({'variant': variant, 'theme': theme_name,
|
|
'skills': sum(len(g.get('skills', [])) for s in skills['sections'] for g in s['groups']),
|
|
'sha256': hashlib.sha256((html_text + css).encode()).hexdigest()}, indent=2) + '\n'
|
|
if check:
|
|
stale = [name for name, content in files.items()
|
|
if not (output / name).exists() or (output / name).read_text(encoding='utf-8') != content]
|
|
if stale:
|
|
raise ValueError(f'generated files are missing or stale: {", ".join(stale)}')
|
|
else:
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
for name, content in files.items():
|
|
(output / name).write_text(content, encoding='utf-8')
|
|
return files
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--variant', choices=('base', 'cyberpunk'), default='base')
|
|
parser.add_argument('--theme', choices=('parchment', 'night'), default='parchment')
|
|
parser.add_argument('--output-dir', type=Path)
|
|
parser.add_argument('--list-themes', action='store_true')
|
|
parser.add_argument('--check', action='store_true', help='verify existing output without writing')
|
|
args = parser.parse_args()
|
|
if args.list_themes:
|
|
print('\n'.join(read_yaml(DATA / 'themes.yaml')['themes']))
|
|
return
|
|
output = args.output_dir or ROOT / 'build' / args.variant / args.theme
|
|
try:
|
|
build(args.variant, args.theme, output, check=args.check)
|
|
except ValueError as error:
|
|
parser.error(str(error))
|
|
print(output)
|
|
|
|
if __name__ == '__main__':
|
|
main()
|