diff tools/balance.py @ 23:2f555a54c332

layout fixes and balancing
author ark
date 2026-10-20 12:04 +0200
parents ad1b478fc4dc
children a464bd43b76c
line wrap: on
line diff
--- a/tools/balance.py	Tue Oct 20 03:08:56 2026 +0200
+++ b/tools/balance.py	Tue Oct 20 12:04:42 2026 +0200
@@ -6,6 +6,7 @@
 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
@@ -13,6 +14,12 @@
 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.
 """
 
@@ -38,8 +45,8 @@
 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)
+# 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
 
@@ -69,8 +76,7 @@
 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.
+    the boss route is the shortest one.
     """
 
     def __init__(self, mp):
@@ -78,7 +84,7 @@
         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]
+        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]
@@ -125,15 +131,27 @@
 
 # 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 with hp scaled by factor f (whole numbers, at least 1).
-    kinds: list of (count, hp, speed, coins, boss).
+    one wave. kinds: list of (count, hp, speed, coins, boss).
     """
 
-    def __init__(self, cfg, monsters, f, interval):
+    def __init__(self, cfg, monsters, interval):
         mons = cfg["monster"]
-        self.kinds = [(n, max(1, round(mons[k]["hp"] * f)), mons[k]["speed"], mons[k]["coins"],
+        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)
@@ -287,6 +305,77 @@
     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):
@@ -296,9 +385,10 @@
 
 
 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, w["monsters"], f, interval) for w in c["wave"]]
+    return [Wave(cfg, scale_counts(cfg, w["monsters"], f), interval) for w in c["wave"]]
 
 
 def bonuses(cfg, m):
@@ -350,12 +440,21 @@
     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
+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
@@ -380,6 +479,49 @@
     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"]
@@ -393,11 +535,12 @@
         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.", "",
+              "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"]))
@@ -413,13 +556,13 @@
                      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"])
+    target = factors_at_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},"
+    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"hp factor at which naive is down to {HEARTS_TARGET} hearts: "
-              + ("beyond the scan" if target is None else f"{target:.2f}"), ""]
+              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
 
 
@@ -452,7 +595,7 @@
     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")
+    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")
@@ -461,14 +604,14 @@
 
     f = [s["f"] for s in a["scan"]]
     ax = axes[1]
-    style(ax, "surplus at the last wave", "hp factor", "coins")
+    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", "hp factor", "hearts")
+    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)
@@ -496,22 +639,44 @@
     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("hp factor 1", f"map{m}, hp factor 1"))
+        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