'use strict'; /* * Versus protocol tests (docs/PROTOCOL.md "Versus"): a real server on port 0 and real ws clients, plus unit cases for the match rules. * The helpers are a small copy of the ones in server.test.js (that file keeps its own, "node --test" runs every file in test/). */ const test = require('node:test'); const assert = require('node:assert/strict'); const WebSocket = require('ws'); const { createServer } = require('../server'); const { Room } = require('../server/room'); const V = require('../server/versus'); const TD = require('../public/js/sim.js'); const { VS } = TD; const noop = () => {}; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let pidCounter = 0; const newPid = () => 'vspid' + String(++pidCounter).padStart(6, '0'); async function until(fn, ms = 3000, label = 'condition') { const end = Date.now() + ms; for (;;) { const v = fn(); if (v) return v; if (Date.now() > end) throw new Error('timed out waiting for ' + label); await sleep(4); } } class Client { constructor(url) { this.msgs = []; this.closeInfo = null; this.opened = false; this.error = null; const ws = this.ws = new WebSocket(url); ws.on('open', () => { this.opened = true; }); ws.on('message', (data) => { try { this.msgs.push(JSON.parse(data.toString())); } catch (e) { this.msgs.push({ t: '?bad-json' }); } }); ws.on('close', (code, reason) => { this.closeInfo = { code, reason: reason.toString() }; }); ws.on('error', (err) => { this.error = err; }); } async open() { await until(() => this.opened || this.error, 3000, 'websocket open'); if (!this.opened) throw this.error; return this; } send(o) { this.ws.send(JSON.stringify(o)); } mark() { return this.msgs.length; } // The first message after `from` (a mark) that matches; never consumes anything, so the order of the waits does not matter after(from, pred, ms = 3000, label = 'message') { return until(() => this.msgs.slice(from).find(pred), ms, label + ' (have: ' + this.msgs.slice(-6).map((m) => m.t + (m.phase ? ':' + m.phase : '')).join(',') + (this.closeInfo ? '; closed ' + this.closeInfo.code : '') + ')'); } vs(from, pred, ms) { return this.after(from, (m) => m.t === 'vs' && (!pred || pred(m)), ms, 'vs'); } type(from, t, ms) { return this.after(from, (m) => m.t === t, ms, t); } last(t) { for (let i = this.msgs.length - 1; i >= 0; i--) if (this.msgs[i].t === t) return this.msgs[i]; return null; } closed(ms = 3000) { return until(() => this.closeInfo, ms, 'close'); } // Round trip: when the echo is back, everything the server sent before it has arrived. async barrier() { const ts = Math.random(); const from = this.mark(); this.send({ t: 'rtt', ts }); await this.after(from, (m) => m.t === 'rtt' && m.ts === ts, 3000, 'barrier'); } } async function withServer(opts, fn) { const srv = await createServer(Object.assign({ port: 0, host: '127.0.0.1', log: noop, graceMs: 400, pingMs: 0, vsCountdownMs: 150, vsNextMs: 60000 }, opts)); const clients = []; const S = { srv, url: 'ws://127.0.0.1:' + srv.port + '/ws', client() { const c = new Client(S.url); clients.push(c); return c; }, async join({ name = 'Alice', pid = newPid(), room, extra } = {}) { const c = S.client(); await c.open(); c.send(Object.assign({ t: 'join', pid, name }, room !== undefined ? { room } : {}, extra)); const r = await until(() => c.msgs.find((x) => x.t === 'joined' || x.t === 'error'), 3000, 'joined'); return { c, pid, r, room: r.room }; }, // host (versus) + guest; roles: host attacker, guest defender unless `hostRole` says otherwise. Returns after both agree on the roles. async pair({ hostRole = 'attacker', extra } = {}) { const a = await S.join({ name: 'Alice', extra: Object.assign({ mode: 'versus' }, extra) }); const b = await S.join({ name: 'Bob', room: a.room }); const m = a.c.mark(); a.c.send({ t: 'vs', c: 'role', v: hostRole }); await a.c.vs(m, (x) => x.roles[a.r.you.slot] === hostRole); await b.c.vs(0, (x) => x.roles[a.r.you.slot] === hostRole); return { a, b, code: a.room, room: () => S.srv.rooms.get(a.room) }; }, // pair + ready + start, and wait until the round is being played async play(o) { const P = await S.pair(o); P.b.c.send({ t: 'vs', c: 'ready', v: true }); await P.a.c.vs(0, (x) => x.ready[P.b.r.you.slot] === true); const ma = P.a.c.mark(), mb = P.b.c.mark(); P.a.c.send({ t: 'vs', c: 'start' }); await P.a.c.vs(ma, (x) => x.phase === 'playing'); await P.b.c.vs(mb, (x) => x.phase === 'playing'); return P; }, }; try { return await fn(S); } finally { for (const c of clients) { try { c.ws.terminate(); } catch (e) { /* ignore */ } } await srv.close(); } } // every key name that occurs anywhere inside a JSON value function keysOf(v, out) { out = out || new Set(); if (Array.isArray(v)) for (const x of v) keysOf(x, out); else if (v && typeof v === 'object') for (const k of Object.keys(v)) { out.add(k); keysOf(v[k], out); } return out; } const rej = (c, from, cmd) => c.after(from, (m) => m.t === 'reject' && m.c === cmd, 3000, 'reject ' + cmd); // ================================================================== match rules (pure) const hist = (a0, ...rest) => [a0, ...rest]; const round = (n, roles, winner, t, lost, extra) => V.historyEntry(n, roles, Object.assign({ winner, t, integrityLost: lost }, extra)); test('match rules: the faster fall wins; one fall beats none; else the bigger integrity loss; ties are draws', () => { const R1 = { 0: 'attacker', 1: 'defender' }, R2 = { 0: 'defender', 1: 'attacker' }; const names = ['A', 'B']; const winner = (h) => V.matchWinner(V.matchScores(h, names)); // both felled the server: the earlier fall wins (slot 0 attacked in round 1, slot 1 in round 2) assert.equal(winner(hist(round(1, R1, 'attacker', 200, 20), round(2, R2, 'attacker', 300, 20))), 0); assert.equal(winner(hist(round(1, R1, 'attacker', 400, 20), round(2, R2, 'attacker', 300, 20))), 1); assert.equal(winner(hist(round(1, R1, 'attacker', 300, 20), round(2, R2, 'attacker', 300, 20))), null, 'the same second: a draw'); // only one felled it assert.equal(winner(hist(round(1, R1, 'defender', 720, 19), round(2, R2, 'attacker', 650, 20))), 1); assert.equal(winner(hist(round(1, R1, 'attacker', 650, 20), round(2, R2, 'defender', 720, 19))), 0); // neither: who took off more assert.equal(winner(hist(round(1, R1, 'defender', 720, 7), round(2, R2, 'defender', 720, 3))), 0); assert.equal(winner(hist(round(1, R1, 'defender', 720, 2), round(2, R2, 'defender', 720, 9))), 1); assert.equal(winner(hist(round(1, R1, 'defender', 720, 5), round(2, R2, 'defender', 720, 5))), null); assert.equal(winner(hist(round(1, R1, 'defender', 720, 0), round(2, R2, 'defender', 720, 0))), null); // the scores say what the contract says: { slot, name, fellAt|null, integrityLost } const sc = V.matchScores(hist(round(1, R1, 'attacker', 200.5, 20), round(2, R2, 'defender', 720, 6)), names); assert.deepEqual(sc, [{ slot: 0, name: 'A', fellAt: 200.5, integrityLost: 20 }, { slot: 1, name: 'B', fellAt: null, integrityLost: 6 }]); // a forfeited round is never "the server fell" const ff = V.matchScores(hist(round(1, R1, 'attacker', 12, 3, { forfeit: true })), names); assert.equal(ff[0].fellAt, null); assert.equal(ff[0].integrityLost, 3); // roles swap, and the history entry names both seats assert.deepEqual(V.swapRoles(R1), R2); assert.deepEqual(round(2, R2, 'defender', 720, 0).result.attacker, 1); assert.deepEqual(round(2, R2, 'defender', 720, 0).result.defender, 0); }); // ================================================================== creating a versus room test('versus: creating join takes mode / limit / rounds; the joined message carries the lobby; co-op is untouched', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus', limit: 480, rounds: 2 } }); assert.equal(a.r.t, 'joined'); assert.equal(a.r.state.mode, 'versus'); assert.equal(a.r.state.limit, 480); assert.equal(a.r.vs.phase, 'lobby'); assert.equal(a.r.vs.round, 1); assert.equal(a.r.vs.rounds, 2); assert.equal(a.r.vs.limit, 480); assert.equal(a.r.vs.bot, null); assert.deepEqual(Object.keys(a.r.vs.roles).sort(), ['0', '1']); assert.notEqual(a.r.vs.roles[0], a.r.vs.roles[1]); assert.equal(a.r.snap.s, 'playing'); // a joiner takes the room's settings: nothing it sends is even looked at const b = await S.join({ name: 'Bob', room: a.room, extra: { mode: 'bogus', limit: 'x', rounds: 9 } }); assert.equal(b.r.t, 'joined'); assert.equal(b.r.vs.limit, 480); assert.equal(b.c.msgs[0].t, 'joined', 'nothing reaches a new connection before its joined message'); // default limit const d = await S.join({ extra: { mode: 'versus' } }); assert.equal(d.r.state.limit, VS.DEFAULT_LIMIT); assert.equal(d.r.vs.limit, VS.DEFAULT_LIMIT); // co-op (explicit or implicit, nulls included): no vs block, no mode in the state for (const extra of [{}, { mode: 'coop' }, { mode: null, limit: 999, rounds: 7 }, { mode: 'coop', limit: 999 }]) { const c = await S.join({ extra }); assert.equal(c.r.t, 'joined'); assert.equal('vs' in c.r, false); assert.equal('mode' in c.r.state, false); assert.equal('limit' in c.r.state, false); } }); }); test('versus: a bad mode, limit or rounds is refused with its own code and no room is created', async () => { await withServer({}, async (S) => { const cases = [ [{ mode: 'bogus' }, 'bad_mode'], [{ mode: 5 }, 'bad_mode'], [{ mode: 'toString' }, 'bad_mode'], [{ mode: ['versus'] }, 'bad_mode'], [{ mode: 'versus', limit: 100 }, 'bad_limit'], [{ mode: 'versus', limit: '720' }, 'bad_limit'], [{ mode: 'versus', limit: 720.5 }, 'bad_limit'], [{ mode: 'versus', limit: {} }, 'bad_limit'], [{ mode: 'versus', rounds: 3 }, 'bad_rounds'], [{ mode: 'versus', rounds: '2' }, 'bad_rounds'], [{ mode: 'versus', rounds: 0 }, 'bad_rounds'], ]; for (const [extra, code] of cases) { const r = await S.join({ extra }); assert.equal(r.r.t, 'error', JSON.stringify(extra)); assert.equal(r.r.code, code, JSON.stringify(extra)); await r.c.closed(); assert.equal(r.c.closeInfo.code, 4400); } assert.equal(S.srv.rooms.size, 0); // every limit the table offers works for (const limit of VS.LIMITS) assert.equal((await S.join({ extra: { mode: 'versus', limit } })).r.state.limit, limit); }); }); // ================================================================== the lobby test('versus lobby: roles are opposite, random re-rolls, ready and start are checked, nothing ticks or accepts commands', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus' } }); const m0 = a.c.mark(); a.c.send({ t: 'vs', c: 'start' }); assert.equal((await rej(a.c, m0, 'start')).reason, 'no_opponent', 'nobody to play against yet'); const b = await S.join({ name: 'Bob', room: a.room }); const sa = a.r.you.slot, sb = b.r.you.slot; assert.equal(b.r.vs.phase, 'lobby'); // the host chooses let m = a.c.mark(); a.c.send({ t: 'vs', c: 'role', v: 'attacker' }); let v = await a.c.vs(m, (x) => x.roles[sa] === 'attacker'); assert.equal(v.roles[sb], 'defender'); assert.equal(v.random, false); // the guest chooses the same role: it gets it and the host gets the other one; the last choice wins m = b.c.mark(); b.c.send({ t: 'vs', c: 'role', v: 'attacker' }); v = await b.c.vs(m, (x) => x.roles[sb] === 'attacker'); assert.equal(v.roles[sa], 'defender'); // random: still opposite roles, and marked as random for (let i = 0; i < 4; i++) { m = b.c.mark(); b.c.send({ t: 'vs', c: 'role', v: 'random' }); v = await b.c.vs(m, (x) => x.random === true); assert.notEqual(v.roles[sa], v.roles[sb]); } // ready: not required of the host; a role change clears everybody's ready m = a.c.mark(); b.c.send({ t: 'vs', c: 'ready', v: true }); v = await a.c.vs(m, (x) => x.ready[sb] === true); assert.equal(v.ready[sa], false); m = a.c.mark(); a.c.send({ t: 'vs', c: 'role', v: 'defender' }); v = await a.c.vs(m, (x) => x.roles[sa] === 'defender'); assert.equal(v.ready[sb], false, 'ready is cleared when the roles change'); // start: guest cannot, host needs the guest ready m = b.c.mark(); b.c.send({ t: 'vs', c: 'start' }); assert.equal((await rej(b.c, m, 'start')).reason, 'not_host'); m = a.c.mark(); a.c.send({ t: 'vs', c: 'start' }); assert.equal((await rej(a.c, m, 'start')).reason, 'not_ready'); // `next` and `rematch` mean nothing in the lobby; a game command is refused for (const c of ['next', 'rematch']) { m = a.c.mark(); a.c.send({ t: 'vs', c }); assert.equal((await rej(a.c, m, c)).reason, 'phase'); } m = a.c.mark(); a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 5, y: 5 }); assert.equal((await rej(a.c, m, 'place')).reason, 'phase'); m = b.c.mark(); b.c.send({ t: 'cmd', c: 'spawn', kind: 'ping' }); assert.equal((await rej(b.c, m, 'spawn')).reason, 'phase'); // snapshots keep flowing in the lobby (the client's watchdog needs them), but the sim does not move and nobody is paid const sim = S.srv.rooms.get(a.room).sim; await sleep(300); assert.equal(sim.time, 0, 'the lobby never ticks'); assert.equal(sim.towers.length, 0); const snaps = a.c.msgs.filter((x) => x.t === 'snap'); assert.ok(snaps.length >= 5, 'snapshots in the lobby: ' + snaps.length); assert.equal(snaps[snaps.length - 1].time, 0); }); }); test('versus lobby: unknown or ill-formed vs messages are malformed and counted like any other', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus' } }); for (const bad of [{ c: 'role', v: 'god' }, { c: 'role' }, { c: 'ready', v: 'yes' }, { c: 'ready' }, { c: 'bot', v: 'x' }, { c: 'bot' }, { c: 'bot', v: 'attacker', skill: 2 }, { c: 'bot', v: 'attacker', skill: 'high' }, { c: 'nope' }, { c: 5 }, {}]) { a.c.send(Object.assign({ t: 'vs' }, bad)); } // 11 malformed so far (the limit is 20): the socket still works, and after ten more it is closed with 4400 await a.c.barrier(); assert.equal(a.c.closeInfo, null); for (let i = 0; i < 10; i++) a.c.send({ t: 'vs', c: 'nope' }); assert.equal((await a.c.closed()).code, 4400); }); }); // ================================================================== a full match with two humans test('versus match: countdown, play, round over, next, swapped roles, match over with scores, rematch swaps again', async () => { await withServer({}, async (S) => { const P = await S.pair({ hostRole: 'attacker' }); const { a, b } = P, sa = a.r.you.slot, sb = b.r.you.slot; b.c.send({ t: 'vs', c: 'ready', v: true }); await a.c.vs(0, (x) => x.ready[sb] === true); const ma = a.c.mark(), mb = b.c.mark(); a.c.send({ t: 'vs', c: 'start' }); // countdown: a new game state for both, the round number, nothing moves; then playing const cdA = await a.c.vs(ma, (x) => x.phase === 'countdown'); assert.ok(cdA.countdown >= 1); assert.equal(cdA.round, 1); const stA = await a.c.type(ma, 'state'); assert.equal(stA.newgame, true); assert.equal(stA.state.mode, 'versus'); await b.c.type(mb, 'state'); const sim1 = P.room().sim; assert.equal(sim1.time, 0, 'no ticking during the countdown'); await a.c.vs(ma, (x) => x.phase === 'playing'); await b.c.vs(mb, (x) => x.phase === 'playing'); await sleep(120); assert.ok(P.room().sim.time > 0, 'the round ticks'); const snap = a.c.last('snap'); assert.deepEqual(Object.keys(snap.vs).sort(), ['lim', 'st', 't']); // the attacker's integrity win ends the round at once const m1a = a.c.mark(), m1b = b.c.mark(); P.room().sim.lives = 0; const ro = await a.c.vs(m1a, (x) => x.phase === 'roundover'); await b.c.vs(m1b, (x) => x.phase === 'roundover'); assert.equal(ro.round, 1); assert.equal(ro.result.winner, 'attacker'); assert.equal(ro.result.attacker, sa); assert.equal(ro.result.defender, sb); assert.equal(typeof ro.result.t, 'number'); assert.equal(ro.history.length, 1); assert.equal(ro.history[0].roles[sa], 'attacker'); assert.equal(P.room().sim.state, 'over'); const m1c = a.c.mark(); a.c.send({ t: 'cmd', c: 'spawn', kind: 'ping' }); assert.equal((await rej(a.c, m1c, 'spawn')).reason, 'over'); // `next` from one is not enough; from both it starts round 2 with the roles swapped on a fresh sim const m2a = a.c.mark(), m2b = b.c.mark(); a.c.send({ t: 'vs', c: 'next' }); const waiting = await b.c.vs(m2b, (x) => x.next && x.next[sa] === true); assert.equal(waiting.phase, 'roundover'); b.c.send({ t: 'vs', c: 'next' }); const cd2 = await a.c.vs(m2a, (x) => x.phase === 'countdown'); assert.equal(cd2.round, 2); assert.equal(cd2.roles[sa], 'defender'); assert.equal(cd2.roles[sb], 'attacker'); assert.equal(cd2.history.length, 1, 'round 1 stays on the picture while round 2 is played'); assert.equal(cd2.history[0].result.winner, 'attacker'); assert.equal(cd2.result, undefined, 'but `result` is only the round that just ended'); const st2 = await b.c.type(m2b, 'state'); assert.equal(st2.newgame, true); assert.equal(st2.snap.s, 'playing'); assert.notEqual(P.room().sim, sim1); await a.c.vs(m2a, (x) => x.phase === 'playing'); // each client now gets the private data of its NEW role await a.c.after(m2a, (m) => m.t === 'priv' && m.role === 'defender'); await b.c.after(m2b, (m) => m.t === 'priv' && m.role === 'attacker' && typeof m.credits === 'number'); // round 2: the clock runs out (the defender wins); the match is over const m3a = a.c.mark(), m3b = b.c.mark(); P.room().sim.time = P.room().sim.vs.limit - 0.05; const mo = await a.c.vs(m3a, (x) => x.phase === 'matchover'); await b.c.vs(m3b, (x) => x.phase === 'matchover'); assert.equal(mo.result.winner, 'defender'); assert.equal(mo.history.length, 2); assert.equal(mo.scores.length, 2); const scoreA = mo.scores.find((s) => s.slot === sa), scoreB = mo.scores.find((s) => s.slot === sb); assert.equal(typeof scoreA.fellAt, 'number'); assert.equal(scoreB.fellAt, null); assert.equal(scoreA.name, 'Alice'); assert.equal(scoreB.name, 'Bob'); assert.equal(mo.winner, sa, 'the one whose attack felled the server wins the match'); assert.equal(mo.forfeit, null); // rematch: needs both; the first roles swap; a new match from round 1 straight into the countdown const m4a = a.c.mark(), m4b = b.c.mark(); a.c.send({ t: 'vs', c: 'rematch' }); const wait = await b.c.vs(m4b, (x) => x.rematch && x.rematch[sa] === true); assert.equal(wait.phase, 'matchover'); b.c.send({ t: 'vs', c: 'rematch' }); const cd3 = await a.c.vs(m4a, (x) => x.phase === 'countdown'); assert.equal(cd3.round, 1); assert.equal(cd3.roles[sa], 'defender', 'the host attacked first, so now the guest does'); assert.equal(cd3.roles[sb], 'attacker'); await b.c.vs(m4b, (x) => x.phase === 'playing'); assert.equal(P.room().vsc.history.length, 0); }); }); test('versus match: a tie in everything is a draw; the defender timing out in both rounds goes to the one who took off more', async () => { await withServer({}, async (S) => { const P = await S.play({ hostRole: 'attacker' }); const { a, b } = P, sa = a.r.you.slot; const sim = () => P.room().sim; // round 1: time runs out with 5 integrity gone sim().vs.lost = 5; let m = a.c.mark(); sim().time = sim().vs.limit - 0.05; await a.c.vs(m, (x) => x.phase === 'roundover' && x.result.winner === 'defender'); assert.equal(P.room().vsc.result.integrityLost, 5); a.c.send({ t: 'vs', c: 'next' }); b.c.send({ t: 'vs', c: 'next' }); await a.c.vs(m, (x) => x.phase === 'playing' && x.round === 2); sim().vs.lost = 5; m = a.c.mark(); sim().time = sim().vs.limit - 0.05; const mo = await a.c.vs(m, (x) => x.phase === 'matchover'); assert.equal(mo.winner, null, 'equal integrity lost, nobody felled the server: a draw'); assert.deepEqual(mo.scores.map((s) => s.integrityLost), [5, 5]); assert.ok(mo.scores.every((s) => s.fellAt === null)); assert.equal(mo.forfeit, null); void b; void sa; }); }); test('versus countdown: a fresh sim exists but nothing ticks, nobody is paid and no command is accepted until the round starts', async () => { await withServer({ vsCountdownMs: 60000 }, async (S) => { const P = await S.pair({ hostRole: 'attacker' }); P.b.c.send({ t: 'vs', c: 'ready', v: true }); await P.a.c.vs(0, (x) => x.ready[P.b.r.you.slot] === true); const sim0 = P.room().sim; const m = P.a.c.mark(); P.a.c.send({ t: 'vs', c: 'start' }); const cd = await P.a.c.vs(m, (x) => x.phase === 'countdown'); assert.equal(cd.countdown, 60); assert.notEqual(P.room().sim, sim0, 'the round has its own sim'); const sim = P.room().sim; const credits = sim.vs.credits, gold = sim.gold; await sleep(400); assert.equal(sim.time, 0); assert.equal(sim.vs.credits, credits, 'no income during the countdown'); assert.equal(sim.gold, gold); const ma = P.a.c.mark(), mb = P.b.c.mark(); P.a.c.send({ t: 'cmd', c: 'spawn', kind: 'ping' }); P.b.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 8 }); P.b.c.send({ t: 'cmd', c: 'tool', id: 'scan', x: 5, y: 5 }); assert.equal((await rej(P.a.c, ma, 'spawn')).reason, 'phase'); assert.equal((await rej(P.b.c, mb, 'place')).reason, 'phase'); assert.equal((await rej(P.b.c, mb, 'tool')).reason, 'phase'); assert.equal(sim.towers.length, 0); assert.equal(sim.vs.credits, credits); // private data is already there in the countdown (the attacker sees its purse), the snapshot says the round has not started await P.a.c.after(m, (x) => x.t === 'priv' && x.role === 'attacker' && x.credits === credits); assert.equal(P.a.c.last('snap').time, 0); }); }); test('versus: the round result waits for `next`, but not for ever (vsNextMs)', async () => { await withServer({ vsNextMs: 250 }, async (S) => { const P = await S.play(); const m = P.a.c.mark(); P.room().sim.lives = 0; await P.a.c.vs(m, (x) => x.phase === 'roundover'); const cd = await P.a.c.vs(m, (x) => x.phase === 'countdown' && x.round === 2, 4000); assert.equal(cd.round, 2); }); }); // ================================================================== commands test('versus commands: the role comes from the seat; cross-role commands are rejected; a forged role or seat changes nothing', async () => { await withServer({}, async (S) => { const P = await S.play({ hostRole: 'attacker' }); const { a, b } = P, sa = a.r.you.slot, sb = b.r.you.slot; // a attacks, b defends const sim = () => P.room().sim; sim().gold = 5000; sim().vs.credits = 5000; // legitimate commands of each side work let m = a.c.mark(); a.c.send({ t: 'cmd', c: 'spawn', kind: 'ping', n: 2 }); m = b.c.mark(); b.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 3, y: 3 }); await b.c.after(m, (x) => x.t === 'snap' && x.tw && x.tw.length === 1); assert.equal(sim().towers.length, 1); assert.equal(sim().towers[0].owner, sb, '`by` is the seat'); assert.ok(sim().vs.stats.spawned + sim().vs.rel.length >= 1); // across the role line m = a.c.mark(); a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 6, y: 6 }); let r = await rej(a.c, m, 'place'); assert.equal(r.reason, 'role'); assert.equal(r.x, 6); m = b.c.mark(); b.c.send({ t: 'cmd', c: 'spawn', kind: 'ping' }); assert.equal((await rej(b.c, m, 'spawn')).reason, 'role'); for (const c of [{ c: 'stage', kind: 'ping' }, { c: 'launch' }, { c: 'tech', id: 'armor' }, { c: 'ability', id: 'surge' }]) { m = b.c.mark(); b.c.send(Object.assign({ t: 'cmd' }, c)); r = await rej(b.c, m, c.c); assert.equal(r.reason, 'role', c.c); if (c.id) assert.equal(r.id, c.id, 'a refused tool / ability / tech names its id'); } m = a.c.mark(); a.c.send({ t: 'cmd', c: 'tool', id: 'scan', x: 5, y: 5 }); assert.equal((await rej(a.c, m, 'tool')).reason, 'role'); m = a.c.mark(); a.c.send({ t: 'cmd', c: 'sell', id: sim().towers[0].id }); assert.equal((await rej(a.c, m, 'sell')).reason, 'role'); assert.equal(sim().towers.length, 1, 'the refused sell changed nothing'); // forging: a `role` / `by` field in the message is ignored (the seat decides) m = b.c.mark(); const spawned0 = sim().vs.stats.unitsSpent; b.c.send({ t: 'cmd', c: 'spawn', kind: 'ping', role: 'attacker', by: sa }); assert.equal((await rej(b.c, m, 'spawn')).reason, 'role'); assert.equal(sim().vs.stats.unitsSpent, spawned0, 'nothing was bought'); m = b.c.mark(); b.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 9, y: 9, role: 'attacker', by: sa }); await b.c.after(m, (x) => x.t === 'snap' && x.tw && x.tw.length === 2); assert.equal(sim().towers[1].owner, sb); // a tool and an ability do work for the right side; their refusals name the reason m = b.c.mark(); b.c.send({ t: 'cmd', c: 'tool', id: 'scan', x: 5, y: 5 }); b.c.send({ t: 'cmd', c: 'tool', id: 'scan', x: 5, y: 5 }); assert.equal((await rej(b.c, m, 'tool')).reason, 'cooldown'); m = a.c.mark(); a.c.send({ t: 'cmd', c: 'ability', id: 'nonsense' }); assert.equal((await rej(a.c, m, 'ability')).reason, 'bad_target'); // the co-op commands exist in versus only to be refused for (const c of ['wave', 'auto', 'continue']) { for (const who of [a, b]) { m = who.c.mark(); who.c.send({ t: 'cmd', c, v: true }); assert.equal((await rej(who.c, m, c)).reason, 'versus', c); } } // pause / speed: refused; a malformed one is malformed for (const ctl of [{ c: 'pause', v: true }, { c: 'pause', v: false }, { c: 'speed', v: 2 }, { c: 'speed', v: 3 }]) { m = a.c.mark(); a.c.send(Object.assign({ t: 'ctl' }, ctl)); assert.equal((await rej(a.c, m, ctl.c)).reason, 'versus'); } await sleep(60); assert.equal(P.room().paused, false); assert.equal(P.room().speed, 1); assert.equal(a.c.last('snap').pa, 0); assert.equal(a.c.last('snap').sp, 1); // newgame would swap in a co-op sim: refused, nothing changes const before = P.room().sim; m = a.c.mark(); a.c.send({ t: 'newgame', map: 'open' }); assert.equal((await rej(a.c, m, 'newgame')).reason, 'versus'); assert.equal(P.room().sim, before); }); }); test('versus commands: shapes are checked; a wrong type is malformed (and counted), a refused value is a reject', async () => { await withServer({}, async (S) => { const P = await S.play(); const { a, b } = P; const bad = [ { c: 'spawn', kind: 5 }, { c: 'spawn', kind: 'x'.repeat(40) }, { c: 'spawn', kind: 'ping', n: 'x' }, { c: 'spawn', kind: 'ping', n: 1.5 }, { c: 'spawn', kind: 'ping', gate: 'a' }, { c: 'ability', id: 7 }, { c: 'tech', id: {} }, { c: 'tool', id: 5 }, { c: 'ability', id: 'emp', tid: 'x' }, { c: 'sell', id: 'abc' }, { c: 'upgrade', id: 'abc' }, { c: 'bogus' }, { c: 5 }, {}, ]; for (const x of bad) a.c.send(Object.assign({ t: 'cmd' }, x)); await a.c.barrier(); assert.equal(a.c.closeInfo, null, 'fewer than 20 malformed messages: still connected'); assert.equal(P.room().sim.vs.rel.length + P.room().sim.monsters.length, 0, 'nothing of it reached the sim'); // values the sim itself refuses are rejects, not malformed const m = a.c.mark(); a.c.send({ t: 'cmd', c: 'spawn', kind: 'nosuchkind' }); a.c.send({ t: 'cmd', c: 'spawn', kind: 'ping', n: 100000 }); a.c.send({ t: 'cmd', c: 'spawn', kind: 'ping', gate: 99 }); a.c.send({ t: 'cmd', c: 'ability', id: 'emp', tid: 12345 }); await until(() => a.c.msgs.slice(m).filter((x) => x.t === 'reject').length === 4, 3000, '4 rejects'); assert.deepEqual(a.c.msgs.slice(m).filter((x) => x.t === 'reject').map((x) => x.reason), ['bad_kind', 'bad_cmd', 'bad_target', 'bad_target']); assert.equal(a.c.closeInfo, null); for (let i = 0; i < 12; i++) b.c.send({ t: 'cmd', c: 'bogus' }); for (let i = 0; i < 12; i++) b.c.send({ t: 'cmd', c: 'spawn', kind: 5 }); assert.equal((await b.c.closed()).code, 4400); }); }); // ================================================================== private data test('versus: each seat gets only its own role\'s private data, at about 4 Hz; nothing of the other side is ever on the wire', async () => { await withServer({}, async (S) => { const P = await S.play({ hostRole: 'attacker' }); const { a, b } = P; // a attacks // the attacker plays: stages a secret convoy, buys tech and an ability const m = a.c.mark(); a.c.send({ t: 'cmd', c: 'stage', kind: 'trojan', n: 2 }); await a.c.after(m, (x) => x.t === 'priv' && x.staged && x.staged.length === 1); await sleep(900); const privA = a.c.msgs.filter((x) => x.t === 'priv'), privB = b.c.msgs.filter((x) => x.t === 'priv'); assert.ok(privA.length >= 3 && privA.length <= 8, 'about 4 Hz for ~1.2 s: ' + privA.length); assert.ok(privB.length >= 3 && privB.length <= 8, privB.length); assert.ok(privA.every((x) => x.role === 'attacker')); assert.ok(privB.every((x) => x.role === 'defender')); const lastA = privA[privA.length - 1]; assert.deepEqual(Object.keys(lastA).sort(), ['active', 'cd', 'credits', 'income', 'role', 'staged', 't', 'tech']); assert.deepEqual(lastA.staged, [['trojan', 2]]); assert.deepEqual(Object.keys(privB[privB.length - 1]).sort(), ['cd', 'role', 't']); assert.deepEqual(Object.keys(privB[privB.length - 1].cd).sort(), [...VS.TOOL_ORDER].sort()); // the defender's whole inbox: no attacker-private key, no convoy composition, no attacker priv message const secret = ['credits', 'income', 'tech', 'staged', 'active']; const seenByB = keysOf(b.c.msgs.filter((x) => x.t !== 'priv')); for (const k of secret) assert.equal(seenByB.has(k), false, 'the defender saw "' + k + '"'); assert.equal(JSON.stringify(b.c.msgs).includes('trojan'), false, 'the convoy composition never reaches the defender'); assert.ok(b.c.msgs.filter((x) => x.t === 'snap').every((x) => Object.keys(x.vs).sort().join() === 'lim,st,t')); assert.equal(b.c.last('snap').vs.st, 2, 'only the size of the convoy is shared'); // and the other way round: the defender's cooldowns never reach the attacker const seenByA = keysOf(a.c.msgs.filter((x) => x.t !== 'priv')); for (const k of VS.TOOL_ORDER) assert.equal(seenByA.has(k), false, 'the attacker saw tool "' + k + '"'); assert.ok(privA.every((x) => !('scan' in x.cd))); }); }); test('versus: sync gives state, the match picture and the private data; the lobby and the countdown carry no private data', async () => { await withServer({}, async (S) => { const P = await S.pair({ hostRole: 'defender' }); const { a, b } = P; await sleep(500); assert.equal(a.c.msgs.filter((x) => x.t === 'priv').length, 0, 'no private data in the lobby'); assert.equal(b.c.msgs.filter((x) => x.t === 'priv').length, 0); b.c.send({ t: 'vs', c: 'ready', v: true }); await a.c.vs(0, (x) => x.ready[b.r.you.slot] === true); const ma = a.c.mark(); a.c.send({ t: 'vs', c: 'start' }); await a.c.vs(ma, (x) => x.phase === 'playing'); const m = b.c.mark(); b.c.send({ t: 'sync' }); const st = await b.c.type(m, 'state'); assert.equal(st.state.mode, 'versus'); await b.c.vs(m, (x) => x.phase === 'playing'); const p = await b.c.type(m, 'priv'); assert.equal(p.role, 'attacker'); assert.equal(typeof p.credits, 'number'); }); }); // ================================================================== connections test('versus: a player who drops mid-round freezes it, comes back with the same seat and the round goes on', async () => { await withServer({ graceMs: 5000 }, async (S) => { const P = await S.play({ hostRole: 'attacker' }); const { a, b } = P; const sim = () => P.room().sim; await sleep(150); const mb = b.c.mark(); a.c.ws.terminate(); const fz = await b.c.vs(mb, (x) => x.frozen === true); assert.equal(fz.phase, 'playing'); const t0 = sim().time; await sleep(300); assert.equal(sim().time, t0, 'the round is frozen while a human seat is offline'); const m2 = b.c.mark(); b.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 }); assert.equal((await rej(b.c, m2, 'place')).reason, 'frozen', 'no building while the opponent is away'); // back with the same pid const a2 = S.client(); await a2.open(); a2.send({ t: 'join', pid: a.pid, name: 'Alice', room: P.code }); const j = await a2.after(0, (x) => x.t === 'joined'); assert.equal(j.resumed, true); assert.equal(j.you.slot, a.r.you.slot); assert.equal(j.vs.phase, 'playing'); assert.equal(j.vs.frozen, false, 'the picture the returning player gets must not say the round is still frozen'); assert.equal(j.vs.roles[j.you.slot], 'attacker'); assert.equal(j.state.mode, 'versus'); const pv = await a2.after(0, (x) => x.t === 'priv'); assert.equal(pv.role, 'attacker'); assert.equal(typeof pv.credits, 'number'); await b.c.vs(mb, (x) => x.frozen === false && x.phase === 'playing'); await until(() => sim().time > t0 + 0.2, 3000, 'the round to run again'); // and the attacker can act again sim().vs.credits = 1000; const m3 = a2.mark(); a2.send({ t: 'cmd', c: 'spawn', kind: 'ping' }); await a2.after(m3, (x) => x.t === 'priv' && x.credits < 1000); }); }); test('versus: the grace period running out in a round forfeits the match to the one who stayed', async () => { await withServer({ graceMs: 300 }, async (S) => { const P = await S.play({ hostRole: 'attacker' }); const { a, b } = P, sa = a.r.you.slot, sb = b.r.you.slot; await sleep(100); const mb = b.c.mark(); a.c.ws.terminate(); const mo = await b.c.vs(mb, (x) => x.phase === 'matchover', 3000); assert.equal(mo.forfeit, sa); assert.equal(mo.winner, sb); assert.equal(mo.result.forfeit, true); assert.equal(mo.result.winner, 'defender', 'the one who stayed (the defender here) wins the round'); assert.equal(mo.history.length, 1); assert.equal(mo.scores.find((s) => s.slot === sa).fellAt, null); assert.equal(mo.scores.find((s) => s.slot === sa).name, 'Alice'); await b.c.after(mb, (x) => x.t === 'snap' && x.s === 'over'); // no rematch without an opponent const m = b.c.mark(); b.c.send({ t: 'vs', c: 'rematch' }); assert.equal((await rej(b.c, m, 'rematch')).reason, 'no_opponent'); }); }); test('versus: leaving on purpose forfeits at once; leaving between rounds forfeits too; leaving a countdown of round 1 is just back to the lobby', async () => { await withServer({}, async (S) => { // mid-round let P = await S.play({ hostRole: 'defender' }); let mb = P.b.c.mark(); P.a.c.send({ t: 'leave' }); let mo = await P.b.c.vs(mb, (x) => x.phase === 'matchover'); assert.equal(mo.forfeit, P.a.r.you.slot); assert.equal(mo.winner, P.b.r.you.slot); assert.equal(mo.result.winner, 'attacker', 'b attacks in this match: the one who stays wins the round'); // the host left: the guest is host now and can start something new in the same room const pl = await P.b.c.after(mb, (x) => x.t === 'players' && x.players.length === 1); assert.equal(pl.players[0].host, true); // between rounds P = await S.play({ hostRole: 'attacker' }); let m = P.a.c.mark(); P.room().sim.lives = 0; await P.a.c.vs(m, (x) => x.phase === 'roundover'); mb = P.b.c.mark(); P.a.c.send({ t: 'leave' }); mo = await P.b.c.vs(mb, (x) => x.phase === 'matchover'); assert.equal(mo.winner, P.b.r.you.slot); assert.equal(mo.history.length, 1, 'the finished round stays in the history'); assert.equal(mo.result.forfeit, undefined); // countdown of round 1: no match yet, so no forfeit: the lobby await withServer({ vsCountdownMs: 60000 }, async (S2) => { const Q = await S2.pair(); Q.b.c.send({ t: 'vs', c: 'ready', v: true }); await Q.a.c.vs(0, (x) => x.ready[Q.b.r.you.slot] === true); m = Q.a.c.mark(); Q.a.c.send({ t: 'vs', c: 'start' }); await Q.b.c.vs(0, (x) => x.phase === 'countdown'); const m2 = Q.b.c.mark(); Q.a.c.send({ t: 'leave' }); const lob = await Q.b.c.vs(m2, (x) => x.phase === 'lobby'); assert.equal(lob.round, 1); assert.equal(lob.ready[Q.b.r.you.slot], false); // a new opponent can join the empty seat (and take the leaver's role) const c = await S2.join({ name: 'Cy', room: Q.code }); assert.equal(c.r.t, 'joined'); assert.equal(c.r.vs.phase, 'lobby'); }); void m; }); }); test('versus: a disconnect during the countdown freezes it; coming back resumes it; staying away sends the room back to the lobby', async () => { await withServer({ graceMs: 700, vsCountdownMs: 1500 }, async (S) => { const P = await S.pair(); P.b.c.send({ t: 'vs', c: 'ready', v: true }); await P.a.c.vs(0, (x) => x.ready[P.b.r.you.slot] === true); const mb = P.b.c.mark(); P.a.c.send({ t: 'vs', c: 'start' }); await P.b.c.vs(mb, (x) => x.phase === 'countdown'); P.a.c.ws.terminate(); await P.b.c.vs(mb, (x) => x.frozen === true); const left = P.room().vsc.cdLeftMs; await sleep(300); assert.equal(P.room().vsc.cdLeftMs, left, 'the countdown stands still while a player is away'); const lob = await P.b.c.vs(mb, (x) => x.phase === 'lobby', 3000); assert.equal(lob.frozen, false); }); }); test('versus: a player who comes back during the countdown continues it', async () => { await withServer({ graceMs: 5000, vsCountdownMs: 900 }, async (S) => { const P = await S.pair(); P.b.c.send({ t: 'vs', c: 'ready', v: true }); await P.a.c.vs(0, (x) => x.ready[P.b.r.you.slot] === true); const mb = P.b.c.mark(); P.a.c.send({ t: 'vs', c: 'start' }); await P.b.c.vs(mb, (x) => x.phase === 'countdown'); P.b.c.ws.terminate(); await until(() => P.room().vsc.frozen, 2000, 'frozen'); const b2 = S.client(); await b2.open(); b2.send({ t: 'join', pid: P.b.pid, name: 'Bob', room: P.code }); const j = await b2.after(0, (x) => x.t === 'joined'); assert.equal(j.vs.phase, 'countdown'); await b2.after(0, (x) => x.t === 'vs' && x.phase === 'playing', 4000); }); }); test('versus: a vote that was only waiting for a player to be back counts when they are back', async () => { await withServer({ graceMs: 5000 }, async (S) => { const P = await S.play({ hostRole: 'attacker' }); const { a, b } = P; const m = a.c.mark(); P.room().sim.lives = 0; await a.c.vs(m, (x) => x.phase === 'roundover'); b.c.send({ t: 'vs', c: 'next' }); await a.c.vs(m, (x) => x.next && x.next[b.r.you.slot] === true); b.c.ws.terminate(); await until(() => P.room().vsc.frozen, 2000, 'frozen'); a.c.send({ t: 'vs', c: 'next' }); // both voted, but b is away: the next round waits await sleep(300); assert.equal(P.room().vsc.phase, 'roundover'); const b2 = S.client(); await b2.open(); b2.send({ t: 'join', pid: b.pid, name: 'Bob', room: P.code }); const j = await b2.after(0, (x) => x.t === 'joined'); assert.equal(j.vs.phase, 'roundover'); assert.equal(j.vs.frozen, false); assert.equal(j.vs.next[b.r.you.slot], true, 'its vote was not forgotten'); const cd = await b2.after(0, (x) => x.t === 'vs' && x.phase === 'countdown' && x.round === 2, 3000); assert.equal(cd.round, 2); }); }); test('versus: cursors and map pings are accepted but never shown to the opponent; a malformed one is still malformed', async () => { await withServer({}, async (S) => { const P = await S.play({ hostRole: 'attacker' }); const { a, b } = P; const ma = a.c.mark(), mb = b.c.mark(); a.c.send({ t: 'cursor', x: 5.5, y: 6.5 }); b.c.send({ t: 'cursor', x: 7, y: 8 }); a.c.send({ t: 'mark', x: 5, y: 5 }); b.c.send({ t: 'mark', x: 6, y: 6 }); await a.c.barrier(); await b.c.barrier(); await sleep(150); for (const c of [a.c, b.c]) { const snaps = c.msgs.filter((x) => x.t === 'snap'); assert.ok(snaps.length > 2); assert.ok(snaps.every((x) => Array.isArray(x.cur) && x.cur.length === 0), 'no cursors in a versus snapshot'); assert.equal(c.msgs.some((x) => x.t === 'mark'), false, 'no map pings'); assert.equal(c.msgs.some((x) => x.t === 'reject'), false, 'ignored, not refused'); } // still validated like any other message: more than 20 malformed ones close the socket for (let i = 0; i < 21; i++) a.c.send({ t: 'cursor', x: 'left', y: 1 }); assert.equal((await a.c.closed()).code, 4400); void ma; void mb; }); }); test('versus: the host leaving hands the lobby to the guest, who can bring a computer and start', async () => { await withServer({}, async (S) => { const P = await S.pair(); const m = P.b.c.mark(); P.a.c.send({ t: 'leave' }); const pl = await P.b.c.after(m, (x) => x.t === 'players' && x.players.length === 1); assert.equal(pl.players[0].host, true); const sb = P.b.r.you.slot; P.b.c.send({ t: 'vs', c: 'bot', v: 'attacker' }); const v = await P.b.c.vs(m, (x) => x.bot !== null); assert.equal(v.bot.slot, 1 - sb); assert.equal(v.bot.role, 'attacker'); assert.equal(v.roles[sb], 'defender'); P.b.c.send({ t: 'vs', c: 'start' }); await P.b.c.vs(m, (x) => x.phase === 'playing'); }); }); test('versus: a third player gets "full"; a rejoin of a held seat still works', async () => { await withServer({}, async (S) => { const P = await S.pair(); const c = await S.join({ name: 'Cy', room: P.code }); assert.equal(c.r.t, 'error'); assert.equal(c.r.code, 'full'); await c.c.closed(); assert.equal(c.c.closeInfo.code, 4409); P.b.c.ws.terminate(); await until(() => P.room().players[P.b.r.you.slot].conn === null, 2000, 'b offline'); const b2 = S.client(); await b2.open(); b2.send({ t: 'join', pid: P.b.pid, name: 'Bob', room: P.code }); assert.equal((await b2.after(0, (x) => x.t === 'joined' || x.t === 'error')).t, 'joined'); }); }); // ================================================================== the computer seat test('versus bot seat: only the host, only in the lobby, only into an empty seat; a joining human takes the seat over', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus' } }); const sa = a.r.you.slot; let m = a.c.mark(); a.c.send({ t: 'vs', c: 'bot', v: 'defender' }); let v = await a.c.vs(m, (x) => x.bot !== null); assert.deepEqual(Object.keys(v.bot).sort(), ['name', 'role', 'skill', 'slot']); assert.equal(v.bot.slot, 1 - sa); assert.equal(v.bot.role, 'defender'); assert.equal(v.roles[sa], 'attacker'); assert.equal(v.ready[1 - sa], true, 'the computer is always ready'); // change its role / skill: still one computer m = a.c.mark(); a.c.send({ t: 'vs', c: 'bot', v: 'attacker', skill: 0.4 }); v = await a.c.vs(m, (x) => x.bot && x.bot.role === 'attacker'); assert.equal(v.bot.skill, 0.4); assert.equal(v.roles[sa], 'defender'); // role choice of the human moves the computer to the other side m = a.c.mark(); a.c.send({ t: 'vs', c: 'role', v: 'attacker' }); v = await a.c.vs(m, (x) => x.roles[sa] === 'attacker'); assert.equal(v.bot.role, 'defender'); // remove it m = a.c.mark(); a.c.send({ t: 'vs', c: 'bot', v: null }); v = await a.c.vs(m, (x) => x.bot === null); // put it back and let a friend join: the friend takes the seat, the computer is gone m = a.c.mark(); a.c.send({ t: 'vs', c: 'bot', v: 'defender' }); await a.c.vs(m, (x) => x.bot !== null); m = a.c.mark(); const b = await S.join({ name: 'Bob', room: a.room }); assert.equal(b.r.t, 'joined'); assert.equal(b.r.you.slot, 1 - sa); assert.equal(b.r.vs.bot, null); v = await a.c.vs(m, (x) => x.bot === null); // with two humans a computer is refused; a guest may not ask for one m = a.c.mark(); a.c.send({ t: 'vs', c: 'bot', v: 'defender' }); assert.equal((await rej(a.c, m, 'bot')).reason, 'full'); m = b.c.mark(); b.c.send({ t: 'vs', c: 'bot', v: null }); assert.equal((await rej(b.c, m, 'bot')).reason, 'not_host'); }); }); test('versus bot seat: a human against a computer attacker; the computer plays through the same door and the match runs to its end', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus' } }); const sa = a.r.you.slot, sbot = 1 - sa; a.c.send({ t: 'vs', c: 'bot', v: 'attacker' }); await a.c.vs(0, (x) => x.bot !== null); let m = a.c.mark(); a.c.send({ t: 'vs', c: 'start' }); // the computer is always ready: the host alone can start await a.c.vs(m, (x) => x.phase === 'playing'); const room = S.srv.rooms.get(a.room); assert.ok(room.vsc.botCtl, 'a bot exists for the round'); room.sim.vs.credits = 2000; // (a purse that makes it act at once) // the computer attacker spends its credits on units within a few seconds await until(() => room.sim.vs.stats.unitsSpent > 0, 8000, 'the computer to buy units'); await until(() => a.c.msgs.some((x) => x.t === 'snap' && x.mo.length > 0), 4000, 'units on the wire'); // the human only ever receives its own private data assert.ok(a.c.msgs.filter((x) => x.t === 'priv').every((x) => x.role === 'defender')); // a human defender builds, and the computer's commands never show up as the human's rejects m = a.c.mark(); a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 10, y: 10 }); await a.c.after(m, (x) => x.t === 'snap' && x.tw && x.tw.length >= 1); // a stranger cannot take the computer's seat in a running match const c = await S.join({ name: 'Cy', room: a.room }); assert.equal(c.r.code, 'full'); // round 1 over (the human falls... the server falls); `next` from the human alone is enough m = a.c.mark(); room.sim.lives = 0; const ro = await a.c.vs(m, (x) => x.phase === 'roundover'); assert.equal(ro.result.attacker, sbot); assert.equal(ro.result.winner, 'attacker'); assert.equal(room.vsc.botCtl, null, 'no thinking between rounds'); a.c.send({ t: 'vs', c: 'next' }); const cd = await a.c.vs(m, (x) => x.phase === 'countdown' && x.round === 2); assert.equal(cd.bot.role, 'defender', 'the computer swaps sides too'); assert.equal(cd.roles[sa], 'attacker'); await a.c.vs(m, (x) => x.phase === 'playing' && x.round === 2); assert.ok(room.vsc.botCtl); // the computer defender builds await until(() => room.sim.towers.length > 0, 8000, 'the computer to build'); m = a.c.mark(); room.sim.time = room.sim.vs.limit - 0.05; const mo = await a.c.vs(m, (x) => x.phase === 'matchover'); assert.equal(mo.scores.find((s) => s.slot === sbot).name, 'Computer'); assert.equal(mo.winner, sbot, 'its round-1 attack felled the server, mine did not'); // rematch: the human alone votes (the computer always agrees) a.c.send({ t: 'vs', c: 'rematch' }); const cd3 = await a.c.vs(m, (x) => x.phase === 'countdown'); assert.equal(cd3.round, 1); assert.equal(cd3.roles[sa], 'attacker', 'the human defended first, so now the human attacks first'); assert.equal(cd3.bot.role, 'defender'); }); }); test('versus bot seat: a computer defender builds for a human attacker, who may buy units and use abilities', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus' } }); a.c.send({ t: 'vs', c: 'bot', v: 'defender' }); const v0 = await a.c.vs(0, (x) => x.bot !== null); assert.equal(v0.roles[a.r.you.slot], 'attacker'); a.c.send({ t: 'vs', c: 'start' }); await a.c.vs(0, (x) => x.phase === 'playing'); const room = S.srv.rooms.get(a.room); await until(() => room.sim.towers.length >= 3, 8000, 'the computer defender to build'); room.sim.vs.credits = 1000; const m = a.c.mark(); a.c.send({ t: 'cmd', c: 'spawn', kind: 'ping', n: 3 }); await a.c.after(m, (x) => x.t === 'priv' && x.credits < 1000); assert.ok(a.c.msgs.filter((x) => x.t === 'priv').every((x) => x.role === 'attacker')); assert.equal(a.c.msgs.some((x) => x.t === 'reject'), false); }); }); test('versus bot seat: the computer is a seat, not a socket: a room with only a computer left is deleted', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus' } }); a.c.send({ t: 'vs', c: 'bot', v: 'defender' }); await a.c.vs(0, (x) => x.bot !== null); a.c.send({ t: 'vs', c: 'start' }); await a.c.vs(0, (x) => x.phase === 'playing'); a.c.send({ t: 'leave' }); await until(() => S.srv.rooms.size === 0, 2000, 'room deleted'); }); }); test('versus bot seat: the computer\'s commands go through the same door (phase, role) and its thinking time is capped', async () => { await withServer({}, async (S) => { const a = await S.join({ extra: { mode: 'versus' } }); a.c.send({ t: 'vs', c: 'bot', v: 'attacker' }); await a.c.vs(0, (x) => x.bot !== null); const room = S.srv.rooms.get(a.room), vsc = room.vsc; // in the lobby the door is shut, and the guarded sim drops writes const g = vsc.guardedSim(room.sim); assert.deepEqual(g.cmd({ c: 'spawn', kind: 'ping' }), { ok: false, reason: 'phase' }); g.gold = 99999; g.lives = 1; assert.notEqual(room.sim.gold, 99999); assert.notEqual(room.sim.lives, 1); assert.equal(g.towers, room.sim.towers, 'reads go straight through'); assert.equal(typeof g.preview, 'function'); a.c.send({ t: 'vs', c: 'start' }); await a.c.vs(0, (x) => x.phase === 'playing'); const g2 = vsc.guardedSim(room.sim); // the seat's role is stamped: this computer attacks, so it cannot build, whatever it says assert.equal(g2.cmd({ c: 'place', type: 'filter', x: 3, y: 3, role: 'defender' }).reason, 'role'); // and a stale bot (from an earlier round) is refused const old = vsc.guardedSim({ cmd() { throw new Error('must not be called'); } }); assert.equal(old.cmd({ c: 'spawn', kind: 'ping' }).ok, false); // thinking budget: over budget = no think; a heavy think buys a quiet period let calls = 0; vsc.botCtl = { think() { calls++; const t0 = process.hrtime.bigint(); while (process.hrtime.bigint() - t0 < 2000000n) { /* a 2 ms decision */ } } }; const mgr = room.manager; const now = process.hrtime.bigint(); vsc.botAcc = 1; vsc.botNextNs = 0n; mgr.botSpentNs = 10n ** 9n; vsc.thinkBot(now); assert.equal(calls, 0, 'the global budget is spent'); mgr.botSpentNs = 0n; vsc.thinkBot(now); assert.equal(calls, 1); assert.ok(mgr.botSpentNs >= 2000000n, 'the time was counted'); assert.ok(vsc.botNextNs > now, 'a quiet period follows'); vsc.botAcc = 1; vsc.thinkBot(now); assert.equal(calls, 1, 'not again until the quiet period is over'); vsc.botAcc = 0.1; vsc.botNextNs = 0n; mgr.botSpentNs = 0n; vsc.thinkBot(now); assert.equal(calls, 1, 'and not more often than 4 Hz of game time'); // a bot that throws is switched off, the room lives vsc.botCtl = { think() { throw new Error('boom'); } }; vsc.botAcc = 1; vsc.botNextNs = 0n; mgr.botSpentNs = 0n; vsc.thinkBot(now); assert.equal(vsc.botCtl, null); await a.c.barrier(); }); }); // ================================================================== co-op is exactly what it was test('co-op rooms: versus messages and commands are malformed there, pause / speed / newgame / waves work as before', async () => { await withServer({}, async (S) => { const a = await S.join({}); const b = await S.join({ name: 'Bob', room: a.room }); // none of the new traffic exists in a co-op room let m = a.c.mark(); a.c.send({ t: 'vs', c: 'ready', v: true }); a.c.send({ t: 'cmd', c: 'spawn', kind: 'ping' }); a.c.send({ t: 'cmd', c: 'tool', id: 'scan', x: 1, y: 1 }); a.c.send({ t: 'cmd', c: 'ability', id: 'emp' }); await a.c.barrier(); assert.equal(a.c.msgs.slice(m).some((x) => x.t === 'reject' || x.t === 'vs' || x.t === 'priv'), false, 'silently malformed, like any unknown message'); for (let i = 0; i < 17; i++) a.c.send({ t: 'vs', c: 'start' }); assert.equal((await a.c.closed()).code, 4400, 'counted as malformed: 4 + 17 > 20'); // the partner still plays: waves, pause, speed, newgame m = b.c.mark(); b.c.send({ t: 'ctl', c: 'pause', v: true }); b.c.send({ t: 'ctl', c: 'speed', v: 2 }); await b.c.after(m, (x) => x.t === 'snap' && x.pa === 1 && x.sp === 2); assert.equal(b.c.msgs.slice(m).some((x) => x.t === 'reject'), false); // no priv messages and no vs key in anything a co-op player ever got assert.equal(b.c.msgs.some((x) => x.t === 'priv' || x.t === 'vs'), false); assert.equal(b.c.msgs.some((x) => x.t === 'snap' && 'vs' in x), false); const sim = S.srv.rooms.get(a.room).sim; assert.equal(sim.vs, null); assert.equal(S.srv.rooms.get(a.room).vsc, null); }); }); // ================================================================== sizes test('versus: a snapshot with the alive cap of units and a built-up defence stays small enough for 20 Hz', () => { const sim = new TD.Sim({ map: 'open', mode: 'versus', credits: 1e9, gold: 1e9, lives: 1e9 }); for (let i = 0; i < 40; i++) sim.cmd({ c: 'place', type: i % 4 === 0 ? 'filter' : 'wall', x: 2 + (i % 20), y: 2 + Math.floor(i / 20) * 4, role: 'defender', by: 0 }); sim.cmd({ c: 'spawn', kind: 'ping', n: VS.MAX_ALIVE, role: 'attacker', by: 1 }); for (let i = 0; i < 60 * 8; i++) sim.tick(TD.STEP); // 8 s: the whole stream is out and moving assert.ok(sim.monsters.length >= 100, 'a crowd: ' + sim.monsters.length); const msg = Object.assign({ t: 'snap', seq: 123456 }, sim.snapshot(), { ev: sim.drainEvents().slice(0, 40), cur: [[0, 12.5, 7.25], [1, 3, 4]], pa: 0, sp: 1 }); const size = JSON.stringify(msg).length; const perMonster = JSON.stringify(sim.snapshot().mo).length / Math.max(1, sim.monsters.length); assert.ok(perMonster < 48, 'bytes per monster row: ' + perMonster); // the slow-client guard drops a socket 512 KB behind: a full second of 20 Hz snapshots of the worst case must be far below that assert.ok(size * 20 < Room.LIMITS.MAX_BUFFERED / 2, 'one second of snapshots: ' + size * 20 + ' bytes (snapshot ' + size + ')'); assert.ok(size < 16 * 1024, 'snapshot bytes: ' + size); // every message the versus protocol adds is tiny by comparison const room = { sim, manager: {}, players: [null, null] }; const vsc = new V.Versus(room, { limit: 720, rounds: 2 }); assert.ok(JSON.stringify(vsc.msg()).length < 400); assert.ok(JSON.stringify(Object.assign({ t: 'priv', role: 'attacker' }, sim.privateState('attacker'))).length < 500); });