towerdef/server/room.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

450 lines
19 KiB
JavaScript

'use strict';
/*
* Rooms: one authoritative Sim per room, two player slots, fixed-step tick loop and snapshot broadcast.
* A "conn" is the per-socket context object created in index.js ({ ws, player, room, dead, ... }); this file
* only touches conn.ws, conn.player and conn.room and never throws on a dead socket.
*/
const crypto = require('crypto');
const TD = require('../public/js/sim.js'); // fixed path on purpose: independent of publicDir
const { Versus } = require('./versus');
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'wave', 'auto', 'continue']);
const OPEN = 1; // WebSocket.OPEN
const LOOP_MS = 8; // global tick loop period
const MAX_CATCHUP_S = 0.25; // clamp one loop iteration (stalled event loop)
const STEP_BUDGET_NS = 20000000n; // never spend more than 20 ms stepping one room per iteration
const MARK_GAP_MS = 400;
const MAX_BUFFERED = 512 * 1024; // a socket this far behind is dropped; it reconnects and resumes
const MAX_MONSTER_LOAD = 1500; // monsters + queued spawns; refuse 'wave' beyond this (CPU/bandwidth guard)
const ALIAS_KEY = crypto.randomBytes(32); // per process; see Room.alias()
const nowMs = () => Number(process.hrtime.bigint() / 1000000n);
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const finite = (v) => typeof v === 'number' && Number.isFinite(v);
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
const round2 = (v) => Math.round(v * 100) / 100;
function sendRaw(conn, str) {
const ws = conn && conn.ws;
if (!ws || ws.readyState !== OPEN) return false;
try { ws.send(str); return true; } catch (e) { return false; }
}
class Room {
// `vsOpts` ({ limit, rounds }) makes it a versus room (docs/PROTOCOL.md "Versus"): `this.vsc` then runs the match and every co-op code path
// below that it replaces is guarded by it; without it nothing here changes.
constructor(manager, code, mapId, difficulty, vsOpts) {
this.manager = manager;
this.code = code;
this.vsc = null;
if (vsOpts) {
this.sim = new TD.Sim({ map: mapId, mode: 'versus', limit: vsOpts.limit }); // the lobby's board; every round gets a fresh sim
this.vsc = new Versus(this, vsOpts);
} else this.sim = new TD.Sim({ map: mapId, difficulty });
this.speed = 1;
this.paused = false;
this.seq = 0;
this.players = [null, null]; // slot -> player
this.acc = 0; // accumulated game seconds not yet stepped
this.lastNs = null; // hrtime of the previous loop iteration
this.nextSnapNs = 0n;
this.lastSentRev = this.sim.rev; // 'tw' is attached only when rev moves past this
this.destroyed = false;
this.createdAt = Date.now();
this.emptySince = null; // nowMs() when the last online player went away; null while somebody is online
}
log(msg) { this.manager.log('[' + this.code + '] ' + msg); }
// ---------------------------------------------------------------- players
onlinePlayers() { return this.players.filter((p) => p && p.conn); }
anyPlayers() { return this.players.some(Boolean); }
// A pid is the reconnect secret (whoever presents it takes over the slot), so it only ever goes to its owner.
// The other player appears under a stable alias: unguessable, different per room, useless as a pid.
alias(pid) {
return crypto.createHmac('sha256', ALIAS_KEY).update(this.code + ':' + pid).digest('base64url').slice(0, 22);
}
// The player list as `viewer` may see it: their own entry carries their pid, everyone else's an alias.
publicPlayers(viewer) {
const out = [];
for (const p of this.players) {
if (p) out.push({ pid: p === viewer ? p.pid : p.alias, slot: p.slot, name: p.name, host: p.host, online: !!p.conn });
}
return out;
}
send(player, obj) { return !!player && sendRaw(player.conn, JSON.stringify(obj)); }
// Same string to everyone online (optionally except one conn).
broadcast(obj, exceptConn) {
const str = JSON.stringify(obj);
for (const p of this.players) if (p && p.conn && p.conn !== exceptConn) sendRaw(p.conn, str);
}
// One message per recipient (each sees their own pid), to everyone online except `exceptConn`.
broadcastPlayers(exceptConn) {
for (const p of this.players) {
if (p && p.conn && p.conn !== exceptConn) this.send(p, { t: 'players', players: this.publicPlayers(p) });
}
}
stateMsg(extra) {
return Object.assign({ t: 'state', state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused }, extra);
}
joinedMsg(player, resumed) {
const m = {
t: 'joined', room: this.code, resumed,
you: { pid: player.pid, slot: player.slot, host: player.host },
players: this.publicPlayers(player),
state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused,
};
if (this.vsc) { this.vsc.updateFrozen(); m.vs = this.vsc.msg(); } // (a player who just came back is online: `frozen` must not be stale in what it is told)
return m;
}
// Called by index.js after `joined` went to the new connection: a versus room tells the others and sends the joiner its private data.
afterJoin(player, resumed, conn) { if (this.vsc) this.vsc.onJoined(player, resumed, conn); }
// Binds `conn` to a slot. Returns { player, resumed } or null when both slots belong to other pids.
join(pid, name, conn) {
let p = this.players.find((x) => x && x.pid === pid);
let resumed = false;
if (p) {
resumed = true;
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
const old = p.conn;
p.conn = conn;
p.name = name;
if (old && old !== conn) { // a second tab / a reconnect racing the dead socket
old.player = null; old.room = null; old.dead = true;
try { old.ws.close(4001, 'replaced by a newer connection'); } catch (e) { /* already closing */ }
}
} else {
const slot = this.vsc ? this.vsc.freeSlot() : this.players.indexOf(null);
if (slot < 0) return null;
p = {
pid, alias: this.alias(pid), slot, name, host: !this.players.some((x) => x && x.host),
conn, cursor: null, lastMarkAt: -Infinity, graceTimer: null,
};
this.players[slot] = p;
if (this.vsc) this.vsc.onSeated(p);
}
p.cursor = null;
this.touchPresence();
return { player: p, resumed };
}
// Keeps `emptySince` in step with who is online (the manager evicts the longest-abandoned room first).
touchPresence() {
if (this.onlinePlayers().length) this.emptySince = null;
else if (this.emptySince === null) this.emptySince = nowMs();
}
// The socket of `conn` closed (not a deliberate leave): keep the slot for graceMs.
disconnect(conn) {
const p = conn.player;
if (this.destroyed || !p || p.conn !== conn) return;
p.conn = null;
p.cursor = null;
this.touchPresence();
this.log(p.name + ' (slot ' + p.slot + ') disconnected; holding the slot for ' + this.manager.graceMs + ' ms');
p.graceTimer = setTimeout(() => { p.graceTimer = null; this.removePlayer(p, 'grace expired'); }, this.manager.graceMs);
this.broadcastPlayers();
if (this.vsc) this.vsc.onPresence();
}
// Frees the slot for good, migrates the host, deletes the room when nobody is left.
removePlayer(p, why) {
if (this.destroyed || this.players[p.slot] !== p) return;
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
this.players[p.slot] = null;
p.conn = null;
p.cursor = null;
this.log(p.name + ' (slot ' + p.slot + ') removed: ' + why);
if (!this.anyPlayers()) { this.manager.deleteRoom(this, 'empty'); return; }
if (p.host) {
const next = this.players.find(Boolean);
next.host = true;
this.log('host is now ' + next.name + ' (slot ' + next.slot + ')');
}
this.touchPresence();
this.broadcastPlayers();
if (this.vsc) this.vsc.onRemoved(p);
}
leave(conn) {
const p = conn.player;
if (!p || p.conn !== conn) return;
conn.player = null; conn.room = null;
this.removePlayer(p, 'left');
}
// ---------------------------------------------------------------- messages after join
// Returns false when the message is malformed (the caller counts those).
handleMessage(p, msg) {
switch (msg.t) {
case 'cmd': return this.handleCmd(p, msg);
case 'ctl': return this.handleCtl(p, msg);
case 'cursor': return this.handleCursor(p, msg);
case 'mark': return this.handleMark(p, msg);
case 'rtt':
if (!finite(msg.ts) && !(typeof msg.ts === 'string' && msg.ts.length <= 32)) return false;
this.send(p, { t: 'rtt', ts: msg.ts });
return true;
case 'sync': this.send(p, this.stateMsg()); if (this.vsc) this.vsc.sendTo(p); return true;
case 'newgame': return this.handleNewgame(p, msg);
case 'vs': return this.vsc ? this.vsc.handleMessage(p, msg) : false; // a co-op room has no such message: malformed, as before
default: return false;
}
}
reject(p, c, reason, msg) {
const out = { t: 'reject', c, reason };
if (msg) {
if (finite(msg.x)) out.x = msg.x;
if (finite(msg.y)) out.y = msg.y;
if (finite(msg.id)) out.id = msg.id;
else if (this.vsc && typeof msg.id === 'string' && msg.id.length <= 24) out.id = msg.id; // versus: which tool / ability / tech track
if (this.vsc && finite(msg.tid)) out.tid = msg.tid;
}
this.send(p, out);
}
handleCmd(p, msg) {
if (this.vsc) return this.vsc.handleCmd(p, msg);
const c = msg.c;
if (typeof c !== 'string' || !CMDS.has(c)) return false;
const sim = this.sim;
if (c === 'wave' && sim.monsters.length + sim.spawnQ.length > MAX_MONSTER_LOAD) {
this.reject(p, c, 'busy', msg);
return true;
}
// `lv` (upgrade: the level the sender saw) and `n` (wave: the wave number it expects to start) make a command idempotent: the sim
// answers 'stale' when the premise no longer holds. Optional, but when present they must be integers.
for (const k of ['lv', 'n']) if (msg[k] !== undefined && msg[k] !== null && !Number.isInteger(msg[k])) return false;
// Whitelisted fields only; `by` always comes from the socket's slot, never from the client.
const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, lv: msg.lv, n: msg.n, by: p.slot };
let r;
try { r = sim.cmd(cmd); } catch (e) { this.log('sim.cmd threw: ' + (e && e.stack || e)); r = { ok: false, reason: 'error' }; }
if (!r || !r.ok) this.reject(p, c, (r && r.reason) || 'error', msg);
return true;
}
handleCtl(p, msg) {
if (this.vsc) return this.vsc.handleCtl(p, msg);
if (msg.c === 'pause' && typeof msg.v === 'boolean') { this.paused = msg.v; return true; }
if (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3)) { this.speed = msg.v; return true; }
return false;
}
boardPoint(msg) {
const b = this.sim.board;
return [round2(clamp(msg.x, 0, b.cols)), round2(clamp(msg.y, 0, b.rows))];
}
handleCursor(p, msg) {
if (msg.x === null) { p.cursor = null; return true; }
if (!finite(msg.x) || !finite(msg.y)) return false;
if (this.vsc) return true; // versus: the opponent does not see where you hover (what you are about to build or target)
p.cursor = this.boardPoint(msg);
return true;
}
handleMark(p, msg) {
if (!finite(msg.x) || !finite(msg.y)) return false;
if (this.vsc) return true; // versus: no map pings to an opponent (valid, ignored)
const now = nowMs(); // monotonic: immune to wall-clock steps
if (now - p.lastMarkAt < MARK_GAP_MS) return true; // rate limited: dropped silently
p.lastMarkAt = now;
const pt = this.boardPoint(msg);
this.broadcast({ t: 'mark', slot: p.slot, x: pt[0], y: pt[1] });
return true;
}
handleNewgame(p, msg) {
if (this.vsc) { this.reject(p, 'newgame', 'versus'); return true; } // a versus room is replayed with { t:'vs', c:'rematch' }
if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; }
const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map;
if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; }
const difficulty = msg.difficulty === undefined || msg.difficulty === null ? this.sim.difficulty : msg.difficulty; // absent: keep the room's
if (!TD.isDifficulty(difficulty)) { this.reject(p, 'newgame', 'bad_difficulty'); return true; }
this.sim = new TD.Sim({ map, difficulty });
this.speed = 1; this.paused = false; this.acc = 0;
this.lastSentRev = this.sim.rev; // the 'state' below carries the tower list
this.log('new game on map ' + map + ' (' + difficulty + ') started by ' + p.name);
this.broadcast(this.stateMsg({ newgame: true }));
return true;
}
// ---------------------------------------------------------------- loop
// Called every LOOP_MS by the manager with process.hrtime.bigint().
step(now) {
if (this.vsc) { this.vsc.step(now); return; }
const last = this.lastNs;
this.lastNs = now;
const online = this.onlinePlayers().length > 0;
const sim = this.sim;
if (!online || this.paused || sim.state !== 'playing' || last === null) {
this.acc = 0; // no catch-up after a pause / an empty room
} else {
let dt = Number(now - last) / 1e9;
if (dt > MAX_CATCHUP_S) dt = MAX_CATCHUP_S;
this.acc += dt * this.speed;
let n = 0;
const t0 = process.hrtime.bigint();
while (this.acc >= TD.STEP) {
sim.tick(TD.STEP);
this.acc -= TD.STEP;
if ((++n & 7) === 0 && process.hrtime.bigint() - t0 > STEP_BUDGET_NS) { // overloaded: run slower, do not freeze the server
this.acc = Math.min(this.acc, TD.STEP);
break;
}
}
}
if (!online) { this.nextSnapNs = now; return; }
this.snapIfDue(now);
}
snapIfDue(now) {
if (now >= this.nextSnapNs) {
this.broadcastSnap();
this.nextSnapNs += this.manager.snapPeriodNs;
if (this.nextSnapNs <= now) this.nextSnapNs = now + this.manager.snapPeriodNs;
}
}
// Serialised once, the same string goes to every online player.
broadcastSnap() {
const sim = this.sim;
const cur = [];
for (const p of this.players) if (p && p.conn && p.cursor) cur.push([p.slot, p.cursor[0], p.cursor[1]]);
const msg = Object.assign({ t: 'snap', seq: ++this.seq }, sim.snapshot(), {
ev: sim.drainEvents(), cur, pa: this.paused ? 1 : 0, sp: this.speed,
});
if (sim.rev !== this.lastSentRev) { msg.tw = sim.towerList(); this.lastSentRev = sim.rev; }
const str = JSON.stringify(msg);
for (const p of this.players) {
if (!p || !p.conn) continue;
const ws = p.conn.ws;
if (ws.bufferedAmount > MAX_BUFFERED) { // hopelessly behind: dropping a snap could lose 'tw'/'ev'
this.log(p.name + ' is too slow (' + ws.bufferedAmount + ' bytes queued); dropping the connection');
try { ws.terminate(); } catch (e) { /* gone */ }
continue;
}
sendRaw(p.conn, str);
}
}
// Something threw inside the loop: tell everyone and drop the room rather than the whole process.
crash(err) {
this.log('room crashed: ' + (err && err.stack || err));
for (const p of this.players) {
if (!p || !p.conn) continue;
sendRaw(p.conn, JSON.stringify({ t: 'error', code: 'server_error', msg: 'internal error' }));
try { p.conn.ws.close(1011, 'internal error'); } catch (e) { /* gone */ }
}
this.manager.deleteRoom(this, 'crashed');
}
destroy() {
this.destroyed = true;
for (const p of this.players) {
if (p && p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
}
}
}
class RoomManager {
constructor(opts) {
this.rooms = new Map();
this.maxRooms = opts.maxRooms;
this.graceMs = opts.graceMs;
this.snapPeriodNs = BigInt(Math.max(1, Math.round(1e9 / opts.snapshotHz)));
this.log = opts.log;
this.vsCountdownMs = opts.vsCountdownMs === undefined ? 3000 : opts.vsCountdownMs; // versus: the pause before a round
this.vsNextMs = opts.vsNextMs === undefined ? 30000 : opts.vsNextMs; // versus: how long the round result waits for everybody's `next`
this.botSpentNs = 0n; // versus: computer-player time spent in this loop iteration
this.timer = null;
this.closed = false;
}
newCode() {
for (let tries = 0; tries < 200; tries++) {
let c = '';
for (let i = 0; i < 4; i++) c += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
if (!this.rooms.has(c)) return c;
}
return null;
}
get(code) { return this.rooms.get(code); }
// The room nobody has been online in for the longest time, or null.
abandonedRoom() {
let oldest = null;
for (const r of this.rooms.values()) if (r.emptySince !== null && (oldest === null || r.emptySince < oldest.emptySince)) oldest = r;
return oldest;
}
// null when the room limit is reached. A full table first drops a room that nobody is online in (it is only
// being held for its grace period): otherwise one client could fill all slots for a minute at a time by
// creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap.
create(mapId, difficulty, vsOpts) {
if (this.closed) return null;
if (this.rooms.size >= this.maxRooms) {
const victim = this.abandonedRoom();
if (!victim) return null;
this.deleteRoom(victim, 'evicted: the server is full and nobody is online in it');
}
const code = this.newCode();
if (!code) return null;
const room = new Room(this, code, mapId, difficulty, vsOpts);
this.rooms.set(code, room);
room.log('created (map ' + mapId + ', ' + (vsOpts ? 'versus, ' + vsOpts.limit + ' s' : room.sim.difficulty) + '); ' + this.rooms.size + ' room(s)');
this.startLoop();
return room;
}
deleteRoom(room, why) {
if (this.rooms.get(room.code) !== room) return;
room.destroy();
this.rooms.delete(room.code);
room.log('deleted (' + why + '); ' + this.rooms.size + ' room(s) left');
if (!this.rooms.size) this.stopLoop();
}
startLoop() {
if (this.timer || this.closed) return;
this.timer = setInterval(() => this.tick(), LOOP_MS);
}
stopLoop() {
if (this.timer) { clearInterval(this.timer); this.timer = null; }
}
tick() {
const now = process.hrtime.bigint();
this.botSpentNs = 0n;
for (const room of Array.from(this.rooms.values())) {
try { room.step(now); } catch (err) { room.crash(err); }
}
}
close() {
this.closed = true;
this.stopLoop();
for (const room of Array.from(this.rooms.values())) room.destroy();
this.rooms.clear();
}
}
Room.LIMITS = { MAX_CATCHUP_S, STEP_BUDGET_NS, MAX_BUFFERED }; // read by versus.js (which room.js requires, so it cannot require this file)
module.exports = { Room, RoomManager, CODE_ALPHABET, CMDS, MAX_MONSTER_LOAD, MAX_BUFFERED };