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
This commit is contained in:
parent
b4ae6cb57d
commit
2098d59c1f
23 changed files with 6166 additions and 90 deletions
|
|
@ -6,6 +6,7 @@
|
|||
*/
|
||||
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']);
|
||||
|
|
@ -32,10 +33,16 @@ function sendRaw(conn, str) {
|
|||
}
|
||||
|
||||
class Room {
|
||||
constructor(manager, code, mapId, difficulty) {
|
||||
// `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.sim = new TD.Sim({ map: mapId, difficulty });
|
||||
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;
|
||||
|
|
@ -90,14 +97,19 @@ class Room {
|
|||
}
|
||||
|
||||
joinedMsg(player, resumed) {
|
||||
return {
|
||||
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);
|
||||
|
|
@ -113,13 +125,14 @@ class Room {
|
|||
try { old.ws.close(4001, 'replaced by a newer connection'); } catch (e) { /* already closing */ }
|
||||
}
|
||||
} else {
|
||||
const slot = this.players.indexOf(null);
|
||||
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();
|
||||
|
|
@ -142,6 +155,7 @@ class Room {
|
|||
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.
|
||||
|
|
@ -160,6 +174,7 @@ class Room {
|
|||
}
|
||||
this.touchPresence();
|
||||
this.broadcastPlayers();
|
||||
if (this.vsc) this.vsc.onRemoved(p);
|
||||
}
|
||||
|
||||
leave(conn) {
|
||||
|
|
@ -174,15 +189,16 @@ class Room {
|
|||
handleMessage(p, msg) {
|
||||
switch (msg.t) {
|
||||
case 'cmd': return this.handleCmd(p, msg);
|
||||
case 'ctl': return this.handleCtl(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()); 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -193,11 +209,14 @@ class Room {
|
|||
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;
|
||||
|
|
@ -216,7 +235,8 @@ class Room {
|
|||
return true;
|
||||
}
|
||||
|
||||
handleCtl(msg) {
|
||||
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;
|
||||
|
|
@ -230,12 +250,14 @@ class Room {
|
|||
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;
|
||||
|
|
@ -245,6 +267,7 @@ class Room {
|
|||
}
|
||||
|
||||
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; }
|
||||
|
|
@ -261,6 +284,7 @@ class Room {
|
|||
// ---------------------------------------------------------------- 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;
|
||||
|
|
@ -285,6 +309,10 @@ class Room {
|
|||
}
|
||||
|
||||
if (!online) { this.nextSnapNs = now; return; }
|
||||
this.snapIfDue(now);
|
||||
}
|
||||
|
||||
snapIfDue(now) {
|
||||
if (now >= this.nextSnapNs) {
|
||||
this.broadcastSnap();
|
||||
this.nextSnapNs += this.manager.snapPeriodNs;
|
||||
|
|
@ -340,6 +368,9 @@ class RoomManager {
|
|||
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;
|
||||
}
|
||||
|
|
@ -365,7 +396,7 @@ class RoomManager {
|
|||
// 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) {
|
||||
create(mapId, difficulty, vsOpts) {
|
||||
if (this.closed) return null;
|
||||
if (this.rooms.size >= this.maxRooms) {
|
||||
const victim = this.abandonedRoom();
|
||||
|
|
@ -374,9 +405,9 @@ class RoomManager {
|
|||
}
|
||||
const code = this.newCode();
|
||||
if (!code) return null;
|
||||
const room = new Room(this, code, mapId, difficulty);
|
||||
const room = new Room(this, code, mapId, difficulty, vsOpts);
|
||||
this.rooms.set(code, room);
|
||||
room.log('created (map ' + mapId + ', ' + room.sim.difficulty + '); ' + this.rooms.size + ' room(s)');
|
||||
room.log('created (map ' + mapId + ', ' + (vsOpts ? 'versus, ' + vsOpts.limit + ' s' : room.sim.difficulty) + '); ' + this.rooms.size + ' room(s)');
|
||||
this.startLoop();
|
||||
return room;
|
||||
}
|
||||
|
|
@ -400,6 +431,7 @@ class RoomManager {
|
|||
|
||||
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); }
|
||||
}
|
||||
|
|
@ -413,4 +445,6 @@ class RoomManager {
|
|||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue