comparison tools/balance.py @ 23:2f555a54c332

layout fixes and balancing
author ark
date 2026-10-20 12:04 +0200
parents ad1b478fc4dc
children a464bd43b76c
comparison
equal deleted inserted replaced
22:ad1b478fc4dc 23:2f555a54c332
4 enough firepower (doc/balance.md, balancing). reads config/game.toml and the 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 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 10
10 towers are t1 only for the wave demands. two players: naive builds level 1 11 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 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 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 damage per coin than a new tower. greedy also starts every wave early for
14 the bonus. 15 the bonus.
16
17 --draft prints wave lists for every map, or for map MAP, as toml to paste
18 into config/game.toml. they are made from monster_share, wave_size and
19 first_wave in the map's section (see draft_waves). the calculation then
20 runs on the drafted lists instead of the ones in game.toml; balance.txt and
21 the charts are not written.
15 22
16 requires python 3.11 or later, numpy and matplotlib. 23 requires python 3.11 or later, numpy and matplotlib.
17 """ 24 """
18 25
19 import math 26 import math
36 SAMPLE_STEP = 4 43 SAMPLE_STEP = 4
37 # greedy cells listed per map, more than any budget buys 44 # greedy cells listed per map, more than any budget buys
38 GREEDY_CELLS = 120 45 GREEDY_CELLS = 120
39 # the tower the wave demands are measured against 46 # the tower the wave demands are measured against
40 TOWER = "t1" 47 TOWER = "t1"
41 # hp factors scanned for the margin charts 48 # wave size factors scanned for the margin charts
42 FACTORS = np.round(np.arange(0.5, 6.001, 0.05), 2) 49 FACTORS = np.round(np.arange(0.5, 3.001, 0.05), 2)
43 # hearts the naive player should have left at the end of a map (decided) 50 # hearts the naive player should have left at the end of a map (decided)
44 HEARTS_TARGET = 5 51 HEARTS_TARGET = 5
45 52
46 # chart colours: surface, text, grid, then series slots in fixed order 53 # chart colours: surface, text, grid, then series slots in fixed order
47 SURFACE = "#fcfcfb" 54 SURFACE = "#fcfcfb"
67 74
68 75
69 class MapCoverage: 76 class MapCoverage:
70 """ 77 """
71 legal placement cells of a map and the route samples each can reach. 78 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 79 the boss route is the shortest one.
73 shortest one.
74 """ 80 """
75 81
76 def __init__(self, mp): 82 def __init__(self, mp):
77 cell, cols = mp["cell"], mp["cols"] 83 cell, cols = mp["cell"], mp["cols"]
78 idx = np.array([i for i, c in enumerate(mp["grid"]) if c == "1"]) 84 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, 85 self.cells = np.column_stack([(idx % cols) * cell + cell // 2,
80 (idx // cols) * cell + cell // 2]).astype(float) 86 (idx // cols) * cell + cell // 2]).astype(float)
81 routes = [r for r in mp["routes"] if r["weight"] != 0] 87 routes = mp["routes"]
82 self.routes = [resample(r["points"], SAMPLE_STEP) for r in routes] 88 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"]) 89 self.boss_route = min(range(len(routes)), key=lambda i: routes[i]["length"])
84 self.lengths = [r["length"] for r in routes] 90 self.lengths = [r["length"] for r in routes]
85 91
86 def within(self, rng): 92 def within(self, rng):
123 return order 129 return order
124 130
125 131
126 # waves 132 # waves
127 133
134 def scale_counts(cfg, monsters, f):
135 """
136 a wave's monster counts with the regular ones scaled by f, rounded, at
137 least one regular monster left. the boss stays.
138 """
139 mons = cfg["monster"]
140 out = {k: (n if mons[k].get("boss") else math.floor(n * f + 0.5)) for k, n in monsters.items()}
141 reg = [k for k in monsters if not mons[k].get("boss")]
142 if reg and not any(out[k] for k in reg):
143 out[max(reg, key=lambda k: monsters[k])] = 1
144 return out
145
146
128 class Wave: 147 class Wave:
129 """ 148 """
130 one wave with hp scaled by factor f (whole numbers, at least 1). 149 one wave. kinds: list of (count, hp, speed, coins, boss).
131 kinds: list of (count, hp, speed, coins, boss). 150 """
132 """ 151
133 152 def __init__(self, cfg, monsters, interval):
134 def __init__(self, cfg, monsters, f, interval):
135 mons = cfg["monster"] 153 mons = cfg["monster"]
136 self.kinds = [(n, max(1, round(mons[k]["hp"] * f)), mons[k]["speed"], mons[k]["coins"], 154 self.kinds = [(n, mons[k]["hp"], mons[k]["speed"], mons[k]["coins"],
137 bool(mons[k].get("boss"))) for k, n in monsters.items() if n] 155 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]] 156 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) 157 self.boss = next((k for k in self.kinds if k[4]), None)
140 self.count = sum(k[0] for k in reg) 158 self.count = sum(k[0] for k in reg)
141 self.hp = sum(k[0] * k[1] for k in reg) 159 self.hp = sum(k[0] * k[1] for k in reg)
285 "need": None if need is None else player.cost[need], "res": res}) 303 "need": None if need is None else player.cost[need], "res": res})
286 coins += res["coins"] 304 coins += res["coins"]
287 return rows 305 return rows
288 306
289 307
308 # drafting
309
310 def draft_waves(cfg, m):
311 """
312 wave lists for map m from the draft numbers in its section: wave_count
313 waves, regular monster counts growing in equal steps from wave_size[0]
314 to wave_size[1], monster level i absent before wave first_wave[i]. the
315 counts of each level over the whole map follow monster_share.
316
317 each level starts with a weight that grows by one per wave from its
318 first wave, so later waves lean to the levels that came in later. the
319 weights are then scaled, alternately per wave and per level, until the
320 wave sizes and the level totals are met, and rounded per wave. every
321 level keeps at least one monster. the boss is added to the last wave.
322 returns a list of {monster: count}.
323 """
324 c = cfg["map"][str(m)]
325 regular = sorted(k for k, v in cfg["monster"].items() if not v.get("boss"))
326 n = c["wave_count"]
327 first, last = c["wave_size"]
328 sizes = np.array([round(first + (last - first) * w / max(1, n - 1)) for w in range(n)], float)
329 share = np.array(c["monster_share"], float)
330 totals = share / share.sum() * sizes.sum()
331 intro = np.array(c["first_wave"]) - 1
332 a = np.maximum(0, np.arange(n)[:, None] - intro[None, :] + 1).astype(float)
333 for _ in range(500):
334 a *= (sizes / np.maximum(a.sum(axis=1), 1e-12))[:, None]
335 a *= (totals / np.maximum(a.sum(axis=0), 1e-12))[None, :]
336 a *= (sizes / np.maximum(a.sum(axis=1), 1e-12))[:, None]
337 counts = np.floor(a).astype(int)
338 for w in range(n):
339 # largest remainders fill the wave up to its size
340 short = int(sizes[w]) - counts[w].sum()
341 for i in np.argsort(-(a[w] - counts[w]))[:short]:
342 counts[w, i] += 1
343 for i in range(len(regular)):
344 if counts[:, i].sum() == 0 and intro[i] < n:
345 counts[n - 1, i] += 1
346 counts[n - 1, int(np.argmax(counts[n - 1]))] -= 1
347 waves = [{k: int(v) for k, v in zip(regular, row) if v} for row in counts]
348 waves[-1][f"b{m}"] = 1
349 return waves
350
351
352 def draft_toml(cfg, m, waves):
353 """the drafted waves as toml lines, each wave with its count, hp and coins."""
354 c = cfg["map"][str(m)]
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):
360 reg = {k: v for k, v in wave.items() if not mons[k].get("boss")}
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()) + " }", ""]
368 return lines
369
370
371 def draft_check(cfg, waves):
372 """warnings for drafted waves: a wave with less hp than the one before."""
373 mons = cfg["monster"]
374 hp = [sum(v * mons[k]["hp"] for k, v in w.items() if not mons[k].get("boss")) for w in waves]
375 return [f"wave {w + 1} has less hp than wave {w} ({hp[w]} < {hp[w - 1]})"
376 for w in range(1, len(hp)) if hp[w] < hp[w - 1]]
377
378
290 # calculation 379 # calculation
291 380
292 def tower_table(cfg): 381 def tower_table(cfg):
293 """tower id -> config with the by-level values filled in.""" 382 """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()} 383 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()} 384 for tid, tw in cfg["tower"].items()}
296 385
297 386
298 def map_waves(cfg, m, f): 387 def map_waves(cfg, m, f):
388 """the map's waves with regular monster counts scaled by f."""
299 c = cfg["map"][str(m)] 389 c = cfg["map"][str(m)]
300 interval = c.get("spawn_interval", cfg["waves"]["spawn_interval"]) 390 interval = c.get("spawn_interval", cfg["waves"]["spawn_interval"])
301 return [Wave(cfg, w["monsters"], f, interval) for w in c["wave"]] 391 return [Wave(cfg, scale_counts(cfg, w["monsters"], f), interval) for w in c["wave"]]
302 392
303 393
304 def bonuses(cfg, m): 394 def bonuses(cfg, m):
305 """early start bonus for skipping the break before each wave.""" 395 """early start bonus for skipping the break before each wave."""
306 c = cfg["map"][str(m)] 396 c = cfg["map"][str(m)]
348 438
349 def hearts_lost(rows): 439 def hearts_lost(rows):
350 return sum(r["res"]["hearts"] for r in rows) 440 return sum(r["res"]["hearts"] for r in rows)
351 441
352 442
353 def factor_for_target(scan): 443 def factors_at_target(scan):
354 """smallest hp factor at which naive keeps HEARTS_TARGET hearts or fewer.""" 444 """
355 for s in scan: 445 the wave size factors at which naive ends with HEARTS_TARGET hearts or
356 if hearts_lost(s["naive"]) >= HEARTS_TARGET: 446 fewer, as a list of (lowest, highest) ranges of neighbouring scan
357 return s["f"] 447 points. larger waves also pay more coins, so there may be several.
358 return None 448 """
449 out = []
450 for i, s in enumerate(scan):
451 if hearts_lost(s["naive"]) < 10 - HEARTS_TARGET:
452 continue
453 if out and out[-1][2] == i - 1:
454 out[-1] = (out[-1][0], s["f"], i)
455 else:
456 out.append((s["f"], s["f"], i))
457 return [(lo, hi) for lo, hi, _ in out]
359 458
360 459
361 # report 460 # report
362 461
363 def value_table(cfg, towers): 462 def value_table(cfg, towers):
378 row += f"{hp / (math.ceil(hp / d) * at) / paid:>8.2f}" 477 row += f"{hp / (math.ceil(hp / d) * at) / paid:>8.2f}"
379 lines.append(row) 478 lines.append(row)
380 return lines 479 return lines
381 480
382 481
482 def t0_table(cfg, towers, analyses):
483 """
484 t0's value per coin with area damage: the single target value times the
485 monsters hit per attack. hits per attack as measured by tools/simulate.js
486 (temp/preview/simulate.json, players naive_t0 and naive_mix) where
487 available, otherwise the estimate from coverage and spacing.
488 """
489 measured = {}
490 sim = PREVIEW / "simulate.json"
491 if sim.exists():
492 for r in json.loads(sim.read_text()):
493 if r.get("t0Hits") is not None:
494 measured.setdefault(r["map"], []).append(r["t0Hits"])
495 t0, t1 = towers["t0"], towers[TOWER]
496 lines = ["t0 with area damage: hp per second per coin, whole shots, times the",
497 "monsters hit per attack. est: monsters in range of a median t0 cell at",
498 "the mean spacing. sim: measured by tools/simulate.js over whole runs of",
499 "the naive t0 players, if it was run. t1 level 1 for comparison.", "",
500 f"{'map':5}{'est':>6}{'sim':>6} level" + "".join(f"{'vs ' + k:>8}" for k in ("m0", "m4"))]
501 for a in analyses:
502 m = a["m"]
503 est = a["coverage"]["t0"][0] / a["spacing"]
504 sim_h = sum(measured[m]) / len(measured[m]) if m in measured else None
505 hits = sim_h if sim_h is not None else est
506 paid = 0
507 for lv in range(len(t0["damage"])):
508 d, at = t0["damage"][lv], t0["attack_time"]
509 paid += t0["cost"][lv]
510 row = (f"map{m:<2}{est:>6.1f}{'-' if sim_h is None else f'{sim_h:.2f}':>6}" if lv == 0
511 else " " * 17)
512 row += f"{lv + 1:>7}"
513 for k in ("m0", "m4"):
514 hp = cfg["monster"][k]["hp"]
515 row += f"{hits * hp / (math.ceil(hp / d) * at) / paid:>8.2f}"
516 lines.append(row)
517 row = " " * 17 + f"{'t1 1':>7}"
518 for k in ("m0", "m4"):
519 hp = cfg["monster"][k]["hp"]
520 row += f"{hp / (math.ceil(hp / t1['damage'][0]) * t1['attack_time']) / t1['cost'][0]:>8.2f}"
521 lines.append(row)
522 return lines + [""]
523
524
383 def map_report(cfg, a): 525 def map_report(cfg, a):
384 m, c = a["m"], cfg["map"][str(a["m"])] 526 m, c = a["m"], cfg["map"][str(a["m"])]
385 lens = a["lengths"] 527 lens = a["lengths"]
386 lines = [f"map{m}", "----", "", 528 lines = [f"map{m}", "----", "",
387 f"{a['routes']} route(s), length {min(lens):.0f}" + (f" to {max(lens):.0f}" if len(lens) > 1 else "") 529 f"{a['routes']} route(s), length {min(lens):.0f}" + (f" to {max(lens):.0f}" if len(lens) > 1 else "")
391 for tid, (med, top, best) in a["coverage"].items(): 533 for tid, (med, top, best) in a["coverage"].items():
392 hits = f"{med / a['spacing']:>9.1f}" if tid == "t0" else "" 534 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}") 535 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,", 536 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.", "", 537 "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", 538 "waves, t1 only, wave size factor 1. need/s: hp per second the towers",
397 "kill (throughput, median cell). single: damage the toughest monster", 539 "have to kill (throughput, median cell). single: damage the toughest",
398 "takes from the naive towers while in range, against its hp. budget:", 540 "monster takes from the naive towers while in range, against its hp.",
399 "coins on hand plus coins spent. need: coins of the purchases that hold", 541 "budget: coins on hand plus coins spent. need: coins of the purchases",
400 "the wave. lost: hearts lost, leaks by throughput plus 5 for a boss.", "", 542 "that hold the wave. lost: hearts lost, leaks by throughput plus 5 for",
543 "a boss.", "",
401 f"{'wave':>4}{'count':>6}{'hp':>6}{'coins':>6}{'need/s':>8}{'single':>12}" 544 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}"] 545 f" naive{'budget':>8}{'need':>6}{'lost':>6} greedy{'budget':>8}{'need':>6}{'lost':>6}"]
403 med = float(np.median(a["cov"])) 546 med = float(np.median(a["cov"]))
404 for w, (wave, n, g) in enumerate(zip(a["waves"], a["naive"], a["greedy"]), start=1): 547 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) 548 rate = wave.hp / (wave.duration + med / wave.speed)
411 need = lambda r: "-" if r["need"] is None else str(r["need"]) 554 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}" 555 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}" 556 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}") 557 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) 558 one = next(s for s in a["scan"] if s["f"] == 1.0)
416 target = factor_for_target(a["scan"]) 559 target = factors_at_target(a["scan"])
417 fmt = lambda v: "-" if v is None else f"{v:.0f}" 560 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" 561 lines += ["", f"wave size factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts,"
419 f" {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f}," 562 f" surplus at the last wave {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f},"
420 f" surplus {fmt(surplus(one['greedy']))}", 563 f" surplus {fmt(surplus(one['greedy']))}",
421 f"hp factor at which naive is down to {HEARTS_TARGET} hearts: " 564 f"wave size factors at which naive ends with {HEARTS_TARGET} hearts or fewer: "
422 + ("beyond the scan" if target is None else f"{target:.2f}"), ""] 565 + (", ".join(f"{lo:.2f} to {hi:.2f}" for lo, hi in target) or "none in the scan"), ""]
423 return lines 566 return lines
424 567
425 568
426 # charts 569 # charts
427 570
450 593
451 def map_chart(a, path): 594 def map_chart(a, path):
452 fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), facecolor=SURFACE) 595 fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), facecolor=SURFACE)
453 waves = range(1, len(a["waves"]) + 1) 596 waves = range(1, len(a["waves"]) + 1)
454 ax = axes[0] 597 ax = axes[0]
455 style(ax, f"map{a['m']}: coins per wave, hp factor 1", "wave", "coins") 598 style(ax, f"map{a['m']}: coins per wave, wave size factor 1", "wave", "coins")
456 line(ax, waves, [r["budget"] for r in a["naive"]], 0, "budget (naive)") 599 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") 600 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") 601 line(ax, waves, [r["need"] for r in a["greedy"]], 2, "needed, greedy")
459 ax.set_xticks(list(waves)) 602 ax.set_xticks(list(waves))
460 legend(ax) 603 legend(ax)
461 604
462 f = [s["f"] for s in a["scan"]] 605 f = [s["f"] for s in a["scan"]]
463 ax = axes[1] 606 ax = axes[1]
464 style(ax, "surplus at the last wave", "hp factor", "coins") 607 style(ax, "surplus at the last wave", "wave size factor", "coins")
465 ax.axhline(0, color=INK2, linewidth=1) 608 ax.axhline(0, color=INK2, linewidth=1)
466 line(ax, f, [surplus(s["naive"]) for s in a["scan"]], 1, "naive", markevery=10) 609 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) 610 line(ax, f, [surplus(s["greedy"]) for s in a["scan"]], 2, "greedy", markevery=10)
468 legend(ax) 611 legend(ax)
469 612
470 ax = axes[2] 613 ax = axes[2]
471 style(ax, "hearts left at the end", "hp factor", "hearts") 614 style(ax, "hearts left at the end", "wave size factor", "hearts")
472 ax.axhline(HEARTS_TARGET, color=INK2, linewidth=1, linestyle="--") 615 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") 616 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) 617 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) 618 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) 619 ax.set_ylim(-0.3, 10.5)
494 fig.tight_layout() 637 fig.tight_layout()
495 fig.savefig(path, dpi=110, facecolor=SURFACE) 638 fig.savefig(path, dpi=110, facecolor=SURFACE)
496 plt.close(fig) 639 plt.close(fig)
497 640
498 641
642 def draft(cfg, towers, maps, only):
643 """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]:
645 waves = draft_waves(cfg, m)
646 print("\n".join(draft_toml(cfg, m, waves)))
647 for msg in draft_check(cfg, waves):
648 print(f"# warning: {msg}")
649 cfg["map"][str(m)]["wave"] = [{"monsters": w} for w in waves]
650 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")
652 return 0
653
654
499 def main(): 655 def main():
656 args = sys.argv[1:]
657 if args and args[0] not in ("--draft",) or len(args) > 2:
658 print(__doc__.split("\n\n")[1])
659 return 2
500 cfg = tomllib.loads((CONFIG / "game.toml").read_text()) 660 cfg = tomllib.loads((CONFIG / "game.toml").read_text())
501 if not MAPS_CACHE.exists(): 661 if not MAPS_CACHE.exists():
502 print("no route data: run tools/build.py first") 662 print("no route data: run tools/build.py first")
503 return 1 663 return 1
504 maps = json.loads(MAPS_CACHE.read_text())["maps"] 664 maps = json.loads(MAPS_CACHE.read_text())["maps"]
505 towers = tower_table(cfg) 665 towers = tower_table(cfg)
666 if args:
667 return draft(cfg, towers, maps, int(args[1]) if len(args) > 1 else None)
506 PREVIEW.mkdir(parents=True, exist_ok=True) 668 PREVIEW.mkdir(parents=True, exist_ok=True)
507 lines = ["balance estimate, written by tools/balance.py", ""] + value_table(cfg, towers) + [""] 669 lines = ["balance estimate, written by tools/balance.py", ""] + value_table(cfg, towers) + [""]
508 value_chart(cfg, towers, PREVIEW / "balance_value.png") 670 value_chart(cfg, towers, PREVIEW / "balance_value.png")
671 analyses = []
509 for m in range(MAPS): 672 for m in range(MAPS):
510 a = analyse_map(cfg, towers, maps[m], m) 673 a = analyse_map(cfg, towers, maps[m], m)
674 analyses.append(a)
511 report = map_report(cfg, a) 675 report = map_report(cfg, a)
512 lines += report 676 lines += report
513 print("\n".join(report[-3:-1]).replace("hp factor 1", f"map{m}, hp factor 1")) 677 print("\n".join(report[-3:-1]).replace("wave size factor 1:", f"map{m}, wave size factor 1:"))
514 map_chart(a, PREVIEW / f"balance_map{m}.png") 678 map_chart(a, PREVIEW / f"balance_map{m}.png")
679 lines += t0_table(cfg, towers, analyses)
515 (PREVIEW / "balance.txt").write_text("\n".join(lines)) 680 (PREVIEW / "balance.txt").write_text("\n".join(lines))
516 print("balance: wrote temp/preview/balance.txt, balance_*.png") 681 print("balance: wrote temp/preview/balance.txt, balance_*.png")
517 return 0 682 return 0
518 683
519 684