#!/usr/bin/env python3
"""Generate the figures of the combat pages, docs/combat/.

The figures are original schematic drawings. Their numbers are read from your
own DOS START.EXE (data-segment image at file offset 0x2e360):

- the strength and dexterity modifiers at data-segment offsets 0x3299,
  0x32bc and 0x32d5, with the three bytes after the dexterity table
  (docs/executable/data/PARTY_AND_CHARACTERS.md#d-5559);
- the saving-throw thresholds at 0x31ac-0x3237 and the group level caps and
  divisors at 0x3250 and 0x3256 (data/PARTY_AND_CHARACTERS.md#d-31ac, data/PARTY_AND_CHARACTERS.md#d-3238);
- the characters hit in each quarter of the party's block at 0x5530
  (data/BLOCK_EVENTS_AND_FLYING_OBJECTS.md#d-2352).

The durations of the hand-recovery timeline (18, 36, 9 and 72 ticks) are
transcribed from the character timers of docs/engine/CLOCK.md. No game
graphics are used.

Usage:
    python3 scripts/combat/make_combat_figures.py [START.EXE] [output_directory]

The defaults are data/originals/eob2/START.EXE and docs/combat/img/.
"""
import hashlib
import sys
from html import escape
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
EXE = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / 'data/originals/eob2/START.EXE'
OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else ROOT / 'docs/combat/img'
SHA256 = '2bb5edf06d966a4dbf40dd4866733a9ce37e47c5ace052615df4b6b69d4cb8b4'

d = EXE.read_bytes()
if hashlib.sha256(d).hexdigest() != SHA256:
    sys.exit(f'{EXE}: unexpected SHA-256; this script reads the DOS START.EXE listed in docs/files/INVENTORY.md')
DS = 0x2e360


def sbytes(offset, n):
    """n signed bytes at a data-segment offset."""
    return [int.from_bytes(d[DS + offset + i:DS + offset + i + 1], 'little', signed=True)
            for i in range(n)]


STR_HIT = sbytes(0x3299, 25)        # scores 1-25
STR_DAMAGE = sbytes(0x32bc, 25)     # scores 1-25
DEX_HIT = sbytes(0x32d5, 19)        # scores 1-19
DEX_PAST = sbytes(0x32d5 + 19, 3)   # what scores 20-22 read
CAPS = sbytes(0x3250, 4)            # warriors, wizards, priests, rogues
DIVISORS = sbytes(0x3256, 4)
THRESHOLDS = {                      # group: (offset, row length)
    'warriors': (0x31ed, 10), 'wizards': (0x321f, 5),
    'priests': (0x31ac, 7), 'rogues': (0x31cf, 6),
}
QUARTER_CHARS = sbytes(0x5530, 8)   # two characters per quarter seen from the party

FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
SURF, BORDER, INK, INK2, MUTED, GRID = '#fcfcfb', '#dddcd7', '#0b0b0b', '#52514e', '#8a8984', '#eeede9'
BLUE, LIGHT, ORANGE, SHADE = '#2a78d6', '#a9c9f0', '#eb6834', '#f1f0ec'
GROUPS = [  # name, colour, dash pattern
    ('Warriors', '#1c5cab', ''),
    ('Wizards', '#eb6834', '6 3'),
    ('Priests', '#2f8f5b', '2 3'),
    ('Rogues', '#8a4fc7', '9 3 2 3'),
]
MINUS = '−'


def num(v):
    return f'{MINUS}{-v}' if v < 0 else (f'+{v}' if v > 0 else '0')


def text(x, y, s, size=12, fill=INK, weight=None, anchor='start'):
    w = ' font-weight="bold"' if weight else ''
    return (f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" fill="{fill}"{w} '
            f'text-anchor="{anchor}" dominant-baseline="central">{escape(s)}</text>')


def frame(W, H, title, desc):
    return [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" '
            f'role="img" font-family="{FONT}">',
            f'<title>{escape(title)}</title>', f'<desc>{escape(desc)}</desc>',
            f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{SURF}" stroke="{BORDER}"/>']


def write(name, parts):
    parts.append('</svg>')
    (OUT / name).write_text('\n'.join(parts) + '\n', encoding='utf-8')
    print(OUT / name)


# ------------------------------------------------------------- hand recovery
def hand_recovery():
    W, H = 700, 330
    x0, x1, tmax = 230, 600, 72
    X = lambda t: x0 + (x1 - x0) * t / tmax
    rows = [
        ('A weapon is used', [(0, 18, 'result'), (18, 54, 'rest')], 54),
        ('Under Haste', [(0, 18, 'result'), (18, 27, 'rest')], 27),
        ("CAN'T REACH, NO AMMO or BASH", [(0, 18, 'result')], 18),
        ('A spell from the spell book', [(0, 72, 'book')], 72),
    ]
    desc = ('Timeline in ticks from 0 to 72. After a weapon is used, its result shows on the portrait for 18 ticks, '
            'then the hand rests 36 more ticks and is ready at 54. Under Haste the rest lasts 9 ticks and the hand '
            'is ready at 27. After a CAN\'T REACH, NO AMMO or BASH result the hand is ready at 18. A spell cast '
            'from the spell book makes the book unusable for 72 ticks.')
    out = frame(W, H, 'When a hand can be used again', desc)
    out.append(text(20, 26, 'When a hand can be used again', 14, weight=True))
    out.append(text(20, 46, 'Ticks after the use; the hand cannot be used until the marker.', 12, INK2))
    ly = 74
    out.append(f'<rect x="20" y="{ly-7}" width="22" height="14" rx="2" fill="{BLUE}"/>')
    out.append(text(48, ly, 'Result shown on the portrait', 12))
    out.append(f'<rect x="250" y="{ly-7}" width="22" height="14" rx="2" fill="{LIGHT}"/>')
    out.append(text(278, ly, 'Hand resting', 12))
    out.append(f'<rect x="400" y="{ly-7}" width="22" height="14" rx="2" fill="{ORANGE}" fill-opacity="0.55"/>')
    out.append(text(428, ly, 'Spell book unusable', 12))
    top, rh, gap = 112, 28, 16
    bottom = top + len(rows) * (rh + gap) - gap
    for t in range(0, tmax + 1, 9):
        out.append(f'<line x1="{X(t):.1f}" y1="{top-8}" x2="{X(t):.1f}" y2="{bottom+8}" stroke="{GRID}"/>')
        out.append(text(X(t), bottom + 22, str(t), 11, INK2, anchor='middle'))
    out.append(text((x0 + x1) / 2, bottom + 42, 'Ticks', 11, INK2, anchor='middle'))
    fills = {'result': (BLUE, '#ffffff'), 'rest': (LIGHT, INK), 'book': (ORANGE, INK)}
    for k, (label, spans, ready) in enumerate(rows):
        y = top + k * (rh + gap)
        out.append(text(x0 - 14, y + rh / 2, label, 12, anchor='end'))
        for a, b, kind in spans:
            fill, ink = fills[kind]
            op = ' fill-opacity="0.55"' if kind == 'book' else ''
            out.append(f'<rect x="{X(a)+1:.1f}" y="{y}" width="{X(b)-X(a)-2:.1f}" height="{rh}" rx="3" fill="{fill}"{op}/>')
            out.append(text((X(a) + X(b)) / 2, y + rh / 2, str(b - a), 12, ink, True, 'middle'))
        xr = X(ready)
        out.append(f'<line x1="{xr:.1f}" y1="{y-4}" x2="{xr:.1f}" y2="{y+rh+4}" stroke="{INK}" stroke-width="2"/>')
        out.append(text(xr + 6, y + rh / 2, f'ready at {ready}', 11, INK, anchor='start'))
    write('combat-hand-recovery.svg', out)


# ------------------------------------------------------------- modifiers
def ability_modifiers():
    W, H = 700, 560
    x0, x1 = 64, 676
    X = lambda s: x0 + (x1 - x0) * (s - 0.5) / 25
    desc = ('Two charts by ability score, from 1 to 25. To hit: the strength modifier, used in melee, rises from '
            f'{num(STR_HIT[0])} at 1 to 0 from 8 to 16 and {num(STR_HIT[-1])} at 25; the dexterity modifier, used '
            f'with thrown weapons and launchers, rises from {num(DEX_HIT[0])} at 1 to 0 from 6 to 11 and '
            f'{num(DEX_HIT[-1])} at 19, the end of its table; scores 20 to 22 read the three bytes that follow the '
            f'table, {", ".join(num(v) for v in DEX_PAST)}. To damage: the strength modifier rises from '
            f'{num(STR_DAMAGE[0])} at 1 to 0 from 6 to 15, {num(STR_DAMAGE[17])} at 18, then jumps to '
            f'{num(STR_DAMAGE[18])} at 19 and reaches {num(STR_DAMAGE[-1])} at 25.')
    out = frame(W, H, 'Strength and dexterity modifiers', desc)
    out.append(text(20, 26, 'Strength and dexterity modifiers', 14, weight=True))
    out.append(text(20, 46, 'By ability score; exceptional strength (18 with a percentage) has its own table.', 12, INK2))

    def panel(top, height, vmin, vmax, step, title, series):
        Y = lambda v: top + height * (vmax - v) / (vmax - vmin)
        out.append(text(x0, top - 20, title, 13, weight=True))
        for v in range(vmin, vmax + 1, step):
            out.append(f'<line x1="{x0}" y1="{Y(v):.1f}" x2="{x1}" y2="{Y(v):.1f}" '
                       f'stroke="{INK2 if v == 0 else GRID}" stroke-width="1"/>')
            out.append(text(x0 - 8, Y(v), num(v), 11, INK2, anchor='end'))
        for s in range(1, 26):
            out.append(text(X(s), top + height + 16, str(s), 10, INK2, anchor='middle'))
        for name, colour, values, past in series:
            pts = ' '.join(f'{X(s):.1f},{Y(v):.1f}' for s, v in enumerate(values, 1))
            out.append(f'<polyline points="{pts}" fill="none" stroke="{colour}" stroke-width="2"/>')
            for s, v in enumerate(values, 1):
                out.append(f'<circle cx="{X(s):.1f}" cy="{Y(v):.1f}" r="3.5" fill="{colour}"/>')
            for i, v in enumerate(past):
                s = len(values) + 1 + i
                out.append(f'<circle cx="{X(s):.1f}" cy="{Y(v):.1f}" r="4" fill="{SURF}" stroke="{colour}" stroke-width="2"/>')
        return Y

    Yh = panel(96, 170, -6, 8, 2, 'To hit', [
        ('Strength (melee)', BLUE, STR_HIT, []),
        ('Dexterity (thrown weapons, launchers)', ORANGE, DEX_HIT, DEX_PAST)])
    # legend of the to-hit panel
    lx, ly = x0 + 14, 106
    out.append(f'<line x1="{lx}" y1="{ly}" x2="{lx+22}" y2="{ly}" stroke="{BLUE}" stroke-width="2"/>')
    out.append(text(lx + 28, ly, 'Strength, in melee', 12))
    out.append(f'<line x1="{lx}" y1="{ly+20}" x2="{lx+22}" y2="{ly+20}" stroke="{ORANGE}" stroke-width="2"/>')
    out.append(text(lx + 28, ly + 20, 'Dexterity, with thrown weapons and launchers', 12))
    out.append(f'<circle cx="{lx+11}" cy="{ly+40}" r="4" fill="{SURF}" stroke="{ORANGE}" stroke-width="2"/>')
    out.append(text(lx + 28, ly + 40, 'Scores 20 to 22: bytes past the table', 12))
    Yd = panel(340, 170, -4, 14, 2, 'To damage', [('Strength (melee)', BLUE, STR_DAMAGE, [])])
    out.append(f'<line x1="{lx}" y1="352" x2="{lx+22}" y2="352" stroke="{BLUE}" stroke-width="2"/>')
    out.append(text(lx + 28, 352, 'Strength, added to the damage of a melee blow', 12))
    out.append(text((x0 + x1) / 2, 546, 'Ability score', 11, INK2, anchor='middle'))
    write('combat-ability-modifiers.svg', out)


# ------------------------------------------------------------- saving throws
def saving_throws():
    W, H = 700, 800
    pw, ph = 280, 150
    lmax, vmin, vmax = 21, 2, 20
    desc_parts = []
    for (name, _, _), cap, div in zip(GROUPS, CAPS, DIVISORS):
        desc_parts.append(f'{name.lower()} up to level {cap}, one step every {div} levels')
    desc = ('Five small charts, one per saving-throw category 0 to 4. Each shows, for levels 1 to 21, the roll '
            'of a twenty-sided die needed to save for the four class groups: ' + '; '.join(desc_parts) +
            '. Monsters use the warriors\' line with their type\'s level. Levels above 13 are shaded: experience '
            'does not reach them. In the rogues\' line, category 1 rises from 6 to 7 at level 20 and category 2 '
            'falls from 8 to 4 there.')
    out = frame(W, H, 'Saving-throw thresholds by level', desc)
    out.append(text(20, 26, 'Saving-throw thresholds by level', 14, weight=True))
    out.append(text(20, 46, 'The roll of 1d20 needed to save, before any constitution adjustment.', 12, INK2))
    # legend
    lx = 20
    for name, colour, dash in GROUPS:
        da = f' stroke-dasharray="{dash}"' if dash else ''
        out.append(f'<line x1="{lx}" y1="74" x2="{lx+28}" y2="74" stroke="{colour}" stroke-width="2.5"{da}/>')
        label = name + (' and monsters' if name == 'Warriors' else '')
        out.append(text(lx + 34, 74, label, 12))
        lx += 34 + len(label) * 7 + 24
    out.append(f'<rect x="{lx}" y="67" width="22" height="14" fill="{SHADE}" stroke="{BORDER}"/>')
    out.append(text(lx + 28, 74, 'Beyond level 13', 12))

    def threshold(group, category, level):
        off, length = THRESHOLDS[group]
        k = [g[0].lower() for g in GROUPS].index(group)
        step = min(level, CAPS[k]) // DIVISORS[k]
        return sbytes(off + category * length + step, 1)[0]

    for c in range(5):
        col, row = c % 2, c // 2
        px = 50 + col * (pw + 55)
        py = 130 + row * (ph + 85)
        X = lambda L: px + pw * (L - 0.5) / lmax
        Y = lambda v: py + ph * (vmax - v) / (vmax - vmin)
        out.append(text(px, py - 14, f'Category {c}', 13, weight=True))
        out.append(f'<rect x="{X(13.5):.1f}" y="{py}" width="{X(lmax+0.5)-X(13.5):.1f}" height="{ph}" fill="{SHADE}"/>')
        for v in range(vmin, vmax + 1, 2):
            out.append(f'<line x1="{px}" y1="{Y(v):.1f}" x2="{px+pw}" y2="{Y(v):.1f}" stroke="{GRID}"/>')
            if v % 4 == 0:
                out.append(text(px - 6, Y(v), str(v), 11, INK2, anchor='end'))
        out.append(f'<rect x="{px}" y="{py}" width="{pw}" height="{ph}" fill="none" stroke="{BORDER}"/>')
        for L in (1, 5, 9, 13, 17, 21):
            out.append(text(X(L), py + ph + 14, str(L), 11, INK2, anchor='middle'))
        out.append(text(px + pw / 2, py + ph + 32, 'Level', 11, INK2, anchor='middle'))
        for k, (name, colour, dash) in enumerate(GROUPS):
            group = name.lower()
            pts = []
            for L in range(1, CAPS[k] + 1):
                v = threshold(group, c, L)
                pts.append((X(L - 0.5), Y(v)))
                pts.append((X(L + 0.5), Y(v)))
            da = f' stroke-dasharray="{dash}"' if dash else ''
            path = ' '.join(f'{x:.1f},{y:.1f}' for x, y in pts)
            out.append(f'<polyline points="{path}" fill="none" stroke="{colour}" stroke-width="2.2"{da}/>')
        if c in (1, 2):
            L = 20
            v = threshold('rogues', c, L)
            out.append(f'<circle cx="{X(20.5):.1f}" cy="{Y(v):.1f}" r="9" fill="none" stroke="{INK}" stroke-width="1.2"/>')
    # note in the free sixth cell
    nx, ny = 50 + (pw + 55), 130 + 2 * (ph + 85)
    notes = ['Circled: the rogues\' line rises in', 'category 1 and drops in category 2', 'at level 20 (ANOMALY-126).',
             '', 'Each line stops at the level cap', 'of its group: warriors 17,', 'priests 19, wizards and rogues 21.']
    for i, line in enumerate(notes):
        out.append(text(nx, ny + 10 + i * 18, line, 12, INK2))
    write('combat-saving-throws.svg', out)


# ------------------------------------------------------------- party quarters
def party_quarters():
    W, H = 700, 420
    bx, by, size = 40, 110, 250
    half = size / 2
    pairs = [QUARTER_CHARS[2 * q:2 * q + 2] for q in range(4)]
    desc = ('Top-down view of the party\'s block, front at the top, divided into four quarters. A flying item that '
            f'reaches the front-left quarter hits character {pairs[0][0]}; the front-right quarter, character '
            f'{pairs[1][0]}; the back-left quarter, character {pairs[2][0]} only, although the table also lists '
            f'character {pairs[2][1]}, who is never hit; the back-right quarter, character {pairs[3][0]} or '
            f'{pairs[3][1]} at random, or both when the item travels along the party\'s facing axis.')
    out = frame(W, H, 'Who a flying item hits in the party\'s block', desc)
    out.append(text(20, 26, 'Who a flying item hits in the party\'s block', 14, weight=True))
    out.append(text(20, 46, 'Seen from above, party facing up; numbers are party slots. No hit roll is made.', 12, INK2))
    # facing arrow
    ax = bx + half
    out.append(f'<line x1="{ax}" y1="{by-12}" x2="{ax}" y2="{by-44}" stroke="{INK2}" stroke-width="2"/>')
    out.append(f'<path d="M{ax-6},{by-38} L{ax},{by-50} L{ax+6},{by-38} Z" fill="{INK2}"/>')
    out.append(text(ax + 10, by - 36, 'facing', 11, INK2))
    names = ['Front left', 'Front right', 'Back left', 'Back right']
    for q in range(4):
        qx = bx + (q % 2) * half
        qy = by + (q // 2) * half
        out.append(f'<rect x="{qx+2}" y="{qy+2}" width="{half-4}" height="{half-4}" rx="6" fill="{SHADE}" stroke="{BORDER}"/>')
        out.append(text(qx + half / 2, qy + 20, names[q], 12, INK2, anchor='middle'))
        first, second = pairs[q]
        if q < 2:
            chips = [(first, True)]
        elif q == 2:
            chips = [(first, True), (second, False)]
        else:
            chips = [(first, True), (second, True)]
        n = len(chips)
        for i, (slot, hit) in enumerate(chips):
            cx = qx + half / 2 + (i - (n - 1) / 2) * 50
            cy = qy + half / 2 + 8
            if hit:
                out.append(f'<circle cx="{cx:.1f}" cy="{cy:.1f}" r="19" fill="{BLUE}"/>')
                out.append(text(cx, cy, str(slot), 16, '#ffffff', True, 'middle'))
            else:
                out.append(f'<circle cx="{cx:.1f}" cy="{cy:.1f}" r="19" fill="{SURF}" stroke="{MUTED}" stroke-width="1.5" stroke-dasharray="3 3"/>')
                out.append(text(cx, cy, str(slot), 16, MUTED, True, 'middle'))
                out.append(text(cx, cy + 30, 'never hit', 11, ORANGE, anchor='middle'))
        if q == 3:
            out.append(text(qx + half / 2, qy + half - 22, 'one at random', 11, INK2, anchor='middle'))
    out.append(f'<rect x="{bx}" y="{by}" width="{size}" height="{size}" fill="none" stroke="{INK2}" stroke-width="2"/>')
    # explanations
    tx, ty = bx + size + 34, by + 8
    lines = [
        ('Front quarters', True),
        (f'One character each: {pairs[0][0]} on the left, {pairs[1][0]} on the right.', False),
        ('', False),
        ('Back right', True),
        (f'Character {pairs[3][0]} or {pairs[3][1]}, chosen at random; both when', False),
        ('the item travels front to back or back to front.', False),
        ('', False),
        ('Back left (anomaly)', True),
        (f'Always character {pairs[2][0]}. The table also names character {pairs[2][1]},', False),
        ('but this quarter is handled like a front one, so', False),
        (f'character {pairs[2][1]} is never hit by a flying item.', False),
        ('', False),
        ('Only a character that is present, alive and not', False),
        ('turned to stone is hit; otherwise the item flies on.', False),
    ]
    for i, (line, bold) in enumerate(lines):
        out.append(text(tx, ty + i * 19, line, 11.5, INK if bold else INK2, bold))
    write('combat-party-quarters.svg', out)


# ------------------------------------------------------------- how an attack unfolds
def attack_flow():
    """Transcribes the flow of docs/combat/README.md."""
    sys.path[:0] = [str(Path(__file__).resolve().parent), str(ROOT / 'scripts/common')]
    import flowcharts
    W, H = 700, 410
    desc = ('How an attack unfolds. A character uses the item in a hand. With a melee weapon, a character outside '
            "the first two slots gets CAN'T REACH; otherwise a hit roll is made against the nearest monster "
            'ahead. With a thrown weapon or a launcher, an object flies block after block, as does an item thrown '
            'by a monster, a wall or a script. In a block with monsters it reaches a monster where it arrives, '
            "after a hit roll for a character's throw; in the party's block it hits the characters of the "
            'quarter it reaches, with no roll. A hit does damage to the monster.')
    out = frame(W, H, 'How an attack unfolds', desc)
    out.append(text(20, 26, 'How an attack unfolds', 14, weight=True))
    out.append(text(20, 46, 'Melee weapons strike the nearest monster ahead; thrown and launched items fly until they hit.', 12, INK2))
    out.append(f'<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" '
               f'orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 Z" fill="{INK2}"/></marker></defs>')

    def box(x1, x2, y, h, label, kind='step'):
        fill, stroke, r = {'step': (SURF, INK2, 6), 'ask': ('#e9f1fb', BLUE, 14), 'end': (SHADE, BORDER, 6)}[kind]
        out.append(f'<rect x="{x1}" y="{y}" width="{x2-x1}" height="{h}" rx="{r}" fill="{fill}" stroke="{stroke}" stroke-width="1.4"/>')
        out.extend(flowcharts.lines((x1 + x2) / 2, y + h / 2, label, 11.5, 'middle'))

    def arrow(d, label=None, lx=0, ly=0, anchor='start'):
        out.append(f'<path d="{d}" fill="none" stroke="{INK2}" stroke-width="1.4" marker-end="url(#ah)"/>')
        if label:
            out.append(text(lx, ly, label, 11, INK2, anchor=anchor))

    box(20, 560, 76, 40, 'A character uses the item in a hand')
    box(575, 680, 70, 56, 'Thrown by a\nmonster, a wall\nor a script')
    box(20, 170, 160, 44, 'In one of the first\ntwo slots?', 'ask')
    box(210, 315, 160, 44, "CAN'T REACH", 'end')
    box(330, 560, 160, 44, 'An object flies,\nblock after block')
    box(20, 170, 250, 44, 'Hit roll against the\nnearest monster ahead')
    box(330, 560, 244, 56, 'Block with monsters: one where\nthe object arrives; a hit roll\nfor a character\'s throw')
    box(575, 680, 244, 56, "Party's block:\ncharacters of the\nquarter, no roll", 'end')
    box(20, 560, 336, 36, 'Damage to the monster')
    arrow('M95,116 L95,157', 'melee weapon', 103, 136)
    arrow('M445,116 L445,157', 'thrown weapon or launcher', 453, 136)
    arrow('M170,182 L207,182')
    out.append(text(189, 172, 'no', 11, INK2, anchor='middle'))
    arrow('M95,204 L95,247', 'yes', 103, 226)
    arrow('M627,126 L560,166')
    arrow('M445,204 L445,241')
    arrow('M540,204 L612,241')
    arrow('M95,294 L95,333', 'hit', 103, 314)
    arrow('M445,300 L445,333', 'hit', 453, 317)
    out.append(text(20, H - 18, 'After any use, the hand rests before it can be used again.', 11, INK2))
    write('combat-attack-flow.svg', out)


if __name__ == '__main__':
    # The figures rely on these readings; stop if the executable disagrees.
    assert STR_HIT == [-5, -3, -3, -2, -2, -1, -1] + [0] * 9 + [1, 1, 3, 3, 4, 4, 5, 6, 7]
    assert STR_DAMAGE == [-4, -2, -1, -1, -1] + [0] * 10 + [1, 1, 2, 7, 8, 9, 10, 11, 12, 14]
    assert DEX_HIT == [-6, -4, -3, -2, -1] + [0] * 6 + [1, 2, 2, 3, 3, 4, 4, 4]
    assert DEX_PAST == [5, 5, 5] and CAPS == [17, 21, 19, 21] and DIVISORS == [2, 5, 3, 4]
    assert sbytes(0x31ed, 50)[:9] == [16, 14, 13, 11, 10, 8, 7, 5, 4]   # warriors, category 0
    assert sbytes(0x31cf, 30)[6:18] == [14, 12, 10, 8, 6, 7, 12, 11, 10, 9, 8, 4]  # rogues 1-2
    assert QUARTER_CHARS == [0, -1, 1, -1, 2, 4, 3, 5]
    OUT.mkdir(parents=True, exist_ok=True)
    hand_recovery()
    ability_modifiers()
    saving_throws()
    party_quarters()
    attack_flow()
