comparison tools/balance.py @ 36:a464bd43b76c 1.0.0

clean documentation rewrite
author ark
date 2026-10-21 22:34 +0200
parents 2f555a54c332
children
comparison
equal deleted inserted replaced
35:0d40f346059c 36:a464bd43b76c
1 #!/usr/bin/env python3 1 #!/usr/bin/env python3
2 """ 2 """
3 estimate, map by map and wave by wave, whether the coins a map pays buy 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 4 enough firepower (doc/balancing.md). reads config/game.toml and the
5 routes and placement grid of the last build, temp/build/maps.json. writes 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. 6 temp/preview/balance.txt and the charts temp/preview/balance_*.png.
7 7
8 usage: python3 tools/balance.py 8 usage: python3 tools/balance.py
9 python3 tools/balance.py --draft [MAP] 9 python3 tools/balance.py --draft [MAP]
161 self.speed = sum(k[0] * k[2] for k in reg) / self.count 161 self.speed = sum(k[0] * k[2] for k in reg) / self.count
162 # time from the first spawn to the last, and the spacing on the route 162 # time from the first spawn to the last, and the spacing on the route
163 self.duration = (self.count - 1) * interval 163 self.duration = (self.count - 1) * interval
164 self.spacing = self.speed * interval 164 self.spacing = self.speed * interval
165 self.tough = max(reg, key=lambda k: k[1]) 165 self.tough = max(reg, key=lambda k: k[1])
166 # heart cost of a regular monster and of the boss getting through
167 self.heart_cost = (cfg["hearts"]["monster"], cfg["hearts"]["boss"])
166 self.reg = reg 168 self.reg = reg
167 169
168 def shots(self, damage): 170 def shots(self, damage):
169 """shots that kill every regular monster of the wave, whole shots each.""" 171 """shots that kill every regular monster of the wave, whole shots each."""
170 return sum(n * math.ceil(hp / damage) for n, hp, _, _, _ in self.reg) 172 return sum(n * math.ceil(hp / damage) for n, hp, _, _, _ in self.reg)
191 if wave.boss: 193 if wave.boss:
192 boss += bcov / wave.boss[2] / attack_time * dmg 194 boss += bcov / wave.boss[2] / attack_time * dmg
193 leak = max(0.0, wave.hp - cap) 195 leak = max(0.0, wave.hp - cap)
194 killed = 1 - leak / wave.hp 196 killed = 1 - leak / wave.hp
195 out = {"leak": leak, "tough": tough, "boss": boss} 197 out = {"leak": leak, "tough": tough, "boss": boss}
196 out["hearts"] = leak / (wave.hp / wave.count) 198 out["hearts"] = leak / (wave.hp / wave.count) * wave.heart_cost[0]
197 out["coins"] = wave.coins * killed 199 out["coins"] = wave.coins * killed
198 boss_ok = True 200 boss_ok = True
199 if wave.boss: 201 if wave.boss:
200 boss_ok = boss >= wave.boss[1] 202 boss_ok = boss >= wave.boss[1]
201 if boss_ok: 203 if boss_ok:
202 out["coins"] += wave.boss[3] 204 out["coins"] += wave.boss[3]
203 else: 205 else:
204 out["hearts"] += 5 206 out["hearts"] += wave.heart_cost[1]
205 out["holds"] = leak < 1e-9 and boss_ok 207 out["holds"] = leak < 1e-9 and boss_ok
206 return out 208 return out
207 209
208 210
209 # players 211 # players
347 waves = [{k: int(v) for k, v in zip(regular, row) if v} for row in counts] 349 waves = [{k: int(v) for k, v in zip(regular, row) if v} for row in counts]
348 waves[-1][f"b{m}"] = 1 350 waves[-1][f"b{m}"] = 1
349 return waves 351 return waves
350 352
351 353
352 def draft_toml(cfg, m, waves): 354 def draft_toml(m, waves):
353 """the drafted waves as toml lines, each wave with its count, hp and coins.""" 355 """the drafted waves as toml lines, each wave marked with its number."""
354 c = cfg["map"][str(m)] 356 lines = [f"# map{m} waves", ""]
355 mons = cfg["monster"]
356 lines = [f"# map{m}: drafted by tools/balance.py --draft from wave_count {c['wave_count']},"
357 f" wave_size {c['wave_size']},",
358 f"# monster_share {c['monster_share']}, first_wave {c['first_wave']}", ""]
359 for w, wave in enumerate(waves, start=1): 357 for w, wave in enumerate(waves, start=1):
360 reg = {k: v for k, v in wave.items() if not mons[k].get("boss")} 358 lines += [f"[[map.{m}.wave]] # wave {w}",
361 boss = [k for k in wave if mons[k].get("boss")]
362 hp = sum(v * mons[k]["hp"] for k, v in reg.items())
363 coins = sum(v * mons[k]["coins"] for k, v in reg.items())
364 extra = "".join(f" + boss {mons[k]['coins']}" for k in boss)
365 lines += [f"[[map.{m}.wave]] # wave {w}, {sum(reg.values())} monsters, {hp} hp,"
366 f" {coins} coins{extra}",
367 "monsters = { " + ", ".join(f"{k} = {v}" for k, v in wave.items()) + " }", ""] 359 "monsters = { " + ", ".join(f"{k} = {v}" for k, v in wave.items()) + " }", ""]
368 return lines 360 return lines
369 361
370 362
371 def draft_check(cfg, waves): 363 def draft_check(cfg, waves):
418 scan = [] 410 scan = []
419 for f in FACTORS: 411 for f in FACTORS:
420 waves = map_waves(cfg, m, f) 412 waves = map_waves(cfg, m, f)
421 n, g = play(naive, waves, start, bon, at), play(greedy, waves, start, bon, at) 413 n, g = play(naive, waves, start, bon, at), play(greedy, waves, start, bon, at)
422 scan.append({"f": f, "naive": n, "greedy": g}) 414 scan.append({"f": f, "naive": n, "greedy": g})
423 out = {"m": m, "cov": cov, "bcov": bcov, "cells": cells, "routes": len(mc.routes), 415 out = {"m": m, "hearts": cfg["hearts"]["per_map"], "cov": cov, "bcov": bcov, "cells": cells, "routes": len(mc.routes),
424 "lengths": mc.lengths, "spacing": spacing, "waves": waves1, "bonus": bon, 416 "lengths": mc.lengths, "spacing": spacing, "waves": waves1, "bonus": bon,
425 "naive": play(naive, waves1, start, bon, at), "greedy": play(greedy, waves1, start, bon, at), 417 "naive": play(naive, waves1, start, bon, at), "greedy": play(greedy, waves1, start, bon, at),
426 "scan": scan, "coverage": {}} 418 "scan": scan, "coverage": {}}
427 for tid, t in towers.items(): 419 for tid, t in towers.items():
428 tc, _ = mc.coverage(t["range"][0]) 420 tc, _ = mc.coverage(t["range"][0])
438 430
439 def hearts_lost(rows): 431 def hearts_lost(rows):
440 return sum(r["res"]["hearts"] for r in rows) 432 return sum(r["res"]["hearts"] for r in rows)
441 433
442 434
443 def factors_at_target(scan): 435 def factors_at_target(scan, per_map):
444 """ 436 """
445 the wave size factors at which naive ends with HEARTS_TARGET hearts or 437 the wave size factors at which naive ends with HEARTS_TARGET hearts or
446 fewer, as a list of (lowest, highest) ranges of neighbouring scan 438 fewer, of per_map, as a list of (lowest, highest) ranges of neighbouring scan
447 points. larger waves also pay more coins, so there may be several. 439 points. larger waves also pay more coins, so there may be several.
448 """ 440 """
449 out = [] 441 out = []
450 for i, s in enumerate(scan): 442 for i, s in enumerate(scan):
451 if hearts_lost(s["naive"]) < 10 - HEARTS_TARGET: 443 if hearts_lost(s["naive"]) < per_map - HEARTS_TARGET:
452 continue 444 continue
453 if out and out[-1][2] == i - 1: 445 if out and out[-1][2] == i - 1:
454 out[-1] = (out[-1][0], s["f"], i) 446 out[-1] = (out[-1][0], s["f"], i)
455 else: 447 else:
456 out.append((s["f"], s["f"], i)) 448 out.append((s["f"], s["f"], i))
460 # report 452 # report
461 453
462 def value_table(cfg, towers): 454 def value_table(cfg, towers):
463 regular = sorted(k for k, v in cfg["monster"].items() if not v.get("boss")) 455 regular = sorted(k for k, v in cfg["monster"].items() if not v.get("boss"))
464 lines = ["value per coin: hp killed per second per coin paid for the tower,", 456 lines = ["value per coin: hp killed per second per coin paid for the tower,",
465 "whole shots per monster. t0 counts one monster per attack.", ""] 457 "whole shots per monster. t0 counts one monster per attack. towers",
458 "that only slow are left out.", ""]
466 head = f"{'tower':6}{'level':>6}{'damage':>8}{'range':>7}{'paid':>6}{'dps':>7}{'dps/coin':>10}" 459 head = f"{'tower':6}{'level':>6}{'damage':>8}{'range':>7}{'paid':>6}{'dps':>7}{'dps/coin':>10}"
467 head += "".join(f"{'vs ' + k:>8}" for k in regular) 460 head += "".join(f"{'vs ' + k:>8}" for k in regular)
468 lines.append(head) 461 lines.append(head)
469 for tid, t in towers.items(): 462 for tid, t in towers.items():
463 if "damage" not in t:
464 continue
470 paid = 0 465 paid = 0
471 for lv in range(len(t["damage"])): 466 for lv in range(len(t["damage"])):
472 d, at = t["damage"][lv], t["attack_time"] 467 d, at = t["damage"][lv], t["attack_time"]
473 paid += t["cost"][lv] 468 paid += t["cost"][lv]
474 row = f"{tid:6}{lv + 1:>6}{d:>8g}{t['range'][lv]:>7g}{paid:>6}{d / at:>7.1f}{d / at / paid:>10.2f}" 469 row = f"{tid:6}{lv + 1:>6}{d:>8g}{t['range'][lv]:>7g}{paid:>6}{d / at:>7.1f}{d / at / paid:>10.2f}"
537 "the number one t0 attack damages in a full wave.", "", 532 "the number one t0 attack damages in a full wave.", "",
538 "waves, t1 only, wave size factor 1. need/s: hp per second the towers", 533 "waves, t1 only, wave size factor 1. need/s: hp per second the towers",
539 "have to kill (throughput, median cell). single: damage the toughest", 534 "have to kill (throughput, median cell). single: damage the toughest",
540 "monster takes from the naive towers while in range, against its hp.", 535 "monster takes from the naive towers while in range, against its hp.",
541 "budget: coins on hand plus coins spent. need: coins of the purchases", 536 "budget: coins on hand plus coins spent. need: coins of the purchases",
542 "that hold the wave. lost: hearts lost, leaks by throughput plus 5 for", 537 "that hold the wave. lost: hearts lost, leaks by throughput plus the",
543 "a boss.", "", 538 "boss's heart cost if it gets through.", "",
544 f"{'wave':>4}{'count':>6}{'hp':>6}{'coins':>6}{'need/s':>8}{'single':>12}" 539 f"{'wave':>4}{'count':>6}{'hp':>6}{'coins':>6}{'need/s':>8}{'single':>12}"
545 f" naive{'budget':>8}{'need':>6}{'lost':>6} greedy{'budget':>8}{'need':>6}{'lost':>6}"] 540 f" naive{'budget':>8}{'need':>6}{'lost':>6} greedy{'budget':>8}{'need':>6}{'lost':>6}"]
546 med = float(np.median(a["cov"])) 541 med = float(np.median(a["cov"]))
547 for w, (wave, n, g) in enumerate(zip(a["waves"], a["naive"], a["greedy"]), start=1): 542 for w, (wave, n, g) in enumerate(zip(a["waves"], a["naive"], a["greedy"]), start=1):
548 rate = wave.hp / (wave.duration + med / wave.speed) 543 rate = wave.hp / (wave.duration + med / wave.speed)
554 need = lambda r: "-" if r["need"] is None else str(r["need"]) 549 need = lambda r: "-" if r["need"] is None else str(r["need"])
555 lines.append(f"{w:>4}{wave.count:>6}{wave.hp:>6}{coins:>6}{rate:>8.1f}{single:>12}" 550 lines.append(f"{w:>4}{wave.count:>6}{wave.hp:>6}{coins:>6}{rate:>8.1f}{single:>12}"
556 f" {n['budget']:>8.0f}{need(n):>6}{n['res']['hearts']:>6.1f}" 551 f" {n['budget']:>8.0f}{need(n):>6}{n['res']['hearts']:>6.1f}"
557 f" {g['budget']:>8.0f}{need(g):>6}{g['res']['hearts']:>6.1f}") 552 f" {g['budget']:>8.0f}{need(g):>6}{g['res']['hearts']:>6.1f}")
558 one = next(s for s in a["scan"] if s["f"] == 1.0) 553 one = next(s for s in a["scan"] if s["f"] == 1.0)
559 target = factors_at_target(a["scan"]) 554 target = factors_at_target(a["scan"], a["hearts"])
560 fmt = lambda v: "-" if v is None else f"{v:.0f}" 555 fmt = lambda v: "-" if v is None else f"{v:.0f}"
561 lines += ["", f"wave size factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts," 556 lines += ["", f"wave size factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts,"
562 f" surplus at the last wave {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f}," 557 f" surplus at the last wave {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f},"
563 f" surplus {fmt(surplus(one['greedy']))}", 558 f" surplus {fmt(surplus(one['greedy']))}",
564 f"wave size factors at which naive ends with {HEARTS_TARGET} hearts or fewer: " 559 f"wave size factors at which naive ends with {HEARTS_TARGET} hearts or fewer: "
612 607
613 ax = axes[2] 608 ax = axes[2]
614 style(ax, "hearts left at the end", "wave size factor", "hearts") 609 style(ax, "hearts left at the end", "wave size factor", "hearts")
615 ax.axhline(HEARTS_TARGET, color=INK2, linewidth=1, linestyle="--") 610 ax.axhline(HEARTS_TARGET, color=INK2, linewidth=1, linestyle="--")
616 ax.text(f[-1], HEARTS_TARGET + 0.2, "target, naive", color=INK2, fontsize=8, ha="right") 611 ax.text(f[-1], HEARTS_TARGET + 0.2, "target, naive", color=INK2, fontsize=8, ha="right")
617 line(ax, f, [max(0, 10 - hearts_lost(s["naive"])) for s in a["scan"]], 1, "naive", markevery=10) 612 h = a["hearts"]
618 line(ax, f, [max(0, 10 - hearts_lost(s["greedy"])) for s in a["scan"]], 2, "greedy", markevery=10) 613 line(ax, f, [max(0, h - hearts_lost(s["naive"])) for s in a["scan"]], 1, "naive", markevery=10)
619 ax.set_ylim(-0.3, 10.5) 614 line(ax, f, [max(0, h - hearts_lost(s["greedy"])) for s in a["scan"]], 2, "greedy", markevery=10)
615 ax.set_ylim(-0.03 * h, 1.05 * h)
620 legend(ax) 616 legend(ax)
621 fig.tight_layout() 617 fig.tight_layout()
622 fig.savefig(path, dpi=110, facecolor=SURFACE) 618 fig.savefig(path, dpi=110, facecolor=SURFACE)
623 plt.close(fig) 619 plt.close(fig)
624 620
627 fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), facecolor=SURFACE) 623 fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), facecolor=SURFACE)
628 for ax, mon in zip(axes, ("m0", "m4")): 624 for ax, mon in zip(axes, ("m0", "m4")):
629 hp = cfg["monster"][mon]["hp"] 625 hp = cfg["monster"][mon]["hp"]
630 style(ax, f"hp per second per coin against {mon} ({hp} hp)", "tower level", "hp/s per coin") 626 style(ax, f"hp per second per coin against {mon} ({hp} hp)", "tower level", "hp/s per coin")
631 for slot, (tid, t) in enumerate(towers.items()): 627 for slot, (tid, t) in enumerate(towers.items()):
628 if "damage" not in t:
629 continue
632 paid = np.cumsum(t["cost"]) 630 paid = np.cumsum(t["cost"])
633 v = [hp / (math.ceil(hp / d) * t["attack_time"]) / p for d, p in zip(t["damage"], paid)] 631 v = [hp / (math.ceil(hp / d) * t["attack_time"]) / p for d, p in zip(t["damage"], paid)]
634 line(ax, range(1, len(v) + 1), v, slot, tid) 632 line(ax, range(1, len(v) + 1), v, slot, tid)
635 ax.set_xticks(range(1, 6)) 633 ax.set_xticks(range(1, 6))
636 legend(ax) 634 legend(ax)
641 639
642 def draft(cfg, towers, maps, only): 640 def draft(cfg, towers, maps, only):
643 """print drafted wave lists as toml and what the calculation makes of them.""" 641 """print drafted wave lists as toml and what the calculation makes of them."""
644 for m in range(MAPS) if only is None else [only]: 642 for m in range(MAPS) if only is None else [only]:
645 waves = draft_waves(cfg, m) 643 waves = draft_waves(cfg, m)
646 print("\n".join(draft_toml(cfg, m, waves))) 644 print("\n".join(draft_toml(m, waves)))
647 for msg in draft_check(cfg, waves): 645 for msg in draft_check(cfg, waves):
648 print(f"# warning: {msg}") 646 print(f"# warning: {msg}")
649 cfg["map"][str(m)]["wave"] = [{"monsters": w} for w in waves] 647 cfg["map"][str(m)]["wave"] = [{"monsters": w} for w in waves]
650 report = map_report(cfg, analyse_map(cfg, towers, maps[m], m)) 648 report = map_report(cfg, analyse_map(cfg, towers, maps[m], m))
651 print("\n".join("# " + l for l in report[-3:-1]), end="\n\n") 649 print("\n".join("# " + l for l in report[-3:-1]), end="\n\n")