+
-
-
+
@@ -110,10 +111,10 @@
NETWALL
NETWALL
Build the firewall. Stretch the route. Protect the server.
@@ -103,6 +103,7 @@
+
+
-
Co-op online
+Co-op online
Two players, one base, one pool of credits. Create a room and send the link, or enter a friend's code.
@@ -140,16 +141,16 @@
-
+
/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 = {};
}
}
diff --git a/public/js/main.js b/public/js/main.js
index 0054eb9..a3bbc66 100644
--- a/public/js/main.js
+++ b/public/js/main.js
@@ -6,6 +6,9 @@
const TD = root.TD, NW = root.NW, Audio = NW.Audio;
const $ = (id) => document.getElementById(id);
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
+ // Anything that came from the server and goes into innerHTML is escaped; colours are looked up in our own table (code-28).
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
+ const slotColor = (slot) => (Number.isInteger(slot) && NW.SLOT_COLORS[slot]) || '#9db4d8';
// ------------------------------------------------------------------ storage (every access guarded)
const store = {
@@ -89,7 +92,45 @@
const wasHidden = o.hidden; o.hidden = o.id !== id;
if (wasHidden && !o.hidden) { const body = o.querySelector('.card-body'); if (body) body.scrollTop = 0; }
}
+ syncModal();
}
+
+ // ------------------------------------------------------------------ dialogs (menu, lobby, help, end are role=dialog)
+ // While one is open the page behind it is inert (not focusable, not clickable, hidden from screen readers), focus moves into the
+ // dialog onto its primary button, Tab stays inside it, and focus goes back to where it was when the dialog closes (code-8).
+ // Overlays are also hidden and shown directly (`$('end').hidden = true`), so a MutationObserver keeps this in step.
+ const modal = { open: null, opener: null, guard: 0 };
+ const isShown = (el) => el.getClientRects().length > 0 && !el.disabled;
+ function syncModal() {
+ const ov = document.querySelector('.overlay:not([hidden])');
+ if (ov === modal.open) return;
+ const was = modal.open;
+ modal.open = ov;
+ if (ov && !was) { const a = document.activeElement; modal.opener = a && a !== document.body && a.isConnected ? a : null; } // (before the page behind it goes inert and drops focus)
+ for (const id of ['topbar', 'stage', 'side']) { const el = $(id); if (el) el.toggleAttribute('inert', !!ov); }
+ if (ov) {
+ const btns = [...ov.querySelectorAll('button')].filter(isShown);
+ const first = btns.find((b) => b.classList.contains('primary')) || btns[0]; // never a text field: on a phone that would raise the keyboard
+ if (ov.id === 'end') modal.guard = performance.now() + 600; // (see the click guard below)
+ if (first) first.focus({ preventScroll: true });
+ } else if (was) {
+ const o = modal.opener; modal.opener = null;
+ if (o && o.isConnected && isShown(o) && !o.closest('[inert]')) o.focus({ preventScroll: true });
+ }
+ }
+ root.addEventListener('keydown', (e) => { // Tab wraps inside the open dialog (browsers without `inert` would let it out)
+ if (e.key !== 'Tab' || !modal.open) return;
+ const items = [...modal.open.querySelectorAll('button, input, a[href]')].filter(isShown);
+ if (!items.length) { e.preventDefault(); return; }
+ const first = items[0], last = items[items.length - 1], a = document.activeElement;
+ if (!modal.open.contains(a)) { e.preventDefault(); first.focus(); }
+ else if (e.shiftKey && a === first) { e.preventDefault(); last.focus(); }
+ else if (!e.shiftKey && a === last) { e.preventDefault(); first.focus(); }
+ });
+ { const mo = new MutationObserver(syncModal); for (const o of document.querySelectorAll('.overlay')) mo.observe(o, { attributes: true, attributeFilter: ['hidden'] }); }
+ // The game-over dialog takes focus the moment the game ends, and a player who was tapping Space / Enter to start waves would
+ // press its focused "Play again" with the next key and never see the result. For the first 0.6 s only a pointer can press its buttons.
+ $('end').addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
function setScreen(name) {
app.screen = name;
$('app').dataset.screen = name;
@@ -99,11 +140,16 @@
function useController(ctrl) {
if (app.ctrl && app.ctrl !== ctrl && app.ctrl.kind === 'remote') { /* closed by caller */ }
app.ctrl = ctrl;
+ app.menuPaused = false;
+ if (ctrl.kind !== 'remote') { ui.coop = false; ui.names = {}; app.prevPlayers = null; } // no co-op owner flags / join toasts left over in a solo game (code-17)
ctrl.on('events', onEvents);
ctrl.on('reject', onReject);
ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); });
ctrl.on('players', onPlayers);
- ctrl.on('newgame', () => { resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true; });
+ ctrl.on('newgame', () => {
+ resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true;
+ app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5)
+ });
adoptBoard(true);
}
function adoptBoard(force) {
@@ -122,6 +168,7 @@
}
function startSolo(mapId) {
+ cancelPending(); // a co-op join that is still connecting must not take this game over (code-3)
leaveRemote(true);
app.mapId = mapId; store.set('nw.map', mapId);
const c = new NW.LocalController({ map: mapId });
@@ -130,8 +177,14 @@
resetSelection(); setScreen('playing'); showOverlay(null);
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
renderInfo(true);
- Audio.music('battle');
+ app.bossMusic = false; Audio.music('battle');
requestWakeLock();
+ firstRunHelp();
+ }
+ // The first-run help opens once per install (storage) and at most once per page load, so a browser whose storage throws does not get it on every start (code-26).
+ function firstRunHelp() {
+ if (app.helpSeen) return;
+ app.helpSeen = true;
if (!store.get('nw.helped', false)) { store.set('nw.helped', true); showOverlay('help'); }
}
function previewMap(mapId) {
@@ -139,13 +192,14 @@
c.paused = true;
useController(c);
app.inGame = false;
+ releaseWakeLock(); // nobody is playing: the screen may sleep again (code-20)
}
- function leaveRemote(silent) {
+ // keep: the connection was lost, not left on purpose, so the saved room stays and a reload or "Resume" can still try (coop-6)
+ function leaveRemote(silent, keep) {
const c = app.ctrl;
if (c && c.kind === 'remote') { c.close(); }
- sess.del('nw.room'); store.del('nw.session');
- clearRoomFromUrl();
+ if (!keep) { sess.del('nw.room'); store.del('nw.session'); clearRoomFromUrl(); }
if (!silent) { /* caller handles screens */ }
}
function clearRoomFromUrl() {
@@ -173,6 +227,7 @@
}
let errSfxAt = -1e9;
function onReject(r) {
+ if (r.reason === 'stale') return; // the partner pressed the same Upgrade / Next wave an instant earlier: it already happened, say nothing (coop-5)
toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad');
// One buzzer per wall stroke (a stroke can reject dozens of cells), and never a burst: co-op rejects arrive after the finger has lifted (touch-16)
const now = performance.now();
@@ -181,6 +236,8 @@
}
// ------------------------------------------------------------------ palette + info panel
+ // What building one more of this tower costs right now (the Orbital Uplink gets dearer for every one owned): same function the sim charges with
+ function priceOf(type) { return TD.priceFor(type, app.ctrl && app.ctrl.view ? app.ctrl.view.towers : 0); }
function buildPalette() {
const pal = $('palette');
pal.textContent = '';
@@ -189,10 +246,10 @@
const def = TD.TOWERS[type];
const b = document.createElement('button');
b.className = 'tbtn'; b.dataset.type = type; b.type = 'button';
- b.setAttribute('aria-label', def.name + ', ' + def.levels[0].cost + ' credits');
+ b.setAttribute('aria-label', def.name + ', ' + priceOf(type) + ' credits');
b.innerHTML = '' + def.key + '';
b.querySelector('.nm').textContent = def.name;
- b.querySelector('.cost').textContent = String(def.levels[0].cost);
+ b.querySelector('.cost').textContent = String(priceOf(type));
b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); });
pal.appendChild(b);
}
@@ -245,12 +302,16 @@
if (L.rate) out.push(['Fire rate', L.rate.toFixed(1) + '/s']);
if (L.dmg && L.rate) out.push(['DPS', String(Math.round(L.dmg * L.rate))]);
if (L.range) out.push(['Range', L.range.toFixed(1)]);
+ if (L.stun) out.push(['Stun', L.stun.toFixed(1) + ' s']); // Sandbox
+ if (L.pulse) out.push(['Pulse', 'every ' + L.pulse.toFixed(1) + ' s']);
+ if (L.boost) out.push(['Fire rate', '+' + Math.round(L.boost * 100) + '%']); // Load Balancer: the bonus it gives the turrets in range
if (L.splash) out.push(['Splash', L.splash.toFixed(1)]);
if (L.slow) out.push(['Slows', Math.round(L.slow * 100) + '%']);
if (L.chains) out.push(['Chains', String(L.chains)]);
return out;
}
function targetsText(def) { return def.ground && def.air ? 'ground + air' : def.ground ? 'ground only' : 'none'; }
+ function aimsAtTargets(def) { return def.role !== 'wall' && def.role !== 'control' && def.role !== 'support'; } // has a Target mode and can get kills
// The info panel is built ONCE per selection (tower id + owner, or armed build type) and then updated in place, so a
// button is never replaced under a finger: partner actions bump view.rev constantly in co-op (code-2). A rebuild that
@@ -267,21 +328,21 @@
if (tower) {
if (ctrl.kind === 'remote' && ctrl.players.length > 1) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : '');
- } else if (app.selType) shape = 'b' + app.selType;
+ } else if (app.selType) shape = 'b' + app.selType + ':' + priceOf(app.selType); // the price can change while armed (Orbital Uplink)
if (!force && shape === info.shape) { if (tower) syncInfo(); return; }
if (info.pressed) { info.dirty = true; return; } // never replace a node while a pointer is down on it
info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false;
if (!shape) { box.textContent = ''; return; }
if (tower) {
- const def = TD.TOWERS[tower.type], wall = tower.type === 'wall';
+ const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', aim = aimsAtTargets(def);
box.innerHTML =
'' +
'';
+ ' ';
box.querySelector('.nm').textContent = def.name;
box.querySelector('.desc').textContent = def.desc;
if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name;
@@ -293,7 +354,7 @@
if (app.selType !== 'wall') kv += '';
box.querySelector('.nm').textContent = def.name;
- box.querySelector('.lv').textContent = def.levels[0].cost + ' credits';
+ box.querySelector('.lv').textContent = priceOf(app.selType) + ' credits';
box.querySelector('.desc').textContent = def.desc;
NW.drawIcon(box.querySelector('canvas'), app.selType, 1);
}
@@ -304,7 +365,7 @@
const box = $('info'), view = app.ctrl.view, t = view.towers.find((x) => x.id === app.selTower);
if (!t || !box.firstChild) return;
const def = TD.TOWERS[t.type], wall = t.type === 'wall', i = t.level - 1;
- const canUp = t.level < def.levels.length, upCost = canUp ? def.levels[t.level].cost : 0;
+ const canUp = t.level < def.levels.length, upCost = canUp ? TD.upgradePrice(t.type, t.level, t.pm) : 0;
const affordable = canUp && view.gold >= upCost;
const sellVal = def.refund ? t.spent : Math.floor(t.spent * TD.SELL_RATIO);
const sig = t.level + ':' + t.mode + ':' + sellVal + ':' + t.kills + ':' + (affordable ? 1 : 0);
@@ -372,6 +433,7 @@
app.last.waveKey = key;
const box = $('nextwave');
if (view.state !== 'playing') { box.textContent = ''; return; }
+ if (n % 10 === 9 || n % 10 === 0) Audio.preload('boss'); // the boss theme is fetched a wave or two ahead, so it starts with the boss instead of seconds later (code-12)
const sum = TD.waveSummary(n);
let html = '
-
- How to play
+How to play
- Goal. Packets pour in from the gateways (red). Don't let them reach the server. Each leak costs integrity (♥).
- Maze. The map is open: Firewalls are cheap walls. Packets always take the shortest open route, so walls make them walk further, past your turrets. You can lengthen the route but never seal it off completely. HoverTap to preview the new route.
- Turrets. Filter (fast), IDS Sniper (long range, armour-piercing), Mortar (splash), Rate Limiter (slows), Router Arc (chain lightning), and the very expensive late-game Orbital Uplink (a piercing beam that ignores armour, hits flyers and slows what it touches). Spoofed packets fly over your maze, so keep some anti-air. Mortars can't hit flyers.
- Credits. Earned from kills and every cleared wave. Upgrade turrets up to level 3. Sell for 70% back (walls refund in full). -
- Controls. Click to build, drag to paint walls, right-click to cancel. Keys 1–6 pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, wheel zooms. +
- Controls. Click to build, drag to paint walls, right-click to cancel. Keys 1–6 pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, M mutes, wheel zooms. Tap a tower type, then tap the map to preview; nudge the cell with the arrows and tap ✓ to build. Walls paint as you drag. Pinch to zoom, two fingers to pan, long-press to ping your partner.
- Co-op. Both players share everything and can build, sell and upgrade at the same time. You see each other's cursors; long-press / Alt-click pings the map.
+
diff --git a/public/js/audio.js b/public/js/audio.js
index db680e3..dabeef8 100644
--- a/public/js/audio.js
+++ b/public/js/audio.js
@@ -17,9 +17,7 @@
let unlocked = false;
let wanted = null; // music track the game currently wants ('theme' | 'battle' | 'boss' | null)
let current = null; // { name, kind:'file'|'synth', el?, stop() }
- const fileState = {}; // name -> 'unknown' | 'ok' | 'missing'
const lastPlay = {};
- const files = {}; // name -> HTMLAudioElement
try {
const s = JSON.parse(localStorage.getItem(STORE) || '{}');
@@ -200,46 +198,115 @@
// ---------------------------------------------------------------- file music
// assets/music/tracks.json maps track names to file names, e.g. {"battle": "my-song.mp3"}; null = use the synth.
// Reading one small manifest (instead of probing for files) keeps the console free of 404s.
- let manifestP = null;
- function manifest() {
- if (!manifestP) {
- manifestP = (typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))
- ? fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' }).then((r) => (r.ok ? r.json() : {})).catch(() => ({}))
- : Promise.resolve({});
- }
+ //
+ // Rules that keep the sound right when the game asks for music faster than a file loads or a fade finishes:
+ // * every track has ONE element for the whole session, created the first time it is asked for (not when it can play), so
+ // rapid music() calls share one download (code-16);
+ // * a fade belongs to its element and any newer fade or restart cancels it, so a stale fade-out can never pause a track that
+ // was started again (code-7); the stinger has its own supersede token (code-12);
+ // * a file that is not playable within timing.load ms (stalled, or broken) is replaced by the synth at once, and the file is
+ // tried again the next time that track is wanted (code-15);
+ // * a play() the browser refuses (iOS / Safari autoplay rules) is retried inside the next tap, click or key press (code-14).
+ const timing = { load: 5000, sting: 2500, retry: 15000 }; // ms: wait for a music file / for a stinger / before retrying a file that errored
+ let manifestData = null, manifestP = null, manifestTried = -1e9;
+ function manifest() { // resolves to the manifest, or null when it could not be read (never latched: it is asked again later)
+ if (manifestData) return Promise.resolve(manifestData);
+ if (manifestP) return manifestP;
+ if (!(typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))) { manifestData = {}; return Promise.resolve(manifestData); }
+ if (Date.now() - manifestTried < timing.retry) return Promise.resolve(null);
+ manifestTried = Date.now();
+ manifestP = fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' })
+ .then((r) => (r.ok ? r.json() : r.status === 404 ? {} : null)) // no manifest at all = no files: synth for good; a server error is asked again later
+ .catch(() => null)
+ .then((m) => { manifestP = null; if (m && typeof m === 'object') manifestData = m; return manifestData; });
return manifestP;
}
- function fileFor(name, cb) {
- if (fileState[name] === 'missing') { cb(null); return; }
- if (files[name]) { cb(files[name]); return; }
- manifest().then((m) => {
- const f = m && typeof m[name] === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(m[name]) ? m[name] : null;
- if (!f) { fileState[name] = 'missing'; cb(null); return; }
- const el = new Audio();
- el.preload = 'auto';
- el.loop = name !== 'win' && name !== 'lose';
- el.addEventListener('canplay', () => { fileState[name] = 'ok'; files[name] = el; cb(el); }, { once: true });
- el.addEventListener('error', () => { fileState[name] = 'missing'; cb(null); }, { once: true });
- el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
- el.load();
- });
+ manifest(); // (read it up front: the first tap can then create the element and call play() inside the gesture, which iOS insists on)
+ function fileName(name) {
+ const f = manifestData && manifestData[name];
+ return typeof f === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(f) ? f : null;
+ }
+ const tracks = {}; // name -> { el, state: 'loading' | 'ready' | 'failed', failedAt }
+ // The element of a track; null when the manifest names no file for it. A failed one is tried again after timing.retry.
+ function track(name) {
+ let t = tracks[name];
+ if (t && t.state === 'failed' && Date.now() - t.failedAt > timing.retry) { try { t.el.removeAttribute('src'); t.el.load(); } catch (e) { /* ignore */ } t = tracks[name] = null; }
+ if (t) return t;
+ const f = fileName(name);
+ if (!f) return null;
+ const el = new Audio();
+ t = tracks[name] = { name, el, state: 'loading', failedAt: 0 };
+ el.preload = 'auto';
+ el.loop = name !== 'win' && name !== 'lose';
+ el.addEventListener('canplay', () => { if (t.state === 'loading') t.state = 'ready'; });
+ el.addEventListener('error', () => { if (tracks[name] === t) { t.state = 'failed'; t.failedAt = Date.now(); } });
+ el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
+ return t;
+ }
+ // Starts a track the player is not listening to yet (the boss theme before the boss, the stingers before the end). Cheap files only
+ // unless the connection allows it: Data Saver and 2G/3G skip it.
+ function preload(name) {
+ const c = root.navigator && root.navigator.connection;
+ if (c && (c.saveData || /(^|-)[23]g$/.test(c.effectiveType || ''))) return;
+ manifest().then(() => { if (manifestData) track(name); });
}
+ const fades = new WeakMap(); // element -> the fade running on it (a token object)
+ function cancelFade(el) { fades.delete(el); }
function fadeEl(el, to, ms, done) {
+ const mine = {}; fades.set(el, mine);
const from = el.volume, t0 = performance.now();
const step = () => {
- const k = Math.min(1, (performance.now() - t0) / ms);
+ if (fades.get(el) !== mine) return; // superseded: a newer fade or a restart owns the element now
+ const k = ms > 0 ? Math.min(1, (performance.now() - t0) / ms) : 1;
try { el.volume = Math.max(0, Math.min(1, from + (to - from) * k)); } catch (e) { /* ignore */ }
- if (k < 1) requestAnimationFrame(step); else if (done) done();
+ if (k < 1) setTimeout(step, 33); else { fades.delete(el); if (done) done(); } // (a timer, not rAF: a hidden tab must still finish its fade-out)
};
step();
}
+ const pauseEl = (el) => { try { el.pause(); } catch (e) { /* ignore */ } };
+ let blocked = false; // the browser refused play(): the next gesture retries (code-14)
+ let stingersLoaded = false; // the end-screen stingers are fetched once, after the first battle track plays
function stopCurrent(fade) {
const c = current; current = null;
- if (!c || c.kind === 'pending') return;
+ if (!c) return;
+ clearTimeout(c.timer);
if (c.kind === 'synth') c.stop(fade);
- else fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { try { c.el.pause(); } catch (e) { /* ignore */ } });
+ else if (c.el) fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { if (!(current && current.el === c.el)) pauseEl(c.el); });
+ }
+ // The generative melody stands in for a track whose file is missing, broken or too slow.
+ function useSynth(tok) {
+ clearTimeout(tok.timer);
+ if (current !== tok) return;
+ if (tok.el) { cancelFade(tok.el); pauseEl(tok.el); } // the file may still arrive: it must not start on top of the synth
+ const c = ensureCtx();
+ current = c ? startSynth(tok.name) : null;
+ if (current) current.name = tok.name;
+ }
+ function playFile(t, tok, keepPos) {
+ const el = t.el;
+ tok.el = el;
+ cancelFade(el);
+ if (el.paused && !keepPos) { try { el.currentTime = 0; } catch (e) { /* not seekable yet */ } el.volume = 0; } // (a track still playing, e.g. a mute undone during its fade-out, carries on)
+ let pr;
+ try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
+ const ok = () => {
+ if (current !== tok) return;
+ clearTimeout(tok.timer);
+ tok.kind = 'file';
+ fadeEl(el, 0.8 * musicVol, 1200);
+ if (tok.name === 'battle' && !stingersLoaded) { stingersLoaded = true; setTimeout(() => { preload('lose'); preload('win'); }, 1500); }
+ };
+ const bad = (err) => {
+ if (current !== tok) return;
+ const why = err && err.name;
+ if (why === 'AbortError') return; // paused or reloaded under it (tab hidden): the visible handler starts it again
+ if (why === 'NotAllowedError') { clearTimeout(tok.timer); pauseEl(el); current = null; blocked = true; return; }
+ t.state = 'failed'; t.failedAt = Date.now();
+ useSynth(tok);
+ };
+ if (pr && pr.then) pr.then(ok, bad); else ok();
}
function applyMusic() {
@@ -249,57 +316,61 @@
if (current && current.name === wanted) return;
const name = wanted;
stopCurrent(0.9);
- // placeholder so that rapid calls do not stack
- const token = current = { name, kind: 'pending', stop() {} };
- fileFor(name, (el) => {
- if (current !== token) return; // superseded while loading
- if (el) {
- el.currentTime = 0; el.volume = 0;
- const pr = el.play();
- if (pr && pr.catch) pr.catch(() => { /* blocked: will retry on next gesture */ current = null; });
- current = { name, kind: 'file', el, stop() {} };
- fadeEl(el, 0.8 * musicVol, 1200);
- } else {
- const c = ensureCtx();
- current = c ? startSynth(name) : null;
- if (current) current.name = name;
- }
- });
+ const tok = current = { name, kind: 'pending', stop() {}, el: null, timer: 0 }; // placeholder: rapid calls do not stack, a late answer is ignored
+ tok.timer = setTimeout(() => { if (current === tok) useSynth(tok); }, timing.load);
+ const go = () => {
+ const t = track(name);
+ if (!t || t.state === 'failed') useSynth(tok); else playFile(t, tok);
+ };
+ if (manifestData) { go(); return; } // (synchronously, so that play() is still inside the tap)
+ manifest().then(() => { if (current === tok) go(); });
}
- let stingEl = null;
+ let stingEl = null, stingTok = 0;
function stopStinger(fade) {
+ stingTok++;
const el = stingEl; stingEl = null;
- if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { try { el.pause(); } catch (e) { /* ignore */ } });
+ if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { if (stingEl !== el) pauseEl(el); });
+ }
+ function jingle(name) { // the synth stinger, also what plays when the file is missing, late or refused
+ if (muted || !ctx) return;
+ if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
+ else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
}
function stinger(name) {
if (muted || !unlocked) return;
- fileFor(name, (el) => {
- if (el) { try { stopStinger(0.2); stingEl = el; el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; }
- if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
- else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
- });
+ stopStinger(0.2);
+ const tok = stingTok, t = manifestData ? track(name) : null;
+ if (!t || t.state === 'failed') { jingle(name); return; }
+ const el = t.el;
+ stingEl = el; cancelFade(el);
+ try { el.currentTime = 0; } catch (e) { /* not seekable yet */ }
+ el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol));
+ const fail = () => { if (tok !== stingTok) return; stingEl = null; cancelFade(el); pauseEl(el); jingle(name); };
+ const timer = setTimeout(fail, timing.sting); // not playing yet after this long: the synth jingle stands in, the file is dropped
+ let pr;
+ try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
+ if (pr && pr.then) pr.then(() => clearTimeout(timer), (err) => { clearTimeout(timer); if (!(err && err.name === 'AbortError')) fail(); });
}
// ---------------------------------------------------------------- public
function unlock() {
- if (unlocked) return;
const c = ensureCtx();
- if (c && c.state === 'suspended') c.resume();
- unlocked = true;
- applyMusic();
+ if (c && c.state !== 'running' && c.state !== 'closed') { try { const p = c.resume(); if (p && p.catch) p.catch(() => {}); } catch (e) { /* ignore */ } }
+ if (!unlocked) { unlocked = true; applyMusic(); return; }
+ if (blocked) { blocked = false; applyMusic(); } // a refused play() is retried at every gesture until it is allowed (code-14)
}
- root.addEventListener('pointerdown', unlock, { passive: true });
- root.addEventListener('keydown', unlock, { passive: true });
+ // Every kind of gesture, in the capture phase: pointerdown alone is no gesture for a finger (touch needs pointerup / touchend / click).
+ for (const ev of ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown']) root.addEventListener(ev, unlock, { passive: true, capture: true });
document.addEventListener('visibilitychange', () => {
- if (!ctx) return;
if (document.hidden) {
- ctx.suspend && ctx.suspend();
- if (current && current.kind === 'file') current.el.pause();
+ if (ctx && ctx.suspend) ctx.suspend();
+ if (current && current.el) pauseEl(current.el);
+ if (stingEl) pauseEl(stingEl);
} else {
- ctx.resume && ctx.resume();
- if (current && current.kind === 'file' && !muted) current.el.play().catch(() => {});
+ if (ctx && ctx.resume) ctx.resume();
+ if (current && current.el && !muted) { const t = tracks[current.name]; if (t && t.el === current.el) playFile(t, current, true); }
}
});
@@ -307,12 +378,15 @@
sfx,
unlock,
stinger,
+ preload,
+ timing, // tunable for tests
get muted() { return muted; },
get now() { return current ? { name: current.name, kind: current.kind } : null; }, // for tests / debugging
+ get blocked() { return blocked; },
setMuted(m) {
muted = !!m; save();
if (master) master.gain.value = muted ? 0 : 0.9;
- if (muted) stopCurrent(0.2); else applyMusic();
+ if (muted) { stopCurrent(0.2); stopStinger(0.2); } else applyMusic();
},
toggleMuted() { this.setMuted(!muted); return muted; },
// Which music the game wants right now: 'theme' | 'battle' | 'boss' | null
@@ -321,7 +395,7 @@
setMusicVolume(v) {
musicVol = Math.min(1, Math.max(0, v)); save();
if (musBus) musBus.gain.value = 0.3 * musicVol;
- if (current && current.kind === 'file') current.el.volume = 0.8 * musicVol;
+ if (current && current.kind === 'file') { cancelFade(current.el); current.el.volume = 0.8 * musicVol; }
},
};
})(typeof self !== 'undefined' ? self : this);
diff --git a/public/js/controllers.js b/public/js/controllers.js
index c35156c..5bb11bc 100644
--- a/public/js/controllers.js
+++ b/public/js/controllers.js
@@ -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)://Breach!
@@ -173,6 +174,7 @@Waiting for the host to start a new game…
+' +
(wall ? '' : '') +
'' +
- (wall ? '' : '') +
+ (aim ? '' : '') +
'
' +
- '' + (wall ? '' : '') + (ownerP ? '' : '') + '
' + (aim ? '' : '') + (ownerP ? '' : '') + '
Targets' + targetsText(def) + '
';
box.innerHTML = '' + kv + '
Next · wave ' + n + '
';
let air = false;
@@ -399,14 +461,15 @@
app.prevPlayers = list.map((p) => Object.assign({}, p));
renderPlayers();
if (ctrl.kind === 'remote') renderInfo(false); // the shape includes the owner, so only a changed roster rebuilds
+ if (!$('end').hidden) syncEndButtons(); // the host left while the end screen is up: the promoted guest gets "Play again" (coop-3, code-11)
}
function renderPlayers() {
const ctrl = app.ctrl, box = $('players');
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
box.hidden = false;
- let html = '
Room ' + (ctrl.room || '') + '
'; + let html = 'Room ' + esc(ctrl.room || '') + '
'; // (every server string is escaped before it goes into HTML, code-28) for (const p of ctrl.players) { - html += '' +
+ html += '
' +
(ctrl.you && p.pid === ctrl.you.pid ? '(you)' : '') + (p.host ? 'host' : '') + (p.online ? '' : 'offline') + '
';
}
if (ctrl.players.length < 2) html += 'Waiting for a partner… share the invite link.
';
@@ -420,7 +483,7 @@
if (b.dataset.act === 'invite') invite();
if (b.dataset.act === 'leave') { leaveToMenu(); }
});
- function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + app.ctrl.room; }
+ function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + encodeURIComponent(app.ctrl.room); }
function invite() {
const url = inviteUrl(), text = 'Join my Netwall game (room ' + app.ctrl.room + ')';
if (root.navigator.share) { root.navigator.share({ title: 'Netwall', text, url }).catch(() => {}); return; }
@@ -448,19 +511,24 @@
const attn = idle && view.wave === 0 && view.state === 'playing';
if (L.attn !== attn) { L.attn = attn; $('btnWave').classList.toggle('attn', attn); }
if (L.auto !== view.auto) { L.auto = view.auto; $('btnAuto').setAttribute('aria-pressed', view.auto ? 'true' : 'false'); }
- if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; }
+ if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; $('btnSpeed').setAttribute('aria-label', 'Game speed ' + view.speed + '×'); } // (the name carries the value: a screen reader hears the speed, not just "Game speed")
if (L.paused !== view.paused) { // paused: dimmed board, a resume pill, and an amber pressed pause button (not a second play triangle)
L.paused = view.paused; $('pausedTag').hidden = !view.paused; $('stage').classList.toggle('paused', !!view.paused);
- $('btnPause').setAttribute('aria-pressed', view.paused ? 'true' : 'false'); $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
+ $('btnPause').setAttribute('aria-pressed', view.paused ? 'true' : 'false'); // a toggle keeps its name ("Pause") and announces "pressed" while paused
}
const offline = !$('reconnect').hidden;
if (L.offline !== offline) { L.offline = offline; $('app').classList.toggle('offline', offline); }
- if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = ''; }
// palette affordability
const gold = view.gold;
- if (L.palGold !== gold) {
- L.palGold = gold;
- for (const b of $('palette').children) b.classList.toggle('poor', gold < TD.TOWERS[b.dataset.type].levels[0].cost);
+ const palKey = gold + ':' + view.towers.length; // prices can change when the tower count does (Orbital Uplink)
+ if (L.palGold !== palKey) {
+ L.palGold = palKey;
+ for (const b of $('palette').children) {
+ const def = TD.TOWERS[b.dataset.type], price = priceOf(b.dataset.type), poor = gold < price;
+ b.classList.toggle('poor', poor);
+ const c = b.querySelector('.cost'); if (c && c.textContent !== String(price)) c.textContent = String(price);
+ b.setAttribute('aria-label', def.name + ', ' + price + ' credits' + (poor ? ', not enough credits' : ''));
+ }
}
if (ctrl.kind === 'remote') {
const chip = $('netChip');
@@ -484,17 +552,21 @@
$('endTitle').textContent = won ? 'Server secured!' : 'Breach!';
$('endTitle').style.color = won ? 'var(--green)' : 'var(--red)';
const best = store.get('nw.best.' + ctrl.board.mapId, 0);
- if (!won && view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave);
+ if (view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave); // a win counts too (code-25)
$('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.';
const walls = view.towers.filter((t) => t.type === 'wall').length;
const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Best (map)', Math.max(best, view.wave)]];
- $('endStats').innerHTML = rows.map((r) => '' + r[0] + '' + r[1] + '
').join('');
- const remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
- $('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
+ $('endStats').innerHTML = rows.map((r) => '' + r[0] + '' + esc(r[1]) + '
').join(''); // (in co-op these numbers come from the server)
+ syncEndButtons();
$('btnContinue').hidden = !won;
showOverlay('end');
Audio.music(null); Audio.stinger(won ? 'win' : 'lose');
}
+ // Only the host of a co-op room starts the next game: the others wait. Called when the end screen opens and whenever the roster changes.
+ function syncEndButtons() {
+ const ctrl = app.ctrl, remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
+ $('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
+ }
// ------------------------------------------------------------------ placement + previews
function cellFromEvent(e) {
@@ -504,7 +576,7 @@
function placeAt(cell) {
const ctrl = app.ctrl;
if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) return false;
- const cost = TD.TOWERS[app.selType].levels[0].cost;
+ const cost = priceOf(app.selType);
if (ctrl.view.gold < cost) { onReject({ reason: 'gold' }); return false; }
ctrl.send({ c: 'place', type: app.selType, x: cell.x, y: cell.y });
app.previewDirty = true;
@@ -521,7 +593,7 @@
if (!force && !app.previewDirty && now - app.lastPreviewAt < 250) return;
app.previewDirty = false; app.lastPreviewAt = now;
const pv = ctrl.preview(cell.x, cell.y, true);
- const cost = TD.TOWERS[app.selType].levels[0].cost;
+ const cost = priceOf(app.selType);
const poor = ctrl.view.gold < cost;
ui.preview = pv; ui.valid = pv.ok && !poor;
if (!pv.ok) hint('✕ ' + (REASONS[pv.reason] || pv.reason), 'bad');
@@ -537,7 +609,7 @@
function updateConfirm() {
const show = !!(app.pending && app.selType && app.selType !== 'wall');
$('confirm').hidden = !show;
- if (show) { const cost = TD.TOWERS[app.selType].levels[0].cost; $('confirmText').textContent = 'Build · ' + cost; $('btnConfirmBuild').setAttribute('aria-label', 'Build for ' + cost + ' credits'); hint(hintText, hintKind); }
+ if (show) { const cost = priceOf(app.selType); $('confirmText').textContent = 'Build · ' + cost; $('btnConfirmBuild').setAttribute('aria-label', 'Build for ' + cost + ' credits'); hint(hintText, hintKind); }
else if (!ptrs.size) clearCursor(); // (no pending cell, no finger down: the partner's view of our touch cursor goes)
layoutBars(true);
}
@@ -837,8 +909,9 @@
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
if (e.ctrlKey || e.metaKey) return;
if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6)
+ if (e.key && e.key.toLowerCase() === 'm' && !e.altKey) { Audio.toggleMuted(); return; } // M mutes anywhere: in the menu, behind a dialog, on the end screen (code-13)
if (!app.inGame) return;
- if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; }
+ if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
const ctrl = app.ctrl, view = ctrl.view;
const k = e.key.toLowerCase();
// Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8)
@@ -851,7 +924,6 @@
case 'p': ctrl.ctl('pause', !view.paused); break;
case 'f': ctrl.ctl('speed', view.speed % 3 + 1); break;
case 'a': ctrl.send({ c: 'auto', v: !view.auto }); break;
- case 'm': Audio.toggleMuted(); break;
case 'u': if (app.selTower) $('info').querySelector('[data-act="up"]') && $('info').querySelector('[data-act="up"]').click(); break;
case 'x': case 'delete': case 'backspace': if (app.selTower) { $('info').querySelector('[data-act="sell"]') && $('info').querySelector('[data-act="sell"]').click(); e.preventDefault(); } break;
case 't': if (app.selTower) $('info').querySelector('[data-act="mode"]') && $('info').querySelector('[data-act="mode"]').click(); break;
@@ -867,7 +939,21 @@
$('btnAuto').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'auto', v: !app.ctrl.view.auto }); });
$('btnSpeed').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('speed', app.ctrl.view.speed % 3 + 1); });
$('btnPause').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', !app.ctrl.view.paused); });
- $('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); });
+ // The sound switch exists three times: the top bar, and a text button in the menu and the end dialog (the top bar is behind a dialog). One function keeps them in step.
+ let soundShown = null;
+ function syncSound() {
+ const m = Audio.muted;
+ if (soundShown === m) return;
+ soundShown = m;
+ const b = $('btnSound');
+ b.innerHTML = '';
+ b.setAttribute('aria-label', m ? 'Unmute sound' : 'Mute sound'); // the name says what a press does; the icon shows what is the case
+ b.title = (m ? 'Sound is off' : 'Sound is on') + ' (M)';
+ for (const id of ['btnMenuSound', 'btnEndSound']) { const x = $(id); if (x) x.textContent = 'Sound: ' + (m ? 'off' : 'on'); }
+ }
+ const toggleSound = () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); syncSound(); };
+ for (const id of ['btnSound', 'btnMenuSound', 'btnEndSound']) $(id).addEventListener('click', toggleSound);
+ syncSound();
$('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); });
$('pausedTag').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', false); });
$('netChip').addEventListener('click', () => { if (app.ctrl && app.ctrl.kind === 'remote') { Audio.sfx('click'); invite(); } }); // room code chip: tap to invite
@@ -905,7 +991,8 @@
}
function openMenu() {
- if (app.inGame && app.ctrl.kind === 'local') app.ctrl.ctl('pause', true);
+ // The menu pauses a solo game, and only the menu un-pauses it again: a game the player paused themselves stays paused (code-21).
+ if (app.inGame && app.ctrl.kind === 'local' && !app.ctrl.view.paused) { app.ctrl.ctl('pause', true); app.menuPaused = true; }
setScreen(app.inGame ? 'playing' : 'menu');
$('btnCloseMenu').hidden = !app.inGame;
$('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo';
@@ -915,11 +1002,13 @@
}
function closeOverlayToGame() {
if (!app.inGame) return;
+ if (!$('lobby').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
showOverlay(null);
- if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false);
+ if (app.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); }
}
- function leaveToMenu() {
- leaveRemote(true);
+ function leaveToMenu(keep) {
+ cancelPending();
+ leaveRemote(true, keep);
app.prevPlayers = null;
app.inGame = false;
$('reconnect').hidden = true; $('players').hidden = true; $('netChip').hidden = true;
@@ -950,11 +1039,11 @@
function openLobby(code) {
showOverlay('lobby'); setScreen(app.inGame ? 'playing' : 'menu');
$('inName').value = store.get('nw.name', '') || '';
- if (code) $('inCode').value = code;
+ if (code) { $('inCode').value = code; $('btnJoin').focus({ preventScroll: true }); } // an invite link: Enter must join that room, not create a new one (the dialog's first button is Create room)
lobbyMsg(root.location.protocol === 'file:' ? 'Co-op needs the Netwall server: run "npm start" and open its address (the page is currently opened as a file).' : '', root.location.protocol === 'file:');
}
$('btnCoop').addEventListener('click', () => { Audio.unlock(); openLobby(); });
- $('btnLobbyBack').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else openMenu(); });
+ $('btnLobbyBack').addEventListener('click', () => { cancelPending(); lobbyMsg(''); if (app.inGame) closeOverlayToGame(); else openMenu(); });
$('inCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
$('btnCreate').addEventListener('click', () => connectRemote({ room: null, map: app.mapId }));
$('btnJoin').addEventListener('click', () => {
@@ -964,34 +1053,64 @@
});
$('inCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnJoin').click(); });
+ // The co-op controller whose join is in progress. It becomes app.ctrl only once it has joined, so a failed join (wrong code, full room)
+ // leaves the game that is running untouched (coop-4), Back / Play solo can cancel it (code-3), and only one attempt runs at a time (code-4).
+ let pendingRc = null;
+ const KEEP_SESSION = { connect: 1, lost: 1, replaced: 1 }; // after these the saved room is still worth another try; any other failure means it is gone
+ function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume']) $(id).disabled = b; }
+ function cancelPending() {
+ const rc = pendingRc; pendingRc = null;
+ if (rc) rc.close();
+ setLobbyBusy(false);
+ }
+ // opts: { room, map, resume }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
function connectRemote(opts) {
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; }
+ if (pendingRc) return; // a double click must not open two rooms and an orphan socket
+ const live = app.inGame && app.ctrl && app.ctrl.kind === 'remote' ? app.ctrl : null;
+ if (live && opts.room && live.room === opts.room) { closeOverlayToGame(); return; } // that is the room we are in
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
store.set('nw.name', name);
- if (app.ctrl && app.ctrl.kind === 'remote') app.ctrl.close();
lobbyMsg('Connecting…');
- const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map });
+ const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, resume: !!opts.resume });
+ pendingRc = rc; setLobbyBusy(true);
+ const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); };
let first = true;
rc.on('joined', () => {
- sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() });
+ if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over
+ saveSession();
$('reconnect').hidden = true;
if (first) {
- first = false;
+ first = false; pendingRc = null; setLobbyBusy(false);
+ const old = app.ctrl; if (old && old !== rc && old.kind === 'remote') old.close(); // the room we were in is left only now that the new one is ours
useController(rc);
app.inGame = true; app.started = true; app.last = {}; app.endShown = false; app.prevPlayers = null;
resetSelection(); setScreen('playing'); showOverlay(null);
onPlayers(rc.players);
- try { root.history.replaceState(null, '', root.location.pathname + '?room=' + rc.room); } catch (e) { /* ignore */ }
+ try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
toast('Room ' + rc.room + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good');
Audio.music('battle'); requestWakeLock();
+ firstRunHelp(); // an invited player is new to the game too (code-26)
} else { toast('Reconnected', 'good'); adoptBoard(); }
lobbyMsg('');
});
- rc.on('status', (s) => { if (app.ctrl === rc && app.inGame) $('reconnect').hidden = s !== 'reconnecting'; });
+ rc.on('status', (s) => {
+ if (app.ctrl !== rc || !app.inGame) return;
+ $('reconnect').hidden = s !== 'reconnecting';
+ if (s === 'reconnecting') saveSession(); // the 15 minutes of "Resume" count from the last time we were in the room
+ });
rc.on('fatal', (f) => {
- sess.del('nw.room'); store.del('nw.session');
- if (app.ctrl === rc && app.inGame) { toast(f.msg, 'bad'); leaveToMenu(); openLobby(); lobbyMsg(f.msg, true); }
- else lobbyMsg(f.msg, true);
+ if (pendingRc === rc) { pendingRc = null; setLobbyBusy(false); }
+ const keep = !!KEEP_SESSION[f.code];
+ if (app.ctrl === rc && app.inGame) { // the game we were playing is gone
+ if (!keep) { sess.del('nw.room'); store.del('nw.session'); }
+ toast(f.msg, 'bad'); leaveToMenu(keep); openLobby(); lobbyMsg(f.msg, true);
+ return;
+ }
+ if (opts.resume && !keep) { sess.del('nw.room'); store.del('nw.session'); } // the saved game cannot be rejoined: forget it
+ lobbyMsg(f.msg, true);
+ if ($('lobby').hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
+ updateResumeButton();
});
rc.connect();
}
@@ -1006,13 +1125,26 @@
const s = store.get('nw.session', null); if (!s) return;
sess.set('nw.pid', s.pid);
$('inName').value = s.name || '';
- connectRemote({ room: s.room });
+ connectRemote({ room: s.room, resume: true });
});
// ------------------------------------------------------------------ misc platform bits
- let wakeLock = null;
+ let wakeLock = null, wakeAsk = false;
function requestWakeLock() {
- try { if (navigator.wakeLock && !wakeLock) navigator.wakeLock.request('screen').then((l) => { wakeLock = l; l.addEventListener('release', () => { wakeLock = null; }); }).catch(() => {}); } catch (e) { /* ignore */ }
+ if (wakeLock || wakeAsk) return;
+ try {
+ if (!navigator.wakeLock) return;
+ wakeAsk = true;
+ navigator.wakeLock.request('screen').then((l) => {
+ wakeAsk = false;
+ if (!app.inGame) { l.release().catch(() => {}); return; } // the game ended while the request was in flight
+ wakeLock = l; l.addEventListener('release', () => { if (wakeLock === l) wakeLock = null; });
+ }).catch(() => { wakeAsk = false; });
+ } catch (e) { wakeAsk = false; }
+ }
+ function releaseWakeLock() { // back at the menu the screen may sleep again (code-20)
+ const l = wakeLock; wakeLock = null;
+ if (l) { try { l.release().catch(() => {}); } catch (e) { /* ignore */ } }
}
document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); });
@@ -1066,20 +1198,25 @@
const ctrl = app.ctrl; if (!ctrl) return;
ctrl.update(now);
const view = ctrl.view;
+ syncSound(); // (M, the top bar, the menu and the end dialog can all flip it)
if (app.inGame) {
if (app.last.state !== view.state) {
app.last.state = view.state;
if (view.state === 'won' || view.state === 'lost') { if (!app.endShown) { app.endShown = true; endScreen(view); } }
- else if (app.endShown) { app.endShown = false; $('end').hidden = true; }
+ else if (app.endShown) { // the game went on without this player pressing anything (the host's Keep going / Play again): its music starts here too (code-5)
+ app.endShown = false; $('end').hidden = true;
+ app.bossMusic = view.monsters.some((m) => m.kind === 'rootkit'); Audio.music(app.bossMusic ? 'boss' : 'battle');
+ }
}
if (app.selTower && !view.towers.some((t) => t.id === app.selTower)) { app.selTower = 0; renderInfo(true); }
if (app.pending && pendFree) { // the partner built on the cell being previewed: drop it and say so (coop-7)
const t = towerAtCell(app.pending);
if (t) { setPending(null); toast(((ui.names && ui.names[t.owner]) || 'Someone') + ' just built there', 'bad'); }
}
- if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(false); }
+ if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower || app.selType) renderInfo(false); }
updateHud(view);
layoutBars(false);
+ updateFit(); // the Reset-zoom button always follows the camera, however it was reset (code-18, coop-8)
if (now - app.lastBossCheck > 600 && view.state === 'playing') {
app.lastBossCheck = now;
const boss = view.monsters.some((m) => m.kind === 'rootkit');
@@ -1108,7 +1245,7 @@
if (savedRoom && /^[A-Z0-9]{4}$/.test(savedRoom) && root.location.protocol !== 'file:' && (!codeParam || codeParam === savedRoom)) {
// page reload in the same tab: slip straight back into the room
$('inName').value = store.get('nw.name', '') || '';
- connectRemote({ room: savedRoom });
+ connectRemote({ room: savedRoom, resume: true });
} else if (/^[A-Z0-9]{4}$/.test(codeParam)) {
openLobby(codeParam);
lobbyMsg('Enter your name and press Join.');
diff --git a/public/js/render.js b/public/js/render.js
index 7748752..6ca7b5e 100644
--- a/public/js/render.js
+++ b/public/js/render.js
@@ -37,8 +37,8 @@
}
// ------------------------------------------------------------------ tower glyphs (also used for UI icons)
- // S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation)
- function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot) {
+ // S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation), fx = 0..1 flash right after a Sandbox pulse
+ function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot, fx) {
const def = TD.TOWERS[type]; if (!def) return;
const col = def.color;
ctx.save();
@@ -117,6 +117,43 @@
}
break;
}
+ case 'sandbox': {
+ // containment cell: four corner brackets round a core that hums, held by thin tethers; it flashes when it pulses
+ const g = fx || 0, p = 0.5 + 0.5 * Math.sin(t * 3), a = S * 0.22, k = S * 0.11;
+ ctx.save(); ctx.translate(0, -S * 0.04);
+ ctx.strokeStyle = rgba(col, 0.45); ctx.lineWidth = S * 0.03;
+ ctx.beginPath();
+ for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * S * 0.09, sy * S * 0.09); ctx.lineTo(sx * (a - k * 0.35), sy * (a - k * 0.35)); }
+ ctx.stroke();
+ ctx.strokeStyle = col; ctx.lineWidth = S * 0.06;
+ ctx.beginPath();
+ for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * a, sy * (a - k)); ctx.lineTo(sx * a, sy * a); ctx.lineTo(sx * (a - k), sy * a); }
+ ctx.stroke();
+ const c = S * (0.095 + 0.015 * p + 0.05 * g);
+ ctx.beginPath(); ctx.moveTo(0, -c); ctx.lineTo(c, 0); ctx.lineTo(0, c); ctx.lineTo(-c, 0); ctx.closePath();
+ ctx.fillStyle = g > 0 ? '#fff3dd' : rgba(col, 0.55 + 0.3 * p); ctx.fill();
+ ctx.lineWidth = S * 0.035; ctx.stroke();
+ ctx.restore();
+ break;
+ }
+ case 'balancer': {
+ // scales: post, a gently rocking beam and two hanging pans
+ const dy = S * 0.27 * Math.sin(Math.sin(t * 1.4) * 0.07), ex = S * 0.27, top = -S * 0.21;
+ ctx.save(); ctx.translate(0, -S * 0.02);
+ ctx.lineWidth = S * 0.05; ctx.strokeStyle = col;
+ ctx.beginPath(); ctx.moveTo(0, top); ctx.lineTo(0, S * 0.14); ctx.moveTo(-S * 0.12, S * 0.15); ctx.lineTo(S * 0.12, S * 0.15); ctx.stroke();
+ ctx.beginPath(); ctx.moveTo(-ex, top - dy); ctx.lineTo(ex, top + dy); ctx.stroke();
+ for (const sx of [-1, 1]) {
+ const px = sx * ex, py = top + sx * dy, w = S * 0.1, d = S * 0.14;
+ ctx.lineWidth = S * 0.03;
+ ctx.beginPath(); ctx.moveTo(px - w, py + d); ctx.lineTo(px, py); ctx.lineTo(px + w, py + d); ctx.stroke();
+ ctx.fillStyle = rgba(col, 0.55); ctx.beginPath(); ctx.arc(px, py + d, w, 0, Math.PI); ctx.closePath(); ctx.fill();
+ ctx.lineWidth = S * 0.04; ctx.beginPath(); ctx.arc(px, py + d, w, 0, Math.PI); ctx.stroke();
+ }
+ ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, top, S * 0.05, 0, TAU); ctx.fill();
+ ctx.restore();
+ break;
+ }
default: break;
}
// level pips: big enough to read at 14 px cells, with a dark halo so they show on any tile colour
@@ -129,8 +166,26 @@
}
// ------------------------------------------------------------------ monsters
- function drawMonster(ctx, m, ang, t, flash, rot) {
+ // Hit points and shield of one enemy, from either kind of view object. Solo hands the sim's monsters over (hp and shield apart:
+ // m.shield / m.maxShield); co-op gets hp + shield out of maxhp + maxShield from the wire, and the split follows the kind's table
+ // (the shield soaks first, so what is above the hit point part of the total is shield). Result is a shared scratch object.
+ const VIT = { hp: 0, mh: 1, sh: 0, ms: 0 };
+ function vitals(m, def) {
+ if (!def.shield) { VIT.hp = m.hp; VIT.mh = m.maxhp; VIT.sh = 0; VIT.ms = 0; }
+ else if (m.maxShield !== undefined) { VIT.hp = m.hp; VIT.mh = m.maxhp; VIT.sh = m.shield; VIT.ms = m.maxShield; }
+ else {
+ const mh = m.maxhp * def.hp / (def.hp + def.shield);
+ VIT.mh = mh; VIT.ms = m.maxhp - mh; VIT.hp = Math.min(m.hp, mh); VIT.sh = Math.max(0, m.hp - mh);
+ }
+ return VIT;
+ }
+ const SWARM = { botnet: 1 }; // swarm units die in a hit or two: no bar, no ground shadow, few particles (there can be 100+)
+
+ // stun: true while the enemy is frozen by a Sandbox (the caller knows: the sim's stunT in solo, "slow flag and not moving" in co-op)
+ function drawMonster(ctx, m, ang, t, flash, rot, stun) {
const def = TD.ENEMIES[m.kind], r = def.r * C, col = def.color;
+ const v = vitals(m, def), sf = v.ms > 0 ? clamp(v.sh / v.ms, 0, 1) : 0;
+ const lift = m.kind === 'ghost' ? -7 : 0;
ctx.save();
ctx.translate(m.x * C, m.y * C);
if (rot) { ctx.rotate(-rot); ang += rot; }
@@ -187,20 +242,72 @@
ctx.fillStyle = rgba('#ff3b3b', 0.55 + Math.sin(t * 4) * 0.3); ctx.beginPath(); ctx.arc(0, 0, r * 0.45, 0, TAU); ctx.fill();
break;
}
+ case 'daemon': {
+ // healer: an upright plus (a medic cross), its core breathing in time with the heal pulse
+ const a = r * 1.3, w = r * 0.38, br = 0.5 + 0.5 * Math.sin(t * 5 + m.id);
+ ctx.beginPath();
+ ctx.moveTo(-w, -a); ctx.lineTo(w, -a); ctx.lineTo(w, -w); ctx.lineTo(a, -w); ctx.lineTo(a, w); ctx.lineTo(w, w);
+ ctx.lineTo(w, a); ctx.lineTo(-w, a); ctx.lineTo(-w, w); ctx.lineTo(-a, w); ctx.lineTo(-a, -w); ctx.lineTo(-w, -w); ctx.closePath();
+ ctx.fillStyle = '#0d2b17'; ctx.fill(); ctx.lineWidth = 2.8; ctx.strokeStyle = col; ctx.stroke();
+ ctx.fillStyle = rgba('#d6ffe0', 0.5 + 0.4 * br);
+ ctx.fillRect(-w * 0.45, -a * 0.62, w * 0.9, a * 1.24); ctx.fillRect(-a * 0.62, -w * 0.45, a * 1.24, w * 0.9);
+ break;
+ }
+ case 'proxy': {
+ // shielded relay: a heater-shield badge (never a hexagon: the Trojan is one) inside a bubble that thins as the shield goes
+ if (sf > 0.01) {
+ ctx.fillStyle = rgba('#7ab8ff', 0.07 + 0.2 * sf); ctx.beginPath(); ctx.arc(0, 0, r * 1.55, 0, TAU); ctx.fill();
+ ctx.lineWidth = 0.9 + 2.3 * sf; ctx.strokeStyle = rgba('#b9dcff', 0.3 + 0.65 * sf); ctx.stroke();
+ }
+ ctx.beginPath();
+ ctx.moveTo(-r * 0.92, -r * 0.8); ctx.lineTo(r * 0.92, -r * 0.8); ctx.lineTo(r * 0.92, r * 0.12); ctx.lineTo(0, r * 1.05); ctx.lineTo(-r * 0.92, r * 0.12); ctx.closePath();
+ ctx.fillStyle = '#0d1a3a'; ctx.fill(); ctx.lineWidth = 2.8; ctx.strokeStyle = col; ctx.stroke();
+ ctx.fillStyle = rgba(col, 0.9); ctx.beginPath(); ctx.arc(0, -r * 0.12, r * 0.3, 0, TAU); ctx.fill();
+ ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(0, r * 0.2); ctx.lineTo(0, r * 0.72); ctx.stroke();
+ break;
+ }
+ case 'botnet': {
+ // a drone of a swarm: spinning X of two struts with a rotor at each tip, wobbling about its path
+ const a = Math.max(r * 1.7, 8), wb = 2.5;
+ ctx.translate(Math.sin(t * 6 + m.id * 1.9) * wb, Math.cos(t * 5 + m.id * 2.3) * wb);
+ ctx.rotate(t * 7 + m.id);
+ ctx.lineWidth = 3; ctx.strokeStyle = col;
+ ctx.beginPath(); ctx.moveTo(-a, -a); ctx.lineTo(a, a); ctx.moveTo(a, -a); ctx.lineTo(-a, a); ctx.stroke();
+ ctx.fillStyle = '#a6f2ea';
+ ctx.beginPath();
+ for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * a + 2.6, sy * a); ctx.arc(sx * a, sy * a, 2.6, 0, TAU); }
+ ctx.fill();
+ ctx.fillStyle = '#e8fffd'; ctx.beginPath(); ctx.arc(0, 0, r * 0.6, 0, TAU); ctx.fill();
+ break;
+ }
default:
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, r, 0, TAU); ctx.fill();
}
- if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; }
- if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r + 3.5, 0, TAU); ctx.stroke(); }
+ if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, lift, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; }
+ if (stun) {
+ // frozen by a Sandbox: an ice shell with crackling crystal spikes (the cyan ring below is only a slow)
+ const swarm = SWARM[m.kind], s = swarm ? 7 : Math.max(r * 1.3, 7) + 2;
+ ctx.fillStyle = 'rgba(200,240,255,.24)'; ctx.beginPath(); ctx.arc(0, lift, s, 0, TAU); ctx.fill();
+ ctx.lineWidth = swarm ? 1.4 : 2; ctx.strokeStyle = '#eefbff'; ctx.stroke();
+ if (!swarm) {
+ ctx.lineWidth = 2.2; ctx.beginPath();
+ for (let i = 0; i < 6; i++) {
+ const a = i * TAU / 6 + 0.5, len = s + (Math.sin(t * 31 + i * 2.1 + m.id) > 0 ? 6 : 3.5);
+ ctx.moveTo(Math.cos(a) * s, lift + Math.sin(a) * s); ctx.lineTo(Math.cos(a) * len, lift + Math.sin(a) * len);
+ }
+ ctx.stroke();
+ }
+ } else if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, lift, r + 3.5, 0, TAU); ctx.stroke(); }
ctx.restore();
- // health bar
- if (m.hp < m.maxhp) {
- const w = Math.max(15, r * 2.3), y = -r - (m.kind === 'ghost' ? 16 : 9), x = -w / 2;
- const f = clamp(m.hp / m.maxhp, 0, 1);
+ // health bar (a blue shield strip above it for shielded kinds)
+ if (!SWARM[m.kind] && (v.hp < v.mh || v.sh < v.ms)) {
+ const w = Math.max(15, r * 2.3), y = -r * (sf > 0.01 ? 1.55 : 1) - (m.kind === 'ghost' ? 16 : 9), x = -w / 2;
+ const f = clamp(v.hp / v.mh, 0, 1);
ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot);
- ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, 5);
+ ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, v.ms > 0 ? 8 : 5);
ctx.fillStyle = f > 0.5 ? '#35e0a1' : f > 0.25 ? '#ffd24d' : '#ff5c7a';
- ctx.fillRect(x, y, w * f, 3);
+ ctx.fillRect(x, y + (v.ms > 0 ? 3 : 0), w * f, 3);
+ if (v.ms > 0) { ctx.fillStyle = '#6fb4ff'; ctx.fillRect(x, y, w * sf, 2); }
ctx.restore();
}
}
@@ -214,6 +321,8 @@
this.cam = { zoom: 1, px: 0, py: 0 };
this.board = null;
this.parts = []; this.rings = []; this.lines = []; this.texts = []; this.marks = [];
+ this.pulses = []; // heal / stun pulses: their own small pool, so a swarm of daemons can never starve the leak and boom rings
+ this.glow = new Map(); // Sandbox cell index -> seconds of flash left after its pulse
this.aim = new Map(); this.trk = new Map();
this.wallGrid = null;
this.shake = 0; this.flashCore = 0; this.lastNow = 0;
@@ -225,8 +334,8 @@
setBoard(board) {
this.board = board;
this.wallGrid = new Uint8Array(board.cols * board.rows);
- this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0;
- this.aim.clear(); this.trk.clear();
+ this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0; this.pulses.length = 0;
+ this.aim.clear(); this.trk.clear(); this.glow.clear();
this.resetCamera();
}
resize(w, h, dpr) {
@@ -296,6 +405,7 @@
}
}
_ring(x, y, r0, r1, col, life, w) { if (this.rings.length < 40) this.rings.push({ x, y, r0, r1, col, life, max: life, w: w || 2 }); }
+ _pulse(x, y, r0, r1, col, life, w, fill) { if (this.pulses.length < 24) this.pulses.push({ x, y, r0, r1, col, life, max: life, w, fill }); }
_text(x, y, txt, col) { if (this.texts.length < 24) this.texts.push({ x, y, txt, col, life: 0.9, max: 0.9 }); }
addMark(x, y, slot) { this.marks.push({ x, y, slot: slot | 0, life: 1.6, max: 1.6 }); if (this.marks.length > 12) this.marks.shift(); }
addEvents(evs) {
@@ -303,7 +413,7 @@
switch (e.e) {
case 'kill': {
const d = TD.ENEMIES[e.k];
- this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : 6, 90, 0.5);
+ this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : SWARM[e.k] ? 2 : 6, 90, 0.5);
if (e.rw >= 3) this._text(e.x * C, e.y * C - 8, '+' + e.rw, '#ffd24d');
break;
}
@@ -334,6 +444,15 @@
case 'place': { const d = TD.TOWERS[e.type]; this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 34, d ? d.color : '#fff', 0.35, 2.5); this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, d ? d.color : '#fff', 5, 60, 0.35); break; }
case 'sell': this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, '#9db4d8', 6, 70, 0.35); break;
case 'up': this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 38, '#ffffff', 0.4, 2.5); break;
+ case 'stun': { // Sandbox pulse: an amber wave out to its range, a white one inside it, and the glyph flashes
+ const d = TD.TOWERS.sandbox, col = d ? d.color : '#ffa447', b = this.board;
+ const rg = (e.r || 3) * C;
+ this._pulse(e.x * C, e.y * C, 10, rg, col, 0.55, 3.5, 0.13);
+ this._pulse(e.x * C, e.y * C, 8, rg * 0.6, '#fff3dd', 0.35, 2, 0);
+ if (b) this.glow.set(Math.floor(e.y) * b.cols + Math.floor(e.x), 0.4);
+ break;
+ }
+ case 'heal': this._pulse(e.x * C, e.y * C, 10, (e.r || 2.2) * C, '#7ee08a', 0.7, 2.2, 0.07); break; // soft green wave out to the daemon's range
default: break;
}
}
@@ -413,6 +532,9 @@
const monById = new Map();
for (let i = 0; i < view.monsters.length; i++) monById.set(view.monsters[i].id, view.monsters[i]);
+ if (this.glow.size) for (const [k, g] of this.glow) { if (g - dt <= 0) this.glow.delete(k); else this.glow.set(k, g - dt); }
+ this._drawLinks(ctx, towers, ui, t);
+
const coop = ui.coop;
for (let i = 0; i < towers.length; i++) {
const tw = towers[i];
@@ -421,7 +543,8 @@
const tg = tw.tgt ? monById.get(tw.tgt) : null;
if (tg) { ang = lerpAngle(ang, Math.atan2(tg.y - (tw.y + 0.5), tg.x - (tw.x + 0.5)), 0.35); this.aim.set(tw.id, ang); }
const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C;
- drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot);
+ const gl = tw.type === 'sandbox' && this.glow.size ? this.glow.get(tw.y * cols + tw.x) : 0;
+ drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot, gl ? Math.min(1, gl / 0.25) : 0);
if (coop && tw.type !== 'wall') { // owner corner flag: at least ~5 CSS px, dark outline so it shows on a tile of the same colour
const k = Math.max(12, 5.5 / sc), x0 = cx - C * 0.46, y0 = cy - C * 0.46;
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + k, y0); ctx.lineTo(x0, y0 + k); ctx.closePath();
@@ -502,6 +625,47 @@
if (labels.length) this._cursorLabels(ctx, labels);
}
+ // Load Balancer links: dashed lines (flowing towards the turret) and an outline on every attack tower it boosts, only for the balancer that is
+ // selected, hovered or about to be built, so a busy board stays calm. Same rule as the sim's updateAuras: attack role, centre to centre
+ // within range. (The wire has no per-tower buff flag, so this is worked out here from the tower list.)
+ _drawLinks(ctx, towers, ui, t) {
+ let src = null;
+ if (ui.selTower) { const st = towers.find((x) => x.id === ui.selTower); if (st) src = st; }
+ if (!src && ui.hover) {
+ for (let i = 0; i < towers.length; i++) if (towers[i].x === ui.hover.x && towers[i].y === ui.hover.y) { src = towers[i]; break; }
+ if (!src && ui.selType && !ui.noGhost) src = { type: ui.selType, level: 1, x: ui.hover.x, y: ui.hover.y };
+ }
+ const def = src && TD.TOWERS[src.type];
+ if (!def || def.role !== 'support') return;
+ const lv = def.levels[src.level - 1] || def.levels[0], r2 = (lv.range || 0) * (lv.range || 0);
+ const bx = (src.x + 0.5) * C, by = (src.y + 0.5) * C;
+ let lines = null;
+ for (let i = 0; i < towers.length; i++) {
+ const tw = towers[i], d = TD.TOWERS[tw.type];
+ if (!d || d.role !== 'attack' || tw === src) continue;
+ const dx = tw.x - src.x, dy = tw.y - src.y;
+ if (dx * dx + dy * dy > r2) continue;
+ (lines || (lines = [])).push(tw);
+ }
+ if (!lines) return;
+ const u = Math.max(1, 0.55 / this.scale), lw = Math.max(2, 1.2 / this.scale); // keep the dashes and arrowheads readable when the cells are small
+ ctx.save();
+ ctx.lineCap = 'round'; ctx.lineJoin = 'round';
+ ctx.strokeStyle = rgba(def.color, 0.75); ctx.lineWidth = lw; ctx.setLineDash([6 * u, 5 * u]); ctx.lineDashOffset = -t * 16;
+ ctx.beginPath();
+ for (const tw of lines) { ctx.moveTo(bx, by); ctx.lineTo((tw.x + 0.5) * C, (tw.y + 0.5) * C); }
+ ctx.stroke();
+ ctx.setLineDash([]);
+ ctx.fillStyle = rgba(def.color, 0.95); ctx.lineWidth = lw;
+ for (const tw of lines) { // an arrowhead just outside the tile, and a frame round it
+ const tx = (tw.x + 0.5) * C, ty = (tw.y + 0.5) * C, a = Math.atan2(ty - by, tx - bx), d = C * 0.62 + 4 * u;
+ const ax = tx - Math.cos(a) * d, ay = ty - Math.sin(a) * d, ca = Math.cos(a), sa = Math.sin(a);
+ ctx.beginPath(); ctx.moveTo(ax + ca * 6 * u, ay + sa * 6 * u); ctx.lineTo(ax - ca * 3 * u - sa * 5 * u, ay - sa * 3 * u + ca * 5 * u); ctx.lineTo(ax - ca * 3 * u + sa * 5 * u, ay - sa * 3 * u - ca * 5 * u); ctx.closePath(); ctx.fill();
+ rr(ctx, tw.x * C + 1.5, tw.y * C + 1.5, C - 3, C - 3, 6); ctx.stroke();
+ }
+ ctx.restore();
+ }
+
_rangeRing(ctx, cx, cy, r, col) {
ctx.fillStyle = rgba(col, 0.07); ctx.beginPath(); ctx.arc(cx, cy, r, 0, TAU); ctx.fill();
ctx.strokeStyle = rgba(col, 0.55); ctx.lineWidth = 1.5; ctx.stroke();
@@ -559,17 +723,33 @@
_drawMonsters(ctx, view, t, dt, air, rot) {
const trk = this.trk;
+ if (!air) { // a Daemon's heal range, faint, all in one stroke
+ let any = false;
+ for (const m of view.monsters) {
+ const d = TD.ENEMIES[m.kind];
+ if (!d.healRange) continue;
+ if (!any) { any = true; ctx.beginPath(); }
+ ctx.moveTo(m.x * C + d.healRange * C, m.y * C); ctx.arc(m.x * C, m.y * C, d.healRange * C, 0, TAU);
+ }
+ if (any) { ctx.strokeStyle = rgba(TD.ENEMIES.daemon.color, 0.15); ctx.lineWidth = 1.5; ctx.stroke(); }
+ }
for (const m of view.monsters) {
if (!!m.air !== air) continue;
+ const def = TD.ENEMIES[m.kind];
let k = trk.get(m.id);
- if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0 }; trk.set(m.id, k); }
+ if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0, still: 0, sv: null }; trk.set(m.id, k); }
+ const dm = def.shield && m.maxShield === undefined ? this._shieldView(k, m, def, dt) : m; // co-op: tell hp and shield apart (see there)
+ const v = vitals(dm, def), cur = v.hp + v.sh;
const dx = m.x - k.x, dy = m.y - k.y;
if (dx * dx + dy * dy > 1e-6) k.ang = lerpAngle(k.ang, Math.atan2(dy, dx), 0.35);
+ k.still = dx * dx + dy * dy < 1e-8 ? k.still + dt : 0;
k.x = m.x; k.y = m.y;
- if (m.hp < k.hp) k.flash = 0.1;
- k.hp = m.hp; k.flash = Math.max(0, k.flash - dt);
- if (air) { const er = TD.ENEMIES[m.kind].r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
- drawMonster(ctx, m, k.ang, t, k.flash, rot);
+ if (cur < k.hp) k.flash = 0.1;
+ k.hp = cur; k.flash = Math.max(0, k.flash - dt);
+ // stunned: solo knows (stunT); in co-op the wire only says "slowed or stunned", and a slowed packet still moves, so a flagged packet that stands still is stunned
+ const stun = m.stunT !== undefined ? m.stunT > 0 : m.slow > 0 && k.still > 0.2 && !view.paused;
+ if (air && !SWARM[m.kind]) { const er = def.r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
+ drawMonster(ctx, dm, k.ang, t, k.flash, rot, stun);
}
if (air && trk.size > view.monsters.length + 60) { // drop stale trackers
const live = new Set(view.monsters.map((x) => x.id));
@@ -577,6 +757,27 @@
}
}
+ // Co-op sends a shielded enemy as hp + shield out of maxhp + maxShield. A shield soaks first, so most of the time the split is plain from the
+ // total, but once the hp is hurt and the shield has regrown the total alone is ambiguous (hp 20 + shield 120 looks like hp 90 + shield 50).
+ // So the split is followed over time: a drop in the total hits the shield first, a rise after shieldDelay seconds without a hit refills the
+ // shield, any other rise is a heal. Returns a solo-style view object (hp and shield apart) kept in the tracker entry.
+ _shieldView(k, m, def, dt) {
+ const mh = m.maxhp * def.hp / (def.hp + def.shield), ms = m.maxhp - mh;
+ let s = k.sv;
+ if (!s) s = k.sv = { id: m.id, kind: m.kind, air: m.air, x: 0, y: 0, hp: 0, maxhp: mh, shield: clamp(m.hp - mh, 0, ms), maxShield: ms, slow: 0, tot: m.hp, idle: 0 };
+ else {
+ const d = m.hp - s.tot;
+ if (d < -0.5) { s.shield -= Math.min(s.shield, -d); s.idle = 0; }
+ else if (d > 0.5 && s.idle >= def.shieldDelay - 0.25 && s.shield < ms) s.shield = Math.min(ms, s.shield + d);
+ s.tot = m.hp; s.idle += dt;
+ }
+ s.maxhp = mh; s.maxShield = ms;
+ if (m.hp - s.shield > mh) s.shield = clamp(m.hp - mh, 0, ms); // more than the hp part can hold: the rest is shield
+ s.hp = clamp(m.hp - s.shield, 0, mh);
+ s.x = m.x; s.y = m.y; s.slow = m.slow; s.air = m.air;
+ return s;
+ }
+
_drawFx(ctx, dt, sc, rot) {
// lines (tracers, arcs)
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
@@ -600,6 +801,15 @@
ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU); ctx.stroke();
}
ctx.globalAlpha = 1;
+ for (let i = this.pulses.length - 1; i >= 0; i--) {
+ const r = this.pulses[i]; r.life -= dt;
+ if (r.life <= 0) { this.pulses.splice(i, 1); continue; }
+ const k = 1 - r.life / r.max;
+ ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU);
+ if (r.fill) { ctx.globalAlpha = (1 - k) * r.fill; ctx.fillStyle = r.col; ctx.fill(); }
+ ctx.globalAlpha = 1 - k; ctx.strokeStyle = r.col; ctx.lineWidth = r.w; ctx.stroke();
+ }
+ ctx.globalAlpha = 1;
for (let i = this.parts.length - 1; i >= 0; i--) {
const p = this.parts[i]; p.life -= dt;
if (p.life <= 0) { this.parts.splice(i, 1); continue; }
@@ -651,6 +861,7 @@
NW.Renderer = Renderer;
NW.drawIcon = drawIcon;
NW.drawGlyph = drawGlyph;
+ NW.drawMonster = drawMonster;
NW.SLOT_COLORS = SLOT_COLORS;
NW.CELL = C;
NW.BOARD_MARGIN = MARGIN;
diff --git a/public/js/sim.js b/public/js/sim.js
index 2262d31..c8ba248 100644
--- a/public/js/sim.js
+++ b/public/js/sim.js
@@ -201,16 +201,21 @@
}
// ---------------------------------------------------------------- definitions
- const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink'];
+ // Every tower has a 'role' so the generic code does not have to know the types:
+ // wall solid block, does nothing attack shoots (dmg/rate, picks a target, can be rate-boosted)
+ // aura continuous effect in range control periodic pulse that stuns everything in range
+ // support no attack of its own: boosts the 'attack' towers around it
+ // Hotkeys: one unique key 1-9 per tower, in palette order.
+ const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink'];
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
const TOWERS = {
wall: {
- name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1,
+ name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1, role: 'wall',
desc: 'Blocks the route. Cheap: use it to build a long maze.',
levels: [{ cost: 5 }],
},
filter: {
- name: 'Packet Filter', key: '2', color: '#35e0a1', air: true, ground: true,
+ name: 'Packet Filter', key: '2', color: '#35e0a1', role: 'attack', air: true, ground: true,
desc: 'Fast, cheap rapid fire. Weak against armour.',
levels: [
{ cost: 25, dmg: 6, range: 3.2, rate: 3.0 },
@@ -220,7 +225,7 @@
bulletSpeed: 14,
},
ids: {
- name: 'IDS Sniper', key: '3', color: '#b78cff', air: true, ground: true,
+ name: 'IDS Sniper', key: '3', color: '#b78cff', role: 'attack', air: true, ground: true,
desc: 'Long range, hard hitting, slow. Great against armour and bosses.',
levels: [
{ cost: 60, dmg: 50, range: 6.5, rate: 0.7 },
@@ -229,7 +234,7 @@
],
},
mortar: {
- name: 'Flood Mortar', key: '4', color: '#d4f04a', air: false, ground: true,
+ name: 'Flood Mortar', key: '4', color: '#d4f04a', role: 'attack', air: false, ground: true,
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
levels: [
{ cost: 55, dmg: 28, range: 4.8, rate: 0.8, splash: 1.3 },
@@ -239,7 +244,7 @@
shellSpeed: 5.5,
},
throttle: {
- name: 'Rate Limiter', key: '5', color: '#4de3ff', air: true, ground: true,
+ name: 'Rate Limiter', key: '5', color: '#4de3ff', role: 'aura', air: true, ground: true,
desc: 'Slows everything in range. Pair it with damage dealers.',
levels: [
{ cost: 40, range: 3.2, slow: 0.35 },
@@ -248,7 +253,7 @@
],
},
arc: {
- name: 'Router Arc', key: '6', color: '#ff7ad9', air: true, ground: true,
+ name: 'Router Arc', key: '6', color: '#ff7ad9', role: 'attack', air: true, ground: true,
desc: 'Chain lightning that jumps between nearby packets.',
levels: [
{ cost: 75, dmg: 16, range: 3.6, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
@@ -256,27 +261,82 @@
{ cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
],
},
- uplink: {
- name: 'Orbital Uplink', key: '7', color: '#ffe27a', air: true, ground: true,
- desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Very expensive to build and to upgrade.',
+ sandbox: {
+ name: 'Sandbox', key: '7', color: '#ffa447', role: 'control', air: true, ground: true,
+ desc: 'Control tower, no damage. Every few seconds it traps every packet in range, ground and air, and freezes it for a moment. Bosses resist and are frozen for half as long.',
levels: [
- { cost: 450, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
- { cost: 500, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
- { cost: 800, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
- { cost: 1200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
+ { cost: 90, range: 2.6, pulse: 5.0, stun: 1.0 },
+ { cost: 80, range: 3.0, pulse: 4.5, stun: 1.3 },
+ { cost: 130, range: 3.4, pulse: 4.0, stun: 1.6 },
+ ],
+ },
+ balancer: {
+ name: 'Load Balancer', key: '8', color: '#d3e0ee', role: 'support',
+ desc: 'Support tower, no attack. Makes every turret in range fire faster. Several balancers do not stack (the best one counts) and a balancer does not boost another balancer.',
+ levels: [
+ { cost: 70, range: 2.2, boost: 0.15 },
+ { cost: 70, range: 2.6, boost: 0.25 },
+ { cost: 110, range: 3.0, boost: 0.35 },
+ ],
+ },
+ uplink: {
+ name: 'Orbital Uplink', key: '9', color: '#ffe27a', role: 'attack', air: true, ground: true,
+ desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Extremely expensive to build and to upgrade, and every Uplink you already own makes the next one 25% dearer, and its upgrades too.',
+ priceGrowth: 1.25, // the Nth Uplink costs cost * 1.25^(N-1) to buy AND to upgrade (see priceMult), so kill rewards cannot buy a carpet of them
+ levels: [
+ { cost: 1500, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
+ { cost: 1200, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
+ { cost: 2000, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
+ { cost: 3200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
],
},
};
- const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit'];
+ // ENEMY_ORDER is part of the wire format (snapshots carry the index): only ever APPEND kinds.
+ // buyCost is the price of one unit in the future versus mode (about 3x the kill reward).
+ // What building one more `type` costs right now, given the towers already on the board (an array, or a plain count).
+ // Most towers have a fixed price; a tower with `priceGrowth` gets dearer for every one already owned. Shared by the Sim and
+ // the UI so the price shown is always the price charged.
+ // The price multiplier a NEW tower of this type is bought at, given how many are already owned. Each tower remembers the multiplier it was
+ // bought at (tower.pm) and its upgrades cost the same multiple, so the Nth Uplink is dearer to buy and to upgrade by the same factor.
+ function priceMult(type, owned) {
+ const def = TOWERS[type];
+ if (!def || !def.priceGrowth) return 1;
+ let n = 0;
+ if (Array.isArray(owned)) { for (const t of owned) if (t.type === type) n++; } else n = owned | 0;
+ return Math.pow(def.priceGrowth, n);
+ }
+ const roundPrice = (v) => Math.round(v / 10) * 10;
+ function priceFor(type, owned) {
+ const def = TOWERS[type];
+ if (!def) return 0;
+ const base = def.levels[0].cost, m = priceMult(type, owned);
+ return m === 1 ? base : roundPrice(base * m);
+ }
+ // What upgrading a tower of `type` that is at `level` (1-based) to the next level costs, given the multiplier it was bought at (pm, default 1).
+ function upgradePrice(type, level, pm) {
+ const def = TOWERS[type], lv = def && def.levels[level];
+ if (!lv) return null;
+ return !pm || pm === 1 ? lv.cost : roundPrice(lv.cost * pm);
+ }
+
+ const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit', 'daemon', 'proxy', 'botnet'];
const ENEMIES = {
- ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a' },
- worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43' },
- trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b' },
- spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166' },
- ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff' },
- rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', slowRes: 0.5 },
+ ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a', buyCost: 10 },
+ worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43', buyCost: 6 },
+ trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b', buyCost: 30 },
+ spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166', buyCost: 3 },
+ ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff', buyCost: 15 },
+ rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', buyCost: 300, slowRes: 0.5 },
+ // Healer: every HEAL_EVERY s it restores 'heal' of the max hp of every other enemy within healRange (several daemons stack up to HEAL_CAP).
+ daemon: { name: 'Daemon', hp: 70, speed: 1.1, armor: 0, reward: 8, leak: 1, air: false, r: 0.3, color: '#7ee08a', buyCost: 25, heal: 0.06, healRange: 2.2 },
+ // Shielded: 'shield' extra hit points (scaled like hp) that soak damage first and regrow shieldRegen/s of their max after shieldDelay s unhurt.
+ proxy: { name: 'Proxy', hp: 90, speed: 1.0, armor: 1, reward: 10, leak: 1, air: false, r: 0.34, color: '#7aa2ff', buyCost: 30, shield: 120, shieldRegen: 0.1, shieldDelay: 3 },
+ // Swarm flyer.
+ botnet: { name: 'Botnet', hp: 12, speed: 2.6, armor: 0, reward: 1, leak: 1, air: true, r: 0.14, color: '#4dd0c8', buyCost: 3 },
};
+ const HEAL_EVERY = 1; // seconds between daemon pulses (one global clock, so the 12%/s cap is exact)
+ const HEAL_CAP = 0.12; // most max-hp fraction one enemy can be healed per pulse, however many daemons are near
// Wave n (1-based). The first eight waves introduce each unit type; later ones loop with bigger numbers.
function waveGroups(n) {
@@ -293,12 +353,42 @@
case 6: g = [{ k: 'ghost', c: c(8), gap: 0.6 }, { k: 'spam', c: c(16), gap: 0.2 }]; break;
default: g = [{ k: 'ping', c: c(10), gap: 0.4 }, { k: 'trojan', c: c(3), gap: 1.0 }, { k: 'ghost', c: c(4), gap: 0.8 }];
}
+ if (n > 8) weave(g, n, c, (n - 1) % 8);
if (n % 10 === 0) g.push({ k: 'rootkit', c: n / 10, gap: 3 });
return g;
}
+ // From wave 9 the eight-wave cycle gets the newer kinds woven in (groups spawn one after the other, so a group
+ // appended behind another trails it):
+ // daemon the first healer rides with the pings of wave 9; from then on every trojan group has an escort that
+ // spawns behind it and (it is faster) catches up and heals while passing through
+ // proxy from wave 12 in the spam / mixed-flyer-and-trojan slots, more slots later
+ // botnet swarms from wave 14, more slots (and bigger) later
+ function weave(g, n, c, p) {
+ const trojans = g.find((e) => e.k === 'trojan');
+ if (trojans) g.push({ k: 'daemon', c: Math.max(1, Math.round(trojans.c / 2)), gap: 1.2 });
+ else if (n === 9) g.push({ k: 'daemon', c: 2, gap: 1.2 });
+ if (n >= 12) {
+ if (p === 3) g.push({ k: 'proxy', c: c(2), gap: 1.6 });
+ else if (p === 7) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
+ else if (p === 5 && n >= 22) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
+ else if (p === 2 && n >= 19) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
+ else if (p === 0 && n >= 25) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
+ }
+ if (n >= 14) {
+ if (p === 5) g.push({ k: 'botnet', c: c(8), gap: 0.12 });
+ else if (p === 6) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
+ else if (p === 1 && n >= 18) g.push({ k: 'botnet', c: c(6), gap: 0.1 });
+ else if (p === 4 && n >= 21) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
+ else if (p === 7 && n >= 24) g.push({ k: 'botnet', c: c(6), gap: 0.12 });
+ }
+ }
+ // What the wave list in the UI shows: one entry per kind (counts summed), in order of appearance, flyers flagged.
function waveSummary(n) {
- const out = [];
- for (const g of waveGroups(n)) out.push({ k: g.k, c: g.c });
+ const out = [], at = {};
+ for (const g of waveGroups(n)) {
+ if (at[g.k] === undefined) { at[g.k] = out.length; out.push({ k: g.k, c: 0, air: !!ENEMIES[g.k].air }); }
+ out[at[g.k]].c += g.c;
+ }
return out;
}
function hpScale(n) { return 1 + 0.16 * (n - 1) + 0.022 * (n - 1) * (n - 1); }
@@ -487,6 +577,7 @@
this.autoWaves = false;
this.nextWaveIn = -1;
this.spawnRR = 0;
+ this.healT = 0; // seconds since the last daemon pulse (one clock for all daemons)
this.towers = [];
this.towerAt = new Array(this.board.cols * this.board.rows).fill(null);
@@ -509,9 +600,9 @@
switch (c.c) {
case 'place': return this.place(c.type, c.x, c.y, c.by | 0);
case 'sell': return this.sell(c.id);
- case 'upgrade': return this.upgrade(c.id);
+ case 'upgrade': return this.upgrade(c.id, c.lv);
case 'target': return this.setTargetMode(c.id, c.mode);
- case 'wave': return this.startWave();
+ case 'wave': return this.startWave(c.n);
case 'auto': return this.setAuto(!!c.v);
case 'continue': return this.continueEndless();
default: return { ok: false, reason: 'bad_cmd' };
@@ -548,13 +639,13 @@
if (this.state !== 'playing') return { ok: false, reason: 'over' };
if (typeof type !== 'string' || !Object.prototype.hasOwnProperty.call(TOWERS, type)) return { ok: false, reason: 'bad_type' };
const def = TOWERS[type];
- const cost = def.levels[0].cost;
+ const cost = priceFor(type, this.towers), pm = priceMult(type, this.towers);
if (this.gold < cost) return { ok: false, reason: 'gold' };
const t = this.preview(x, y, false);
if (!t.ok) return { ok: false, reason: t.reason };
const tower = {
- id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0,
- cd: 0, tgt: 0, kills: 0, dealt: 0,
+ id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0, pm,
+ cd: 0, tgt: 0, kills: 0, dealt: 0, buff: 0,
};
this.gold -= cost;
this.towers.push(tower);
@@ -587,14 +678,14 @@
return { ok: true, refund };
}
- upgradeCost(t) {
- const lv = TOWERS[t.type].levels[t.level];
- return lv ? lv.cost : null;
- }
- upgrade(id) {
+ upgradeCost(t) { return upgradePrice(t.type, t.level, t.pm); }
+ // `lv` is the level the sender SAW when it pressed Upgrade (absent: no check). Two players pressing it at the same moment send the
+ // same command twice; the second one finds the tower already a level higher and is refused as 'stale' instead of being charged again.
+ upgrade(id, lv) {
if (this.state !== 'playing') return { ok: false, reason: 'over' };
const t = this.towerById(id);
if (!t) return { ok: false, reason: 'no_tower' };
+ if (lv !== undefined && lv !== null && lv !== t.level) return { ok: false, reason: 'stale' };
const cost = this.upgradeCost(t);
if (cost === null) return { ok: false, reason: 'max' };
if (this.gold < cost) return { ok: false, reason: 'gold' };
@@ -628,8 +719,11 @@
return { ok: true };
}
- startWave() {
+ // `expect` is the wave number the sender expects this command to start (the wave it saw + 1; absent: no check; the auto-wave timer
+ // never passes one). A second "Next wave" pressed at the same moment by the other player is refused as 'stale', not started twice.
+ startWave(expect) {
if (this.state !== 'playing') return { ok: false, reason: 'over' };
+ if (expect !== undefined && expect !== null && expect !== this.wave + 1) return { ok: false, reason: 'stale' };
const n = ++this.wave;
let t = this.time + 0.3;
for (const g of waveGroups(n)) {
@@ -647,12 +741,15 @@
const b = this.board;
const s = b.spawns[this.spawnRR++ % b.spawns.length];
const hp = Math.round(def.hp * hpScale(q.wave));
+ const shield = def.shield ? Math.round(def.shield * hpScale(q.wave)) : 0;
const m = {
id: this.nid++, kind: q.k, air: !!def.air,
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
hp, maxhp: hp, armor: def.armor, speed: def.speed,
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave))),
- leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, rem: 0, dead: false, wave: q.wave,
+ leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
+ shield, maxShield: shield, shieldT: 0,
+ rem: 0, dead: false, wave: q.wave,
};
m.rem = m.air
? Math.hypot(b.core.x - s.x, b.core.y - s.y)
@@ -672,7 +769,12 @@
for (const m of this.monsters) { // slow = lingering slow (Orbital Uplink) unless a Rate Limiter says more
if (m.slowT > 0) { m.slow = m.slowAmt; m.slowT -= dt; } else m.slow = 0;
+ if (m.stunT > 0) m.stunT -= dt;
+ if (m.maxShield > 0) this.regenShield(m, dt);
}
+ this.healT += dt;
+ if (this.healT >= HEAL_EVERY) { this.healT -= HEAL_EVERY; this.healPulse(); }
+ this.updateAuras();
for (const t of this.towers) this.updateTower(t, dt);
this.updateBullets(dt);
for (const m of this.monsters) if (!m.dead) this.moveMonster(m, dt);
@@ -704,6 +806,7 @@
// ---- monsters -------------------------------------------------------------------------
moveMonster(m, dt) {
+ if (m.stunT > 0) return; // stunned (Sandbox): frozen in place
const b = this.board;
const slowMul = 1 - Math.min(0.6, m.slow);
let remaining = m.speed * slowMul * dt;
@@ -747,8 +850,13 @@
damage(m, raw, src, ignoreArmor) {
if (m.dead) return;
- const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25);
- m.hp -= d;
+ const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25); // armour applies once, to the damage dealt
+ let hit = d;
+ if (m.maxShield > 0) { // a shield soaks first, any damage restarts its regrow timer
+ const soak = Math.min(m.shield, d);
+ m.shield -= soak; hit = d - soak; m.shieldT = 0;
+ }
+ m.hp -= hit;
if (src) src.dealt += d;
if (m.hp <= 0) {
m.dead = true;
@@ -759,6 +867,51 @@
}
}
+ // Shield: after shieldDelay s without damage it regrows shieldRegen of its maximum per second.
+ regenShield(m, dt) {
+ const def = ENEMIES[m.kind];
+ m.shieldT += dt;
+ const over = Math.min(dt, m.shieldT - def.shieldDelay);
+ if (over > 0 && m.shield < m.maxShield) m.shield = Math.min(m.maxShield, m.shield + m.maxShield * def.shieldRegen * over);
+ }
+
+ // Daemon pulse, once a second on the sim's own clock: every enemy gets healed by the daemons around it (never by itself),
+ // together at most HEAL_CAP of its max hp, never above max. Shields are not healed.
+ healPulse() {
+ let ds = null;
+ for (const m of this.monsters) if (!m.dead && ENEMIES[m.kind].heal) (ds || (ds = [])).push(m);
+ if (!ds) return;
+ const did = new Set();
+ for (const m of this.monsters) {
+ if (m.dead || m.hp >= m.maxhp) continue;
+ let f = 0;
+ for (const d of ds) {
+ if (d === m) continue;
+ const def = ENEMIES[d.kind], dx = m.x - d.x, dy = m.y - d.y;
+ if (dx * dx + dy * dy > def.healRange * def.healRange) continue;
+ f += def.heal; did.add(d);
+ }
+ if (f > 0) m.hp = Math.min(m.maxhp, m.hp + Math.min(f, HEAL_CAP) * m.maxhp);
+ }
+ for (const d of did) this.emit({ e: 'heal', x: round2(d.x), y: round2(d.y), r: ENEMIES[d.kind].healRange });
+ }
+
+ // Load Balancer: each attack tower gets the best boost of the support towers in range (no stacking).
+ updateAuras() {
+ const ts = this.towers;
+ let sup = null;
+ for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support') (sup || (sup = [])).push(t); }
+ if (!sup) return;
+ for (const s of sup) {
+ const st = TOWERS[s.type].levels[s.level - 1], r2 = st.range * st.range;
+ for (const t of ts) {
+ if (t.buff >= st.boost || TOWERS[t.type].role !== 'attack') continue;
+ const dx = t.x - s.x, dy = t.y - s.y;
+ if (dx * dx + dy * dy <= r2) t.buff = st.boost;
+ }
+ }
+ }
+
// ---- towers ---------------------------------------------------------------------------
findTarget(t, range, def) {
const tx = t.x + 0.5, ty = t.y + 0.5, r2 = range * range;
@@ -771,7 +924,7 @@
let v;
switch (t.mode) {
case 'last': v = m.rem; break;
- case 'strong': v = m.hp; break;
+ case 'strong': v = m.hp + (m.shield || 0); break;
case 'close': v = -d2; break;
default: v = -m.rem; // 'first': smallest remaining distance wins
}
@@ -781,11 +934,12 @@
}
updateTower(t, dt) {
- if (t.type === 'wall') return;
const def = TOWERS[t.type];
+ if (def.role === 'wall' || def.role === 'support') return;
const st = def.levels[t.level - 1];
const cx = t.x + 0.5, cy = t.y + 0.5;
- if (t.type === 'throttle') {
+ if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt); return; }
+ if (def.role === 'aura') {
const r2 = st.range * st.range;
for (const m of this.monsters) {
if (m.dead) continue;
@@ -796,7 +950,7 @@
}
return;
}
- t.cd -= dt;
+ t.cd -= dt * (1 + (t.buff || 0)); // a Load Balancer makes cooldowns elapse faster
const m = this.findTarget(t, st.range, def);
t.tgt = m ? m.id : 0;
if (!m) { if (t.cd < 0) t.cd = 0; return; }
@@ -805,6 +959,27 @@
this.fire(t, st, def, m, cx, cy);
}
+ // Sandbox: when anything is in range it stuns everything in range (ground and air) for st.stun s, then recharges st.pulse s.
+ // Enemies with slowRes (bosses) are stunned for (1 - slowRes) of that. Stunned enemies do not move.
+ pulseStun(t, st, def, cx, cy, dt) {
+ t.cd -= dt;
+ t.tgt = 0;
+ const r2 = st.range * st.range, hit = [];
+ for (const m of this.monsters) {
+ if (m.dead || (m.air ? !def.air : !def.ground)) continue;
+ const dx = m.x - cx, dy = m.y - cy;
+ if (dx * dx + dy * dy <= r2) hit.push(m);
+ }
+ if (!hit.length) { if (t.cd < 0) t.cd = 0; return; }
+ if (t.cd > 0) return;
+ t.cd += st.pulse;
+ for (const m of hit) {
+ const dur = st.stun * (1 - (ENEMIES[m.kind].slowRes || 0));
+ if (dur > m.stunT) m.stunT = dur;
+ }
+ this.emit({ e: 'stun', x: round2(cx), y: round2(cy), r: st.range, n: hit.length });
+ }
+
fire(t, st, def, m, cx, cy) {
switch (t.type) {
case 'filter':
@@ -819,7 +994,7 @@
let gx = m.x, gy = m.y;
if (m.tx >= 0) { // lead the target along its current step
const ex = m.tx + 0.5 - m.x, ey = m.ty + 0.5 - m.y, el = Math.hypot(ex, ey) || 1;
- const T = Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed;
+ const T = Math.max(0, Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed - (m.stunT > 0 ? m.stunT : 0));
const lead = Math.min(el, m.speed * (1 - Math.min(0.6, m.slow)) * T);
gx += (ex / el) * lead; gy += (ey / el) * lead;
}
@@ -910,7 +1085,7 @@
// ---- views of the state ---------------------------------------------------------------
towerList() {
- return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner]);
+ return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner, t.pm === 1 ? 1 : round2(t.pm * 1000) / 1000]);
}
// Everything a client needs to (re)build the board from scratch.
@@ -924,7 +1099,8 @@
// Compact per-tick state for the wire. Arrays, not objects, to keep it small.
snapshot() {
- const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp), m.maxhp, m.slow > 0 ? 1 : 0]);
+ // a shield is sent as extra hp: hp + shield out of maxhp + maxShield (the client derives the shield part from the kind's table)
+ const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp + (m.shield || 0)), m.maxhp + (m.maxShield || 0), m.slow > 0 || m.stunT > 0 ? 1 : 0]);
const bu = this.bullets.map((b) => [b.id, b.k === 'mortar' ? 1 : 0, round2(b.x), round2(b.y)]);
const tt = [];
for (const t of this.towers) if (t.type !== 'wall') tt.push([t.id, t.tgt, t.kills]);
@@ -940,9 +1116,9 @@
function round2(v) { return Math.round(v * 100) / 100; }
return {
- STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE,
+ STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP,
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
- waveGroups, waveSummary, hpScale, rewardScale,
+ priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale,
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
};
});
diff --git a/server/room.js b/server/room.js
index 9d0fba8..9abfc91 100644
--- a/server/room.js
+++ b/server/room.js
@@ -205,8 +205,11 @@ class Room {
this.reject(p, c, 'busy', msg);
return true;
}
+ // `lv` (upgrade: the level the sender saw) and `n` (wave: the wave number it expects to start) make a command idempotent: the sim
+ // answers 'stale' when the premise no longer holds. Optional, but when present they must be integers.
+ for (const k of ['lv', 'n']) if (msg[k] !== undefined && msg[k] !== null && !Number.isInteger(msg[k])) return false;
// Whitelisted fields only; `by` always comes from the socket's slot, never from the client.
- const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, by: p.slot };
+ const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, lv: msg.lv, n: msg.n, by: p.slot };
let r;
try { r = sim.cmd(cmd); } catch (e) { this.log('sim.cmd threw: ' + (e && e.stack || e)); r = { ok: false, reason: 'error' }; }
if (!r || !r.ok) this.reject(p, c, (r && r.reason) || 'error', msg);
diff --git a/test/controllers.test.js b/test/controllers.test.js
new file mode 100644
index 0000000..85b4f59
--- /dev/null
+++ b/test/controllers.test.js
@@ -0,0 +1,251 @@
+'use strict';
+/*
+ * RemoteController / LocalController without a browser: public/js/controllers.js runs in a vm context with a fake WebSocket, a fake
+ * document/window and a manual clock (timers and performance.now() advance only when the test says so).
+ */
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+const vm = require('node:vm');
+const TD = require('../public/js/sim.js');
+
+const SRC = fs.readFileSync(path.join(__dirname, '..', 'public', 'js', 'controllers.js'), 'utf8');
+
+function harness() {
+ const H = { now: 1000, timers: [], seq: 0, sockets: [], docAdded: 0, docRemoved: 0, winAdded: 0, winRemoved: 0 };
+ const timer = (fn, ms, repeat) => { const t = { id: ++H.seq, at: H.now + ms, fn, ms, repeat }; H.timers.push(t); return t.id; };
+ class FakeWS {
+ constructor(url) { this.url = url; this.readyState = 0; this.sent = []; this.closeCalls = 0; H.sockets.push(this); }
+ send(s) { this.sent.push(JSON.parse(s)); }
+ close() { this.closeCalls++; this.readyState = 2; } // a half-open socket: no close event follows
+ open() { this.readyState = 1; if (this.onopen) this.onopen(); }
+ recv(o) { if (this.onmessage) this.onmessage({ data: JSON.stringify(o) }); }
+ serverClose(code) { this.readyState = 3; if (this.onclose) this.onclose({ code }); }
+ }
+ const sandbox = {
+ TD, console, URL, FakeWS,
+ WebSocket: FakeWS,
+ document: { hidden: false, addEventListener() { H.docAdded++; }, removeEventListener() { H.docRemoved++; } },
+ performance: { now: () => H.now },
+ location: { href: 'http://localhost/index.html' },
+ addEventListener() { H.winAdded++; }, removeEventListener() { H.winRemoved++; },
+ setTimeout: (fn, ms) => timer(fn, ms, false), clearTimeout: (id) => { H.timers = H.timers.filter((t) => t.id !== id); },
+ setInterval: (fn, ms) => timer(fn, ms, true), clearInterval: (id) => { H.timers = H.timers.filter((t) => t.id !== id); },
+ };
+ sandbox.self = sandbox;
+ vm.runInNewContext(SRC, sandbox, { filename: 'controllers.js' });
+ H.NW = sandbox.NW;
+ H.advance = (ms) => { // runs the timers that fall due, in order, moving the clock along
+ const end = H.now + ms;
+ for (;;) {
+ const due = H.timers.filter((t) => t.at <= end).sort((a, b) => a.at - b.at || a.id - b.id)[0];
+ if (!due) break;
+ H.now = Math.max(H.now, due.at);
+ if (due.repeat) due.at += due.ms; else H.timers = H.timers.filter((t) => t !== due);
+ due.fn();
+ }
+ H.now = end;
+ };
+ return H;
+}
+
+// What the server would send for a sim in its current state.
+function joinedMsg(sim, extra) {
+ return Object.assign({
+ t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 1, host: false },
+ players: [{ pid: 'pidpidpid1', slot: 1, name: 'Bob', host: false, online: true }, { pid: 'aliasaliasalias', slot: 0, name: 'Alice', host: true, online: true }],
+ state: sim.fullState(), snap: sim.snapshot(), speed: 1, paused: false,
+ }, extra);
+}
+let seq = 0;
+function snapMsg(sim, tw) {
+ const m = Object.assign({ t: 'snap', seq: ++seq }, sim.snapshot(), { ev: [], cur: [], pa: 0, sp: 1 });
+ if (tw) m.tw = sim.towerList();
+ return m;
+}
+function connected(opts) {
+ const H = harness();
+ const sim = new TD.Sim({ map: 'open' });
+ const rc = new H.NW.RemoteController(Object.assign({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' }, opts));
+ rc.connect();
+ const ws = H.sockets[0];
+ ws.open();
+ ws.recv(joinedMsg(sim));
+ return { H, sim, rc, ws };
+}
+
+test('coop-1: a burst of snapshots larger than the buffer does not lose the partner\'s tower change', () => {
+ const { H, sim, rc, ws } = connected();
+ assert.equal(rc.status, 'joined');
+ ws.recv(snapMsg(sim)); // quiet snapshots, then the partner builds...
+ sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 });
+ ws.recv(snapMsg(sim, true)); // ...this one carries the tower list (sent exactly once)
+ for (let i = 0; i < 14; i++) ws.recv(snapMsg(sim)); // the page was stalled: 14 more arrive before it renders again
+ assert.ok(rc.buf.length <= 10, 'the buffer is still bounded');
+ H.advance(500);
+ rc.update(H.now);
+ assert.equal(rc.towers.length, 1, 'the tower is there');
+ assert.equal(rc.view.towers.length, 1);
+ assert.equal(rc.rev, sim.rev, 'and so is the revision');
+ assert.ok(rc.board.solid[5 * rc.board.cols + 12], 'the mirror board knows the new wall (route previews are right)');
+ assert.equal(ws.sent.filter((m) => m.t === 'sync').length, 0, 'no resync was needed');
+});
+
+test('coop-1: the NEWEST of several dropped tower lists wins; an older one is never applied over it', () => {
+ const { H, sim, rc, ws } = connected();
+ sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 });
+ ws.recv(snapMsg(sim, true));
+ sim.cmd({ c: 'place', type: 'wall', x: 12, y: 6, by: 1 });
+ ws.recv(snapMsg(sim, true));
+ sim.cmd({ c: 'sell', id: 1 });
+ ws.recv(snapMsg(sim, true)); // list 3: wall 2 only
+ for (let i = 0; i < 20; i++) ws.recv(snapMsg(sim));
+ H.advance(500);
+ rc.update(H.now);
+ assert.deepEqual([...rc.towers.map((t) => t.id)], [2]);
+ assert.equal(rc.rev, sim.rev);
+});
+
+test('coop-1: a tower list that never arrives is noticed (revision mismatch) and the full state is requested', () => {
+ const { H, sim, rc, ws } = connected();
+ sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 });
+ ws.recv(snapMsg(sim, true));
+ rc.buf.length = 0; ws.recv(snapMsg(sim)); // (simulate the list being lost on the way)
+ H.advance(500);
+ rc.update(H.now);
+ assert.equal(ws.sent.filter((m) => m.t === 'sync').length, 1);
+});
+
+test('coop-2: a joined socket that goes silent is abandoned after 5 s: reconnecting at once and a fresh socket, without waiting for a close', () => {
+ const { H, rc, ws } = connected();
+ const states = [];
+ rc.on('status', (s) => states.push(s));
+ H.advance(4000);
+ assert.equal(rc.status, 'joined', 'still fine after 4 s of silence');
+ assert.equal(H.sockets.length, 1);
+ H.advance(2500);
+ assert.equal(rc.status, 'reconnecting', 'the watchdog shows it immediately');
+ assert.equal(H.sockets.length, 2, 'a new socket was opened without waiting for the dead one to close');
+ assert.equal(ws.closeCalls, 1, 'the dead one was closed');
+ assert.equal(ws.onclose, null, 'its handlers are detached: a late close / the server\'s 4001 cannot be mistaken for the new connection');
+ assert.deepEqual(states, ['reconnecting']);
+ const ws2 = H.sockets[1];
+ ws2.open();
+ assert.equal(ws2.sent[0].t, 'join'); assert.equal(ws2.sent[0].room, 'ABCD'); assert.equal(ws2.sent[0].pid, 'pidpidpid1');
+ ws2.recv(joinedMsg(new TD.Sim({ map: 'open' }), { resumed: true }));
+ assert.equal(rc.status, 'joined');
+ ws.serverClose(1006); // the old socket finally dies: nothing changes
+ assert.equal(rc.status, 'joined');
+ assert.equal(H.sockets.length, 2);
+});
+
+test('coop-2: waking up after a stall abandons a socket that has been silent for 2.5 s', () => {
+ const { H, rc } = connected();
+ H.now += 3000; // the page was frozen; timers have not run
+ rc._wake();
+ assert.equal(rc.status, 'reconnecting');
+ assert.equal(H.sockets.length, 2);
+});
+
+test('coop-2: a connection attempt that hangs is abandoned after 10 s and retried', () => {
+ const { H, rc } = connected();
+ H.advance(6000); // watchdog: socket 2 is opened and then hangs (never opens)
+ assert.equal(H.sockets.length, 2);
+ H.advance(10100);
+ assert.equal(rc.status, 'reconnecting');
+ assert.equal(H.sockets[1].closeCalls, 1, 'the attempt that went nowhere was dropped');
+ H.advance(500);
+ assert.equal(H.sockets.length, 3, 'and another attempt was made');
+});
+
+test('coop-6: "no such room" after a reconnect says the server restarted; on a resume it says the game is gone; a plain join says so', () => {
+ const a = connected();
+ const fatal = []; a.rc.on('fatal', (f) => fatal.push(f));
+ a.ws.serverClose(1006); // the server went away...
+ a.H.advance(500);
+ const ws2 = a.H.sockets[1]; ws2.open();
+ ws2.recv({ t: 'error', code: 'no_room', msg: 'no such room' }); // ...and came back without the room
+ assert.equal(fatal.length, 1);
+ assert.equal(fatal[0].code, 'restarted');
+ assert.match(fatal[0].msg, /server restarted, your game was lost/);
+
+ const H = harness();
+ const resume = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ZZZZ', url: 'ws://x/ws', resume: true });
+ const f2 = []; resume.on('fatal', (f) => f2.push(f));
+ resume.connect(); H.sockets[0].open(); H.sockets[0].recv({ t: 'error', code: 'no_room', msg: 'no such room' });
+ assert.equal(f2[0].code, 'restarted'); assert.match(f2[0].msg, /gone/);
+
+ const plain = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ZZZZ', url: 'ws://x/ws' });
+ const f3 = []; plain.on('fatal', (f) => f3.push(f));
+ plain.connect(); H.sockets[1].open(); H.sockets[1].recv({ t: 'error', code: 'no_room', msg: 'no such room' });
+ assert.equal(f3[0].code, 'no_room'); assert.match(f3[0].msg, /does not exist/);
+});
+
+test('code-19: listeners are removed when the controller dies and when it is closed', () => {
+ const { H, rc, ws } = connected();
+ assert.equal(H.docAdded, 1); assert.equal(H.winAdded, 1);
+ ws.recv({ t: 'error', code: 'full', msg: 'x' }); // fatal
+ assert.equal(H.docRemoved, 1); assert.equal(H.winRemoved, 1);
+ const c2 = new H.NW.RemoteController({ pid: 'pidpidpid2', name: 'x', room: 'ABCD', url: 'ws://x/ws' });
+ c2.close();
+ assert.equal(H.docRemoved, 2); assert.equal(H.winRemoved, 2);
+ c2.close(); // idempotent
+ assert.equal(H.docRemoved, 2);
+ assert.equal(rc.status, 'closed');
+});
+
+test('code-3: a controller that was closed while connecting never emits again (a late "joined" cannot take over a game)', () => {
+ const H = harness();
+ const rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: null, map: 'open', url: 'ws://x/ws' });
+ const events = [];
+ for (const e of ['joined', 'players', 'status', 'fatal', 'events']) rc.on(e, () => events.push(e));
+ rc.connect();
+ const ws = H.sockets[0];
+ ws.open();
+ assert.equal(ws.sent[0].t, 'join');
+ rc.close(); // (the user pressed Back / Play solo)
+ assert.deepEqual(ws.sent.map((m) => m.t), ['join', 'leave'], 'the room that is being created is left again at once');
+ events.length = 0;
+ ws.recv(joinedMsg(new TD.Sim({ map: 'open' }))); // the server's answer arrives anyway
+ rc._onMsg(JSON.stringify(joinedMsg(new TD.Sim({ map: 'open' })))); // (even if the browser still delivered a frame already queued)
+ ws.serverClose(1000);
+ assert.deepEqual(events, []);
+ assert.equal(rc.status, 'closed');
+});
+
+test('coop-5: Upgrade carries the level that is on screen, Next wave the wave it expects to start; explicit values are kept', () => {
+ const { sim, rc, ws, H } = connected();
+ sim.gold = 5000;
+ sim.cmd({ c: 'place', type: 'filter', x: 10, y: 8, by: 0 });
+ sim.cmd({ c: 'upgrade', id: 1 });
+ ws.recv(snapMsg(sim, true));
+ H.advance(500); rc.update(H.now);
+ assert.equal(rc.view.towers[0].level, 2);
+ rc.send({ c: 'upgrade', id: 1 });
+ rc.send({ c: 'wave' });
+ rc.send({ c: 'upgrade', id: 1, lv: 7 });
+ rc.send({ c: 'place', type: 'wall', x: 3, y: 3 });
+ rc.send({ c: 'upgrade', id: 99 }); // a tower this client does not know: no level to carry
+ const cmds = ws.sent.filter((m) => m.t === 'cmd');
+ assert.deepEqual(cmds[0], { t: 'cmd', c: 'upgrade', id: 1, lv: 2 });
+ assert.deepEqual(cmds[1], { t: 'cmd', c: 'wave', n: rc.view.wave + 1 });
+ assert.equal(cmds[2].lv, 7);
+ assert.equal(cmds[3].lv, undefined); assert.equal(cmds[3].n, undefined);
+ assert.equal(cmds[4].lv, undefined);
+});
+
+test('coop-5: solo too: a second "Next wave" in the same frame (a double tap) is stale, the next frame\'s is not', () => {
+ const H = harness();
+ const lc = new H.NW.LocalController({ map: 'open' });
+ const rejects = [];
+ lc.on('reject', (r) => rejects.push(r));
+ lc.update(1000);
+ assert.equal(lc.send({ c: 'wave' }).ok, true);
+ assert.equal(lc.send({ c: 'wave' }).reason, 'stale');
+ assert.equal(lc.sim.wave, 1);
+ assert.deepEqual(rejects.map((r) => r.reason), ['stale']);
+ lc.update(1016);
+ assert.equal(lc.send({ c: 'wave' }).ok, true);
+ assert.equal(lc.sim.wave, 2);
+});
diff --git a/test/server.test.js b/test/server.test.js
index 2ff6d26..ed46003 100644
--- a/test/server.test.js
+++ b/test/server.test.js
@@ -460,6 +460,67 @@ test('upgrade / target / sell / auto / continue go through the same path', async
});
});
+test('simultaneous Upgrade from both players: applied once, the second is rejected as stale (sender only), charged once (coop-5)', async () => {
+ await withServer({}, async (S) => {
+ const { a, b, room } = await S.pair();
+ const sim = S.srv.rooms.get(room).sim;
+ a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 });
+ await a.c.snap((m) => m.tw && m.tw.length === 1);
+ await b.c.snap((m) => m.tw && m.tw.length === 1);
+ const gold = sim.gold, cost = TD.TOWERS.filter.levels[1].cost;
+ // both saw level 1 and pressed Upgrade at the same moment
+ a.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 1 });
+ b.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 1 });
+ await a.c.barrier(); await b.c.barrier();
+ assert.equal(sim.towers[0].level, 2, 'level 2, not 3');
+ assert.equal(sim.gold, gold - cost, 'charged once');
+ const rejects = [...a.c.of('reject'), ...b.c.of('reject')];
+ assert.equal(rejects.length, 1, 'exactly one of them was refused');
+ assert.deepEqual(rejects[0], { t: 'reject', c: 'upgrade', reason: 'stale', id: 1 });
+ // a client that saw level 2 may continue; a command without lv is still applied (older clients)
+ a.c.send({ t: 'cmd', c: 'upgrade', id: 1, lv: 2 });
+ await a.c.snap((m) => m.tw && m.tw[0][4] === 3);
+ sim.gold = 1000;
+ a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 6, y: 4 });
+ await a.c.snap((m) => m.tw && m.tw.length === 2);
+ a.c.send({ t: 'cmd', c: 'upgrade', id: 2 });
+ await a.c.snap((m) => m.tw && m.tw[1][4] === 2);
+ });
+});
+
+test('simultaneous Next wave from both players starts one wave; the other is stale (coop-5)', async () => {
+ await withServer({}, async (S) => {
+ const { a, b, room } = await S.pair();
+ const sim = S.srv.rooms.get(room).sim;
+ a.c.send({ t: 'cmd', c: 'wave', n: 1 });
+ b.c.send({ t: 'cmd', c: 'wave', n: 1 });
+ await a.c.barrier(); await b.c.barrier();
+ assert.equal(sim.wave, 1, 'one wave, not two');
+ const rejects = [...a.c.of('reject'), ...b.c.of('reject')];
+ assert.equal(rejects.length, 1);
+ assert.deepEqual(rejects[0], { t: 'reject', c: 'wave', reason: 'stale' });
+ b.c.send({ t: 'cmd', c: 'wave', n: 2 });
+ await b.c.snap((m) => m.w === 2);
+ a.c.send({ t: 'cmd', c: 'wave' }); // no number: always the next wave
+ await a.c.snap((m) => m.w === 3);
+ });
+});
+
+test('"lv" and "n" must be integers when present: anything else is a malformed command, never "stale"', async () => {
+ await withServer({}, async (S) => {
+ const { a, room } = await S.pair();
+ const sim = S.srv.rooms.get(room).sim;
+ a.c.send({ t: 'cmd', c: 'place', type: 'filter', x: 4, y: 4 });
+ await a.c.snap((m) => m.tw && m.tw.length === 1);
+ for (const bad of [{ c: 'upgrade', id: 1, lv: '1' }, { c: 'upgrade', id: 1, lv: 1.5 }, { c: 'wave', n: 'x' }, { c: 'wave', n: {} }]) a.c.send(Object.assign({ t: 'cmd' }, bad));
+ await a.c.barrier();
+ assert.equal(sim.towers[0].level, 1); assert.equal(sim.wave, 0);
+ assert.equal(a.c.of('reject').length, 0, 'not rejected by the sim: dropped as malformed');
+ for (let i = 0; i < 17; i++) a.c.send({ t: 'cmd', c: 'wave', n: 'x' }); // 4 + 17 = 21 malformed messages
+ assert.equal((await a.c.closed()).code, 4400);
+ });
+});
+
test('wave command spawns monsters that appear in snapshots; refused beyond the load cap', async () => {
await withServer({}, async (S) => {
const { a, room } = await S.pair();
diff --git a/test/sim-commands.test.js b/test/sim-commands.test.js
new file mode 100644
index 0000000..70ef9ce
--- /dev/null
+++ b/test/sim-commands.test.js
@@ -0,0 +1,87 @@
+'use strict';
+/*
+ * Idempotent commands (coop-5): two players who press Upgrade / Next wave at the same moment send the same
+ * command twice. Each carries what its sender saw (`lv`: the tower level, `n`: the wave it expects to start);
+ * the sim applies the first and rejects the second with reason 'stale' instead of charging or launching twice.
+ * A command without the field is applied as before (auto waves, the balance bot, older clients).
+ */
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const TD = require('../public/js/sim.js');
+
+const { Sim, TOWERS } = TD;
+
+function withTower(type = 'filter') {
+ const s = new Sim({ map: 'open', gold: 5000 });
+ const r = s.cmd({ c: 'place', type, x: 10, y: 8, by: 0 });
+ assert.ok(r.ok, 'place ' + type);
+ return { s, id: r.id };
+}
+
+test('upgrade carrying the level the sender saw is applied once; the same command again is stale and costs nothing', () => {
+ const { s, id } = withTower();
+ const g0 = s.gold, cost = TOWERS.filter.levels[1].cost;
+ const a = s.cmd({ c: 'upgrade', id, lv: 1, by: 0 });
+ assert.deepEqual([a.ok, a.level], [true, 2]);
+ assert.equal(s.gold, g0 - cost);
+ const rev = s.rev;
+ const b = s.cmd({ c: 'upgrade', id, lv: 1, by: 1 });
+ assert.deepEqual([b.ok, b.reason], [false, 'stale']);
+ assert.equal(s.towerById(id).level, 2, 'still level 2, not 3');
+ assert.equal(s.gold, g0 - cost, 'charged once');
+ assert.equal(s.rev, rev, 'a rejected command changes nothing');
+ assert.equal(s.cmd({ c: 'upgrade', id, lv: 2, by: 1 }).ok, true, 'a sender who saw level 2 may go on to 3');
+ assert.equal(s.towerById(id).level, 3);
+});
+
+test('upgrade without a level (older client, bot, console) keeps working; a stale level never matches a later level either', () => {
+ const { s, id } = withTower();
+ assert.equal(s.cmd({ c: 'upgrade', id }).ok, true);
+ assert.equal(s.towerById(id).level, 2);
+ assert.equal(s.cmd({ c: 'upgrade', id, lv: null }).ok, true);
+ assert.equal(s.towerById(id).level, 3);
+ assert.equal(s.cmd({ c: 'upgrade', id, lv: 2 }).reason, 'stale');
+ assert.equal(s.cmd({ c: 'upgrade', id, lv: '3' }).reason, 'stale', 'a level of the wrong type is never "the level I saw"');
+ assert.equal(s.towerById(id).level, 3);
+});
+
+test('stale beats max / gold: a sender who saw an older level is told it is stale, not that the tower is maxed out', () => {
+ const { s, id } = withTower();
+ const top = TOWERS.filter.levels.length;
+ for (let lv = 1; lv < top; lv++) assert.ok(s.cmd({ c: 'upgrade', id, lv }).ok);
+ assert.equal(s.towerById(id).level, top);
+ assert.equal(s.cmd({ c: 'upgrade', id, lv: top - 1 }).reason, 'stale');
+ assert.equal(s.cmd({ c: 'upgrade', id, lv: top }).reason, 'max', 'a sender who saw the top level still gets the real reason');
+ const poor = new Sim({ map: 'open', gold: TOWERS.filter.levels[0].cost });
+ const p = poor.cmd({ c: 'place', type: 'filter', x: 10, y: 8 });
+ assert.equal(poor.cmd({ c: 'upgrade', id: p.id, lv: 1 }).reason, 'gold');
+ assert.equal(poor.cmd({ c: 'upgrade', id: 999, lv: 1 }).reason, 'no_tower');
+ s.state = 'lost'; // and a finished game answers "over" before it says "stale"
+ assert.equal(s.cmd({ c: 'upgrade', id, lv: 7 }).reason, 'over');
+ assert.equal(s.cmd({ c: 'wave', n: 7 }).reason, 'over');
+});
+
+test('wave carrying the number it expects to start: the first starts it, a second sender who saw the same wave is stale', () => {
+ const s = new Sim({ map: 'open' });
+ const a = s.cmd({ c: 'wave', n: 1, by: 0 });
+ assert.deepEqual([a.ok, a.wave], [true, 1]);
+ const queued = s.spawnQ.length;
+ const b = s.cmd({ c: 'wave', n: 1, by: 1 });
+ assert.deepEqual([b.ok, b.reason], [false, 'stale']);
+ assert.equal(s.wave, 1, 'one wave started, not two');
+ assert.equal(s.spawnQ.length, queued, 'nothing was queued by the rejected command');
+ assert.equal(s.cmd({ c: 'wave', n: 2 }).ok, true, 'a sender who saw wave 1 may start wave 2');
+ assert.equal(s.wave, 2);
+ assert.equal(s.cmd({ c: 'wave', n: 9 }).reason, 'stale', 'a number from the future is stale too');
+});
+
+test('wave without a number still starts the next wave; auto waves never need one', () => {
+ const s = new Sim({ map: 'open' });
+ assert.equal(s.cmd({ c: 'wave' }).wave, 1);
+ assert.equal(s.cmd({ c: 'wave', n: null }).wave, 2);
+ s.cmd({ c: 'auto', v: true });
+ s.nextWaveIn = 0.01;
+ s.tick(TD.STEP * 2);
+ assert.equal(s.wave, 3, 'the timer starts a wave on its own');
+ assert.equal(s.cmd({ c: 'wave', n: 3 }).reason, 'stale', 'and a click that saw the old wave number is now stale');
+});
diff --git a/test/sim.test.js b/test/sim.test.js
index 6ae41c5..38c4926 100644
--- a/test/sim.test.js
+++ b/test/sim.test.js
@@ -313,19 +313,27 @@ test('fuzz: garbage commands never throw', () => {
});
test('balance tables keep the shape the client and server rely on', () => {
- assert.deepEqual(TD.TOWER_ORDER, ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink']);
- assert.deepEqual(TD.ENEMY_ORDER, ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']);
+ assert.deepEqual(TD.TOWER_ORDER, ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink']);
+ assert.deepEqual(TD.ENEMY_ORDER, ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit', 'daemon', 'proxy', 'botnet']);
+ assert.equal(Object.keys(TOWERS).length, TD.TOWER_ORDER.length, 'every tower is in the palette order');
+ assert.equal(Object.keys(ENEMIES).length, TD.ENEMY_ORDER.length, 'every enemy is in the wire order');
assert.equal(TOWERS.wall.levels.length, 1);
assert.ok(TOWERS.wall.refund, 'walls refund in full');
+ const ROLES = ['wall', 'attack', 'aura', 'control', 'support'];
for (const k of TD.TOWER_ORDER) {
const t = TOWERS[k];
assert.ok(t.name && t.color && t.key && t.desc, k + ' has display fields');
+ assert.ok(ROLES.includes(t.role), k + ' has a known role');
if (k === 'wall') continue;
assert.equal(t.levels.length, k === 'uplink' ? 4 : 3, k + ' has the expected number of levels');
t.levels.forEach((lv, i) => {
assert.ok(lv.cost > 0 && lv.range > 0, k + ' L' + (i + 1) + ' cost/range');
if (k === 'throttle') assert.ok(lv.slow > 0 && lv.slow <= 0.6, 'slow is capped at 0.6 by the sim');
+ else if (k === 'sandbox') assert.ok(lv.pulse > 0 && lv.stun > 0 && lv.stun < lv.pulse, 'sandbox pulses and stuns for less than the recharge');
+ else if (k === 'balancer') assert.ok(lv.boost > 0 && lv.boost <= 1, 'balancer boosts the fire rate');
else assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' L' + (i + 1) + ' dmg/rate');
+ if (t.role === 'attack') assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' attack towers have dmg and rate');
+ else assert.ok(!lv.dmg && !lv.rate, k + ' deals no damage of its own');
if (k === 'mortar') assert.ok(lv.splash > 0);
if (k === 'arc') assert.ok(lv.chains >= 1 && lv.chainRange > 0 && lv.falloff > 0 && lv.falloff < 1);
if (k === 'uplink') assert.ok(lv.width > 0 && lv.splash > 0 && lv.slowOnHit > 0 && lv.slowOnHit <= 0.6 && lv.slowFor > 0);
@@ -335,6 +343,8 @@ test('balance tables keep the shape the client and server rely on', () => {
for (const k of TD.ENEMY_ORDER) {
const e = ENEMIES[k];
assert.ok(e.name && e.color && e.hp > 0 && e.speed > 0 && e.reward > 0 && e.leak > 0 && e.armor >= 0 && e.r > 0, k);
+ assert.equal(typeof e.air, 'boolean', k + ' says whether it flies');
+ assert.ok(Number.isInteger(e.buyCost) && e.buyCost > 0, k + ' has a versus buyCost');
}
assert.ok(TD.START_GOLD >= TOWERS.filter.levels[0].cost * 2, 'the opening credits buy at least two turrets');
assert.ok(TD.SELL_RATIO > 0 && TD.SELL_RATIO < 1, 'selling a turret always loses credits');
@@ -384,3 +394,476 @@ test('Orbital Uplink: expensive endgame beam that pierces, ignores armour, blast
const g = s.gold; s.sell(t.id);
assert.equal(s.gold, g + Math.floor(upTotal * TD.SELL_RATIO));
});
+
+// ---------------------------------------------------------------------------------------------------- new content
+// A real monster (spawned through the sim so it has every field) moved to (x, y) and, by default, held still.
+function put(s, kind, x, y, wave) {
+ s.spawnMonster({ k: kind, wave: wave || 1 });
+ const m = s.monsters[s.monsters.length - 1];
+ m.x = x; m.y = y; m.cx = Math.floor(x); m.cy = Math.floor(y); m.tx = -1; m.ty = -1;
+ m.speed = 0;
+ return m;
+}
+const tick = (s, seconds) => { const n = Math.round(seconds / STEP); for (let i = 0; i < n; i++) s.tick(STEP); };
+
+test('hotkeys: one unique key 1-9 per tower, in palette order; enemy kinds are only ever appended', () => {
+ const keys = TD.TOWER_ORDER.map((k) => TOWERS[k].key);
+ assert.deepEqual(keys, ['1', '2', '3', '4', '5', '6', '7', '8', '9']);
+ assert.equal(new Set(keys).size, keys.length);
+ assert.equal(TOWERS.wall.key, '1');
+ assert.equal(TOWERS.sandbox.key, '7');
+ assert.equal(TOWERS.balancer.key, '8');
+ assert.equal(TOWERS.uplink.key, '9');
+ // the first six indexes are on the wire already (snapshot kindIndex)
+ assert.deepEqual(TD.ENEMY_ORDER.slice(0, 6), ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']);
+ assert.deepEqual(TD.ENEMY_ORDER.slice(6), ['daemon', 'proxy', 'botnet']);
+});
+
+test('buyCost: every enemy has one, about three times its kill reward', () => {
+ for (const k of TD.ENEMY_ORDER) {
+ const e = ENEMIES[k];
+ assert.ok(Number.isInteger(e.buyCost) && e.buyCost > 0, k);
+ const ratio = e.buyCost / e.reward;
+ assert.ok(ratio >= 2.5 && ratio <= 3.5, k + ' buyCost/reward = ' + ratio.toFixed(2));
+ }
+ assert.ok(ENEMIES.daemon.air === false && ENEMIES.proxy.air === false && ENEMIES.botnet.air === true);
+});
+
+test('every tower can be built, upgraded through all its levels, and sold (solid blocks like the others)', () => {
+ const s = new Sim({ map: 'open', gold: 100000 });
+ let x = 3;
+ for (const type of TD.TOWER_ORDER) {
+ const def = TOWERS[type];
+ const r = s.place(type, x, 10);
+ assert.ok(r.ok, type + ' can be placed');
+ assert.equal(s.board.solid[10 * s.board.cols + x], 1, type + ' is a solid block');
+ assert.equal(s.place(type, x, 10).reason, 'occupied');
+ const t = s.towerById(r.id);
+ for (let lv = 1; lv < def.levels.length; lv++) assert.ok(s.upgrade(t.id).ok, type + ' upgrade to level ' + (lv + 1));
+ assert.equal(s.upgrade(t.id).reason, 'max', type);
+ assert.equal(t.level, def.levels.length);
+ assert.equal(t.spent, def.levels.reduce((a, l) => a + l.cost, 0));
+ assert.ok(s.setTargetMode(t.id, 'close').ok);
+ const g = s.gold, sold = s.sell(t.id);
+ assert.equal(sold.refund, def.refund ? t.spent : Math.floor(t.spent * TD.SELL_RATIO));
+ assert.equal(s.gold, g + sold.refund);
+ assert.equal(s.board.solid[10 * s.board.cols + x], 0, type + ' sold: the cell is free again');
+ x++;
+ }
+ assert.equal(s.towers.length, 0);
+ // a Sandbox or Load Balancer cannot seal the route either
+ const tiny = new Sim({ map: mini(['S....', '.....', '.....', '.....', '....C']), gold: 1000 });
+ assert.ok(tiny.place('sandbox', 3, 4).ok);
+ assert.equal(tiny.place('balancer', 4, 3).reason, 'blocks');
+ assert.equal(tiny.place('sandbox', 5, 5).reason, 'bounds');
+});
+
+test('Daemon heals every other enemy within 2.2 cells for 6% of max hp, never itself, never above max', () => {
+ const s = new Sim({ map: 'open', gold: 0 });
+ const d = put(s, 'daemon', 10.5, 5.5);
+ const near = put(s, 'trojan', 12.5, 5.5), far = put(s, 'trojan', 13.0, 5.5); // 2.0 and 2.5 cells away
+ const air = put(s, 'botnet', 10.5, 7.5); // 2.0 cells away, a flyer
+ const full = put(s, 'ping', 10.5, 4.0);
+ const dead = put(s, 'trojan', 10.5, 6.0);
+ for (const m of [near, far, d, air]) m.hp = m.maxhp / 2;
+ air.maxhp = air.hp = 100; air.hp = 50;
+ dead.hp = 1; dead.dead = true;
+ const per = (m) => 0.06 * m.maxhp;
+ const n0 = near.hp, f0 = far.hp, d0 = d.hp, a0 = air.hp;
+ s.healPulse();
+ assert.ok(Math.abs(near.hp - (n0 + per(near))) < 1e-9, 'a trojan 2.0 cells away is healed by 6% of its max');
+ assert.equal(far.hp, f0, 'one 2.5 cells away is not');
+ assert.equal(d.hp, d0, 'a daemon never heals itself');
+ assert.ok(Math.abs(air.hp - (a0 + per(air))) < 1e-9, 'flyers are healed too');
+ assert.equal(full.hp, full.maxhp);
+ assert.equal(dead.hp, 1, 'dead enemies are not healed');
+ near.hp = near.maxhp - 1;
+ s.healPulse();
+ assert.equal(near.hp, near.maxhp, 'never above max');
+ // two daemons heal each other, a lone one does not
+ const d2 = put(s, 'daemon', 10.5, 6.5);
+ d.hp = d.maxhp / 2; d2.hp = d2.maxhp / 2;
+ s.healPulse();
+ assert.ok(d.hp > d.maxhp / 2 && d2.hp > d2.maxhp / 2);
+ assert.equal(d.hp, d.maxhp / 2 + per(d), 'the healing came from the other daemon only (6%, not 12%)');
+});
+
+test('several daemons never heal one enemy for more than 12% of its max hp per second', () => {
+ const s = new Sim({ map: 'open', gold: 0 });
+ const t = put(s, 'trojan', 10.5, 5.5);
+ for (let i = 0; i < 5; i++) put(s, 'daemon', 10.5 + 0.3 * i, 6.0);
+ t.hp = t.maxhp * 0.1;
+ s.healPulse();
+ assert.ok(Math.abs(t.hp - t.maxhp * 0.22) < 1e-9, 'five daemons heal 12%, not 30%: ' + (t.hp / t.maxhp));
+ // two daemons already give the full 12%; one gives 6%
+ const s1 = new Sim({ map: 'open', gold: 0 });
+ const t1 = put(s1, 'trojan', 10.5, 5.5); put(s1, 'daemon', 11.0, 5.5); t1.hp = 0;
+ s1.healPulse();
+ assert.ok(Math.abs(t1.hp - 0.06 * t1.maxhp) < 1e-9);
+});
+
+test('daemons pulse once a second on one clock; heals scale with wave hp (max hp, not base hp)', () => {
+ const s = new Sim({ map: 'open', gold: 0 });
+ const d = put(s, 'daemon', 10.5, 5.5, 10), t = put(s, 'trojan', 11.5, 5.5, 10);
+ t.hp = 100;
+ assert.equal(t.maxhp, Math.round(ENEMIES.trojan.hp * TD.hpScale(10)));
+ tick(s, 0.9);
+ assert.equal(t.hp, 100, 'no heal before the first second is up');
+ tick(s, 0.2);
+ assert.ok(Math.abs(t.hp - (100 + 0.06 * t.maxhp)) < 1e-6, 'one pulse after a second');
+ tick(s, 1.0);
+ assert.ok(Math.abs(t.hp - (100 + 2 * 0.06 * t.maxhp)) < 1e-6, 'one more pulse a second later');
+ const ev = s.drainEvents().filter((e) => e.e === 'heal');
+ assert.equal(ev.length, 2, 'each pulse tells the client where the daemon healed');
+ assert.ok(ev[0].r === ENEMIES.daemon.healRange && Number.isFinite(ev[0].x));
+ s.monsters.splice(s.monsters.indexOf(d), 1);
+ const before = t.hp;
+ tick(s, 2.5);
+ assert.equal(t.hp, before, 'no daemon, no healing');
+});
+
+test('Proxy: the shield soaks damage first, armour applies once, overflow hurts hp, the snapshot carries hp + shield', () => {
+ const s = new Sim({ map: 'open', gold: 0 });
+ const m = put(s, 'proxy', 10.5, 5.5);
+ const E = ENEMIES.proxy;
+ assert.equal(m.hp, E.hp); assert.equal(m.shield, E.shield); assert.equal(m.maxShield, E.shield);
+ s.damage(m, 10); // armour 1: 9 get through to the shield
+ assert.equal(m.shield, E.shield - 9);
+ assert.equal(m.hp, E.hp, 'hp untouched while the shield holds');
+ const snap1 = s.snapshot().mo[0];
+ assert.equal(snap1[4], E.hp + E.shield - 9, 'hp field = hp + shield');
+ assert.equal(snap1[5], E.hp + E.shield, 'maxhp field = maxhp + maxShield');
+ assert.equal(snap1.length, 7);
+ s.damage(m, 150); // 149 after armour: 111 left in the shield, 38 into hp (armour NOT applied a second time)
+ assert.equal(m.shield, 0);
+ assert.equal(m.hp, E.hp - (149 - (E.shield - 9)));
+ assert.equal(s.snapshot().mo[0][4], m.hp);
+ assert.equal(m.dead, false);
+ s.damage(m, 1e6);
+ assert.equal(m.dead, true);
+ assert.equal(s.kills, 1);
+ // the whole pool (shield + hp) must be dealt before it dies; armour-ignoring damage also hits the shield first
+ const m2 = put(s, 'proxy', 10.5, 5.5);
+ s.damage(m2, E.shield + E.hp - 1, null, true);
+ assert.equal(m2.dead, false);
+ s.damage(m2, 1, null, true);
+ assert.equal(m2.dead, true);
+});
+
+test('Proxy shield is scaled with the wave like hp, regrows 10%/s after 3 s without damage, and the timer restarts on every hit', () => {
+ const s = new Sim({ map: 'open', gold: 0 });
+ const m = put(s, 'proxy', 10.5, 5.5, 12);
+ const sh = Math.round(ENEMIES.proxy.shield * TD.hpScale(12));
+ assert.equal(m.maxShield, sh);
+ assert.equal(m.maxhp, Math.round(ENEMIES.proxy.hp * TD.hpScale(12)));
+ s.damage(m, 400, null, true);
+ const left = sh - 400;
+ assert.equal(m.shield, left);
+ tick(s, 2.8);
+ assert.equal(m.shield, left, 'nothing regrows during the 3 s delay');
+ tick(s, 1.2); // 4.0 s since the hit: one second of regrow
+ assert.ok(Math.abs(m.shield - (left + 0.1 * sh)) < 0.5, 'regrew 10% of max in the first second after the delay: ' + (m.shield - left) + ' vs ' + 0.1 * sh);
+ s.damage(m, 5, null, true);
+ const after = m.shield;
+ tick(s, 2.9);
+ assert.equal(m.shield, after, 'a hit restarts the delay');
+ tick(s, 60);
+ assert.equal(m.shield, sh, 'regrows to the maximum and not beyond');
+ assert.equal(m.hp, m.maxhp, 'the shield regrows, hp is not touched');
+ // a daemon never tops up a shield, only hp
+ s.damage(m, sh + 40, null, true);
+ const d = put(s, 'daemon', 11.0, 5.5, 12);
+ s.healPulse();
+ assert.equal(m.shield, 0);
+ assert.ok(Math.abs(m.hp - (m.maxhp - 40 + 0.06 * m.maxhp)) < 1e-6 || m.hp === m.maxhp);
+ assert.ok(d.hp > 0);
+});
+
+test('Botnet: a fast, tiny flyer that goes straight for the core and is hit by anti-air only', () => {
+ const s = new Sim({ map: 'open', gold: 1000 });
+ const E = ENEMIES.botnet;
+ assert.ok(E.air && E.hp <= 15 && E.speed > ENEMIES.ghost.speed && E.reward === 1);
+ const m = put(s, 'botnet', 12.5, 7.5);
+ s.place('mortar', 12, 6);
+ tick(s, 1);
+ assert.equal(m.dead, false, 'a mortar cannot hit flyers');
+ s.place('filter', 11, 6);
+ tick(s, 1);
+ assert.ok(m.dead || m.hp < m.maxhp, 'a filter can');
+ // and it flies straight at the core at its own speed
+ const s2 = new Sim({ map: 'open', gold: 0 });
+ const f = put(s2, 'botnet', 0.5, 7.5);
+ f.speed = E.speed;
+ tick(s2, 2);
+ assert.ok(Math.abs(f.x - (0.5 + 2 * E.speed * Math.cos(Math.atan2(8 - 7.5, 25.5 - 0.5)))) < 0.1, 'x=' + f.x);
+});
+
+test('Sandbox stuns everything in range (ground and air), not what is outside, and stunned enemies do not move', () => {
+ const s = new Sim({ map: 'open', gold: 1000 });
+ s.place('sandbox', 2, 6); // centre (2.5, 6.5), range 2.6
+ const L = TOWERS.sandbox.levels[0];
+ const ground = put(s, 'ping', 0.5, 7.5), air = put(s, 'ghost', 3.5, 7.5), out = put(s, 'ping', 8.5, 7.5);
+ for (const m of [ground, air, out]) m.speed = ENEMIES[m.kind].speed;
+ const gx = ground.x, ax = air.x, ox = out.x;
+ tick(s, L.stun * 0.9);
+ assert.ok(ground.stunT > 0 && air.stunT > 0, 'ground and air are stunned');
+ assert.equal(out.stunT, 0, 'out of range: untouched');
+ assert.equal(ground.x, gx, 'stunned ground unit stands still');
+ assert.equal(air.x, ax, 'stunned flyer stands still');
+ assert.ok(out.x > ox, 'the unit outside keeps moving');
+ assert.equal(s.snapshot().mo.find((e) => e[0] === ground.id)[6], 1, 'stunned units are flagged in the snapshot (the 0/1 slow flag)');
+ tick(s, L.stun * 0.3);
+ assert.ok(ground.x > gx, 'moves again once the stun is over');
+ const ev = s.drainEvents().filter((e) => e.e === 'stun');
+ assert.equal(ev.length, 1);
+ assert.equal(ev[0].n, 2);
+});
+
+test('Sandbox: pulse cadence by level, only pulses when something is in range, stun does not stack, bosses get half', () => {
+ const s = new Sim({ map: 'open', gold: 10000 });
+ const r = s.place('sandbox', 5, 5), t = s.towerById(r.id);
+ tick(s, 12);
+ assert.equal(s.drainEvents().filter((e) => e.e === 'stun').length, 0, 'nothing in range: no pulse and the charge is kept');
+ assert.equal(t.cd, 0);
+ const boss = put(s, 'rootkit', 6.5, 6.5, 10), ping = put(s, 'ping', 5.5, 7.0);
+ const L1 = TOWERS.sandbox.levels[0];
+ tick(s, 0.1);
+ assert.ok(Math.abs(ping.stunT - (L1.stun - 0.1 + STEP)) < 0.05, 'a ping is stunned for the full time');
+ assert.ok(Math.abs(boss.stunT - (L1.stun * (1 - ENEMIES.rootkit.slowRes) - 0.1 + STEP)) < 0.05, 'a boss for half');
+ assert.ok(boss.stunT < ping.stunT);
+ tick(s, 8.8); // 8.9 s: pulses at 0 and 5
+ assert.equal(s.drainEvents().filter((e) => e.e === 'stun').length, 2);
+ // level 3 pulses faster and stuns longer; a second pulse never adds to a running stun, it only refreshes it
+ s.upgrade(t.id); s.upgrade(t.id);
+ const L3 = TOWERS.sandbox.levels[2];
+ assert.ok(L3.pulse < L1.pulse && L3.stun > L1.stun && L3.range > L1.range);
+ s.drainEvents();
+ t.cd = 0; ping.stunT = 0.5;
+ tick(s, 0.05);
+ assert.ok(Math.abs(ping.stunT - (L3.stun - 0.05 + STEP)) < 0.05 && ping.stunT <= L3.stun, 'stun is set to the pulse stun, not added');
+ t.cd = 0; ping.stunT = L3.stun * 2; // an already longer stun stays
+ s.tick(STEP);
+ assert.ok(ping.stunT > L3.stun, 'a shorter stun never cuts a longer one');
+ s.drainEvents();
+ tick(s, 12.1);
+ assert.equal(s.drainEvents().filter((e) => e.e === 'stun').length, 3, 'level 3 recharges every ' + L3.pulse + ' s');
+});
+
+test('Load Balancer: boosts attack towers in range, best boost only, not itself, not control/aura towers, ends when sold', () => {
+ const s = new Sim({ map: 'open', gold: 100000 });
+ const f1 = s.towerById(s.place('filter', 10, 5).id); // 1 cell from the balancer at (11,5)
+ const fFar = s.towerById(s.place('filter', 14, 5).id); // 3 cells: outside the level 1 and 2 range, exactly inside level 3
+ const sb = s.towerById(s.place('sandbox', 10, 6).id);
+ const th = s.towerById(s.place('throttle', 9, 5).id);
+ const wl = s.towerById(s.place('wall', 11, 6).id);
+ const b1 = s.towerById(s.place('balancer', 11, 5).id);
+ const B = TOWERS.balancer.levels;
+ s.updateAuras();
+ assert.equal(f1.buff, B[0].boost);
+ assert.equal(fFar.buff, 0, 'out of range');
+ for (const t of [sb, th, wl, b1]) assert.equal(t.buff, 0, t.type + ' is not an attack tower');
+ // upgrading makes it stronger; a second, weaker balancer never adds to it
+ s.upgrade(b1.id);
+ s.updateAuras();
+ assert.equal(f1.buff, B[1].boost);
+ assert.equal(fFar.buff, 0);
+ const b2 = s.towerById(s.place('balancer', 10, 4).id);
+ s.updateAuras();
+ assert.equal(f1.buff, B[1].boost, 'the best boost applies, they do not stack (not 0.15 + 0.25)');
+ assert.equal(b1.buff, 0, 'a balancer does not boost another balancer'); assert.equal(b2.buff, 0);
+ s.upgrade(b1.id);
+ s.updateAuras();
+ assert.equal(f1.buff, B[2].boost);
+ assert.equal(fFar.buff, B[2].boost, 'level 3 reaches 3 cells');
+ // selling the strong one drops back to the weak one, selling the last ends the boost
+ s.sell(b1.id);
+ s.updateAuras();
+ assert.equal(f1.buff, B[0].boost);
+ assert.equal(fFar.buff, 0);
+ s.sell(b2.id);
+ s.tick(STEP);
+ assert.equal(f1.buff, 0, 'selling the last balancer ends the boost');
+});
+
+test('Load Balancer: cooldowns really elapse faster, so a boosted tower fires more often', () => {
+ const mk = (withBalancer) => {
+ const s = new Sim({ map: 'open', gold: 10000 });
+ const t = s.towerById(s.place('ids', 10, 5).id);
+ if (withBalancer) s.place('balancer', 11, 5);
+ const target = put(s, 'trojan', 10.5, 7.5, 1);
+ target.hp = target.maxhp = 1e12; target.armor = 0;
+ return { s, t, target };
+ };
+ const a = mk(false), b = mk(true);
+ a.t.cd = b.t.cd = 1;
+ a.s.tick(0.1); b.s.tick(0.1);
+ assert.ok(Math.abs(a.t.cd - 0.9) < 1e-9);
+ assert.ok(Math.abs(b.t.cd - (1 - 0.1 * (1 + TOWERS.balancer.levels[0].boost))) < 1e-9, 'cooldown ran 15% faster');
+ const shots = (x) => { tick(x.s, 40); return x.s.drainEvents().filter((e) => e.e === 'shot' && e.k === 'ids').length; };
+ const na = shots(a), nb = shots(b);
+ assert.ok(na >= 25, 'baseline fires ~28 shots in 40 s: ' + na);
+ assert.ok(nb > na * 1.1 && nb < na * 1.2, 'boosted ' + nb + ' vs ' + na);
+});
+
+test('waves 1-8 are exactly the original introduction', () => {
+ const W = [
+ [{ k: 'ping', c: 8, gap: 0.7 }],
+ [{ k: 'worm', c: 11, gap: 0.4 }],
+ [{ k: 'ping', c: 9, gap: 0.6 }, { k: 'trojan', c: 1, gap: 1.4 }],
+ [{ k: 'spam', c: 30, gap: 0.18 }],
+ [{ k: 'ghost', c: 7, gap: 0.9 }, { k: 'ping', c: 8, gap: 0.5 }],
+ [{ k: 'trojan', c: 4, gap: 1.2 }, { k: 'worm', c: 11, gap: 0.35 }],
+ [{ k: 'ghost', c: 12, gap: 0.6 }, { k: 'spam', c: 24, gap: 0.2 }],
+ [{ k: 'ping', c: 16, gap: 0.4 }, { k: 'trojan', c: 5, gap: 1 }, { k: 'ghost', c: 6, gap: 0.8 }],
+ ];
+ for (let n = 1; n <= 8; n++) assert.deepEqual(TD.waveGroups(n), W[n - 1], 'wave ' + n);
+ for (let n = 1; n <= 8; n++) assert.ok(!TD.waveGroups(n).some((g) => ['daemon', 'proxy', 'botnet'].includes(g.k)));
+});
+
+test('new kinds are woven into the waves from 9 on: daemons with trojans, proxies from 12, botnets from 14', () => {
+ const first = {};
+ for (let n = 1; n <= 60; n++) {
+ const g = TD.waveGroups(n);
+ for (const e of g) {
+ assert.ok(ENEMIES[e.k], 'wave ' + n + ' kind ' + e.k);
+ assert.ok(Number.isInteger(e.c) && e.c >= 1 && e.gap > 0, 'wave ' + n);
+ if (first[e.k] === undefined) first[e.k] = n;
+ }
+ assert.ok(g.length <= 8, 'wave ' + n + ' has a sane number of groups');
+ const t = g.reduce((a, e) => a + e.c * e.gap + 1.5, 0);
+ assert.ok(t < 120, 'wave ' + n + ' finishes spawning within two minutes (' + t.toFixed(0) + ' s)');
+ if (n >= 9 && g.some((e) => e.k === 'trojan')) {
+ const tr = g.find((e) => e.k === 'trojan'), dm = g.find((e) => e.k === 'daemon');
+ assert.ok(dm && dm.c >= 1, 'wave ' + n + ' has a daemon escort');
+ assert.ok(g.indexOf(dm) > g.indexOf(tr), 'the escort spawns behind the trojans');
+ assert.ok(dm.c <= tr.c, 'the escort is not bigger than the trojan group');
+ }
+ }
+ assert.equal(first.daemon, 9);
+ assert.equal(first.proxy, 12);
+ assert.equal(first.botnet, 14);
+ for (const k of TD.ENEMY_ORDER) assert.ok(first[k] !== undefined, k + ' appears somewhere in waves 1-60');
+ for (let n = 9; n <= 60; n++) {
+ const kinds = TD.waveGroups(n).map((e) => e.k);
+ if (n < 12) assert.ok(!kinds.includes('proxy'), 'no proxy before 12');
+ if (n < 14) assert.ok(!kinds.includes('botnet'), 'no botnet before 14');
+ }
+ // the late waves combine them
+ assert.ok(['daemon', 'proxy', 'botnet'].every((k) => TD.waveGroups(30).some((e) => e.k === k)), 'wave 30 has all three');
+ assert.ok(TD.waveGroups(20).some((e) => e.k === 'rootkit') && TD.waveGroups(20).some((e) => e.k === 'proxy'));
+ // the loop keeps growing: the same slot gets more units later
+ const cnt = (n, k) => TD.waveGroups(n).filter((e) => e.k === k).reduce((a, e) => a + e.c, 0);
+ assert.ok(cnt(22, 'botnet') > cnt(14, 'botnet') && cnt(36, 'proxy') > cnt(12, 'proxy'));
+});
+
+test('waveSummary lists one entry per kind with counts and flags flyers', () => {
+ for (let n = 1; n <= 60; n++) {
+ const sum = TD.waveSummary(n), groups = TD.waveGroups(n);
+ assert.equal(new Set(sum.map((e) => e.k)).size, sum.length, 'one entry per kind in wave ' + n);
+ for (const e of sum) {
+ assert.equal(e.air, !!ENEMIES[e.k].air, 'wave ' + n + ' ' + e.k + ' air flag');
+ assert.equal(e.c, groups.filter((g) => g.k === e.k).reduce((a, g) => a + g.c, 0));
+ }
+ assert.equal(sum.reduce((a, e) => a + e.c, 0), groups.reduce((a, g) => a + g.c, 0));
+ }
+ assert.deepEqual(TD.waveSummary(5), [{ k: 'ghost', c: 7, air: true }, { k: 'ping', c: 8, air: false }]);
+ assert.ok(TD.waveSummary(14).some((e) => e.k === 'botnet' && e.air === true));
+ assert.ok(TD.waveSummary(7).some((e) => e.k === 'ghost' && e.air));
+});
+
+test('the new waves run end to end and the snapshot (incl. daemon, proxy, botnet) survives JSON', () => {
+ const s = new Sim({ map: 'twin', gold: 0, lives: 1000 });
+ s.wave = 14; // every new kind in the queue at once
+ s.spawnQ.push({ t: 0, k: 'daemon', wave: 14 }, { t: 0, k: 'proxy', wave: 14 }, { t: 0, k: 'botnet', wave: 14 }, { t: 0, k: 'trojan', wave: 14 });
+ s.spawnQ.push(...TD.waveGroups(14).flatMap((g, gi) => Array.from({ length: g.c }, (_, i) => ({ t: gi * 5 + i * g.gap, k: g.k, wave: 14 }))));
+ s.spawnQ.sort((a, b) => a.t - b.t);
+ let sawNew = false, sawShield = false;
+ for (let i = 0; i < 60 * 25 && s.state === 'playing'; i++) {
+ s.tick(STEP);
+ if (i % 30 === 0) {
+ const snap = JSON.parse(JSON.stringify(s.snapshot()));
+ assert.deepEqual(snap, JSON.parse(JSON.stringify(snap)));
+ for (const e of snap.mo) {
+ assert.equal(e.length, 7);
+ assert.ok(Number.isInteger(e[1]) && e[1] >= 0 && e[1] < TD.ENEMY_ORDER.length, 'kindIndex indexes ENEMY_ORDER');
+ assert.ok(e[4] > 0 && e[4] <= e[5], 'hp (incl. shield) within maxhp (incl. maxShield)');
+ if (e[1] >= 6) sawNew = true;
+ if (TD.ENEMY_ORDER[e[1]] === 'proxy') { sawShield = true; assert.ok(e[5] > ENEMIES.proxy.hp * TD.hpScale(14), 'proxy maxhp includes the shield'); }
+ }
+ }
+ }
+ assert.ok(sawNew && sawShield);
+ assert.ok(s.leaks > 0, 'undefended waves leak');
+ assert.equal(JSON.stringify(s.fullState()).includes('null'), false);
+});
+
+test('Orbital Uplink pricing: very expensive, and every one you own makes the next dearer', () => { // (25% per owned one, for buying and for upgrading)
+ const base = TOWERS.uplink.levels[0].cost;
+ assert.ok(base >= 8 * TD.START_GOLD, 'the first Uplink costs many times the opening credits');
+ assert.ok(base >= 20 * TOWERS.ids.levels[0].cost, 'and a lot more than an IDS Sniper');
+ // the shared helper: arrays of towers and plain counts agree; other towers have a flat price
+ assert.equal(TD.priceFor('uplink', 0), base);
+ assert.equal(TD.priceFor('uplink', [{ type: 'uplink' }, { type: 'filter' }, { type: 'uplink' }]), TD.priceFor('uplink', 2));
+ assert.equal(TD.priceFor('filter', 50), TOWERS.filter.levels[0].cost, 'a Packet Filter never gets dearer');
+ assert.equal(TD.priceFor('wall', [{ type: 'wall' }, { type: 'wall' }]), TOWERS.wall.levels[0].cost);
+ for (let n = 1; n < 6; n++) assert.ok(TD.priceFor('uplink', n) >= 1.2 * TD.priceFor('uplink', n - 1), 'each Uplink is about 25% dearer than the one before');
+
+ const s = new Sim({ map: 'open', gold: 1e6 });
+ const ids = [];
+ let prev = 0;
+ for (let i = 0; i < 4; i++) {
+ const want = TD.priceFor('uplink', s.towers);
+ assert.ok(want > prev, 'price keeps rising');
+ prev = want;
+ const g = s.gold;
+ const r = s.place('uplink', 4 + 2 * i, 6);
+ assert.ok(r.ok);
+ assert.equal(g - s.gold, want, 'the sim charges exactly the price the UI shows');
+ assert.equal(s.towerById(r.id).spent, want, 'spent records what was actually paid');
+ ids.push(r.id);
+ }
+ // refunds follow what each one cost, and selling brings the price back down
+ const before = TD.priceFor('uplink', s.towers);
+ const g0 = s.gold, t0 = s.towerById(ids[0]);
+ const refund = s.sell(ids[0]).refund;
+ assert.equal(refund, Math.floor(t0.spent * TD.SELL_RATIO));
+ assert.equal(s.gold, g0 + refund);
+ assert.ok(TD.priceFor('uplink', s.towers) < before, 'owning fewer makes the next one cheaper again');
+ // not enough credits for the dearer one: refused without charging
+ const poor = new Sim({ map: 'open', gold: base });
+ assert.ok(poor.place('uplink', 5, 5).ok);
+ poor.gold = TD.priceFor('uplink', poor.towers) - 10;
+ const gp = poor.gold;
+ assert.equal(poor.place('uplink', 8, 5).reason, 'gold');
+ assert.equal(poor.gold, gp);
+});
+
+test('Orbital Uplink upgrades get dearer by the same factor as the tower they belong to', () => {
+ const s = new Sim({ map: 'open', gold: 1e7 });
+ const a = s.towerById(s.place('uplink', 4, 6).id), b = s.towerById(s.place('uplink', 8, 6).id), c = s.towerById(s.place('uplink', 12, 6).id);
+ assert.equal(a.pm, 1);
+ assert.ok(Math.abs(b.pm - TOWERS.uplink.priceGrowth) < 1e-9 && Math.abs(c.pm - TOWERS.uplink.priceGrowth ** 2) < 1e-9, 'each remembers the multiplier it was bought at');
+ for (const t of [a, b, c]) {
+ const m = t.pm;
+ const g0 = s.gold, up1 = TD.upgradePrice('uplink', 1, m);
+ assert.equal(s.upgradeCost(t), up1, 'the sim and the shared helper agree');
+ assert.ok(Math.abs(up1 / TOWERS.uplink.levels[1].cost - m) < 0.01 * m + 0.01, 'level 2 costs the base upgrade times the multiplier');
+ assert.ok(s.upgrade(t.id).ok);
+ assert.equal(g0 - s.gold, up1);
+ assert.equal(t.spent, TD.priceFor('uplink', t.pm === 1 ? 0 : Math.round(Math.log(t.pm) / Math.log(TOWERS.uplink.priceGrowth))) + up1);
+ }
+ assert.ok(TD.upgradePrice('uplink', 3, c.pm) > TD.upgradePrice('uplink', 3, a.pm) * 1.5, 'the third Uplink is much dearer to upgrade than the first');
+ // flat-price towers are untouched
+ const f = s.towerById(s.place('filter', 6, 10).id);
+ assert.equal(f.pm, 1);
+ assert.equal(TD.upgradePrice('filter', 1, f.pm), TOWERS.filter.levels[1].cost);
+ // a tower bought after another was sold gets the lower multiplier back
+ s.sell(a.id);
+ const d = s.towerById(s.place('uplink', 16, 6).id);
+ assert.ok(d.pm < c.pm * 1.0001 && d.pm >= b.pm - 1e-9, 'owning fewer when you buy lowers the multiplier again');
+ // the multiplier travels in the tower list so a co-op client can show the same upgrade price
+ const row = s.towerList().find((r) => r[0] === c.id);
+ assert.equal(row.length, 9);
+ assert.ok(Math.abs(row[8] - c.pm) < 0.002);
+ assert.equal(s.towerList().find((r) => r[0] === f.id)[8], 1);
+});
diff --git a/tools/bot.js b/tools/bot.js
index 69cb61b..cc9247c 100644
--- a/tools/bot.js
+++ b/tools/bot.js
@@ -194,7 +194,8 @@ class Bot {
let gs = 0, gn = 0;
for (const g of groups) if (g.k === q.k) { gs += g.gap * g.c; gn += g.c; }
const g = (gn ? gs / gn : 1) * nSp; // seconds between consecutive packets on ONE route
- const h = Math.round(TD.ENEMIES[q.k].hp * TD.hpScale(w));
+ const ed = TD.ENEMIES[q.k];
+ const h = Math.round((ed.hp + (ed.shield || 0)) * TD.hpScale(w)); // a shield is extra hit points
out.push({ ki, N: q.c, Nr: Math.max(1, q.c / nSp), h, leak: K.leak, v: K.v, armor: K.armor, air: K.air, g, spacing: Math.max(0.2, K.v * g), w: weight });
}
};
@@ -230,6 +231,7 @@ class Bot {
capSpec(sp, e, slow, G) {
if (sp.type === 'throttle') return 0;
const TD = this.TD, td = TD.TOWERS[sp.type], st = sp.st;
+ if (!(st.dmg > 0)) return 0; // support / control towers (Load Balancer, Sandbox) deal no damage; the bot never builds them
if (e.air ? !td.air : !td.ground) return 0;
const hit0 = Math.min(perHit(st.dmg, e.armor), e.h); // no credit for overkill
let dps = hit0 * st.rate, M = 1;