One player defends, the other plays the Internet: earns credits over time and spends them on packets, upgrades and sabotage. Two rounds with swapped roles, timed (the faster fall wins). Built end to end, NOT yet QA'd or balanced. Sim (public/js/sim.js, TD.VS table): attacker economy (income, lifetime bonus, leak payback), spawn / stage / launch convoys, 7 tech tracks, abilities (EMP, decoy, surge, DDoS), defender tools (scan, patch, repair, quarantine), role-checked commands, round result, role-private state. Co-op/solo unchanged (24 scripted games replay identically). Bots (public/js/bot.js, tools/versus.js): defender (maze + turrets) and attacker (budgeted spender reading the tower mix); headless bot-vs-bot runner. Server (server/versus.js, protocol doc): versus rooms with lobby / countdown / playing / roundover / matchover, role stamping, cross-role refusal, role-private priv messages at 4 Hz, computer seat, freeze/forfeit rules, no pause/speed. Client (public/js/versus.js): setup dialog (role, length, vs computer or online), countdown, defender tools row, attacker unit shop with convoy + launch, tech and abilities, gateway choice, round/match screens, sounds, phone-first dock rows. Status and next steps (balance: the attacker currently wins ~100% of bot rounds; QA with two browsers; layout matrix rerun) are in docs/NEXT.md and docs/VERSUS.md. The full planned workflow incl. balance/QA prompts is in docs/workflows/versus-full.js. 253 unit tests pass; one smoke e2e run; no other e2e per the user's request. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
815 lines
50 KiB
JavaScript
815 lines
50 KiB
JavaScript
/*
|
||
* NETWALL versus UI (docs/VERSUS.md, docs/PROTOCOL.md "Versus"). Everything that is specific to the attack-vs-defend mode lives here: the setup and
|
||
* room dialogs, the round / match result dialog, the role-aware HUD (attacker: unit shop, convoy + Launch, abilities, tech; defender: counter-tools),
|
||
* the countdown card and the sounds for the new actions. main.js owns the rest (board, input, co-op, solo) and calls into this module at a few
|
||
* guarded places; with no versus game running (V.active false) none of it does anything, so solo and co-op behave as they always did.
|
||
*
|
||
* The module talks to a controller (LocalController against the computer, or RemoteController in an online room) only through the documented
|
||
* surface: ctrl.vs (match message), ctrl.priv (role-private data), ctrl.role, ctrl.view, ctrl.send(cmd), ctrl.vsRole / vsReady / vsBot / vsStart /
|
||
* vsNext / vsRematch. The role of a command is never set here: the controller (or the server) knows the seat.
|
||
*/
|
||
(function (root) {
|
||
'use strict';
|
||
const NW = root.NW = root.NW || {};
|
||
const TD = root.TD;
|
||
const VS = TD.VS;
|
||
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
||
const other = (r) => (r === 'attacker' ? 'defender' : 'attacker');
|
||
const roleCls = (r) => (r === 'attacker' ? 'attacker' : 'defender'); // (a role from the server goes into HTML only through this)
|
||
const cap1 = (s) => String(s).charAt(0).toUpperCase() + String(s).slice(1);
|
||
const mmss = (sec) => { sec = Math.max(0, Math.round(sec)); return Math.floor(sec / 60) + ':' + (sec % 60 < 10 ? '0' : '') + (sec % 60); };
|
||
const SVGNS = 'http://www.w3.org/2000/svg';
|
||
const icon = (id) => '<svg class="ic" aria-hidden="true"><use href="#' + id + '"/></svg>';
|
||
|
||
const SKILLS = [{ id: 'easy', name: 'Easy', v: 0.35 }, { id: 'normal', name: 'Normal', v: 0.7 }, { id: 'hard', name: 'Hard', v: 1 }];
|
||
const QTYS = [1, 5, 10];
|
||
const NAMES = {
|
||
armor: 'Armor', speed: 'Speed', health: 'Health', regen: 'Regen', shield: 'Shield', stealth: 'Stealth', crypt: 'Crypt',
|
||
emp: 'EMP', decoy: 'Decoy', surge: 'Surge', ddos: 'DDoS', scan: 'Scan', patch: 'Patch', repair: 'Repair', quarantine: 'Quarantine',
|
||
};
|
||
const nameOf = (id) => NAMES[id] || cap1(id);
|
||
const REASONS = {
|
||
role: "That is the other player's job", credits: 'Not enough credits', cooldown: 'Still cooling down', cap: 'Too many packets on the board', max: 'Nothing to do',
|
||
bad_target: 'Not a valid target', bad_kind: 'Unknown packet', empty: 'The convoy is empty', phase: 'The round has not started yet', frozen: 'Paused: waiting for the other player to come back',
|
||
versus: 'Not available in versus', not_host: 'Only the host can do that', no_opponent: 'Waiting for an opponent', offline: 'The opponent is offline',
|
||
not_ready: 'The opponent is not ready yet', full: 'Both seats are taken', over: 'The round is over',
|
||
};
|
||
|
||
// What a level of a tech upgrade does, worded from the table (a retune cannot leave this text wrong).
|
||
function techText(id, lv) {
|
||
const X = VS.TECH[id];
|
||
if (!X) return '';
|
||
switch (id) {
|
||
case 'armor': return '+' + +(X.per * lv).toFixed(2) + ' armour';
|
||
case 'speed': return '+' + Math.round(X.per * lv * 100) + '% speed';
|
||
case 'health': return '+' + Math.round(X.per * lv * 100) + '% hit points';
|
||
case 'regen': return Math.round(X.per * lv * 100) + '% of max hp back per second';
|
||
case 'shield': return '+' + Math.round(X.per * lv) + ' shield';
|
||
case 'stealth': return 'towers cannot target a packet for its first ' + X.secs[lv - 1] + ' s';
|
||
case 'crypt': return 'slows work ' + Math.round(X.res[lv - 1] * 100) + '% weaker';
|
||
default: return '';
|
||
}
|
||
}
|
||
function abilityText(id) {
|
||
const A = VS.ABILITIES[id];
|
||
if (!A) return '';
|
||
switch (id) {
|
||
case 'emp': return 'Disable one tower for ' + A.dur + ' s';
|
||
case 'decoy': return 'A harmless packet every tower shoots at for ' + A.dur + ' s';
|
||
case 'surge': return 'All packets ' + Math.round(A.speed * 100) + '% faster for ' + A.dur + ' s';
|
||
case 'ddos': return 'All towers fire ' + Math.round(A.slow * 100) + '% slower for ' + A.dur + ' s';
|
||
default: return '';
|
||
}
|
||
}
|
||
function toolText(id) {
|
||
const T = VS.TOOLS[id];
|
||
if (!T) return '';
|
||
switch (id) {
|
||
case 'scan': return 'Clear EMP and reveal stealth within ' + T.radius + ' cells for ' + T.reveal + ' s (tap the map)';
|
||
case 'patch': return 'Re-enable a disabled tower at once';
|
||
case 'repair': return 'Restore ' + T.amount + ' integrity';
|
||
case 'quarantine': return 'Freeze every packet for ' + T.dur + ' s';
|
||
default: return '';
|
||
}
|
||
}
|
||
|
||
// A segmented radiogroup (the same pattern as the difficulty picker): items [{ id, label, title? }]
|
||
function buildSeg(box, items, onPick) {
|
||
box.textContent = '';
|
||
for (const it of items) {
|
||
const b = document.createElement('button');
|
||
b.type = 'button'; b.dataset.v = it.id; b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', 'false');
|
||
b.textContent = it.label; if (it.title) b.title = it.title;
|
||
b.addEventListener('click', () => onPick(it.id));
|
||
box.appendChild(b);
|
||
}
|
||
}
|
||
function segSet(box, id) { for (const b of box.children) b.setAttribute('aria-checked', b.dataset.v === String(id) ? 'true' : 'false'); }
|
||
|
||
function create(api) {
|
||
const { $, app, renderer, Audio, store, esc, toast, banner, showOverlay } = api;
|
||
const S = {
|
||
ctrl: null, active: false, role: null, vs: null, priv: null, privAt: 0, phase: '',
|
||
qty: 1, mode: 'now', gate: -1, shopOn: false, scanArm: false, empArm: false,
|
||
cd: {}, act: {}, fx: { surge: 0, ddos: 0, freeze: 0 }, confirm: { key: '', until: 0 },
|
||
endTimer: 0, sentNext: false, sentRematch: false, el: {}, last: {}, built: '', decoys: new Map(),
|
||
setup: { role: store.get('nw.vs.role', 'random'), limit: store.get('nw.vs.limit', VS.DEFAULT_LIMIT), skill: store.get('nw.vs.skill', 'normal') },
|
||
};
|
||
if (!['attacker', 'defender', 'random'].includes(S.setup.role)) S.setup.role = 'random';
|
||
if (!VS.LIMITS.includes(S.setup.limit)) S.setup.limit = VS.DEFAULT_LIMIT;
|
||
if (!SKILLS.some((k) => k.id === S.setup.skill)) S.setup.skill = 'normal';
|
||
const UIS = { role: null, tech: null, gate: -1, gates: 1, scanArm: false, empArm: false, decoys: S.decoys }; // what the renderer needs (reused every frame)
|
||
const now = () => performance.now();
|
||
|
||
// ------------------------------------------------------------------ small helpers
|
||
const ctrl = () => S.ctrl;
|
||
const mySlot = () => (S.ctrl && S.ctrl.you && Number.isInteger(S.ctrl.you.slot) ? S.ctrl.you.slot : 0);
|
||
const roleOf = () => (S.ctrl && S.vs ? S.vs.roles[mySlot()] || null : null);
|
||
const players = () => (S.ctrl && S.ctrl.players) || [];
|
||
const playerName = (slot) => {
|
||
if (slot === mySlot()) return 'You';
|
||
if (S.vs && S.vs.bot && S.vs.bot.slot === slot) return S.vs.bot.name || 'Computer';
|
||
const p = players().find((q) => q.slot === slot);
|
||
return p ? p.name : 'Opponent';
|
||
};
|
||
const phasePlaying = () => !!S.vs && S.vs.phase === 'playing' && !S.vs.frozen;
|
||
const gates = () => (S.ctrl && S.ctrl.board ? S.ctrl.board.spawns.length : 1);
|
||
const skillValue = () => (SKILLS.find((k) => k.id === S.setup.skill) || SKILLS[1]).v;
|
||
const credits = () => { // the attacker's purse, run forward from the last private message (4 Hz) so it moves smoothly
|
||
const p = S.priv; if (!p || p.role !== 'attacker') return 0;
|
||
return Math.max(0, Math.floor(p.credits + p.income * clamp((now() - S.privAt) / 1000, 0, 0.6)));
|
||
};
|
||
const stagedTotal = () => { let n = 0; if (S.priv && S.priv.staged) for (const e of S.priv.staged) n += e[1]; return n; };
|
||
const cdLeft = (id) => { const c = S.cd[id]; return c ? Math.max(0, c.left - (now() - c.at) / 1000) : 0; };
|
||
const actLeft = (id) => { const c = S.act[id]; return c ? Math.max(0, c.left - (now() - c.at) / 1000) : 0; };
|
||
const fxLeft = (id) => Math.max(0, (S.fx[id] - now()) / 1000);
|
||
function say(text, kind) { // the pill at the top of the stage (armed states)
|
||
const n = $('vsNote');
|
||
if (!text) { n.hidden = true; return; }
|
||
n.hidden = false; n.textContent = text; n.className = 'hint ' + (kind || 'info');
|
||
}
|
||
function disarm() {
|
||
if (!S.scanArm && !S.empArm) return;
|
||
S.scanArm = false; S.empArm = false; say(null);
|
||
}
|
||
function confirmTap(key, text) { // a costly action asks for a second tap within 2.5 s
|
||
const t = now();
|
||
if (S.confirm.key === key && t < S.confirm.until) { S.confirm.key = ''; return true; }
|
||
S.confirm.key = key; S.confirm.until = t + 2500;
|
||
toast(text || 'Tap again to confirm', 'good');
|
||
return false;
|
||
}
|
||
function send(cmd) {
|
||
const c = S.ctrl; if (!c) return { ok: false };
|
||
return c.send(cmd);
|
||
}
|
||
function gateArg(cmd) { if (S.gate >= 0 && S.gate < gates()) cmd.gate = S.gate; return cmd; }
|
||
|
||
// ------------------------------------------------------------------ attach / detach (called by main.useController)
|
||
function attach(c) {
|
||
const on = !!c && c.mode === 'versus';
|
||
if (!on) {
|
||
if (S.active) teardown();
|
||
S.ctrl = c;
|
||
return;
|
||
}
|
||
S.ctrl = c; S.active = true;
|
||
S.vs = c.vs || null; S.priv = c.priv || null; S.privAt = now(); S.phase = '';
|
||
S.role = null; S.gate = -1; S.scanArm = false; S.empArm = false; S.sentNext = false; S.sentRematch = false;
|
||
S.cd = {}; S.act = {}; S.fx = { surge: 0, ddos: 0, freeze: 0 }; S.decoys.clear(); S.last = {};
|
||
clearTimeout(S.endTimer);
|
||
$('app').dataset.mode = 'versus';
|
||
if (c.kind === 'remote') { c.sendCursor = () => {}; c.sendMark = () => {}; } // the server ignores them in versus (an opponent must not see where you aim)
|
||
c.on('vs', (m) => { if (S.ctrl === c) onVs(m); });
|
||
c.on('priv', (m) => { if (S.ctrl === c) onPriv(m); });
|
||
c.on('newgame', () => { if (S.ctrl === c) { disarm(); S.gate = -1; S.last = {}; S.cd = {}; S.act = {}; S.decoys.clear(); S.fx = { surge: 0, ddos: 0, freeze: 0 }; } });
|
||
if (c.priv) onPriv(c.priv);
|
||
if (c.vs) onVs(c.vs);
|
||
}
|
||
function teardown() {
|
||
S.active = false; S.role = null; S.vs = null; S.priv = null; S.phase = '';
|
||
clearTimeout(S.endTimer); say(null);
|
||
const a = $('app'); delete a.dataset.mode; delete a.dataset.role;
|
||
for (const id of ['vsbar', 'vstech', 'vsHud', 'vsCount']) $(id).hidden = true;
|
||
$('vsbar').textContent = ''; $('vstech').textContent = ''; $('vsFx').textContent = '';
|
||
S.built = ''; S.el = {};
|
||
if (S.shopOn) { S.shopOn = false; api.buildPalette(); }
|
||
app.last.gold = undefined;
|
||
for (const id of ['vsRoom', 'vsEnd']) if (!$(id).hidden) showOverlay(null);
|
||
api.resize();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ messages
|
||
function onPriv(m) {
|
||
if (!m || m.role !== roleOf() && m.role !== (S.ctrl && S.ctrl.role)) return; // the first priv of a new round can race the vs message: a stale role is dropped
|
||
S.priv = m; S.privAt = now();
|
||
const t = now();
|
||
if (m.cd) for (const id in m.cd) S.cd[id] = { left: m.cd[id], at: t };
|
||
if (m.active) for (const id in m.active) S.act[id] = { left: m.active[id], at: t };
|
||
}
|
||
function onVs(m) {
|
||
if (!m) return;
|
||
const prev = S.phase;
|
||
S.vs = m; S.phase = m.phase;
|
||
syncRole();
|
||
if (m.phase !== prev) onPhase(prev, m.phase);
|
||
if (m.phase === 'lobby') renderRoom();
|
||
if (m.phase === 'roundover' || m.phase === 'matchover') { if (!$('vsEnd').hidden) renderEnd(); }
|
||
renderCount();
|
||
}
|
||
function onPhase(prev, ph) {
|
||
disarm(); S.confirm.key = '';
|
||
clearTimeout(S.endTimer);
|
||
if (ph === 'lobby') { showOverlay('vsRoom'); renderRoom(); }
|
||
else if (ph === 'countdown') {
|
||
S.sentNext = false; S.sentRematch = false;
|
||
hideMine(); S.gate = -1; S.last = {};
|
||
api.adoptBoard(); api.resetSelection(); // (a local match builds a new board for every round; the renderer must follow it)
|
||
Audio.music('battle');
|
||
} else if (ph === 'playing') {
|
||
hideMine();
|
||
if (prev === 'countdown') { banner(S.role === 'attacker' ? 'ATTACK!' : 'DEFEND!', S.role === 'attacker'); Audio.sfx('go'); }
|
||
} else if (ph === 'roundover' || ph === 'matchover') {
|
||
S.sentNext = false; S.sentRematch = false;
|
||
const won = ph === 'matchover' ? matchResult() === 'win' : roundWon();
|
||
Audio.music(null);
|
||
const show = () => { if (S.active && (S.phase === 'roundover' || S.phase === 'matchover')) { renderEnd(); showOverlay('vsEnd'); Audio.stinger(won ? 'win' : 'lose'); } };
|
||
if (prev === 'playing') S.endTimer = setTimeout(show, 1100); else show(); // a beat to watch the last second
|
||
}
|
||
}
|
||
function hideMine() { for (const id of ['vsRoom', 'vsEnd']) if (!$(id).hidden) { showOverlay(null); break; } }
|
||
function roundWon() { const r = S.vs && S.vs.result; return !!r && r.winner === roleOf(); }
|
||
function matchResult() { // 'win' | 'lose' | 'draw' for me, from the SERVER's verdict (never recomputed here)
|
||
const w = S.vs ? S.vs.winner : null;
|
||
if (w === null || w === undefined) return 'draw';
|
||
return w === mySlot() ? 'win' : 'lose';
|
||
}
|
||
|
||
// A role change (round 2, or the host moved the computer) rebuilds the dock: the palette becomes the unit shop for the attacker and the
|
||
// tower palette again for the defender.
|
||
function syncRole() {
|
||
const role = roleOf();
|
||
if (role === S.role) return;
|
||
S.role = role; S.priv = S.priv && S.priv.role === role ? S.priv : null;
|
||
disarm(); S.gate = -1; S.cd = {}; S.act = {};
|
||
$('app').dataset.role = role || '';
|
||
app.last.gold = undefined;
|
||
const att = role === 'attacker';
|
||
if (att) buildShop(); else if (S.shopOn) { S.shopOn = false; api.buildPalette(); }
|
||
buildDock();
|
||
app.selTower = 0; if (role) { api.selectType(null); }
|
||
api.renderInfo(true);
|
||
api.resize();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ the dock: unit shop, convoy row, abilities / tools, tech
|
||
function drawUnitIcon(cv, kind) {
|
||
const def = TD.ENEMIES[kind]; if (!def || !NW.drawMonster) return;
|
||
const dpr = Math.min(2, root.devicePixelRatio || 1), size = cv.clientWidth || 34;
|
||
cv.width = cv.height = Math.round(size * dpr);
|
||
const ctx = cv.getContext('2d');
|
||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, size, size);
|
||
const k = size * 0.36 / Math.max(def.r * NW.CELL * 1.3, 8);
|
||
ctx.translate(size / 2, size / 2 + (kind === 'ghost' ? 4 : 0)); ctx.scale(k, k);
|
||
NW.drawMonster(ctx, { kind, x: 0, y: 0, hp: 1, maxhp: 1, id: 1, slow: 0 }, -0.6, 0.3, 0, 0, false);
|
||
}
|
||
function drawShopIcons() { for (const b of $('palette').children) if (b.dataset.kind) drawUnitIcon(b.querySelector('canvas'), b.dataset.kind); }
|
||
function unitTip(kind) {
|
||
const d = TD.ENEMIES[kind];
|
||
return d.name + ', ' + d.buyCost + ' credits: ' + d.hp + ' hp' + (d.armor ? ', armour ' + d.armor : '') + ', speed ' + d.speed + (d.air ? ', flies' : '') + (d.heal || d.healRange ? ', heals others' : '');
|
||
}
|
||
function buildShop() {
|
||
const pal = $('palette');
|
||
pal.textContent = '';
|
||
pal.classList.toggle('many', TD.ENEMY_ORDER.length > 6);
|
||
pal.classList.add('shop');
|
||
for (const kind of TD.ENEMY_ORDER) {
|
||
const d = TD.ENEMIES[kind];
|
||
const b = document.createElement('button');
|
||
b.className = 'tbtn ubtn'; b.dataset.kind = kind; b.type = 'button';
|
||
b.innerHTML = '<span class="key"></span><canvas></canvas><span class="nm"></span><span class="cost"></span>';
|
||
b.querySelector('.nm').textContent = d.name;
|
||
b.title = unitTip(kind);
|
||
b.addEventListener('click', () => { Audio.unlock(); buy(kind); b.classList.add('hit'); setTimeout(() => b.classList.remove('hit'), 160); });
|
||
pal.appendChild(b);
|
||
}
|
||
[...pal.children].forEach((b, i) => { b.querySelector('.key').textContent = i < 9 ? String(i + 1) : ''; });
|
||
S.shopOn = true; S.last.shop = '';
|
||
drawShopIcons();
|
||
api.updatePaletteHint();
|
||
}
|
||
function buildDock() {
|
||
const bar = $('vsbar'), tech = $('vstech');
|
||
bar.textContent = ''; tech.textContent = ''; S.el = {};
|
||
const att = S.role === 'attacker', def = S.role === 'defender';
|
||
bar.hidden = !(att || def); tech.hidden = !att;
|
||
$('vsHud').hidden = !S.role;
|
||
if (att) {
|
||
const abil = VS.ABILITY_ORDER.map((id) => dockBtn('ab', id, VS.ABILITIES[id].cost)).join('');
|
||
bar.innerHTML =
|
||
'<div class="vsrow vsctlrow"><button type="button" class="vsctl" id="vsQty"></button><button type="button" class="vsctl" id="vsMode"></button>' +
|
||
'<button type="button" class="vsctl" id="vsGateBtn" hidden></button>' +
|
||
'<button type="button" class="primary vslaunch" id="vsLaunch" disabled>' + icon('i-launch') + '<span class="lt"><b>LAUNCH</b><small></small></span></button></div>' +
|
||
'<div class="vsrow vsabil" id="vsAbil">' + abil + '</div>';
|
||
tech.innerHTML = '<div class="vshead"><span>Tech</span><small>permanent, for packets sent from now on</small></div><div class="vstiles" id="vsTiles"></div>';
|
||
const tiles = tech.querySelector('#vsTiles');
|
||
for (const id of VS.TECH_ORDER) {
|
||
const b = document.createElement('button');
|
||
b.type = 'button'; b.className = 'tbtn techbtn'; b.dataset.tech = id;
|
||
b.innerHTML = icon('i-te-' + id) + '<span class="nm"></span><span class="pips"></span><span class="cost"></span>';
|
||
b.querySelector('.nm').textContent = nameOf(id);
|
||
tiles.appendChild(b);
|
||
}
|
||
S.el = { qty: bar.querySelector('#vsQty'), mode: bar.querySelector('#vsMode'), gate: bar.querySelector('#vsGateBtn'), launch: bar.querySelector('#vsLaunch'), launchSub: bar.querySelector('#vsLaunch small'), tiles };
|
||
S.el.qty.addEventListener('click', () => { S.qty = QTYS[(QTYS.indexOf(S.qty) + 1) % QTYS.length]; Audio.sfx('click'); S.last.shop = ''; });
|
||
S.el.mode.addEventListener('click', () => { S.mode = S.mode === 'now' ? 'stage' : 'now'; Audio.sfx('click'); });
|
||
S.el.gate.addEventListener('click', () => { Audio.sfx('click'); setGate(S.gate + 1 >= gates() ? -1 : S.gate + 1); });
|
||
S.el.launch.addEventListener('click', launch);
|
||
bar.querySelector('#vsAbil').addEventListener('click', (e) => { const b = e.target.closest('button[data-ab]'); if (b) { Audio.unlock(); ability(b.dataset.ab); } });
|
||
tiles.addEventListener('click', (e) => { const b = e.target.closest('button[data-tech]'); if (b) { Audio.unlock(); buyTech(b.dataset.tech); } });
|
||
S.last.dock = ''; S.last.shop = '';
|
||
} else if (def) {
|
||
bar.innerHTML = '<div class="vsrow vsabil vstools" id="vsAbil">' + VS.TOOL_ORDER.map((id) => dockBtn('tl', id, VS.TOOLS[id].cost)).join('') + '</div>';
|
||
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 '<button type="button" class="vsbtn" data-' + kind + '="' + id + '" title="' + esc(nameOf(id) + ': ' + tip) + '" aria-label="' + esc(nameOf(id) + ', ' + cost + ' credits. ' + tip) + '">' +
|
||
icon(kind === 'ab' ? 'i-ab-' + id : 'i-tl-' + id) + '<span class="nm">' + esc(nameOf(id)) + '</span><span class="cost">' + cost + '</span><span class="cd"></span></button>';
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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) => '<span class="fxchip ' + p[0] + '">' + label[p[0]] + ' ' + p[1] + 's</span>').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 = '<div class="vsc-big">PAUSED</div><div class="vsc-sub">The other player lost the connection. The round waits for them (up to a minute), then you win.</div>';
|
||
} else {
|
||
const n = m.countdown !== undefined ? m.countdown : 0;
|
||
html = '<div class="vsc-top">ROUND ' + m.round + ' OF ' + m.rounds + '</div>' +
|
||
'<div class="vsc-role ' + (att ? 'att' : 'def') + '">YOU ' + (att ? 'ATTACK' : 'DEFEND') + '</div>' +
|
||
'<div class="vsc-sub">' + (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.') + '</div>' +
|
||
'<div class="vsc-num" aria-hidden="true">' + n + '</div>';
|
||
if (S.last.cd !== n) { S.last.cd = n; if (n > 0) Audio.sfx('tick'); }
|
||
}
|
||
if (S.last.countHtml !== html) { S.last.countHtml = html; box.innerHTML = html; }
|
||
box.hidden = false;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ dialogs: setup, room, result
|
||
function initDialogs() {
|
||
buildSeg($('vsRolePick'), [{ id: 'attacker', label: 'Attack' }, { id: 'defender', label: 'Defend' }, { id: 'random', label: 'Random' }], (v) => { Audio.sfx('click'); S.setup.role = v; store.set('nw.vs.role', v); segSet($('vsRolePick'), v); });
|
||
buildSeg($('vsLimitPick'), VS.LIMITS.map((s) => ({ id: s, label: Math.round(s / 60) + ' min' })), (v) => { Audio.sfx('click'); S.setup.limit = +v; store.set('nw.vs.limit', +v); segSet($('vsLimitPick'), v); });
|
||
buildSeg($('vsSkillPick'), SKILLS.map((k) => ({ id: k.id, label: k.name })), (v) => { Audio.sfx('click'); S.setup.skill = v; store.set('nw.vs.skill', v); segSet($('vsSkillPick'), v); });
|
||
segSet($('vsRolePick'), S.setup.role); segSet($('vsLimitPick'), S.setup.limit); segSet($('vsSkillPick'), S.setup.skill);
|
||
$('vsCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
|
||
$('vsCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnVsJoin').click(); });
|
||
$('btnVsBack').addEventListener('click', () => { msg(''); api.cancelPending(); if (app.inGame) api.closeOverlayToGame(); else api.openMenu(); });
|
||
$('btnVsComputer').addEventListener('click', () => { Audio.unlock(); msg(''); api.startLocal({ role: S.setup.role, limit: S.setup.limit, skill: skillValue() }); });
|
||
$('btnVsCreate').addEventListener('click', () => { Audio.unlock(); api.connect({ room: null, map: app.mapId, mode: 'versus', limit: S.setup.limit, name: $('vsName').value, say: msg }); });
|
||
$('btnVsJoin').addEventListener('click', () => {
|
||
const code = $('vsCode').value.trim().toUpperCase();
|
||
if (!/^[A-Z0-9]{4}$/.test(code)) { msg('Enter the 4 character room code.', true); return; }
|
||
api.connect({ room: code, name: $('vsName').value, say: msg });
|
||
});
|
||
// room
|
||
buildSeg($('vsRoomRole'), [{ id: 'attacker', label: 'Attack' }, { id: 'defender', label: 'Defend' }, { id: 'random', label: 'Random' }], (v) => { Audio.sfx('click'); if (S.ctrl) S.ctrl.vsRole(v); });
|
||
buildSeg($('vsRoomOpp'), [{ id: 'friend', label: 'A friend' }, { id: 'computer', label: 'Computer' }], (v) => {
|
||
Audio.sfx('click');
|
||
if (!S.ctrl) return;
|
||
if (v === 'computer') { const mine = roleOf() || 'attacker'; S.ctrl.vsBot(other(mine), skillValue()); } else S.ctrl.vsBot(null);
|
||
});
|
||
$('btnVsReady').addEventListener('click', () => { Audio.sfx('click'); const me = mySlot(); S.ctrl.vsReady(!(S.vs && S.vs.ready && S.vs.ready[me])); });
|
||
$('btnVsStart').addEventListener('click', () => { Audio.sfx('click'); S.ctrl.vsStart(); });
|
||
$('btnVsInvite').addEventListener('click', () => api.invite());
|
||
$('btnVsLeave').addEventListener('click', () => api.exitToMenu());
|
||
// result
|
||
$('btnVsNext').addEventListener('click', () => { Audio.sfx('click'); S.sentNext = true; S.ctrl.vsNext(); renderEnd(); });
|
||
$('btnVsRematch').addEventListener('click', () => { Audio.sfx('click'); S.sentRematch = true; S.ctrl.vsRematch(); renderEnd(); });
|
||
$('btnVsEndMenu').addEventListener('click', () => api.exitToMenu());
|
||
}
|
||
function msg(text, bad) { const m = $('vsMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
|
||
function openSetup(code) {
|
||
$('vsName').value = store.get('nw.name', '') || '';
|
||
$('vsMapName').textContent = 'Map: ' + TD.MAPS[app.mapId].name + ' (pick another in the menu)';
|
||
segSet($('vsRolePick'), S.setup.role); segSet($('vsLimitPick'), S.setup.limit); segSet($('vsSkillPick'), S.setup.skill);
|
||
msg(root.location.protocol === 'file:' ? 'Online play needs the Netwall server (npm start). Against the computer works from the file.' : '');
|
||
showOverlay('vsSetup'); api.setScreen(app.inGame ? 'playing' : 'menu');
|
||
if (code) { $('vsCode').value = code; $('btnVsJoin').focus({ preventScroll: true }); }
|
||
}
|
||
|
||
// ---- the online room (lobby phase)
|
||
function renderRoom() {
|
||
const c = S.ctrl, m = S.vs;
|
||
if (!c || !m || m.phase !== 'lobby') return;
|
||
const me = mySlot(), isHost = !!(c.you && c.you.host), opp = 1 - me;
|
||
const oppP = players().find((p) => p.slot === opp), botOpp = !!(m.bot && m.bot.slot === opp);
|
||
$('vsRoomCode').textContent = 'Room ' + (c.room || '');
|
||
$('vsRoomLimit').textContent = 'Round: ' + mmss(m.limit) + ' · 2 rounds, roles swap';
|
||
let seats = '';
|
||
for (const slot of [0, 1]) {
|
||
const p = players().find((q) => q.slot === slot), isBot = !!(m.bot && m.bot.slot === slot), role = roleCls(m.roles[slot]);
|
||
const nm = isBot ? (m.bot.name || 'Computer') : p ? p.name : null;
|
||
const rdy = isBot || (p && p.host) || (m.ready && m.ready[slot]);
|
||
seats += '<div class="vsseat' + (nm ? '' : ' empty') + '"><span class="dot" style="background:' + api.slotColor(slot) + '"></span>' +
|
||
'<span class="sn">' + (nm ? esc(nm) : 'Waiting for an opponent…') + '</span>' +
|
||
(p && c.you && p.pid === c.you.pid ? '<span class="you">(you)</span>' : '') + (p && p.host ? '<span class="you">host</span>' : '') + (p && !p.online ? '<span class="off">offline</span>' : '') +
|
||
(nm ? '<span class="rolebadge ' + role + '">' + (role === 'attacker' ? 'ATTACK' : 'DEFEND') + '</span><span class="rdy' + (rdy ? ' ok' : '') + '">' + (rdy ? '✓ ready' : 'not ready') + '</span>' : '') + '</div>';
|
||
}
|
||
$('vsSeats').innerHTML = seats;
|
||
segSet($('vsRoomRole'), m.random ? 'random' : roleOf());
|
||
$('vsOppField').hidden = !isHost;
|
||
segSet($('vsRoomOpp'), m.bot ? 'computer' : 'friend');
|
||
$('vsRoomNote').textContent = m.random ? 'Roles are drawn at random: you ' + (roleOf() === 'attacker' ? 'attack' : 'defend') + ' first, then it swaps.' : 'You ' + (roleOf() === 'attacker' ? 'attack' : 'defend') + ' first, then it swaps.';
|
||
let why = '';
|
||
if (!oppP && !botOpp) why = 'Waiting for an opponent to join. Share the invite, or play the computer.';
|
||
else if (oppP && !oppP.online) why = oppP.name + ' is offline.';
|
||
else if (oppP && !(m.ready && m.ready[opp])) why = 'Waiting for ' + oppP.name + ' to get ready.';
|
||
const imReady = !!(m.ready && m.ready[me]);
|
||
$('btnVsStart').hidden = !isHost;
|
||
$('btnVsStart').disabled = !!why;
|
||
$('btnVsReady').hidden = isHost;
|
||
$('btnVsReady').textContent = imReady ? 'Ready (tap to undo)' : "I'm ready";
|
||
$('btnVsReady').setAttribute('aria-pressed', imReady ? 'true' : 'false');
|
||
$('btnVsReady').classList.toggle('on', imReady);
|
||
const mm = $('vsRoomMsg');
|
||
mm.textContent = isHost ? why : imReady ? 'Waiting for the host to start.' : 'Press ready when you are.';
|
||
mm.className = 'msg';
|
||
}
|
||
|
||
// ---- round over / match over
|
||
function entryText(h) {
|
||
const r = h.result;
|
||
if (r.forfeit) return 'Forfeited';
|
||
return r.winner === 'attacker' ? 'Server fell at ' + mmss(r.t) : 'Server held for ' + mmss(r.t);
|
||
}
|
||
function renderEnd() {
|
||
const m = S.vs; if (!m || (m.phase !== 'roundover' && m.phase !== 'matchover')) return;
|
||
const me = mySlot(), over = m.phase === 'matchover', c = S.ctrl;
|
||
const hist = (m.history || []).slice();
|
||
if (m.result && !hist.some((h) => h.round === m.round)) hist.push({ round: m.round, roles: m.roles, result: m.result });
|
||
let title, text, color;
|
||
if (over) {
|
||
const res = matchResult();
|
||
title = res === 'win' ? 'You win the match!' : res === 'lose' ? 'You lose the match' : 'A draw';
|
||
color = res === 'win' ? 'var(--green)' : res === 'lose' ? 'var(--red)' : 'var(--amber)';
|
||
if (m.forfeit !== null && m.forfeit !== undefined) text = m.forfeit === me ? 'You left the match.' : playerName(m.forfeit) + ' left the match. You win by forfeit.';
|
||
else text = reasonText(m);
|
||
} else {
|
||
const won = roundWon(), r = m.result || {};
|
||
title = 'Round ' + m.round + ': ' + (won ? 'you won' : 'you lost');
|
||
color = won ? 'var(--green)' : 'var(--red)';
|
||
text = (r.winner === 'attacker' ? 'The server fell after ' + mmss(r.t) + '.' : 'The server held for the whole ' + mmss(r.t) + '.') + ' Integrity lost: ' + (r.integrityLost || 0) + '. ' +
|
||
'Next round you ' + (other(roleOf()) === 'attacker' ? 'attack' : 'defend') + '.';
|
||
}
|
||
$('vsEndTitle').textContent = title; $('vsEndTitle').style.color = color;
|
||
$('vsEndText').textContent = text;
|
||
// both rounds side by side
|
||
const cols = hist.map((h) => {
|
||
const mine = roleCls(h.roles[me]), won = h.result.winner === mine;
|
||
return '<div class="vsround"><h4>Round ' + h.round + '</h4>' +
|
||
'<div class="vsrow2"><span>You were</span><b class="rolebadge ' + mine + '">' + (mine === 'attacker' ? 'ATTACKER' : 'DEFENDER') + '</b></div>' +
|
||
'<div class="vsrow2"><span>Result</span><b>' + esc(entryText(h)) + '</b></div>' +
|
||
'<div class="vsrow2"><span>Integrity lost</span><b>' + esc(h.result.integrityLost || 0) + '</b></div>' +
|
||
'<div class="vsrow2"><span>Round won by</span><b class="' + (won ? 'good' : 'bad') + '">' + (won ? 'you' : esc(playerName(1 - me))) + '</b></div></div>';
|
||
});
|
||
if (!over) cols.push('<div class="vsround pending"><h4>Round ' + (m.round + 1) + '</h4><div class="vsrow2"><span>You will</span><b class="rolebadge ' + other(roleOf()) + '">' + (other(roleOf()) === 'attacker' ? 'ATTACK' : 'DEFEND') + '</b></div></div>');
|
||
let score = '';
|
||
if (over && m.scores && !(m.forfeit !== null && m.forfeit !== undefined)) {
|
||
score = '<div class="vsscore"><h4>Who attacked best</h4>' + m.scores.map((s) =>
|
||
'<div class="vsrow2"><span>' + esc(s.slot === me ? 'You' : playerName(s.slot)) + '</span><b>' + (s.fellAt !== null && s.fellAt !== undefined ? 'felled the server at ' + mmss(s.fellAt) : 'did not fell it, took off ' + (s.integrityLost || 0)) + '</b></div>').join('') + '</div>';
|
||
}
|
||
$('vsEndRounds').innerHTML = '<div class="vscols">' + cols.join('') + '</div>' + score;
|
||
// buttons and waiting text
|
||
const oppHere = c.kind === 'local' || !!(m.bot) || players().some((p) => p.slot !== me && p.online);
|
||
$('btnVsNext').hidden = over; $('btnVsRematch').hidden = !over;
|
||
$('btnVsNext').disabled = S.sentNext;
|
||
$('btnVsRematch').disabled = S.sentRematch || !oppHere;
|
||
$('btnVsRematch').textContent = 'Rematch (roles swap)';
|
||
const w = $('vsEndWait'); let wt = '';
|
||
if (!over && S.sentNext) wt = 'Waiting for the other player' + (m.nextIn ? ' (the next round starts anyway in ' + m.nextIn + ' s)' : '') + '…';
|
||
else if (!over && m.next && m.next[1 - me] && c.kind === 'remote' && !m.bot) wt = playerName(1 - me) + ' is ready for the next round.';
|
||
else if (over && S.sentRematch) wt = 'Waiting for the other player to accept the rematch…';
|
||
else if (over && m.rematch && m.rematch[1 - me] && !S.sentRematch && !m.bot) wt = playerName(1 - me) + ' wants a rematch.';
|
||
else if (over && !oppHere) wt = 'The other player has left.';
|
||
w.hidden = !wt; w.textContent = wt;
|
||
}
|
||
function reasonText(m) {
|
||
const sc = m.scores; if (!sc) return '';
|
||
const a = sc[0], b = sc[1], nm = (s) => (s.slot === mySlot() ? 'you' : playerName(s.slot));
|
||
if (a.fellAt !== null && b.fellAt !== null) return a.fellAt === b.fellAt ? 'Both servers fell at the same second.' : 'The faster fall wins: ' + nm(a) + ' ' + mmss(a.fellAt) + ', ' + nm(b) + ' ' + mmss(b.fellAt) + '.';
|
||
if (a.fellAt !== null || b.fellAt !== null) { const w = a.fellAt !== null ? a : b; return 'Only ' + nm(w) + ' felled the server (' + mmss(w.fellAt) + ').'; }
|
||
if (a.integrityLost === b.integrityLost) return 'Neither server fell, and the same integrity was taken off.';
|
||
return 'Neither server fell: the attacker who took off more integrity wins (' + nm(a) + ' ' + (a.integrityLost || 0) + ', ' + nm(b) + ' ' + (b.integrityLost || 0) + ').';
|
||
}
|
||
// the room code box of the setup dialog is filled by an invite link (?room=ABCD)
|
||
function onRoomWait(code) { openSetup(code); }
|
||
|
||
initDialogs();
|
||
return {
|
||
get active() { return S.active; }, get role() { return S.role; }, get shopOn() { return S.shopOn; }, get phase() { return S.phase; }, state: S,
|
||
attach, tick, tapCell, key, onEvent, leakSfx, isDecoy, minSide, uiState, holdsOverlay, refreshOverlay, openSetup, onRoomWait, renderRoom, renderEnd,
|
||
drawShopIcons, castEmp, disarm, msg, say, decoys: S.decoys, REASONS, matchResult,
|
||
};
|
||
}
|
||
|
||
NW.Versus = { create, techText, abilityText, toolText };
|
||
})(typeof self !== 'undefined' ? self : this);
|