Co-op robustness, audio/a11y, new towers and enemies, Uplink rebalance
Co-op (QA'd with two to three real browsers, TCP-proxy chaos scenarios): - partner's tower changes are never dropped after a render stall or snapshot burst - half-open connections show "reconnecting" in ~6 s instead of 45-65 s - upgrade and next-wave are idempotent (stale commands refused), restart message, promoted host gets Play again, failed joins never kill a live game, listener leaks Audio / keyboard / a11y: - one Audio element per track, fade/stinger supersede tokens, play() retry on the next gesture, 5 s fallback to the synth, mute works everywhere, dialogs with role/aria-modal/focus handling, accessible names for sound/speed/pause New content: - enemies: Daemon (healer), Proxy (regenerating shield), Botnet (flyer swarm); waves weave them in from wave 9 (waves 1-8 unchanged) - towers: Sandbox (stun pulse), Load Balancer (fire-rate aura); hotkeys 1-9 - glyphs/shapes, stun/heal effects, gallery e2e that pixel-checks every kind Orbital Uplink rebalanced after playtesting (was affordable by wave ~6 and buyable in bulk from boss rewards): 1500 credits, upgrades 1200/2000/3200, and every Uplink already owned makes the next one 25% dearer to buy AND to upgrade (each tower remembers its multiplier, carried in the tower list as a 9th field). Shared TD.priceFor/upgradePrice so the UI shows exactly what the sim charges. Also: tablet/foldable viewports in the layout matrix (tolerant colour check), docs (README tower/enemy tables, PROTOCOL shield/stun/pm encodings, NEXT roadmap). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
parent
962189419a
commit
28502984ec
29 changed files with 3370 additions and 230 deletions
|
|
@ -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 = '<span class="key">' + def.key + '</span><canvas></canvas><span class="nm"></span><span class="cost"></span>';
|
||||
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 =
|
||||
'<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' +
|
||||
'<div class="desc"></div><div class="kv"></div><div class="actions">' +
|
||||
(wall ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
|
||||
'<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>' +
|
||||
(wall ? '' : '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>') +
|
||||
(aim ? '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>' : '') +
|
||||
'<button type="button" data-act="close" class="icon" aria-label="Close" title="Close"><svg class="ic"><use href="#i-x"/></svg></button></div>' +
|
||||
'<div class="byline">' + (wall ? '' : '<span id="infoKills"></span>') + (ownerP ? '<span class="dot" style="background:' + NW.SLOT_COLORS[ownerP.slot] + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
|
||||
'<div class="byline">' + (aim ? '<span id="infoKills"></span>' : '') + (ownerP ? '<span class="dot" style="background:' + slotColor(ownerP.slot) + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
|
||||
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 += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>';
|
||||
box.innerHTML = '<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div><div class="desc"></div><div class="kv">' + kv + '</div></div>';
|
||||
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 = '<div class="panel"><h4>Next · wave ' + n + '</h4><div class="wv">';
|
||||
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 = '<div class="panel"><h4>Room ' + (ctrl.room || '') + ' <span id="plPing" class="muted"></span></h4>';
|
||||
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + ' <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
|
||||
for (const p of ctrl.players) {
|
||||
html += '<div class="pl"><span class="dot" style="background:' + NW.SLOT_COLORS[p.slot] + '"></span><span class="pn"></span>' +
|
||||
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
|
||||
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
|
||||
}
|
||||
if (ctrl.players.length < 2) html += '<div class="muted small">Waiting for a partner… share the invite link.</div>';
|
||||
|
|
@ -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 = '<svg class="ic"><use href="#i-' + (Audio.muted ? 'mute' : 'sound') + '"/></svg>'; }
|
||||
// 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) => '<div><span>' + r[0] + '</span><b>' + r[1] + '</b></div>').join('');
|
||||
const remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
|
||||
$('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
|
||||
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + esc(r[1]) + '</b></div>').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 = '<svg class="ic"><use href="#i-' + (m ? 'mute' : 'sound') + '"/></svg>';
|
||||
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.');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue