- docs/NEXT.md: where to pick up, prioritised, with the known wall-selling bug and its two-line fix - docs/review-2026-10-09/: 85 reviewer findings (touch, co-op, client code, visual, reverse proxy) with verification status, repro scripts archive and the review workflow script; nothing fixed yet by design - docs/BALANCE.md + tools/bot.js: headless balance bot and the untuned baseline (IDS Sniper dominates, maze is a near-guaranteed win, credits snowball) - test/sim.test.js derives tunable numbers from the tables, plus a shape test - README status note Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
885 lines
43 KiB
JavaScript
885 lines
43 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
/*
|
|
* NETWALL balance bot - a headless "player" that drives Sim only through sim.cmd() / sim.preview() / sim.monsterCells()
|
|
* and ticks with TD.STEP. It is a DEV TOOL (not a test): it exists to measure how the numbers in public/js/sim.js play.
|
|
*
|
|
* const { playGame } = require('./tools/bot');
|
|
* const r = playGame({ map: 'open', strategy: 'maze', maxWave: 30, seed: 1 });
|
|
* r.result -> { survivedWaves, won, livesLeft, ... } r.log -> [{ wave, lives, gold, towers, routeLen, kills, leaks, ... }]
|
|
*
|
|
* CLI (runs a matrix of games on all CPU cores and prints tables):
|
|
* node tools/bot.js --maps open,twin,hub --strategies maze,nomaze,spam-filter,lazy --seeds 6 --max 30
|
|
* node tools/bot.js --sim /path/to/other/sim.js ... (or SIM_PATH=...) to measure another copy of the sim (baselines)
|
|
* node tools/bot.js --json out.json --detail (raw results / per-game rows)
|
|
*
|
|
* Strategies: maze | nomaze | spam-filter | spam-ids | spam-mortar | spam-arc | lazy
|
|
* maze-no-<type> (ablation: the mixed maze build without one tower type, e.g. maze-no-ids)
|
|
* any of them can take overrides: "maze:share=0.6,S=1.2" (see DEFAULTS)
|
|
*
|
|
* How the "mixed" build decides (it must adapt to whatever numbers are in the TOWERS / ENEMIES tables):
|
|
* - The upcoming waves (next 3, plus a Rootkit wave up to 8 ahead) come from TD.waveSummary / TD.waveGroups and
|
|
* hpScale. Each wave entry (kind, count, scaled hp, leak value, stream spacing) is a "threat".
|
|
* - A cheap analytic model estimates how much damage the current defence deals to ONE packet of that kind during its walk
|
|
* along the traced route (time inside each tower's range, throttle slows, armour, splash / chain multipliers,
|
|
* flow-sharing when a dense stream is in range). Expected lives lost = sum threat.count * leak * (1 - min(1, dmg / (S*hp))).
|
|
* - Every candidate purchase (new tower at a site, upgrade) is scored by the reduction of that surrogate per credit.
|
|
* - The maze: greedy hill climbing on route length per credit over wall LINE segments anchored on a border / existing
|
|
* solid cell (a single wall on open ground gains almost nothing, a whole line with a gap gains a lot), only under a wall
|
|
* budget (a fraction of all credits seen so far). Turrets are placed on off-route sites with good coverage, or swapped
|
|
* for an existing wall (walls refund 100%, so a swap costs only the turret).
|
|
* - All randomness is a seeded PRNG used for per-seed "personality" (wall share, caution) and score jitter.
|
|
*/
|
|
const path = require('path');
|
|
|
|
const DEFAULT_SIM = process.env.SIM_PATH || path.join(__dirname, '..', 'public', 'js', 'sim.js');
|
|
const ALL_TYPES = ['filter', 'ids', 'mortar', 'throttle', 'arc'];
|
|
|
|
const DEFAULTS = {
|
|
maze: true, // build wall lines
|
|
types: ALL_TYPES, // turret types the bot may buy
|
|
share: 0.25, // walls may take this fraction of all credits seen so far (0.4 starves the turrets: measured worse at every difficulty)
|
|
S: 1.4, // caution: want S x hp of damage per packet
|
|
minGain: 3, // a wall segment must add at least this much route length (sum over spawns)
|
|
minTurrets: 2, // turrets before the first wall
|
|
idsStrong: false, // set IDS snipers to 'strong' targeting (off: it makes them ignore fast flyers when armoured ground units are in range)
|
|
flat: false, // 'nomaze': refuse turret sites that lengthen the route
|
|
lazy: false,
|
|
jitter: 0.12, // relative score noise
|
|
explore: 1.7, // curiosity: until exploreUntil, a type with fewer than 2 towers gets this bonus on new purchases
|
|
exploreUntil: 10,
|
|
learn: 0.5, // exponent of the damage-per-credit feedback (0 = off)
|
|
persona: true, // randomise share / S per seed
|
|
waitClear: true, // call next wave as soon as the previous is cleared (else only on the timer)
|
|
waveTimer: 0, // sim seconds after which the next wave is called anyway (0 = TD.WAVE_INTERVAL, the server's auto-wave timer)
|
|
thinkEvery: 60, // ticks between decisions during a wave (60 = once per sim second)
|
|
horizon: 6, // waves looked ahead (the wave pattern repeats every 8, a human sees it coming)
|
|
maxSegLen: 22,
|
|
gate: false, // build a wall line only when its surrogate value per credit beats the best turret purchase
|
|
kappa: 0.7,
|
|
mazeFuture: 1.5, // a maze also boosts turrets bought later
|
|
rampStart: 3, // wall budget share ramps up from this wave ...
|
|
rampLen: 6, // ... over this many waves
|
|
coreBias: 1.0, // prefer wall lines near the server (flyers end there too)
|
|
compact: 1.0, // bonus for wall lines two cells from another solid line
|
|
};
|
|
|
|
function parseStrategy(spec) {
|
|
let name = spec, over = {};
|
|
if (spec && typeof spec === 'object') { name = spec.name; over = spec; }
|
|
else if (typeof spec === 'string' && spec.indexOf(':') >= 0) {
|
|
name = spec.slice(0, spec.indexOf(':'));
|
|
for (const kv of spec.slice(spec.indexOf(':') + 1).split(',')) {
|
|
const [k, v] = kv.split('=');
|
|
over[k] = v === 'true' ? true : v === 'false' ? false : isNaN(+v) ? v : +v;
|
|
}
|
|
}
|
|
const s = Object.assign({}, DEFAULTS, { name: typeof spec === 'string' ? spec : name });
|
|
if (name === 'maze') { /* defaults */ }
|
|
else if (name === 'nomaze') { s.maze = false; s.flat = true; }
|
|
else if (name.startsWith('spam-')) { s.types = [name.slice(5)]; }
|
|
else if (name.startsWith('maze-no-')) { s.types = ALL_TYPES.filter((t) => t !== name.slice(8)); }
|
|
else if (name === 'lazy') { s.lazy = true; s.maze = false; s.waitClear = false; }
|
|
else throw new Error('unknown strategy ' + name);
|
|
for (const k of Object.keys(over)) if (k !== 'name') s[k] = over[k];
|
|
return s;
|
|
}
|
|
|
|
function prng(seed) { // mulberry32
|
|
let a = seed >>> 0;
|
|
return function () {
|
|
a = (a + 0x6D2B79F5) >>> 0;
|
|
let t = a;
|
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
};
|
|
}
|
|
|
|
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
|
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
|
|
|
|
class Bot {
|
|
constructor(TD, sim, strat, rng, ctx) {
|
|
this.TD = TD; this.sim = sim; this.s = Object.assign({}, strat); this.rng = rng;
|
|
this.maxWave = ctx.maxWave;
|
|
if (this.s.persona && !this.s.lazy) {
|
|
this.s.share *= 0.7 + 0.6 * rng();
|
|
this.s.S *= 0.85 + 0.3 * rng();
|
|
this.s.minTurrets += Math.floor(rng() * 3);
|
|
this.s.jitter *= 1 + rng();
|
|
this.typeBias = {}; // every "player" has favourites
|
|
for (const t of ALL_TYPES) this.typeBias[t] = 0.85 + 0.3 * rng();
|
|
}
|
|
this.kinds = TD.ENEMY_ORDER.map((k) => {
|
|
const d = TD.ENEMIES[k];
|
|
return { k, v: d.speed, armor: d.armor, air: !!d.air, slowRes: d.slowRes || 0, hp: d.hp, leak: d.leak };
|
|
});
|
|
this.typeBias = this.typeBias || {};
|
|
this.kindIdx = {};
|
|
this.kinds.forEach((k, i) => { this.kindIdx[k.k] = i; });
|
|
this.wallCost = TD.TOWERS.wall.levels[0].cost;
|
|
this.spentWalls = 0; this.spentOther = 0;
|
|
this.plan = [];
|
|
this.noPlanRev = -1;
|
|
this.rev = -1;
|
|
this.nSp = sim.board.spawns.length;
|
|
this.minCost = Math.min.apply(null, this.s.types.map((t) => TD.TOWERS[t].levels[0].cost));
|
|
this.lazyState = { init: false, done: {} };
|
|
this.ema = {}; this.learned = {}; this.lastD = new Map();
|
|
this.actions = 0;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ geometry cache
|
|
// ground path points (cell centres) of every spawn's traced route
|
|
pathsFromRoutes(routes) {
|
|
const b = this.sim.board;
|
|
const gx = [], gy = [], gl = [], gs = [];
|
|
const onRoute = new Uint8Array(b.cols * b.rows);
|
|
const touch = new Uint8Array(b.cols * b.rows);
|
|
routes.forEach((route, ri) => {
|
|
for (let j = 0; j < route.length; j++) {
|
|
const c = route[j], p = route[j - 1], n = route[j + 1];
|
|
let len = 0;
|
|
if (p) len += Math.hypot(c[0] - p[0], c[1] - p[1]);
|
|
if (n) len += Math.hypot(c[0] - n[0], c[1] - n[1]);
|
|
gx.push(c[0] + 0.5); gy.push(c[1] + 0.5); gl.push(len / 2); gs.push(ri);
|
|
onRoute[c[1] * b.cols + c[0]] = 1;
|
|
touch[c[1] * b.cols + c[0]] = 1;
|
|
if (n && n[0] !== c[0] && n[1] !== c[1]) { // diagonal step: both corner cells matter
|
|
touch[c[1] * b.cols + n[0]] = 1; touch[n[1] * b.cols + c[0]] = 1;
|
|
}
|
|
}
|
|
});
|
|
return { g: { x: Float64Array.from(gx), y: Float64Array.from(gy), l: Float64Array.from(gl), s: Int32Array.from(gs), n: gx.length }, onRoute, touch };
|
|
}
|
|
|
|
refresh() {
|
|
const sim = this.sim, b = sim.board;
|
|
if (this.rev === sim.rev && this.g) return;
|
|
this.rev = sim.rev;
|
|
const P = this.pathsFromRoutes(b.routes);
|
|
this.g = P.g; this.onRoute = P.onRoute; this.touch = P.touch;
|
|
if (!this.a) { // flyers go straight spawn -> core (static)
|
|
const ax = [], ay = [], al = [], as = [];
|
|
b.spawns.forEach((sp, si) => {
|
|
const x0 = sp.x + 0.5, y0 = sp.y + 0.5, x1 = b.core.x + 0.5, y1 = b.core.y + 0.5;
|
|
const d = Math.hypot(x1 - x0, y1 - y0), n = Math.max(2, Math.ceil(d / 0.25));
|
|
for (let i = 0; i <= n; i++) { ax.push(x0 + (x1 - x0) * i / n); ay.push(y0 + (y1 - y0) * i / n); al.push(d / n); as.push(si); }
|
|
});
|
|
this.a = { x: Float64Array.from(ax), y: Float64Array.from(ay), l: Float64Array.from(al), s: Int32Array.from(as), n: ax.length };
|
|
}
|
|
this.specs = this.specsNow();
|
|
}
|
|
|
|
specsNow() {
|
|
const out = [];
|
|
for (const t of this.sim.towers) {
|
|
if (t.type === 'wall') continue;
|
|
out.push({ id: t.id, type: t.type, level: t.level, x: t.x + 0.5, y: t.y + 0.5, st: this.TD.TOWERS[t.type].levels[t.level - 1] });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ threat model
|
|
entries() {
|
|
const sim = this.sim, TD = this.TD, nSp = this.nSp;
|
|
const out = [];
|
|
const add = (w, weight, onlyBoss) => {
|
|
if (w > this.maxWave) return;
|
|
const sum = TD.waveSummary(w), groups = TD.waveGroups(w);
|
|
for (const q of sum) {
|
|
if (onlyBoss && q.k !== 'rootkit') continue;
|
|
const ki = this.kindIdx[q.k], K = this.kinds[ki];
|
|
let gs = 0, gn = 0;
|
|
for (const g of groups) if (g.k === q.k) { gs += g.gap * g.c; gn += g.c; }
|
|
const g = (gn ? gs / gn : 1) * nSp; // seconds between consecutive packets on ONE route
|
|
const h = Math.round(TD.ENEMIES[q.k].hp * TD.hpScale(w));
|
|
out.push({ ki, N: q.c, Nr: Math.max(1, q.c / nSp), h, leak: K.leak, v: K.v, armor: K.armor, air: K.air, g, spacing: Math.max(0.2, K.v * g), w: weight });
|
|
}
|
|
};
|
|
const cur = sim.wave, alive = sim.monsters.length > 0 || sim.spawnQ.length > 0;
|
|
if (alive && cur >= 1) add(cur, 0.5, false);
|
|
const wts = [1.0, 0.75, 0.55, 0.42, 0.32, 0.25, 0.2, 0.15];
|
|
for (let i = 1; i <= this.s.horizon; i++) add(cur + i, wts[i - 1] || 0.15, false);
|
|
for (let w = cur + this.s.horizon + 1; w <= cur + 10; w++) if (w % 10 === 0) add(w, 0.4, true);
|
|
return out;
|
|
}
|
|
|
|
slowFields(specs, G) {
|
|
// per kind: slow factor at each path point from the throttles
|
|
const out = [];
|
|
specs = specs || this.specs; G = G || this.g;
|
|
for (let ki = 0; ki < this.kinds.length; ki++) {
|
|
const K = this.kinds[ki], P = K.air ? this.a : G;
|
|
const arr = new Float64Array(P.n);
|
|
for (const sp of specs) {
|
|
if (sp.type !== 'throttle') continue;
|
|
const r2 = sp.st.range * sp.st.range, eff = Math.min(0.6, sp.st.slow * (1 - K.slowRes));
|
|
for (let i = 0; i < P.n; i++) {
|
|
const dx = P.x[i] - sp.x, dy = P.y[i] - sp.y;
|
|
if (dx * dx + dy * dy <= r2 && eff > arr[i]) arr[i] = eff;
|
|
}
|
|
}
|
|
out.push(arr);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// damage one packet of entry e takes from tower spec sp over its whole walk (analytic model)
|
|
capSpec(sp, e, slow, G) {
|
|
if (sp.type === 'throttle') return 0;
|
|
const TD = this.TD, td = TD.TOWERS[sp.type], st = sp.st;
|
|
if (e.air ? !td.air : !td.ground) return 0;
|
|
const hit0 = Math.min(perHit(st.dmg, e.armor), e.h); // no credit for overkill
|
|
let dps = hit0 * st.rate, M = 1;
|
|
if (sp.type === 'mortar') {
|
|
dps *= 0.8;
|
|
M = clamp(1 + 2 * st.splash / e.spacing, 1, Math.max(1, e.N));
|
|
} else if (sp.type === 'arc') {
|
|
const avail = 2 * st.chainRange / e.spacing;
|
|
let tot = hit0, d = st.dmg;
|
|
for (let i = 1; i <= st.chains; i++) {
|
|
d *= st.falloff;
|
|
const q = clamp(avail - (i - 1), 0, 1) * (i <= e.N - 1 ? 1 : 0);
|
|
tot += q * Math.min(perHit(d, e.armor), e.h);
|
|
}
|
|
M = tot / hit0;
|
|
}
|
|
const P = e.air ? this.a : (G || this.g);
|
|
const r2 = st.range * st.range;
|
|
const Nr = e.Nr, flow = M * e.g;
|
|
let total = 0, T = 0, seg = -1;
|
|
const fin = () => dps * ((Nr - 1) * Math.min(T, flow) + T) / Nr;
|
|
for (let i = 0; i < P.n; i++) {
|
|
const sg = P.s[i];
|
|
if (sg !== seg) { if (T > 0) total += fin(); T = 0; seg = sg; }
|
|
const dx = P.x[i] - sp.x, dy = P.y[i] - sp.y;
|
|
if (dx * dx + dy * dy <= r2) T += P.l[i] / (e.v * (1 - (slow ? slow[i] : 0)));
|
|
else if (T > 0) { total += fin(); T = 0; }
|
|
}
|
|
if (T > 0) total += fin();
|
|
return total / this.nSp;
|
|
}
|
|
|
|
capsFor(specs, ents, slows, G) {
|
|
const caps = new Float64Array(ents.length);
|
|
for (const sp of specs) for (let i = 0; i < ents.length; i++) caps[i] += this.capSpec(sp, ents[i], slows[ents[i].ki], G);
|
|
return caps;
|
|
}
|
|
|
|
value(caps, ents) {
|
|
let v = 0;
|
|
for (let i = 0; i < ents.length; i++) {
|
|
const e = ents[i], u = caps[i] / (this.s.S * e.h);
|
|
v += e.w * e.N * e.leak * (Math.min(u, 1) + 0.08 * Math.min(u, 3));
|
|
}
|
|
return v;
|
|
}
|
|
|
|
// ------------------------------------------------------------------ turret sites
|
|
sites() {
|
|
const sim = this.sim, b = sim.board, cols = b.cols, TD = this.TD;
|
|
const res = sim.monsterCells().reserved;
|
|
const g = this.g, a = this.a;
|
|
// one coverage ranking per distinct tower range (a sniper wants a different spot than a filter)
|
|
const ranges = [];
|
|
for (const t of this.s.types) { const r = TD.TOWERS[t].levels[1] ? TD.TOWERS[t].levels[1].range : TD.TOWERS[t].levels[0].range; if (!ranges.some((q) => Math.abs(q - r) < 0.3)) ranges.push(r); }
|
|
const list = [];
|
|
for (let y = 0; y < b.rows; y++) {
|
|
for (let x = 0; x < cols; x++) {
|
|
const i = y * cols + x;
|
|
if (b.obst[i] || this.onRoute[i] || res.has(i) || b.isSpecial(x, y)) continue;
|
|
const tw = sim.towerAt[i];
|
|
if (b.solid[i] && !(tw && tw.type === 'wall')) continue;
|
|
const cx = x + 0.5, cy = y + 0.5;
|
|
const sc = ranges.map((r) => {
|
|
const r2 = r * r; let sg = 0, sa = 0;
|
|
for (let k = 0; k < g.n; k++) { const dx = g.x[k] - cx, dy = g.y[k] - cy; if (dx * dx + dy * dy <= r2) sg += g.l[k]; }
|
|
for (let k = 0; k < a.n; k++) { const dx = a.x[k] - cx, dy = a.y[k] - cy; if (dx * dx + dy * dy <= r2) sa += a.l[k]; }
|
|
return { g: sg, a: sa, c: sg + 0.5 * sa };
|
|
});
|
|
if (sc[0].c > 0 || sc[sc.length - 1].c > 0) list.push({ x, y, i, sc, wall: !!tw });
|
|
}
|
|
}
|
|
const pick = new Map();
|
|
ranges.forEach((r, ri) => {
|
|
const byC = list.slice().sort((p, q) => q.sc[ri].c - p.sc[ri].c);
|
|
const byA = list.slice().sort((p, q) => q.sc[ri].a - p.sc[ri].a);
|
|
for (const c of byC.slice(0, 9)) pick.set(c.i, c);
|
|
for (const c of byA.slice(0, 5)) pick.set(c.i, c);
|
|
});
|
|
const rest = list.filter((c) => !pick.has(c.i));
|
|
for (let k = 0; k < 6 && rest.length; k++) { const c = rest.splice(Math.floor(this.rng() * rest.length), 1)[0]; pick.set(c.i, c); }
|
|
return Array.from(pick.values());
|
|
}
|
|
|
|
jit(v) { return v * (1 + this.s.jitter * (this.rng() - 0.5) * 2); }
|
|
|
|
// best purchase (new tower or upgrade) by surrogate value per credit; null when nothing is worth it
|
|
bestOption() {
|
|
const sim = this.sim, TD = this.TD;
|
|
this.refresh();
|
|
const ents = this.entries();
|
|
if (!ents.length) return null;
|
|
const slows = this.slowFields();
|
|
const baseCaps = this.capsFor(this.specs, ents, slows);
|
|
const baseV = this.value(baseCaps, ents);
|
|
const perSpec = this.specs.map((sp) => ents.map((e) => this.capSpec(sp, e, slows[e.ki])));
|
|
const opts = [];
|
|
const consider = (o, newCaps) => {
|
|
const dv = this.value(newCaps, ents) - baseV;
|
|
o.ratio = this.jit(dv / o.cost) * (this.typeBias[o.type] || 1) * (this.learned[o.type] || 1) * (o.kind === 'new' && this.sim.wave <= this.s.exploreUntil && (this.typeCount[o.type] || 0) < 2 ? this.s.explore : 1);
|
|
o.dv = dv;
|
|
opts.push(o);
|
|
};
|
|
// upgrades
|
|
this.specs.forEach((sp, si) => {
|
|
const lv = TD.TOWERS[sp.type].levels[sp.level];
|
|
if (!lv || !this.s.types.includes(sp.type)) return;
|
|
const nsp = Object.assign({}, sp, { st: lv, level: sp.level + 1 });
|
|
let nc;
|
|
if (sp.type === 'throttle') {
|
|
const specs2 = this.specs.map((q, j) => (j === si ? nsp : q));
|
|
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
|
} else {
|
|
nc = Float64Array.from(baseCaps);
|
|
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]) - perSpec[si][i];
|
|
}
|
|
consider({ kind: 'up', id: sp.id, type: sp.type, cost: lv.cost }, nc);
|
|
});
|
|
// new towers
|
|
const sites = this.sites();
|
|
this.typeCount = {};
|
|
for (const sp of this.specs) this.typeCount[sp.type] = (this.typeCount[sp.type] || 0) + 1;
|
|
for (const type of this.s.types) {
|
|
const lv = TD.TOWERS[type].levels[0];
|
|
const sl = type === 'throttle' ? sites.filter((q, ix) => ix % 3 === 0) : sites; // throttle evaluation is the expensive one
|
|
for (const site of sl) {
|
|
const nsp = { type, level: 1, x: site.x + 0.5, y: site.y + 0.5, st: lv };
|
|
let nc;
|
|
if (type === 'throttle') {
|
|
const specs2 = this.specs.concat([nsp]);
|
|
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
|
} else {
|
|
nc = Float64Array.from(baseCaps);
|
|
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]);
|
|
}
|
|
consider({ kind: 'new', type, x: site.x, y: site.y, wall: site.wall, cost: lv.cost }, nc);
|
|
}
|
|
}
|
|
return opts;
|
|
}
|
|
|
|
slowFieldsFor(specs) { return this.slowFields(specs, this.g); }
|
|
|
|
buyBest() {
|
|
const sim = this.sim;
|
|
if (sim.gold < Math.max(this.minCost, this.waitCost || 0)) return false;
|
|
this.waitCost = 0;
|
|
let opts = this.bestOption();
|
|
if (!opts || !opts.length) return false;
|
|
opts.sort((p, q) => q.ratio - p.ratio);
|
|
const best = opts[0];
|
|
if (!(best.ratio > 0)) return false;
|
|
this.waitCost = Math.min(best.cost, ...opts.filter((o) => o.ratio >= 0.6 * best.ratio).map((o) => o.cost));
|
|
let pick = null;
|
|
for (const o of opts) {
|
|
if (o.ratio <= 0) break;
|
|
if (o.cost > sim.gold) continue;
|
|
if (this.s.flat && o.kind === 'new' && !o.wall) {
|
|
const p = sim.preview(o.x, o.y, false);
|
|
if (!p.ok || p.after - p.before > 0.5 * this.nSp) continue;
|
|
}
|
|
pick = o; break;
|
|
}
|
|
if (!pick) return false;
|
|
if (pick.ratio < 0.6 * best.ratio && pick !== best) return false; // rather save for the clearly better option
|
|
return this.exec(pick);
|
|
}
|
|
|
|
exec(o) {
|
|
const sim = this.sim;
|
|
this.waitCost = 0;
|
|
if (o.kind === 'up') {
|
|
const r = sim.cmd({ c: 'upgrade', id: o.id });
|
|
if (r.ok) { this.spentOther += o.cost; this.actions++; }
|
|
return r.ok;
|
|
}
|
|
if (o.wall) { // swap an existing wall for the turret (walls refund 100%)
|
|
const t = sim.towerAt[o.y * sim.board.cols + o.x];
|
|
if (!t || t.type !== 'wall' || sim.gold + this.wallCost < o.cost) return false;
|
|
const s = sim.cmd({ c: 'sell', id: t.id });
|
|
if (!s.ok) return false;
|
|
this.spentWalls -= this.wallCost;
|
|
const r = sim.cmd({ c: 'place', type: o.type, x: o.x, y: o.y, by: 0 });
|
|
if (!r.ok) {
|
|
const back = sim.cmd({ c: 'place', type: 'wall', x: o.x, y: o.y, by: 0 });
|
|
if (back.ok) this.spentWalls += this.wallCost;
|
|
return false;
|
|
}
|
|
this.spentOther += o.cost; this.actions++;
|
|
this.afterPlace(r.id, o.type);
|
|
return true;
|
|
}
|
|
const r = sim.cmd({ c: 'place', type: o.type, x: o.x, y: o.y, by: 0 });
|
|
if (!r.ok) return false;
|
|
this.spentOther += o.cost; this.actions++;
|
|
this.afterPlace(r.id, o.type);
|
|
return true;
|
|
}
|
|
|
|
afterPlace(id, type) {
|
|
if (type === 'ids' && this.s.idsStrong) this.sim.cmd({ c: 'target', id, mode: 'strong' });
|
|
}
|
|
|
|
// ------------------------------------------------------------------ the maze
|
|
turretCount() { let n = 0; for (const t of this.sim.towers) if (t.type !== 'wall') n++; return n; }
|
|
wallCount() { let n = 0; for (const t of this.sim.towers) if (t.type === 'wall') n++; return n; }
|
|
|
|
wallBudget() {
|
|
const total = this.spentWalls + this.spentOther + this.sim.gold;
|
|
const ramp = clamp((this.sim.wave - this.s.rampStart) / this.s.rampLen, 0, 1); // early waves are cheap to hold; the maze can wait
|
|
return this.s.share * ramp * total + 10 * (ramp > 0 ? 1 : 0) - this.spentWalls;
|
|
}
|
|
|
|
// greedy hill climb: the wall line segment with the best route-length gain per credit that we can afford under the budget
|
|
bestSegment(maxCells) {
|
|
const TD = this.TD, sim = this.sim, b = sim.board, cols = b.cols, rows = b.rows;
|
|
this.refresh();
|
|
const mc = sim.monsterCells();
|
|
const solid = Uint8Array.from(b.solid);
|
|
const base = b.routeLen;
|
|
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
|
|
const cands = [];
|
|
const maxL = Math.min(this.s.maxSegLen, maxCells);
|
|
for (let y = 0; y < rows; y++) {
|
|
for (let x = 0; x < cols; x++) {
|
|
const i0 = y * cols + x;
|
|
if (solid[i0] || b.isSpecial(x, y) || mc.reserved.has(i0)) continue;
|
|
for (const d of dirs) {
|
|
const bx = x - d[0], by = y - d[1];
|
|
if (!(bx < 0 || by < 0 || bx >= cols || by >= rows || solid[by * cols + bx])) continue; // anchored start only
|
|
let cx = x, cy = y, touched = false;
|
|
const added = [];
|
|
let bestL = null;
|
|
for (let l = 1; l <= maxL; l++) {
|
|
if (cx < 0 || cy < 0 || cx >= cols || cy >= rows) break;
|
|
const ci = cy * cols + cx;
|
|
if (solid[ci] || b.isSpecial(cx, cy) || mc.reserved.has(ci)) break;
|
|
solid[ci] = 1; added.push(ci);
|
|
if (this.touch[ci]) touched = true;
|
|
if (touched) {
|
|
const f = TD.buildField(cols, rows, solid, b.coreIdx);
|
|
let blocked = false, after = 0;
|
|
for (const sp of b.spawns) { const v = f[sp.y * cols + sp.x]; if (!isFinite(v)) { blocked = true; break; } after += v; }
|
|
if (!blocked) for (const m of mc.must) if (!isFinite(f[m])) { blocked = true; break; }
|
|
if (blocked) break;
|
|
const gain = after - base;
|
|
const ratio = gain / (this.wallCost * l);
|
|
if (gain >= this.s.minGain && (!bestL || ratio > bestL.ratio * 1.001)) bestL = { l, gain, ratio };
|
|
}
|
|
cx += d[0]; cy += d[1];
|
|
}
|
|
for (const ci of added) solid[ci] = 0;
|
|
if (bestL) {
|
|
// compactness: a tight serpentine (parallel lines two cells apart) puts every turret next to several corridors
|
|
let comp = 0;
|
|
const px = d[1], py = d[0]; // perpendicular
|
|
for (let k = 0; k < bestL.l; k++) {
|
|
const qx = x + d[0] * k, qy = y + d[1] * k;
|
|
for (const sgn of [1, -1]) {
|
|
const ox = qx + sgn * px * 2, oy = qy + sgn * py * 2, mx = qx + sgn * px, my = qy + sgn * py;
|
|
const outside = ox < 0 || oy < 0 || ox >= cols || oy >= rows;
|
|
const wallThere = outside || solid[oy * cols + ox];
|
|
const midFree = mx >= 0 && my >= 0 && mx < cols && my < rows && !solid[my * cols + mx];
|
|
if (wallThere && midFree) { comp++; break; }
|
|
}
|
|
}
|
|
const mx = x + d[0] * (bestL.l - 1) / 2 + 0.5, my = y + d[1] * (bestL.l - 1) / 2 + 0.5;
|
|
const near = 1 - clamp(Math.hypot(mx - b.core.x - 0.5, my - b.core.y - 0.5) / 18, 0, 1); // keep the maze where the flight line ends too
|
|
cands.push({ x, y, d, l: bestL.l, gain: bestL.gain, ratio: bestL.ratio * (1 + this.s.compact * comp / bestL.l) * (1 + this.s.coreBias * near), len: bestL.ratio });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (!cands.length) return null;
|
|
cands.sort((p, q) => q.ratio - p.ratio);
|
|
// turret awareness: a segment that drags the route away from the existing turrets is worth less
|
|
let pool = cands.slice(0, 8);
|
|
if (this.specs.length) {
|
|
const ents = this.entries();
|
|
if (ents.length) {
|
|
const J0 = this.value(this.capsFor(this.specs, ents, this.slowFields(), this.g), ents);
|
|
for (const c of pool) {
|
|
const sl = Uint8Array.from(b.solid);
|
|
for (let k = 0; k < c.l; k++) sl[(c.y + c.d[1] * k) * cols + c.x + c.d[0] * k] = 1;
|
|
const f = TD.buildField(cols, rows, sl, b.coreIdx);
|
|
const routes = b.spawns.map((sp) => TD.traceRoute(cols, rows, sl, f, sp.x, sp.y));
|
|
const P = this.pathsFromRoutes(routes);
|
|
const J1 = this.value(this.capsFor(this.specs, ents, this.slowFields(this.specs, P.g), P.g), ents);
|
|
c.dJ = J1 - J0;
|
|
c.ret = J0 > 0 ? J1 / J0 : 1;
|
|
c.score = c.ratio * Math.min(c.ret, 1.3) * (c.ret < 0.8 ? 0.3 : 1);
|
|
}
|
|
} else pool.forEach((c) => { c.score = c.ratio; });
|
|
} else pool.forEach((c) => { c.score = c.ratio; });
|
|
pool.sort((p, q) => q.score - p.score);
|
|
const top = pool[0].score;
|
|
if (!(top > 0)) return null;
|
|
const near = pool.filter((c) => c.score >= top * 0.94);
|
|
const c = near[Math.floor(this.rng() * near.length)];
|
|
const cells = [];
|
|
for (let k = 0; k < c.l; k++) cells.push([c.x + c.d[0] * k, c.y + c.d[1] * k]);
|
|
return { cells, dJr: (c.dJ || 0) / (this.wallCost * c.l) };
|
|
}
|
|
|
|
wallStep() {
|
|
const sim = this.sim;
|
|
if (!this.plan.length) {
|
|
if (this.noPlanRev === sim.rev) return 0;
|
|
if (this.wallBudget() < this.wallCost || sim.gold < this.wallCost) return 0;
|
|
const seg = this.bestSegment(this.s.maxSegLen);
|
|
if (!seg) { this.noPlanRev = sim.rev; return 0; }
|
|
if (this.s.gate) {
|
|
// is a wall line worth more per credit than the best turret purchase right now?
|
|
const opts = this.bestOption() || [];
|
|
let bt = 0;
|
|
for (const o of opts) if (o.ratio > bt) bt = o.ratio;
|
|
if (seg.dJr * this.s.mazeFuture < this.s.kappa * bt) { this.noPlanRev = sim.rev; return 0; }
|
|
}
|
|
this.plan = seg.cells;
|
|
}
|
|
let placed = 0;
|
|
// walls are built incrementally as the wall budget (a share of all credits) and gold allow; a half-built line costs nothing but idle credits
|
|
while (this.plan.length && sim.gold >= this.wallCost && this.wallBudget() >= this.wallCost) {
|
|
const [x, y] = this.plan[0];
|
|
const r = sim.cmd({ c: 'place', type: 'wall', x, y, by: 0 });
|
|
if (r.ok) { placed++; this.spentWalls += this.wallCost; this.plan.shift(); }
|
|
else if (r.reason === 'gold') break;
|
|
else if (r.reason === 'monster') break; // retry later
|
|
else if (r.reason === 'occupied') this.plan.shift();
|
|
else { this.plan = []; break; }
|
|
}
|
|
if (placed) this.actions++;
|
|
return placed;
|
|
}
|
|
|
|
// sell a turret that covers none of the route / flight line any more (e.g. the maze moved the route away)
|
|
prune() {
|
|
const sim = this.sim;
|
|
this.refresh();
|
|
let sold = 0;
|
|
for (const sp of this.specs) {
|
|
if (sp.level > 1) continue;
|
|
const r2 = sp.st.range * sp.st.range;
|
|
let hit = false;
|
|
for (let i = 0; i < this.g.n && !hit; i++) { const dx = this.g.x[i] - sp.x, dy = this.g.y[i] - sp.y; if (dx * dx + dy * dy <= r2) hit = true; }
|
|
for (let i = 0; i < this.a.n && !hit; i++) { const dx = this.a.x[i] - sp.x, dy = this.a.y[i] - sp.y; if (dx * dx + dy * dy <= r2) hit = true; }
|
|
if (!hit) { const r = sim.cmd({ c: 'sell', id: sp.id }); if (r.ok) { sold++; this.spentOther -= r.refund; } }
|
|
}
|
|
return sold;
|
|
}
|
|
|
|
// A human watches the damage counters on the towers and buys more of what visibly works. Per wave: damage dealt per credit
|
|
// invested, per tower type (exponential average); the types that beat the average get a bonus on their purchase score.
|
|
learn() {
|
|
if (!this.s.learn) return;
|
|
const acc = {};
|
|
for (const t of this.sim.towers) {
|
|
if (t.type === 'wall' || t.type === 'throttle') continue;
|
|
const prev = this.lastD.get(t.id);
|
|
if (prev !== undefined) { const a = acc[t.type] || (acc[t.type] = { d: 0, c: 0 }); a.d += t.dealt - prev.d; a.c += prev.spent; }
|
|
this.lastD.set(t.id, { d: t.dealt, spent: t.spent });
|
|
}
|
|
for (const k of Object.keys(acc)) {
|
|
if (acc[k].c < 40) continue;
|
|
const e = acc[k].d / acc[k].c;
|
|
this.ema[k] = this.ema[k] === undefined ? e : 0.6 * this.ema[k] + 0.4 * e;
|
|
}
|
|
const ks = Object.keys(this.ema).filter((k) => this.ema[k] > 0);
|
|
if (ks.length < 2) return;
|
|
let lg = 0; for (const k of ks) lg += Math.log(this.ema[k]);
|
|
const gm = Math.exp(lg / ks.length);
|
|
for (const k of ks) this.learned[k] = clamp(Math.pow(this.ema[k] / gm, this.s.learn), 0.5, 2.5);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ the lazy player
|
|
nearRoute(type, routeIdx) {
|
|
const sim = this.sim, b = sim.board;
|
|
this.refresh();
|
|
const route = b.routes[0];
|
|
const c = route[Math.min(route.length - 2, routeIdx)];
|
|
const res = sim.monsterCells().reserved;
|
|
for (let ring = 1; ring <= 3; ring++) {
|
|
for (let dy = -ring; dy <= ring; dy++) for (let dx = -ring; dx <= ring; dx++) {
|
|
const x = c[0] + dx, y = c[1] + dy;
|
|
if (!b.inBounds(x, y)) continue;
|
|
const i = y * b.cols + x;
|
|
if (b.solid[i] || this.onRoute[i] || res.has(i) || b.isSpecial(x, y)) continue;
|
|
const r = sim.cmd({ c: 'place', type, x, y, by: 0 });
|
|
if (r.ok) { this.actions++; return true; }
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
lazyThink() {
|
|
const sim = this.sim, TD = this.TD, ls = this.lazyState;
|
|
if (!ls.init) {
|
|
ls.init = true;
|
|
let k = 0;
|
|
while (sim.gold >= TD.TOWERS.filter.levels[0].cost && k < 4) { this.nearRoute('filter', 6 + 5 * k); k++; }
|
|
return;
|
|
}
|
|
if (sim.wave > 0 && sim.wave % 6 === 0 && !ls.done[sim.wave]) {
|
|
ls.done[sim.wave] = true;
|
|
let guard = 0;
|
|
while (guard++ < 4) { // a few clicks: upgrade the oldest tower that can be upgraded, else a filter
|
|
const t = sim.towers.find((q) => q.type !== 'wall' && TD.TOWERS[q.type].levels[q.level]);
|
|
if (t && sim.gold >= TD.TOWERS[t.type].levels[t.level].cost) sim.cmd({ c: 'upgrade', id: t.id });
|
|
else if (sim.gold >= TD.TOWERS.ids.levels[0].cost) this.nearRoute('ids', 10 + 4 * guard);
|
|
else break;
|
|
this.actions++;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ one round of decisions
|
|
think(maxActions) {
|
|
if (this.s.lazy) { this.lazyThink(); return; }
|
|
let n = 0;
|
|
if (this.s.maze && this.sim.rev !== this.prunedRev) { this.prune(); this.prunedRev = this.sim.rev; }
|
|
while (n++ < (maxActions || 40)) {
|
|
let did = false;
|
|
if (this.s.maze && this.turretCount() >= this.s.minTurrets) did = this.wallStep() > 0;
|
|
if (!did) did = this.buyBest();
|
|
if (!did) break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------- the game driver
|
|
function playGame(opts) {
|
|
opts = opts || {};
|
|
const TD = require(opts.simPath || DEFAULT_SIM);
|
|
const strat = parseStrategy(opts.strategy || 'maze');
|
|
const seed = opts.seed === undefined ? 1 : opts.seed;
|
|
const rng = prng(seed * 7919 + 13);
|
|
const maxWave = opts.maxWave || 30;
|
|
const simOpts = { map: opts.map || 'open', events: false };
|
|
if (opts.startGold !== undefined) simOpts.gold = opts.startGold;
|
|
if (opts.lives !== undefined) simOpts.lives = opts.lives;
|
|
const sim = new TD.Sim(simOpts);
|
|
if (!strat.waveTimer) strat.waveTimer = TD.WAVE_INTERVAL;
|
|
const bot = new Bot(TD, sim, strat, rng, { maxWave });
|
|
|
|
// instrumentation (does not change the sim's behaviour)
|
|
const leakByKind = {};
|
|
const origLeak = sim.leak;
|
|
sim.leak = function (m) { leakByKind[m.kind] = (leakByKind[m.kind] || 0) + m.leak; return origLeak.call(this, m); };
|
|
|
|
const log = [];
|
|
const anomalies = [];
|
|
const births = new Map();
|
|
let bonusesPaid = 0, lastBonus = 0, waveT0 = -1e9, waveStart = null, won = false;
|
|
let bossLeaks = 0;
|
|
const wallTime = Date.now();
|
|
|
|
const snapshot = (w) => {
|
|
const types = {};
|
|
let walls = 0;
|
|
for (const t of sim.towers) { if (t.type === 'wall') walls++; else types[t.type] = (types[t.type] || 0) + 1; }
|
|
return { wave: w, lives: sim.lives, gold: sim.gold, towers: sim.towers.length - walls, walls, types, routeLen: Math.round(sim.board.routeLen * 10) / 10,
|
|
kills: sim.kills, leaks: sim.leaks, time: Math.round(sim.time), alive: sim.monsters.length, spentWalls: bot.spentWalls, spentOther: bot.spentOther };
|
|
};
|
|
const closeWave = () => {
|
|
if (!waveStart) return;
|
|
const s = snapshot(waveStart.wave);
|
|
s.waveKills = sim.kills - waveStart.kills; s.waveLeaks = sim.leaks - waveStart.leaks;
|
|
s.lifeLoss = waveStart.lives - sim.lives; s.goldBefore = waveStart.gold;
|
|
s.bonuses = bonusesPaid;
|
|
log.push(s);
|
|
waveStart = null;
|
|
};
|
|
|
|
bot.think(60);
|
|
let tick = 0;
|
|
const hardLimit = (maxWave * 140 + 900);
|
|
for (;;) {
|
|
if (sim.state === 'lost') break;
|
|
if (sim.state === 'won') {
|
|
won = true;
|
|
if (maxWave > sim.wave && opts.continueAfterWin !== false) sim.cmd({ c: 'continue' });
|
|
else break;
|
|
}
|
|
const inWave = sim.monsters.length > 0 || sim.spawnQ.length > 0;
|
|
if (!inWave && sim.wave >= maxWave) break;
|
|
if (sim.wave < maxWave && sim.wave < sim.winWave && ((!inWave && (strat.waitClear || sim.time - waveT0 >= strat.waveTimer)) || sim.time - waveT0 >= strat.waveTimer)) {
|
|
closeWave();
|
|
bot.waitCost = 0;
|
|
bot.learn();
|
|
bot.think(60);
|
|
if (opts.onWave) opts.onWave(bot, sim);
|
|
const gBefore = sim.gold, lBefore = sim.lives;
|
|
sim.cmd({ c: 'wave' });
|
|
waveT0 = sim.time;
|
|
waveStart = { wave: sim.wave, kills: sim.kills, leaks: sim.leaks, gold: gBefore, lives: lBefore };
|
|
}
|
|
sim.tick(TD.STEP); tick++;
|
|
if (sim.bonusWave !== lastBonus) { bonusesPaid++; lastBonus = sim.bonusWave; }
|
|
if (tick % strat.thinkEvery === 0) {
|
|
if (inWave && sim.gold >= Math.max(bot.minCost, bot.waitCost || 0)) bot.think(3);
|
|
if (tick % 600 === 0) { // stuck-monster watchdog
|
|
for (const m of sim.monsters) {
|
|
if (!births.has(m.id)) births.set(m.id, sim.time);
|
|
else if (sim.time - births.get(m.id) > 1500 && anomalies.length < 5) anomalies.push('monster ' + m.kind + '#' + m.id + ' alive for ' + Math.round(sim.time - births.get(m.id)) + 's at wave ' + sim.wave);
|
|
}
|
|
}
|
|
}
|
|
if (sim.time > hardLimit) { anomalies.push('time limit hit at wave ' + sim.wave); break; }
|
|
}
|
|
closeWave();
|
|
if (sim.state === 'lost' && log.length) { log[log.length - 1].lives = 0; }
|
|
const lost = sim.state === 'lost';
|
|
const result = {
|
|
survivedWaves: lost ? Math.max(0, sim.wave - 1) : sim.bonusWave,
|
|
won, lost, livesLeft: sim.lives, diedAtWave: lost ? sim.wave : 0, finalWave: sim.wave,
|
|
leaks: sim.leaks, kills: sim.kills, leakByKind, actions: bot.actions, bonusesPaid,
|
|
wallsBuilt: bot.wallCount(), spentWalls: bot.spentWalls, spentOther: bot.spentOther, goldEnd: sim.gold,
|
|
simSeconds: Math.round(sim.time), wallMs: Date.now() - wallTime, anomalies,
|
|
dealt: dealtByType(sim), towers: snapshot(sim.wave).types, routeLenEnd: snapshot(sim.wave).routeLen,
|
|
};
|
|
return { log, result, map: simOpts.map, strategy: strat.name, seed };
|
|
}
|
|
|
|
function dealtByType(sim) {
|
|
const o = {};
|
|
for (const t of sim.towers) if (t.type !== 'wall') o[t.type] = Math.round((o[t.type] || 0) + t.dealt);
|
|
return o;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------- CLI: matrix runner + tables
|
|
function parseArgs(argv) {
|
|
const a = { maps: ['open', 'twin', 'hub'], strategies: ['maze', 'nomaze', 'spam-filter', 'spam-ids', 'spam-mortar', 'spam-arc', 'lazy'],
|
|
seeds: 6, max: 30, jobs: Math.max(1, require('os').cpus().length), sim: null, json: null, detail: false, verbose: false, seedStart: 1, startGold: undefined };
|
|
for (let i = 2; i < argv.length; i++) {
|
|
const k = argv[i];
|
|
const next = () => argv[++i];
|
|
if (k === '--maps') a.maps = next().split(',');
|
|
else if (k === '--strategies') { const v = next(); a.strategies = v.indexOf(';') >= 0 || v.indexOf(':') >= 0 ? v.split(';') : v.split(','); } // use ';' between strategies that carry :k=v,k=v overrides
|
|
else if (k === '--seeds') a.seeds = +next();
|
|
else if (k === '--seed-start') a.seedStart = +next();
|
|
else if (k === '--max') a.max = +next();
|
|
else if (k === '--jobs') a.jobs = +next();
|
|
else if (k === '--sim') a.sim = path.resolve(next());
|
|
else if (k === '--json') a.json = next();
|
|
else if (k === '--gold') a.startGold = +next();
|
|
else if (k === '--detail') a.detail = true;
|
|
else if (k === '--verbose') a.verbose = true;
|
|
}
|
|
return a;
|
|
}
|
|
|
|
const mean = (xs) => (xs.length ? xs.reduce((s, v) => s + v, 0) / xs.length : 0);
|
|
const pad = (v, n) => String(v).padStart(n);
|
|
const padr = (v, n) => String(v).padEnd(n);
|
|
function logAt(r, w) { let best = null; for (const e of r.log) if (e.wave <= w) best = e; return best; }
|
|
|
|
function printTables(results, a) {
|
|
const maps = a.maps, strats = a.strategies;
|
|
for (const map of maps) {
|
|
console.log('\n=== map ' + map + ' (' + a.seeds + ' seeds, up to wave ' + a.max + ') ===');
|
|
console.log(padr('strategy', 16) + pad('win', 6) + pad('surv', 7) + pad('min-max', 9) + pad('lives', 7) + pad('leaks', 7) + pad('gold@5', 8) + pad('gold@10', 8) + pad('gold@15', 8) + pad('gold@20', 8) + pad('gold@30', 8) + pad('rt@10', 7) + pad('rt@20', 7) + pad('rt@30', 7) + pad('twr@20', 7) + pad('walls', 6) + pad('actions', 8));
|
|
for (const st of strats) {
|
|
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
|
if (!rs.length) continue;
|
|
const surv = rs.map((r) => r.result.survivedWaves);
|
|
const g = (w, f) => { const v = rs.map((r) => logAt(r, w)).filter(Boolean).map(f); return v.length ? Math.round(mean(v)) : '-'; };
|
|
console.log(padr(st, 16) + pad(rs.filter((r) => r.result.won).length + '/' + rs.length, 6) + pad(mean(surv).toFixed(1), 7) + pad(Math.min(...surv) + '-' + Math.max(...surv), 9)
|
|
+ pad(mean(rs.map((r) => r.result.livesLeft)).toFixed(1), 7) + pad(mean(rs.map((r) => r.result.leaks)).toFixed(0), 7)
|
|
+ pad(g(5, (e) => e.gold), 8) + pad(g(10, (e) => e.gold), 8) + pad(g(15, (e) => e.gold), 8) + pad(g(20, (e) => e.gold), 8) + pad(g(30, (e) => e.gold), 8)
|
|
+ pad(g(10, (e) => e.routeLen), 7) + pad(g(20, (e) => e.routeLen), 7) + pad(g(30, (e) => e.routeLen), 7) + pad(g(20, (e) => e.towers), 7)
|
|
+ pad(Math.round(mean(rs.map((r) => r.result.wallsBuilt))), 6) + pad(Math.round(mean(rs.map((r) => r.result.actions))), 8));
|
|
}
|
|
}
|
|
// where do games end?
|
|
console.log('\n--- death waves (wave in which the game was lost; "W" = reached the end) ---');
|
|
for (const map of maps) for (const st of strats) {
|
|
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
|
if (!rs.length) continue;
|
|
console.log(padr(map, 6) + padr(st, 16) + rs.map((r) => (r.result.lost ? pad(r.result.diedAtWave, 3) : pad(r.result.won ? 'W' + (r.result.finalWave > 30 ? r.result.finalWave : '') : 'ok', 3))).join(' '));
|
|
}
|
|
// tower mix of mixed builds
|
|
console.log('\n--- average final tower mix (maze strategies) ---');
|
|
for (const map of maps) for (const st of strats) {
|
|
if (!/^maze/.test(st)) continue;
|
|
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
|
if (!rs.length) continue;
|
|
const mix = {};
|
|
for (const r of rs) for (const k of Object.keys(r.result.towers)) mix[k] = (mix[k] || 0) + r.result.towers[k] / rs.length;
|
|
const dealt = {};
|
|
let tot = 0;
|
|
for (const r of rs) for (const k of Object.keys(r.result.dealt)) { dealt[k] = (dealt[k] || 0) + r.result.dealt[k]; tot += r.result.dealt[k]; }
|
|
console.log(padr(map, 6) + padr(st, 16) + Object.keys(mix).map((k) => k + ' ' + mix[k].toFixed(1) + ' (' + Math.round(100 * (dealt[k] || 0) / Math.max(1, tot)) + '%dmg)').join(' '));
|
|
}
|
|
// leak sources
|
|
console.log('\n--- lives lost by packet kind (sum over seeds) ---');
|
|
for (const map of maps) for (const st of strats) {
|
|
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
|
if (!rs.length) continue;
|
|
const lk = {};
|
|
for (const r of rs) for (const k of Object.keys(r.result.leakByKind)) lk[k] = (lk[k] || 0) + r.result.leakByKind[k];
|
|
console.log(padr(map, 6) + padr(st, 16) + Object.keys(lk).map((k) => k + ' ' + lk[k]).join(' '));
|
|
}
|
|
const an = results.filter((r) => r.result.anomalies.length);
|
|
if (an.length) { console.log('\n--- ANOMALIES ---'); for (const r of an) console.log(r.map, r.strategy, r.seed, r.result.anomalies.join('; ')); }
|
|
}
|
|
|
|
function printDetail(results) {
|
|
for (const r of results) {
|
|
console.log('\n## ' + r.map + ' ' + r.strategy + ' seed ' + r.seed + ' -> ' + JSON.stringify(r.result));
|
|
console.log('wave lives gold twr walls route kills leaks wKills wLeaks time mix');
|
|
for (const e of r.log) console.log(pad(e.wave, 4) + pad(e.lives, 6) + pad(e.gold, 6) + pad(e.towers, 4) + pad(e.walls, 5) + pad(e.routeLen, 7) + pad(e.kills, 6) + pad(e.leaks, 6) + pad(e.waveKills, 7) + pad(e.waveLeaks, 7) + pad(e.time, 6) + ' ' + JSON.stringify(e.types));
|
|
}
|
|
}
|
|
|
|
function main() {
|
|
const a = parseArgs(process.argv);
|
|
const jobs = [];
|
|
for (const map of a.maps) for (const strategy of a.strategies) for (let s = 0; s < a.seeds; s++) jobs.push({ map, strategy, seed: a.seedStart + s, maxWave: a.max, simPath: a.sim || undefined, startGold: a.startGold });
|
|
const { fork } = require('child_process');
|
|
const results = [];
|
|
let next = 0, running = 0, done = 0;
|
|
const t0 = Date.now();
|
|
const startOne = () => {
|
|
if (next >= jobs.length) return;
|
|
const job = jobs[next++];
|
|
running++;
|
|
const child = fork(__filename, ['--worker'], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'] });
|
|
child.on('message', (m) => {
|
|
results.push(m);
|
|
done++;
|
|
if (a.verbose) process.stderr.write('[' + done + '/' + jobs.length + '] ' + m.map + ' ' + m.strategy + ' s' + m.seed + ' surv=' + m.result.survivedWaves + ' ' + m.result.wallMs + 'ms\n');
|
|
child.kill();
|
|
});
|
|
child.on('exit', () => { running--; if (next < jobs.length) startOne(); else if (!running) finish(); });
|
|
child.send(job);
|
|
};
|
|
const finish = () => {
|
|
results.sort((p, q) => (p.map + p.strategy + String(1000 + p.seed)).localeCompare(q.map + q.strategy + String(1000 + q.seed)));
|
|
if (a.json) require('fs').writeFileSync(a.json, JSON.stringify(results));
|
|
printTables(results, a);
|
|
if (a.detail) printDetail(results);
|
|
console.log('\n(' + jobs.length + ' games, ' + ((Date.now() - t0) / 1000).toFixed(0) + ' s wall clock, sim=' + (a.sim || DEFAULT_SIM) + ')');
|
|
};
|
|
for (let i = 0; i < Math.min(a.jobs, jobs.length); i++) startOne();
|
|
}
|
|
|
|
if (require.main === module) {
|
|
if (process.argv.includes('--worker')) {
|
|
process.on('message', (job) => { process.send(playGame(job)); });
|
|
} else main();
|
|
}
|
|
|
|
module.exports = { playGame, parseStrategy, Bot, prng, DEFAULTS };
|