'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 };