towerdef/tools/versus.js
Claude 2098d59c1f Versus mode: attack vs defend (sim, bots, server, client)
One player defends, the other plays the Internet: earns credits over time and
spends them on packets, upgrades and sabotage. Two rounds with swapped roles,
timed (the faster fall wins). Built end to end, NOT yet QA'd or balanced.

Sim (public/js/sim.js, TD.VS table): attacker economy (income, lifetime bonus,
leak payback), spawn / stage / launch convoys, 7 tech tracks, abilities (EMP,
decoy, surge, DDoS), defender tools (scan, patch, repair, quarantine), role-checked
commands, round result, role-private state. Co-op/solo unchanged (24 scripted
games replay identically).

Bots (public/js/bot.js, tools/versus.js): defender (maze + turrets) and attacker
(budgeted spender reading the tower mix); headless bot-vs-bot runner.

Server (server/versus.js, protocol doc): versus rooms with lobby / countdown /
playing / roundover / matchover, role stamping, cross-role refusal, role-private
priv messages at 4 Hz, computer seat, freeze/forfeit rules, no pause/speed.

Client (public/js/versus.js): setup dialog (role, length, vs computer or online),
countdown, defender tools row, attacker unit shop with convoy + launch, tech and
abilities, gateway choice, round/match screens, sounds, phone-first dock rows.

Status and next steps (balance: the attacker currently wins ~100% of bot rounds;
QA with two browsers; layout matrix rerun) are in docs/NEXT.md and docs/VERSUS.md.
The full planned workflow incl. balance/QA prompts is in docs/workflows/versus-full.js.

253 unit tests pass; one smoke e2e run; no other e2e per the user's request.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-11 10:22:29 +00:00

159 lines
10 KiB
JavaScript

