/* * 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 * 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 * ctrl.ctl(c, v) 'pause' | 'speed' * 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' */ (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)); 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); } } } } // 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.speed = 1; this.paused = false; this.players = [{ slot: 0, name: 'You', online: true, host: true }]; this.you = { slot: 0, host: true }; this._fresh(); } _fresh() { this.sim = new TD.Sim({ map: this.mapId }); 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, towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [], }; this._sync(); } _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.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets; } update(now) { 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) { const res = this.sim.cmd(Object.assign({}, cmd, { by: 0 })); 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 (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); } newGame(map) { if (map) this.mapId = map; 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.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.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, towers: [], monsters: [], bullets: [], cursors: [], }; this._onVis = () => { if (!document.hidden) this._wake(); }; document.addEventListener('visibilitychange', this._onVis); root.addEventListener('online', this._onVis); this._timers = []; } 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 j.map = this.mapId; 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 */ }; } _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.emit('fatal', { code, msg }); } _onClose(e) { this.ws = null; 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) { try { this.ws.close(); } catch (e) { /* ignore */ } } } _stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; 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 > 5000) { try { this.ws.close(); } catch (e) { /* ignore */ } } }, 1000); } _send(o) { if (this.ws && this.ws.readyState === 1) this.ws.send(JSON.stringify(o)); } _onMsg(raw) { 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': this.room = m.room; this.you = m.you; this.players = m.players || []; this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused; this._applyState(m.state, m.snap); this._setStatus('joined'); this._startRtt(); this.emit('joined', m); this.emit('players', this.players); 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 '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': { const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', 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.' }; 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], 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.buf.length = 0; 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); if (this.buf.length > 10) this.buf.shift(); } // 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) / (b.t - a.t), 0, 1); let lastTw = null; for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k]; } buf[k].twDone = true; } if (lastTw) { this._setTowers(lastTw.snap.tw); this.rev = lastTw.snap.rev; } 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; 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; } 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; this._send(Object.assign({ t: 'cmd' }, c)); return { ok: true, pending: true }; } ctl(c, v) { this._send({ t: 'ctl', c, v }); } 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) { this._send({ t: 'newgame', map }); } sendCursor(x, y) { const now = performance.now(); if (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 }); } close() { this.intentional = true; this._stopTimers(); document.removeEventListener('visibilitychange', this._onVis); root.removeEventListener('online', this._onVis); if (this.ws) { try { this._send({ t: 'leave' }); this.ws.close(); } catch (e) { /* ignore */ } } this._setStatus('closed'); } } NW.LocalController = LocalController; NW.RemoteController = RemoteController; NW.wsUrl = wsUrl; })(typeof self !== 'undefined' ? self : this);