/*
* 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));
// ------------------------------------------------------------------ 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_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'),
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';
// ------------------------------------------------------------------ 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);
}
function hint(text, kind) {
const h = $('hint');
if (!text) { h.hidden = true; return; }
h.hidden = false; h.textContent = text; h.className = 'hint ' + (kind || 'info');
}
const fmtLen = (v) => String(Math.round(v / Math.max(1, ui.spawns || 1)));
function showOverlay(id) {
for (const o of document.querySelectorAll('.overlay')) o.hidden = o.id !== id;
}
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;
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; });
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) {
leaveRemote(true);
app.mapId = mapId; store.set('nw.map', mapId);
const c = new NW.LocalController({ map: mapId });
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);
Audio.music('battle');
requestWakeLock();
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;
}
function leaveRemote(silent) {
const c = app.ctrl;
if (c && c.kind === 'remote') { c.close(); }
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;
}
}
}
function onReject(r) {
toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad');
Audio.sfx('error');
}
// ------------------------------------------------------------------ palette + info panel
function buildPalette() {
const pal = $('palette');
pal.textContent = '';
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 + ', ' + def.levels[0].cost + ' credits');
b.innerHTML = '' + def.key + ' ';
b.querySelector('.nm').textContent = def.name;
b.querySelector('.cost').textContent = String(def.levels[0].cost);
b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); });
pal.appendChild(b);
}
drawPaletteIcons();
}
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');
}
}
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.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'; }
let infoSig = '';
function renderInfo(force) {
const box = $('info'), ctrl = app.ctrl, view = ctrl.view;
let sig, tower = null;
if (app.selTower) {
tower = view.towers.find((t) => t.id === app.selTower);
if (!tower) { app.selTower = 0; }
}
if (tower) sig = 't' + tower.id + ':' + tower.level + ':' + tower.mode;
else if (app.selType) sig = 'b' + app.selType;
else sig = '';
if (!force && sig === infoSig) return;
infoSig = sig;
if (!sig) { box.textContent = ''; return; }
if (tower) {
const def = TD.TOWERS[tower.type], i = tower.level - 1;
const cur = statsFor(tower.type, i), nxt = tower.level < 3 ? statsFor(tower.type, i + 1) : null;
let kv = '';
cur.forEach((row, k) => {
const n = nxt && nxt[k] && nxt[k][1] !== row[1] ? ' → ' + nxt[k][1] + ' ' : '';
kv += '
' + row[0] + ' ' + row[1] + n + '
';
});
if (tower.type !== 'wall') kv += 'Targets ' + targetsText(def) + '
';
const sellVal = def.refund ? tower.spent : Math.floor(tower.spent * TD.SELL_RATIO);
const upCost = tower.level < 3 ? def.levels[tower.level].cost : null;
const owner = ctrl.kind === 'remote' && ctrl.players.length > 1;
const ownerP = owner ? ctrl.players.find((p) => p.slot === tower.owner) : null;
box.innerHTML =
'' +
'
' + kv + '
' +
(tower.type === 'wall' ? '' :
' ' + (upCost === null ? 'Max level' : 'Upgrade ' + upCost + ' ') + ' ' +
'Target: ' + MODE_NAMES[tower.mode] + ' ') +
' Sell ' + sellVal + '
' +
'
' + (tower.type === 'wall' ? '' : ' ') + (ownerP ? ' ' : '') + '
';
box.querySelector('.nm').textContent = def.name;
box.querySelector('.lv').textContent = tower.type === 'wall' ? '' : 'Level ' + tower.level + ' / 3';
box.querySelector('.desc').textContent = def.desc;
if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name;
NW.drawIcon(box.querySelector('canvas'), tower.type, tower.level);
} else {
const def = TD.TOWERS[app.selType];
let kv = '';
for (const row of statsFor(app.selType, 0)) kv += '' + row[0] + ' ' + row[1] + '
';
if (app.selType !== 'wall') kv += 'Targets ' + targetsText(def) + '
';
box.innerHTML = '';
box.querySelector('.nm').textContent = def.name;
box.querySelector('.lv').textContent = def.levels[0].cost + ' credits';
box.querySelector('.desc').textContent = def.desc;
NW.drawIcon(box.querySelector('canvas'), app.selType, 1);
}
}
function updateInfoDynamic() {
if (!app.selTower) return;
const t = app.ctrl.view.towers.find((x) => x.id === app.selTower);
if (!t) return;
const k = $('infoKills'); if (k) k.textContent = t.kills + (t.kills === 1 ? ' kill' : ' kills');
const def = TD.TOWERS[t.type];
const up = $('info').querySelector('[data-act="up"]');
if (up && t.level < 3) up.disabled = app.ctrl.view.gold < def.levels[t.level].cost;
}
$('info').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-act]'); if (!btn || !app.selTower) return;
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 '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 key = n + ':' + view.state;
if (app.last.waveKey === key) return;
app.last.waveKey = key;
const box = $('nextwave');
if (view.state !== 'playing') { box.textContent = ''; return; }
const sum = TD.waveSummary(n);
let html = 'Next · wave ' + n + ' ';
let air = false;
for (const g of sum) {
const d = TD.ENEMIES[g.k];
if (d.air) air = true;
html += ' ' + g.c + '× ' + d.name + ' ';
}
if (air) html += 'AIR ';
if (n % 10 === 0) html += 'BOSS ';
html += '
';
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(true);
}
function renderPlayers() {
const ctrl = app.ctrl, box = $('players');
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
box.hidden = false;
let html = 'Room ' + (ctrl.room || '') + ' ';
for (const p of ctrl.players) {
html += '
' +
(ctrl.you && p.pid === ctrl.you.pid ? '(you) ' : '') + (p.host ? 'host ' : '') + (p.online ? '' : 'offline ') + '
';
}
if (ctrl.players.length < 2) html += '
Waiting for a partner… share the invite link.
';
html += '
InviteLeave
';
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=' + 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 + '×'; }
if (L.paused !== view.paused) { L.paused = view.paused; $('btnPause').innerHTML = ' '; $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause'); }
if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = ' '; }
// palette affordability
const gold = view.gold;
if (L.palGold !== gold) {
L.palGold = gold;
for (const b of $('palette').children) b.classList.toggle('poor', gold < TD.TOWERS[b.dataset.type].levels[0].cost);
}
if (ctrl.kind === 'remote') {
const chip = $('netChip');
chip.hidden = false;
$('netRoom').textContent = ctrl.room || '';
const p = ctrl.rtt ? ctrl.rtt + ' ms' : '';
if (L.ping !== p) { L.ping = p; $('netPing').textContent = p; chip.classList.toggle('bad', ctrl.rtt > 220); }
}
renderWavePanel(view);
updateInfoDynamic();
}
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 best = store.get('nw.best.' + ctrl.board.mapId, 0);
if (!won && view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave);
$('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.';
const walls = view.towers.filter((t) => t.type === 'wall').length;
const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Best (map)', Math.max(best, view.wave)]];
$('endStats').innerHTML = rows.map((r) => '' + r[0] + ' ' + r[1] + '
').join('');
const remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
$('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
$('btnContinue').hidden = !won;
showOverlay('end');
Audio.music(null); Audio.stinger(won ? 'win' : 'lose');
}
// ------------------------------------------------------------------ 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 = TD.TOWERS[app.selType].levels[0].cost;
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 = TD.TOWERS[app.selType].levels[0].cost;
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) {
$('confirmText').textContent = 'Build · ' + TD.TOWERS[app.selType].levels[0].cost;
// keep the bar clear of the cell being placed: show it on the opposite half of the stage
const p = renderer.cellToScreen(app.pending.x, app.pending.y);
$('confirm').classList.toggle('top', p.y > $('stage').clientHeight * 0.5);
}
}
$('btnConfirmBuild').addEventListener('click', () => { if (app.pending && placeAt(app.pending)) { app.pending = null; updateConfirm(); } });
$('btnCancelBuild').addEventListener('click', () => { selectType(null); });
// ------------------------------------------------------------------ pointer input
const ptrs = new Map();
let painting = false, paintCell = null, panning = false, longT = 0, longFired = false, rightDown = null, prevPending = null, pinch = null;
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;
}
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 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, abandon whatever the first finger started
cancelLong(); painting = false; tapSelectOnUp = false;
const [a, b] = [...ptrs.values()];
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
return;
}
if (ptrs.size > 2) return;
const cell = renderer.screenToCell(sx, sy);
longFired = false;
if (e.pointerType === 'mouse') {
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 && 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') { painting = true; paintCell = cell; }
} else {
tapSelectOnUp = true; panning = renderer.zoom > 1.01;
}
return;
}
// touch / pen
prevPending = app.pending ? { x: app.pending.x, y: app.pending.y } : null;
const ex = towerAtCell(cell);
if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) {
selectTower(ex.id); Audio.sfx('click');
} else if (app.selType === 'wall') {
setHover(cell); if (!ex) placeAt(cell); painting = true; paintCell = cell;
} else if (app.selType) {
app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm();
} else {
tapSelectOnUp = true;
longT = setTimeout(() => { longFired = true; tapSelectOnUp = false; markAt(cell); }, 520);
}
});
let tapSelectOnUp = false;
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) > 8) p.moved = true;
if (ptrs.size === 2 && pinch) {
const [a, b] = [...ptrs.values()];
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;
}
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)) { paintLine(paintCell, cell); paintCell = cell; }
return;
}
// touch / pen
if (p.moved) { cancelLong(); tapSelectOnUp = tapSelectOnUp && !p.moved; }
if (painting && app.selType === 'wall') {
setHover(cell);
if (paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { paintLine(paintCell, cell); paintCell = cell; }
} else if (app.selType) {
app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm();
app.ctrl.sendCursor(cell.fx, cell.fy);
} else if (p.moved && renderer.zoom > 1.01) {
renderer.panBy(dx, dy); updateFit();
}
});
function endPointer(e) {
const p = ptrs.get(e.pointerId);
ptrs.delete(e.pointerId);
try { canvas.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ }
if (!p || !app.inGame) return;
cancelLong();
if (ptrs.size < 2) pinch = null;
const r = canvas.getBoundingClientRect(), cell = renderer.screenToCell(e.clientX - r.left, e.clientY - r.top);
if (e.pointerType === 'mouse') {
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);
tapSelectOnUp = false; painting = false; panning = false;
return;
}
if (e.type === 'pointercancel') { painting = false; tapSelectOnUp = false; return; }
if (painting) { painting = false; return; }
if (ptrs.size > 0) return; // lifted one finger of a pinch
if (app.selType && app.pending && !p.moved && prevPending && prevPending.x === app.pending.x && prevPending.y === app.pending.y) {
if (placeAt(app.pending)) { app.pending = null; updateConfirm(); } // tapping the previewed cell again builds
} else if (!app.selType && tapSelectOnUp && !p.moved && !longFired) tapSelect(cell);
tapSelectOnUp = false;
}
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();
renderer.setZoom(renderer.zoom * (e.deltaY < 0 ? 1.15 : 1 / 1.15), e.clientX - r.left, e.clientY - r.top);
updateFit();
}, { passive: 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 (!app.inGame) return;
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; }
const ctrl = app.ctrl, view = ctrl.view;
const k = e.key.toLowerCase();
const idx = '123456'.indexOf(k);
if (idx >= 0 && k.length === 1) { selectType(app.selType === TD.TOWER_ORDER[idx] ? null : TD.TOWER_ORDER[idx]); 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 '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;
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); });
$('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); });
$('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); });
// ------------------------------------------------------------------ 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 = 'DIFFICULTY ';
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() {
if (app.inGame && app.ctrl.kind === 'local') app.ctrl.ctl('pause', true);
setScreen(app.inGame ? 'playing' : 'menu');
$('btnCloseMenu').hidden = !app.inGame;
$('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo';
showOverlay('menu');
if (!app.inGame) Audio.music('theme');
updateResumeButton();
}
function closeOverlayToGame() {
if (!app.inGame) return;
showOverlay(null);
if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false);
}
function leaveToMenu() {
leaveRemote(true);
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');
if (app.ctrl.kind === 'local') { app.ctrl.newGame(app.ctrl.mapId); Audio.music('battle'); }
else { app.ctrl.newGame(app.ctrl.board.mapId); }
});
$('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;
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(); });
$('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', () => {
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(); });
function connectRemote(opts) {
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; }
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 });
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() });
$('reconnect').hidden = true;
if (first) {
first = false;
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 */ }
toast('Room ' + rc.room + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good');
Audio.music('battle'); requestWakeLock();
} else { toast('Reconnected', 'good'); adoptBoard(); }
lobbyMsg('');
});
rc.on('status', (s) => { if (app.ctrl === rc && app.inGame) $('reconnect').hidden = s !== 'reconnecting'; });
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);
});
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 });
});
// ------------------------------------------------------------------ misc platform bits
let wakeLock = null;
function requestWakeLock() {
try { if (navigator.wakeLock && !wakeLock) navigator.wakeLock.request('screen').then((l) => { wakeLock = l; l.addEventListener('release', () => { wakeLock = null; }); }).catch(() => {}); } catch (e) { /* ignore */ }
}
document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); });
function resizeCanvas() {
const st = $('stage'), r = st.getBoundingClientRect();
renderer.setRotation(r.height > r.width * 1.05); // portrait: draw the 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);
}
if (root.ResizeObserver) new ResizeObserver(resizeCanvas).observe($('stage')); else root.addEventListener('resize', resizeCanvas);
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;
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; }
}
if (app.selTower && !view.towers.some((t) => t.id === app.selTower)) { app.selTower = 0; renderInfo(true); }
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(true); }
updateHud(view);
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();
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 });
} else if (/^[A-Z0-9]{4}$/.test(codeParam)) {
openLobby(codeParam);
lobbyMsg('Enter your name and press Join.');
} else {
updateResumeButton();
Audio.music('theme');
}
if (root.navigator.serviceWorker && root.location.protocol.startsWith('http')) { /* reserved for offline support */ }
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
NW.app = app; // handy for debugging and automated tests
})(typeof self !== 'undefined' ? self : this);