view tools/balance.py @ 28:b0658e7fcee2

Added tag 0.9.1 for changeset 75deda08db90
author ark
date 2026-10-20 17:19 +0200
parents 2f555a54c332
children a464bd43b76c
line wrap: on
line source

#!/usr/bin/env python3
"""
estimate, map by map and wave by wave, whether the coins a map pays buy
enough firepower (doc/balance.md, balancing). reads config/game.toml and the
routes and placement grid of the last build, temp/build/maps.json. writes
temp/preview/balance.txt and the charts temp/preview/balance_*.png.

usage: python3 tools/balance.py
       python3 tools/balance.py --draft [MAP]

towers are t1 only for the wave demands. two players: naive builds level 1
towers on cells of median coverage whenever it can afford one; greedy picks
cells by coverage of route not yet covered and upgrades when that buys more
damage per coin than a new tower. greedy also starts every wave early for
the bonus.

--draft prints wave lists for every map, or for map MAP, as toml to paste
into config/game.toml. they are made from monster_share, wave_size and
first_wave in the map's section (see draft_waves). the calculation then
runs on the drafted lists instead of the ones in game.toml; balance.txt and
the charts are not written.

requires python 3.11 or later, numpy and matplotlib.
"""

import math
import sys
import tomllib
import json

import numpy as np

# keep tools/ free of __pycache__
sys.dont_write_bytecode = True

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from build import CONFIG, MAPS, MAPS_CACHE, PREVIEW, TOWER_BY_LEVEL, tower_levels

# distance between route samples for coverage
SAMPLE_STEP = 4
# greedy cells listed per map, more than any budget buys
GREEDY_CELLS = 120
# the tower the wave demands are measured against
TOWER = "t1"
# wave size factors scanned for the margin charts
FACTORS = np.round(np.arange(0.5, 3.001, 0.05), 2)
# hearts the naive player should have left at the end of a map (decided)
HEARTS_TARGET = 5

# chart colours: surface, text, grid, then series slots in fixed order
SURFACE = "#fcfcfb"
INK = "#0b0b0b"
INK2 = "#52514e"
GRID = "#e4e3de"
SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#6250d6"]


# coverage

def resample(points, step):
    """
    sample a route at about step apart. returns (samples, weight): an n x 2
    array of positions in the middle of equal pieces, and the length of a
    piece.
    """
    p = np.asarray(points, float)
    cum = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(p, axis=0).T))])
    n = max(1, math.ceil(cum[-1] / step))
    pos = (np.arange(n) + 0.5) * cum[-1] / n
    return np.column_stack([np.interp(pos, cum, p[:, 0]), np.interp(pos, cum, p[:, 1])]), cum[-1] / n


