comparison tools/balance.py @ 22:ad1b478fc4dc

balancing work, docs and scripts
author ark
date 2026-10-20 03:08 +0200
parents
children 2f555a54c332
comparison
equal deleted inserted replaced
21:fa04481563b7 22:ad1b478fc4dc
1 #!/usr/bin/env python3
2 """
3 estimate, map by map and wave by wave, whether the coins a map pays buy
4 enough firepower (doc/balance.md, balancing). reads config/game.toml and the
5 routes and placement grid of the last build, temp/build/maps.json. writes
6 temp/preview/balance.txt and the charts temp/preview/balance_*.png.
7
8 usage: python3 tools/balance.py
9
10 towers are t1 only for the wave demands. two players: naive builds level 1
11 towers on cells of median coverage whenever it can afford one; greedy picks
12 cells by coverage of route not yet covered and upgrades when that buys more
13 damage per coin than a new tower. greedy also starts every wave early for
14 the bonus.
15
16 requires python 3.11 or later, numpy and matplotlib.
17 """
18
19 import math
20 import sys
21 import tomllib
22 import json
23
24 import numpy as np
25
26 # keep tools/ free of __pycache__
27 sys.dont_write_bytecode = True
28
29 import matplotlib
30 matplotlib.use("Agg")
31 import matplotlib.pyplot as plt
32
33 from build import CONFIG, MAPS, MAPS_CACHE, PREVIEW, TOWER_BY_LEVEL, tower_levels
34
35 # distance between route samples for coverage
36 SAMPLE_STEP = 4
37 # greedy cells listed per map, more than any budget buys
38 GREEDY_CELLS = 120
39 # the tower the wave demands are measured against
40 TOWER = "t1"
41 # hp factors scanned for the margin charts
42 FACTORS = np.round(np.arange(0.5, 6.001, 0.05), 2)
43 # hearts the naive player should have left at the end of a map (decided)
44 HEARTS_TARGET = 5
45
46 # chart colours: surface, text, grid, then series slots in fixed order
47 SURFACE = "#fcfcfb"
48 INK = "#0b0b0b"
49 INK2 = "#52514e"
50 GRID = "#e4e3de"
51 SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#6250d6"]
52
53
54 # coverage
55
56 def resample(points, step):
57 """
58 sample a route at about step apart. returns (samples, weight): an n x 2
59 array of positions in the middle of equal pieces, and the length of a
60 piece.
61 """
62 p = np.asarray(points, float)
63 cum = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(p, axis=0).T))])
64 n = max(1, math.ceil(cum[-1] / step))
65 pos = (np.arange(n) + 0.5) * cum[-1] / n
66 return np.column_stack([np.interp(pos, cum, p[:, 0]), np.interp(pos, cum, p[:, 1])]), cum[-1] / n
67
68
69 class MapCoverage:
70 """
71 legal placement cells of a map and the route samples each can reach.
72 routes with a fixed weight of 0 are left out; the boss route is the
73 shortest one.
74 """
75
76 def __init__(self, mp):
77 cell, cols = mp["cell"], mp["cols"]
78 idx = np.array([i for i, c in enumerate(mp["grid"]) if c == "1"])
79 self.cells = np.column_stack([(idx % cols) * cell + cell // 2,
80 (idx // cols) * cell + cell // 2]).astype(float)
81 routes = [r for r in mp["routes"] if r["weight"] != 0]
82 self.routes = [resample(r["points"], SAMPLE_STEP) for r in routes]
83 self.boss_route = min(range(len(routes)), key=lambda i: routes[i]["length"])
84 self.lengths = [r["length"] for r in routes]
85
86 def within(self, rng):
87 """per route, a cells x samples array: sample in range of the cell."""
88 out = []
89 for samples, _ in self.routes:
90 d2 = ((self.cells[:, None, :] - samples[None, :, :]) ** 2).sum(axis=2)
91 out.append(d2 <= rng * rng)
92 return out
93
94 def coverage(self, rng):
95 """per cell: (mean route length in range over routes, on the boss route)."""
96 per_route = np.array([w.sum(axis=1) * wt for w, (_, wt) in zip(self.within(rng), self.routes)])
97 return per_route.mean(axis=0), per_route[self.boss_route]
98
99 def greedy(self, rng, count, min_dist):
100 """
101 up to count cells, picked one after the other by the route length in
102 range that no earlier pick covers, mean over routes. picks keep
103 min_dist from each other. once all route is covered, the cell with
104 the most route in range is next. returns cell indices.
105 """
106 within = self.within(rng)
107 weights = [wt for _, wt in self.routes]
108 full = sum(w.sum(axis=1) * wt for w, wt in zip(within, weights)) / len(within)
109 covered = [np.zeros(w.shape[1], bool) for w in within]
110 free = np.ones(len(self.cells), bool)
111 order = []
112 for _ in range(count):
113 if not free.any():
114 break
115 gain = sum(w[:, ~c].sum(axis=1) * wt for w, c, wt in zip(within, covered, weights)) / len(within)
116 if gain[free].max() <= 0:
117 gain = full
118 i = int(np.flatnonzero(free)[np.argmax(gain[free])])
119 order.append(i)
120 for w, c in zip(within, covered):
121 c |= w[i]
122 free &= np.hypot(*(self.cells - self.cells[i]).T) >= min_dist
123 return order
124
125
126 # waves
127
128 class Wave:
129 """
130 one wave with hp scaled by factor f (whole numbers, at least 1).
131 kinds: list of (count, hp, speed, coins, boss).
132 """
133
134 def __init__(self, cfg, monsters, f, interval):
135 mons = cfg["monster"]
136 self.kinds = [(n, max(1, round(mons[k]["hp"] * f)), mons[k]["speed"], mons[k]["coins"],
137 bool(mons[k].get("boss"))) for k, n in monsters.items() if n]
138 reg = [k for k in self.kinds if not k[4]]
139 self.boss = next((k for k in self.kinds if k[4]), None)
140 self.count = sum(k[0] for k in reg)
141 self.hp = sum(k[0] * k[1] for k in reg)
142 self.coins = sum(k[0] * k[3] for k in reg)
143 self.speed = sum(k[0] * k[2] for k in reg) / self.count
144 # time from the first spawn to the last, and the spacing on the route
145 self.duration = (self.count - 1) * interval
146 self.spacing = self.speed * interval
147 self.tough = max(reg, key=lambda k: k[1])
148 self.reg = reg
149
150 def shots(self, damage):
151 """shots that kill every regular monster of the wave, whole shots each."""
152 return sum(n * math.ceil(hp / damage) for n, hp, _, _, _ in self.reg)
153
154
155 def result(towers, wave, attack_time):
156 """
157 what towers do against a wave. towers: list of (coverage, boss route
158 coverage, damage). throughput: each tower attacks from the first monster
159 reaching it until the last has passed, while a monster is in range,
160 with whole shots per monster. single target: the monster gets every
161 tower's full attention while in range. returns a dict with leak (regular
162 hp not killed), hearts, coins earned, holds, and the single target
163 damage on the boss and on the toughest regular monster.
164 """
165 cap = 0.0
166 tough = 0.0
167 boss = 0.0
168 for cov, bcov, dmg in towers:
169 busy = 1 - math.exp(-cov / wave.spacing)
170 window = wave.duration + cov / wave.speed
171 cap += window / attack_time * busy * wave.hp / wave.shots(dmg)
172 tough += cov / wave.tough[2] / attack_time * dmg
173 if wave.boss:
174 boss += bcov / wave.boss[2] / attack_time * dmg
175 leak = max(0.0, wave.hp - cap)
176 killed = 1 - leak / wave.hp
177 out = {"leak": leak, "tough": tough, "boss": boss}
178 out["hearts"] = leak / (wave.hp / wave.count)
179 out["coins"] = wave.coins * killed
180 boss_ok = True
181 if wave.boss:
182 boss_ok = boss >= wave.boss[1]
183 if boss_ok:
184 out["coins"] += wave.boss[3]
185 else:
186 out["hearts"] += 5
187 out["holds"] = leak < 1e-9 and boss_ok
188 return out
189
190
191 # players
192
193 class Player:
194 """
195 a fixed order of purchases. states[k] is the list of towers after the
196 first k purchases, cost[k] what they cost in all.
197 """
198
199 def holds_from(self, wave, attack_time):
200 """smallest k whose towers hold the wave, None if none does."""
201 lo, hi = 0, len(self.states) - 1
202 if not result(self.states[hi], wave, attack_time)["holds"]:
203 return None
204 while lo < hi:
205 mid = (lo + hi) // 2
206 if result(self.states[mid], wave, attack_time)["holds"]:
207 hi = mid
208 else:
209 lo = mid + 1
210 return lo
211
212
213 class Naive(Player):
214 def __init__(self, tower, cov, bcov, budget):
215 n = budget // tower["cost"][0] + 1
216 self.states = [[(cov, bcov, tower["damage"][0])] * k for k in range(n)]
217 self.cost = [k * tower["cost"][0] for k in range(n)]
218 self.bonus = False
219
220
221 class Greedy(Player):
222 """
223 each purchase is a new level 1 tower on the next greedy cell or an
224 upgrade, whichever adds more damage per second per coin. damage per
225 second counts while a monster is in range, at spacing s.
226 """
227
228 def __init__(self, tower, cells, cov, bcov, budget, spacing):
229 at = tower["attack_time"]
230 dmg, cost = tower["damage"], tower["cost"]
231
232 def busy(i):
233 return 1 - math.exp(-cov[i] / spacing)
234
235 levels = [] # (cell, level) per tower
236 nxt = 0
237 total = 0
238 self.states = [[]]
239 self.cost = [0]
240 while True:
241 best, choice = 0.0, None
242 if nxt < len(cells):
243 best, choice = dmg[0] / at * busy(cells[nxt]) / cost[0], ("new", None)
244 for t, (c, lv) in enumerate(levels):
245 if lv < len(dmg):
246 v = (dmg[lv] - dmg[lv - 1]) / at * busy(c) / cost[lv]
247 if v > best:
248 best, choice = v, ("up", t)
249 if choice is None:
250 break
251 if choice[0] == "new":
252 price = cost[0]
253 levels.append((cells[nxt], 1))
254 nxt += 1
255 else:
256 c, lv = levels[choice[1]]
257 price = cost[lv]
258 levels[choice[1]] = (c, lv + 1)
259 total += price
260 if total > budget:
261 break
262 self.states.append([(cov[c], bcov[c], dmg[lv - 1]) for c, lv in levels])
263 self.cost.append(total)
264 self.bonus = True
265
266
267 def play(player, waves, start, bonuses, attack_time):
268 """
269 play a map: at each wave start buy what the coins allow, in the
270 player's order. returns one row per wave: budget (coins on hand plus
271 coins spent so far), coins left after buying, towers bought, coins the
272 wave needs (None: more than the purchase list holds), hearts lost, and
273 the result.
274 """
275 coins, k, rows = start, 0, []
276 for w, wave in enumerate(waves):
277 if player.bonus:
278 coins += bonuses[w]
279 while k + 1 < len(player.states) and player.cost[k + 1] - player.cost[k] <= coins:
280 coins -= player.cost[k + 1] - player.cost[k]
281 k += 1
282 res = result(player.states[k], wave, attack_time)
283 need = player.holds_from(wave, attack_time)
284 rows.append({"budget": coins + player.cost[k], "left": coins, "towers": len(player.states[k]),
285 "need": None if need is None else player.cost[need], "res": res})
286 coins += res["coins"]
287 return rows
288
289
290 # calculation
291
292 def tower_table(cfg):
293 """tower id -> config with the by-level values filled in."""
294 return {tid: {k: tower_levels(v) if k in TOWER_BY_LEVEL else v for k, v in tw.items()}
295 for tid, tw in cfg["tower"].items()}
296
297
298 def map_waves(cfg, m, f):
299 c = cfg["map"][str(m)]
300 interval = c.get("spawn_interval", cfg["waves"]["spawn_interval"])
301 return [Wave(cfg, w["monsters"], f, interval) for w in c["wave"]]
302
303
304 def bonuses(cfg, m):
305 """early start bonus for skipping the break before each wave."""
306 c = cfg["map"][str(m)]
307 n = len(c["wave"])
308 return [math.floor(c["early_bonus"] * (cfg["waves"]["first_break"] if w == 0 else cfg["waves"]["break"]))
309 for w in range(n)]
310
311
312 def analyse_map(cfg, towers, mp, m):
313 """everything the report and charts show for map m."""
314 c = cfg["map"][str(m)]
315 tw = towers[TOWER]
316 mc = MapCoverage(mp)
317 cov, bcov = mc.coverage(tw["range"][0])
318 cells = mc.greedy(tw["range"][0], GREEDY_CELLS, cfg["placement"]["min_tower_distance"])
319 waves1 = map_waves(cfg, m, 1.0)
320 # budget large enough for every factor scanned
321 budget = (c["starting_coins"] + sum(w.coins + (w.boss[3] if w.boss else 0) for w in waves1)
322 + sum(bonuses(cfg, m))) * 3
323 spacing = sum(w.spacing * w.count for w in waves1) / sum(w.count for w in waves1)
324 naive = Naive(tw, float(np.median(cov)), float(np.median(bcov)), budget)
325 greedy = Greedy(tw, cells, cov, bcov, budget, spacing)
326 at, start, bon = tw["attack_time"], c["starting_coins"], bonuses(cfg, m)
327
328 scan = []
329 for f in FACTORS:
330 waves = map_waves(cfg, m, f)
331 n, g = play(naive, waves, start, bon, at), play(greedy, waves, start, bon, at)
332 scan.append({"f": f, "naive": n, "greedy": g})
333 out = {"m": m, "cov": cov, "bcov": bcov, "cells": cells, "routes": len(mc.routes),
334 "lengths": mc.lengths, "spacing": spacing, "waves": waves1, "bonus": bon,
335 "naive": play(naive, waves1, start, bon, at), "greedy": play(greedy, waves1, start, bon, at),
336 "scan": scan, "coverage": {}}
337 for tid, t in towers.items():
338 tc, _ = mc.coverage(t["range"][0])
339 out["coverage"][tid] = (float(np.median(tc)), float(np.percentile(tc, 90)), float(tc.max()))
340 return out
341
342
343 def surplus(rows):
344 """coins on hand at the start of the last wave beyond what it needs."""
345 last = rows[-1]
346 return None if last["need"] is None else last["budget"] - last["need"]
347
348
349 def hearts_lost(rows):
350 return sum(r["res"]["hearts"] for r in rows)
351
352
353 def factor_for_target(scan):
354 """smallest hp factor at which naive keeps HEARTS_TARGET hearts or fewer."""
355 for s in scan:
356 if hearts_lost(s["naive"]) >= HEARTS_TARGET:
357 return s["f"]
358 return None
359
360
361 # report
362
363 def value_table(cfg, towers):
364 regular = sorted(k for k, v in cfg["monster"].items() if not v.get("boss"))
365 lines = ["value per coin: hp killed per second per coin paid for the tower,",
366 "whole shots per monster. t0 counts one monster per attack.", ""]
367 head = f"{'tower':6}{'level':>6}{'damage':>8}{'range':>7}{'paid':>6}{'dps':>7}{'dps/coin':>10}"
368 head += "".join(f"{'vs ' + k:>8}" for k in regular)
369 lines.append(head)
370 for tid, t in towers.items():
371 paid = 0
372 for lv in range(len(t["damage"])):
373 d, at = t["damage"][lv], t["attack_time"]
374 paid += t["cost"][lv]
375 row = f"{tid:6}{lv + 1:>6}{d:>8g}{t['range'][lv]:>7g}{paid:>6}{d / at:>7.1f}{d / at / paid:>10.2f}"
376 for k in regular:
377 hp = cfg["monster"][k]["hp"]
378 row += f"{hp / (math.ceil(hp / d) * at) / paid:>8.2f}"
379 lines.append(row)
380 return lines
381
382
383 def map_report(cfg, a):
384 m, c = a["m"], cfg["map"][str(a["m"])]
385 lens = a["lengths"]
386 lines = [f"map{m}", "----", "",
387 f"{a['routes']} route(s), length {min(lens):.0f}" + (f" to {max(lens):.0f}" if len(lens) > 1 else "")
388 + f"; spacing between monsters {a['spacing']:.0f}; starting coins {c['starting_coins']}", "",
389 "coverage by level 1 range, route length in range per legal cell:", "",
390 f"{'tower':6}{'median':>8}{'top10%':>8}{'best':>8}{'t0 hits':>9}"]
391 for tid, (med, top, best) in a["coverage"].items():
392 hits = f"{med / a['spacing']:>9.1f}" if tid == "t0" else ""
393 lines.append(f"{tid:6}{med:>8.0f}{top:>8.0f}{best:>8.0f}{hits}")
394 lines += ["", "t0 hits: monsters in range of a median t0 cell at the mean spacing,",
395 "the number one t0 attack damages in a full wave.", "",
396 "waves, t1 only, hp factor 1. need/s: hp per second the towers have to",
397 "kill (throughput, median cell). single: damage the toughest monster",
398 "takes from the naive towers while in range, against its hp. budget:",
399 "coins on hand plus coins spent. need: coins of the purchases that hold",
400 "the wave. lost: hearts lost, leaks by throughput plus 5 for a boss.", "",
401 f"{'wave':>4}{'count':>6}{'hp':>6}{'coins':>6}{'need/s':>8}{'single':>12}"
402 f" naive{'budget':>8}{'need':>6}{'lost':>6} greedy{'budget':>8}{'need':>6}{'lost':>6}"]
403 med = float(np.median(a["cov"]))
404 for w, (wave, n, g) in enumerate(zip(a["waves"], a["naive"], a["greedy"]), start=1):
405 rate = wave.hp / (wave.duration + med / wave.speed)
406 if wave.boss:
407 single = f"{n['res']['boss']:.0f}/{wave.boss[1]}b"
408 else:
409 single = f"{n['res']['tough']:.0f}/{wave.tough[1]}"
410 coins = wave.coins + (wave.boss[3] if wave.boss else 0)
411 need = lambda r: "-" if r["need"] is None else str(r["need"])
412 lines.append(f"{w:>4}{wave.count:>6}{wave.hp:>6}{coins:>6}{rate:>8.1f}{single:>12}"
413 f" {n['budget']:>8.0f}{need(n):>6}{n['res']['hearts']:>6.1f}"
414 f" {g['budget']:>8.0f}{need(g):>6}{g['res']['hearts']:>6.1f}")
415 one = next(s for s in a["scan"] if s["f"] == 1.0)
416 target = factor_for_target(a["scan"])
417 fmt = lambda v: "-" if v is None else f"{v:.0f}"
418 lines += ["", f"hp factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts, surplus at the last wave"
419 f" {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f},"
420 f" surplus {fmt(surplus(one['greedy']))}",
421 f"hp factor at which naive is down to {HEARTS_TARGET} hearts: "
422 + ("beyond the scan" if target is None else f"{target:.2f}"), ""]
423 return lines
424
425
426 # charts
427
428 def style(ax, title, xlabel, ylabel):
429 ax.set_facecolor(SURFACE)
430 ax.set_title(title, color=INK, fontsize=11, loc="left")
431 ax.set_xlabel(xlabel, color=INK2, fontsize=9)
432 ax.set_ylabel(ylabel, color=INK2, fontsize=9)
433 ax.grid(True, color=GRID, linewidth=0.8)
434 ax.set_axisbelow(True)
435 for side in ("top", "right"):
436 ax.spines[side].set_visible(False)
437 for side in ("left", "bottom"):
438 ax.spines[side].set_color(INK2)
439 ax.tick_params(colors=INK2, labelsize=8)
440
441
442 def line(ax, x, y, slot, label, **kw):
443 ax.plot(x, y, color=SERIES[slot], linewidth=2, marker="o", markersize=5,
444 markeredgecolor=SURFACE, markeredgewidth=1, label=label, **kw)
445
446
447 def legend(ax):
448 ax.legend(frameon=False, fontsize=8, labelcolor=INK)
449
450
451 def map_chart(a, path):
452 fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), facecolor=SURFACE)
453 waves = range(1, len(a["waves"]) + 1)
454 ax = axes[0]
455 style(ax, f"map{a['m']}: coins per wave, hp factor 1", "wave", "coins")
456 line(ax, waves, [r["budget"] for r in a["naive"]], 0, "budget (naive)")
457 line(ax, waves, [r["need"] for r in a["naive"]], 1, "needed, naive")
458 line(ax, waves, [r["need"] for r in a["greedy"]], 2, "needed, greedy")
459 ax.set_xticks(list(waves))
460 legend(ax)
461
462 f = [s["f"] for s in a["scan"]]
463 ax = axes[1]
464 style(ax, "surplus at the last wave", "hp factor", "coins")
465 ax.axhline(0, color=INK2, linewidth=1)
466 line(ax, f, [surplus(s["naive"]) for s in a["scan"]], 1, "naive", markevery=10)
467 line(ax, f, [surplus(s["greedy"]) for s in a["scan"]], 2, "greedy", markevery=10)
468 legend(ax)
469
470 ax = axes[2]
471 style(ax, "hearts left at the end", "hp factor", "hearts")
472 ax.axhline(HEARTS_TARGET, color=INK2, linewidth=1, linestyle="--")
473 ax.text(f[-1], HEARTS_TARGET + 0.2, "target, naive", color=INK2, fontsize=8, ha="right")
474 line(ax, f, [max(0, 10 - hearts_lost(s["naive"])) for s in a["scan"]], 1, "naive", markevery=10)
475 line(ax, f, [max(0, 10 - hearts_lost(s["greedy"])) for s in a["scan"]], 2, "greedy", markevery=10)
476 ax.set_ylim(-0.3, 10.5)
477 legend(ax)
478 fig.tight_layout()
479 fig.savefig(path, dpi=110, facecolor=SURFACE)
480 plt.close(fig)
481
482
483 def value_chart(cfg, towers, path):
484 fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), facecolor=SURFACE)
485 for ax, mon in zip(axes, ("m0", "m4")):
486 hp = cfg["monster"][mon]["hp"]
487 style(ax, f"hp per second per coin against {mon} ({hp} hp)", "tower level", "hp/s per coin")
488 for slot, (tid, t) in enumerate(towers.items()):
489 paid = np.cumsum(t["cost"])
490 v = [hp / (math.ceil(hp / d) * t["attack_time"]) / p for d, p in zip(t["damage"], paid)]
491 line(ax, range(1, len(v) + 1), v, slot, tid)
492 ax.set_xticks(range(1, 6))
493 legend(ax)
494 fig.tight_layout()
495 fig.savefig(path, dpi=110, facecolor=SURFACE)
496 plt.close(fig)
497
498
499 def main():
500 cfg = tomllib.loads((CONFIG / "game.toml").read_text())
501 if not MAPS_CACHE.exists():
502 print("no route data: run tools/build.py first")
503 return 1
504 maps = json.loads(MAPS_CACHE.read_text())["maps"]
505 towers = tower_table(cfg)
506 PREVIEW.mkdir(parents=True, exist_ok=True)
507 lines = ["balance estimate, written by tools/balance.py", ""] + value_table(cfg, towers) + [""]
508 value_chart(cfg, towers, PREVIEW / "balance_value.png")
509 for m in range(MAPS):
510 a = analyse_map(cfg, towers, maps[m], m)
511 report = map_report(cfg, a)
512 lines += report
513 print("\n".join(report[-3:-1]).replace("hp factor 1", f"map{m}, hp factor 1"))
514 map_chart(a, PREVIEW / f"balance_map{m}.png")
515 (PREVIEW / "balance.txt").write_text("\n".join(lines))
516 print("balance: wrote temp/preview/balance.txt, balance_*.png")
517 return 0
518
519
520 if __name__ == "__main__":
521 sys.exit(main())