|
22
|
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
|
|
23
|
9 python3 tools/balance.py --draft [MAP]
|
|
22
|
10
|
|
|
11 towers are t1 only for the wave demands. two players: naive builds level 1
|
|
|
12 towers on cells of median coverage whenever it can afford one; greedy picks
|
|
|
13 cells by coverage of route not yet covered and upgrades when that buys more
|
|
|
14 damage per coin than a new tower. greedy also starts every wave early for
|
|
|
15 the bonus.
|
|
|
16
|
|
23
|
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.
|
|
|
22
|
|
22
|
23 requires python 3.11 or later, numpy and matplotlib.
|
|
|
24 """
|
|
|
25
|
|
|
26 import math
|
|
|
27 import sys
|
|
|
28 import tomllib
|
|
|
29 import json
|
|
|
30
|
|
|
31 import numpy as np
|
|
|
32
|
|
|
33 # keep tools/ free of __pycache__
|
|
|
34 sys.dont_write_bytecode = True
|
|
|
35
|
|
|
36 import matplotlib
|
|
|
37 matplotlib.use("Agg")
|
|
|
38 import matplotlib.pyplot as plt
|
|
|
39
|
|
|
40 from build import CONFIG, MAPS, MAPS_CACHE, PREVIEW, TOWER_BY_LEVEL, tower_levels
|
|
|
41
|
|
|
42 # distance between route samples for coverage
|
|
|
43 SAMPLE_STEP = 4
|
|
|
44 # greedy cells listed per map, more than any budget buys
|
|
|
45 GREEDY_CELLS = 120
|
|
|
46 # the tower the wave demands are measured against
|
|
|
47 TOWER = "t1"
|
|
23
|
48 # wave size factors scanned for the margin charts
|
|
|
49 FACTORS = np.round(np.arange(0.5, 3.001, 0.05), 2)
|
|
22
|
50 # hearts the naive player should have left at the end of a map (decided)
|
|
|
51 HEARTS_TARGET = 5
|
|
|
52
|
|
|
53 # chart colours: surface, text, grid, then series slots in fixed order
|
|
|
54 SURFACE = "#fcfcfb"
|
|
|
55 INK = "#0b0b0b"
|
|
|
56 INK2 = "#52514e"
|
|
|
57 GRID = "#e4e3de"
|
|
|
58 SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#6250d6"]
|
|
|
59
|
|
|
60
|
|
|
61 # coverage
|
|
|
62
|
|
|
63 def resample(points, step):
|
|
|
64 """
|
|
|
65 sample a route at about step apart. returns (samples, weight): an n x 2
|
|
|
66 array of positions in the middle of equal pieces, and the length of a
|
|
|
67 piece.
|
|
|
68 """
|
|
|
69 p = np.asarray(points, float)
|
|
|
70 cum = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(p, axis=0).T))])
|
|
|
71 n = max(1, math.ceil(cum[-1] / step))
|
|
|
72 pos = (np.arange(n) + 0.5) * cum[-1] / n
|
|
|
73 return np.column_stack([np.interp(pos, cum, p[:, 0]), np.interp(pos, cum, p[:, 1])]), cum[-1] / n
|
|
|
74
|
|
|
75
|
|
|
76 class MapCoverage:
|
|
|
77 """
|
|
|
78 legal placement cells of a map and the route samples each can reach.
|
|
23
|
79 the boss route is the shortest one.
|
|
22
|
80 """
|
|
|
81
|
|
|
82 def __init__(self, mp):
|
|
|
83 cell, cols = mp["cell"], mp["cols"]
|
|
|
84 idx = np.array([i for i, c in enumerate(mp["grid"]) if c == "1"])
|
|
|
85 self.cells = np.column_stack([(idx % cols) * cell + cell // 2,
|
|
|
86 (idx // cols) * cell + cell // 2]).astype(float)
|
|
23
|
87 routes = mp["routes"]
|
|
22
|
88 self.routes = [resample(r["points"], SAMPLE_STEP) for r in routes]
|
|
|
89 self.boss_route = min(range(len(routes)), key=lambda i: routes[i]["length"])
|
|
|
90 self.lengths = [r["length"] for r in routes]
|
|
|
91
|
|
|
92 def within(self, rng):
|
|
|
93 """per route, a cells x samples array: sample in range of the cell."""
|
|
|
94 out = []
|
|
|
95 for samples, _ in self.routes:
|
|
|
96 d2 = ((self.cells[:, None, :] - samples[None, :, :]) ** 2).sum(axis=2)
|
|
|
97 out.append(d2 <= rng * rng)
|
|
|
98 return out
|
|
|
99
|
|
|
100 def coverage(self, rng):
|
|
|
101 """per cell: (mean route length in range over routes, on the boss route)."""
|
|
|
102 per_route = np.array([w.sum(axis=1) * wt for w, (_, wt) in zip(self.within(rng), self.routes)])
|
|
|
103 return per_route.mean(axis=0), per_route[self.boss_route]
|
|
|
104
|
|
|
105 def greedy(self, rng, count, min_dist):
|
|
|
106 """
|
|
|
107 up to count cells, picked one after the other by the route length in
|
|
|
108 range that no earlier pick covers, mean over routes. picks keep
|
|
|
109 min_dist from each other. once all route is covered, the cell with
|
|
|
110 the most route in range is next. returns cell indices.
|
|
|
111 """
|
|
|
112 within = self.within(rng)
|
|
|
113 weights = [wt for _, wt in self.routes]
|
|
|
114 full = sum(w.sum(axis=1) * wt for w, wt in zip(within, weights)) / len(within)
|
|
|
115 covered = [np.zeros(w.shape[1], bool) for w in within]
|
|
|
116 free = np.ones(len(self.cells), bool)
|
|
|
117 order = []
|
|
|
118 for _ in range(count):
|
|
|
119 if not free.any():
|
|
|
120 break
|
|
|
121 gain = sum(w[:, ~c].sum(axis=1) * wt for w, c, wt in zip(within, covered, weights)) / len(within)
|
|
|
122 if gain[free].max() <= 0:
|
|
|
123 gain = full
|
|
|
124 i = int(np.flatnonzero(free)[np.argmax(gain[free])])
|
|
|
125 order.append(i)
|
|
|
126 for w, c in zip(within, covered):
|
|
|
127 c |= w[i]
|
|
|
128 free &= np.hypot(*(self.cells - self.cells[i]).T) >= min_dist
|
|
|
129 return order
|
|
|
130
|
|
|
131
|
|
|
132 # waves
|
|
|
133
|
|
23
|
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
|
|
22
|
147 class Wave:
|
|
|
148 """
|
|
23
|
149 one wave. kinds: list of (count, hp, speed, coins, boss).
|
|
22
|
150 """
|
|
|
151
|
|
23
|
152 def __init__(self, cfg, monsters, interval):
|
|
22
|
153 mons = cfg["monster"]
|
|
23
|
154 self.kinds = [(n, mons[k]["hp"], mons[k]["speed"], mons[k]["coins"],
|
|
22
|
155 bool(mons[k].get("boss"))) for k, n in monsters.items() if n]
|
|
|
156 reg = [k for k in self.kinds if not k[4]]
|
|
|
157 self.boss = next((k for k in self.kinds if k[4]), None)
|
|
|
158 self.count = sum(k[0] for k in reg)
|
|
|
159 self.hp = sum(k[0] * k[1] for k in reg)
|
|
|
160 self.coins = sum(k[0] * k[3] for k in reg)
|
|
|
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
|
|
|
163 self.duration = (self.count - 1) * interval
|
|
|
164 self.spacing = self.speed * interval
|
|
|
165 self.tough = max(reg, key=lambda k: k[1])
|
|
|
166 self.reg = reg
|
|
|
167
|
|
|
168 def shots(self, damage):
|
|
|
169 """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)
|
|
|
171
|
|
|
172
|
|
|
173 def result(towers, wave, attack_time):
|
|
|
174 """
|
|
|
175 what towers do against a wave. towers: list of (coverage, boss route
|
|
|
176 coverage, damage). throughput: each tower attacks from the first monster
|
|
|
177 reaching it until the last has passed, while a monster is in range,
|
|
|
178 with whole shots per monster. single target: the monster gets every
|
|
|
179 tower's full attention while in range. returns a dict with leak (regular
|
|
|
180 hp not killed), hearts, coins earned, holds, and the single target
|
|
|
181 damage on the boss and on the toughest regular monster.
|
|
|
182 """
|
|
|
183 cap = 0.0
|
|
|
184 tough = 0.0
|
|
|
185 boss = 0.0
|
|
|
186 for cov, bcov, dmg in towers:
|
|
|
187 busy = 1 - math.exp(-cov / wave.spacing)
|
|
|
188 window = wave.duration + cov / wave.speed
|
|
|
189 cap += window / attack_time * busy * wave.hp / wave.shots(dmg)
|
|
|
190 tough += cov / wave.tough[2] / attack_time * dmg
|
|
|
191 if wave.boss:
|
|
|
192 boss += bcov / wave.boss[2] / attack_time * dmg
|
|
|
193 leak = max(0.0, wave.hp - cap)
|
|
|
194 killed = 1 - leak / wave.hp
|
|
|
195 out = {"leak": leak, "tough": tough, "boss": boss}
|
|
|
196 out["hearts"] = leak / (wave.hp / wave.count)
|
|
|
197 out["coins"] = wave.coins * killed
|
|
|
198 boss_ok = True
|
|
|
199 if wave.boss:
|
|
|
200 boss_ok = boss >= wave.boss[1]
|
|
|
201 if boss_ok:
|
|
|
202 out["coins"] += wave.boss[3]
|
|
|
203 else:
|
|
|
204 out["hearts"] += 5
|
|
|
205 out["holds"] = leak < 1e-9 and boss_ok
|
|
|
206 return out
|
|
|
207
|
|
|
208
|
|
|
209 # players
|
|
|
210
|
|
|
211 class Player:
|
|
|
212 """
|
|
|
213 a fixed order of purchases. states[k] is the list of towers after the
|
|
|
214 first k purchases, cost[k] what they cost in all.
|
|
|
215 """
|
|
|
216
|
|
|
217 def holds_from(self, wave, attack_time):
|
|
|
218 """smallest k whose towers hold the wave, None if none does."""
|
|
|
219 lo, hi = 0, len(self.states) - 1
|
|
|
220 if not result(self.states[hi], wave, attack_time)["holds"]:
|
|
|
221 return None
|
|
|
222 while lo < hi:
|
|
|
223 mid = (lo + hi) // 2
|
|
|
224 if result(self.states[mid], wave, attack_time)["holds"]:
|
|
|
225 hi = mid
|
|
|
226 else:
|
|
|
227 lo = mid + 1
|
|
|
228 return lo
|
|
|
229
|
|
|
230
|
|
|
231 class Naive(Player):
|
|
|
232 def __init__(self, tower, cov, bcov, budget):
|
|
|
233 n = budget // tower["cost"][0] + 1
|
|
|
234 self.states = [[(cov, bcov, tower["damage"][0])] * k for k in range(n)]
|
|
|
235 self.cost = [k * tower["cost"][0] for k in range(n)]
|
|
|
236 self.bonus = False
|
|
|
237
|
|
|
238
|
|
|
239 class Greedy(Player):
|
|
|
240 """
|
|
|
241 each purchase is a new level 1 tower on the next greedy cell or an
|
|
|
242 upgrade, whichever adds more damage per second per coin. damage per
|
|
|
243 second counts while a monster is in range, at spacing s.
|
|
|
244 """
|
|
|
245
|
|
|
246 def __init__(self, tower, cells, cov, bcov, budget, spacing):
|
|
|
247 at = tower["attack_time"]
|
|
|
248 dmg, cost = tower["damage"], tower["cost"]
|
|
|
249
|
|
|
250 def busy(i):
|
|
|
251 return 1 - math.exp(-cov[i] / spacing)
|
|
|
252
|
|
|
253 levels = [] # (cell, level) per tower
|
|
|
254 nxt = 0
|
|
|
255 total = 0
|
|
|
256 self.states = [[]]
|
|
|
257 self.cost = [0]
|
|
|
258 while True:
|
|
|
259 best, choice = 0.0, None
|
|
|
260 if nxt < len(cells):
|
|
|
261 best, choice = dmg[0] / at * busy(cells[nxt]) / cost[0], ("new", None)
|
|
|
262 for t, (c, lv) in enumerate(levels):
|
|
|
263 if lv < len(dmg):
|
|
|
264 v = (dmg[lv] - dmg[lv - 1]) / at * busy(c) / cost[lv]
|
|
|
265 if v > best:
|
|
|
266 best, choice = v, ("up", t)
|
|
|
267 if choice is None:
|
|
|
268 break
|
|
|
269 if choice[0] == "new":
|
|
|
270 price = cost[0]
|
|
|
271 levels.append((cells[nxt], 1))
|
|
|
272 nxt += 1
|
|
|
273 else:
|
|
|
274 c, lv = levels[choice[1]]
|
|
|
275 price = cost[lv]
|
|
|
276 levels[choice[1]] = (c, lv + 1)
|
|
|
277 total += price
|
|
|
278 if total > budget:
|
|
|
279 break
|
|
|
280 self.states.append([(cov[c], bcov[c], dmg[lv - 1]) for c, lv in levels])
|
|
|
281 self.cost.append(total)
|
|
|
282 self.bonus = True
|
|
|
283
|
|
|
284
|
|
|
285 def play(player, waves, start, bonuses, attack_time):
|
|
|
286 """
|
|
|
287 play a map: at each wave start buy what the coins allow, in the
|
|
|
288 player's order. returns one row per wave: budget (coins on hand plus
|
|
|
289 coins spent so far), coins left after buying, towers bought, coins the
|
|
|
290 wave needs (None: more than the purchase list holds), hearts lost, and
|
|
|
291 the result.
|
|
|
292 """
|
|
|
293 coins, k, rows = start, 0, []
|
|
|
294 for w, wave in enumerate(waves):
|
|
|
295 if player.bonus:
|
|
|
296 coins += bonuses[w]
|
|
|
297 while k + 1 < len(player.states) and player.cost[k + 1] - player.cost[k] <= coins:
|
|
|
298 coins -= player.cost[k + 1] - player.cost[k]
|
|
|
299 k += 1
|
|
|
300 res = result(player.states[k], wave, attack_time)
|
|
|
301 need = player.holds_from(wave, attack_time)
|
|
|
302 rows.append({"budget": coins + player.cost[k], "left": coins, "towers": len(player.states[k]),
|
|
|
303 "need": None if need is None else player.cost[need], "res": res})
|
|
|
304 coins += res["coins"]
|
|
|
305 return rows
|
|
|
306
|
|
|
307
|
|
23
|
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
|
|
22
|
379 # calculation
|
|
|
380
|
|
|
381 def tower_table(cfg):
|
|
|
382 """tower id -> config with the by-level values filled in."""
|
|
|
383 return {tid: {k: tower_levels(v) if k in TOWER_BY_LEVEL else v for k, v in tw.items()}
|
|
|
384 for tid, tw in cfg["tower"].items()}
|
|
|
385
|
|
|
386
|
|
|
387 def map_waves(cfg, m, f):
|
|
23
|
388 """the map's waves with regular monster counts scaled by f."""
|
|
22
|
389 c = cfg["map"][str(m)]
|
|
|
390 interval = c.get("spawn_interval", cfg["waves"]["spawn_interval"])
|
|
23
|
391 return [Wave(cfg, scale_counts(cfg, w["monsters"], f), interval) for w in c["wave"]]
|
|
22
|
392
|
|
|
393
|
|
|
394 def bonuses(cfg, m):
|
|
|
395 """early start bonus for skipping the break before each wave."""
|
|
|
396 c = cfg["map"][str(m)]
|
|
|
397 n = len(c["wave"])
|
|
|
398 return [math.floor(c["early_bonus"] * (cfg["waves"]["first_break"] if w == 0 else cfg["waves"]["break"]))
|
|
|
399 for w in range(n)]
|
|
|
400
|
|
|
401
|
|
|
402 def analyse_map(cfg, towers, mp, m):
|
|
|
403 """everything the report and charts show for map m."""
|
|
|
404 c = cfg["map"][str(m)]
|
|
|
405 tw = towers[TOWER]
|
|
|
406 mc = MapCoverage(mp)
|
|
|
407 cov, bcov = mc.coverage(tw["range"][0])
|
|
|
408 cells = mc.greedy(tw["range"][0], GREEDY_CELLS, cfg["placement"]["min_tower_distance"])
|
|
|
409 waves1 = map_waves(cfg, m, 1.0)
|
|
|
410 # budget large enough for every factor scanned
|
|
|
411 budget = (c["starting_coins"] + sum(w.coins + (w.boss[3] if w.boss else 0) for w in waves1)
|
|
|
412 + sum(bonuses(cfg, m))) * 3
|
|
|
413 spacing = sum(w.spacing * w.count for w in waves1) / sum(w.count for w in waves1)
|
|
|
414 naive = Naive(tw, float(np.median(cov)), float(np.median(bcov)), budget)
|
|
|
415 greedy = Greedy(tw, cells, cov, bcov, budget, spacing)
|
|
|
416 at, start, bon = tw["attack_time"], c["starting_coins"], bonuses(cfg, m)
|
|
|
417
|
|
|
418 scan = []
|
|
|
419 for f in FACTORS:
|
|
|
420 waves = map_waves(cfg, m, f)
|
|
|
421 n, g = play(naive, waves, start, bon, at), play(greedy, waves, start, bon, at)
|
|
|
422 scan.append({"f": f, "naive": n, "greedy": g})
|
|
|
423 out = {"m": m, "cov": cov, "bcov": bcov, "cells": cells, "routes": len(mc.routes),
|
|
|
424 "lengths": mc.lengths, "spacing": spacing, "waves": waves1, "bonus": bon,
|
|
|
425 "naive": play(naive, waves1, start, bon, at), "greedy": play(greedy, waves1, start, bon, at),
|
|
|
426 "scan": scan, "coverage": {}}
|
|
|
427 for tid, t in towers.items():
|
|
|
428 tc, _ = mc.coverage(t["range"][0])
|
|
|
429 out["coverage"][tid] = (float(np.median(tc)), float(np.percentile(tc, 90)), float(tc.max()))
|
|
|
430 return out
|
|
|
431
|
|
|
432
|
|
|
433 def surplus(rows):
|
|
|
434 """coins on hand at the start of the last wave beyond what it needs."""
|
|
|
435 last = rows[-1]
|
|
|
436 return None if last["need"] is None else last["budget"] - last["need"]
|
|
|
437
|
|
|
438
|
|
|
439 def hearts_lost(rows):
|
|
|
440 return sum(r["res"]["hearts"] for r in rows)
|
|
|
441
|
|
|
442
|
|
23
|
443 def factors_at_target(scan):
|
|
|
444 """
|
|
|
445 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
|
|
|
447 points. larger waves also pay more coins, so there may be several.
|
|
|
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]
|
|
22
|
458
|
|
|
459
|
|
|
460 # report
|
|
|
461
|
|
|
462 def value_table(cfg, towers):
|
|
|
463 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,",
|
|
|
465 "whole shots per monster. t0 counts one monster per attack.", ""]
|
|
|
466 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)
|
|
|
468 lines.append(head)
|
|
|
469 for tid, t in towers.items():
|
|
|
470 paid = 0
|
|
|
471 for lv in range(len(t["damage"])):
|
|
|
472 d, at = t["damage"][lv], t["attack_time"]
|
|
|
473 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}"
|
|
|
475 for k in regular:
|
|
|
476 hp = cfg["monster"][k]["hp"]
|
|
|
477 row += f"{hp / (math.ceil(hp / d) * at) / paid:>8.2f}"
|
|
|
478 lines.append(row)
|
|
|
479 return lines
|
|
|
480
|
|
|
481
|
|
23
|
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
|
|
22
|
525 def map_report(cfg, a):
|
|
|
526 m, c = a["m"], cfg["map"][str(a["m"])]
|
|
|
527 lens = a["lengths"]
|
|
|
528 lines = [f"map{m}", "----", "",
|
|
|
529 f"{a['routes']} route(s), length {min(lens):.0f}" + (f" to {max(lens):.0f}" if len(lens) > 1 else "")
|
|
|
530 + f"; spacing between monsters {a['spacing']:.0f}; starting coins {c['starting_coins']}", "",
|
|
|
531 "coverage by level 1 range, route length in range per legal cell:", "",
|
|
|
532 f"{'tower':6}{'median':>8}{'top10%':>8}{'best':>8}{'t0 hits':>9}"]
|
|
|
533 for tid, (med, top, best) in a["coverage"].items():
|
|
|
534 hits = f"{med / a['spacing']:>9.1f}" if tid == "t0" else ""
|
|
|
535 lines.append(f"{tid:6}{med:>8.0f}{top:>8.0f}{best:>8.0f}{hits}")
|
|
|
536 lines += ["", "t0 hits: monsters in range of a median t0 cell at the mean spacing,",
|
|
|
537 "the number one t0 attack damages in a full wave.", "",
|
|
23
|
538 "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",
|
|
|
540 "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",
|
|
|
542 "that hold the wave. lost: hearts lost, leaks by throughput plus 5 for",
|
|
|
543 "a boss.", "",
|
|
22
|
544 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}"]
|
|
|
546 med = float(np.median(a["cov"]))
|
|
|
547 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)
|
|
|
549 if wave.boss:
|
|
|
550 single = f"{n['res']['boss']:.0f}/{wave.boss[1]}b"
|
|
|
551 else:
|
|
|
552 single = f"{n['res']['tough']:.0f}/{wave.tough[1]}"
|
|
|
553 coins = wave.coins + (wave.boss[3] if wave.boss else 0)
|
|
|
554 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}"
|
|
|
556 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}")
|
|
|
558 one = next(s for s in a["scan"] if s["f"] == 1.0)
|
|
23
|
559 target = factors_at_target(a["scan"])
|
|
22
|
560 fmt = lambda v: "-" if v is None else f"{v:.0f}"
|
|
23
|
561 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},"
|
|
22
|
563 f" surplus {fmt(surplus(one['greedy']))}",
|
|
23
|
564 f"wave size factors at which naive ends with {HEARTS_TARGET} hearts or fewer: "
|
|
|
565 + (", ".join(f"{lo:.2f} to {hi:.2f}" for lo, hi in target) or "none in the scan"), ""]
|
|
22
|
566 return lines
|
|
|
567
|
|
|
568
|
|
|
569 # charts
|
|
|
570
|
|
|
571 def style(ax, title, xlabel, ylabel):
|
|
|
572 ax.set_facecolor(SURFACE)
|
|
|
573 ax.set_title(title, color=INK, fontsize=11, loc="left")
|
|
|
574 ax.set_xlabel(xlabel, color=INK2, fontsize=9)
|
|
|
575 ax.set_ylabel(ylabel, color=INK2, fontsize=9)
|
|
|
576 ax.grid(True, color=GRID, linewidth=0.8)
|
|
|
577 ax.set_axisbelow(True)
|
|
|
578 for side in ("top", "right"):
|
|
|
579 ax.spines[side].set_visible(False)
|
|
|
580 for side in ("left", "bottom"):
|
|
|
581 ax.spines[side].set_color(INK2)
|
|
|
582 ax.tick_params(colors=INK2, labelsize=8)
|
|
|
583
|
|
|
584
|
|
|
585 def line(ax, x, y, slot, label, **kw):
|
|
|
586 ax.plot(x, y, color=SERIES[slot], linewidth=2, marker="o", markersize=5,
|
|
|
587 markeredgecolor=SURFACE, markeredgewidth=1, label=label, **kw)
|
|
|
588
|
|
|
589
|
|
|
590 def legend(ax):
|
|
|
591 ax.legend(frameon=False, fontsize=8, labelcolor=INK)
|
|
|
592
|
|
|
593
|
|
|
594 def map_chart(a, path):
|
|
|
595 fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), facecolor=SURFACE)
|
|
|
596 waves = range(1, len(a["waves"]) + 1)
|
|
|
597 ax = axes[0]
|
|
23
|
598 style(ax, f"map{a['m']}: coins per wave, wave size factor 1", "wave", "coins")
|
|
22
|
599 line(ax, waves, [r["budget"] for r in a["naive"]], 0, "budget (naive)")
|
|
|
600 line(ax, waves, [r["need"] for r in a["naive"]], 1, "needed, naive")
|
|
|
601 line(ax, waves, [r["need"] for r in a["greedy"]], 2, "needed, greedy")
|
|
|
602 ax.set_xticks(list(waves))
|
|
|
603 legend(ax)
|
|
|
604
|
|
|
605 f = [s["f"] for s in a["scan"]]
|
|
|
606 ax = axes[1]
|
|
23
|
607 style(ax, "surplus at the last wave", "wave size factor", "coins")
|
|
22
|
608 ax.axhline(0, color=INK2, linewidth=1)
|
|
|
609 line(ax, f, [surplus(s["naive"]) for s in a["scan"]], 1, "naive", markevery=10)
|
|
|
610 line(ax, f, [surplus(s["greedy"]) for s in a["scan"]], 2, "greedy", markevery=10)
|
|
|
611 legend(ax)
|
|
|
612
|
|
|
613 ax = axes[2]
|
|
23
|
614 style(ax, "hearts left at the end", "wave size factor", "hearts")
|
|
22
|
615 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")
|
|
|
617 line(ax, f, [max(0, 10 - hearts_lost(s["naive"])) for s in a["scan"]], 1, "naive", markevery=10)
|
|
|
618 line(ax, f, [max(0, 10 - hearts_lost(s["greedy"])) for s in a["scan"]], 2, "greedy", markevery=10)
|
|
|
619 ax.set_ylim(-0.3, 10.5)
|
|
|
620 legend(ax)
|
|
|
621 fig.tight_layout()
|
|
|
622 fig.savefig(path, dpi=110, facecolor=SURFACE)
|
|
|
623 plt.close(fig)
|
|
|
624
|
|
|
625
|
|
|
626 def value_chart(cfg, towers, path):
|
|
|
627 fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), facecolor=SURFACE)
|
|
|
628 for ax, mon in zip(axes, ("m0", "m4")):
|
|
|
629 hp = cfg["monster"][mon]["hp"]
|
|
|
630 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()):
|
|
|
632 paid = np.cumsum(t["cost"])
|
|
|
633 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)
|
|
|
635 ax.set_xticks(range(1, 6))
|
|
|
636 legend(ax)
|
|
|
637 fig.tight_layout()
|
|
|
638 fig.savefig(path, dpi=110, facecolor=SURFACE)
|
|
|
639 plt.close(fig)
|
|
|
640
|
|
|
641
|
|
23
|
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
|
|
22
|
655 def main():
|
|
23
|
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
|
|
22
|
660 cfg = tomllib.loads((CONFIG / "game.toml").read_text())
|
|
|
661 if not MAPS_CACHE.exists():
|
|
|
662 print("no route data: run tools/build.py first")
|
|
|
663 return 1
|
|
|
664 maps = json.loads(MAPS_CACHE.read_text())["maps"]
|
|
|
665 towers = tower_table(cfg)
|
|
23
|
666 if args:
|
|
|
667 return draft(cfg, towers, maps, int(args[1]) if len(args) > 1 else None)
|
|
22
|
668 PREVIEW.mkdir(parents=True, exist_ok=True)
|
|
|
669 lines = ["balance estimate, written by tools/balance.py", ""] + value_table(cfg, towers) + [""]
|
|
|
670 value_chart(cfg, towers, PREVIEW / "balance_value.png")
|
|
23
|
671 analyses = []
|
|
22
|
672 for m in range(MAPS):
|
|
|
673 a = analyse_map(cfg, towers, maps[m], m)
|
|
23
|
674 analyses.append(a)
|
|
22
|
675 report = map_report(cfg, a)
|
|
|
676 lines += report
|
|
23
|
677 print("\n".join(report[-3:-1]).replace("wave size factor 1:", f"map{m}, wave size factor 1:"))
|
|
22
|
678 map_chart(a, PREVIEW / f"balance_map{m}.png")
|
|
23
|
679 lines += t0_table(cfg, towers, analyses)
|
|
22
|
680 (PREVIEW / "balance.txt").write_text("\n".join(lines))
|
|
|
681 print("balance: wrote temp/preview/balance.txt, balance_*.png")
|
|
|
682 return 0
|
|
|
683
|
|
|
684
|
|
|
685 if __name__ == "__main__":
|
|
|
686 sys.exit(main())
|