class MapCoverage:
    """
    legal placement cells of a map and the route samples each can reach.
    the boss route is the shortest one.
    """

    def __init__(self, mp):
        cell, cols = mp["cell"], mp["cols"]
        idx = np.array([i for i, c in enumerate(mp["grid"]) if c == "1"])
        self.cells = np.column_stack([(idx % cols) * cell + cell // 2,
                                      (idx // cols) * cell + cell // 2]).astype(float)
        routes = mp["routes"]
        self.routes = [resample(r["points"], SAMPLE_STEP) for r in routes]
        self.boss_route = min(range(len(routes)), key=lambda i: routes[i]["length"])
        self.lengths = [r["length"] for r in routes]

    def within(self, rng):
        """per route, a cells x samples array: sample in range of the cell."""
        out = []
        for samples, _ in self.routes:
            d2 = ((self.cells[:, None, :] - samples[None, :, :]) ** 2).sum(axis=2)
            out.append(d2 <= rng * rng)
        return out

    def coverage(self, rng):
        """per cell: (mean route length in range over routes, on the boss route)."""
        per_route = np.array([w.sum(axis=1) * wt for w, (_, wt) in zip(self.within(rng), self.routes)])
        return per_route.mean(axis=0), per_route[self.boss_route]

    def greedy(self, rng, count, min_dist):
        """
        up to count cells, picked one after the other by the route length in
        range that no earlier pick covers, mean over routes. picks keep
        min_dist from each other. once all route is covered, the cell with
        the most route in range is next. returns cell indices.
        """
        within = self.within(rng)
        weights = [wt for _, wt in self.routes]
        full = sum(w.sum(axis=1) * wt for w, wt in zip(within, weights)) / len(within)
        covered = [np.zeros(w.shape[1], bool) for w in within]
        free = np.ones(len(self.cells), bool)
        order = []
        for _ in range(count):
            if not free.any():
                break
            gain = sum(w[:, ~c].sum(axis=1) * wt for w, c, wt in zip(within, covered, weights)) / len(within)
            if gain[free].max() <= 0:
                gain = full
            i = int(np.flatnonzero(free)[np.argmax(gain[free])])
            order.append(i)
            for w, c in zip(within, covered):
                c |= w[i]
            free &= np.hypot(*(self.cells - self.cells[i]).T) >= min_dist
        return order


# waves

def scale_counts(cfg, monsters, f):
    """
    a wave's monster counts with the regular ones scaled by f, rounded, at
    least one regular monster left. the boss stays.
    """
    mons = cfg["monster"]
    out = {k: (n if mons[k].get("boss") else math.floor(n * f + 0.5)) for k, n in monsters.items()}
    reg = [k for k in monsters if not mons[k].get("boss")]
    if reg and not any(out[k] for k in reg):
        out[max(reg, key=lambda k: monsters[k])] = 1
    return out


class Wave:
    """
    one wave. kinds: list of (count, hp, speed, coins, boss).
    """

    def __init__(self, cfg, monsters, interval):
        mons = cfg["monster"]
        self.kinds = [(n, mons[k]["hp"], mons[k]["speed"], mons[k]["coins"],
                       bool(mons[k].get("boss"))) for k, n in monsters.items() if n]
        reg = [k for k in self.kinds if not k[4]]
        self.boss = next((k for k in self.kinds if k[4]), None)
        self.count = sum(k[0] for k in reg)
        self.hp = sum(k[0] * k[1] for k in reg)
        self.coins = sum(k[0] * k[3] for k in reg)
        self.speed = sum(k[0] * k[2] for k in reg) / self.count
        # time from the first spawn to the last, and the spacing on the route
        self.duration = (self.count - 1) * interval
        self.spacing = self.speed * interval
        self.tough = max(reg, key=lambda k: k[1])
        self.reg = reg

    def shots(self, damage):
        """shots that kill every regular monster of the wave, whole shots each."""
        return sum(n * math.ceil(hp / damage) for n, hp, _, _, _ in self.reg)


def result(towers, wave, attack_time):
    """
    what towers do against a wave. towers: list of (coverage, boss route
    coverage, damage). throughput: each tower attacks from the first monster
    reaching it until the last has passed, while a monster is in range,
    with whole shots per monster. single target: the monster gets every
    tower's full attention while in range. returns a dict with leak (regular
    hp not killed), hearts, coins earned, holds, and the single target
    damage on the boss and on the toughest regular monster.
    """
    cap = 0.0
    tough = 0.0
    boss = 0.0
    for cov, bcov, dmg in towers:
        busy = 1 - math.exp(-cov / wave.spacing)
        window = wave.duration + cov / wave.speed
        cap += window / attack_time * busy * wave.hp / wave.shots(dmg)
        tough += cov / wave.tough[2] / attack_time * dmg
        if wave.boss:
            boss += bcov / wave.boss[2] / attack_time * dmg
    leak = max(0.0, wave.hp - cap)
    killed = 1 - leak / wave.hp
    out = {"leak": leak, "tough": tough, "boss": boss}
    out["hearts"] = leak / (wave.hp / wave.count)
    out["coins"] = wave.coins * killed
    boss_ok = True
    if wave.boss:
        boss_ok = boss >= wave.boss[1]
        if boss_ok:
            out["coins"] += wave.boss[3]
        else:
            out["hearts"] += 5
    out["holds"] = leak < 1e-9 and boss_ok
    return out


# players

class Player:
    """
    a fixed order of purchases. states[k] is the list of towers after the
    first k purchases, cost[k] what they cost in all.
    """

    def holds_from(self, wave, attack_time):
        """smallest k whose towers hold the wave, None if none does."""
        lo, hi = 0, len(self.states) - 1
        if not result(self.states[hi], wave, attack_time)["holds"]:
            return None
        while lo < hi:
            mid = (lo + hi) // 2
            if result(self.states[mid], wave, attack_time)["holds"]:
                hi = mid
            else:
                lo = mid + 1
        return lo


class Naive(Player):
    def __init__(self, tower, cov, bcov, budget):
        n = budget // tower["cost"][0] + 1
        self.states = [[(cov, bcov, tower["damage"][0])] * k for k in range(n)]
        self.cost = [k * tower["cost"][0] for k in range(n)]
        self.bonus = False


class Greedy(Player):
    """
    each purchase is a new level 1 tower on the next greedy cell or an
    upgrade, whichever adds more damage per second per coin. damage per
    second counts while a monster is in range, at spacing s.
    """

    def __init__(self, tower, cells, cov, bcov, budget, spacing):
        at = tower["attack_time"]
        dmg, cost = tower["damage"], tower["cost"]

        def busy(i):
            return 1 - math.exp(-cov[i] / spacing)

        levels = []         # (cell, level) per tower
        nxt = 0
        total = 0
        self.states = [[]]
        self.cost = [0]
        while True:
            best, choice = 0.0, None
            if nxt < len(cells):
                best, choice = dmg[0] / at * busy(cells[nxt]) / cost[0], ("new", None)
            for t, (c, lv) in enumerate(levels):
                if lv < len(dmg):
                    v = (dmg[lv] - dmg[lv - 1]) / at * busy(c) / cost[lv]
                    if v > best:
                        best, choice = v, ("up", t)
            if choice is None:
                break
            if choice[0] == "new":
                price = cost[0]
                levels.append((cells[nxt], 1))
                nxt += 1
            else:
                c, lv = levels[choice[1]]
                price = cost[lv]
                levels[choice[1]] = (c, lv + 1)
            total += price
            if total > budget:
                break
            self.states.append([(cov[c], bcov[c], dmg[lv - 1]) for c, lv in levels])
            self.cost.append(total)
        self.bonus = True


def play(player, waves, start, bonuses, attack_time):
    """
    play a map: at each wave start buy what the coins allow, in the
    player's order. returns one row per wave: budget (coins on hand plus
    coins spent so far), coins left after buying, towers bought, coins the
    wave needs (None: more than the purchase list holds), hearts lost, and
    the result.
    """
    coins, k, rows = start, 0, []
    for w, wave in enumerate(waves):
        if player.bonus:
            coins += bonuses[w]
        while k + 1 < len(player.states) and player.cost[k + 1] - player.cost[k] <= coins:
            coins -= player.cost[k + 1] - player.cost[k]
            k += 1
        res = result(player.states[k], wave, attack_time)
        need = player.holds_from(wave, attack_time)
        rows.append({"budget": coins + player.cost[k], "left": coins, "towers": len(player.states[k]),
                     "need": None if need is None else player.cost[need], "res": res})
        coins += res["coins"]
    return rows


# drafting

def draft_waves(cfg, m):
    """
    wave lists for map m from the draft numbers in its section: wave_count
    waves, regular monster counts growing in equal steps from wave_size[0]
    to wave_size[1], monster level i absent before wave first_wave[i]. the
    counts of each level over the whole map follow monster_share.

    each level starts with a weight that grows by one per wave from its
    first wave, so later waves lean to the levels that came in later. the
    weights are then scaled, alternately per wave and per level, until the
    wave sizes and the level totals are met, and rounded per wave. every
    level keeps at least one monster. the boss is added to the last wave.
    returns a list of {monster: count}.
    """
    c = cfg["map"][str(m)]
    regular = sorted(k for k, v in cfg["monster"].items() if not v.get("boss"))
    n = c["wave_count"]
    first, last = c["wave_size"]
    sizes = np.array([round(first + (last - first) * w / max(1, n - 1)) for w in range(n)], float)
    share = np.array(c["monster_share"], float)
    totals = share / share.sum() * sizes.sum()
    intro = np.array(c["first_wave"]) - 1
    a = np.maximum(0, np.arange(n)[:, None] - intro[None, :] + 1).astype(float)
    for _ in range(500):
        a *= (sizes / np.maximum(a.sum(axis=1), 1e-12))[:, None]
        a *= (totals / np.maximum(a.sum(axis=0), 1e-12))[None, :]
    a *= (sizes / np.maximum(a.sum(axis=1), 1e-12))[:, None]
    counts = np.floor(a).astype(int)
    for w in range(n):
        # largest remainders fill the wave up to its size
        short = int(sizes[w]) - counts[w].sum()
        for i in np.argsort(-(a[w] - counts[w]))[:short]:
            counts[w, i] += 1
    for i in range(len(regular)):
        if counts[:, i].sum() == 0 and intro[i] < n:
            counts[n - 1, i] += 1
            counts[n - 1, int(np.argmax(counts[n - 1]))] -= 1
    waves = [{k: int(v) for k, v in zip(regular, row) if v} for row in counts]
    waves[-1][f"b{m}"] = 1
    return waves


def draft_toml(cfg, m, waves):
    """the drafted waves as toml lines, each wave with its count, hp and coins."""
    c = cfg["map"][str(m)]
    mons = cfg["monster"]
    lines = [f"# map{m}: drafted by tools/balance.py --draft from wave_count {c['wave_count']},"
             f" wave_size {c['wave_size']},",
             f"# monster_share {c['monster_share']}, first_wave {c['first_wave']}", ""]
    for w, wave in enumerate(waves, start=1):
        reg = {k: v for k, v in wave.items() if not mons[k].get("boss")}
        boss = [k for k in wave if mons[k].get("boss")]
        hp = sum(v * mons[k]["hp"] for k, v in reg.items())
        coins = sum(v * mons[k]["coins"] for k, v in reg.items())
        extra = "".join(f" + boss {mons[k]['coins']}" for k in boss)
        lines += [f"[[map.{m}.wave]]   # wave {w}, {sum(reg.values())} monsters, {hp} hp,"
                  f" {coins} coins{extra}",
                  "monsters = { " + ", ".join(f"{k} = {v}" for k, v in wave.items()) + " }", ""]
    return lines


def draft_check(cfg, waves):
    """warnings for drafted waves: a wave with less hp than the one before."""
    mons = cfg["monster"]
    hp = [sum(v * mons[k]["hp"] for k, v in w.items() if not mons[k].get("boss")) for w in waves]
    return [f"wave {w + 1} has less hp than wave {w} ({hp[w]} < {hp[w - 1]})"
            for w in range(1, len(hp)) if hp[w] < hp[w - 1]]


# calculation

def tower_table(cfg):
    """tower id -> config with the by-level values filled in."""
    return {tid: {k: tower_levels(v) if k in TOWER_BY_LEVEL else v for k, v in tw.items()}
            for tid, tw in cfg["tower"].items()}


def map_waves(cfg, m, f):
    """the map's waves with regular monster counts scaled by f."""
    c = cfg["map"][str(m)]
    interval = c.get("spawn_interval", cfg["waves"]["spawn_interval"])
    return [Wave(cfg, scale_counts(cfg, w["monsters"], f), interval) for w in c["wave"]]


def bonuses(cfg, m):
    """early start bonus for skipping the break before each wave."""
    c = cfg["map"][str(m)]
    n = len(c["wave"])
    return [math.floor(c["early_bonus"] * (cfg["waves"]["first_break"] if w == 0 else cfg["waves"]["break"]))
            for w in range(n)]


def analyse_map(cfg, towers, mp, m):
    """everything the report and charts show for map m."""
    c = cfg["map"][str(m)]
    tw = towers[TOWER]
    mc = MapCoverage(mp)
    cov, bcov = mc.coverage(tw["range"][0])
    cells = mc.greedy(tw["range"][0], GREEDY_CELLS, cfg["placement"]["min_tower_distance"])
    waves1 = map_waves(cfg, m, 1.0)
    # budget large enough for every factor scanned
    budget = (c["starting_coins"] + sum(w.coins + (w.boss[3] if w.boss else 0) for w in waves1)
              + sum(bonuses(cfg, m))) * 3
    spacing = sum(w.spacing * w.count for w in waves1) / sum(w.count for w in waves1)
    naive = Naive(tw, float(np.median(cov)), float(np.median(bcov)), budget)
    greedy = Greedy(tw, cells, cov, bcov, budget, spacing)
    at, start, bon = tw["attack_time"], c["starting_coins"], bonuses(cfg, m)

    scan = []
    for f in FACTORS:
        waves = map_waves(cfg, m, f)
        n, g = play(naive, waves, start, bon, at), play(greedy, waves, start, bon, at)
        scan.append({"f": f, "naive": n, "greedy": g})
    out = {"m": m, "cov": cov, "bcov": bcov, "cells": cells, "routes": len(mc.routes),
           "lengths": mc.lengths, "spacing": spacing, "waves": waves1, "bonus": bon,
           "naive": play(naive, waves1, start, bon, at), "greedy": play(greedy, waves1, start, bon, at),
           "scan": scan, "coverage": {}}
    for tid, t in towers.items():
        tc, _ = mc.coverage(t["range"][0])
        out["coverage"][tid] = (float(np.median(tc)), float(np.percentile(tc, 90)), float(tc.max()))
    return out


def surplus(rows):
    """coins on hand at the start of the last wave beyond what it needs."""
    last = rows[-1]
    return None if last["need"] is None else last["budget"] - last["need"]


def hearts_lost(rows):
    return sum(r["res"]["hearts"] for r in rows)


def factors_at_target(scan):
    """
    the wave size factors at which naive ends with HEARTS_TARGET hearts or
    fewer, as a list of (lowest, highest) ranges of neighbouring scan
    points. larger waves also pay more coins, so there may be several.
    """
    out = []
    for i, s in enumerate(scan):
        if hearts_lost(s["naive"]) < 10 - HEARTS_TARGET:
            continue
        if out and out[-1][2] == i - 1:
            out[-1] = (out[-1][0], s["f"], i)
        else:
            out.append((s["f"], s["f"], i))
    return [(lo, hi) for lo, hi, _ in out]


# report

def value_table(cfg, towers):
    regular = sorted(k for k, v in cfg["monster"].items() if not v.get("boss"))
    lines = ["value per coin: hp killed per second per coin paid for the tower,",
             "whole shots per monster. t0 counts one monster per attack.", ""]
    head = f"{'tower':6}{'level':>6}{'damage':>8}{'range':>7}{'paid':>6}{'dps':>7}{'dps/coin':>10}"
    head += "".join(f"{'vs ' + k:>8}" for k in regular)
    lines.append(head)
    for tid, t in towers.items():
        paid = 0
        for lv in range(len(t["damage"])):
            d, at = t["damage"][lv], t["attack_time"]
            paid += t["cost"][lv]
            row = f"{tid:6}{lv + 1:>6}{d:>8g}{t['range'][lv]:>7g}{paid:>6}{d / at:>7.1f}{d / at / paid:>10.2f}"
            for k in regular:
                hp = cfg["monster"][k]["hp"]
                row += f"{hp / (math.ceil(hp / d) * at) / paid:>8.2f}"
            lines.append(row)
    return lines


def t0_table(cfg, towers, analyses):
    """
    t0's value per coin with area damage: the single target value times the
    monsters hit per attack. hits per attack as measured by tools/simulate.js
    (temp/preview/simulate.json, players naive_t0 and naive_mix) where
    available, otherwise the estimate from coverage and spacing.
    """
    measured = {}
    sim = PREVIEW / "simulate.json"
    if sim.exists():
        for r in json.loads(sim.read_text()):
            if r.get("t0Hits") is not None:
                measured.setdefault(r["map"], []).append(r["t0Hits"])
    t0, t1 = towers["t0"], towers[TOWER]
    lines = ["t0 with area damage: hp per second per coin, whole shots, times the",
             "monsters hit per attack. est: monsters in range of a median t0 cell at",
             "the mean spacing. sim: measured by tools/simulate.js over whole runs of",
             "the naive t0 players, if it was run. t1 level 1 for comparison.", "",
             f"{'map':5}{'est':>6}{'sim':>6}  level" + "".join(f"{'vs ' + k:>8}" for k in ("m0", "m4"))]
    for a in analyses:
        m = a["m"]
        est = a["coverage"]["t0"][0] / a["spacing"]
        sim_h = sum(measured[m]) / len(measured[m]) if m in measured else None
        hits = sim_h if sim_h is not None else est
        paid = 0
        for lv in range(len(t0["damage"])):
            d, at = t0["damage"][lv], t0["attack_time"]
            paid += t0["cost"][lv]
            row = (f"map{m:<2}{est:>6.1f}{'-' if sim_h is None else f'{sim_h:.2f}':>6}" if lv == 0
                   else " " * 17)
            row += f"{lv + 1:>7}"
            for k in ("m0", "m4"):
                hp = cfg["monster"][k]["hp"]
                row += f"{hits * hp / (math.ceil(hp / d) * at) / paid:>8.2f}"
            lines.append(row)
        row = " " * 17 + f"{'t1 1':>7}"
        for k in ("m0", "m4"):
            hp = cfg["monster"][k]["hp"]
            row += f"{hp / (math.ceil(hp / t1['damage'][0]) * t1['attack_time']) / t1['cost'][0]:>8.2f}"
        lines.append(row)
    return lines + [""]


def map_report(cfg, a):
    m, c = a["m"], cfg["map"][str(a["m"])]
    lens = a["lengths"]
    lines = [f"map{m}", "----", "",
             f"{a['routes']} route(s), length {min(lens):.0f}" + (f" to {max(lens):.0f}" if len(lens) > 1 else "")
             + f"; spacing between monsters {a['spacing']:.0f}; starting coins {c['starting_coins']}", "",
             "coverage by level 1 range, route length in range per legal cell:", "",
             f"{'tower':6}{'median':>8}{'top10%':>8}{'best':>8}{'t0 hits':>9}"]
    for tid, (med, top, best) in a["coverage"].items():
        hits = f"{med / a['spacing']:>9.1f}" if tid == "t0" else ""
        lines.append(f"{tid:6}{med:>8.0f}{top:>8.0f}{best:>8.0f}{hits}")
    lines += ["", "t0 hits: monsters in range of a median t0 cell at the mean spacing,",
              "the number one t0 attack damages in a full wave.", "",
              "waves, t1 only, wave size factor 1. need/s: hp per second the towers",
              "have to kill (throughput, median cell). single: damage the toughest",
              "monster takes from the naive towers while in range, against its hp.",
              "budget: coins on hand plus coins spent. need: coins of the purchases",
              "that hold the wave. lost: hearts lost, leaks by throughput plus 5 for",
              "a boss.", "",
              f"{'wave':>4}{'count':>6}{'hp':>6}{'coins':>6}{'need/s':>8}{'single':>12}"
              f"   naive{'budget':>8}{'need':>6}{'lost':>6}   greedy{'budget':>8}{'need':>6}{'lost':>6}"]
    med = float(np.median(a["cov"]))
    for w, (wave, n, g) in enumerate(zip(a["waves"], a["naive"], a["greedy"]), start=1):
        rate = wave.hp / (wave.duration + med / wave.speed)
        if wave.boss:
            single = f"{n['res']['boss']:.0f}/{wave.boss[1]}b"
        else:
            single = f"{n['res']['tough']:.0f}/{wave.tough[1]}"
        coins = wave.coins + (wave.boss[3] if wave.boss else 0)
        need = lambda r: "-" if r["need"] is None else str(r["need"])
        lines.append(f"{w:>4}{wave.count:>6}{wave.hp:>6}{coins:>6}{rate:>8.1f}{single:>12}"
                     f"        {n['budget']:>8.0f}{need(n):>6}{n['res']['hearts']:>6.1f}"
                     f"         {g['budget']:>8.0f}{need(g):>6}{g['res']['hearts']:>6.1f}")
    one = next(s for s in a["scan"] if s["f"] == 1.0)
    target = factors_at_target(a["scan"])
    fmt = lambda v: "-" if v is None else f"{v:.0f}"
    lines += ["", f"wave size factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts,"
              f" surplus at the last wave {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f},"
              f" surplus {fmt(surplus(one['greedy']))}",
              f"wave size factors at which naive ends with {HEARTS_TARGET} hearts or fewer: "
              + (", ".join(f"{lo:.2f} to {hi:.2f}" for lo, hi in target) or "none in the scan"), ""]
    return lines


# charts

def style(ax, title, xlabel, ylabel):
    ax.set_facecolor(SURFACE)
    ax.set_title(title, color=INK, fontsize=11, loc="left")
    ax.set_xlabel(xlabel, color=INK2, fontsize=9)
    ax.set_ylabel(ylabel, color=INK2, fontsize=9)
    ax.grid(True, color=GRID, linewidth=0.8)
    ax.set_axisbelow(True)
    for side in ("top", "right"):
        ax.spines[side].set_visible(False)
    for side in ("left", "bottom"):
        ax.spines[side].set_color(INK2)
    ax.tick_params(colors=INK2, labelsize=8)


def line(ax, x, y, slot, label, **kw):
    ax.plot(x, y, color=SERIES[slot], linewidth=2, marker="o", markersize=5,
            markeredgecolor=SURFACE, markeredgewidth=1, label=label, **kw)


def legend(ax):
    ax.legend(frameon=False, fontsize=8, labelcolor=INK)


def map_chart(a, path):
    fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), facecolor=SURFACE)
    waves = range(1, len(a["waves"]) + 1)
    ax = axes[0]
    style(ax, f"map{a['m']}: coins per wave, wave size factor 1", "wave", "coins")
    line(ax, waves, [r["budget"] for r in a["naive"]], 0, "budget (naive)")
    line(ax, waves, [r["need"] for r in a["naive"]], 1, "needed, naive")
    line(ax, waves, [r["need"] for r in a["greedy"]], 2, "needed, greedy")
    ax.set_xticks(list(waves))
    legend(ax)

    f = [s["f"] for s in a["scan"]]
    ax = axes[1]
    style(ax, "surplus at the last wave", "wave size factor", "coins")
    ax.axhline(0, color=INK2, linewidth=1)
    line(ax, f, [surplus(s["naive"]) for s in a["scan"]], 1, "naive", markevery=10)
    line(ax, f, [surplus(s["greedy"]) for s in a["scan"]], 2, "greedy", markevery=10)
    legend(ax)

    ax = axes[2]
    style(ax, "hearts left at the end", "wave size factor", "hearts")
    ax.axhline(HEARTS_TARGET, color=INK2, linewidth=1, linestyle="--")
    ax.text(f[-1], HEARTS_TARGET + 0.2, "target, naive", color=INK2, fontsize=8, ha="right")
    line(ax, f, [max(0, 10 - hearts_lost(s["naive"])) for s in a["scan"]], 1, "naive", markevery=10)
    line(ax, f, [max(0, 10 - hearts_lost(s["greedy"])) for s in a["scan"]], 2, "greedy", markevery=10)
    ax.set_ylim(-0.3, 10.5)
    legend(ax)
    fig.tight_layout()
    fig.savefig(path, dpi=110, facecolor=SURFACE)
    plt.close(fig)


def value_chart(cfg, towers, path):
    fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), facecolor=SURFACE)
    for ax, mon in zip(axes, ("m0", "m4")):
        hp = cfg["monster"][mon]["hp"]
        style(ax, f"hp per second per coin against {mon} ({hp} hp)", "tower level", "hp/s per coin")
        for slot, (tid, t) in enumerate(towers.items()):
            paid = np.cumsum(t["cost"])
            v = [hp / (math.ceil(hp / d) * t["attack_time"]) / p for d, p in zip(t["damage"], paid)]
            line(ax, range(1, len(v) + 1), v, slot, tid)
        ax.set_xticks(range(1, 6))
        legend(ax)
    fig.tight_layout()
    fig.savefig(path, dpi=110, facecolor=SURFACE)
    plt.close(fig)


