/* * NETWALL controllers. The UI and renderer talk to a "controller" and do not care whether the game runs * in this tab (LocalController, solo, works from file://) or on the server (RemoteController, co-op). * * ctrl.kind 'local' | 'remote' * ctrl.board TD.Board (own for local, a mirror for remote: used for route previews) * ctrl.view render state, refreshed by ctrl.update(nowMs): * gold lives maxLives wave state auto nextWaveIn kills winWave rev queued speed paused difficulty * towers[{id,type,x,y,level,mode,spent,owner,tgt,kills}] * monsters[{id,kind,x,y,hp,maxhp,slow,air}] bullets[{id,k,x,y}] cursors[{slot,x,y}] * ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue. An upgrade carries the level the player saw (lv) * and a wave carries the wave it expects to start (n), filled in here from the view: a second player who * pressed the same button at the same moment is refused as 'stale' (see sim.js) instead of paying twice. * ctrl.ctl(c, v) 'pause' | 'speed' * ctrl.difficulty the game's difficulty id (TD.DIFFICULTIES); `newGame(map, difficulty)` keeps the current one when none is given * ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route? * events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt' * * VERSUS (attack vs defend, docs/VERSUS.md and docs/PROTOCOL.md "Versus"). Both controllers speak the same language to the UI, so the UI code * does not care whether the other seat is a person on the server or the computer in this tab: * ctrl.mode 'solo' (LocalController), 'coop' or 'versus' (what the room was created as; RemoteController learns it from the server's state) * ctrl.vs the newest match message { phase, round, rounds, roles:{slot:'attacker'|'defender'}, random, bot, limit, ready, frozen, countdown?, next?, * result?, history?, scores?, winner?, forfeit?, rematch? }, or null (not versus); event 'vs' fires on every change. * phase: lobby | countdown | playing | roundover | matchover (a LocalController starts in the countdown: there is no lobby) * ctrl.priv the newest role-private data { role, ...privateState }: attacker { credits, income, tech, staged, cd, active }, defender { cd }; * event 'priv'. Compare priv.role with ctrl.role after a role swap (the first priv of a round replaces the old one). * ctrl.role my role in the current round ('attacker' | 'defender') or null * ctrl.view.vs the SHARED round block { t, lim, st } (round clock, limit, staged convoy size) or null; ctrl.view.mode as ctrl.mode * view.towers[].empT seconds of EMP left on a tower (0 when none), versus only * ctrl.send(cmd) also the versus commands: spawn | stage | launch | tech | ability | tool (see the protocol); the role is the controller's, never the caller's * ctrl.vsSend(c, v, extra) lobby / match control: 'role' | 'ready' | 'bot' | 'start' | 'next' | 'rematch'; wrappers vsRole(v) vsReady(v) vsBot(v, skill) * vsStart() vsNext() vsRematch(). A LocalController has no lobby: role / ready / bot / start are refused ('phase'), * `next` starts round 2 and `rematch` a new match with the first roles swapped. * ctrl.ctl(c, v) does nothing in versus (no pause, no speed); `new LocalController({ map, mode:'versus', role:'attacker'|'defender'|'random', limit, skill })` * plays against NWBot (js/bot.js must be loaded), `new RemoteController({ ..., mode:'versus', limit })` creates a versus room. */ (function (root) { 'use strict'; const NW = root.NW = root.NW || {}; const TD = root.TD; const clamp = (v, a, b) => Math.min(b, Math.max(a, v)); const WATCHDOG_MS = 5000; // a joined socket that has been silent this long is dead (snapshots arrive at 20 Hz) const CONNECT_MS = 10000; // a socket that is not joined this long after it was opened is abandoned const BUF_MAX = 10; // snapshots kept for interpolation class Emitter { constructor() { this._h = {}; } on(ev, fn) { (this._h[ev] = this._h[ev] || []).push(fn); return this; } emit(ev, a, b) { const l = this._h[ev]; if (!l) return; for (const fn of l.slice()) { try { fn(a, b); } catch (e) { console.error(e); } } } } // What the player SAW when pressing the button (the view they were looking at), so the sim can tell a stale command from a fresh one. function stampCmd(c, view) { if (c.c === 'upgrade' && c.lv === undefined) { const t = view.towers.find((x) => x.id === c.id); if (t) c.lv = t.level; } else if (c.c === 'wave' && c.n === undefined) c.n = view.wave + 1; return c; } // ---- match rules (the same rules as server/versus.js: test/controllers.test.js feeds both the same rounds) ---- const vsOpposite = (r) => (r === 'attacker' ? 'defender' : 'attacker'); const vsSwap = (roles) => ({ 0: vsOpposite(roles[0]), 1: vsOpposite(roles[1]) }); // history entry: { round, roles:{0,1}, result:{ winner, t, integrityLost, attacker:slot, defender:slot, forfeit? } } 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 }; }); } 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; } const VS_COUNTDOWN_MS = 3000; // a local match: the pause before each round (the server's default too) const VS_BOT_STEP = 0.25; // the computer is asked to think at about 4 Hz of game time const VS_PRIV_MS = 250; // role-private data at 4 Hz // ws(s):///ws, relative to the page so it also works under a proxy path prefix function wsUrl() { const u = new URL('ws', root.location.href); u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:'; u.search = ''; u.hash = ''; return u.toString(); } // ================================================================= local (solo) class LocalController extends Emitter { constructor(opts) { super(); this.kind = 'local'; this.mapId = (opts && opts.map) || 'open'; this.difficulty = TD.difficultyId(opts && opts.difficulty); this.speed = 1; this.paused = false; this.players = [{ slot: 0, name: 'You', online: true, host: true }]; this.you = { slot: 0, host: true }; this.versus = !!(opts && opts.mode === 'versus'); this.mode = this.versus ? 'versus' : 'solo'; this.vs = null; this.priv = null; this.bot = null; if (this.versus) { this._vsInit(opts); this._vsRound(); } else this._fresh(); } get role() { return this.vs ? this.vs.roles[0] : null; } _fresh() { this.sim = this.versus ? new TD.Sim({ map: this.mapId, mode: 'versus', limit: this.limit }) : new TD.Sim({ map: this.mapId, difficulty: this.difficulty }); this.board = this.sim.board; this.acc = 0; this.last = 0; this.view = { gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0, speed: this.speed, paused: this.paused, time: 0, difficulty: this.difficulty, mode: this.mode, vs: null, towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [], }; this._sync(); } // ---- versus against the computer (the human is seat 0, NWBot seat 1) ---- _vsInit(opts) { if (!root.NWBot) throw new Error('A versus game against the computer needs js/bot.js (NWBot) to be loaded before it is created.'); const V = TD.VS; this.limit = Number.isFinite(opts.limit) && opts.limit > 0 ? opts.limit : V.DEFAULT_LIMIT; this.skill = Number.isFinite(opts.skill) ? clamp(opts.skill, 0, 1) : 1; this.rounds = V.ROUNDS; this.countdownMs = Number.isFinite(opts.countdownMs) ? opts.countdownMs : VS_COUNTDOWN_MS; this.seed = Number.isInteger(opts.seed) ? opts.seed : Math.floor(Math.random() * 0x7fffffff); const mine = opts.role === 'attacker' || opts.role === 'defender' ? opts.role : (Math.random() < 0.5 ? 'attacker' : 'defender'); this.firstRoles = { 0: mine, 1: vsOpposite(mine) }; this.players = [{ slot: 0, name: 'You', online: true, host: true }]; this._privAt = -Infinity; this._vsStartMatch(this.firstRoles); } _vsStartMatch(roles) { this.firstRoles = { 0: roles[0], 1: roles[1] }; this.vsm = { phase: 'countdown', round: 1, roles: { 0: roles[0], 1: roles[1] }, history: [], result: null, scores: null, winner: null, cdMs: 0, cdSent: -1, botAcc: 0 }; } // The sim and the computer of the current round (called when a round's countdown starts). _vsRound() { const m = this.vsm; this._fresh(); m.phase = 'countdown'; m.cdMs = this.countdownMs; m.cdSent = Math.ceil(m.cdMs / 1000); m.botAcc = 0; m.result = null; this.bot = root.NWBot.create(this.sim, m.roles[1], { seed: this.seed + m.round * 101, skill: this.skill, by: 1 }); this._vsEmit(); this._vsPriv(); } _vsNames() { return [this.players[0].name, 'Computer']; } _vsMsg() { const m = this.vsm; const out = { t: 'vs', phase: m.phase, round: m.round, rounds: this.rounds, roles: { 0: m.roles[0], 1: m.roles[1] }, random: false, bot: { slot: 1, role: m.roles[1], skill: this.skill, name: 'Computer' }, limit: this.limit, ready: { 0: true, 1: true }, frozen: false, }; if (m.phase === 'countdown') out.countdown = Math.max(0, Math.ceil(m.cdMs / 1000)); if (m.phase === 'roundover') out.next = { 0: false, 1: true }; if (m.phase === 'roundover' || m.phase === 'matchover') out.result = m.result; if (m.history.length) out.history = m.history; if (m.phase === 'matchover') { out.scores = m.scores; out.winner = m.winner; out.forfeit = null; out.rematch = { 0: false, 1: true }; } return out; } _vsEmit() { this.vs = this._vsMsg(); this.emit('vs', this.vs); } _vsPriv() { const role = this.vsm.roles[0], ps = this.sim.privateState(role); if (!ps) return; this.priv = Object.assign({ t: 'priv', role }, ps); this.emit('priv', this.priv); } _vsRoundEnd() { const m = this.vsm, res = this.sim.vs.result; const attacker = m.roles[0] === 'attacker' ? 0 : 1; const entry = { round: m.round, roles: { 0: m.roles[0], 1: m.roles[1] }, result: { winner: res.winner, t: res.t, integrityLost: res.integrityLost, attacker, defender: 1 - attacker } }; m.history.push(entry); m.result = entry.result; this.bot = null; if (m.round < this.rounds) m.phase = 'roundover'; else { m.phase = 'matchover'; m.scores = matchScores(m.history, this._vsNames()); m.winner = matchWinner(m.scores); } this._vsEmit(); this._vsPriv(); } _vsUpdate(now) { const m = this.vsm; if (!this.last) this.last = now; const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000)); this.last = now; if (m.phase === 'countdown') { m.cdMs -= dt * 1000; if (m.cdMs <= 0) { m.phase = 'playing'; this.acc = 0; this._vsEmit(); this._vsPriv(); } else if (Math.ceil(m.cdMs / 1000) !== m.cdSent) { m.cdSent = Math.ceil(m.cdMs / 1000); this._vsEmit(); } } else if (m.phase === 'playing') { this.acc = Math.min(0.6, this.acc + dt); let ticked = 0; while (this.acc >= TD.STEP && this.sim.state === 'playing') { this.sim.tick(TD.STEP); this.acc -= TD.STEP; ticked += TD.STEP; } m.botAcc += ticked; if (this.bot && m.botAcc >= VS_BOT_STEP) { const d = m.botAcc; m.botAcc = 0; try { this.bot.think(d); } catch (e) { console.error(e); this.bot = null; } } if (this.sim.state !== 'playing') this._vsRoundEnd(); } const ev = this.sim.drainEvents(); this._sync(); if (ev.length) this.emit('events', ev); if ((m.phase === 'countdown' || m.phase === 'playing') && now - this._privAt >= VS_PRIV_MS) { this._privAt = now; this._vsPriv(); } } _vsSend(cmd) { const m = this.vsm; let res; if (m.phase !== 'playing') res = { ok: false, reason: m.phase === 'roundover' || m.phase === 'matchover' ? 'over' : 'phase' }; else { const c = Object.assign({}, cmd, { by: 0, role: m.roles[0] }); res = this.sim.cmd(stampCmd(c, this.view)); } if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id, tid: cmd.tid }); else { this._vsPriv(); this._sync(); } return res; } // lobby / match control; a local game has no lobby, so only `next` and `rematch` do anything vsSend(c, v) { const m = this.vsm; if (!this.versus) return { ok: false, reason: 'versus' }; if (c === 'next' && m.phase === 'roundover') { m.round++; m.roles = vsSwap(m.roles); this._vsRound(); return { ok: true }; } if (c === 'rematch' && m.phase === 'matchover') { this._vsStartMatch(vsSwap(this.firstRoles)); this._vsRound(); return { ok: true }; } this.emit('reject', { c, reason: 'phase' }); return { ok: false, reason: 'phase' }; } vsRole(v) { return this.vsSend('role', v); } vsReady(v) { return this.vsSend('ready', v); } vsBot(v, skill) { return this.vsSend('bot', v, { skill }); } vsStart() { return this.vsSend('start'); } vsNext() { return this.vsSend('next'); } vsRematch() { return this.vsSend('rematch'); } _sync() { const s = this.sim, v = this.view; v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state; v.auto = s.autoWaves; v.nextWaveIn = s.autoWaves ? s.nextWaveIn : -1; v.kills = s.kills; v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length; v.speed = this.speed; v.paused = this.paused; v.time = s.time; v.difficulty = s.difficulty; v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets; if (s.vs) v.vs = { t: TD.round2(s.time), lim: s.vs.limit, st: s.vsStaged() }; } update(now) { if (this.versus) { this._vsUpdate(now); return; } if (!this.last) this.last = now; const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000)); this.last = now; if (!this.paused) { this.acc = Math.min(0.6, this.acc + dt * this.speed); while (this.acc >= TD.STEP) { this.sim.tick(TD.STEP); this.acc -= TD.STEP; } } const ev = this.sim.drainEvents(); this._sync(); if (ev.length) this.emit('events', ev); } send(cmd) { if (this.versus) return this._vsSend(cmd); const res = this.sim.cmd(stampCmd(Object.assign({}, cmd, { by: 0 }), this.view)); if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id }); return res; } ctl(c, v) { if (this.versus) return; // no pause, no speed in versus if (c === 'pause') this.paused = !!v; else if (c === 'speed') this.speed = clamp(v | 0, 1, 3); this._sync(); } preview(x, y, routes) { return this.sim.preview(x, y, routes); } // `difficulty` absent: the same one again ("Play again"); an unknown one is normal (the sim's rule) newGame(map, difficulty) { if (this.versus) { // a new match (the first roles swapped), at once, whatever the phase if (map) this.mapId = map; this._vsStartMatch(vsSwap(this.firstRoles)); this._vsRound(); this.emit('newgame'); return; } if (map) this.mapId = map; if (difficulty !== undefined && difficulty !== null) this.difficulty = TD.difficultyId(difficulty); this._fresh(); this.emit('newgame'); } sendCursor() {} sendMark(x, y) { this.emit('mark', { slot: 0, x, y }); } requestSync() {} close() {} } // ================================================================= remote (co-op) class RemoteController extends Emitter { constructor(opts) { super(); this.kind = 'remote'; this.url = opts.url || wsUrl(); this.pid = opts.pid; this.name = opts.name || 'Player'; this.room = opts.room || null; // null => create a room on first connect this.mapId = opts.map || 'open'; this.mode = opts.mode === 'versus' ? 'versus' : 'coop'; // what a CREATING join asks for; afterwards whatever the server's state says this.limit = opts.limit; // versus round limit (seconds) of a creating join this.vs = null; this.priv = null; // the newest 'vs' / 'priv' messages (see the header) this.difficulty = TD.difficultyId(opts.difficulty); // what a CREATING join asks for; afterwards whatever the server's state says this.status = 'idle'; // idle | connecting | joined | reconnecting | closed this.ws = null; this.players = []; this.you = null; this.board = null; this.buf = []; this.delay = 120; this.rev = -1; this.recvRev = -1; this.towers = []; this._carryTw = null; // the newest tower list that was pushed out of the buffer before it was displayed (coop-1) this.resume = !!opts.resume; // rejoining a game we left (reload / Resume button): "no such room" then means it is gone this.everJoined = false; this.monCache = new Map(); this.bulCache = new Map(); this._gen = 0; this.rtt = 0; this.retry = 0; this.intentional = false; this.fatal = false; this.lastMsg = 0; this.lastSync = 0; this.lastCursor = 0; this.speed = 1; this.paused = false; this.view = { gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0, speed: 1, paused: false, time: 0, difficulty: this.difficulty, mode: this.mode, vs: null, towers: [], monsters: [], bullets: [], cursors: [], }; this._onVis = () => { if (!document.hidden) this._wake(); }; document.addEventListener('visibilitychange', this._onVis); root.addEventListener('online', this._onVis); this._timers = []; } get role() { return this.vs && this.you ? this.vs.roles[this.you.slot] || null : null; } // The document / window listeners must not outlive the controller (code-19): called when it dies and when it is closed. _dispose() { document.removeEventListener('visibilitychange', this._onVis); root.removeEventListener('online', this._onVis); } connect() { if (this.intentional || this.fatal) return; if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) return; this._setStatus(this.status === 'joined' || this.status === 'reconnecting' ? 'reconnecting' : 'connecting'); let ws; try { ws = new WebSocket(this.url); } catch (e) { this._failed(); return; } this.ws = ws; ws.onopen = () => { const j = { t: 'join', pid: this.pid, name: this.name }; if (this.room) j.room = this.room; else { // only a creating join carries these: a joiner takes the room's j.map = this.mapId; j.difficulty = this.difficulty; if (this.mode === 'versus') { j.mode = 'versus'; if (this.limit) j.limit = this.limit; } } this._send(j); }; ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); }; ws.onclose = (e) => { if (this.ws === ws) this._onClose(e); }; ws.onerror = () => { /* onclose follows */ }; // A connect over a dead path can hang for minutes: give up on this socket and try again (or report it) after CONNECT_MS. clearTimeout(this._connT); this._connT = setTimeout(() => { if (this.ws === ws && this.status !== 'joined') this._abandon(); }, CONNECT_MS); } // The socket is presumed dead: no frame for WATCHDOG_MS, or the page woke up after a stall. A half-open connection (Wi-Fi / cell // switch, NAT or proxy drop) never delivers a close for 47 to 65 s, so we do not wait for one (coop-2): forget the socket, show // "reconnecting" now and open a fresh one. The server swaps the old connection out by pid. Handlers are detached first, so the // dead socket's eventual close (or the server's 4001 "replaced") cannot be mistaken for the new connection's. _abandon() { const ws = this.ws; this.ws = null; clearTimeout(this._connT); this._stopRtt(); if (ws) { ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null; try { ws.close(); } catch (e) { /* ignore */ } } if (this.status === 'joined') { this._setStatus('reconnecting'); this.connect(); } // it was alive a moment ago: straight back in else this._failed(); // never got in: count it, back off, give up eventually } _setStatus(s) { if (this.status !== s) { this.status = s; this.emit('status', s); } } _failed() { if (this.status === 'connecting') { this._die('connect', 'Could not reach the game server.'); return; } this.retry++; if (this.retry > 14) { this._die('lost', 'Lost connection to the server.'); return; } this._setStatus('reconnecting'); const wait = Math.min(5000, 350 * Math.pow(1.7, this.retry - 1)); const id = setTimeout(() => this.connect(), wait); this._timers.push(id); } _die(code, msg) { this.fatal = true; this._setStatus('closed'); this._stopTimers(); this._dispose(); this.emit('fatal', { code, msg }); } _onClose(e) { this.ws = null; clearTimeout(this._connT); this._stopRtt(); if (this.intentional || this.fatal) { this._setStatus('closed'); return; } if (e && e.code === 4001) { this._die('replaced', 'This game was opened in another tab or device.'); return; } this._failed(); } _wake() { // back from sleep / background / network switch: a socket that looks open may be dead, so reconnect quickly if (this.intentional || this.fatal || this.status === 'connecting') return; const stale = performance.now() - this.lastMsg > 2500; if (!this.ws || this.ws.readyState > 1) { this.retry = 0; this.connect(); } else if (this.status === 'joined' && stale) this._abandon(); } _stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; clearTimeout(this._connT); this._stopRtt(); } _stopRtt() { if (this._rttT) { clearInterval(this._rttT); this._rttT = 0; } if (this._wdT) { clearInterval(this._wdT); this._wdT = 0; } } _startRtt() { this._stopRtt(); this._rttT = setInterval(() => this._send({ t: 'rtt', ts: performance.now() }), 2000); this._wdT = setInterval(() => { // snapshots flow at 20 Hz even when paused: silence means a dead socket if (this.status === 'joined' && this.ws && performance.now() - this.lastMsg > WATCHDOG_MS) this._abandon(); }, 1000); } _send(o) { if (this.ws && this.ws.readyState === 1) this.ws.send(JSON.stringify(o)); } _onMsg(raw) { if (this.intentional || this.fatal) return; // closed on purpose: nothing may reach the UI any more (code-3) let m; try { m = JSON.parse(raw); } catch (e) { return; } if (!m || typeof m.t !== 'string') return; switch (m.t) { case 'snap': this._onSnap(m); break; case 'joined': clearTimeout(this._connT); this.room = m.room; this.you = m.you; this.players = m.players || []; this.everJoined = true; this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused; this._applyState(m.state, m.snap); if (m.vs) this.vs = m.vs; this._setStatus('joined'); this._startRtt(); this.emit('joined', m); this.emit('players', this.players); if (m.vs) this.emit('vs', m.vs); break; case 'state': this.speed = m.speed || 1; this.paused = !!m.paused; this._applyState(m.state, m.snap); if (m.newgame) this.emit('newgame'); break; case 'players': this.players = m.players || []; { const me = this.players.find((p) => this.you && p.pid === this.you.pid); if (me) this.you = Object.assign({}, this.you, { host: me.host, slot: me.slot }); } this.emit('players', this.players); break; case 'vs': this.vs = m; this.emit('vs', m); break; case 'priv': this.priv = m; this.emit('priv', m); break; case 'reject': this.emit('reject', m); break; case 'mark': this.emit('mark', m); break; case 'rtt': { const s = performance.now() - m.ts; this.rtt = this.rtt ? Math.round(this.rtt * 0.7 + s * 0.3) : Math.round(s); this.emit('rtt', this.rtt); } break; case 'error': { // "no such room" while rejoining means the server lost it: it restarted (coop-6). The code says so, the text spells it out. if (m.code === 'no_room' && (this.everJoined || this.resume)) { this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.'); break; } const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_mode: 'Unknown game mode.', bad_limit: 'Unknown round length.', bad_rounds: 'Unsupported number of rounds.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.', bad_difficulty: 'Unknown difficulty.' }; this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.'); break; } default: break; } } _setTowers(list) { const b = this.board; b.solid.set(b.obst); this.towers = list.map((a) => { b.setSolid(a[2], a[3], 1); return { id: a[0], type: a[1], x: a[2], y: a[3], level: a[4], mode: a[5], spent: a[6], owner: a[7], pm: a[8] || 1, tgt: 0, kills: 0 }; }); b.recompute(); } _applyState(state, snap) { if (!this.board || this.board.mapId !== state.map) { this.board = new TD.Board(state.map); this.mapId = state.map; } this._setTowers(state.towers); this.rev = this.recvRev = state.rev; this.maxLives = state.maxLives; this.winWave = state.winWave; this.difficulty = TD.isDifficulty(state.difficulty) ? state.difficulty : 'normal'; // (a server from before difficulties sends none) this.view.difficulty = this.difficulty; this.mode = state.mode === 'versus' ? 'versus' : 'coop'; this.limit = state.limit || this.limit; this.view.mode = this.mode; this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear(); if (snap) this._push(snap, true); } _push(snap, first) { const mo = new Map(), bu = new Map(), tt = new Map(); for (const a of snap.mo || []) mo.set(a[0], a); for (const a of snap.bu || []) bu.set(a[0], a); for (const a of snap.tt || []) tt.set(a[0], a); const e = { t: performance.now(), snap, mo, bu, tt, rel: !!first }; this.buf.push(e); while (this.buf.length > BUF_MAX) { const old = this.buf.shift(); // A stalled page (hidden tab, a long frame) gets a burst of snapshots. The server sends a tower list exactly once, so an entry // that carries one and was never displayed must not simply vanish (coop-1): its list rides along to the next update (the newest wins). if (old.snap.tw && !old.twDone) this._carryTw = old.snap; } } // Towers ride along with the snapshot that changed them and are applied when that snapshot is *displayed* // (see update), so a new tower and the credits it cost appear on screen together. _onSnap(m) { if (m.tw) this.recvRev = m.rev; else if (m.rev !== this.recvRev) this.requestSync(); this._push(m, false); } requestSync() { const now = performance.now(); if (now - this.lastSync < 1000) return; this.lastSync = now; this._send({ t: 'sync' }); } update(now) { const buf = this.buf; if (!buf.length || !this.board) return; const rt = now - this.delay; for (const e of buf) { if (!e.rel && e.t <= rt) { e.rel = true; if (e.snap.ev && e.snap.ev.length) this.emit('events', e.snap.ev); } } let i = buf.length - 1; while (i > 0 && buf[i].t > rt) i--; const a = buf[i], b = buf[Math.min(i + 1, buf.length - 1)]; const alpha = a === b ? 1 : clamp((rt - a.t) / Math.max(1e-3, b.t - a.t), 0, 1); // (a burst after a stall has equal arrival times) let lastTw = this._carryTw; this._carryTw = null; for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k].snap; } buf[k].twDone = true; } if (lastTw) { this._setTowers(lastTw.tw); this.rev = lastTw.rev; } // Backstop: every tower list that arrived has been applied or is still waiting in the buffer. If the revisions still differ, a list // was lost somehow: ask for the full state instead of showing a wrong maze until somebody builds again. else if (this.rev !== this.recvRev && !buf.some((x) => x.snap.tw && !x.twDone)) this.requestSync(); const s = a.snap, v = this.view; v.gold = s.g; v.lives = s.l; v.wave = s.w; v.state = s.s; v.auto = !!s.au; v.nextWaveIn = s.nw; v.kills = s.k; v.rev = s.rev; v.queued = s.q || 0; v.time = s.time; v.maxLives = this.maxLives; v.winWave = this.winWave; v.speed = s.sp || 1; v.paused = !!s.pa; v.vs = s.vs || null; // versus: the shared round block { t, lim, st } const gen = ++this._gen; const kinds = TD.ENEMY_ORDER; const mons = v.monsters; mons.length = 0; for (const mb of b.mo.values()) { const ma = a !== b ? a.mo.get(mb[0]) : null; let o = this.monCache.get(mb[0]); if (!o) { o = { id: mb[0], kind: kinds[mb[1]], air: !!TD.ENEMIES[kinds[mb[1]]].air }; this.monCache.set(mb[0], o); } o.x = ma ? ma[2] + (mb[2] - ma[2]) * alpha : mb[2]; o.y = ma ? ma[3] + (mb[3] - ma[3]) * alpha : mb[3]; o.hp = mb[4]; o.maxhp = mb[5]; o.slow = mb[6]; o.gen = gen; mons.push(o); } for (const [id, o] of this.monCache) if (o.gen !== gen) this.monCache.delete(id); const buls = v.bullets; buls.length = 0; for (const bb of b.bu.values()) { const ba = a !== b ? a.bu.get(bb[0]) : null; let o = this.bulCache.get(bb[0]); if (!o) { o = { id: bb[0], k: bb[1] === 1 ? 'mortar' : 'filter' }; this.bulCache.set(bb[0], o); } o.x = ba ? ba[2] + (bb[2] - ba[2]) * alpha : bb[2]; o.y = ba ? ba[3] + (bb[3] - ba[3]) * alpha : bb[3]; o.gen = gen; buls.push(o); } for (const [id, o] of this.bulCache) if (o.gen !== gen) this.bulCache.delete(id); for (const t of this.towers) { const r = a.tt.get(t.id); t.tgt = r ? r[1] : 0; t.kills = r ? r[2] : 0; if (this.mode === 'versus') t.empT = r && r[3] ? r[3] : 0; // versus rows carry a 4th field: seconds of EMP left } v.towers = this.towers; const mySlot = this.you ? this.you.slot : -1; v.cursors = (b.snap.cur || []).filter((c) => c[0] !== mySlot).map((c) => ({ slot: c[0], x: c[1], y: c[2] })); } send(cmd) { const c = Object.assign({}, cmd); delete c.by; delete c.role; // the server knows the seat and its role stampCmd(c, this.view); this._send(Object.assign({ t: 'cmd' }, c)); return { ok: true, pending: true }; } ctl(c, v) { if (this.mode !== 'versus') this._send({ t: 'ctl', c, v }); } // versus has no pause and no speed (the server refuses them) vsSend(c, v, extra) { this._send(Object.assign({ t: 'vs', c, v }, extra)); return { ok: true, pending: true }; } vsRole(v) { return this.vsSend('role', v); } vsReady(v) { return this.vsSend('ready', v); } vsBot(v, skill) { return this.vsSend('bot', v, skill === undefined ? undefined : { skill }); } vsStart() { return this.vsSend('start'); } vsNext() { return this.vsSend('next'); } vsRematch() { return this.vsSend('rematch'); } preview(x, y, routes) { if (!this.board) return { ok: false, reason: 'bounds' }; const reserved = new Set(); for (const m of this.view.monsters) if (!m.air) reserved.add(Math.floor(m.y) * this.board.cols + Math.floor(m.x)); return this.board.trial(x, y, reserved, null, routes); } newGame(map, difficulty) { this._send({ t: 'newgame', map, difficulty }); } // (JSON drops an undefined difficulty: the server keeps the room's) // Moves are throttled to one per 70 ms. A clear (x === null) or `force` always goes out, so the final position / the // "cursor gone" message of a touch is never swallowed by the throttle (touch-9). sendCursor(x, y, force) { const now = performance.now(); if (x !== null && !force && now - this.lastCursor < 70) return; this.lastCursor = now; this._send({ t: 'cursor', x: x === null ? null : Math.round(x * 100) / 100, y: y === null ? null : Math.round(y * 100) / 100 }); } sendMark(x, y) { this._send({ t: 'mark', x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100 }); } // Leaves the room (a deliberate leave frees the seat at once) and detaches from the UI for good: after this nothing is emitted, so // a controller that was still connecting cannot take over a game that was started meanwhile (code-3). close() { if (this.intentional) return; this.intentional = true; this._stopTimers(); this._dispose(); const ws = this.ws; this.ws = null; if (ws) { try { if (ws.readyState === 1) ws.send(JSON.stringify({ t: 'leave' })); } catch (e) { /* ignore */ } ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null; try { ws.close(); } catch (e) { /* ignore */ } } this._setStatus('closed'); this._h = {}; } } NW.LocalController = LocalController; NW.RemoteController = RemoteController; NW.matchScores = matchScores; // the match rules (shared with the server by a parity test): also handy for the end screen NW.matchWinner = matchWinner; NW.wsUrl = wsUrl; })(typeof self !== 'undefined' ? self : this);