comparison tools/simulate.js @ 23:2f555a54c332

layout fixes and balancing
author ark
date 2026-10-20 12:04 +0200
parents
children 75deda08db90
comparison
equal deleted inserted replaced
22:ad1b478fc4dc 23:2f555a54c332
1 #!/usr/bin/env node
2 // headless simulation of the game with scripted players (doc/balance.md,
3 // balancing). runs the game logic from www/ after a build: data/config.js,
4 // data/maps.js and the js/ files of the simulation, with MM.audio replaced
5 // by a stub. writes temp/preview/simulate.txt, the results as json in
6 // temp/preview/simulate.json (read by tools/balance.py), and prints a
7 // summary.
8 //
9 // usage: node tools/simulate.js [options]
10 //
11 // --maps 0,1 maps to play (default all)
12 // --players a,b players (default naive,greedy); also naive_t0, naive_mix
13 // --seeds n seeds per map and player, 1 to n (default 5)
14 // --need all measure the coins needed for every wave, not only the
15 // last one (slower)
16 // --waves file json {"0": [{"monsters": {...}}, ...], ...}: wave lists
17 // that replace the config's for the maps named
18 // --config file a config.js to use instead of www/data/config.js
19 // --json print the results as json instead of the summary, and
20 // write no files
21 //
22 // players (all build at the first moment they can afford the next
23 // purchase, through the game's own shop, preview and upgrade functions):
24 //
25 // naive t1 only, level 1, on cells of median t1 coverage. never
26 // starts a wave early
27 // greedy t1, cells picked by coverage of route not yet covered, and
28 // upgrades when that adds more damage per second per coin
29 // than a new tower (the rules of tools/balance.py). starts
30 // every wave early for the bonus
31 // naive_t0 as naive, t0 only, on cells of median t0 coverage
32 // naive_mix as naive, t1 and t0 in turn, each on cells of median
33 // coverage for its own range
34 //
35 // coverage of a cell is the route length within range, the mean over the
36 // map's routes, as in tools/balance.py. the coins a wave needs are the cost of the smallest
37 // number of the player's purchases, in its order, that hold the wave
38 // without losing a heart. it is measured by playing the wave on its own
39 // from an empty map, with the same seed.
40
41 "use strict";
42
43 var fs = require("fs");
44 var path = require("path");
45 var vm = require("vm");
46
47 var ROOT = path.resolve(__dirname, "..");
48 var WWW = path.join(ROOT, "www");
49 var OUT = path.join(ROOT, "temp", "preview", "simulate.txt");
50 var OUT_JSON = path.join(ROOT, "temp", "preview", "simulate.json");
51 var DT = 1 / 60;
52 // distance between route samples for coverage, as in tools/balance.py
53 var SAMPLE_STEP = 4;
54 // naive cells: coverage within this share of the median counts as median
55 var MEDIAN_BAND = 0.05;
56 // longest purchase lists
57 var MAX_TOWERS = 80;
58 var MAX_SPENT = 4000;
59 // a run stops after this much game time
60 var MAX_TIME = 4000;
61 // hearts the naive player should have left (decided)
62 var HEARTS_TARGET = 5;
63
64 // options
65
66 function options(argv) {
67 var o = { maps: null, players: ["naive", "greedy"], seeds: 5, needAll: false,
68 waves: null, config: path.join(WWW, "data", "config.js"), json: false };
69 for (var i = 0; i < argv.length; i++) {
70 var a = argv[i];
71 if (a === "--maps") o.maps = argv[++i].split(",").map(Number);
72 else if (a === "--players") o.players = argv[++i].split(",");
73 else if (a === "--seeds") o.seeds = Number(argv[++i]);
74 else if (a === "--need") o.needAll = argv[++i] === "all";
75 else if (a === "--waves") o.waves = JSON.parse(fs.readFileSync(argv[++i], "utf8"));
76 else if (a === "--config") o.config = path.resolve(argv[++i]);
77 else if (a === "--json") o.json = true;
78 else {
79 console.error("unknown option " + a + "; see the comment at the top of tools/simulate.js");
80 process.exit(2);
81 }
82 }
83 return o;
84 }
85
86 // load the game logic into this context, as the browser would
87 function load(configFile, waves) {
88 globalThis.window = globalThis;
89 var files = [configFile, path.join(WWW, "data", "maps.js")];
90 ["util", "assets", "map", "monster", "tower", "projectile", "wave", "game"].forEach(function (f) {
91 files.push(path.join(WWW, "js", f + ".js"));
92 });
93 files.forEach(function (f, i) {
94 vm.runInThisContext(fs.readFileSync(f, "utf8"), { filename: f });
95 if (i === files.length - 1) countMelee();
96 if (i === 1) {
97 var cfg = MM.config;
98 // debug switches off, whatever the config says
99 cfg.debug.start_coins = -1;
100 cfg.debug.unlimited_coins = false;
101 cfg.debug.no_heart_loss = false;
102 cfg.debug.extra_speeds = [];
103 if (waves) {
104 Object.keys(waves).forEach(function (m) { cfg.maps[m].waves = waves[m]; });
105 }
106 MM.audio = { play: function () {} };
107 }
108 });
109 }
110
111 // melee attacks and the monsters they hit, by tower type, counted from the
112 // game's own tower update and damage functions
113 var melee = {};
114
115 function countMelee() {
116 var update = MM.tower.update, damage = MM.Game.prototype.damage, current = null;
117 MM.tower.update = function (t, game, dt) {
118 var before = t.cooldown;
119 current = t.def.projectile_speed === 0 ? t : null;
120 update(t, game, dt);
121 if (current && t.cooldown > before) {
122 var c = melee[t.type] || (melee[t.type] = { attacks: 0, hits: 0 });
123 c.attacks++;
124 c.hits += current.hitsNow || 0;
125 }
126 if (current) current.hitsNow = 0;
127 current = null;
128 };
129 MM.Game.prototype.damage = function (m, amount) {
130 if (current && m.alive) current.hitsNow = (current.hitsNow || 0) + 1;
131 return damage.call(this, m, amount);
132 };
133 }
134
135 // coverage
136
137 // route samples about SAMPLE_STEP apart, in the middle of equal pieces:
138 // {xs, ys, weight}, weight being the length of a piece
139 function resample(r) {
140 var n = r.xs.length, cum = r.at, len = r.length;
141 var k = Math.max(1, Math.ceil(len / SAMPLE_STEP));
142 var xs = [], ys = [], seg = 1;
143 for (var i = 0; i < k; i++) {
144 var s = (i + 0.5) * len / k;
145 while (seg < n - 1 && cum[seg] < s) seg++;
146 var t = (s - cum[seg - 1]) / (cum[seg] - cum[seg - 1]);
147 xs.push(r.xs[seg - 1] + (r.xs[seg] - r.xs[seg - 1]) * t);
148 ys.push(r.ys[seg - 1] + (r.ys[seg] - r.ys[seg - 1]) * t);
149 }
150 return { xs: xs, ys: ys, weight: len / k };
151 }
152
153 // legal cells and route samples of a map
154 function MapData(index) {
155 var gm = new MM.GameMap(index), d = gm.data;
156 this.index = index;
157 this.cells = [];
158 for (var i = 0; i < d.grid.length; i++) {
159 if (d.grid.charCodeAt(i) === 49) {
160 this.cells.push([(i % d.cols) * d.cell + d.cell / 2, Math.floor(i / d.cols) * d.cell + d.cell / 2]);
161 }
162 }
163 this.routes = gm.routes.map(resample);
164 this.cache = {};
165 }
166
167 // per route, per cell: indices of the samples within range rng
168 MapData.prototype.within = function (rng) {
169 if (this.cache[rng]) return this.cache[rng];
170 var r2 = rng * rng, cells = this.cells;
171 var out = this.routes.map(function (r) {
172 return cells.map(function (c) {
173 var hit = [];
174 for (var i = 0; i < r.xs.length; i++) {
175 var dx = r.xs[i] - c[0], dy = r.ys[i] - c[1];
176 if (dx * dx + dy * dy <= r2) hit.push(i);
177 }
178 return hit;
179 });
180 });
181 this.cache[rng] = out;
182 return out;
183 };
184
185 // per cell: route length within range, the mean over routes
186 MapData.prototype.coverage = function (rng) {
187 var w = this.within(rng), routes = this.routes;
188 return this.cells.map(function (c, j) {
189 var sum = 0;
190 for (var r = 0; r < routes.length; r++) sum += w[r][j].length * routes[r].weight;
191 return sum / routes.length;
192 });
193 };
194
195 function median(v) {
196 var s = v.slice().sort(function (a, b) { return a - b; }), n = s.length;
197 return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
198 }
199
200 function farEnough(cells, picked, j, minDist) {
201 for (var i = 0; i < picked.length; i++) {
202 var a = cells[picked[i]], b = cells[j];
203 if (Math.hypot(a[0] - b[0], a[1] - b[1]) < minDist) return false;
204 }
205 return true;
206 }
207
208 // cells for the naive players: the cells within MEDIAN_BAND of the median
209 // coverage in random order, then the others by distance from the median.
210 // towers keep the minimum distance from each other. returns cell indices.
211 function medianCells(md, rng, random, count, picked) {
212 var cov = md.coverage(rng), med = median(cov);
213 var idx = cov.map(function (_, j) { return j; });
214 var band = idx.filter(function (j) { return Math.abs(cov[j] - med) <= MEDIAN_BAND * med; });
215 for (var i = band.length - 1; i > 0; i--) {
216 var k = Math.floor(random() * (i + 1)), t = band[i];
217 band[i] = band[k];
218 band[k] = t;
219 }
220 var rest = idx.filter(function (j) { return Math.abs(cov[j] - med) > MEDIAN_BAND * med; });
221 rest.sort(function (a, b) { return Math.abs(cov[a] - med) - Math.abs(cov[b] - med); });
222 var order = band.concat(rest), out = [];
223 var minDist = MM.config.placement.min_tower_distance;
224 for (i = 0; i < order.length && out.length < count; i++) {
225 if (farEnough(md.cells, picked, order[i], minDist)) {
226 out.push(order[i]);
227 picked.push(order[i]);
228 }
229 }
230 return out;
231 }
232
233 // cells picked one after the other by the route length in range that no
234 // earlier pick covers, mean over routes, keeping the minimum distance. once
235 // all route is covered, the cell with the most route in range is next.
236 function greedyCells(md, rng, count) {
237 var w = md.within(rng), routes = md.routes, cells = md.cells;
238 var full = md.coverage(rng);
239 var covered = routes.map(function (r) { return new Uint8Array(r.xs.length); });
240 var free = cells.map(function () { return true; });
241 var minDist = MM.config.placement.min_tower_distance;
242 var order = [];
243 while (order.length < count) {
244 var best = -1, bestGain = 0, bestFull = -1, bestFullV = -1;
245 for (var j = 0; j < cells.length; j++) {
246 if (!free[j]) continue;
247 var gain = 0;
248 for (var r = 0; r < routes.length; r++) {
249 var hit = w[r][j], cv = covered[r], n = 0;
250 for (var i = 0; i < hit.length; i++) if (!cv[hit[i]]) n++;
251 gain += n * routes[r].weight;
252 }
253 gain /= routes.length;
254 if (gain > bestGain) { bestGain = gain; best = j; }
255 if (full[j] > bestFullV) { bestFullV = full[j]; bestFull = j; }
256 }
257 if (best < 0) best = bestFull;
258 if (best < 0) break;
259 order.push(best);
260 for (r = 0; r < routes.length; r++) {
261 w[r][best].forEach(function (i) { covered[r][i] = 1; });
262 }
263 for (j = 0; j < cells.length; j++) {
264 if (free[j] && Math.hypot(cells[j][0] - cells[best][0], cells[j][1] - cells[best][1]) < minDist)
265 free[j] = false;
266 }
267 }
268 return order;
269 }
270
271 // players: a purchase list, each entry {type, x, y} for a new tower or
272 // {up: n} for an upgrade of the n-th tower built, with its cost
273
274 function mapSpacing(index) {
275 var mc = MM.config.maps[index], mons = MM.config.monster;
276 var interval = mc.spawn_interval !== undefined ? mc.spawn_interval : MM.config.waves.spawn_interval;
277 var sum = 0, count = 0;
278 mc.waves.forEach(function (w) {
279 for (var k in w.monsters) {
280 if (mons[k].boss) continue;
281 sum += w.monsters[k] * mons[k].speed * interval;
282 count += w.monsters[k];
283 }
284 });
285 return sum / count;
286 }
287
288 function naiveList(md, types, seed) {
289 var random = MM.util.rng(seed * 7919 + 17), picked = [], list = [], spent = 0;
290 var cfg = MM.config;
291 while (list.length < MAX_TOWERS && spent < MAX_SPENT) {
292 var type = types[list.length % types.length], def = cfg.tower[type];
293 var c = medianCells(md, def.range[0], random, 1, picked);
294 if (!c.length) break;
295 var cell = md.cells[c[0]];
296 list.push({ type: type, x: cell[0], y: cell[1], cost: def.cost[0] });
297 spent += def.cost[0];
298 }
299 return list;
300 }
301
302 function greedyList(md, index) {
303 var def = MM.config.tower.t1, dmg = def.damage, cost = def.cost, at = def.attack_time;
304 var cells = greedyCells(md, def.range[0], MAX_TOWERS);
305 var cov = md.coverage(def.range[0]), spacing = mapSpacing(index);
306 function busy(j) { return 1 - Math.exp(-cov[j] / spacing); }
307 var levels = [], list = [], next = 0, spent = 0;
308 while (spent < MAX_SPENT) {
309 var best = 0, choice = null;
310 if (next < cells.length) {
311 best = dmg[0] / at * busy(cells[next]) / cost[0];
312 choice = -1;
313 }
314 levels.forEach(function (t, n) {
315 if (t.level >= dmg.length) return;
316 var v = (dmg[t.level] - dmg[t.level - 1]) / at * busy(t.cell) / cost[t.level];
317 if (v > best) { best = v; choice = n; }
318 });
319 if (choice === null) break;
320 if (choice < 0) {
321 var cell = md.cells[cells[next]];
322 levels.push({ cell: cells[next], level: 1 });
323 list.push({ type: "t1", x: cell[0], y: cell[1], cost: cost[0] });
324 next++;
325 spent += cost[0];
326 } else {
327 var t = levels[choice];
328 list.push({ up: choice, cost: cost[t.level] });
329 spent += cost[t.level];
330 t.level++;
331 }
332 }
333 return list;
334 }
335
336 function makePlayer(name, md, index, seed) {
337 if (name === "naive") return { name: name, list: naiveList(md, ["t1"], seed), early: false };
338 if (name === "naive_t0") return { name: name, list: naiveList(md, ["t0"], seed), early: false };
339 if (name === "naive_mix") return { name: name, list: naiveList(md, ["t1", "t0"], seed), early: false };
340 if (name === "greedy") return { name: name, list: greedyList(md, index), early: true };
341 throw new Error("unknown player " + name);
342 }
343
344 // make purchase p through the game's functions. built: the towers built so
345 // far, in order. returns false when it could not be made.
346 function buy(g, p, built) {
347 if (p.up !== undefined) {
348 var t = built[p.up];
349 g.selected = null;
350 g.shop = null;
351 g.pressMap(t.x, t.y, 0);
352 if (g.selected !== t) return false;
353 var level = t.level;
354 g.upgrade();
355 g.selected = null;
356 return t.level > level;
357 }
358 if (g.shop !== p.type) g.chooseShop(p.type);
359 if (!g.movePreview(p.x, p.y) || g.preview.x !== p.x || g.preview.y !== p.y) {
360 g.shop = null;
361 g.preview = null;
362 return false;
363 }
364 var n = g.towers.length;
365 if (!g.build()) return false;
366 built.push(g.towers[n]);
367 return true;
368 }
369
370 // play
371
372 function spentOn(g) {
373 return g.towers.reduce(function (s, t) { return s + t.paid; }, 0);
374 }
375
376 // play map index with the player. returns per wave the coins on hand and
377 // the budget (coins on hand plus coins spent) at its start and the hearts
378 // lost in it, and the result.
379 function play(index, player, seed) {
380 melee = {};
381 var g = new MM.Game(index, seed, 1);
382 var built = [], k = 0, recorded = 0, rows = [], stuck = false;
383 function act() {
384 while (k < player.list.length && g.canAfford(player.list[k].cost)) {
385 if (!buy(g, player.list[k], built)) { stuck = true; break; }
386 k++;
387 }
388 }
389 while (!g.result && g.time < MAX_TIME) {
390 act();
391 if (player.early && g.waves.phase === "break") {
392 g.startEarly();
393 act();
394 }
395 if (g.waves.next !== recorded) {
396 if (rows.length) rows[rows.length - 1].lost -= g.hearts;
397 recorded = g.waves.next;
398 rows.push({ coins: g.coins, budget: g.coins + spentOn(g), towers: g.towers.length,
399 bought: k, lost: g.hearts });
400 }
401 g.step(DT);
402 }
403 if (rows.length) rows[rows.length - 1].lost -= g.hearts;
404 return { rows: rows, hearts: g.hearts, won: g.result === "won", stuck: stuck,
405 coinsEnd: g.coins, purchases: k, melee: melee };
406 }
407
408 // hearts lost in wave w (from 0) played on its own from an empty map with
409 // the first k purchases of the player
410 function waveLoss(index, player, seed, w, k) {
411 var g = new MM.Game(index, seed, w + 1), built = [];
412 g.coins = 1e9;
413 for (var i = 0; i < k; i++) {
414 if (!buy(g, player.list[i], built)) throw new Error("purchase " + i + " failed in a wave test");
415 }
416 var h = g.hearts;
417 g.startEarly();
418 // the break after the wave starts while its monsters are still on the
419 // map; it is held so the next wave does not start
420 while (!g.result && (g.waves.phase === "spawning" || g.monsters.length) && g.time < MAX_TIME) {
421 if (g.waves.phase === "break") g.waves.left = Infinity;
422 g.step(DT);
423 }
424 return h - g.hearts;
425 }
426
427 // coins of the smallest purchase prefix that holds wave w, null if none in
428 // the list does
429 function need(index, player, seed, w) {
430 var lo = 0, hi = player.list.length;
431 if (waveLoss(index, player, seed, w, hi) > 0) return null;
432 while (lo < hi) {
433 var mid = (lo + hi) >> 1;
434 if (waveLoss(index, player, seed, w, mid) === 0) hi = mid;
435 else lo = mid + 1;
436 }
437 var c = 0;
438 for (var i = 0; i < lo; i++) c += player.list[i].cost;
439 return c;
440 }
441
442 // report
443
444 function mean(v) {
445 return v.reduce(function (a, b) { return a + b; }, 0) / v.length;
446 }
447
448 function pad(s, n) {
449 s = String(s);
450 return s.length >= n ? s : " ".repeat(n - s.length) + s;
451 }
452
453 function fmt(v, d) {
454 return v === null || v === undefined || Number.isNaN(v) ? "-" : v.toFixed(d || 0);
455 }
456
457 function summary(index, name, runs) {
458 var last = runs.map(function (r) { return r.rows[r.rows.length - 1]; });
459 var needs = runs.map(function (r) { return r.need[r.need.length - 1]; });
460 var surplus = runs.map(function (r, i) {
461 return needs[i] === null || !last[i] ? null : last[i].budget - needs[i];
462 });
463 var ok = surplus.filter(function (v) { return v !== null; });
464 return {
465 map: index, player: name, seeds: runs.length,
466 won: runs.filter(function (r) { return r.won; }).length,
467 hearts: mean(runs.map(function (r) { return r.hearts; })),
468 heartsMin: Math.min.apply(null, runs.map(function (r) { return r.hearts; })),
469 heartsMax: Math.max.apply(null, runs.map(function (r) { return r.hearts; })),
470 coinsLast: mean(last.map(function (r) { return r ? r.coins : 0; })),
471 budgetLast: mean(last.map(function (r) { return r ? r.budget : 0; })),
472 needLast: ok.length ? mean(needs.filter(function (v) { return v !== null; })) : null,
473 surplus: ok.length === runs.length ? mean(ok) : null,
474 lost: runs[0].rows.map(function (_, w) {
475 return mean(runs.map(function (r) { return r.rows[w] ? r.rows[w].lost : 0; }));
476 }),
477 need: runs[0].need.map(function (_, w) {
478 var v = runs.map(function (r) { return r.need[w]; });
479 return v.indexOf(null) >= 0 || v[0] === undefined ? null : mean(v);
480 }),
481 budget: runs[0].rows.map(function (_, w) {
482 return mean(runs.map(function (r) { return r.rows[w] ? r.rows[w].budget : 0; }));
483 }),
484 stuck: runs.some(function (r) { return r.stuck; }),
485 // monsters hit per t0 attack, over all runs
486 t0Hits: (function () {
487 var a = 0, h = 0;
488 runs.forEach(function (r) { if (r.melee.t0) { a += r.melee.t0.attacks; h += r.melee.t0.hits; } });
489 return a ? h / a : null;
490 })()
491 };
492 }
493
494 function table(results, o) {
495 var lines = ["simulation, written by tools/simulate.js", "",
496 "seeds 1 to " + o.seeds + " per map and player. hearts: left at the end, mean (min to max).",
497 "coins: on hand at the start of the last wave. budget: coins on hand plus",
498 "coins spent then. need: coins of the purchases that hold the last wave",
499 "on its own. surplus: budget minus need, at the last wave. per wave: hearts",
500 "lost, mean over seeds; budget and need by wave where measured.", "",
501 "map player won hearts coins budget need surplus"];
502 results.forEach(function (s) {
503 lines.push(pad("map" + s.map, 4) + " " + (s.player + " ").slice(0, 10)
504 + pad(s.won + "/" + s.seeds, 5)
505 + pad(fmt(s.hearts, 1), 7) + " (" + s.heartsMin + " to " + s.heartsMax + ")"
506 + pad("", 13 - (" (" + s.heartsMin + " to " + s.heartsMax + ")").length)
507 + pad(fmt(s.coinsLast, 1), 7) + pad(fmt(s.budgetLast), 8) + pad(fmt(s.needLast), 7)
508 + pad(fmt(s.surplus), 9) + (s.stuck ? " (a purchase failed)" : "")
509 + (s.t0Hits !== null ? " t0 hits per attack " + fmt(s.t0Hits, 2) : ""));
510 });
511 results.forEach(function (s) {
512 lines.push("", "map" + s.map + " " + s.player + ", per wave:",
513 " lost " + s.lost.map(function (v) { return pad(fmt(v, 1), 6); }).join(""),
514 " budget " + s.budget.map(function (v) { return pad(fmt(v), 6); }).join(""),
515 " need " + s.need.map(function (v) { return pad(fmt(v), 6); }).join(""));
516 });
517 return lines;
518 }
519
520 function main() {
521 var o = options(process.argv.slice(2));
522 load(o.config, o.waves);
523 var maps = o.maps || MM.maps.map(function (_, i) { return i; });
524 var results = [];
525 maps.forEach(function (index) {
526 var md = new MapData(index);
527 var n = MM.config.maps[index].waves.length;
528 o.players.forEach(function (name) {
529 var runs = [];
530 for (var seed = 1; seed <= o.seeds; seed++) {
531 var player = makePlayer(name, md, index, seed);
532 var run = play(index, player, seed);
533 run.need = [];
534 for (var w = 0; w < n; w++) {
535 run.need.push(o.needAll || w === n - 1 ? need(index, player, seed, w) : undefined);
536 }
537 runs.push(run);
538 }
539 results.push(summary(index, name, runs));
540 });
541 });
542 if (o.json) {
543 console.log(JSON.stringify(results));
544 return;
545 }
546 var lines = table(results, o);
547 fs.mkdirSync(path.dirname(OUT), { recursive: true });
548 fs.writeFileSync(OUT, lines.join("\n") + "\n");
549 fs.writeFileSync(OUT_JSON, JSON.stringify(results, null, 1) + "\n");
550 results.forEach(function (s) {
551 console.log("map" + s.map + " " + s.player + ": won " + s.won + "/" + s.seeds + ", hearts "
552 + fmt(s.hearts, 1) + ", coins at the last wave " + fmt(s.coinsLast, 1)
553 + ", surplus " + fmt(s.surplus) + (s.player === "naive" && s.hearts > HEARTS_TARGET + 1
554 ? " (target " + HEARTS_TARGET + " hearts)" : ""));
555 });
556 console.log("simulate: wrote temp/preview/simulate.txt, simulate.json");
557 }
558
559 if (require.main === module) main();
560
561 module.exports = { options: options, load: load, MapData: MapData, greedyCells: greedyCells,
562 makePlayer: makePlayer, play: play, need: need, waveLoss: waveLoss,
563 summary: summary };