diff tools/balance.py @ 22:ad1b478fc4dc

balancing work, docs and scripts
author ark
date 2026-10-20 03:08 +0200
parents
children 2f555a54c332
line wrap: on
line diff
--- /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())