Versus mode: attack vs defend (sim, bots, server, client)
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
This commit is contained in:
parent
b4ae6cb57d
commit
2098d59c1f
23 changed files with 6166 additions and 90 deletions
|
|
@ -97,6 +97,14 @@
|
|||
syncModal();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ versus (js/versus.js): the mode's dialogs, HUD and sounds. With no versus game running (V.active false) it does nothing.
|
||||
const V = NW.Versus.create({
|
||||
$, app, renderer, Audio, store, esc, toast, banner, showOverlay, slotColor,
|
||||
buildPalette, selectType, renderInfo, updatePaletteHint, setScreen, renderPlayers, adoptBoard, resetSelection,
|
||||
resize: () => scheduleResize(), startLocal: startVersusLocal, connect: connectRemote, cancelPending, invite, exitToMenu, openMenu, closeOverlayToGame,
|
||||
});
|
||||
for (const k in V.REASONS) if (!(k in REASONS)) REASONS[k] = V.REASONS[k]; // the versus refusals get words (existing ones keep theirs)
|
||||
|
||||
// ------------------------------------------------------------------ dialogs (menu, lobby, help, end are role=dialog)
|
||||
// While one is open the page behind it is inert (not focusable, not clickable, hidden from screen readers), focus moves into the
|
||||
// dialog onto its primary button, Tab stays inside it, and focus goes back to where it was when the dialog closes (code-8).
|
||||
|
|
@ -113,7 +121,7 @@
|
|||
if (ov) {
|
||||
const btns = [...ov.querySelectorAll('button')].filter(isShown);
|
||||
const first = btns.find((b) => b.classList.contains('primary')) || btns[0]; // never a text field: on a phone that would raise the keyboard
|
||||
if (ov.id === 'end') modal.guard = performance.now() + 600; // (see the click guard below)
|
||||
if (ov.id === 'end' || ov.id === 'vsEnd') modal.guard = performance.now() + 600; // (see the click guard below)
|
||||
if (first) first.focus({ preventScroll: true });
|
||||
} else if (was) {
|
||||
const o = modal.opener; modal.opener = null;
|
||||
|
|
@ -132,7 +140,7 @@
|
|||
{ const mo = new MutationObserver(syncModal); for (const o of document.querySelectorAll('.overlay')) mo.observe(o, { attributes: true, attributeFilter: ['hidden'] }); }
|
||||
// The game-over dialog takes focus the moment the game ends, and a player who was tapping Space / Enter to start waves would
|
||||
// press its focused "Play again" with the next key and never see the result. For the first 0.6 s only a pointer can press its buttons.
|
||||
$('end').addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
|
||||
for (const id of ['end', 'vsEnd']) $(id).addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
|
||||
function setScreen(name) {
|
||||
app.screen = name;
|
||||
$('app').dataset.screen = name;
|
||||
|
|
@ -148,11 +156,13 @@
|
|||
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('vs', () => { if (ctrl === app.ctrl && ctrl.kind === 'remote') renderPlayers(); }); // the roles are part of the players panel
|
||||
ctrl.on('newgame', () => {
|
||||
resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true;
|
||||
app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5)
|
||||
if (ctrl.kind === 'remote') renderPlayers(); // (the room header names the difficulty, which a new game may have changed)
|
||||
});
|
||||
V.attach(ctrl); // a versus controller switches the HUD to versus, any other one switches it back
|
||||
adoptBoard(true);
|
||||
}
|
||||
function adoptBoard(force) {
|
||||
|
|
@ -184,6 +194,21 @@
|
|||
requestWakeLock();
|
||||
firstRunHelp();
|
||||
}
|
||||
// A versus match against the computer: no server, no lobby (the controller starts in its countdown). opts: { role, limit, skill, countdownMs?, seed? }
|
||||
function startVersusLocal(opts) {
|
||||
cancelPending();
|
||||
leaveRemote(true);
|
||||
store.set('nw.map', app.mapId);
|
||||
const c = new NW.LocalController({ map: app.mapId, mode: 'versus', role: opts.role, limit: opts.limit, skill: opts.skill, countdownMs: opts.countdownMs, seed: opts.seed });
|
||||
useController(c);
|
||||
app.inGame = true; app.started = true; app.endShown = false; app.last = {};
|
||||
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
|
||||
renderInfo(true);
|
||||
app.bossMusic = false; Audio.music('battle');
|
||||
requestWakeLock();
|
||||
return c;
|
||||
}
|
||||
// The first-run help opens once per install (storage) and at most once per page load, so a browser whose storage throws does not get it on every start (code-26).
|
||||
function firstRunHelp() {
|
||||
if (app.helpSeen) return;
|
||||
|
|
@ -221,10 +246,10 @@
|
|||
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 'leak': Audio.sfx(V.leakSfx()); 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;
|
||||
default: if (V.active) V.onEvent(e); break; // versus: emp, decoy, surge, ddos, quarantine, scan, repair
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -243,7 +268,7 @@
|
|||
function priceOf(type) { return TD.priceFor(type, app.ctrl && app.ctrl.view ? app.ctrl.view.towers : 0); }
|
||||
function buildPalette() {
|
||||
const pal = $('palette');
|
||||
pal.textContent = '';
|
||||
pal.textContent = ''; pal.classList.remove('shop');
|
||||
pal.classList.toggle('many', TD.TOWER_ORDER.length > 6);
|
||||
for (const type of TD.TOWER_ORDER) {
|
||||
const def = TD.TOWERS[type];
|
||||
|
|
@ -279,9 +304,11 @@
|
|||
}
|
||||
$('palette').addEventListener('scroll', updatePaletteHint, { passive: true });
|
||||
function drawPaletteIcons() {
|
||||
if (V.shopOn) { V.drawShopIcons(); return; } // the attacker's palette is the unit shop
|
||||
for (const b of $('palette').children) NW.drawIcon(b.querySelector('canvas'), b.dataset.type, 1);
|
||||
}
|
||||
function syncPalette() {
|
||||
if (V.shopOn) return; // (the attacker's unit shop has nothing to select)
|
||||
for (const b of $('palette').children) {
|
||||
const sel = b.dataset.type === app.selType;
|
||||
b.classList.toggle('sel', sel);
|
||||
|
|
@ -290,6 +317,7 @@
|
|||
}
|
||||
}
|
||||
function selectType(type) {
|
||||
if (type && V.active) V.disarm();
|
||||
app.selType = type; app.selTower = 0; app.pending = null; app.previewDirty = true;
|
||||
syncPalette(); renderInfo(true); updateConfirm();
|
||||
if (!type) { ui.preview = null; hint(null); }
|
||||
|
|
@ -329,7 +357,7 @@
|
|||
if (!tower) app.selTower = 0;
|
||||
}
|
||||
if (tower) {
|
||||
if (ctrl.kind === 'remote' && ctrl.players.length > 1) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
|
||||
if (ctrl.kind === 'remote' && ctrl.players.length > 1 && !V.active) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
|
||||
shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : '');
|
||||
} else if (app.selType) shape = 'b' + app.selType + ':' + priceOf(app.selType); // the price can change while armed (Orbital Uplink)
|
||||
if (!force && shape === info.shape) { if (tower) syncInfo(); return; }
|
||||
|
|
@ -337,12 +365,13 @@
|
|||
info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false;
|
||||
if (!shape) { box.textContent = ''; return; }
|
||||
if (tower) {
|
||||
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', aim = aimsAtTargets(def);
|
||||
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', att = V.active && V.role === 'attacker', aim = aimsAtTargets(def) && !att;
|
||||
const empBtn = att && !wall ? '<button type="button" data-act="emp" title="Disable this tower for a few seconds"><svg class="ic"><use href="#i-ab-emp"/></svg><span class="w">EMP</span><span class="cost"></span></button>' : '';
|
||||
box.innerHTML =
|
||||
'<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' +
|
||||
'<div class="desc"></div><div class="kv"></div><div class="actions">' +
|
||||
(wall ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
|
||||
'<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>' +
|
||||
(wall || att ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
|
||||
(att ? empBtn : '<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>') +
|
||||
(aim ? '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>' : '') +
|
||||
'<button type="button" data-act="close" class="icon" aria-label="Close" title="Close"><svg class="ic"><use href="#i-x"/></svg></button></div>' +
|
||||
'<div class="byline">' + (aim ? '<span id="infoKills"></span>' : '') + (ownerP ? '<span class="dot" style="background:' + slotColor(ownerP.slot) + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
|
||||
|
|
@ -396,8 +425,7 @@
|
|||
up.setAttribute('aria-label', canUp ? 'Upgrade for ' + upCost + ' credits' : 'Max level');
|
||||
}
|
||||
const sell = box.querySelector('[data-act="sell"]');
|
||||
setText(sell.querySelector('.cost'), String(sellVal));
|
||||
sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits');
|
||||
if (sell) { setText(sell.querySelector('.cost'), String(sellVal)); sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits'); } // (the attacker's panel has no Sell)
|
||||
const mode = box.querySelector('[data-act="mode"]');
|
||||
if (mode) { setText(mode.querySelector('.mv'), MODE_NAMES[t.mode]); mode.setAttribute('aria-label', 'Target: ' + MODE_NAMES[t.mode] + '. Tap to change'); }
|
||||
setText(box.querySelector('#infoKills'), t.kills + (t.kills === 1 ? ' kill' : ' kills'));
|
||||
|
|
@ -421,6 +449,7 @@
|
|||
case 'up': ctrl.send({ c: 'upgrade', id: tower.id }); break;
|
||||
case 'sell': ctrl.send({ c: 'sell', id: tower.id }); app.selTower = 0; renderInfo(true); app.previewDirty = true; break;
|
||||
case 'close': selectTower(0); break;
|
||||
case 'emp': V.castEmp(tower.id); 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;
|
||||
|
|
@ -430,6 +459,7 @@
|
|||
});
|
||||
|
||||
function renderWavePanel(view) {
|
||||
if (V.active) { if (app.last.waveKey !== 'vs') { app.last.waveKey = 'vs'; $('nextwave').textContent = ''; } return; } // versus has no waves
|
||||
const n = view.wave + 1;
|
||||
const dif = viewDifficulty(view);
|
||||
const key = n + ':' + view.state + ':' + dif;
|
||||
|
|
@ -455,7 +485,7 @@
|
|||
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;
|
||||
ui.coop = list.length > 1 && !V.active; // (owner flags on the towers are for co-op: in versus one side builds everything)
|
||||
// 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'); }
|
||||
|
|
@ -472,12 +502,13 @@
|
|||
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
|
||||
box.hidden = false;
|
||||
const dif = viewDifficulty(ctrl.view);
|
||||
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span> <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
|
||||
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + (V.active ? '<span class="dtag" title="Attack versus defend">VERSUS</span>' : '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span>') + ' <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
|
||||
for (const p of ctrl.players) {
|
||||
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
|
||||
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
|
||||
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') +
|
||||
(V.active && ctrl.vs && ctrl.vs.roles && ctrl.vs.roles[p.slot] ? (ctrl.vs.roles[p.slot] === 'attacker' ? '<span class="rolebadge attacker">ATTACK</span>' : '<span class="rolebadge defender">DEFEND</span>') : '') + '</div>';
|
||||
}
|
||||
if (ctrl.players.length < 2) html += '<div class="muted small">Waiting for a partner… share the invite link.</div>';
|
||||
if (ctrl.players.length < 2 && !(V.active && ctrl.vs && ctrl.vs.bot)) html += '<div class="muted small">Waiting for ' + (V.active ? 'an opponent' : 'a partner') + '… share the invite link.</div>';
|
||||
html += '<div class="actions"><button type="button" data-act="invite"><svg class="ic"><use href="#i-share"/></svg>Invite</button><button type="button" data-act="leave" class="danger">Leave</button></div></div>';
|
||||
box.innerHTML = html;
|
||||
const names = box.querySelectorAll('.pn');
|
||||
|
|
@ -500,7 +531,7 @@
|
|||
// ------------------------------------------------------------------ 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 (!(V.active && V.role === 'attacker') && L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); } // (the attacker's top bar shows its own purse: versus.js)
|
||||
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);
|
||||
|
|
@ -526,7 +557,7 @@
|
|||
// palette affordability
|
||||
const gold = view.gold;
|
||||
const palKey = gold + ':' + view.towers.length; // prices can change when the tower count does (Orbital Uplink)
|
||||
if (L.palGold !== palKey) {
|
||||
if (!V.shopOn && L.palGold !== palKey) {
|
||||
L.palGold = palKey;
|
||||
for (const b of $('palette').children) {
|
||||
const def = TD.TOWERS[b.dataset.type], price = priceOf(b.dataset.type), poor = gold < price;
|
||||
|
|
@ -537,7 +568,7 @@
|
|||
}
|
||||
if (ctrl.kind === 'remote') {
|
||||
const chip = $('netChip');
|
||||
chip.hidden = false;
|
||||
chip.hidden = V.active; // (a running versus match has nobody to invite: the room code is in the players panel)
|
||||
$('netRoom').textContent = ctrl.room || '';
|
||||
const alone = ctrl.players.length < 2;
|
||||
if (L.alone !== alone || L.room !== ctrl.room) {
|
||||
|
|
@ -744,6 +775,7 @@
|
|||
return app.ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y) || null;
|
||||
}
|
||||
function tapSelect(cell) {
|
||||
if (V.active && V.tapCell(cell)) return; // versus: a tapped gateway (attacker), an armed Scan / EMP
|
||||
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);
|
||||
|
|
@ -917,11 +949,12 @@
|
|||
if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6)
|
||||
if (e.key && e.key.toLowerCase() === 'm' && !e.altKey) { Audio.toggleMuted(); return; } // M mutes anywhere: in the menu, behind a dialog, on the end screen (code-13)
|
||||
if (!app.inGame) return;
|
||||
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
|
||||
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden && !V.holdsOverlay()) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
|
||||
const ctrl = app.ctrl, view = ctrl.view;
|
||||
const k = e.key.toLowerCase();
|
||||
// Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8)
|
||||
if ((k === ' ' || k === 'enter') && e.target && e.target.closest && e.target.closest('button, a, select, [role="button"]')) return;
|
||||
if (V.active && V.key(k, e)) return; // versus: attacker digits buy units, Space launches; waves, pause and speed do nothing
|
||||
const keyType = k.length === 1 ? TD.TOWER_ORDER.find((t) => TD.TOWERS[t].key === k) : null; // 1-9, 0: one key per tower in the palette
|
||||
if (keyType) { selectType(app.selType === keyType ? null : keyType); Audio.sfx('click'); e.preventDefault(); return; }
|
||||
switch (k) {
|
||||
|
|
@ -1058,9 +1091,10 @@
|
|||
}
|
||||
function closeOverlayToGame() {
|
||||
if (!app.inGame) return;
|
||||
if (!$('lobby').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
|
||||
if (!$('lobby').hidden || !$('vsSetup').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
|
||||
showOverlay(null);
|
||||
if (app.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); }
|
||||
if (V.active) V.refreshOverlay(); // a versus lobby / result dialog that was waiting behind the menu comes back
|
||||
}
|
||||
function leaveToMenu(keep) {
|
||||
cancelPending();
|
||||
|
|
@ -1073,6 +1107,7 @@
|
|||
}
|
||||
|
||||
$('btnSolo').addEventListener('click', () => { Audio.unlock(); startSolo(app.mapId); });
|
||||
$('btnVersus').addEventListener('click', () => { Audio.unlock(); V.openSetup(); });
|
||||
$('btnCloseMenu').addEventListener('click', closeOverlayToGame);
|
||||
$('btnHelp').addEventListener('click', () => showOverlay('help'));
|
||||
$('btnHelpClose').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else showOverlay('menu'); });
|
||||
|
|
@ -1089,7 +1124,8 @@
|
|||
else { app.ctrl.newGame(app.ctrl.board.mapId, app.ctrl.difficulty); }
|
||||
});
|
||||
$('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); });
|
||||
$('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } });
|
||||
function exitToMenu() { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } }
|
||||
$('btnEndMenu').addEventListener('click', exitToMenu);
|
||||
|
||||
// lobby
|
||||
function lobbyMsg(text, bad) { const m = $('lobbyMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
|
||||
|
|
@ -1114,24 +1150,25 @@
|
|||
// leaves the game that is running untouched (coop-4), Back / Play solo can cancel it (code-3), and only one attempt runs at a time (code-4).
|
||||
let pendingRc = null;
|
||||
const KEEP_SESSION = { connect: 1, lost: 1, replaced: 1 }; // after these the saved room is still worth another try; any other failure means it is gone
|
||||
function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume']) $(id).disabled = b; }
|
||||
function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume', 'btnVsCreate', 'btnVsJoin']) $(id).disabled = b; }
|
||||
function cancelPending() {
|
||||
const rc = pendingRc; pendingRc = null;
|
||||
if (rc) rc.close();
|
||||
setLobbyBusy(false);
|
||||
}
|
||||
// opts: { room, map, resume }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
|
||||
// opts: { room, map, resume, difficulty, mode:'versus'?, limit?, name?, say?(text, bad) }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
|
||||
function connectRemote(opts) {
|
||||
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; }
|
||||
const say = opts.say || lobbyMsg; // where the connecting / failure text goes (the co-op lobby, or the versus dialog)
|
||||
if (root.location.protocol === 'file:') { say('Open the game through the Netwall server to play online.', true); return; }
|
||||
if (pendingRc) return; // a double click must not open two rooms and an orphan socket
|
||||
const live = app.inGame && app.ctrl && app.ctrl.kind === 'remote' ? app.ctrl : null;
|
||||
if (live && opts.room && live.room === opts.room) { closeOverlayToGame(); return; } // that is the room we are in
|
||||
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
|
||||
const name = ((opts.name !== undefined ? opts.name : $('inName').value) || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
|
||||
store.set('nw.name', name);
|
||||
lobbyMsg('Connecting…');
|
||||
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, resume: !!opts.resume });
|
||||
say('Connecting…');
|
||||
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, mode: opts.mode, limit: opts.limit, resume: !!opts.resume });
|
||||
pendingRc = rc; setLobbyBusy(true);
|
||||
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); };
|
||||
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now(), mode: rc.mode }); };
|
||||
let first = true;
|
||||
rc.on('joined', () => {
|
||||
if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over
|
||||
|
|
@ -1145,11 +1182,15 @@
|
|||
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||
onPlayers(rc.players);
|
||||
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
|
||||
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here)
|
||||
Audio.music('battle'); requestWakeLock();
|
||||
firstRunHelp(); // an invited player is new to the game too (code-26)
|
||||
if (rc.mode === 'versus') { // a versus room opens on its lobby dialog (or straight into the round that is running)
|
||||
V.refreshOverlay(); Audio.music(V.phase === 'lobby' ? 'theme' : 'battle'); requestWakeLock();
|
||||
} else {
|
||||
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here)
|
||||
Audio.music('battle'); requestWakeLock();
|
||||
firstRunHelp(); // an invited player is new to the game too (code-26)
|
||||
}
|
||||
} else { toast('Reconnected', 'good'); adoptBoard(); }
|
||||
lobbyMsg('');
|
||||
say('');
|
||||
});
|
||||
rc.on('status', (s) => {
|
||||
if (app.ctrl !== rc || !app.inGame) return;
|
||||
|
|
@ -1161,12 +1202,14 @@
|
|||
const keep = !!KEEP_SESSION[f.code];
|
||||
if (app.ctrl === rc && app.inGame) { // the game we were playing is gone
|
||||
if (!keep) { sess.del('nw.room'); store.del('nw.session'); }
|
||||
toast(f.msg, 'bad'); leaveToMenu(keep); openLobby(); lobbyMsg(f.msg, true);
|
||||
const vsGame = rc.mode === 'versus';
|
||||
toast(f.msg, 'bad'); leaveToMenu(keep);
|
||||
if (vsGame) { V.openSetup(); V.msg(f.msg, true); } else { openLobby(); lobbyMsg(f.msg, true); }
|
||||
return;
|
||||
}
|
||||
if (opts.resume && !keep) { sess.del('nw.room'); store.del('nw.session'); } // the saved game cannot be rejoined: forget it
|
||||
lobbyMsg(f.msg, true);
|
||||
if ($('lobby').hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
|
||||
say(f.msg, true);
|
||||
if ((opts.say ? $('vsSetup') : $('lobby')).hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
|
||||
updateResumeButton();
|
||||
});
|
||||
rc.connect();
|
||||
|
|
@ -1176,7 +1219,7 @@
|
|||
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;
|
||||
if (fresh) b.textContent = 'Resume ' + (s.mode === 'versus' ? 'versus' : 'co-op') + ' game · room ' + s.room;
|
||||
}
|
||||
$('btnResume').addEventListener('click', () => {
|
||||
const s = store.get('nw.session', null); if (!s) return;
|
||||
|
|
@ -1221,7 +1264,7 @@
|
|||
const W = a.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0);
|
||||
const H = a.clientHeight - (parseFloat(cs.paddingTop) || 0) - (parseFloat(cs.paddingBottom) || 0) - $('topbar').offsetHeight;
|
||||
const mg = (NW.BOARD_MARGIN || 0) * 2, dw = b.cols * NW.CELL + mg, dh = b.rows * NW.CELL + mg, pad = 8;
|
||||
const minSide = clamp(Math.round(H * 0.25), 140, 210); // room for the palette row and a window onto the info panel
|
||||
const minSide = V.minSide(H) || clamp(Math.round(H * 0.25), 140, 210); // room for the palette row and a window onto the info panel (versus: the dock too)
|
||||
const maxStage = Math.max(120, H - minSide);
|
||||
const sU = Math.min((W - pad) / dw, (maxStage - pad) / dh), sR = Math.min((W - pad) / dh, (maxStage - pad) / dw);
|
||||
const rot = sR > sU * 1.08;
|
||||
|
|
@ -1272,6 +1315,7 @@
|
|||
}
|
||||
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower || app.selType) renderInfo(false); }
|
||||
updateHud(view);
|
||||
V.tick(now, view); // versus: clock, credits, cooldown rings, shop affordability
|
||||
layoutBars(false);
|
||||
updateFit(); // the Reset-zoom button always follows the camera, however it was reset (code-18, coop-8)
|
||||
if (now - app.lastBossCheck > 600 && view.state === 'playing') {
|
||||
|
|
@ -1280,7 +1324,7 @@
|
|||
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;
|
||||
ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower; ui.vs = V.uiState();
|
||||
// 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);
|
||||
|
|
@ -1317,5 +1361,7 @@
|
|||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
|
||||
|
||||
app.startVersus = startVersusLocal; // (tests: a local versus game with its own limit and countdown)
|
||||
app.vs = V;
|
||||
NW.app = app; // handy for debugging and automated tests
|
||||
})(typeof self !== 'undefined' ? self : this);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue