';
bar.querySelector('#vsAbil').addEventListener('click', (e) => { const b = e.target.closest('button[data-tl]'); if (b) { Audio.unlock(); useTool(b.dataset.tl); } });
S.last.dock = '';
}
if (att || def) {
for (const b of bar.querySelectorAll('.vsbtn')) { const id = b.dataset.ab || b.dataset.tl; S.el[id] = { b, cd: b.querySelector('.cd'), cost: b.querySelector('.cost'), ring: -1 }; }
}
}
function dockBtn(kind, id, cost) {
const tip = kind === 'ab' ? abilityText(id) : toolText(id);
return '';
}
// ------------------------------------------------------------------ actions: attacker
function buy(kind) {
if (!ready()) return;
const d = TD.ENEMIES[kind], have = credits();
let n = S.qty;
if (have < d.buyCost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (have < d.buyCost * n) { n = Math.floor(have / d.buyCost); toast('Only ' + n + ' affordable: buying ' + n); }
const res = send(gateArg({ c: S.mode === 'stage' ? 'stage' : 'spawn', kind, n }));
if (res && res.ok) {
Audio.sfx(S.mode === 'stage' ? 'stage' : 'buy');
if (S.ctrl.kind === 'remote' && S.priv) S.priv.credits = Math.max(0, S.priv.credits - d.buyCost * n);
}
}
function launch() {
if (!ready()) return;
if (!stagedTotal()) { toast(REASONS.empty, 'bad'); return; }
const res = send(gateArg({ c: 'launch' }));
if (res && res.ok) {
Audio.sfx('launch');
if (S.ctrl.kind === 'remote' && S.priv) S.priv.staged = [];
}
}
function buyTech(id) {
if (!ready()) return;
const lv = S.priv && S.priv.tech ? S.priv.tech[id] || 0 : 0, X = VS.TECH[id];
if (!X || lv >= X.max) { toast(REASONS.max === 'Nothing to do' ? nameOf(id) + ' is at its maximum' : REASONS.max); return; }
const cost = VS.TECH_COST * Math.pow(2, lv);
if (credits() < cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
const res = send({ c: 'tech', id });
if (res && res.ok) {
Audio.sfx('tech');
if (S.ctrl.kind === 'remote' && S.priv) { S.priv.credits = Math.max(0, S.priv.credits - cost); S.priv.tech = Object.assign({}, S.priv.tech, { [id]: lv + 1 }); }
}
}
function ability(id) {
if (!ready()) return;
const A = VS.ABILITIES[id]; if (!A) return;
if (id === 'emp') {
if (S.empArm) { disarm(); return; }
const t = app.selTower ? S.ctrl.view.towers.find((x) => x.id === app.selTower) : null;
if (t && t.type !== 'wall') { castEmp(t.id); return; }
disarm(); S.empArm = true; say('Tap a tower to EMP it (' + A.dur + ' s)'); Audio.sfx('click');
return;
}
if (cdLeft(id) > 0.05) { toast(nameOf(id) + ' is cooling down', 'bad'); return; }
if (credits() < A.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (A.cost >= 150 && !confirmTap(id, 'Tap ' + nameOf(id) + ' again to fire it (' + A.cost + ')')) { flashConfirm(id); return; }
cast({ c: 'ability', id }, id, A.cost, A.cd, id === 'decoy');
}
function castEmp(tid) {
const A = VS.ABILITIES.emp;
disarm();
if (cdLeft('emp') > 0.05) { toast('EMP is cooling down', 'bad'); return; }
if (credits() < A.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
cast({ c: 'ability', id: 'emp', tid }, 'emp', A.cost, A.cd, false);
app.selTower = 0; api.renderInfo(true);
}
function cast(cmd, id, cost, cd, useGate) {
const res = send(useGate ? gateArg(cmd) : cmd);
if (res && res.ok && S.ctrl.kind === 'remote' && S.priv) { S.priv.credits = Math.max(0, S.priv.credits - cost); S.cd[id] = { left: cd, at: now() }; }
}
function flashConfirm(id) {
const e = S.el[id]; if (!e) return;
e.b.classList.add('confirm'); setTimeout(() => e.b.classList.remove('confirm'), 2500);
}
function setGate(i) {
S.gate = i;
toast(i < 0 ? 'Gateways: automatic' : 'Gateway ' + (i + 1) + ' chosen', 'good');
}
// ------------------------------------------------------------------ actions: defender
function useTool(id) {
if (!ready()) return;
const T = VS.TOOLS[id]; if (!T) return;
const view = S.ctrl.view;
if (id === 'scan' && S.scanArm) { disarm(); return; }
if (cdLeft(id) > 0.05) { toast(nameOf(id) + ' is cooling down', 'bad'); return; }
if (view.gold < T.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (id === 'scan') { disarm(); api.selectType(null); S.scanArm = true; say('Tap the map to scan (radius ' + T.radius + ')'); Audio.sfx('click'); return; }
let cmd = { c: 'tool', id };
if (id === 'patch') {
const sel = app.selTower ? view.towers.find((t) => t.id === app.selTower && t.empT > 0) : null;
let t = sel;
if (!t) for (const x of view.towers) if (x.empT > 0 && (!t || x.empT > t.empT)) t = x;
if (!t) { toast('No tower is disabled', 'bad'); return; }
cmd.tid = t.id;
} else if (id === 'repair') {
if (view.lives >= view.maxLives) { toast('Integrity is already full', 'bad'); return; }
} else if (T.cost >= 150 && !confirmTap(id, 'Tap ' + nameOf(id) + ' again to use it (' + T.cost + ')')) { flashConfirm(id); return; }
const res = send(cmd);
if (res && res.ok) {
Audio.sfx(id === 'patch' ? 'patch' : 'click');
if (S.ctrl.kind === 'remote') S.cd[id] = { left: T.cd, at: now() };
}
}
function scanAt(cell) {
disarm();
const T = VS.TOOLS.scan;
if (cdLeft('scan') > 0.05) { toast('Scan is cooling down', 'bad'); return; }
if (S.ctrl.view.gold < T.cost) { toast(REASONS.credits, 'bad'); return; }
const res = send({ c: 'tool', id: 'scan', x: cell.x + 0.5, y: cell.y + 0.5 });
if (res && res.ok && S.ctrl.kind === 'remote') S.cd.scan = { left: T.cd, at: now() };
}
function ready() {
if (!S.active || !S.role) return false;
if (S.vs && S.vs.frozen) { toast(REASONS.frozen, 'bad'); return false; }
if (!phasePlaying()) { toast(REASONS.phase, 'bad'); return false; }
return true;
}
// ------------------------------------------------------------------ board taps and keys (called by main)
function tapCell(cell) {
if (!S.active || !S.role || !S.ctrl.board || !S.ctrl.board.inBounds(cell.x, cell.y)) return false;
const view = S.ctrl.view;
if (S.role === 'defender') {
if (S.scanArm && ready()) { scanAt(cell); return true; }
return false;
}
const tw = view.towers.find((x) => x.x === cell.x && x.y === cell.y);
if (S.empArm) {
if (tw && tw.type !== 'wall') { if (ready()) castEmp(tw.id); return true; }
if (tw) { toast("A Firewall can't be disabled", 'bad'); return true; }
disarm(); return true;
}
if (tw) return false; // an ordinary tap on a tower selects it (its panel offers EMP)
const sp = S.ctrl.board.spawns;
if (sp.length > 1) {
let best = -1, bd = 3;
for (let i = 0; i < sp.length; i++) { const d = Math.max(Math.abs(sp[i].x - cell.x), Math.abs(sp[i].y - cell.y)); if (d <= 1 && d < bd) { bd = d; best = i; } }
if (best >= 0) { Audio.sfx('click'); setGate(S.gate === best ? -1 : best); return true; }
}
return false;
}
// Keys: attacker digits buy units, Space launches; the wave / pause / speed keys do nothing in versus. Returns true when handled.
function key(k, e) {
if (!S.active) return false;
if (k === 'p' || k === 'f' || k === 'a') return true;
if (k === 'escape' || k === 'q') { disarm(); return false; }
if (S.role === 'attacker') {
if (k === ' ' || k === 'enter') { launch(); e.preventDefault(); return true; }
const i = k.length === 1 && k >= '1' && k <= '9' ? +k - 1 : k === '0' ? 9 : -1;
if (i >= 0 && TD.ENEMY_ORDER[i]) { buy(TD.ENEMY_ORDER[i]); e.preventDefault(); return true; }
return false;
}
if (k === ' ' || k === 'enter') return true;
return false;
}
const holdsOverlay = () => S.active && (S.phase === 'lobby' || S.phase === 'roundover' || S.phase === 'matchover');
function refreshOverlay() {
if (!S.active) return;
if (S.phase === 'lobby') { renderRoom(); showOverlay('vsRoom'); }
else if (S.phase === 'roundover' || S.phase === 'matchover') { renderEnd(); showOverlay('vsEnd'); }
}
// The stacked layout needs more room under the board in versus: the attacker's dock is shop + convoy + abilities + tech.
function minSide(H) {
if (!S.active || !S.role) return 0;
return S.role === 'attacker' ? clamp(Math.round(H * 0.4), 295, 340) : clamp(Math.round(H * 0.3), 190, 250);
}
function uiState() {
if (!S.active) return null;
UIS.role = S.role; UIS.tech = S.role === 'attacker' && S.priv ? S.priv.tech || null : null;
UIS.gate = S.gate; UIS.gates = gates(); UIS.scanArm = S.scanArm; UIS.empArm = S.empArm;
return UIS;
}
// ------------------------------------------------------------------ events (sounds and cues for the new actions)
function onEvent(e) {
if (!S.active) return;
const t = now();
switch (e.e) {
case 'emp': Audio.sfx('emp'); if (S.role === 'defender') toast('EMP: a tower went offline. Patch or Scan it', 'bad'); break;
case 'decoy': Audio.sfx('decoy'); if (e.id !== undefined) S.decoys.set(e.id, t + (e.d || 5) * 1000); break;
case 'surge': S.fx.surge = t + (e.d || 6) * 1000; Audio.sfx('surge'); banner('SURGE', true); break;
case 'ddos': S.fx.ddos = t + (e.d || 4) * 1000; Audio.sfx('ddos'); banner('DDoS', true); break;
case 'quarantine': S.fx.freeze = t + (e.d || 2) * 1000; Audio.sfx('quarantine'); banner('QUARANTINE'); break;
case 'scan': Audio.sfx('scan'); break;
case 'repair': Audio.sfx('repair'); break;
default: break;
}
}
const leakSfx = () => (S.active && S.role === 'attacker' ? 'breach' : 'leak');
const isDecoy = (m) => !!m.decoy || (S.decoys.size > 0 && S.decoys.has(m.id));
// ------------------------------------------------------------------ per frame: top bar, dock, cooldown rings
function setText(el, v) { if (el && el.textContent !== v) el.textContent = v; }
function setCls(el, c, on) { if (el && el.classList.contains(c) !== on) el.classList.toggle(c, on); }
function tick(t, view) {
if (!S.active) return;
const att = S.role === 'attacker', L = S.last, vsb = view.vs;
// clock
const left = vsb ? Math.max(0, vsb.lim - vsb.t) : S.vs ? S.vs.limit : 0;
const tt = mmss(left);
if (L.time !== tt) { L.time = tt; $('vTime').textContent = tt; }
const low = left <= 30 && phasePlaying();
if (L.low !== low) { L.low = low; $('statTime').classList.toggle('low', low); }
// the attacker's credits and income replace the defender's gold in the top bar
if (att) {
const c = credits(), inc = S.priv && S.priv.role === 'attacker' ? S.priv.income : 0;
if (L.cr !== c) { L.cr = c; $('vGold').textContent = String(c); }
const it = inc ? '+' + (Math.round(inc * 10) / 10) + '/s' : '';
if (L.inc !== it) { L.inc = it; $('vIncome').textContent = it; }
$('statGold').title = 'Your credits (income ' + it + ')';
} else if (L.inc !== '') { L.inc = ''; $('vIncome').textContent = ''; $('statGold').title = 'Credits'; }
// shop / tech / convoy
if (att) tickAttacker(view);
tickDock(view);
tickHud(view);
tickFx(t);
}
function tickAttacker(view) {
const L = S.last, c = credits(), E = S.el;
const shopKey = c + '|' + S.qty + '|' + S.mode;
if (E.qty && L.shop !== shopKey) {
L.shop = shopKey;
setText(E.qty, '×' + S.qty); E.qty.setAttribute('aria-label', 'Quantity ' + S.qty + ' per tap. Tap to change');
setText(E.mode, S.mode === 'stage' ? 'Stage' : 'Send');
E.mode.setAttribute('aria-label', S.mode === 'stage' ? 'Stage: pay now and hold the units in the convoy. Tap to switch to Send now' : 'Send now: units enter at once. Tap to switch to Stage');
E.mode.classList.toggle('on', S.mode === 'stage');
for (const b of $('palette').children) {
const d = TD.ENEMIES[b.dataset.kind]; if (!d) continue;
const price = d.buyCost * S.qty, poor = c < d.buyCost;
setText(b.querySelector('.cost'), String(price));
setCls(b, 'poor', poor);
b.setAttribute('aria-label', d.name + ', ' + price + ' credits' + (S.qty > 1 ? ' for ' + S.qty : '') + (poor ? ', not enough credits' : ''));
}
}
// convoy + Launch
const n = stagedTotal();
const comp = S.priv && S.priv.staged ? S.priv.staged.map((e) => e[1] + ' ' + (TD.ENEMIES[e[0]] ? TD.ENEMIES[e[0]].name : e[0])).join(', ') : '';
const lk = n + '|' + comp;
if (L.launch !== lk && E.launch) {
L.launch = lk;
E.launch.disabled = n === 0;
E.launch.querySelector('b').textContent = n ? 'LAUNCH ' + n : 'LAUNCH';
setText(E.launchSub, n ? comp : 'convoy empty');
E.launch.setAttribute('aria-label', n ? 'Launch the convoy: ' + comp : 'Launch (the convoy is empty: use Stage to hold units)');
}
const ng = gates();
if (E.gate) {
E.gate.hidden = ng < 2;
const gt = S.gate < 0 ? 'Gate: auto' : 'Gate ' + (S.gate + 1);
if (L.gate !== gt) { L.gate = gt; E.gate.textContent = S.gate < 0 ? 'Any gate' : 'Gate ' + (S.gate + 1); E.gate.setAttribute('aria-label', gt + '. Tap to change (or tap a gateway on the map)'); E.gate.classList.toggle('on', S.gate >= 0); }
}
// tech tiles
const tech = S.priv && S.priv.tech ? S.priv.tech : {};
for (const b of E.tiles ? E.tiles.children : []) {
const id = b.dataset.tech, X = VS.TECH[id], lv = tech[id] || 0, max = lv >= X.max;
const cost = max ? 0 : VS.TECH_COST * Math.pow(2, lv);
const key = lv + '|' + (max ? 'm' : c >= cost ? 'y' : 'n');
if (b.dataset.k === key) continue;
b.dataset.k = key;
b.querySelector('.pips').textContent = '●'.repeat(lv) + '○'.repeat(X.max - lv);
setText(b.querySelector('.cost'), max ? 'MAX' : String(cost));
setCls(b, 'poor', !max && c < cost); setCls(b, 'maxed', max);
const nxt = max ? 'maxed out' : 'next: ' + techText(id, lv + 1);
b.title = nameOf(id) + ' ' + lv + '/' + X.max + ', ' + nxt;
b.setAttribute('aria-label', nameOf(id) + ', level ' + lv + ' of ' + X.max + ', ' + nxt + (max ? '' : ', ' + cost + ' credits') + (!max && c < cost ? ', not enough credits' : ''));
}
}
function tickDock(view) {
const att = S.role === 'attacker', c = att ? credits() : view.gold, table = att ? VS.ABILITIES : VS.TOOLS;
for (const id in table) {
const e = S.el[id]; if (!e) continue;
const T = table[id], left = cdLeft(id), frac = T.cd ? clamp(left / T.cd, 0, 1) : 0;
const q = Math.round(frac * 50);
if (e.ring !== q) { e.ring = q; e.b.style.setProperty('--p', String(q / 50)); }
const act = att ? actLeft(id) : 0;
const txt = act > 0 ? Math.ceil(act) + 's' : left > 0.05 ? Math.ceil(left) + 's' : '';
setText(e.cd, txt);
setCls(e.b, 'cooling', left > 0.05);
setCls(e.b, 'poor', left <= 0.05 && c < T.cost);
setCls(e.b, 'live', act > 0);
setCls(e.b, 'armed', (id === 'emp' && S.empArm) || (id === 'scan' && S.scanArm));
if (id === 'patch') { let any = false; for (const t of view.towers) if (t.empT > 0) { any = true; break; } setCls(e.b, 'idle', !any); }
if (id === 'repair') setCls(e.b, 'idle', view.lives >= view.maxLives);
if (id === 'emp') { // a selected tower makes EMP a one-tap action
const sel = app.selTower ? view.towers.find((t) => t.id === app.selTower) : null;
setCls(e.b, 'ready', !!sel && sel.type !== 'wall');
}
}
// the EMP button in the selected tower's action bar (attacker)
const eb = $('info').querySelector('[data-act="emp"]');
if (eb) {
const left = cdLeft('emp'), A = VS.ABILITIES.emp;
setCls(eb, 'poor', c < A.cost || left > 0.05);
const cost = eb.querySelector('.cost'); setText(cost, left > 0.05 ? Math.ceil(left) + 's' : String(A.cost));
}
}
function tickHud(view) {
const L = S.last, hud = $('vsHud');
let txt;
const alive = view.monsters.length;
if (S.role === 'attacker') txt = (S.priv && S.priv.income ? '+' + (Math.round(S.priv.income * 10) / 10) + '/s · ' : '') + alive + ' alive · def ' + view.gold + 'cr';
else txt = alive + ' alive' + (view.vs && view.vs.st ? ' · ' + view.vs.st + ' staged' : '');
if (L.hud !== txt) { L.hud = txt; hud.textContent = txt; }
}
function tickFx(t) {
const box = $('vsFx'), L = S.last;
if (S.decoys.size > 12) for (const [id, until] of S.decoys) if (until < t) S.decoys.delete(id);
const parts = [];
for (const id of ['surge', 'ddos', 'freeze']) {
const left = fxLeft(id);
if (left > 0) parts.push([id, Math.ceil(left)]);
}
const key = parts.map((p) => p.join(':')).join(',');
if (L.fx === key) return;
L.fx = key;
const label = { surge: 'SURGE: packets faster', ddos: 'DDoS: towers slowed', freeze: 'QUARANTINE: packets frozen' };
box.innerHTML = parts.map((p) => '' + label[p[0]] + ' ' + p[1] + 's').join('');
}
// ------------------------------------------------------------------ countdown / paused card on the stage
function renderCount() {
const box = $('vsCount'), m = S.vs;
if (!m || !S.role || m.phase === 'lobby' || m.phase === 'roundover' || m.phase === 'matchover' || (m.phase === 'playing' && !m.frozen)) { box.hidden = true; return; }
const att = S.role === 'attacker';
let html;
if (m.frozen) {
html = '
PAUSED
The other player lost the connection. The round waits for them (up to a minute), then you win.
';
} else {
const n = m.countdown !== undefined ? m.countdown : 0;
html = '
ROUND ' + m.round + ' OF ' + m.rounds + '
' +
'
YOU ' + (att ? 'ATTACK' : 'DEFEND') + '
' +
'
' + (att ? 'Spend credits on packets and break the server before the clock runs out.' : 'Build walls and turrets, keep the server alive until the clock runs out.') + '