changeset 22:ad1b478fc4dc

balancing work, docs and scripts
author ark
date 2026-10-20 03:08 +0200
parents fa04481563b7
children 2f555a54c332
files config/game.toml doc/architecture.md doc/balance.md doc/game_design.md doc/roadmap.md tools/balance.py tools/build.py
diffstat 7 files changed, 679 insertions(+), 21 deletions(-) [+]
line wrap: on
line diff
--- a/config/game.toml	Tue Oct 20 00:44:02 2026 +0200
+++ b/config/game.toml	Tue Oct 20 03:08:56 2026 +0200
@@ -19,8 +19,8 @@
 hp_bar = 0.25       # guess
 
 
-# monsters. coins: regular monsters drop 0.2 coins per hp, bosses 1 coin per
-# hp (derived). hit_radius is a share of the scaled sprite's smaller side.
+# monsters. coins: monsters and bosses drop 0.2 coins per hp (derived).
+# hit_radius is a share of the scaled sprite's smaller side.
 
 [monster.m0]
 hp = 5              # notes
@@ -48,25 +48,25 @@
 speed = 35          # guess
 
 [monster.b0]
-hp = 30             # notes
+hp = 150            # decided, 5 x the notes (30)
 coins = 30          # notes
 speed = 25          # guess
 boss = true
 
 [monster.b1]
-hp = 50             # notes
+hp = 250            # decided, 5 x the notes (50)
 coins = 50          # notes
 speed = 25          # guess
 boss = true
 
 [monster.b2]
-hp = 70             # notes
+hp = 350            # decided, 5 x the notes (70)
 coins = 70          # notes
 speed = 25          # guess
 boss = true
 
 [monster.b3]
-hp = 100            # notes
+hp = 500            # decided, 5 x the notes (100)
 coins = 100         # notes
 speed = 25          # guess
 boss = true
@@ -143,9 +143,9 @@
 
 
 [placement]
-footprint_radius = 20   # balancing
+footprint_radius = 16   # guess
 max_gap = 14            # guess, largest gap between footprint and path edge
-min_tower_distance = 32 # derived (two footprints)
+min_tower_distance = 40 # decided, keeps towers apart (was 32, two footprints)
 edge_distance = 16      # guess
 snap_radius = 48        # guess
 grid_cell = 4           # guess
--- a/doc/architecture.md	Tue Oct 20 00:44:02 2026 +0200
+++ b/doc/architecture.md	Tue Oct 20 03:08:56 2026 +0200
@@ -140,6 +140,32 @@
 `tools/publish.py` writes a zip of www/ into dist/, with debug switches off.
 
 
+balance tools
+-------------
+
+tools/balance.py estimates, map by map and wave by wave, whether the coins
+a map pays buy enough firepower (balance.md, balancing). it is run by hand
+after a build: it reads config/game.toml, and the routes and placement grid
+from temp/build/maps.json. it only calculates and leaves the images alone.
+it writes tables and charts (numpy, matplotlib) to temp/preview/:
+
+- balance.txt: value per coin for every tower and level; per map the
+  coverage of each tower's range, and per wave the coins on hand, the
+  damage rate both demands need and the coins the naive and greedy players
+  need to hold the wave
+- balance_value.png: value per coin by tower level
+- balance_map0.png to balance_map3.png: coins per wave, and the surplus at
+  the last wave and the hearts left against a factor on all monster hp
+
+tools/build.py does not count balance.py as one of its inputs, so changing
+it does not rebuild the game.
+
+a headless simulation will check the calculation. it runs the game logic
+from game/js/ in node, with MM.audio and MM.assets.size replaced by stubs,
+and plays the naive and greedy players. the seeded random generator makes a
+run repeatable. it is built after the calculation.
+
+
 routes
 ------
 
@@ -288,6 +314,3 @@
 -----------
 
 - in-browser editors or tuning panels
-- automatic balance simulation: tower placement is up to the player, so a
-  simulation would need a placement strategy first. could be revisited once
-  the game is playable
--- a/doc/balance.md	Tue Oct 20 00:44:02 2026 +0200
+++ b/doc/balance.md	Tue Oct 20 03:08:56 2026 +0200
@@ -55,12 +55,13 @@
 | m2      | 15 | 3     | 45    | as above |
 | m3      | 20 | 4     | 40    | as above |
 | m4      | 30 | 6     | 35    | as above |
-| b0      | 30 | 30    | 25    | as above |
-| b1      | 50 | 50    | 25    | as above |
-| b2      | 70 | 70    | 25    | as above |
-| b3      | 100 | 100  | 25    | as above |
+| b0      | 150 | 30   | 25    | hp: decided, 5 x the notes; coins: notes; speed: guess |
+| b1      | 250 | 50   | 25    | as above |
+| b2      | 350 | 70   | 25    | as above |
+| b3      | 500 | 100  | 25    | as above |
 
-regular monsters drop 0.2 coins per hp; bosses drop 1 coin per hp (derived).
+monsters and bosses drop 0.2 coins per hp (derived). the notes gave bosses
+hp equal to their coins; balancing raised it to 5 times that (decided).
 
 time to walk the whole path at 35-45 speed (derived): map0 about 50 s, map3
 about 23 s.
@@ -201,7 +202,7 @@
 | largest gap between footprint and road edge | 14   | guess  |
 | space between footprint and spawn point    | per map: 50 | decided |
 | space between footprint and exit point     | per map: 40 | decided |
-| smallest distance between tower centres    | 32    | derived (two footprints) |
+| smallest distance between tower centres    | 40    | decided (was 32, two footprints; towers stood too close together) |
 | distance from the map edge                 | 16    | guess  |
 | snap radius, how far a tap may be from a legal position | 48 | guess |
 | placement grid cell                        | 4     | guess  |
@@ -307,3 +308,112 @@
 | parameter  | value  | source |
 |------------|--------|--------|
 | game speeds | 1x, 2x, 4x | decided |
+
+
+balancing
+---------
+
+the values above were set without a way to estimate their effect, and the
+game is far too easy. two t1 towers win every map, t2 is never needed, and
+many coins are left over when a map is won. the aim is a game where the
+player has to think about where to place towers and which ones to build. a
+player who only buys plain firepower should need nearly every coin a map
+pays in order to win it. coins left over then come from better choices.
+
+two scripted players mark the range (decided):
+
+- naive: builds t1 only, on placement cells of median coverage, whenever it
+  can afford one. it should win with about 5 of its 10 hearts left and with
+  next to no coins at the start of the last wave
+- greedy: builds on the best cells, and upgrades when no good cell is left.
+  it should win with coins to spare
+
+rules for changing values:
+
+- shop prices and starting coins stay multiples of 5. round upgrade prices
+  are preferred
+- values the player does not see are free: hp, damage, coin drops, speeds,
+  attack times
+- shop prices are set first. hp, damage and the wave mix are then fitted to
+  them
+- the main control is coins per hp. regular monsters drop 0.2 coins per hp,
+  so a map's difficulty and its income grow together. a map gets harder when
+  its hp go up while its coins stay the same
+
+the coins of the last wave, the boss's included, arrive when the map is as
+good as won. leftover coins are therefore measured at the start of the last
+wave. the last wave's coins are left out of the calculation. the boss keeps
+its drop as a visible reward (decided).
+
+the calculation goes wave by wave, not per map. at the start of each wave
+the player has the starting coins, the coins dropped in earlier waves and
+any early start bonus. these coins buy a certain amount of firepower. the
+wave sets two demands on it:
+
+- throughput: the towers' damage per second has to keep up with the hp
+  arriving per second. the time a monster spends in range gives some buffer
+- single target: the toughest monster of the wave, m4 or the boss, has to
+  die within its time in range
+
+damage is counted in whole shots. t1 at level 1 needs 2 shots for the 5 hp
+of an m0, not five thirds of one.
+
+simplifications in tools/balance.py:
+
+- a tower attacks from the first monster of a wave reaching it until the
+  last has passed. it is idle when no monster is in range. with route
+  length c in range and spacing s between monsters, the share of time with
+  a monster in range is taken as 1 - e^(-c/s)
+- for the single target demand the monster gets every tower's full
+  attention while in range. in the game, faster monsters overtake the
+  boss and draw fire away from it
+- the naive player builds at the start of a wave with the coins on hand
+  and never starts a wave early. the greedy player always starts early and
+  takes the bonus. coins dropped during a wave count from the next wave
+- monsters that leak cost one heart each and drop no coins, so a leaky
+  wave leaves less for the next one
+- routes are equally likely; the route preference is left out. the boss
+  takes the shortest route
+- towers keep their level 1 range when upgraded
+
+the time a monster spends in range comes from coverage: the length of route
+within a tower's range, measured for every legal placement cell from the
+build's route and placement data. the median cell stands for the naive
+player and the best cells for the greedy one. for more than one tower,
+cells are picked one after the other, each counting only route that no
+earlier tower covers. maps with several routes are measured per route.
+
+t1 coverage at range 100 and footprint radius 16, in map pixels of route
+within range, the mean over routes on maps with several. top 10 % is the
+coverage the best tenth of the cells reach:
+
+| map  | routes | legal cells | best | top 10 % | median |
+|------|--------|-------------|------|----------|--------|
+| map0 | 1      | 2893        | 415  | 360      | 228    |
+| map1 | 3      | 2132        | 325  | 232      | 129    |
+| map2 | 6      | 1857        | 276  | 195      | 111    |
+| map3 | 1      | 1369        | 422  | 311      | 174    |
+
+route lengths: map0 2068, map1 737 to 1048, map2 722 to 1363, map3 1035.
+
+value per coin is damage per second divided by all coins paid for the
+tower. for t1 it falls with level: 0.43, 0.38, 0.31, 0.26 and 0.22. this
+is the intended trade between upgrading and building another tower. t0 at
+level 1 reaches 0.67 against a single target, kills an m0 in one hit and
+damages every monster in range. it may be the better buy for a naive
+player than t1, so the calculation lists value per coin for every tower and
+level, area damage included.
+
+t2 works as a time multiplier. a slow to 0.6 of the speed gives 1.67 times
+the time in range for every tower covering the same stretch. this only
+helps against the single target demand, so t2 needs faster monsters or
+tough monsters spaced apart to pay off. it is tuned after the t1 baseline.
+
+order of work (decided):
+
+1. the calculation, tools/balance.py (architecture.md): value per coin for
+   every tower, the wave demands against t1 only
+2. shop prices fixed, then hp, damage and waves fitted to them
+3. t2 after the t1 baseline
+4. a headless simulation of the real game code with the two scripted
+   players confirms the result
--- a/doc/game_design.md	Tue Oct 20 00:44:02 2026 +0200
+++ b/doc/game_design.md	Tue Oct 20 03:08:56 2026 +0200
@@ -100,8 +100,8 @@
   overlap out of red path
 - monsters do not walk in single file: each walks a little to the side of the
   path, drifting from side to side, and at a slightly different speed
-- bosses are map-specific, b0 belongs to map0 etc; boss hp 30/50/70/100 coin
-  drop equal to hp
+- bosses are map-specific, b0 belongs to map0 etc; boss coin drop
+  30/50/70/100, boss hp 5 times that (balance.md)
 - hp bars are always shown above every monster. the boss uses its own bar, also
   above the boss. the bar turns blue while t2 slows the monster
 - dropped coins fly to the coin counter on their own. each coin uses a random
@@ -111,7 +111,8 @@
 -----------------
 
 - starting coins per map level: 10, 20, 40, 60
-- balance of monster speed vs tower fire frequency tbd
+- balance of monster speed vs tower fire frequency tbd, see balance.md,
+  balancing
 - several monster waves per map with breaks between them, total 10*map
   starting coins, last wave includes boss
 - the break between waves counts down, and the next wave starts on its own
--- a/doc/roadmap.md	Tue Oct 20 00:44:02 2026 +0200
+++ b/doc/roadmap.md	Tue Oct 20 03:08:56 2026 +0200
@@ -34,6 +34,8 @@
       splash screen, map lost back to the first map
     - no map selection, unlocking or localStorage
 8. tuning on all maps
+    - balance calculation, then the headless simulation to check it
+      (balance.md, balancing; architecture.md, balance tools)
     - wave lists for maps 1-3, playtesting, balance changes in config only
 9. supplied art and sound
     - icons, screens and digits as the drawings arrive (art.md)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/balance.py	Tue Oct 20 03:08:56 2026 +0200
@@ -0,0 +1,521 @@
+#!/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
+
+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.
+
+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"
+# hp factors scanned for the margin charts
+FACTORS = np.round(np.arange(0.5, 6.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.
+    routes with a fixed weight of 0 are left out; 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 = [r for r in mp["routes"] if r["weight"] != 0]
+        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
+
+class Wave:
+    """
+    one wave with hp scaled by factor f (whole numbers, at least 1).
+    kinds: list of (count, hp, speed, coins, boss).
+    """
+
+    def __init__(self, cfg, monsters, f, interval):
+        mons = cfg["monster"]
+        self.kinds = [(n, max(1, round(mons[k]["hp"] * f)), 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
+
+
+# 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):
+    c = cfg["map"][str(m)]
+    interval = c.get("spawn_interval", cfg["waves"]["spawn_interval"])
+    return [Wave(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 factor_for_target(scan):
+    """smallest hp factor at which naive keeps HEARTS_TARGET hearts or fewer."""
+    for s in scan:
+        if hearts_lost(s["naive"]) >= HEARTS_TARGET:
+            return s["f"]
+    return None
+
+
+# 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 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, hp 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 = factor_for_target(a["scan"])
+    fmt = lambda v: "-" if v is None else f"{v:.0f}"
+    lines += ["", f"hp factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts, surplus at the last wave"
+              f" {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f},"
+              f" surplus {fmt(surplus(one['greedy']))}",
+              f"hp factor at which naive is down to {HEARTS_TARGET} hearts: "
+              + ("beyond the scan" if target is None else f"{target:.2f}"), ""]
+    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, hp 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", "hp 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", "hp 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 main():
+    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)
+    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")
+    for m in range(MAPS):
+        a = analyse_map(cfg, towers, maps[m], m)
+        report = map_report(cfg, a)
+        lines += report
+        print("\n".join(report[-3:-1]).replace("hp factor 1", f"map{m}, hp factor 1"))
+        map_chart(a, PREVIEW / f"balance_map{m}.png")
+    (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())
--- a/tools/build.py	Tue Oct 20 00:44:02 2026 +0200
+++ b/tools/build.py	Tue Oct 20 03:08:56 2026 +0200
@@ -46,7 +46,8 @@
 # route data of the last mask step, read when the step is skipped
 MAPS_CACHE = TEMP / "build" / "maps.json"
 
-TOOLS = sorted((ROOT / "tools").glob("*.py"))
+# build scripts; tools/balance.py only reads the build's output
+TOOLS = sorted(p for p in (ROOT / "tools").glob("*.py") if p.name != "balance.py")
 HEADER = "// generated by tools/build.py from {src}, do not edit\n"
 
 SPRITES = (["m%d" % i for i in range(5)] + ["b%d" % i for i in range(4)]