towerdef/public/js/controllers.js
Claude b4ae6cb57d Difficulty picker (Easy/Normal/Hard) and a balance pass
Difficulty:
- TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated
  create-room / newgame option, state carries it; solo menu picker and co-op lobby
  picker (44px segmented control, reachable on every layout), HUD/room/end-screen
  labels, best-wave record per map AND difficulty (Normal keeps the legacy key),
  Play again keeps the running game's difficulty for host and guest

Balance (12 bot runs, deterministic, 48/48 games replay identically in QA):
- Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open
- credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling
  eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at
  wave 30: 1309 -> 335
- IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only
  dies by wave 7); Mortar, Arc and Filter buffed
- Orbital Uplink price step per owned unit 30% (buy and upgrade)
- remaining imbalances documented in docs/BALANCE.md

Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix
reachability of the picker. 156 unit tests, 17 e2e scenarios.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-10 23:41:21 +00:00

427 lines
22 KiB
JavaScript

/*
* 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'
*/
(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;
}
// ws(s)://<same host>/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._fresh();
}
_fresh() {
this.sim = 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,
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.difficulty = s.difficulty;
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(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 (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 (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.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, towers: [], monsters: [], bullets: [], cursors: [],
};
this._onVis = () => { if (!document.hidden) this._wake(); };
document.addEventListener('visibilitychange', this._onVis);
root.addEventListener('online', this._onVis);
this._timers = [];
}
// 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 { j.map = this.mapId; j.difficulty = this.difficulty; } // only a creating join carries them: a joiner takes the room's
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);
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': {
// "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_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.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;
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;
stampCmd(c, this.view);
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, 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.wsUrl = wsUrl;
})(typeof self !== 'undefined' ? self : this);