Co-op robustness, audio/a11y, new towers and enemies, Uplink rebalance

Co-op (QA'd with two to three real browsers, TCP-proxy chaos scenarios):
- partner's tower changes are never dropped after a render stall or snapshot burst
- half-open connections show "reconnecting" in ~6 s instead of 45-65 s
- upgrade and next-wave are idempotent (stale commands refused), restart message,
  promoted host gets Play again, failed joins never kill a live game, listener leaks

Audio / keyboard / a11y:
- one Audio element per track, fade/stinger supersede tokens, play() retry on the
  next gesture, 5 s fallback to the synth, mute works everywhere, dialogs with
  role/aria-modal/focus handling, accessible names for sound/speed/pause

New content:
- enemies: Daemon (healer), Proxy (regenerating shield), Botnet (flyer swarm);
  waves weave them in from wave 9 (waves 1-8 unchanged)
- towers: Sandbox (stun pulse), Load Balancer (fire-rate aura); hotkeys 1-9
- glyphs/shapes, stun/heal effects, gallery e2e that pixel-checks every kind

Orbital Uplink rebalanced after playtesting (was affordable by wave ~6 and buyable
in bulk from boss rewards): 1500 credits, upgrades 1200/2000/3200, and every Uplink
already owned makes the next one 25% dearer to buy AND to upgrade (each tower
remembers its multiplier, carried in the tower list as a 9th field). Shared
TD.priceFor/upgradePrice so the UI shows exactly what the sim charges.

Also: tablet/foldable viewports in the layout matrix (tolerant colour check),
docs (README tower/enemy tables, PROTOCOL shield/stun/pm encodings, NEXT roadmap).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
Claude 2026-10-10 21:18:43 +00:00
parent 962189419a
commit 28502984ec
29 changed files with 3370 additions and 230 deletions

View file

@ -8,7 +8,9 @@
* 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.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.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'
@ -18,6 +20,9 @@
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 = {}; }
@ -29,6 +34,13 @@
}
}
// 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);
@ -80,7 +92,7 @@
if (ev.length) this.emit('events', ev);
}
send(cmd) {
const res = this.sim.cmd(Object.assign({}, cmd, { by: 0 }));
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;
}
@ -110,6 +122,9 @@
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;
@ -124,6 +139,11 @@
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;
@ -140,6 +160,23 @@
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); } }
@ -155,11 +192,12 @@
}
_die(code, msg) {
this.fatal = true; this._setStatus('closed');
this._stopTimers();
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; }
@ -170,27 +208,30 @@
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 */ } }
else if (this.status === 'joined' && stale) this._abandon();
}
_stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; this._stopRtt(); }
_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 > 5000) { try { this.ws.close(); } catch (e) { /* ignore */ } }
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');
@ -214,6 +255,11 @@
{ 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.' };
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
break;
@ -227,7 +273,7 @@
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 };
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();
}
@ -236,7 +282,7 @@
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();
this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear();
if (snap) this._push(snap, true);
}
_push(snap, first) {
@ -246,7 +292,12 @@
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();
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.
@ -272,10 +323,13 @@
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 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;
@ -319,6 +373,7 @@
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 };
}
@ -339,13 +394,20 @@
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();
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._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 = {};
}
}