diff tools/balance.py @ 36:a464bd43b76c 1.0.0

clean documentation rewrite
author ark
date 2026-10-21 22:34 +0200
parents 2f555a54c332
children
line wrap: on
line diff
--- a/tools/balance.py	Tue Oct 20 19:54:56 2026 +0200
+++ b/tools/balance.py	Wed Oct 21 22:34:43 2026 +0200
@@ -1,7 +1,7 @@
 #!/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
+enough firepower (doc/balancing.md). 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.
 
@@ -163,6 +163,8 @@
         self.duration = (self.count - 1) * interval
         self.spacing = self.speed * interval
         self.tough = max(reg, key=lambda k: k[1])
+        # heart cost of a regular monster and of the boss getting through
+        self.heart_cost = (cfg["hearts"]["monster"], cfg["hearts"]["boss"])
         self.reg = reg
 
     def shots(self, damage):
@@ -193,7 +195,7 @@
     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["hearts"] = leak / (wave.hp / wave.count) * wave.heart_cost[0]
     out["coins"] = wave.coins * killed
     boss_ok = True
     if wave.boss:
@@ -201,7 +203,7 @@
         if boss_ok:
             out["coins"] += wave.boss[3]
         else:
-            out["hearts"] += 5
+            out["hearts"] += wave.heart_cost[1]
     out["holds"] = leak < 1e-9 and boss_ok
     return out
 
@@ -349,21 +351,11 @@
     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']}", ""]
+def draft_toml(m, waves):
+    """the drafted waves as toml lines, each wave marked with its number."""
+    lines = [f"# map{m} waves", ""]
     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}",
+        lines += [f"[[map.{m}.wave]]   # wave {w}",
                   "monsters = { " + ", ".join(f"{k} = {v}" for k, v in wave.items()) + " }", ""]
     return lines
 
@@ -420,7 +412,7 @@
         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),
+    out = {"m": m, "hearts": cfg["hearts"]["per_map"], "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": {}}
@@ -440,15 +432,15 @@
     return sum(r["res"]["hearts"] for r in rows)
 
 
-def factors_at_target(scan):
+def factors_at_target(scan, per_map):
     """
     the wave size factors at which naive ends with HEARTS_TARGET hearts or
-    fewer, as a list of (lowest, highest) ranges of neighbouring scan
+    fewer, of per_map, 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:
+        if hearts_lost(s["naive"]) < per_map - HEARTS_TARGET:
             continue
         if out and out[-1][2] == i - 1:
             out[-1] = (out[-1][0], s["f"], i)
@@ -462,11 +454,14 @@
 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.", ""]
+             "whole shots per monster. t0 counts one monster per attack. towers",
+             "that only slow are left out.", ""]
     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():
+        if "damage" not in t:
+            continue
         paid = 0
         for lv in range(len(t["damage"])):
             d, at = t["damage"][lv], t["attack_time"]
@@ -539,8 +534,8 @@
               "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.", "",
+              "that hold the wave. lost: hearts lost, leaks by throughput plus the",
+              "boss's heart cost if it gets through.", "",
               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"]))
@@ -556,7 +551,7 @@
                      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 = factors_at_target(a["scan"])
+    target = factors_at_target(a["scan"], a["hearts"])
     fmt = lambda v: "-" if v is None else f"{v:.0f}"
     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},"
@@ -614,9 +609,10 @@
     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)
-    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)
+    h = a["hearts"]
+    line(ax, f, [max(0, h - hearts_lost(s["naive"])) for s in a["scan"]], 1, "naive", markevery=10)
+    line(ax, f, [max(0, h - hearts_lost(s["greedy"])) for s in a["scan"]], 2, "greedy", markevery=10)
+    ax.set_ylim(-0.03 * h, 1.05 * h)
     legend(ax)
     fig.tight_layout()
     fig.savefig(path, dpi=110, facecolor=SURFACE)
@@ -629,6 +625,8 @@
         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()):
+            if "damage" not in t:
+                continue
             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)
@@ -643,7 +641,7 @@
     """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)))
+        print("\n".join(draft_toml(m, waves)))
         for msg in draft_check(cfg, waves):
             print(f"# warning: {msg}")
         cfg["map"][str(m)]["wave"] = [{"monsters": w} for w in waves]