Difficulty picker (Easy/Normal/Hard) and a balance pass

Difficulty:
- TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated
  create-room / newgame option, state carries it; solo menu picker and co-op lobby
  picker (44px segmented control, reachable on every layout), HUD/room/end-screen
  labels, best-wave record per map AND difficulty (Normal keeps the legacy key),
  Play again keeps the running game's difficulty for host and guest

Balance (12 bot runs, deterministic, 48/48 games replay identically in QA):
- Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open
- credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling
  eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at
  wave 30: 1309 -> 335
- IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only
  dies by wave 7); Mortar, Arc and Filter buffed
- Orbital Uplink price step per owned unit 30% (buy and upgrade)
- remaining imbalances documented in docs/BALANCE.md

Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix
reachability of the picker. 156 unit tests, 17 e2e scenarios.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
Claude 2026-10-10 23:41:21 +00:00
parent 28502984ec
commit b4ae6cb57d
19 changed files with 1348 additions and 156 deletions

View file

@ -12,9 +12,11 @@
* 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)
* a strategy can name a game difficulty after '@' and the only maps it runs on after '#': --strategies maze,maze@easy#open,maze@hard#open+twin (default: normal)
*
* 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)
* full (the mixed build plus Sandbox, Load Balancer and Orbital Uplink) | maze+<type> (the mixed build plus one of those)
* 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):
@ -34,6 +36,7 @@ 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 EXTRA_TYPES = ['sandbox', 'balancer', 'uplink']; // bought only by the 'full' / 'maze+<type>' strategies (the older matrices never had them)
const DEFAULTS = {
maze: true, // build wall lines
@ -62,6 +65,9 @@ const DEFAULTS = {
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
uplinkFrom: 0, // from this wave on, a bot that may buy the Orbital Uplink SAVES for it (stops buying anything else until it can pay); 0 = never saves
uplinkLevel: 2, // ... and for the upgrades of the Uplinks it owns, up to this level
uplinkMax: 1, // ... and for this many Uplinks
};
function parseStrategy(spec) {
@ -79,6 +85,8 @@ function parseStrategy(spec) {
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 === 'full') { s.types = ALL_TYPES.concat(EXTRA_TYPES); s.uplinkFrom = 16; }
else if (name.startsWith('maze+')) { s.types = ALL_TYPES.concat([name.slice(5)]); if (name.slice(5) === 'uplink') s.uplinkFrom = 16; }
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];
@ -98,6 +106,9 @@ function prng(seed) { // mulberry32
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
const isSlower = (type) => type === 'throttle' || type === 'sandbox';
// a Rate Limiter slows by `slow`; a Sandbox freezes for `stun` out of every `pulse` seconds, which holds a packet back by the same fraction
const slowOf = (sp) => (sp.type === 'sandbox' ? sp.st.stun / sp.st.pulse : sp.st.slow);
class Bot {
constructor(TD, sim, strat, rng, ctx) {
@ -172,11 +183,46 @@ class Bot {
this.specs = this.specsNow();
}
inRange(sp, x, y, range) { const dx = sp.x - x, dy = sp.y - y; return dx * dx + dy * dy <= range * range; }
// caps after a Load Balancer of stats `st` stands at (x, y): the attack turrets it reaches fire faster (only where it beats their current boost)
boostCaps(baseCaps, perSpec, ents, slows, x, y, st) {
const nc = Float64Array.from(baseCaps);
this.specs.forEach((sp, si) => {
if (this.TD.TOWERS[sp.type].role !== 'attack' || sp.buff >= st.boost || !this.inRange(sp, x, y, st.range)) return;
const nsp = Object.assign({}, sp, { buff: st.boost });
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]) - perSpec[si][i];
});
return nc;
}
// free cells next to several attack turrets: the places a Load Balancer is worth a thought
balancerSites() {
const sim = this.sim, b = sim.board, res = sim.monsterCells().reserved, TD = this.TD;
const range = TD.TOWERS.balancer.levels[0].range;
const att = this.specs.filter((sp) => TD.TOWERS[sp.type].role === 'attack');
if (att.length < 2) return [];
const list = [];
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
const i = y * b.cols + x;
if (b.solid[i] || b.obst[i] || res.has(i) || b.isSpecial(x, y)) continue;
let n = 0;
for (const sp of att) if (this.inRange(sp, x + 0.5, y + 0.5, range)) n++;
if (n >= 2) list.push({ x, y, n });
}
list.sort((p, q) => q.n - p.n);
return list.slice(0, 8);
}
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] });
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], buff: 0 });
}
for (const b of out) { // Load Balancers: every attack turret takes the best boost in range (no stacking)
if (b.type !== 'balancer') continue;
for (const t of out) if (this.TD.TOWERS[t.type].role === 'attack' && t.buff < b.st.boost && this.inRange(t, b.x, b.y, b.st.range)) t.buff = b.st.boost;
}
return out;
}
@ -215,8 +261,8 @@ class Bot {
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));
if (!isSlower(sp.type)) continue;
const r2 = sp.st.range * sp.st.range, eff = Math.min(0.6, slowOf(sp) * (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;
@ -229,13 +275,15 @@ class Bot {
// 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;
if (isSlower(sp.type) || sp.type === 'balancer') return 0;
const TD = this.TD, td = TD.TOWERS[sp.type], st = sp.st;
if (!(st.dmg > 0)) return 0; // support / control towers (Load Balancer, Sandbox) deal no damage; the bot never builds them
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') {
const hit0 = Math.min(sp.type === 'uplink' ? st.dmg : perHit(st.dmg, e.armor), e.h); // no credit for overkill (the Uplink ignores armour)
let dps = hit0 * st.rate * (1 + (sp.buff || 0)), M = 1;
if (sp.type === 'uplink') {
M = clamp(1 + (2 * st.splash + 0.6 * st.range) / e.spacing, 1, Math.max(1, e.N)); // the beam pierces everything on its line, the blast hits the packets around the target
} else 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') {
@ -331,7 +379,7 @@ class Bot {
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.ratio = this.jit(dv / o.cost) * (this.typeBias[o.type] || 1) * (this.learned[o.type] || 1) * (o.kind === 'new' && ALL_TYPES.includes(o.type) && this.sim.wave <= this.s.exploreUntil && (this.typeCount[o.type] || 0) < 2 ? this.s.explore : 1);
o.dv = dv;
opts.push(o);
};
@ -341,33 +389,37 @@ class Bot {
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') {
if (isSlower(sp.type)) {
const specs2 = this.specs.map((q, j) => (j === si ? nsp : q));
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
} else if (sp.type === 'balancer') {
nc = this.boostCaps(baseCaps, perSpec, ents, slows, sp.x, sp.y, lv);
} 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);
consider({ kind: 'up', id: sp.id, type: sp.type, cost: sim.upgradeCost(sim.towerById(sp.id)) }, 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
const lv = TD.TOWERS[type].levels[0], price = TD.priceFor(type, sim.towers);
const sl = isSlower(type) ? sites.filter((q, ix) => ix % 3 === 0) : type === 'balancer' ? this.balancerSites() : sites; // slow-field 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 };
const nsp = { type, level: 1, x: site.x + 0.5, y: site.y + 0.5, st: lv, buff: 0 };
let nc;
if (type === 'throttle') {
if (isSlower(type)) {
const specs2 = this.specs.concat([nsp]);
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
} else if (type === 'balancer') {
nc = this.boostCaps(baseCaps, perSpec, ents, slows, nsp.x, nsp.y, lv);
} 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);
consider({ kind: 'new', type, x: site.x, y: site.y, wall: site.wall, cost: price }, nc);
}
}
return opts;
@ -573,7 +625,7 @@ class Bot {
this.refresh();
let sold = 0;
for (const sp of this.specs) {
if (sp.level > 1) continue;
if (sp.level > 1 || sp.type === 'balancer') 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; }
@ -647,9 +699,31 @@ class Bot {
}
}
// The Orbital Uplink costs more than the bot ever has in hand (it spends as it earns), so a player who wants one has to save. From
// wave uplinkFrom the bot stops buying anything else until it can pay for the Uplink (then the best site by the surrogate) or the
// next Uplink upgrade. Returns true while it is saving (the caller skips every other purchase).
uplinkStep() {
const sim = this.sim, TD = this.TD;
if (!(this.s.uplinkFrom > 0) || !this.s.types.includes('uplink') || sim.wave < this.s.uplinkFrom || sim.lives < 0.5 * sim.maxLives) return false;
const ups = sim.towers.filter((t) => t.type === 'uplink');
let up = null, cost;
if (ups.length < this.s.uplinkMax) cost = TD.priceFor('uplink', sim.towers);
else {
up = ups.filter((t) => t.level < this.s.uplinkLevel).sort((a, b) => a.level - b.level)[0];
if (!up) return false;
cost = sim.upgradeCost(up);
}
if (sim.gold < cost) return true; // keep saving
if (up) { sim.cmd({ c: 'upgrade', id: up.id }); return false; }
const opts = (this.bestOption() || []).filter((o) => o.kind === 'new' && o.type === 'uplink' && !o.wall).sort((a, b) => b.dv - a.dv);
for (const o of opts.slice(0, 3)) if (this.exec(o)) return false;
return false;
}
// ------------------------------------------------------------------ one round of decisions
think(maxActions) {
if (this.s.lazy) { this.lazyThink(); return; }
if (this.uplinkStep()) return;
let n = 0;
if (this.s.maze && this.sim.rev !== this.prunedRev) { this.prune(); this.prunedRev = this.sim.rev; }
while (n++ < (maxActions || 40)) {
@ -670,6 +744,7 @@ function playGame(opts) {
const rng = prng(seed * 7919 + 13);
const maxWave = opts.maxWave || 30;
const simOpts = { map: opts.map || 'open', events: false };
if (opts.difficulty) simOpts.difficulty = opts.difficulty;
if (opts.startGold !== undefined) simOpts.gold = opts.startGold;
if (opts.lives !== undefined) simOpts.lives = opts.lives;
const sim = new TD.Sim(simOpts);
@ -792,7 +867,7 @@ 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));
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@25', 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;
@ -800,11 +875,19 @@ function printTables(results, a) {
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(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(25, (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));
}
}
// credits the bot has been paid by wave N (gold in hand + everything invested), games that reached it only: the true size of the economy
console.log('\n--- credits seen (gold + invested) at waves 10 / 15 / 20 / 25 / 30, games that got that far ---');
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 cs = [10, 15, 20, 25, 30].map((w) => { const v = rs.filter((r) => r.log.some((e) => e.wave >= w)).map((r) => logAt(r, w)).map((e) => e.gold + e.spentWalls + e.spentOther); return v.length ? Math.round(mean(v)) + ' (' + v.length + ')' : '-'; });
console.log(padr(map, 12) + padr(st, 16) + cs.map((c) => pad(c, 12)).join(''));
}
// 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) {
@ -815,7 +898,7 @@ function printTables(results, a) {
// 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;
if (!/^(maze|full)/.test(st)) continue;
const rs = results.filter((r) => r.map === map && r.strategy === st);
if (!rs.length) continue;
const mix = {};
@ -849,7 +932,16 @@ function printDetail(results) {
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 });
// a strategy may carry a game difficulty after '@' ("maze@hard") and a list of the only maps it runs on after '#' ("maze@hard#open+twin");
// the label of the rows keeps both
for (const map of a.maps) for (const label of a.strategies) {
const hash = label.indexOf('#');
if (hash >= 0 && label.slice(hash + 1).split('+').indexOf(map) < 0) continue;
const bare = hash < 0 ? label : label.slice(0, hash);
const at = bare.indexOf('@');
const strategy = at < 0 ? bare : bare.slice(0, at), difficulty = at < 0 ? undefined : bare.slice(at + 1);
for (let s = 0; s < a.seeds; s++) jobs.push({ map, strategy, label, difficulty, 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;
@ -880,7 +972,7 @@ function main() {
if (require.main === module) {
if (process.argv.includes('--worker')) {
process.on('message', (job) => { process.send(playGame(job)); });
process.on('message', (job) => { const r = playGame(job); r.strategy = job.label || r.strategy; process.send(r); });
} else main();
}