#!/usr/bin/env node
'use strict';
/*
* NETWALL versus balance runner - plays bot-vs-bot ROUNDS (public/js/bot.js: the attacker bot against the defender bot, each driven only
* through sim.cmd like a human) and prints who won, how fast the server fell and what each side spent. It is a DEV TOOL (not a test) for
* tuning the VS table at the top of public/js/sim.js; the numbers it prints move when that table moves.
*
* node tools/versus.js --maps open,twin --limit 600 --seeds 6 [--attacker-skill 1 --defender-skill 1]
* node tools/versus.js --maps all --seeds 4 --json out.json --detail (every map, raw rows, one line per round)
*
* --maps comma list of map ids, or "all" (default open,twin,hub)
* --limit the round timer in sim seconds (default 600)
* --seeds N N rounds per map, seeds --seed-start .. +N-1 (each seed gives both bots a different personality) (default 6)
* --attacker-skill / --defender-skill 0..1, how well each bot plays (default 1)
* --jobs N parallel child processes (default: all cores)
* --json FILE write the raw rows --detail print one line per round --verbose progress on stderr
*
* As a module: const { playRound } = require('./tools/versus'); playRound({ map, limit, seed, attackerSkill, defenderSkill }) -> one row.
*/
const path = require('path');
const os = require('os');
const SIM_PATH = path.join(__dirname, '..', 'public', 'js', 'sim.js');
const BOT_PATH = path.join(__dirname, '..', 'public', 'js', 'bot.js');
function playRound(o) {
const TD = require(SIM_PATH), Bot = require(BOT_PATH);
const map = o.map || 'open', limit = o.limit || 600, seed = o.seed === undefined ? 1 : o.seed;
const sim = new TD.Sim({ map, mode: 'versus', limit, events: false });
const refusals = {}; // every refusal by "role:command:reason" (a healthy bot has none but wall / turret site clashes)
const send = sim.cmd.bind(sim);
sim.cmd = (c) => { const r = send(c); if (!r.ok) { const k = c.role + ':' + c.c + ':' + r.reason; refusals[k] = (refusals[k] || 0) + 1; } return r; };
const att = Bot.create(sim, 'attacker', { seed, skill: o.attackerSkill === undefined ? 1 : o.attackerSkill, by: 1 });
const def = Bot.create(sim, 'defender', { seed, skill: o.defenderSkill === undefined ? 1 : o.defenderSkill, by: 0 });
const t0 = Date.now();
let ticks = 0, peakAlive = 0;
const hard = (limit + 5) * 60;
while (sim.state === 'playing' && ticks++ < hard) {
def.think(TD.STEP); att.think(TD.STEP);
sim.tick(TD.STEP);
if (ticks % 60 === 0 && sim.monsters.length > peakAlive) peakAlive = sim.monsters.length;
}
const v = sim.vs, st = v.stats, mix = {};
let invested = 0;
for (const t of sim.towers) { invested += t.spent; if (t.type !== 'wall') mix[t.type] = (mix[t.type] || 0) + 1; }
const res = v.result || { winner: 'none', t: Math.round(sim.time), integrityLost: v.lost };
return {
map, seed, limit, winner: res.winner, t: res.t, integrityLost: res.integrityLost, maxLives: sim.maxLives,
unitsSpawned: st.spawned, creditsSpent: Math.round(st.unitsSpent + st.techSpent + st.abilitySpent), unitsSpent: st.unitsSpent, techSpent: st.techSpent,
abilitySpent: st.abilitySpent, creditsEarned: Math.round(st.earned), toolSpent: st.toolSpent, kills: st.kills, leaked: st.leaked,
towers: mix, walls: sim.towers.filter((t) => t.type === 'wall').length, defenderInvested: invested, goldEnd: sim.gold, peakAlive,
tech: sim.privateState('attacker').tech, refusals, wallMs: Date.now() - t0,
};
}
// ---------------------------------------------------------------------- CLI
function parseArgs(argv) {
const a = { maps: ['open', 'twin', 'hub'], limit: 600, seeds: 6, seedStart: 1, attackerSkill: 1, defenderSkill: 1, jobs: Math.max(1, os.cpus().length), json: null, detail: false, verbose: false };
for (let i = 2; i < argv.length; i++) {
const k = argv[i], next = () => argv[++i];
if (k === '--maps') { const v = next(); a.maps = v === 'all' ? require(SIM_PATH).MAP_ORDER.slice() : v.split(','); }
else if (k === '--limit') a.limit = +next();
else if (k === '--seeds') a.seeds = +next();
else if (k === '--seed-start') a.seedStart = +next();
else if (k === '--attacker-skill') a.attackerSkill = +next();
else if (k === '--defender-skill') a.defenderSkill = +next();
else if (k === '--jobs') a.jobs = +next();
else if (k === '--json') a.json = next();
else if (k === '--detail') a.detail = true;
else if (k === '--verbose') a.verbose = true;
else if (k === '--worker') a.worker = true;
else if (k === '--help' || k === '-h') { console.log(require('fs').readFileSync(__filename, 'utf8').split('*/')[0].replace(/^[^]*?\/\*/, '')); process.exit(0); }
else { console.error('unknown option ' + k); process.exit(2); }
}
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);
const pct = (n, d) => (d ? Math.round(100 * n / d) + '%' : '-');
function table(rows, label) {
const att = rows.filter((r) => r.winner === 'attacker'), def = rows.filter((r) => r.winner === 'defender');
const fell = att.map((r) => r.t).sort((p, q) => p - q), med = fell.length ? fell[Math.floor(fell.length / 2)] : 0;
return padr(label, 13) + pad(rows.length, 6) + pad(pct(att.length, rows.length), 8) + pad(pct(def.length, rows.length), 8)
+ pad(fell.length ? mean(fell).toFixed(0) + 's' : '-', 8) + pad(fell.length ? med.toFixed(0) + 's' : '-', 8)
+ pad(mean(rows.map((r) => r.integrityLost)).toFixed(1), 8) + pad(Math.round(mean(rows.map((r) => r.unitsSpawned))), 8)
+ pad(Math.round(mean(rows.map((r) => r.creditsSpent))), 8) + pad(Math.round(mean(rows.map((r) => r.creditsEarned))), 8)
+ pad(Math.round(mean(rows.map((r) => r.kills))), 7) + pad(Math.round(mean(rows.map((r) => r.defenderInvested))), 8)
+ pad(mean(rows.map((r) => Object.keys(r.towers).reduce((s, k) => s + r.towers[k], 0))).toFixed(1), 7) + pad(Math.round(mean(rows.map((r) => r.wallMs))) + 'ms', 8);
}
function printTables(rows, a) {
console.log('\nversus bots: attacker skill ' + a.attackerSkill + ' vs defender skill ' + a.defenderSkill + ', round limit ' + a.limit + ' s, ' + a.seeds + ' seeds per map');
console.log(padr('map', 13) + pad('rounds', 6) + pad('att win', 8) + pad('def win', 8) + pad('fall avg', 8) + pad('fall med', 8) + pad('int lost', 8) + pad('units', 8) + pad('att cr', 8) + pad('earned', 8) + pad('kills', 7) + pad('def inv', 8) + pad('towers', 7) + pad('cpu', 8));
for (const map of a.maps) { const rs = rows.filter((r) => r.map === map); if (rs.length) console.log(table(rs, map)); }
if (a.maps.length > 1) console.log(table(rows, 'ALL MAPS'));
const mix = {}, tech = {};
for (const r of rows) {
for (const k of Object.keys(r.towers)) mix[k] = (mix[k] || 0) + r.towers[k] / rows.length;
for (const k of Object.keys(r.tech)) tech[k] = (tech[k] || 0) + r.tech[k] / rows.length;
}
console.log('\naverage final tower mix: ' + Object.keys(mix).map((k) => k + ' ' + mix[k].toFixed(1)).join(' '));
console.log('average attacker tech: ' + Object.keys(tech).map((k) => k + ' ' + tech[k].toFixed(1)).join(' '));
console.log('average spend (attacker): units ' + Math.round(mean(rows.map((r) => r.unitsSpent))) + ' tech ' + Math.round(mean(rows.map((r) => r.techSpent))) + ' abilities ' + Math.round(mean(rows.map((r) => r.abilitySpent)))
+ ' (defender): towers+walls ' + Math.round(mean(rows.map((r) => r.defenderInvested))) + ' tools ' + Math.round(mean(rows.map((r) => r.toolSpent))));
const ref = {};
for (const r of rows) for (const k of Object.keys(r.refusals)) ref[k] = (ref[k] || 0) + r.refusals[k];
const keys = Object.keys(ref).sort();
console.log('refused commands (all rounds): ' + (keys.length ? keys.map((k) => k + ' x' + ref[k]).join(' ') : 'none'));
const bad = keys.filter((k) => /:(role|bad_[a-z]+|over|max|cooldown|credits|cap|empty)$/.test(k));
if (bad.length) console.log('WARNING: a bot sent commands a human UI would not have allowed: ' + bad.join(', '));
const stuck = rows.filter((r) => r.winner === 'none');
if (stuck.length) console.log('WARNING: ' + stuck.length + ' round(s) hit the tick guard without a result');
}
function printDetail(rows) {
console.log('\nmap seed winner t lost units spent earned kills leaked defender mix');
for (const r of rows) console.log(padr(r.map, 12) + pad(r.seed, 5) + pad(r.winner, 9) + pad(Math.round(r.t), 6) + pad(r.integrityLost, 5) + pad(r.unitsSpawned, 6) + pad(r.creditsSpent, 6) + pad(r.creditsEarned, 7) + pad(r.kills, 6) + pad(r.leaked, 7) + ' ' + JSON.stringify(r.towers) + ' walls ' + r.walls);
}
function main() {
const a = parseArgs(process.argv);
const jobs = [];
for (const map of a.maps) for (let s = 0; s < a.seeds; s++) jobs.push({ map, limit: a.limit, seed: a.seedStart + s, attackerSkill: a.attackerSkill, defenderSkill: a.defenderSkill });
const { fork } = require('child_process');
const rows = [];
let next = 0, running = 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) => {
rows.push(m);
if (a.verbose) process.stderr.write('[' + rows.length + '/' + jobs.length + '] ' + m.map + ' s' + m.seed + ' ' + m.winner + ' t=' + Math.round(m.t) + ' ' + m.wallMs + 'ms\n');
child.kill();
});
child.on('exit', () => { running--; if (next < jobs.length) startOne(); else if (!running) finish(); });
child.send(job);
};
const finish = () => {
rows.sort((p, q) => (p.map + String(1000 + p.seed)).localeCompare(q.map + String(1000 + q.seed)));
if (a.json) require('fs').writeFileSync(a.json, JSON.stringify(rows));
printTables(rows, a);
if (a.detail) printDetail(rows);
console.log('\n(' + jobs.length + ' rounds, ' + ((Date.now() - t0) / 1000).toFixed(1) + ' s wall clock, ' + a.jobs + ' jobs)');
};
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(playRound(job)));
else main();
}
module.exports = { playRound, parseArgs };