#!/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}$') 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') for section in sections: for group in section['groups']: 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) 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'' 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'' for key, short in options) return (f'
' f'' f'' f'' f'{roll(esc(name_field), threshold)}
') def render(model, skills, variant, theme_name, theme): parts = [f'
', f'

{esc(model["title"])}

', '', '', '', '

Caractéristiques

'] for item in model['attributes']: key = item['id'] threshold = f'(@{{base-{key}}}+@{{exal-{key}}})*2' parts.append(f'
' f'' f'' f'{roll(esc(item["name"]), threshold)}
') parts.append('

Ressources

') for item in model['resources']: key = item['id'] parts.append(f'
' f'' f'
') if model.get('health_locations'): parts.append('

Localisations

') for location in model['health_locations']: parts.append(f'
' f'' f'' f'
') parts.append('

Combat

') for item in model.get('combat', []): parts.append(f'
' f'
') parts.append(roll('Initiative', '@{base-Agilite}+@{exal-Agilite}+@{Initiative}')) parts.append(roll('Attaque', '@{general_attack_threshold}')) for number in range(1, model.get('weapons', 0) + 1): parts.append(f'
' f'' f'' f'
') parts.append('

Compétences

') for section in skills['sections']: parts.append(f'

{esc(section["name"])}

') for group in section['groups']: parts.append(f'
{esc(group["name"])}') parts.extend(render_skill(group, skill, variant) for skill in group.get('skills', [])) parts.append('
') parts.append('

Autres

') for block in model['repeating']: parts.append(f'
{esc(block["name"])}' f'
') for field in block['fields']: kind = 'number' if field in ('skilllevel', 'skillcost', 'quantity', 'damage') else 'text' parts.append(f'') if 'skilllevel' in block['fields']: options = ''.join( f'' for item in model['attributes']) parts.append(f'') parts.append(roll('@{skillname}', '@{skilllevel}+@{attribute_select}')) parts.append('
') parts.append('
') html_text = '\n'.join(parts) + '\n' css = '.sheet-d10 {\n' + '\n'.join( f' --d10-{key}: {value};' for key, value in theme.items()) + ''' background: var(--d10-background); color: var(--d10-ink); padding: 1rem; font-family: sans-serif; } .sheet-d10 section, .sheet-d10 details { background: var(--d10-panel); border: 1px solid var(--d10-border); padding: .6rem; margin: .5rem 0; } .sheet-d10 h1, .sheet-d10 h2, .sheet-d10 h3 { color: var(--d10-accent); } .sheet-d10 .sheet-stat, .sheet-d10 .sheet-skill { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem; margin: .3rem 0; } .sheet-d10 .sheet-stat label, .sheet-d10 .sheet-skill label { min-width: 9rem; } .sheet-d10 input[type=number] { width: 4rem; } .sheet-d10 button { background: var(--d10-accent); color: var(--d10-panel); border: 0; padding: .3rem .7rem; } .sheet-rolltemplate-d10skillcheck { background: var(--d10-panel); color: var(--d10-ink); border: 1px solid var(--d10-border); padding: .5rem; } ''' html_text += '''
{{name}} — {{roll_name}}
Seuil: {{threshold}} · Résultat: {{result}}
''' return html_text, css def build(variant, theme_name, output): 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' 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') 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 build(args.variant, args.theme, output) print(output) if __name__ == '__main__': main()