Difficulty: - TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated create-room / newgame option, state carries it; solo menu picker and co-op lobby picker (44px segmented control, reachable on every layout), HUD/room/end-screen labels, best-wave record per map AND difficulty (Normal keeps the legacy key), Play again keeps the running game's difficulty for host and guest Balance (12 bot runs, deterministic, 48/48 games replay identically in QA): - Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open - credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at wave 30: 1309 -> 335 - IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only dies by wave 7); Mortar, Arc and Filter buffed - Orbital Uplink price step per owned unit 30% (buy and upgrade) - remaining imbalances documented in docs/BALANCE.md Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix reachability of the picker. 156 unit tests, 17 e2e scenarios. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
1321 lines
82 KiB
JavaScript
1321 lines
82 KiB
JavaScript
/*
|
||
* NETWALL main: screens, HUD, input (mouse + touch), lobby, glue between controllers, renderer and audio.
|
||
*/
|
||
(function (root) {
|
||
'use strict';
|
||
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 = {
|
||
get(k, d) { try { const v = root.localStorage.getItem(k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } },
|
||
set(k, v) { try { root.localStorage.setItem(k, JSON.stringify(v)); } catch (e) { /* ignore */ } },
|
||
del(k) { try { root.localStorage.removeItem(k); } catch (e) { /* ignore */ } },
|
||
};
|
||
const sess = {
|
||
get(k) { try { return root.sessionStorage.getItem(k); } catch (e) { return null; } },
|
||
set(k, v) { try { root.sessionStorage.setItem(k, v); } catch (e) { /* ignore */ } },
|
||
del(k) { try { root.sessionStorage.removeItem(k); } catch (e) { /* ignore */ } },
|
||
};
|
||
function randomId(n) {
|
||
const abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
|
||
let out = '';
|
||
const buf = new Uint8Array(n);
|
||
if (root.crypto && root.crypto.getRandomValues) root.crypto.getRandomValues(buf); else for (let i = 0; i < n; i++) buf[i] = Math.random() * 256;
|
||
for (let i = 0; i < n; i++) out += abc[buf[i] & 63];
|
||
return out;
|
||
}
|
||
function getPid() { let p = sess.get('nw.pid'); if (!p || !/^[A-Za-z0-9_-]{8,40}$/.test(p)) { p = randomId(22); sess.set('nw.pid', p); } return p; }
|
||
|
||
const REASONS = {
|
||
bounds: 'Out of bounds', obstacle: 'That node is dead. Pick another cell', occupied: 'Something is already there', spawn: "Can't build on a gateway",
|
||
core: "Can't build on the server", monster: 'A packet is in the way', blocks: 'That would seal the route. Leave a path!', gold: 'Not enough credits',
|
||
over: 'The game is over', no_tower: 'That tower no longer exists', max: 'Already at max level', not_host: 'Only the host can do that',
|
||
bad_map: 'Unknown map', bad_difficulty: 'Unknown difficulty', bad_type: 'Unknown tower', bad_cmd: 'Invalid command', not_won: 'Nothing to continue',
|
||
};
|
||
const MODE_NAMES = { first: 'First', last: 'Last', strong: 'Strongest', close: 'Closest' };
|
||
|
||
// ------------------------------------------------------------------ app state
|
||
const app = {
|
||
ctrl: null, renderer: null, screen: 'menu', inGame: false,
|
||
mapId: store.get('nw.map', 'open'),
|
||
difficulty: 'normal', // the player's pick for the NEXT game (the running game's is ctrl.view.difficulty); loaded below
|
||
selType: null, selTower: 0,
|
||
hover: null, pending: null, preview: null, valid: true, previewDirty: true, lastPreviewAt: 0,
|
||
zoomed: false, last: {}, names: {}, started: false, lastBossCheck: 0, bossMusic: false,
|
||
endShown: false, prevPlayers: null,
|
||
};
|
||
const ui = { hover: null, selType: null, selTower: 0, preview: null, valid: true, coop: false, names: {} };
|
||
|
||
const canvas = $('board');
|
||
const renderer = new NW.Renderer(canvas);
|
||
app.renderer = renderer;
|
||
if (!TD.MAPS[app.mapId]) app.mapId = 'open';
|
||
{ const d = store.get('nw.difficulty', 'normal'); app.difficulty = TD.isDifficulty(d) ? d : 'normal'; } // (a stored value that is not a difficulty any more is normal)
|
||
|
||
// ------------------------------------------------------------------ small UI helpers
|
||
let lastToast = '', lastToastAt = 0;
|
||
function toast(text, kind) {
|
||
const now = performance.now();
|
||
if (text === lastToast && now - lastToastAt < 900) return;
|
||
lastToast = text; lastToastAt = now;
|
||
const d = document.createElement('div');
|
||
d.className = 'toast' + (kind ? ' ' + kind : '');
|
||
d.textContent = text;
|
||
$('toasts').appendChild(d);
|
||
setTimeout(() => d.remove(), 2700);
|
||
while ($('toasts').children.length > 3) $('toasts').firstChild.remove();
|
||
}
|
||
let bannerT = 0;
|
||
function banner(text, boss) {
|
||
const b = $('banner');
|
||
b.textContent = text; b.className = 'banner show' + (boss ? ' boss' : '');
|
||
clearTimeout(bannerT);
|
||
bannerT = setTimeout(() => { b.className = 'banner' + (boss ? ' boss' : ''); }, 1500);
|
||
}
|
||
let hintText = '', hintKind = '';
|
||
function hint(text, kind) {
|
||
const h = $('hint'), ch = $('confirmHint');
|
||
hintText = text || ''; hintKind = kind || 'info';
|
||
if (!$('confirm').hidden && $('app').dataset.barrows !== '0') { // the touch build bar carries the route text itself: one overlay on the board instead of two (not when it is too small for it)
|
||
h.hidden = true; h.textContent = hintText; ch.textContent = hintText; ch.className = 'chint ' + hintKind; return; // (#hint keeps the text, hidden, for readers and tests)
|
||
}
|
||
if (!text) { h.hidden = true; return; }
|
||
h.hidden = false; h.textContent = text; h.className = 'hint ' + hintKind;
|
||
}
|
||
const fmtLen = (v) => String(Math.round(v / Math.max(1, ui.spawns || 1)));
|
||
|
||
function showOverlay(id) {
|
||
for (const o of document.querySelectorAll('.overlay')) {
|
||
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;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ controller switching
|
||
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;
|
||
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)
|
||
if (ctrl.kind === 'remote') renderPlayers(); // (the room header names the difficulty, which a new game may have changed)
|
||
});
|
||
adoptBoard(true);
|
||
}
|
||
function adoptBoard(force) {
|
||
const b = app.ctrl.board;
|
||
if (b && (force || renderer.board !== b)) {
|
||
renderer.setBoard(b);
|
||
$('app').style.setProperty('--aspect', b.cols + ' / ' + b.rows);
|
||
$('app').style.setProperty('--aspect-p', b.rows + ' / ' + b.cols);
|
||
ui.spawns = b.spawns.length;
|
||
resizeCanvas();
|
||
}
|
||
}
|
||
function resetSelection() {
|
||
app.selType = null; app.selTower = 0; app.pending = null; app.hover = null; app.preview = null; app.previewDirty = true;
|
||
syncPalette(); renderInfo(true); updateConfirm();
|
||
}
|
||
|
||
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, difficulty: app.difficulty });
|
||
useController(c);
|
||
app.inGame = true; app.started = true; app.endShown = false; app.last = {};
|
||
resetSelection(); setScreen('playing'); showOverlay(null);
|
||
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
|
||
renderInfo(true);
|
||
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) {
|
||
const c = new NW.LocalController({ map: mapId });
|
||
c.paused = true;
|
||
useController(c);
|
||
app.inGame = false;
|
||
releaseWakeLock(); // nobody is playing: the screen may sleep again (code-20)
|
||
}
|
||
|
||
// 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(); }
|
||
if (!keep) { sess.del('nw.room'); store.del('nw.session'); clearRoomFromUrl(); }
|
||
if (!silent) { /* caller handles screens */ }
|
||
}
|
||
function clearRoomFromUrl() {
|
||
try { if (root.location.search) root.history.replaceState(null, '', root.location.pathname); } catch (e) { /* ignore */ }
|
||
}
|
||
|
||
// ------------------------------------------------------------------ events from the controller
|
||
function onEvents(evs) {
|
||
renderer.addEvents(evs);
|
||
for (const e of evs) {
|
||
switch (e.e) {
|
||
case 'place': Audio.sfx(e.type === 'wall' ? 'wall' : 'place'); break;
|
||
case 'sell': Audio.sfx('sell'); break;
|
||
case 'up': Audio.sfx('up'); break;
|
||
case 'shot': Audio.sfx('shot_' + e.k); break;
|
||
case 'arc': Audio.sfx('arc'); break;
|
||
case 'boom': Audio.sfx('boom'); break;
|
||
case 'kill': Audio.sfx('kill'); break;
|
||
case 'leak': Audio.sfx('leak'); break;
|
||
case 'wave': banner(e.boss ? 'BOSS WAVE ' + e.n : 'WAVE ' + e.n, e.boss); Audio.sfx(e.boss ? 'boss' : 'wave'); break;
|
||
case 'clear': toast('Wave ' + e.n + ' cleared +' + e.bonus + ' credits', 'good'); Audio.sfx('clear'); break;
|
||
default: break;
|
||
}
|
||
}
|
||
}
|
||
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();
|
||
if (now - errSfxAt > 450 && !(painting && strokeErr)) { errSfxAt = now; Audio.sfx('error'); }
|
||
if (painting) strokeErr = true;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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 = '';
|
||
pal.classList.toggle('many', TD.TOWER_ORDER.length > 6);
|
||
for (const type of TD.TOWER_ORDER) {
|
||
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 + ', ' + 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(priceOf(type));
|
||
b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); });
|
||
pal.appendChild(b);
|
||
}
|
||
drawPaletteIcons(); updatePaletteHint();
|
||
}
|
||
// A palette that does not fit scrolls (sideways when stacked, down in the narrow landscape column). data-more says on which
|
||
// side more tiles are hidden; the CSS fades that edge so the player can see there is more.
|
||
function updatePaletteHint() {
|
||
const p = $('palette'); let more = '';
|
||
const edge = (pos, size, view) => { const a = pos > 2, b = pos < size - view - 2; return a && b ? 'both' : a ? 'start' : b ? 'end' : ''; };
|
||
if (p.scrollWidth > p.clientWidth + 2) more = edge(p.scrollLeft, p.scrollWidth, p.clientWidth);
|
||
else if (p.scrollHeight > p.clientHeight + 2) more = edge(p.scrollTop, p.scrollHeight, p.clientHeight);
|
||
if (more) { if (p.dataset.more !== more) p.dataset.more = more; } else if (p.dataset.more) delete p.dataset.more;
|
||
}
|
||
function revealTile(b) { // scroll the palette (only the palette, never the page) so this tile is fully in view
|
||
const p = $('palette'); if (!b) return;
|
||
const pr = p.getBoundingClientRect(), br = b.getBoundingClientRect(), m = 34; // keep clear of the edge fade
|
||
if (p.scrollWidth > p.clientWidth + 2) {
|
||
if (br.left < pr.left + m) p.scrollLeft -= pr.left + m - br.left; else if (br.right > pr.right - m) p.scrollLeft += br.right - (pr.right - m);
|
||
} else if (p.scrollHeight > p.clientHeight + 2) {
|
||
if (br.top < pr.top + m) p.scrollTop -= pr.top + m - br.top; else if (br.bottom > pr.bottom - m) p.scrollTop += br.bottom - (pr.bottom - m);
|
||
}
|
||
updatePaletteHint();
|
||
}
|
||
$('palette').addEventListener('scroll', updatePaletteHint, { passive: true });
|
||
function drawPaletteIcons() {
|
||
for (const b of $('palette').children) NW.drawIcon(b.querySelector('canvas'), b.dataset.type, 1);
|
||
}
|
||
function syncPalette() {
|
||
for (const b of $('palette').children) {
|
||
const sel = b.dataset.type === app.selType;
|
||
b.classList.toggle('sel', sel);
|
||
b.setAttribute('aria-pressed', sel ? 'true' : 'false');
|
||
if (sel) revealTile(b);
|
||
}
|
||
}
|
||
function selectType(type) {
|
||
app.selType = type; app.selTower = 0; app.pending = null; app.previewDirty = true;
|
||
syncPalette(); renderInfo(true); updateConfirm();
|
||
if (!type) { ui.preview = null; hint(null); }
|
||
}
|
||
function selectTower(id) {
|
||
app.selTower = id; app.selType = null; app.pending = null; app.preview = null; ui.preview = null;
|
||
syncPalette(); renderInfo(true); updateConfirm(); hint(null);
|
||
}
|
||
|
||
function statsFor(type, lv) {
|
||
const L = TD.TOWERS[type].levels[lv], out = [];
|
||
if (L.dmg) out.push(['Damage', String(Math.round(L.dmg))]);
|
||
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
|
||
// would replace nodes is deferred while a pointer is down inside the panel.
|
||
const info = { shape: '', sig: '', lv: 0, pressed: false, dirty: false };
|
||
|
||
function renderInfo(force) {
|
||
const box = $('info'), ctrl = app.ctrl, view = ctrl.view;
|
||
let tower = null, ownerP = null, shape = '';
|
||
if (app.selTower) {
|
||
tower = view.towers.find((t) => t.id === app.selTower) || null;
|
||
if (!tower) app.selTower = 0;
|
||
}
|
||
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 + ':' + 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', 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>' +
|
||
(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">' + (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;
|
||
syncInfo();
|
||
} else {
|
||
const def = TD.TOWERS[app.selType];
|
||
let kv = '';
|
||
for (const row of statsFor(app.selType, 0)) kv += '<div class="kvp"><span>' + row[0] + '</span><span>' + row[1] + '</span></div>';
|
||
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 = priceOf(app.selType) + ' credits';
|
||
box.querySelector('.desc').textContent = def.desc;
|
||
NW.drawIcon(box.querySelector('canvas'), app.selType, 1);
|
||
}
|
||
}
|
||
// numbers of the selected tower: only text/disabled changes, never a replaced element
|
||
function syncInfo() {
|
||
if (!app.selTower) return;
|
||
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 ? 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);
|
||
if (sig === info.sig) return;
|
||
info.sig = sig;
|
||
const setText = (el, v) => { if (el && el.textContent !== v) el.textContent = v; };
|
||
if (info.lv !== t.level) { // level changed: stats table and icon
|
||
info.lv = t.level;
|
||
const cur = statsFor(t.type, i), nxt = canUp ? statsFor(t.type, i + 1) : null;
|
||
let kv = '';
|
||
cur.forEach((row, k) => {
|
||
const n = nxt && nxt[k] && nxt[k][1] !== row[1] ? ' <span class="up">→ ' + nxt[k][1] + '</span>' : '';
|
||
kv += '<div class="kvp"><span>' + row[0] + '</span><span>' + row[1] + n + '</span></div>';
|
||
});
|
||
if (!wall) kv += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>';
|
||
box.querySelector('.kv').innerHTML = kv;
|
||
setText(box.querySelector('.lv'), wall ? '' : 'Level ' + t.level + ' / ' + def.levels.length);
|
||
NW.drawIcon(box.querySelector('canvas'), t.type, t.level);
|
||
}
|
||
const up = box.querySelector('[data-act="up"]');
|
||
if (up) {
|
||
setText(up.querySelector('.w'), canUp ? 'Upgrade' : 'Max level');
|
||
setText(up.querySelector('.cost'), canUp ? String(upCost) : '');
|
||
up.disabled = !affordable;
|
||
up.setAttribute('aria-label', canUp ? 'Upgrade for ' + upCost + ' credits' : 'Max level');
|
||
}
|
||
const sell = box.querySelector('[data-act="sell"]');
|
||
setText(sell.querySelector('.cost'), String(sellVal));
|
||
sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits');
|
||
const mode = box.querySelector('[data-act="mode"]');
|
||
if (mode) { setText(mode.querySelector('.mv'), MODE_NAMES[t.mode]); mode.setAttribute('aria-label', 'Target: ' + MODE_NAMES[t.mode] + '. Tap to change'); }
|
||
setText(box.querySelector('#infoKills'), t.kills + (t.kills === 1 ? ' kill' : ' kills'));
|
||
}
|
||
let infoTimer = 0;
|
||
$('info').addEventListener('pointerdown', () => { clearTimeout(infoTimer); info.pressed = true; }); // (a new press cancels the previous release timer)
|
||
const infoRelease = () => {
|
||
if (!info.pressed) return;
|
||
clearTimeout(infoTimer);
|
||
infoTimer = setTimeout(() => { info.pressed = false; if (info.dirty) renderInfo(false); }, 90); // after the click has been delivered
|
||
};
|
||
document.addEventListener('pointerup', infoRelease, true);
|
||
document.addEventListener('pointercancel', infoRelease, true);
|
||
$('info').addEventListener('click', (e) => {
|
||
const btn = e.target.closest('button[data-act]'); if (!btn || !app.selTower) return;
|
||
info.pressed = false;
|
||
const ctrl = app.ctrl, tower = ctrl.view.towers.find((t) => t.id === app.selTower);
|
||
if (!tower) return;
|
||
Audio.sfx('click');
|
||
switch (btn.dataset.act) {
|
||
case 'up': ctrl.send({ c: 'upgrade', id: tower.id }); break;
|
||
case 'sell': ctrl.send({ c: 'sell', id: tower.id }); app.selTower = 0; renderInfo(true); app.previewDirty = true; break;
|
||
case 'close': selectTower(0); break;
|
||
case 'mode': {
|
||
const modes = TD.TARGET_MODES; ctrl.send({ c: 'target', id: tower.id, mode: modes[(modes.indexOf(tower.mode) + 1) % modes.length] });
|
||
break;
|
||
}
|
||
default: break;
|
||
}
|
||
});
|
||
|
||
function renderWavePanel(view) {
|
||
const n = view.wave + 1;
|
||
const dif = viewDifficulty(view);
|
||
const key = n + ':' + view.state + ':' + dif;
|
||
if (app.last.waveKey === key) return;
|
||
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 + '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span></h4><div class="wv">';
|
||
let air = false;
|
||
for (const g of sum) {
|
||
const d = TD.ENEMIES[g.k];
|
||
if (d.air) air = true;
|
||
html += '<span class="e" title="' + d.name + (d.air ? ' (flies)' : '') + '"><i class="sh-' + g.k + '" style="--c:' + d.color + '"></i>' + g.c + '× ' + d.name + '</span>';
|
||
}
|
||
if (air) html += '<span class="tag air">AIR</span>';
|
||
if (n % 10 === 0) html += '<span class="tag boss">BOSS</span>';
|
||
html += '</div></div>';
|
||
box.innerHTML = html;
|
||
}
|
||
|
||
function onPlayers(list) {
|
||
const ctrl = app.ctrl;
|
||
ui.names = {}; for (const p of list) ui.names[p.slot] = p.name;
|
||
ui.coop = list.length > 1;
|
||
// join / leave toasts
|
||
if (app.prevPlayers) {
|
||
for (const p of list) if (!app.prevPlayers.find((q) => q.pid === p.pid)) { toast(p.name + ' joined', 'good'); Audio.sfx('join'); }
|
||
for (const q of app.prevPlayers) if (!list.find((p) => p.pid === q.pid)) toast(q.name + ' left');
|
||
for (const p of list) { const q = app.prevPlayers.find((x) => x.pid === p.pid); if (q && q.online && !p.online) toast(p.name + ' lost connection'); if (q && !q.online && p.online) toast(p.name + ' is back', 'good'); }
|
||
}
|
||
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;
|
||
const dif = viewDifficulty(ctrl.view);
|
||
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span> <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:' + 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>';
|
||
html += '<div class="actions"><button type="button" data-act="invite"><svg class="ic"><use href="#i-share"/></svg>Invite</button><button type="button" data-act="leave" class="danger">Leave</button></div></div>';
|
||
box.innerHTML = html;
|
||
const names = box.querySelectorAll('.pn');
|
||
ctrl.players.forEach((p, i) => { names[i].textContent = p.name; });
|
||
}
|
||
$('players').addEventListener('click', (e) => {
|
||
const b = e.target.closest('button[data-act]'); if (!b) return;
|
||
if (b.dataset.act === 'invite') invite();
|
||
if (b.dataset.act === 'leave') { leaveToMenu(); }
|
||
});
|
||
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; }
|
||
const done = () => toast('Invite link copied', 'good');
|
||
if (root.navigator.clipboard && root.navigator.clipboard.writeText) root.navigator.clipboard.writeText(url).then(done, () => root.prompt('Copy this link', url));
|
||
else root.prompt('Copy this link', url);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ HUD
|
||
function updateHud(view) {
|
||
const L = app.last, ctrl = app.ctrl;
|
||
if (L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); }
|
||
if (L.lives !== view.lives) {
|
||
L.lives = view.lives; $('vLives').textContent = String(view.lives);
|
||
$('statLives').classList.toggle('low', view.maxLives > 0 && view.lives <= view.maxLives * 0.25);
|
||
}
|
||
if (L.wave !== view.wave) { L.wave = view.wave; $('vWave').textContent = String(view.wave); }
|
||
if (L.winWave !== view.winWave) { L.winWave = view.winWave; $('vWaveMax').textContent = view.winWave ? '/' + view.winWave : ''; }
|
||
const idle = view.queued === 0 && view.monsters.length === 0;
|
||
const timer = view.auto && view.nextWaveIn >= 0 ? ' · ' + Math.ceil(view.nextWaveIn) + 's' : '';
|
||
const wtxt = 'Wave ' + (view.wave + 1) + timer;
|
||
if (L.wtxt !== wtxt) { L.wtxt = wtxt; $('btnWaveText').textContent = wtxt; }
|
||
const wdis = view.state !== 'playing';
|
||
if (L.wdis !== wdis) { L.wdis = wdis; $('btnWave').disabled = wdis; }
|
||
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 + '×'; $('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'); // 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); }
|
||
// palette affordability
|
||
const gold = view.gold;
|
||
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');
|
||
chip.hidden = false;
|
||
$('netRoom').textContent = ctrl.room || '';
|
||
const alone = ctrl.players.length < 2;
|
||
if (L.alone !== alone || L.room !== ctrl.room) {
|
||
L.alone = alone; L.room = ctrl.room; chip.classList.toggle('waiting', alone);
|
||
chip.setAttribute('aria-label', 'Co-op room ' + (ctrl.room || '') + (alone ? '. Waiting for a partner: tap to invite them' : '. Tap to invite your partner'));
|
||
}
|
||
const p = ctrl.rtt ? ctrl.rtt + ' ms' : '';
|
||
if (L.ping !== p) { L.ping = p; $('netPing').textContent = p; chip.classList.toggle('bad', ctrl.rtt > 220); const pp = $('plPing'); if (pp) pp.textContent = p ? '\u00b7 ' + p : ''; }
|
||
}
|
||
renderWavePanel(view);
|
||
syncInfo();
|
||
}
|
||
|
||
function endScreen(view) {
|
||
const ctrl = app.ctrl;
|
||
const won = view.state === 'won';
|
||
$('endTitle').textContent = won ? 'Server secured!' : 'Breach!';
|
||
$('endTitle').style.color = won ? 'var(--green)' : 'var(--red)';
|
||
const dif = viewDifficulty(view), bk = bestKey(ctrl.board.mapId, dif);
|
||
const best = +store.get(bk, 0) || 0;
|
||
if (view.wave > best) store.set(bk, 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], ['Difficulty', diffName(dif)], ['Best on ' + diffName(dif), Math.max(best, view.wave)]];
|
||
$('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) {
|
||
const r = canvas.getBoundingClientRect();
|
||
return renderer.screenToCell(e.clientX - r.left, e.clientY - r.top);
|
||
}
|
||
function placeAt(cell) {
|
||
const ctrl = app.ctrl;
|
||
if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) return false;
|
||
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;
|
||
return true;
|
||
}
|
||
function refreshPreview(force) {
|
||
const ctrl = app.ctrl, now = performance.now();
|
||
const cell = app.pending || app.hover;
|
||
if (cell && app.selType && ui.noGhost) { if (ui.preview || !$('hint').hidden) { ui.preview = null; ui.valid = true; hint(null); } return; }
|
||
if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) {
|
||
if (ui.preview || !$('hint').hidden) { ui.preview = null; ui.valid = true; hint(null); }
|
||
return;
|
||
}
|
||
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 = 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');
|
||
else if (poor) hint('Need ' + cost + ' credits (have ' + ctrl.view.gold + ')', 'bad');
|
||
else {
|
||
const d = Math.round(pv.after - pv.before) / 1;
|
||
const a = Math.round(pv.before / (ui.spawns || 1)), b = Math.round(pv.after / (ui.spawns || 1));
|
||
hint(b === a ? 'Route ' + a : 'Route ' + a + ' → ' + b + (b > a ? ' (+' + (b - a) + ')' : ' (' + (b - a) + ')'), d > 0.5 ? 'ok' : 'info');
|
||
}
|
||
}
|
||
|
||
// touch placement bar
|
||
function updateConfirm() {
|
||
const show = !!(app.pending && app.selType && app.selType !== 'wall');
|
||
$('confirm').hidden = !show;
|
||
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);
|
||
}
|
||
// Where the floating bars go (the touch confirm bar and the selected-tower action bar): on the half of the stage away from the
|
||
// cell they act on, so they never cover it. Runs every frame (cheap, writes only on change) so rotation, resize, pan and zoom
|
||
// keep it right (touch-14). The stage rectangle goes into CSS variables because the tower bar is position:fixed.
|
||
// The bar does not hop to the other half while the same cell is being worked on (nudging across the middle must not move the buttons
|
||
// out from under the thumb): it flips only when the cell would end up under it.
|
||
let barKey = '', barSide = '', barSubject = '';
|
||
function layoutBars(force) {
|
||
const r = $('stage').getBoundingClientRect(), a = $('app'), conf = !$('confirm').hidden && !!app.pending;
|
||
let cell = null;
|
||
if (conf) cell = app.pending;
|
||
else if (app.selTower && app.ctrl) cell = app.ctrl.view.towers.find((t) => t.id === app.selTower) || null;
|
||
let side = '';
|
||
if (cell) {
|
||
const sp = renderer.cellToScreen(cell.x, cell.y), bar = conf ? $('confirm') : $('info').querySelector('.actions');
|
||
const guard = (bar ? bar.offsetHeight : 54) + 8 + renderer.cellSizePx() / 2 + 8; // the strip a bar there would cover, plus the cell itself
|
||
const hit = (s) => (s === 'top' ? sp.y < guard : sp.y > r.height - guard);
|
||
const subject = conf ? 'pending' : 'tower' + app.selTower;
|
||
const mid = sp.y > r.height * 0.5 ? 'top' : 'bottom', other = mid === 'top' ? 'bottom' : 'top';
|
||
side = subject === barSubject && barSide && !hit(barSide) ? barSide : hit(mid) && !hit(other) ? other : mid;
|
||
barSubject = subject; barSide = side;
|
||
} else { barSubject = ''; barSide = ''; }
|
||
const key = side + '|' + (conf ? 1 : 0) + '|' + Math.round(r.left) + ',' + Math.round(r.top) + ',' + Math.round(r.width) + ',' + Math.round(r.height);
|
||
if (!force && key === barKey) return;
|
||
barKey = key;
|
||
const st = a.style;
|
||
st.setProperty('--st-l', r.left.toFixed(1) + 'px'); st.setProperty('--st-t', r.top.toFixed(1) + 'px');
|
||
st.setProperty('--st-w', r.width.toFixed(1) + 'px'); st.setProperty('--st-h', r.height.toFixed(1) + 'px');
|
||
if (side) a.dataset.bar = side; else delete a.dataset.bar;
|
||
if (conf) a.dataset.conf = '1'; else delete a.dataset.conf; // the build bar is taller than the tower bar (it has the nudge row)
|
||
a.dataset.barrows = r.width >= 484 ? '1' : r.height >= 262 ? '2' : '0'; // build bar: nudge buttons in the bar's row on a wide stage, a second row on a phone, no text at all on a tiny one
|
||
a.dataset.barw = r.width < 440 ? 's' : 'm'; // narrow stage: the bar drops the words, keeps icons + numbers
|
||
$('confirm').classList.toggle('top', side === 'top');
|
||
}
|
||
$('btnConfirmBuild').addEventListener('click', () => { if (app.pending && placeAt(app.pending)) setPending(null); });
|
||
$('btnCancelBuild').addEventListener('click', () => { selectType(null); });
|
||
|
||
// ------------------------------------------------------------------ pointer input
|
||
// Touch rules. pointerdown never builds and never selects: every pinch starts with one finger down. A TAP (the finger stays within
|
||
// TAP_SLOP of where it landed and lifts before the long press) acts on the cell it LANDED on, when it lifts. A DRAG acts as soon as it
|
||
// passes the slop: it paints a Firewall line, aims the pending turret, or pans a zoomed board. A second finger turns the whole gesture
|
||
// into pinch/pan and undoes whatever the first finger had begun; extra fingers (a palm) are ignored. A long press pings the map,
|
||
// whatever is armed, and never builds. Cells are only 12 to 20 px on a phone, which is why the build bar also has nudge buttons.
|
||
const TAP_SLOP = 10, MOUSE_SLOP = 8, LONG_MS = 520;
|
||
const ptrs = new Map();
|
||
let painting = false, paintCell = null, panning = false, longT = 0, longFired = false, rightDown = null, pinch = null;
|
||
let multi = false; // a second finger landed: pinch/pan owns the gesture until every finger is up
|
||
let tg = null; // the one-finger touch gesture in progress: { id, cell (where it landed), pend (pending cell then), hover0, dragged }
|
||
let tapSelectOnUp = false;
|
||
let tapTowerId = 0; // a wall stroke that began on a turret: a stationary click or tap selects that turret instead (touch-17)
|
||
let pendFree = true; // the pending cell held no tower when it was chosen (a tower appearing there later is the partner's, coop-7)
|
||
let curSent = false; // a touch cursor is showing on the partner's board
|
||
let strokeErr = false; // this wall stroke already played its error sound (touch-16)
|
||
|
||
function cancelLong() { clearTimeout(longT); longT = 0; }
|
||
function setHover(cell) {
|
||
const c = cell && app.ctrl.board.inBounds(cell.x, cell.y) ? { x: cell.x, y: cell.y } : null;
|
||
if (!c && !app.hover) return;
|
||
if (c && app.hover && c.x === app.hover.x && c.y === app.hover.y) return;
|
||
app.hover = c; app.previewDirty = true;
|
||
}
|
||
// The partner's view of where this touch is aiming. `force` skips the 70 ms throttle (the last position must get through).
|
||
function touchCursor(cell, force) {
|
||
if (!cell || !app.ctrl.board.inBounds(cell.x, cell.y)) return;
|
||
app.ctrl.sendCursor(cell.x + 0.5, cell.y + 0.5, force); curSent = true;
|
||
}
|
||
function clearCursor() { if (curSent) { curSent = false; app.ctrl.sendCursor(null, null); } }
|
||
// The only way the touch-pending build cell changes. An off-board cell is no cell (code-23).
|
||
function setPending(cell, commit) {
|
||
const c = cell && app.ctrl.board.inBounds(cell.x, cell.y) ? { x: cell.x, y: cell.y } : null;
|
||
app.pending = c; pendFree = !c || !towerAtCell(c); app.previewDirty = true;
|
||
if (c) { setHover(c); touchCursor(c, commit); }
|
||
updateConfirm();
|
||
}
|
||
// the finger-down preview ends without a commit (long press, second finger, cancel): hover goes back, the touch cursor goes away
|
||
function unaim() {
|
||
if (tg) { app.hover = tg.hover0; app.previewDirty = true; }
|
||
if (!app.pending) clearCursor();
|
||
}
|
||
function abortTouch() { // forget what the first finger began: a second finger landed, or the touch was cancelled
|
||
cancelLong(); painting = false; paintCell = null; tapSelectOnUp = false; tapTowerId = 0; longFired = false;
|
||
if (tg) { if (tg.dragged) setPending(tg.pend); unaim(); tg = null; }
|
||
}
|
||
function startStroke(cell) { painting = true; paintCell = cell; strokeErr = false; }
|
||
function seedPinch() { // pinch/pan between the first two fingers only; the pair is re-seeded when one of them lifts
|
||
const ids = [...ptrs.keys()].slice(0, 2), a = ptrs.get(ids[0]), b = ptrs.get(ids[1]);
|
||
pinch = { ids, d: Math.hypot(a.x - b.x, a.y - b.y) || 1, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
|
||
}
|
||
// nudge buttons: move the pending cell one cell in a screen direction (rotation-safe), and keep it in view when zoomed in
|
||
function nudge(dx, dy) {
|
||
const p = app.pending; if (!p) return;
|
||
const c = renderer.stepCell(p.x, p.y, dx, dy);
|
||
if (!app.ctrl.board.inBounds(c.x, c.y)) return; // the edge of the board: stay put
|
||
setPending(c, true);
|
||
if (renderer.zoom > 1.01) {
|
||
const s = renderer.cellToScreen(c.x, c.y), m = renderer.cellSizePx() * 1.5;
|
||
const mx = s.x < m ? m - s.x : s.x > renderer.W - m ? renderer.W - m - s.x : 0, my = s.y < m ? m - s.y : s.y > renderer.H - m ? renderer.H - m - s.y : 0;
|
||
if (mx || my) { renderer.panBy(mx, my); updateFit(); }
|
||
}
|
||
}
|
||
$('nudge').addEventListener('click', (e) => {
|
||
const b = e.target.closest('button[data-dx]'); if (!b) return;
|
||
Audio.sfx('click'); nudge(+b.dataset.dx, +b.dataset.dy);
|
||
});
|
||
|
||
function paintLine(from, to) { // place on every cell crossed by a fast drag (Bresenham)
|
||
let x0 = from.x, y0 = from.y; const x1 = to.x, y1 = to.y;
|
||
const dx = Math.abs(x1 - x0), dy = -Math.abs(y1 - y0), sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1;
|
||
let err = dx + dy;
|
||
for (let guard = 0; guard < 80; guard++) {
|
||
if (x0 !== from.x || y0 !== from.y) placeAt({ x: x0, y: y0 });
|
||
if (x0 === x1 && y0 === y1) break;
|
||
const e2 = 2 * err;
|
||
if (e2 >= dy) { err += dy; x0 += sx; }
|
||
if (e2 <= dx) { err += dx; y0 += sy; }
|
||
}
|
||
}
|
||
function markAt(cell) {
|
||
if (!cell || !app.ctrl.board.inBounds(cell.x, cell.y)) return;
|
||
app.ctrl.sendMark(cell.x, cell.y);
|
||
if (navigator.vibrate) try { navigator.vibrate(15); } catch (e) { /* ignore */ }
|
||
}
|
||
function towerAtCell(cell) {
|
||
return app.ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y) || null;
|
||
}
|
||
function tapSelect(cell) {
|
||
const ctrl = app.ctrl;
|
||
if (!ctrl.board.inBounds(cell.x, cell.y)) { selectTower(0); return; }
|
||
const t = ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y);
|
||
if (t) { selectTower(t.id); Audio.sfx('click'); } else selectTower(0);
|
||
}
|
||
|
||
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
|
||
canvas.addEventListener('pointerdown', (e) => {
|
||
if (!app.inGame) return;
|
||
e.preventDefault();
|
||
try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ }
|
||
Audio.unlock();
|
||
const touch = e.pointerType !== 'mouse';
|
||
if (touch && e.isPrimary) { ptrs.clear(); abortTouch(); multi = false; pinch = null; } // (a lost pointerup must never leave half a gesture behind)
|
||
const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top;
|
||
ptrs.set(e.pointerId, { x: sx, y: sy, sx, sy, type: e.pointerType, moved: false, btn: e.button });
|
||
if (ptrs.size >= 2) { // second finger: pinch/pan; whatever the first finger had begun is undone, a third finger is ignored
|
||
if (!multi) { multi = true; abortTouch(); }
|
||
if (!pinch) seedPinch();
|
||
return;
|
||
}
|
||
const cell = renderer.screenToCell(sx, sy);
|
||
longFired = false;
|
||
if (!touch) {
|
||
if (e.button === 2) { rightDown = { x: sx, y: sy, moved: false }; return; }
|
||
if (e.button === 1) { panning = true; return; }
|
||
if (e.altKey) { markAt(cell); return; }
|
||
const ex = towerAtCell(cell);
|
||
if (app.selType === 'wall' && ex && ex.type !== 'wall') { setHover(cell); startStroke(cell); tapTowerId = ex.id; } // a Firewall stroke may start on a turret; a plain click selects it
|
||
else if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) { selectTower(ex.id); Audio.sfx('click'); }
|
||
else if (app.selType) {
|
||
setHover(cell);
|
||
if (!ex) placeAt(cell);
|
||
if (app.selType === 'wall') startStroke(cell);
|
||
} else {
|
||
tapSelectOnUp = true; panning = renderer.zoom > 1.01;
|
||
}
|
||
return;
|
||
}
|
||
// touch / pen: remember what is under the finger and preview it; commit nothing until the finger lifts or drags
|
||
tg = { id: e.pointerId, cell, pend: app.pending ? { x: app.pending.x, y: app.pending.y } : null, hover0: app.hover, dragged: false };
|
||
if (app.selType) { setHover(cell); touchCursor(cell); }
|
||
tapSelectOnUp = !app.selType;
|
||
longT = setTimeout(() => { // a long press pings the map, whatever is armed
|
||
longT = 0; if (!tg || multi || tg.id !== e.pointerId) return;
|
||
longFired = true; tapSelectOnUp = false; unaim(); markAt(tg.cell);
|
||
}, LONG_MS);
|
||
});
|
||
|
||
canvas.addEventListener('pointermove', (e) => {
|
||
const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top;
|
||
const p = ptrs.get(e.pointerId);
|
||
if (!app.inGame) return;
|
||
if (!p) { // hovering mouse
|
||
if (e.pointerType === 'mouse') {
|
||
const cell = renderer.screenToCell(sx, sy);
|
||
setHover(cell);
|
||
app.ctrl.sendCursor(cell.fx, cell.fy);
|
||
}
|
||
return;
|
||
}
|
||
const dx = sx - p.x, dy = sy - p.y;
|
||
p.x = sx; p.y = sy;
|
||
if (Math.hypot(sx - p.sx, sy - p.sy) > (e.pointerType === 'mouse' ? MOUSE_SLOP : TAP_SLOP)) p.moved = true;
|
||
if (pinch) {
|
||
if (!pinch.ids.includes(e.pointerId)) return; // a third finger (palm) neither pans nor zooms
|
||
const a = ptrs.get(pinch.ids[0]), b = ptrs.get(pinch.ids[1]); if (!a || !b) return;
|
||
const d = Math.hypot(a.x - b.x, a.y - b.y) || 1, mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
|
||
renderer.panBy(mx - pinch.mx, my - pinch.my);
|
||
renderer.setZoom(renderer.zoom * d / pinch.d, mx, my);
|
||
pinch.d = d; pinch.mx = mx; pinch.my = my;
|
||
updateFit();
|
||
return;
|
||
}
|
||
if (multi) return; // one finger of a pinch is still down: it must not paint, aim or pan
|
||
const cell = renderer.screenToCell(sx, sy);
|
||
if (e.pointerType === 'mouse') {
|
||
if (rightDown) { if (Math.hypot(sx - rightDown.x, sy - rightDown.y) > 5) rightDown.moved = true; if (rightDown.moved) { renderer.panBy(dx, dy); updateFit(); } rightDown.x = rightDown.moved ? sx : rightDown.x; return; }
|
||
if (panning && p.moved) { renderer.panBy(dx, dy); updateFit(); tapSelectOnUp = false; return; }
|
||
setHover(cell);
|
||
app.ctrl.sendCursor(cell.fx, cell.fy);
|
||
if (painting && app.selType === 'wall' && paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { tapTowerId = 0; paintLine(paintCell, cell); paintCell = cell; }
|
||
return;
|
||
}
|
||
// touch / pen
|
||
if (!tg || tg.id !== e.pointerId || !p.moved) return; // inside the tap slop it is still a tap: nothing moves
|
||
cancelLong(); tapSelectOnUp = false;
|
||
if (app.selType === 'wall') {
|
||
if (!painting) { // the stroke starts here; paintLine skips its first cell, so the origin goes in now (unless a tower is on it)
|
||
startStroke(tg.cell);
|
||
if (!towerAtCell(tg.cell)) placeAt(tg.cell);
|
||
}
|
||
setHover(cell);
|
||
if (cell.x !== paintCell.x || cell.y !== paintCell.y) { paintLine(paintCell, cell); paintCell = cell; }
|
||
} else if (app.selType) { // aim: the pending cell follows the finger (off the board it stays on the last cell)
|
||
if (app.ctrl.board.inBounds(cell.x, cell.y)) { tg.dragged = true; setPending(cell); }
|
||
} else if (renderer.zoom > 1.01) {
|
||
renderer.panBy(dx, dy); updateFit();
|
||
}
|
||
});
|
||
|
||
function endPointer(e) {
|
||
const p = ptrs.get(e.pointerId), cancelled = e.type === 'pointercancel';
|
||
ptrs.delete(e.pointerId);
|
||
try { canvas.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ }
|
||
if (!p || !app.inGame) { if (!ptrs.size) { multi = false; pinch = null; } return; }
|
||
cancelLong();
|
||
if (e.pointerType === 'mouse') {
|
||
const r = canvas.getBoundingClientRect(), cell = renderer.screenToCell(e.clientX - r.left, e.clientY - r.top);
|
||
if (e.button === 2 && rightDown) { if (!rightDown.moved) { selectType(null); selectTower(0); } rightDown = null; return; }
|
||
if (e.button === 1) { panning = false; return; }
|
||
if (tapSelectOnUp && !p.moved && e.type === 'pointerup') tapSelect(cell);
|
||
if (tapTowerId && !p.moved && e.type === 'pointerup') { selectTower(tapTowerId); Audio.sfx('click'); }
|
||
tapSelectOnUp = false; tapTowerId = 0; painting = false; panning = false;
|
||
return;
|
||
}
|
||
// touch / pen
|
||
if (pinch && pinch.ids.includes(e.pointerId)) { if (ptrs.size >= 2) seedPinch(); else pinch = null; }
|
||
const wasMulti = multi;
|
||
if (!ptrs.size) multi = false;
|
||
if (wasMulti) return; // the end of a pinch/pan is never a tap
|
||
const g = tg;
|
||
if (!g || g.id !== e.pointerId) return;
|
||
if (cancelled) { abortTouch(); return; } // pointercancel: no action, nothing half done
|
||
tg = null;
|
||
const wasPainting = painting; painting = false; paintCell = null;
|
||
if (wasPainting || p.moved || longFired) { // a stroke, an aim drag, a pan or a long press: lifting the finger adds nothing
|
||
tapSelectOnUp = false;
|
||
if (longFired) unaim(); else if (!app.pending) clearCursor();
|
||
return;
|
||
}
|
||
// a tap, on the cell the finger landed on (not wherever it drifted to)
|
||
const cell = g.cell, ex = towerAtCell(cell);
|
||
if (app.selType === 'wall') {
|
||
if (ex && ex.type !== 'wall') { selectTower(ex.id); Audio.sfx('click'); } // (a drag that starts on a turret is a stroke: it keeps the tool)
|
||
else if (!ex) placeAt(cell);
|
||
} else if (app.selType) {
|
||
if (ex) { selectTower(ex.id); Audio.sfx('click'); }
|
||
else if (!app.ctrl.board.inBounds(cell.x, cell.y)) setPending(null);
|
||
else if (g.pend && g.pend.x === cell.x && g.pend.y === cell.y) { if (placeAt(cell)) setPending(null); } // tapping the previewed cell again builds
|
||
else setPending(cell, true);
|
||
} else if (tapSelectOnUp) tapSelect(cell);
|
||
tapSelectOnUp = false;
|
||
if (!app.pending) clearCursor();
|
||
}
|
||
canvas.addEventListener('pointerup', endPointer);
|
||
canvas.addEventListener('pointercancel', endPointer);
|
||
canvas.addEventListener('pointerleave', (e) => { if (e.pointerType === 'mouse' && !ptrs.size) { app.hover = null; app.previewDirty = true; app.ctrl.sendCursor(null, null); } });
|
||
canvas.addEventListener('wheel', (e) => {
|
||
if (!app.inGame) return;
|
||
e.preventDefault();
|
||
const r = canvas.getBoundingClientRect();
|
||
// proportional to the scroll distance (a mouse notch is about the old 1.15x; a trackpad glides). ctrl+wheel is a trackpad pinch: much smaller deltas.
|
||
const dy = clamp(e.deltaY * (e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1), -300, 300);
|
||
renderer.setZoom(renderer.zoom * Math.exp(-dy * (e.ctrlKey ? 0.01 : 0.0015)), e.clientX - r.left, e.clientY - r.top);
|
||
updateFit();
|
||
}, { passive: false });
|
||
// (the window lost focus mid-gesture: the pointerup may never arrive)
|
||
root.addEventListener('blur', () => { ptrs.clear(); abortTouch(); multi = false; pinch = null; rightDown = null; panning = false; });
|
||
|
||
function updateFit() {
|
||
const z = renderer.zoom > 1.02;
|
||
if (z !== app.zoomed) { app.zoomed = z; $('btnFit').hidden = !z; }
|
||
}
|
||
$('btnFit').addEventListener('click', () => { renderer.resetCamera(); updateFit(); });
|
||
|
||
// ------------------------------------------------------------------ keyboard
|
||
root.addEventListener('keydown', (e) => {
|
||
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' && $('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)
|
||
if ((k === ' ' || k === 'enter') && e.target && e.target.closest && e.target.closest('button, a, select, [role="button"]')) return;
|
||
const keyType = k.length === 1 ? TD.TOWER_ORDER.find((t) => TD.TOWERS[t].key === k) : null; // 1-9, 0: one key per tower in the palette
|
||
if (keyType) { selectType(app.selType === keyType ? null : keyType); Audio.sfx('click'); e.preventDefault(); return; }
|
||
switch (k) {
|
||
case 'escape': case 'q': selectType(null); selectTower(0); app.pending = null; updateConfirm(); break;
|
||
case ' ': case 'enter': ctrl.send({ c: 'wave' }); e.preventDefault(); break;
|
||
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 '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;
|
||
case '?': case 'h': showOverlay('help'); break;
|
||
default: break;
|
||
}
|
||
});
|
||
|
||
document.addEventListener('click', (e) => { const b = e.target.closest && e.target.closest('button'); if (b && e.detail > 0) b.blur(); });
|
||
|
||
// ------------------------------------------------------------------ top bar buttons
|
||
$('btnWave').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'wave' }); });
|
||
$('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); });
|
||
// 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
|
||
|
||
// ------------------------------------------------------------------ difficulty
|
||
// The picker (menu, and the co-op lobby for the host) sets app.difficulty, the pick for the NEXT game, and remembers it. A game that is
|
||
// running keeps its own (view.difficulty): Play again repeats that one, and every screen about the running game shows it.
|
||
const diffName = (id) => (TD.DIFFICULTIES[id] ? TD.DIFFICULTIES[id].name : String(id));
|
||
const viewDifficulty = (view) => (view && TD.isDifficulty(view.difficulty) ? view.difficulty : 'normal');
|
||
// The best wave per map AND difficulty. Normal keeps the key the game always used (nw.best.<map>), so every record from before
|
||
// difficulties existed is simply the normal one and nothing is lost or migrated; easy and hard get their own suffix.
|
||
const bestKey = (map, dif) => 'nw.best.' + map + (dif === 'normal' ? '' : '.' + dif);
|
||
// What a difficulty changes, worded from the table (so a retune cannot leave this text wrong).
|
||
function diffSummary(id) {
|
||
const d = TD.DIFFICULTIES[id], out = [];
|
||
if (!d) return '';
|
||
const pct = (m) => Math.round(Math.abs(m - 1) * 100) + '%';
|
||
if (d.gold !== 1) out.push(pct(d.gold) + (d.gold > 1 ? ' more' : ' fewer') + ' starting credits');
|
||
if (d.lives !== 1) out.push(pct(d.lives) + (d.lives > 1 ? ' more' : ' less') + ' integrity');
|
||
if (d.hp !== 1) out.push('packets ' + pct(d.hp) + (d.hp < 1 ? ' weaker' : ' tougher'));
|
||
if (d.reward !== 1) out.push('kills pay ' + pct(d.reward) + (d.reward > 1 ? ' more' : ' less'));
|
||
return out.length ? out.join(', ') : 'The standard game.';
|
||
}
|
||
const diffBoxes = () => [$('diffPick'), $('lobbyDiff')].filter(Boolean);
|
||
function buildDiffPickers() {
|
||
for (const box of diffBoxes()) {
|
||
box.textContent = '';
|
||
for (const id of TD.DIFFICULTY_ORDER) {
|
||
const b = document.createElement('button');
|
||
b.type = 'button'; b.dataset.diff = id; b.setAttribute('role', 'radio');
|
||
b.textContent = diffName(id);
|
||
b.title = diffSummary(id);
|
||
b.addEventListener('click', () => { Audio.sfx('click'); chooseDifficulty(id); });
|
||
box.appendChild(b);
|
||
}
|
||
}
|
||
chooseDifficulty(app.difficulty, true);
|
||
}
|
||
function chooseDifficulty(id, silent) {
|
||
if (!TD.isDifficulty(id)) id = 'normal';
|
||
app.difficulty = id;
|
||
if (!silent) store.set('nw.difficulty', id);
|
||
for (const box of diffBoxes()) for (const b of box.children) b.setAttribute('aria-checked', b.dataset.diff === id ? 'true' : 'false');
|
||
renderDiffNote();
|
||
}
|
||
// One line under the picker: what the picked difficulty does; while a game is running, which one that game is on.
|
||
function renderDiffNote() {
|
||
const n = $('diffNote'); if (!n) return;
|
||
const cur = app.inGame && app.ctrl ? viewDifficulty(app.ctrl.view) : null;
|
||
n.className = 'diffnote' + (cur ? ' live' : '');
|
||
n.textContent = cur ? 'This game: ' + diffName(cur) + (cur !== app.difficulty ? ' \u00b7 next game: ' + diffName(app.difficulty) : '') : diffSummary(app.difficulty);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ menu / lobby
|
||
function buildMapPicker() {
|
||
const box = $('mapPick'); box.textContent = '';
|
||
for (const id of TD.MAP_ORDER) {
|
||
const def = TD.MAPS[id];
|
||
const b = document.createElement('button');
|
||
b.type = 'button'; b.className = 'mapcard'; b.dataset.map = id; b.setAttribute('role', 'radio');
|
||
b.innerHTML = '<canvas width="208" height="128"></canvas><span class="nm"></span><span class="df">RATING <b></b></span>';
|
||
b.querySelector('.nm').textContent = def.name;
|
||
b.querySelector('.df b').textContent = '●'.repeat(def.difficulty) + '○'.repeat(3 - def.difficulty);
|
||
drawMapPreview(b.querySelector('canvas'), def);
|
||
b.addEventListener('click', () => { Audio.sfx('click'); chooseMap(id); });
|
||
box.appendChild(b);
|
||
}
|
||
chooseMap(app.mapId, true);
|
||
}
|
||
function drawMapPreview(cv, def) {
|
||
const p = TD.parseMap(def), ctx = cv.getContext('2d'), w = cv.width / p.cols, h = cv.height / p.rows;
|
||
ctx.fillStyle = '#09101f'; ctx.fillRect(0, 0, cv.width, cv.height);
|
||
ctx.fillStyle = '#26304f';
|
||
for (let y = 0; y < p.rows; y++) for (let x = 0; x < p.cols; x++) if (p.obst[y * p.cols + x]) ctx.fillRect(x * w + 1, y * h + 1, w - 2, h - 2);
|
||
ctx.fillStyle = '#ff5c7a'; for (const s of p.spawns) { ctx.beginPath(); ctx.arc((s.x + 0.5) * w, (s.y + 0.5) * h, h * 0.6, 0, Math.PI * 2); ctx.fill(); }
|
||
ctx.fillStyle = '#4de3ff'; ctx.fillRect(p.core.x * w - 2, p.core.y * h - 2, w + 4, h + 4);
|
||
}
|
||
function chooseMap(id, silent) {
|
||
app.mapId = id; store.set('nw.map', id);
|
||
for (const b of $('mapPick').children) b.setAttribute('aria-checked', b.dataset.map === id ? 'true' : 'false');
|
||
$('mapDesc').textContent = TD.MAPS[id].desc;
|
||
$('lobbyMapName').textContent = 'Map: ' + TD.MAPS[id].name;
|
||
if (!silent && !app.inGame) previewMap(id);
|
||
}
|
||
|
||
function openMenu() {
|
||
// 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';
|
||
showOverlay('menu');
|
||
renderDiffNote();
|
||
if (!app.inGame) Audio.music('theme');
|
||
updateResumeButton();
|
||
}
|
||
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.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); }
|
||
}
|
||
function leaveToMenu(keep) {
|
||
cancelPending();
|
||
leaveRemote(true, keep);
|
||
app.prevPlayers = null;
|
||
app.inGame = false;
|
||
$('reconnect').hidden = true; $('players').hidden = true; $('netChip').hidden = true;
|
||
previewMap(app.mapId);
|
||
setScreen('menu'); openMenu();
|
||
}
|
||
|
||
$('btnSolo').addEventListener('click', () => { Audio.unlock(); startSolo(app.mapId); });
|
||
$('btnCloseMenu').addEventListener('click', closeOverlayToGame);
|
||
$('btnHelp').addEventListener('click', () => showOverlay('help'));
|
||
$('btnHelpClose').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else showOverlay('menu'); });
|
||
$('btnFullscreen').addEventListener('click', () => {
|
||
const d = document, el = d.documentElement;
|
||
if (d.fullscreenElement) d.exitFullscreen(); else if (el.requestFullscreen) el.requestFullscreen().catch(() => {});
|
||
});
|
||
if (!document.documentElement.requestFullscreen || (root.matchMedia && root.matchMedia('(display-mode: standalone)').matches)) $('btnFullscreen').hidden = true; else $('btnFullscreen').hidden = false;
|
||
|
||
$('btnAgain').addEventListener('click', () => {
|
||
Audio.sfx('click');
|
||
// Play again keeps the difficulty of the game that just ended (not the menu's pick, which is for a NEW game)
|
||
if (app.ctrl.kind === 'local') { app.ctrl.newGame(app.ctrl.mapId, app.ctrl.difficulty); Audio.music('battle'); }
|
||
else { app.ctrl.newGame(app.ctrl.board.mapId, app.ctrl.difficulty); }
|
||
});
|
||
$('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); });
|
||
$('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } });
|
||
|
||
// lobby
|
||
function lobbyMsg(text, bad) { const m = $('lobbyMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
|
||
function openLobby(code) {
|
||
showOverlay('lobby'); setScreen(app.inGame ? 'playing' : 'menu');
|
||
$('inName').value = store.get('nw.name', '') || '';
|
||
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', () => { 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, difficulty: app.difficulty }));
|
||
$('btnJoin').addEventListener('click', () => {
|
||
const code = $('inCode').value.trim().toUpperCase();
|
||
if (!/^[A-Z0-9]{4}$/.test(code)) { lobbyMsg('Enter the 4 character room code.', true); return; }
|
||
connectRemote({ room: code });
|
||
});
|
||
$('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);
|
||
lobbyMsg('Connecting…');
|
||
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, 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', () => {
|
||
if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over
|
||
saveSession();
|
||
$('reconnect').hidden = true;
|
||
if (first) {
|
||
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=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
|
||
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here)
|
||
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) 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) => {
|
||
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();
|
||
}
|
||
|
||
function updateResumeButton() {
|
||
const s = store.get('nw.session', null), b = $('btnResume');
|
||
const fresh = s && s.room && Date.now() - s.ts < 15 * 60 * 1000 && !(app.ctrl && app.ctrl.kind === 'remote');
|
||
b.hidden = !fresh || root.location.protocol === 'file:';
|
||
if (fresh) b.textContent = 'Resume co-op game · room ' + s.room;
|
||
}
|
||
$('btnResume').addEventListener('click', () => {
|
||
const s = store.get('nw.session', null); if (!s) return;
|
||
sess.set('nw.pid', s.pid);
|
||
$('inName').value = s.name || '';
|
||
connectRemote({ room: s.room, resume: true });
|
||
});
|
||
|
||
// ------------------------------------------------------------------ misc platform bits
|
||
let wakeLock = null, wakeAsk = false;
|
||
function requestWakeLock() {
|
||
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(); });
|
||
|
||
// ------------------------------------------------------------------ app layout (the JS half of the layout modes in style.css)
|
||
const mq = (q) => (root.matchMedia ? root.matchMedia(q) : { matches: false, addEventListener() {} });
|
||
const mqStacked = mq('(orientation: portrait), (max-width: 760px) and (min-height: 521px)');
|
||
const mqCompact = mq('(pointer: coarse), (orientation: portrait), (max-width: 760px) and (min-height: 521px), (orientation: landscape) and (max-height: 520px)');
|
||
// Stacked (portrait / narrow) layout: the stage hugs the board, so there is no dead band above and below it and the side panel gets
|
||
// everything else. The board is drawn turned 90 degrees when that makes the cells clearly bigger (tall phones), otherwise upright
|
||
// and short (small phones: the freed height goes to the palette and info panel). Inputs are the viewport and top bar only (never
|
||
// the stage's own size), so this cannot feed back into the ResizeObserver.
|
||
function layoutApp() {
|
||
const a = $('app'), b = app.ctrl && app.ctrl.board;
|
||
a.dataset.ui = mqCompact.matches ? 'compact' : 'wide';
|
||
if (!mqStacked.matches || !b) { a.style.removeProperty('--stage-h'); app.rotate = null; return; }
|
||
const cs = root.getComputedStyle(a);
|
||
const W = a.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0);
|
||
const H = a.clientHeight - (parseFloat(cs.paddingTop) || 0) - (parseFloat(cs.paddingBottom) || 0) - $('topbar').offsetHeight;
|
||
const mg = (NW.BOARD_MARGIN || 0) * 2, dw = b.cols * NW.CELL + mg, dh = b.rows * NW.CELL + mg, pad = 8;
|
||
const minSide = clamp(Math.round(H * 0.25), 140, 210); // room for the palette row and a window onto the info panel
|
||
const maxStage = Math.max(120, H - minSide);
|
||
const sU = Math.min((W - pad) / dw, (maxStage - pad) / dh), sR = Math.min((W - pad) / dh, (maxStage - pad) / dw);
|
||
const rot = sR > sU * 1.08;
|
||
const bh = rot ? dw : dh, bw = rot ? dh : dw;
|
||
const stageH = Math.round(Math.min(maxStage, Math.ceil(bh * ((W - pad) / bw) + pad)));
|
||
app.rotate = rot;
|
||
if (a.style.getPropertyValue('--stage-h') !== stageH + 'px') a.style.setProperty('--stage-h', stageH + 'px');
|
||
}
|
||
function resizeCanvas() {
|
||
layoutApp();
|
||
const st = $('stage'), r = st.getBoundingClientRect();
|
||
renderer.setRotation(app.rotate !== null && app.rotate !== undefined ? app.rotate : r.height > r.width * 1.05); // portrait: board turned 90 degrees (bigger cells)
|
||
const dpr = Math.min(root.devicePixelRatio || 1, root.matchMedia && root.matchMedia('(pointer: coarse)').matches ? 2 : 2.5);
|
||
renderer.resize(r.width, r.height, dpr);
|
||
updatePaletteHint(); layoutBars(true); updateFit(); // (a rotation or board swap resets the camera: hide a stale Reset-zoom button)
|
||
}
|
||
let resizeRaf = 0;
|
||
function scheduleResize() { if (!resizeRaf) resizeRaf = root.requestAnimationFrame(() => { resizeRaf = 0; resizeCanvas(); }); } // (a frame later: never resize inside the observer callback)
|
||
if (root.ResizeObserver) { const ro = new ResizeObserver(scheduleResize); ro.observe($('stage')); ro.observe($('topbar')); ro.observe($('palette')); }
|
||
root.addEventListener('resize', scheduleResize);
|
||
mqStacked.addEventListener && mqStacked.addEventListener('change', scheduleResize);
|
||
mqCompact.addEventListener && mqCompact.addEventListener('change', scheduleResize);
|
||
root.addEventListener('orientationchange', () => setTimeout(() => { resizeCanvas(); drawPaletteIcons(); }, 250));
|
||
// keep the page from scrolling/bouncing or zooming on iOS
|
||
document.addEventListener('gesturestart', (e) => e.preventDefault());
|
||
document.addEventListener('touchmove', (e) => { if (e.target === canvas || e.target.closest('#stage')) e.preventDefault(); }, { passive: false });
|
||
|
||
// ------------------------------------------------------------------ main loop
|
||
function frame(now) {
|
||
root.requestAnimationFrame(frame);
|
||
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) { // 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 || 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');
|
||
if (boss !== app.bossMusic) { app.bossMusic = boss; if (!app.endShown) Audio.music(boss ? 'boss' : 'battle'); }
|
||
}
|
||
}
|
||
ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower;
|
||
// hovering an existing tower while a build type is active: a click selects it, so show no ghost
|
||
ui.noGhost = !!(ui.hover && app.selType && view.towers.some((t) => t.x === ui.hover.x && t.y === ui.hover.y));
|
||
refreshPreview(false);
|
||
renderer.frame(now, view, ui);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ boot
|
||
function boot() {
|
||
buildPalette(); buildMapPicker(); buildDiffPickers();
|
||
{ const keys = TD.TOWER_ORDER.map((t) => TD.TOWERS[t].key); $('helpKeys').textContent = keys[0] + '\u2013' + keys[keys.length - 1]; }
|
||
previewMap(app.mapId);
|
||
setScreen('menu'); showOverlay('menu');
|
||
$('btnCloseMenu').hidden = true;
|
||
resizeCanvas(); drawPaletteIcons();
|
||
root.requestAnimationFrame(frame);
|
||
|
||
const q = new URLSearchParams(root.location.search), codeParam = (q.get('room') || '').toUpperCase();
|
||
const savedRoom = sess.get('nw.room');
|
||
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, resume: true });
|
||
} else if (/^[A-Z0-9]{4}$/.test(codeParam)) {
|
||
openLobby(codeParam);
|
||
lobbyMsg('Enter your name and press Join.');
|
||
} else {
|
||
updateResumeButton();
|
||
Audio.music('theme');
|
||
}
|
||
// installable + offline-capable solo play (service workers need https or localhost)
|
||
if (root.navigator.serviceWorker && (root.location.protocol === 'https:' || /^(localhost|127\.0\.0\.1|\[::1\])$/.test(root.location.hostname))) {
|
||
root.navigator.serviceWorker.register('sw.js').catch(() => {});
|
||
}
|
||
}
|
||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
|
||
|
||
NW.app = app; // handy for debugging and automated tests
|
||
})(typeof self !== 'undefined' ? self : this);
|