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
|
|
@ -23,7 +23,7 @@ const PID_RE = /^[A-Za-z0-9_-]{8,40}$/;
|
|||
const ROOM_RE = /^[A-Za-z0-9]{4}$/;
|
||||
const NAME_STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
|
||||
// Close codes for a failed join (the 'error' message carries the machine-readable code).
|
||||
const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, bad_difficulty: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 };
|
||||
const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, bad_difficulty: 4400, bad_mode: 4400, bad_limit: 4400, bad_rounds: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 };
|
||||
|
||||
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const noop = () => {};
|
||||
|
|
@ -42,6 +42,8 @@ async function createServer(userOpts) {
|
|||
graceMs: 60000, snapshotHz: 20, maxRooms: 50,
|
||||
trustProxy: 'auto', trustedProxies: null, allowedOrigins: [], maxConnPerIp: 40, pingMs: 25000, log: defaultLog,
|
||||
joinTimeoutMs: 10000, // not in the protocol's option list: lets tests shorten the 10 s join window
|
||||
vsCountdownMs: 3000, // versus: the pause before each round (tests shorten it)
|
||||
vsNextMs: 30000, // versus: how long a round result waits for everybody's `next` before the next round starts anyway
|
||||
};
|
||||
for (const k of Object.keys(userOpts || {})) if (userOpts[k] !== undefined) o[k] = userOpts[k];
|
||||
o.trustProxy = parseTrustProxy(o.trustProxy);
|
||||
|
|
@ -50,7 +52,7 @@ async function createServer(userOpts) {
|
|||
o.snapshotHz = Math.min(60, Math.max(1, Number(o.snapshotHz) || 20));
|
||||
const log = typeof o.log === 'function' ? o.log : noop;
|
||||
|
||||
const manager = new RoomManager({ maxRooms: o.maxRooms, graceMs: o.graceMs, snapshotHz: o.snapshotHz, log });
|
||||
const manager = new RoomManager({ maxRooms: o.maxRooms, graceMs: o.graceMs, snapshotHz: o.snapshotHz, log, vsCountdownMs: o.vsCountdownMs, vsNextMs: o.vsNextMs });
|
||||
const serveStatic = createStaticHandler(o.publicDir);
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false });
|
||||
wss.on('error', (err) => log('websocket server error: ' + (err && err.message)));
|
||||
|
|
@ -207,7 +209,20 @@ async function createServer(userOpts) {
|
|||
if (!TD.isDifficulty(msg.difficulty)) return failJoin(ctx, 'bad_difficulty', 'unknown difficulty');
|
||||
difficulty = msg.difficulty;
|
||||
}
|
||||
room = manager.create(map, difficulty);
|
||||
// Game mode: only a creating join carries it (like the map). Absent or null is co-op; versus also takes the round limit and the number of rounds.
|
||||
let vsOpts = null;
|
||||
if (msg.mode !== undefined && msg.mode !== null) {
|
||||
if (msg.mode !== 'coop' && msg.mode !== 'versus') return failJoin(ctx, 'bad_mode', 'unknown mode');
|
||||
if (msg.mode === 'versus') {
|
||||
vsOpts = { limit: TD.VS.DEFAULT_LIMIT, rounds: TD.VS.ROUNDS };
|
||||
if (msg.limit !== undefined && msg.limit !== null) {
|
||||
if (typeof msg.limit !== 'number' || !TD.VS.LIMITS.includes(msg.limit)) return failJoin(ctx, 'bad_limit', 'unknown round limit');
|
||||
vsOpts.limit = msg.limit;
|
||||
}
|
||||
if (msg.rounds !== undefined && msg.rounds !== null && msg.rounds !== TD.VS.ROUNDS) return failJoin(ctx, 'bad_rounds', 'unsupported number of rounds');
|
||||
}
|
||||
}
|
||||
room = manager.create(map, difficulty, vsOpts);
|
||||
if (!room) return failJoin(ctx, 'too_many_rooms', 'the server has reached its room limit');
|
||||
why = 'created';
|
||||
} else {
|
||||
|
|
@ -222,6 +237,7 @@ async function createServer(userOpts) {
|
|||
if (ctx.joinTimer) { clearTimeout(ctx.joinTimer); ctx.joinTimer = null; }
|
||||
send(ctx, room.joinedMsg(r.player, r.resumed));
|
||||
room.broadcastPlayers(ctx);
|
||||
room.afterJoin(r.player, r.resumed, ctx);
|
||||
room.log(name + ' ' + (r.resumed ? 'resumed' : (why || 'joined')) + ' as slot ' + r.player.slot + (r.player.host ? ' (host)' : '') + ' from ' + ctx.ip);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
|
|||
487
server/versus.js
Normal file
487
server/versus.js
Normal file
|
|
@ -0,0 +1,487 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Versus rooms (docs/VERSUS.md, docs/PROTOCOL.md "Versus"): the lobby / countdown / round / round-over / match-over state machine, the
|
||||
* seats and roles, the optional computer seat and the role-private data messages. A Room (room.js) owns one of these when it was
|
||||
* created with mode 'versus' and calls into it at a handful of hooks; a co-op room has none and never gets here.
|
||||
*
|
||||
* Phases: lobby -> countdown -> playing -> roundover -> countdown -> playing -> matchover -> (rematch) countdown ...
|
||||
* lobby roles / ready / computer seat are being agreed. The sim exists (so a joiner has a board to look at) but NEVER ticks.
|
||||
* countdown a fresh Sim for the round exists and the players are told; nothing ticks, no command is accepted.
|
||||
* playing the sim ticks (only while every human seat is online) and the bot thinks. Commands are accepted.
|
||||
* roundover the round's result is shown; waits for every human's `next` (or vsNextMs).
|
||||
* matchover both rounds are done (or somebody forfeited); `rematch` starts a new match with the first roles swapped.
|
||||
* The sim is replaced for every round (a new Sim + a `state` message with newgame:true), so nothing leaks from one round to the next.
|
||||
*/
|
||||
const crypto = require('crypto');
|
||||
const TD = require('../public/js/sim.js');
|
||||
const NWBot = require('../public/js/bot.js');
|
||||
|
||||
const { VS } = TD;
|
||||
const BOT_NAME = 'Computer';
|
||||
const BOT_THINK_S = 0.25; // the bot is asked to think at about 4 Hz of game time (it decides about once per second itself)
|
||||
const BOT_BUDGET_NS = 15000000n; // all the bots on the server together may start thinking only while less than this was spent this loop
|
||||
const PRIV_NS = 250000000n; // role-private data goes out at 4 Hz
|
||||
const MAX_KIND_LEN = 24;
|
||||
|
||||
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const finite = (v) => typeof v === 'number' && Number.isFinite(v);
|
||||
const opposite = (r) => (r === 'attacker' ? 'defender' : 'attacker');
|
||||
const swapRoles = (roles) => ({ 0: opposite(roles[0]), 1: opposite(roles[1]) });
|
||||
const slotOf = (roles, role) => (roles[0] === role ? 0 : 1);
|
||||
const coin = () => (crypto.randomInt(2) ? 'attacker' : 'defender');
|
||||
const nowNs = () => process.hrtime.bigint();
|
||||
|
||||
// What a client may send as a game command in a versus room. `wave`, `auto` and `continue` are valid messages that the sim refuses with
|
||||
// 'versus' (so a stray co-op client gets a reject, not a disconnect); everything else is malformed, exactly like in a co-op room.
|
||||
const VS_CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'tool', 'spawn', 'stage', 'launch', 'tech', 'ability', 'wave', 'auto', 'continue']);
|
||||
const STRING_ID_CMDS = new Set(['tool', 'ability', 'tech']); // `id` names a tool / ability / tech track here, a tower id elsewhere
|
||||
const NUMBER_ID_CMDS = new Set(['sell', 'upgrade', 'target']);
|
||||
|
||||
// ------------------------------------------------------------------------------------------------------ match rules (pure)
|
||||
// history entry: { round, roles: {0, 1}, result: { winner, t, integrityLost, attacker: slot, defender: slot, forfeit? } }
|
||||
function historyEntry(round, roles, result) {
|
||||
return { round, roles: { 0: roles[0], 1: roles[1] }, result: Object.assign({}, result, { attacker: slotOf(roles, 'attacker'), defender: slotOf(roles, 'defender') }) };
|
||||
}
|
||||
|
||||
// Each player's ATTACKING performance: the time the server fell (null when it did not) and the integrity taken off in total.
|
||||
// A forfeited round never counts as "the server fell".
|
||||
function matchScores(history, names) {
|
||||
return [0, 1].map((slot) => {
|
||||
let fellAt = null, lost = 0;
|
||||
for (const h of history) {
|
||||
if (h.roles[slot] !== 'attacker') continue;
|
||||
lost += h.result.integrityLost || 0;
|
||||
if (h.result.winner === 'attacker' && !h.result.forfeit && (fellAt === null || h.result.t < fellAt)) fellAt = h.result.t;
|
||||
}
|
||||
return { slot, name: names[slot], fellAt, integrityLost: lost };
|
||||
});
|
||||
}
|
||||
|
||||
// The match winner's slot, or null for a draw: the faster fall; if only one felled the server, that player; if neither did, the one who took
|
||||
// off more integrity.
|
||||
function matchWinner(scores) {
|
||||
const a = scores[0], b = scores[1];
|
||||
if (a.fellAt !== null && b.fellAt !== null) return a.fellAt === b.fellAt ? null : a.fellAt < b.fellAt ? a.slot : b.slot;
|
||||
if (a.fellAt !== null) return a.slot;
|
||||
if (b.fellAt !== null) return b.slot;
|
||||
return a.integrityLost === b.integrityLost ? null : a.integrityLost > b.integrityLost ? a.slot : b.slot;
|
||||
}
|
||||
|
||||
class Versus {
|
||||
constructor(room, opts) {
|
||||
this.room = room;
|
||||
this.limit = opts.limit;
|
||||
this.rounds = opts.rounds;
|
||||
this.phase = 'lobby';
|
||||
this.round = 1;
|
||||
this.roles = { 0: coin(), 1: null }; // roles by seat; the creator's is a coin flip until somebody chooses
|
||||
this.roles[1] = opposite(this.roles[0]);
|
||||
this.random = true; // true while the roles are still the coin flip
|
||||
this.firstRoles = null; // the roles of round 1 of the current match (a rematch swaps them)
|
||||
this.ready = [false, false];
|
||||
this.nextVotes = [false, false];
|
||||
this.rematchVotes = [false, false];
|
||||
this.bot = null; // { slot, skill }: a computer holds that seat (its role is roles[slot])
|
||||
this.botCtl = null; // the NWBot of the current round
|
||||
this.botAcc = 0; this.botNextNs = 0n;
|
||||
this.history = [];
|
||||
this.result = null; this.winner = null; this.forfeit = null; this.scores = null;
|
||||
this.cdLeftMs = 0; this.cdSent = -1;
|
||||
this.nextLeftMs = 0;
|
||||
this.nextPrivNs = 0n;
|
||||
this.frozen = false;
|
||||
}
|
||||
|
||||
get mgr() { return this.room.manager; }
|
||||
humans() { return this.room.players.filter(Boolean); }
|
||||
// `gone`: a player that was just removed from the room (its seat is already empty) but still belongs in the result
|
||||
names(gone) { return [0, 1].map((s) => (this.room.players[s] ? this.room.players[s].name : this.bot && this.bot.slot === s ? BOT_NAME : gone && gone.slot === s ? gone.name : '')); }
|
||||
seated() { return this.humans().length + (this.bot ? 1 : 0); }
|
||||
|
||||
// ---------------------------------------------------------------- what clients are told
|
||||
readyMap() { return { 0: this.bot && this.bot.slot === 0 ? true : this.ready[0], 1: this.bot && this.bot.slot === 1 ? true : this.ready[1] }; }
|
||||
|
||||
msg() {
|
||||
const m = {
|
||||
t: 'vs', phase: this.phase, round: this.round, rounds: this.rounds,
|
||||
roles: { 0: this.roles[0], 1: this.roles[1] }, random: this.random,
|
||||
bot: this.bot ? { slot: this.bot.slot, role: this.roles[this.bot.slot], skill: this.bot.skill, name: BOT_NAME } : null,
|
||||
limit: this.limit, ready: this.readyMap(), frozen: this.frozen,
|
||||
};
|
||||
if (this.phase === 'countdown') m.countdown = Math.max(0, Math.ceil(this.cdLeftMs / 1000));
|
||||
if (this.phase === 'roundover') { m.next = { 0: this.isVoted(this.nextVotes, 0), 1: this.isVoted(this.nextVotes, 1) }; m.nextIn = Math.max(0, Math.ceil(this.nextLeftMs / 1000)); }
|
||||
if (this.phase === 'roundover' || this.phase === 'matchover') m.result = this.result;
|
||||
if (this.history.length) m.history = this.history; // the finished rounds of this match (also while round 2 is played: a reconnecting client can show round 1)
|
||||
if (this.phase === 'matchover') {
|
||||
m.scores = this.scores; m.winner = this.winner; m.forfeit = this.forfeit;
|
||||
m.rematch = { 0: this.isVoted(this.rematchVotes, 0), 1: this.isVoted(this.rematchVotes, 1) };
|
||||
}
|
||||
return m;
|
||||
}
|
||||
isVoted(votes, slot) { return this.bot && this.bot.slot === slot ? true : votes[slot]; }
|
||||
broadcastVs() { this.room.broadcast(this.msg()); }
|
||||
|
||||
// Role-private data for ONE human: only what the sim says that role may see, addressed by the seat's current role.
|
||||
sendPriv(p) {
|
||||
if (!p || !p.conn || this.phase === 'lobby') return;
|
||||
const role = this.roles[p.slot];
|
||||
const ps = this.room.sim.privateState(role);
|
||||
if (ps) this.room.send(p, Object.assign({ t: 'priv', role }, ps));
|
||||
}
|
||||
sendPrivAll() { for (const p of this.humans()) this.sendPriv(p); }
|
||||
// sync / a (re)joining client: the whole picture for one player
|
||||
sendTo(p) { this.room.send(p, this.msg()); this.sendPriv(p); }
|
||||
|
||||
// ---------------------------------------------------------------- seats (hooks called by Room)
|
||||
// The seat a joining pid gets, or -1. A computer holds its seat during a match; in the lobby the next human takes it over.
|
||||
freeSlot() {
|
||||
const pl = this.room.players;
|
||||
for (let s = 0; s < 2; s++) if (!pl[s] && !(this.bot && this.bot.slot === s)) return s;
|
||||
if (this.phase === 'lobby' && this.bot && !pl[this.bot.slot]) return this.bot.slot;
|
||||
return -1;
|
||||
}
|
||||
onSeated(p) { // a NEW player took a seat (not a reconnect)
|
||||
if (this.bot && this.bot.slot === p.slot) this.bot = null;
|
||||
this.ready = [false, false]; this.rematchVotes[p.slot] = false; this.nextVotes[p.slot] = false;
|
||||
}
|
||||
// after `joined` was sent to `ctx`: everybody else hears the new picture, the joiner gets its private data
|
||||
onJoined(p, resumed, exceptConn) {
|
||||
this.updateFrozen();
|
||||
this.room.broadcast(this.msg(), exceptConn);
|
||||
this.sendPriv(p);
|
||||
this.checkProgress(); // (a vote that was only waiting for this player to be back)
|
||||
}
|
||||
onPresence() { this.updateFrozen(true); }
|
||||
updateFrozen(announce) {
|
||||
const humans = this.humans();
|
||||
const f = (this.phase === 'playing' || this.phase === 'countdown' || this.phase === 'roundover') && humans.some((h) => !h.conn);
|
||||
if (f !== this.frozen) { this.frozen = f; if (announce) this.broadcastVs(); }
|
||||
return f;
|
||||
}
|
||||
// A human left for good (deliberate leave, or the grace period ran out).
|
||||
onRemoved(p) {
|
||||
const slot = p.slot;
|
||||
this.ready = [false, false]; this.nextVotes[slot] = false; this.rematchVotes[slot] = false;
|
||||
switch (this.phase) {
|
||||
case 'playing': this.forfeitMatch(p, true); break;
|
||||
case 'countdown':
|
||||
if (this.round === 1) this.toLobby(); else this.forfeitMatch(p, false);
|
||||
break;
|
||||
case 'roundover': this.forfeitMatch(p, false); break;
|
||||
default: this.updateFrozen(); this.broadcastVs(); // lobby, matchover: the picture just changes
|
||||
}
|
||||
this.updateFrozen();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the lobby messages ({ t:'vs', c, v })
|
||||
// Returns false only for a malformed message (the caller counts those); refusals are rejects.
|
||||
handleMessage(p, msg) {
|
||||
switch (msg.c) {
|
||||
case 'role':
|
||||
if (msg.v !== 'attacker' && msg.v !== 'defender' && msg.v !== 'random') return false;
|
||||
return this.doRole(p, msg.v);
|
||||
case 'ready':
|
||||
if (typeof msg.v !== 'boolean') return false;
|
||||
return this.doReady(p, msg.v);
|
||||
case 'bot': {
|
||||
if (msg.v !== null && msg.v !== 'attacker' && msg.v !== 'defender') return false;
|
||||
if (msg.skill !== undefined && msg.skill !== null && !(finite(msg.skill) && msg.skill >= 0 && msg.skill <= 1)) return false;
|
||||
return this.doBot(p, msg.v, msg.skill);
|
||||
}
|
||||
case 'start': return this.doStart(p);
|
||||
case 'next': return this.doNext(p);
|
||||
case 'rematch': return this.doRematch(p);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
rej(p, c, reason) { this.room.reject(p, c, reason); return true; }
|
||||
|
||||
doRole(p, v) {
|
||||
if (this.phase !== 'lobby') return this.rej(p, 'role', 'phase');
|
||||
if (v === 'random') { this.roles[p.slot] = coin(); this.random = true; } else { this.roles[p.slot] = v; this.random = false; }
|
||||
this.roles[1 - p.slot] = opposite(this.roles[p.slot]);
|
||||
this.ready = [false, false]; // everybody agrees to the roles they actually get
|
||||
this.broadcastVs();
|
||||
return true;
|
||||
}
|
||||
|
||||
doReady(p, v) {
|
||||
if (this.phase !== 'lobby') return this.rej(p, 'ready', 'phase');
|
||||
this.ready[p.slot] = v;
|
||||
this.broadcastVs();
|
||||
return true;
|
||||
}
|
||||
|
||||
doBot(p, v, skill) {
|
||||
if (!p.host) return this.rej(p, 'bot', 'not_host');
|
||||
if (this.phase !== 'lobby') return this.rej(p, 'bot', 'phase');
|
||||
if (v === null) {
|
||||
if (this.bot) { this.bot = null; this.ready = [false, false]; this.broadcastVs(); }
|
||||
return true;
|
||||
}
|
||||
const humans = this.humans();
|
||||
if (humans.length !== 1 || humans[0] !== p) return this.rej(p, 'bot', 'full'); // the computer takes the EMPTY seat
|
||||
const sk = skill === undefined || skill === null ? (this.bot ? this.bot.skill : 1) : skill;
|
||||
this.bot = { slot: 1 - p.slot, skill: sk };
|
||||
this.roles[this.bot.slot] = v; this.roles[p.slot] = opposite(v); this.random = false;
|
||||
this.ready = [false, false];
|
||||
this.broadcastVs();
|
||||
return true;
|
||||
}
|
||||
|
||||
doStart(p) {
|
||||
if (!p.host) return this.rej(p, 'start', 'not_host');
|
||||
if (this.phase !== 'lobby') return this.rej(p, 'start', 'phase');
|
||||
if (this.seated() < 2) return this.rej(p, 'start', 'no_opponent');
|
||||
const humans = this.humans();
|
||||
if (humans.some((h) => !h.conn)) return this.rej(p, 'start', 'offline');
|
||||
if (humans.some((h) => h !== p && !this.ready[h.slot])) return this.rej(p, 'start', 'not_ready');
|
||||
this.beginMatch();
|
||||
return true;
|
||||
}
|
||||
|
||||
doNext(p) {
|
||||
if (this.phase !== 'roundover') return this.rej(p, 'next', 'phase');
|
||||
this.nextVotes[p.slot] = true;
|
||||
this.broadcastVs();
|
||||
this.checkProgress();
|
||||
return true;
|
||||
}
|
||||
|
||||
doRematch(p) {
|
||||
if (this.phase !== 'matchover') return this.rej(p, 'rematch', 'phase');
|
||||
if (this.seated() < 2) return this.rej(p, 'rematch', 'no_opponent');
|
||||
this.rematchVotes[p.slot] = true;
|
||||
this.broadcastVs();
|
||||
this.checkProgress();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Votes that completed: roundover -> the next round, matchover -> a new match. Needs every human online (an absent one is waited for).
|
||||
checkProgress() {
|
||||
const humans = this.humans();
|
||||
if (!humans.length || humans.some((h) => !h.conn)) return;
|
||||
if (this.phase === 'roundover' && humans.every((h) => this.nextVotes[h.slot])) this.nextRound();
|
||||
else if (this.phase === 'matchover' && this.seated() === 2 && humans.every((h) => this.rematchVotes[h.slot])) this.rematch();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rounds
|
||||
beginMatch() {
|
||||
this.round = 1; this.history = []; this.result = null; this.winner = null; this.forfeit = null; this.scores = null;
|
||||
this.firstRoles = { 0: this.roles[0], 1: this.roles[1] };
|
||||
this.startRound();
|
||||
}
|
||||
nextRound() {
|
||||
this.round++;
|
||||
this.roles = swapRoles(this.roles);
|
||||
this.startRound();
|
||||
}
|
||||
rematch() {
|
||||
this.roles = swapRoles(this.firstRoles);
|
||||
this.random = false;
|
||||
this.rematchVotes = [false, false];
|
||||
this.beginMatch();
|
||||
}
|
||||
|
||||
// A fresh Sim for the round, a bot for the computer seat, and the countdown. Clients get a new `state` (newgame:true) and the vs picture.
|
||||
startRound() {
|
||||
const room = this.room;
|
||||
room.sim = new TD.Sim({ map: room.sim.mapId, mode: 'versus', limit: this.limit });
|
||||
room.lastSentRev = room.sim.rev;
|
||||
room.acc = 0;
|
||||
this.botAcc = 0; this.botNextNs = 0n;
|
||||
this.botCtl = null;
|
||||
if (this.bot) {
|
||||
try {
|
||||
this.botCtl = NWBot.create(this.guardedSim(room.sim), this.roles[this.bot.slot], { seed: crypto.randomInt(1, 0x7fffffff), skill: this.bot.skill, by: this.bot.slot });
|
||||
} catch (e) { room.log('could not create the computer player: ' + (e && e.stack || e)); }
|
||||
}
|
||||
this.nextVotes = [false, false];
|
||||
this.rematchVotes = [false, false];
|
||||
this.result = null;
|
||||
this.phase = 'countdown';
|
||||
this.cdLeftMs = this.mgr.vsCountdownMs; this.cdSent = -1;
|
||||
this.updateFrozen();
|
||||
room.broadcast(room.stateMsg({ newgame: true }));
|
||||
this.broadcastVs();
|
||||
this.sendPrivAll();
|
||||
this.cdSent = Math.ceil(this.cdLeftMs / 1000);
|
||||
room.log('versus round ' + this.round + '/' + this.rounds + ' (' + this.limit + ' s): countdown; roles ' + this.roles[0] + '/' + this.roles[1] + (this.bot ? ', computer is seat ' + this.bot.slot : ''));
|
||||
}
|
||||
|
||||
beginPlay() {
|
||||
this.phase = 'playing';
|
||||
this.room.acc = 0; this.botAcc = 0;
|
||||
this.broadcastVs();
|
||||
this.sendPrivAll();
|
||||
}
|
||||
|
||||
// The sim says the round is over (integrity gone / time up).
|
||||
endRound() {
|
||||
const sim = this.room.sim, res = sim.vs.result;
|
||||
this.finishRound({ winner: res.winner, t: res.t, integrityLost: res.integrityLost });
|
||||
}
|
||||
|
||||
finishRound(result) {
|
||||
this.botCtl = null;
|
||||
const entry = historyEntry(this.round, this.roles, result);
|
||||
this.result = entry.result;
|
||||
this.history.push(entry);
|
||||
this.room.log('versus round ' + this.round + ' over: the ' + result.winner + ' wins at ' + result.t + ' s, integrity lost ' + result.integrityLost);
|
||||
if (this.round < this.rounds) {
|
||||
this.phase = 'roundover';
|
||||
this.nextVotes = [false, false];
|
||||
this.nextLeftMs = this.mgr.vsNextMs;
|
||||
} else {
|
||||
this.phase = 'matchover';
|
||||
this.scores = matchScores(this.history, this.names());
|
||||
const w = matchWinner(this.scores);
|
||||
this.winner = w;
|
||||
this.forfeit = null;
|
||||
this.rematchVotes = [false, false];
|
||||
}
|
||||
this.updateFrozen();
|
||||
this.broadcastVs();
|
||||
this.sendPrivAll();
|
||||
}
|
||||
|
||||
// A human is gone for good while a match was on: the one who stays wins it. `inRound`: the round was being played (its result is the
|
||||
// forfeit); otherwise it is between rounds / in the countdown.
|
||||
forfeitMatch(gone, inRound) {
|
||||
const sim = this.room.sim, leaver = gone.slot, stay = 1 - leaver;
|
||||
this.botCtl = null;
|
||||
if (inRound) {
|
||||
sim.vsEnd(this.roles[stay]); // the sim's own end of round: state 'over', the round event
|
||||
const res = sim.vs.result;
|
||||
const entry = historyEntry(this.round, this.roles, { winner: res.winner, t: res.t, integrityLost: res.integrityLost, forfeit: true });
|
||||
this.history.push(entry); this.result = entry.result;
|
||||
}
|
||||
this.phase = 'matchover';
|
||||
this.scores = matchScores(this.history, this.names(gone));
|
||||
this.winner = stay; this.forfeit = leaver;
|
||||
this.room.log('versus match forfeited by seat ' + leaver + (inRound ? ' during round ' + this.round : ' between rounds'));
|
||||
this.rematchVotes = [false, false];
|
||||
this.updateFrozen();
|
||||
this.broadcastVs();
|
||||
this.sendPrivAll();
|
||||
}
|
||||
|
||||
toLobby() {
|
||||
this.botCtl = null;
|
||||
this.room.log('versus: back to the lobby (a player left before the first round began)');
|
||||
this.phase = 'lobby'; this.round = 1; this.history = []; this.result = null; this.winner = null; this.forfeit = null; this.scores = null;
|
||||
this.room.acc = 0;
|
||||
this.updateFrozen();
|
||||
this.broadcastVs();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- game commands
|
||||
// One door for every command that reaches the sim in a versus room, humans and the computer alike: the phase gate, the role of the
|
||||
// seat for THIS round (never taken from the message), the seat as `by`.
|
||||
applyCmd(slot, cmd) {
|
||||
if (this.phase !== 'playing') return { ok: false, reason: this.phase === 'roundover' || this.phase === 'matchover' ? 'over' : 'phase' };
|
||||
if (this.frozen) return { ok: false, reason: 'frozen' };
|
||||
try { return this.room.sim.cmd(Object.assign({}, cmd, { role: this.roles[slot], by: slot })); } catch (e) {
|
||||
this.room.log('sim.cmd threw: ' + (e && e.stack || e));
|
||||
return { ok: false, reason: 'error' };
|
||||
}
|
||||
}
|
||||
|
||||
// Returns false when the message is malformed.
|
||||
handleCmd(p, msg) {
|
||||
const c = msg.c;
|
||||
if (typeof c !== 'string' || !VS_CMDS.has(c)) return false;
|
||||
for (const k of ['lv', 'n']) if (msg[k] !== undefined && msg[k] !== null && !Number.isInteger(msg[k])) return false;
|
||||
for (const k of ['gate', 'tid']) if (msg[k] !== undefined && msg[k] !== null && !Number.isInteger(msg[k])) return false;
|
||||
if (msg.kind !== undefined && (typeof msg.kind !== 'string' || msg.kind.length > MAX_KIND_LEN)) return false;
|
||||
if (msg.id !== undefined) {
|
||||
if (STRING_ID_CMDS.has(c) ? (typeof msg.id !== 'string' || msg.id.length > MAX_KIND_LEN) : (NUMBER_ID_CMDS.has(c) && !finite(msg.id))) return false;
|
||||
}
|
||||
// Whitelisted fields only; `role` and `by` come from the seat, 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, kind: msg.kind, gate: msg.gate, tid: msg.tid };
|
||||
const r = this.applyCmd(p.slot, cmd);
|
||||
if (!r || !r.ok) this.room.reject(p, c, (r && r.reason) || 'error', msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
// pause / speed exist in co-op only (either would be exploitable here): a well-formed one is refused, a malformed one is malformed.
|
||||
handleCtl(p, msg) {
|
||||
if ((msg.c === 'pause' && typeof msg.v === 'boolean') || (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3))) {
|
||||
this.room.reject(p, msg.c, 'versus');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the loop
|
||||
// The computer sees the sim through this: reads and queries go straight through, `cmd` goes through applyCmd (the same door as a human's,
|
||||
// with the computer seat's role), writes are dropped.
|
||||
guardedSim(sim) {
|
||||
const self = this, bound = new Map();
|
||||
return new Proxy(sim, {
|
||||
get(target, key) {
|
||||
if (key === 'cmd') return (c) => (self.room.sim === sim && self.bot ? self.applyCmd(self.bot.slot, c) : { ok: false, reason: 'over' });
|
||||
const v = target[key];
|
||||
if (typeof v !== 'function') return v;
|
||||
let f = bound.get(key);
|
||||
if (!f) { f = v.bind(target); bound.set(key, f); }
|
||||
return f;
|
||||
},
|
||||
set() { return true; },
|
||||
});
|
||||
}
|
||||
|
||||
thinkBot(now) {
|
||||
if (!this.botCtl || this.phase !== 'playing' || this.botAcc < BOT_THINK_S) return;
|
||||
const mgr = this.mgr;
|
||||
if (mgr.botSpentNs >= BOT_BUDGET_NS || now < this.botNextNs) return; // over budget: it will think a little later with the time it saved up
|
||||
const dt = this.botAcc; this.botAcc = 0;
|
||||
const t0 = nowNs();
|
||||
try { this.botCtl.think(dt); } catch (e) {
|
||||
this.room.log('the computer player failed and is switched off: ' + (e && e.stack || e));
|
||||
this.botCtl = null;
|
||||
}
|
||||
const spent = nowNs() - t0;
|
||||
mgr.botSpentNs += spent;
|
||||
this.botNextNs = now + spent * 3n; // a heavy decision buys a quiet period: at most ~25% of the loop
|
||||
}
|
||||
|
||||
// Called by Room.step in place of the co-op step.
|
||||
step(now) {
|
||||
const room = this.room, L = room.constructor.LIMITS;
|
||||
const last = room.lastNs;
|
||||
room.lastNs = now;
|
||||
const humans = this.humans();
|
||||
if (!humans.some((h) => h.conn)) { room.acc = 0; room.nextSnapNs = now; return; }
|
||||
const dt = last === null ? 0 : Math.min(L.MAX_CATCHUP_S, Number(now - last) / 1e9);
|
||||
const frozen = this.updateFrozen(true);
|
||||
|
||||
if (frozen) room.acc = 0; // a human seat is offline: the round waits (the grace period decides)
|
||||
else if (this.phase === 'countdown') {
|
||||
this.cdLeftMs -= dt * 1000;
|
||||
const sec = Math.max(0, Math.ceil(this.cdLeftMs / 1000));
|
||||
if (this.cdLeftMs <= 0) this.beginPlay();
|
||||
else if (sec !== this.cdSent) { this.cdSent = sec; this.broadcastVs(); }
|
||||
} else if (this.phase === 'roundover') {
|
||||
this.nextLeftMs -= dt * 1000;
|
||||
if (this.nextLeftMs <= 0) this.nextRound();
|
||||
} else if (this.phase === 'playing') {
|
||||
const sim = room.sim;
|
||||
room.acc += dt;
|
||||
let n = 0, ticked = 0;
|
||||
const t0 = nowNs();
|
||||
while (room.acc >= TD.STEP && sim.state === 'playing') {
|
||||
sim.tick(TD.STEP); room.acc -= TD.STEP; ticked++;
|
||||
if ((++n & 7) === 0 && nowNs() - t0 > L.STEP_BUDGET_NS) { room.acc = Math.min(room.acc, TD.STEP); break; }
|
||||
}
|
||||
this.botAcc += ticked * TD.STEP;
|
||||
this.thinkBot(now);
|
||||
if (sim.state !== 'playing') this.endRound();
|
||||
} else room.acc = 0;
|
||||
|
||||
room.snapIfDue(now);
|
||||
if ((this.phase === 'countdown' || this.phase === 'playing') && now >= this.nextPrivNs) { this.sendPrivAll(); this.nextPrivNs = now + PRIV_NS; }
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Versus, VS_CMDS, historyEntry, matchScores, matchWinner, swapRoles, opposite, BOT_NAME, BOT_THINK_S, BOT_BUDGET_NS };
|
||||
Loading…
Add table
Add a link
Reference in a new issue