def draft(cfg, towers, maps, only):
    """print drafted wave lists as toml and what the calculation makes of them."""
    for m in range(MAPS) if only is None else [only]:
        waves = draft_waves(cfg, m)
        print("\n".join(draft_toml(cfg, m, waves)))
        for msg in draft_check(cfg, waves):
            print(f"# warning: {msg}")
        cfg["map"][str(m)]["wave"] = [{"monsters": w} for w in waves]
        report = map_report(cfg, analyse_map(cfg, towers, maps[m], m))
        print("\n".join("# " + l for l in report[-3:-1]), end="\n\n")
    return 0


def main():
    args = sys.argv[1:]
    if args and args[0] not in ("--draft",) or len(args) > 2:
        print(__doc__.split("\n\n")[1])
        return 2
    cfg = tomllib.loads((CONFIG / "game.toml").read_text())
    if not MAPS_CACHE.exists():
        print("no route data: run tools/build.py first")
        return 1
    maps = json.loads(MAPS_CACHE.read_text())["maps"]
    towers = tower_table(cfg)
    if args:
        return draft(cfg, towers, maps, int(args[1]) if len(args) > 1 else None)
    PREVIEW.mkdir(parents=True, exist_ok=True)
    lines = ["balance estimate, written by tools/balance.py", ""] + value_table(cfg, towers) + [""]
    value_chart(cfg, towers, PREVIEW / "balance_value.png")
    analyses = []
    for m in range(MAPS):
        a = analyse_map(cfg, towers, maps[m], m)
        analyses.append(a)
        report = map_report(cfg, a)
        lines += report
        print("\n".join(report[-3:-1]).replace("wave size factor 1:", f"map{m}, wave size factor 1:"))
        map_chart(a, PREVIEW / f"balance_map{m}.png")
    lines += t0_table(cfg, towers, analyses)
    (PREVIEW / "balance.txt").write_text("\n".join(lines))
    print("balance: wrote temp/preview/balance.txt, balance_*.png")
    return 0


if __name__ == "__main__":
    sys.exit(main())