Co-op robustness, audio/a11y, new towers and enemies, Uplink rebalance
Co-op (QA'd with two to three real browsers, TCP-proxy chaos scenarios): - partner's tower changes are never dropped after a render stall or snapshot burst - half-open connections show "reconnecting" in ~6 s instead of 45-65 s - upgrade and next-wave are idempotent (stale commands refused), restart message, promoted host gets Play again, failed joins never kill a live game, listener leaks Audio / keyboard / a11y: - one Audio element per track, fade/stinger supersede tokens, play() retry on the next gesture, 5 s fallback to the synth, mute works everywhere, dialogs with role/aria-modal/focus handling, accessible names for sound/speed/pause New content: - enemies: Daemon (healer), Proxy (regenerating shield), Botnet (flyer swarm); waves weave them in from wave 9 (waves 1-8 unchanged) - towers: Sandbox (stun pulse), Load Balancer (fire-rate aura); hotkeys 1-9 - glyphs/shapes, stun/heal effects, gallery e2e that pixel-checks every kind Orbital Uplink rebalanced after playtesting (was affordable by wave ~6 and buyable in bulk from boss rewards): 1500 credits, upgrades 1200/2000/3200, and every Uplink already owned makes the next one 25% dearer to buy AND to upgrade (each tower remembers its multiplier, carried in the tower list as a 9th field). Shared TD.priceFor/upgradePrice so the UI shows exactly what the sim charges. Also: tablet/foldable viewports in the layout matrix (tolerant colour check), docs (README tower/enemy tables, PROTOCOL shield/stun/pm encodings, NEXT roadmap). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
parent
962189419a
commit
28502984ec
29 changed files with 3370 additions and 230 deletions
|
|
@ -12,6 +12,8 @@ name them in `tracks.json`:
|
|||
* Formats: mp3, ogg, m4a or wav. Anything left `null` keeps the synth version.
|
||||
* Loops are played with the browser's `loop` flag, so crop the track to a whole number of bars for a clean seam.
|
||||
* Keep files small (a few MB) so phones start playing quickly.
|
||||
* A track that is not playing 5 s after it was asked for (slow connection, missing or broken file) is replaced by the synth melody for that moment and tried again the next time it is wanted. `win` and `lose` are fetched in the background once the first `battle` track plays, `boss` a wave or two before the first boss wave (Data Saver and 2G/3G skip that).
|
||||
* Browsers that refuse to start audio without a tap (iOS / iPadOS Safari, Chrome on Android) get the music at the first tap. The `volume` of an audio element is read-only on iOS, so the fades there are instant and the music plays at full file volume: master the files accordingly.
|
||||
|
||||
## Suno prompts
|
||||
|
||||
|
|
|
|||
|
|
@ -265,7 +265,10 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(
|
|||
.wv .e i.sh-ping, .wv .e i.sh-worm { border-radius: 50%; }
|
||||
.wv .e i.sh-trojan { clip-path: polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0 50%); }
|
||||
.wv .e i.sh-spam { clip-path: polygon(0 20%, 60% 20%, 60% 0, 100% 50%, 60% 100%, 60% 80%, 0 80%); }
|
||||
.wv .e i.sh-spoof { clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); }
|
||||
.wv .e i.sh-spoof, .wv .e i.sh-ghost { clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); } /* (the kind key is "ghost": this used to be a plain square) */
|
||||
.wv .e i.sh-daemon { clip-path: polygon(34% 0, 66% 0, 66% 34%, 100% 34%, 100% 66%, 66% 66%, 66% 100%, 34% 100%, 34% 66%, 0 66%, 0 34%, 34% 34%); } /* healer: a plus */
|
||||
.wv .e i.sh-proxy { clip-path: polygon(0 4%, 100% 4%, 100% 58%, 50% 100%, 0 58%); } /* shielded: a shield */
|
||||
.wv .e i.sh-botnet { clip-path: polygon(18% 0, 50% 32%, 82% 0, 100% 18%, 68% 50%, 100% 82%, 82% 100%, 50% 68%, 18% 100%, 0 82%, 32% 50%, 0 18%); } /* swarm drone: an X */
|
||||
.wv .e i.sh-rootkit { clip-path: polygon(30% 0, 70% 0, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0 70%, 0 30%); width: 14px; height: 14px; }
|
||||
.wv .tag { padding: 1px 6px; border-radius: 6px; font-size: 11px; border: 1px solid; }
|
||||
.wv .tag.air { color: #e29bff; border-color: #5b3a73; }
|
||||
|
|
|
|||
|
|
@ -51,9 +51,9 @@
|
|||
<div class="spacer"></div>
|
||||
<button id="btnWave" class="primary" aria-label="Start next wave"><svg class="ic"><use href="#i-play"/></svg><span id="btnWaveText">Wave 1</span></button>
|
||||
<button id="btnAuto" class="icon toggle" aria-pressed="false" aria-label="Automatic waves" title="Automatic waves (A)"><span>AUTO</span></button>
|
||||
<button id="btnSpeed" class="icon" aria-label="Game speed" title="Speed (F)"><span id="speedText">1×</span></button>
|
||||
<button id="btnSpeed" class="icon" aria-label="Game speed 1×" title="Speed (F)"><span id="speedText">1×</span></button>
|
||||
<button id="btnPause" class="icon" aria-label="Pause" aria-pressed="false" title="Pause (P)"><svg class="ic"><use href="#i-pause"/></svg></button>
|
||||
<button id="btnSound" class="icon" aria-label="Sound" title="Sound (M)"><svg class="ic"><use href="#i-sound"/></svg></button>
|
||||
<button id="btnSound" class="icon" aria-label="Mute sound" title="Sound (M)"><svg class="ic"><use href="#i-sound"/></svg></button>
|
||||
</header>
|
||||
|
||||
<main id="stage">
|
||||
|
|
@ -85,10 +85,10 @@
|
|||
</aside>
|
||||
|
||||
<!-- ===== main menu: .card-body scrolls, .card-foot (the primary buttons) is always visible ===== -->
|
||||
<div id="menu" class="overlay">
|
||||
<div id="menu" class="overlay" role="dialog" aria-modal="true" aria-labelledby="menuTitle">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="logo"><span class="logo-mark" aria-hidden="true"></span><h1>NETWALL</h1></div>
|
||||
<div class="logo"><span class="logo-mark" aria-hidden="true"></span><h1 id="menuTitle">NETWALL</h1></div>
|
||||
<p class="tag">Build the firewall. Stretch the route. Protect the server.</p>
|
||||
<div id="mapPick" class="maps" role="radiogroup" aria-label="Map"></div>
|
||||
<p id="mapDesc" class="mapdesc"></p>
|
||||
|
|
@ -103,6 +103,7 @@
|
|||
<div class="row small">
|
||||
<button id="btnHelp" class="link">How to play</button>
|
||||
<button id="btnFullscreen" class="link" hidden>Fullscreen</button>
|
||||
<button id="btnMenuSound" class="link">Sound: on</button>
|
||||
<button id="btnCloseMenu" class="link" hidden>Back to game</button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -110,10 +111,10 @@
|
|||
</div>
|
||||
|
||||
<!-- ===== co-op lobby ===== -->
|
||||
<div id="lobby" class="overlay" hidden>
|
||||
<div id="lobby" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="lobbyTitle">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h2>Co-op online</h2>
|
||||
<h2 id="lobbyTitle">Co-op online</h2>
|
||||
<p class="muted lead">Two players, one base, one pool of credits. Create a room and send the link, or enter a friend's code.</p>
|
||||
<label class="field"><span>Your name</span><input id="inName" maxlength="16" autocomplete="nickname" autocapitalize="words" spellcheck="false" placeholder="Player"></label>
|
||||
<div class="split">
|
||||
|
|
@ -140,16 +141,16 @@
|
|||
</div>
|
||||
|
||||
<!-- ===== help ===== -->
|
||||
<div id="help" class="overlay" hidden>
|
||||
<div id="help" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="helpTitle">
|
||||
<div class="card wide">
|
||||
<div class="card-body">
|
||||
<h2>How to play</h2>
|
||||
<h2 id="helpTitle">How to play</h2>
|
||||
<ul class="howto">
|
||||
<li><b>Goal.</b> Packets pour in from the gateways (red). Don't let them reach the <b>server</b>. Each leak costs integrity (♥).</li>
|
||||
<li><b>Maze.</b> The map is open: <b>Firewalls</b> are cheap walls. Packets always take the shortest open route, so walls make them walk further, past your turrets. You can lengthen the route but never seal it off completely. <span class="kbd-only">Hover</span><span class="touch-only">Tap</span> to preview the new route.</li>
|
||||
<li><b>Turrets.</b> Filter (fast), IDS Sniper (long range, armour-piercing), Mortar (splash), Rate Limiter (slows), Router Arc (chain lightning), and the very expensive late-game <b>Orbital Uplink</b> (a piercing beam that ignores armour, hits flyers and slows what it touches). <b>Spoofed packets fly</b> over your maze, so keep some anti-air. Mortars can't hit flyers.</li>
|
||||
<li><b>Credits.</b> Earned from kills and every cleared wave. Upgrade turrets up to level 3. Sell for 70% back (walls refund in full).</li>
|
||||
<li><b>Controls.</b> <span class="kbd-only">Click to build, drag to paint walls, right-click to cancel. Keys <span id="helpKeys">1–6</span> pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, wheel zooms.</span>
|
||||
<li><b>Controls.</b> <span class="kbd-only">Click to build, drag to paint walls, right-click to cancel. Keys <span id="helpKeys">1–6</span> pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, M mutes, wheel zooms.</span>
|
||||
<span class="touch-only">Tap a tower type, then tap the map to preview; nudge the cell with the arrows and tap ✓ to build. Walls paint as you drag. Pinch to zoom, two fingers to pan, long-press to ping your partner.</span></li>
|
||||
<li><b>Co-op.</b> Both players share everything and can build, sell and upgrade at the same time. You see each other's cursors; long-press / Alt-click pings the map.</li>
|
||||
</ul>
|
||||
|
|
@ -159,7 +160,7 @@
|
|||
</div>
|
||||
|
||||
<!-- ===== game over / victory ===== -->
|
||||
<div id="end" class="overlay" hidden>
|
||||
<div id="end" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="endTitle" aria-describedby="endText">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h2 id="endTitle">Breach!</h2>
|
||||
|
|
@ -173,6 +174,7 @@
|
|||
<button id="btnEndMenu" class="big">Menu</button>
|
||||
</div>
|
||||
<p id="endWait" class="msg" hidden>Waiting for the host to start a new game…</p>
|
||||
<div class="row small"><button id="btnEndSound" class="link">Sound: on</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -17,9 +17,7 @@
|
|||
let unlocked = false;
|
||||
let wanted = null; // music track the game currently wants ('theme' | 'battle' | 'boss' | null)
|
||||
let current = null; // { name, kind:'file'|'synth', el?, stop() }
|
||||
const fileState = {}; // name -> 'unknown' | 'ok' | 'missing'
|
||||
const lastPlay = {};
|
||||
const files = {}; // name -> HTMLAudioElement
|
||||
|
||||
try {
|
||||
const s = JSON.parse(localStorage.getItem(STORE) || '{}');
|
||||
|
|
@ -200,46 +198,115 @@
|
|||
// ---------------------------------------------------------------- file music
|
||||
// assets/music/tracks.json maps track names to file names, e.g. {"battle": "my-song.mp3"}; null = use the synth.
|
||||
// Reading one small manifest (instead of probing for files) keeps the console free of 404s.
|
||||
let manifestP = null;
|
||||
function manifest() {
|
||||
if (!manifestP) {
|
||||
manifestP = (typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))
|
||||
? fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' }).then((r) => (r.ok ? r.json() : {})).catch(() => ({}))
|
||||
: Promise.resolve({});
|
||||
}
|
||||
//
|
||||
// Rules that keep the sound right when the game asks for music faster than a file loads or a fade finishes:
|
||||
// * every track has ONE element for the whole session, created the first time it is asked for (not when it can play), so
|
||||
// rapid music() calls share one download (code-16);
|
||||
// * a fade belongs to its element and any newer fade or restart cancels it, so a stale fade-out can never pause a track that
|
||||
// was started again (code-7); the stinger has its own supersede token (code-12);
|
||||
// * a file that is not playable within timing.load ms (stalled, or broken) is replaced by the synth at once, and the file is
|
||||
// tried again the next time that track is wanted (code-15);
|
||||
// * a play() the browser refuses (iOS / Safari autoplay rules) is retried inside the next tap, click or key press (code-14).
|
||||
const timing = { load: 5000, sting: 2500, retry: 15000 }; // ms: wait for a music file / for a stinger / before retrying a file that errored
|
||||
let manifestData = null, manifestP = null, manifestTried = -1e9;
|
||||
function manifest() { // resolves to the manifest, or null when it could not be read (never latched: it is asked again later)
|
||||
if (manifestData) return Promise.resolve(manifestData);
|
||||
if (manifestP) return manifestP;
|
||||
if (!(typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))) { manifestData = {}; return Promise.resolve(manifestData); }
|
||||
if (Date.now() - manifestTried < timing.retry) return Promise.resolve(null);
|
||||
manifestTried = Date.now();
|
||||
manifestP = fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' })
|
||||
.then((r) => (r.ok ? r.json() : r.status === 404 ? {} : null)) // no manifest at all = no files: synth for good; a server error is asked again later
|
||||
.catch(() => null)
|
||||
.then((m) => { manifestP = null; if (m && typeof m === 'object') manifestData = m; return manifestData; });
|
||||
return manifestP;
|
||||
}
|
||||
function fileFor(name, cb) {
|
||||
if (fileState[name] === 'missing') { cb(null); return; }
|
||||
if (files[name]) { cb(files[name]); return; }
|
||||
manifest().then((m) => {
|
||||
const f = m && typeof m[name] === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(m[name]) ? m[name] : null;
|
||||
if (!f) { fileState[name] = 'missing'; cb(null); return; }
|
||||
const el = new Audio();
|
||||
el.preload = 'auto';
|
||||
el.loop = name !== 'win' && name !== 'lose';
|
||||
el.addEventListener('canplay', () => { fileState[name] = 'ok'; files[name] = el; cb(el); }, { once: true });
|
||||
el.addEventListener('error', () => { fileState[name] = 'missing'; cb(null); }, { once: true });
|
||||
el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
|
||||
el.load();
|
||||
});
|
||||
manifest(); // (read it up front: the first tap can then create the element and call play() inside the gesture, which iOS insists on)
|
||||
function fileName(name) {
|
||||
const f = manifestData && manifestData[name];
|
||||
return typeof f === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(f) ? f : null;
|
||||
}
|
||||
const tracks = {}; // name -> { el, state: 'loading' | 'ready' | 'failed', failedAt }
|
||||
// The element of a track; null when the manifest names no file for it. A failed one is tried again after timing.retry.
|
||||
function track(name) {
|
||||
let t = tracks[name];
|
||||
if (t && t.state === 'failed' && Date.now() - t.failedAt > timing.retry) { try { t.el.removeAttribute('src'); t.el.load(); } catch (e) { /* ignore */ } t = tracks[name] = null; }
|
||||
if (t) return t;
|
||||
const f = fileName(name);
|
||||
if (!f) return null;
|
||||
const el = new Audio();
|
||||
t = tracks[name] = { name, el, state: 'loading', failedAt: 0 };
|
||||
el.preload = 'auto';
|
||||
el.loop = name !== 'win' && name !== 'lose';
|
||||
el.addEventListener('canplay', () => { if (t.state === 'loading') t.state = 'ready'; });
|
||||
el.addEventListener('error', () => { if (tracks[name] === t) { t.state = 'failed'; t.failedAt = Date.now(); } });
|
||||
el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
|
||||
return t;
|
||||
}
|
||||
// Starts a track the player is not listening to yet (the boss theme before the boss, the stingers before the end). Cheap files only
|
||||
// unless the connection allows it: Data Saver and 2G/3G skip it.
|
||||
function preload(name) {
|
||||
const c = root.navigator && root.navigator.connection;
|
||||
if (c && (c.saveData || /(^|-)[23]g$/.test(c.effectiveType || ''))) return;
|
||||
manifest().then(() => { if (manifestData) track(name); });
|
||||
}
|
||||
|
||||
const fades = new WeakMap(); // element -> the fade running on it (a token object)
|
||||
function cancelFade(el) { fades.delete(el); }
|
||||
function fadeEl(el, to, ms, done) {
|
||||
const mine = {}; fades.set(el, mine);
|
||||
const from = el.volume, t0 = performance.now();
|
||||
const step = () => {
|
||||
const k = Math.min(1, (performance.now() - t0) / ms);
|
||||
if (fades.get(el) !== mine) return; // superseded: a newer fade or a restart owns the element now
|
||||
const k = ms > 0 ? Math.min(1, (performance.now() - t0) / ms) : 1;
|
||||
try { el.volume = Math.max(0, Math.min(1, from + (to - from) * k)); } catch (e) { /* ignore */ }
|
||||
if (k < 1) requestAnimationFrame(step); else if (done) done();
|
||||
if (k < 1) setTimeout(step, 33); else { fades.delete(el); if (done) done(); } // (a timer, not rAF: a hidden tab must still finish its fade-out)
|
||||
};
|
||||
step();
|
||||
}
|
||||
const pauseEl = (el) => { try { el.pause(); } catch (e) { /* ignore */ } };
|
||||
|
||||
let blocked = false; // the browser refused play(): the next gesture retries (code-14)
|
||||
let stingersLoaded = false; // the end-screen stingers are fetched once, after the first battle track plays
|
||||
function stopCurrent(fade) {
|
||||
const c = current; current = null;
|
||||
if (!c || c.kind === 'pending') return;
|
||||
if (!c) return;
|
||||
clearTimeout(c.timer);
|
||||
if (c.kind === 'synth') c.stop(fade);
|
||||
else fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { try { c.el.pause(); } catch (e) { /* ignore */ } });
|
||||
else if (c.el) fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { if (!(current && current.el === c.el)) pauseEl(c.el); });
|
||||
}
|
||||
// The generative melody stands in for a track whose file is missing, broken or too slow.
|
||||
function useSynth(tok) {
|
||||
clearTimeout(tok.timer);
|
||||
if (current !== tok) return;
|
||||
if (tok.el) { cancelFade(tok.el); pauseEl(tok.el); } // the file may still arrive: it must not start on top of the synth
|
||||
const c = ensureCtx();
|
||||
current = c ? startSynth(tok.name) : null;
|
||||
if (current) current.name = tok.name;
|
||||
}
|
||||
function playFile(t, tok, keepPos) {
|
||||
const el = t.el;
|
||||
tok.el = el;
|
||||
cancelFade(el);
|
||||
if (el.paused && !keepPos) { try { el.currentTime = 0; } catch (e) { /* not seekable yet */ } el.volume = 0; } // (a track still playing, e.g. a mute undone during its fade-out, carries on)
|
||||
let pr;
|
||||
try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
|
||||
const ok = () => {
|
||||
if (current !== tok) return;
|
||||
clearTimeout(tok.timer);
|
||||
tok.kind = 'file';
|
||||
fadeEl(el, 0.8 * musicVol, 1200);
|
||||
if (tok.name === 'battle' && !stingersLoaded) { stingersLoaded = true; setTimeout(() => { preload('lose'); preload('win'); }, 1500); }
|
||||
};
|
||||
const bad = (err) => {
|
||||
if (current !== tok) return;
|
||||
const why = err && err.name;
|
||||
if (why === 'AbortError') return; // paused or reloaded under it (tab hidden): the visible handler starts it again
|
||||
if (why === 'NotAllowedError') { clearTimeout(tok.timer); pauseEl(el); current = null; blocked = true; return; }
|
||||
t.state = 'failed'; t.failedAt = Date.now();
|
||||
useSynth(tok);
|
||||
};
|
||||
if (pr && pr.then) pr.then(ok, bad); else ok();
|
||||
}
|
||||
|
||||
function applyMusic() {
|
||||
|
|
@ -249,57 +316,61 @@
|
|||
if (current && current.name === wanted) return;
|
||||
const name = wanted;
|
||||
stopCurrent(0.9);
|
||||
// placeholder so that rapid calls do not stack
|
||||
const token = current = { name, kind: 'pending', stop() {} };
|
||||
fileFor(name, (el) => {
|
||||
if (current !== token) return; // superseded while loading
|
||||
if (el) {
|
||||
el.currentTime = 0; el.volume = 0;
|
||||
const pr = el.play();
|
||||
if (pr && pr.catch) pr.catch(() => { /* blocked: will retry on next gesture */ current = null; });
|
||||
current = { name, kind: 'file', el, stop() {} };
|
||||
fadeEl(el, 0.8 * musicVol, 1200);
|
||||
} else {
|
||||
const c = ensureCtx();
|
||||
current = c ? startSynth(name) : null;
|
||||
if (current) current.name = name;
|
||||
}
|
||||
});
|
||||
const tok = current = { name, kind: 'pending', stop() {}, el: null, timer: 0 }; // placeholder: rapid calls do not stack, a late answer is ignored
|
||||
tok.timer = setTimeout(() => { if (current === tok) useSynth(tok); }, timing.load);
|
||||
const go = () => {
|
||||
const t = track(name);
|
||||
if (!t || t.state === 'failed') useSynth(tok); else playFile(t, tok);
|
||||
};
|
||||
if (manifestData) { go(); return; } // (synchronously, so that play() is still inside the tap)
|
||||
manifest().then(() => { if (current === tok) go(); });
|
||||
}
|
||||
|
||||
let stingEl = null;
|
||||
let stingEl = null, stingTok = 0;
|
||||
function stopStinger(fade) {
|
||||
stingTok++;
|
||||
const el = stingEl; stingEl = null;
|
||||
if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { try { el.pause(); } catch (e) { /* ignore */ } });
|
||||
if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { if (stingEl !== el) pauseEl(el); });
|
||||
}
|
||||
function jingle(name) { // the synth stinger, also what plays when the file is missing, late or refused
|
||||
if (muted || !ctx) return;
|
||||
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
|
||||
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
|
||||
}
|
||||
function stinger(name) {
|
||||
if (muted || !unlocked) return;
|
||||
fileFor(name, (el) => {
|
||||
if (el) { try { stopStinger(0.2); stingEl = el; el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; }
|
||||
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
|
||||
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
|
||||
});
|
||||
stopStinger(0.2);
|
||||
const tok = stingTok, t = manifestData ? track(name) : null;
|
||||
if (!t || t.state === 'failed') { jingle(name); return; }
|
||||
const el = t.el;
|
||||
stingEl = el; cancelFade(el);
|
||||
try { el.currentTime = 0; } catch (e) { /* not seekable yet */ }
|
||||
el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol));
|
||||
const fail = () => { if (tok !== stingTok) return; stingEl = null; cancelFade(el); pauseEl(el); jingle(name); };
|
||||
const timer = setTimeout(fail, timing.sting); // not playing yet after this long: the synth jingle stands in, the file is dropped
|
||||
let pr;
|
||||
try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
|
||||
if (pr && pr.then) pr.then(() => clearTimeout(timer), (err) => { clearTimeout(timer); if (!(err && err.name === 'AbortError')) fail(); });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- public
|
||||
function unlock() {
|
||||
if (unlocked) return;
|
||||
const c = ensureCtx();
|
||||
if (c && c.state === 'suspended') c.resume();
|
||||
unlocked = true;
|
||||
applyMusic();
|
||||
if (c && c.state !== 'running' && c.state !== 'closed') { try { const p = c.resume(); if (p && p.catch) p.catch(() => {}); } catch (e) { /* ignore */ } }
|
||||
if (!unlocked) { unlocked = true; applyMusic(); return; }
|
||||
if (blocked) { blocked = false; applyMusic(); } // a refused play() is retried at every gesture until it is allowed (code-14)
|
||||
}
|
||||
|
||||
root.addEventListener('pointerdown', unlock, { passive: true });
|
||||
root.addEventListener('keydown', unlock, { passive: true });
|
||||
// Every kind of gesture, in the capture phase: pointerdown alone is no gesture for a finger (touch needs pointerup / touchend / click).
|
||||
for (const ev of ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown']) root.addEventListener(ev, unlock, { passive: true, capture: true });
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) {
|
||||
ctx.suspend && ctx.suspend();
|
||||
if (current && current.kind === 'file') current.el.pause();
|
||||
if (ctx && ctx.suspend) ctx.suspend();
|
||||
if (current && current.el) pauseEl(current.el);
|
||||
if (stingEl) pauseEl(stingEl);
|
||||
} else {
|
||||
ctx.resume && ctx.resume();
|
||||
if (current && current.kind === 'file' && !muted) current.el.play().catch(() => {});
|
||||
if (ctx && ctx.resume) ctx.resume();
|
||||
if (current && current.el && !muted) { const t = tracks[current.name]; if (t && t.el === current.el) playFile(t, current, true); }
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -307,12 +378,15 @@
|
|||
sfx,
|
||||
unlock,
|
||||
stinger,
|
||||
preload,
|
||||
timing, // tunable for tests
|
||||
get muted() { return muted; },
|
||||
get now() { return current ? { name: current.name, kind: current.kind } : null; }, // for tests / debugging
|
||||
get blocked() { return blocked; },
|
||||
setMuted(m) {
|
||||
muted = !!m; save();
|
||||
if (master) master.gain.value = muted ? 0 : 0.9;
|
||||
if (muted) stopCurrent(0.2); else applyMusic();
|
||||
if (muted) { stopCurrent(0.2); stopStinger(0.2); } else applyMusic();
|
||||
},
|
||||
toggleMuted() { this.setMuted(!muted); return muted; },
|
||||
// Which music the game wants right now: 'theme' | 'battle' | 'boss' | null
|
||||
|
|
@ -321,7 +395,7 @@
|
|||
setMusicVolume(v) {
|
||||
musicVol = Math.min(1, Math.max(0, v)); save();
|
||||
if (musBus) musBus.gain.value = 0.3 * musicVol;
|
||||
if (current && current.kind === 'file') current.el.volume = 0.8 * musicVol;
|
||||
if (current && current.kind === 'file') { cancelFade(current.el); current.el.volume = 0.8 * musicVol; }
|
||||
},
|
||||
};
|
||||
})(typeof self !== 'undefined' ? self : this);
|
||||
|
|
|
|||
|
|
@ -8,7 +8,9 @@
|
|||
* gold lives maxLives wave state auto nextWaveIn kills winWave rev queued speed paused
|
||||
* towers[{id,type,x,y,level,mode,spent,owner,tgt,kills}]
|
||||
* monsters[{id,kind,x,y,hp,maxhp,slow,air}] bullets[{id,k,x,y}] cursors[{slot,x,y}]
|
||||
* ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue
|
||||
* ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue. An upgrade carries the level the player saw (lv)
|
||||
* and a wave carries the wave it expects to start (n), filled in here from the view: a second player who
|
||||
* pressed the same button at the same moment is refused as 'stale' (see sim.js) instead of paying twice.
|
||||
* ctrl.ctl(c, v) 'pause' | 'speed'
|
||||
* ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route?
|
||||
* events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt'
|
||||
|
|
@ -18,6 +20,9 @@
|
|||
const NW = root.NW = root.NW || {};
|
||||
const TD = root.TD;
|
||||
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
||||
const WATCHDOG_MS = 5000; // a joined socket that has been silent this long is dead (snapshots arrive at 20 Hz)
|
||||
const CONNECT_MS = 10000; // a socket that is not joined this long after it was opened is abandoned
|
||||
const BUF_MAX = 10; // snapshots kept for interpolation
|
||||
|
||||
class Emitter {
|
||||
constructor() { this._h = {}; }
|
||||
|
|
@ -29,6 +34,13 @@
|
|||
}
|
||||
}
|
||||
|
||||
// What the player SAW when pressing the button (the view they were looking at), so the sim can tell a stale command from a fresh one.
|
||||
function stampCmd(c, view) {
|
||||
if (c.c === 'upgrade' && c.lv === undefined) { const t = view.towers.find((x) => x.id === c.id); if (t) c.lv = t.level; }
|
||||
else if (c.c === 'wave' && c.n === undefined) c.n = view.wave + 1;
|
||||
return c;
|
||||
}
|
||||
|
||||
// ws(s)://<same host>/ws, relative to the page so it also works under a proxy path prefix
|
||||
function wsUrl() {
|
||||
const u = new URL('ws', root.location.href);
|
||||
|
|
@ -80,7 +92,7 @@
|
|||
if (ev.length) this.emit('events', ev);
|
||||
}
|
||||
send(cmd) {
|
||||
const res = this.sim.cmd(Object.assign({}, cmd, { by: 0 }));
|
||||
const res = this.sim.cmd(stampCmd(Object.assign({}, cmd, { by: 0 }), this.view));
|
||||
if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id });
|
||||
return res;
|
||||
}
|
||||
|
|
@ -110,6 +122,9 @@
|
|||
this.ws = null; this.players = []; this.you = null; this.board = null;
|
||||
this.buf = []; this.delay = 120;
|
||||
this.rev = -1; this.recvRev = -1; this.towers = [];
|
||||
this._carryTw = null; // the newest tower list that was pushed out of the buffer before it was displayed (coop-1)
|
||||
this.resume = !!opts.resume; // rejoining a game we left (reload / Resume button): "no such room" then means it is gone
|
||||
this.everJoined = false;
|
||||
this.monCache = new Map(); this.bulCache = new Map(); this._gen = 0;
|
||||
this.rtt = 0;
|
||||
this.retry = 0; this.intentional = false; this.fatal = false;
|
||||
|
|
@ -124,6 +139,11 @@
|
|||
root.addEventListener('online', this._onVis);
|
||||
this._timers = [];
|
||||
}
|
||||
// The document / window listeners must not outlive the controller (code-19): called when it dies and when it is closed.
|
||||
_dispose() {
|
||||
document.removeEventListener('visibilitychange', this._onVis);
|
||||
root.removeEventListener('online', this._onVis);
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (this.intentional || this.fatal) return;
|
||||
|
|
@ -140,6 +160,23 @@
|
|||
ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); };
|
||||
ws.onclose = (e) => { if (this.ws === ws) this._onClose(e); };
|
||||
ws.onerror = () => { /* onclose follows */ };
|
||||
// A connect over a dead path can hang for minutes: give up on this socket and try again (or report it) after CONNECT_MS.
|
||||
clearTimeout(this._connT);
|
||||
this._connT = setTimeout(() => { if (this.ws === ws && this.status !== 'joined') this._abandon(); }, CONNECT_MS);
|
||||
}
|
||||
|
||||
// The socket is presumed dead: no frame for WATCHDOG_MS, or the page woke up after a stall. A half-open connection (Wi-Fi / cell
|
||||
// switch, NAT or proxy drop) never delivers a close for 47 to 65 s, so we do not wait for one (coop-2): forget the socket, show
|
||||
// "reconnecting" now and open a fresh one. The server swaps the old connection out by pid. Handlers are detached first, so the
|
||||
// dead socket's eventual close (or the server's 4001 "replaced") cannot be mistaken for the new connection's.
|
||||
_abandon() {
|
||||
const ws = this.ws;
|
||||
this.ws = null;
|
||||
clearTimeout(this._connT);
|
||||
this._stopRtt();
|
||||
if (ws) { ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null; try { ws.close(); } catch (e) { /* ignore */ } }
|
||||
if (this.status === 'joined') { this._setStatus('reconnecting'); this.connect(); } // it was alive a moment ago: straight back in
|
||||
else this._failed(); // never got in: count it, back off, give up eventually
|
||||
}
|
||||
|
||||
_setStatus(s) { if (this.status !== s) { this.status = s; this.emit('status', s); } }
|
||||
|
|
@ -155,11 +192,12 @@
|
|||
}
|
||||
_die(code, msg) {
|
||||
this.fatal = true; this._setStatus('closed');
|
||||
this._stopTimers();
|
||||
this._stopTimers(); this._dispose();
|
||||
this.emit('fatal', { code, msg });
|
||||
}
|
||||
_onClose(e) {
|
||||
this.ws = null;
|
||||
clearTimeout(this._connT);
|
||||
this._stopRtt();
|
||||
if (this.intentional || this.fatal) { this._setStatus('closed'); return; }
|
||||
if (e && e.code === 4001) { this._die('replaced', 'This game was opened in another tab or device.'); return; }
|
||||
|
|
@ -170,27 +208,30 @@
|
|||
if (this.intentional || this.fatal || this.status === 'connecting') return;
|
||||
const stale = performance.now() - this.lastMsg > 2500;
|
||||
if (!this.ws || this.ws.readyState > 1) { this.retry = 0; this.connect(); }
|
||||
else if (this.status === 'joined' && stale) { try { this.ws.close(); } catch (e) { /* ignore */ } }
|
||||
else if (this.status === 'joined' && stale) this._abandon();
|
||||
}
|
||||
_stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; this._stopRtt(); }
|
||||
_stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; clearTimeout(this._connT); this._stopRtt(); }
|
||||
_stopRtt() { if (this._rttT) { clearInterval(this._rttT); this._rttT = 0; } if (this._wdT) { clearInterval(this._wdT); this._wdT = 0; } }
|
||||
_startRtt() {
|
||||
this._stopRtt();
|
||||
this._rttT = setInterval(() => this._send({ t: 'rtt', ts: performance.now() }), 2000);
|
||||
this._wdT = setInterval(() => { // snapshots flow at 20 Hz even when paused: silence means a dead socket
|
||||
if (this.status === 'joined' && this.ws && performance.now() - this.lastMsg > 5000) { try { this.ws.close(); } catch (e) { /* ignore */ } }
|
||||
if (this.status === 'joined' && this.ws && performance.now() - this.lastMsg > WATCHDOG_MS) this._abandon();
|
||||
}, 1000);
|
||||
}
|
||||
_send(o) { if (this.ws && this.ws.readyState === 1) this.ws.send(JSON.stringify(o)); }
|
||||
|
||||
_onMsg(raw) {
|
||||
if (this.intentional || this.fatal) return; // closed on purpose: nothing may reach the UI any more (code-3)
|
||||
let m;
|
||||
try { m = JSON.parse(raw); } catch (e) { return; }
|
||||
if (!m || typeof m.t !== 'string') return;
|
||||
switch (m.t) {
|
||||
case 'snap': this._onSnap(m); break;
|
||||
case 'joined':
|
||||
clearTimeout(this._connT);
|
||||
this.room = m.room; this.you = m.you; this.players = m.players || [];
|
||||
this.everJoined = true;
|
||||
this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused;
|
||||
this._applyState(m.state, m.snap);
|
||||
this._setStatus('joined');
|
||||
|
|
@ -214,6 +255,11 @@
|
|||
{ const s = performance.now() - m.ts; this.rtt = this.rtt ? Math.round(this.rtt * 0.7 + s * 0.3) : Math.round(s); this.emit('rtt', this.rtt); }
|
||||
break;
|
||||
case 'error': {
|
||||
// "no such room" while rejoining means the server lost it: it restarted (coop-6). The code says so, the text spells it out.
|
||||
if (m.code === 'no_room' && (this.everJoined || this.resume)) {
|
||||
this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.');
|
||||
break;
|
||||
}
|
||||
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.' };
|
||||
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
|
||||
break;
|
||||
|
|
@ -227,7 +273,7 @@
|
|||
b.solid.set(b.obst);
|
||||
this.towers = list.map((a) => {
|
||||
b.setSolid(a[2], a[3], 1);
|
||||
return { id: a[0], type: a[1], x: a[2], y: a[3], level: a[4], mode: a[5], spent: a[6], owner: a[7], tgt: 0, kills: 0 };
|
||||
return { id: a[0], type: a[1], x: a[2], y: a[3], level: a[4], mode: a[5], spent: a[6], owner: a[7], pm: a[8] || 1, tgt: 0, kills: 0 };
|
||||
});
|
||||
b.recompute();
|
||||
}
|
||||
|
|
@ -236,7 +282,7 @@
|
|||
this._setTowers(state.towers);
|
||||
this.rev = this.recvRev = state.rev;
|
||||
this.maxLives = state.maxLives; this.winWave = state.winWave;
|
||||
this.buf.length = 0; this.monCache.clear(); this.bulCache.clear();
|
||||
this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear();
|
||||
if (snap) this._push(snap, true);
|
||||
}
|
||||
_push(snap, first) {
|
||||
|
|
@ -246,7 +292,12 @@
|
|||
for (const a of snap.tt || []) tt.set(a[0], a);
|
||||
const e = { t: performance.now(), snap, mo, bu, tt, rel: !!first };
|
||||
this.buf.push(e);
|
||||
if (this.buf.length > 10) this.buf.shift();
|
||||
while (this.buf.length > BUF_MAX) {
|
||||
const old = this.buf.shift();
|
||||
// A stalled page (hidden tab, a long frame) gets a burst of snapshots. The server sends a tower list exactly once, so an entry
|
||||
// that carries one and was never displayed must not simply vanish (coop-1): its list rides along to the next update (the newest wins).
|
||||
if (old.snap.tw && !old.twDone) this._carryTw = old.snap;
|
||||
}
|
||||
}
|
||||
// Towers ride along with the snapshot that changed them and are applied when that snapshot is *displayed*
|
||||
// (see update), so a new tower and the credits it cost appear on screen together.
|
||||
|
|
@ -272,10 +323,13 @@
|
|||
let i = buf.length - 1;
|
||||
while (i > 0 && buf[i].t > rt) i--;
|
||||
const a = buf[i], b = buf[Math.min(i + 1, buf.length - 1)];
|
||||
const alpha = a === b ? 1 : clamp((rt - a.t) / (b.t - a.t), 0, 1);
|
||||
let lastTw = null;
|
||||
for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k]; } buf[k].twDone = true; }
|
||||
if (lastTw) { this._setTowers(lastTw.snap.tw); this.rev = lastTw.snap.rev; }
|
||||
const alpha = a === b ? 1 : clamp((rt - a.t) / Math.max(1e-3, b.t - a.t), 0, 1); // (a burst after a stall has equal arrival times)
|
||||
let lastTw = this._carryTw; this._carryTw = null;
|
||||
for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k].snap; } buf[k].twDone = true; }
|
||||
if (lastTw) { this._setTowers(lastTw.tw); this.rev = lastTw.rev; }
|
||||
// Backstop: every tower list that arrived has been applied or is still waiting in the buffer. If the revisions still differ, a list
|
||||
// was lost somehow: ask for the full state instead of showing a wrong maze until somebody builds again.
|
||||
else if (this.rev !== this.recvRev && !buf.some((x) => x.snap.tw && !x.twDone)) this.requestSync();
|
||||
const s = a.snap, v = this.view;
|
||||
v.gold = s.g; v.lives = s.l; v.wave = s.w; v.state = s.s; v.auto = !!s.au; v.nextWaveIn = s.nw; v.kills = s.k;
|
||||
v.rev = s.rev; v.queued = s.q || 0; v.time = s.time;
|
||||
|
|
@ -319,6 +373,7 @@
|
|||
|
||||
send(cmd) {
|
||||
const c = Object.assign({}, cmd); delete c.by;
|
||||
stampCmd(c, this.view);
|
||||
this._send(Object.assign({ t: 'cmd' }, c));
|
||||
return { ok: true, pending: true };
|
||||
}
|
||||
|
|
@ -339,13 +394,20 @@
|
|||
this._send({ t: 'cursor', x: x === null ? null : Math.round(x * 100) / 100, y: y === null ? null : Math.round(y * 100) / 100 });
|
||||
}
|
||||
sendMark(x, y) { this._send({ t: 'mark', x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100 }); }
|
||||
// Leaves the room (a deliberate leave frees the seat at once) and detaches from the UI for good: after this nothing is emitted, so
|
||||
// a controller that was still connecting cannot take over a game that was started meanwhile (code-3).
|
||||
close() {
|
||||
if (this.intentional) return;
|
||||
this.intentional = true;
|
||||
this._stopTimers();
|
||||
document.removeEventListener('visibilitychange', this._onVis);
|
||||
root.removeEventListener('online', this._onVis);
|
||||
if (this.ws) { try { this._send({ t: 'leave' }); this.ws.close(); } catch (e) { /* ignore */ } }
|
||||
this._stopTimers(); this._dispose();
|
||||
const ws = this.ws; this.ws = null;
|
||||
if (ws) {
|
||||
try { if (ws.readyState === 1) ws.send(JSON.stringify({ t: 'leave' })); } catch (e) { /* ignore */ }
|
||||
ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
|
||||
try { ws.close(); } catch (e) { /* ignore */ }
|
||||
}
|
||||
this._setStatus('closed');
|
||||
this._h = {};
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,9 @@
|
|||
const TD = root.TD, NW = root.NW, Audio = NW.Audio;
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
||||
// Anything that came from the server and goes into innerHTML is escaped; colours are looked up in our own table (code-28).
|
||||
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const slotColor = (slot) => (Number.isInteger(slot) && NW.SLOT_COLORS[slot]) || '#9db4d8';
|
||||
|
||||
// ------------------------------------------------------------------ storage (every access guarded)
|
||||
const store = {
|
||||
|
|
@ -89,7 +92,45 @@
|
|||
const wasHidden = o.hidden; o.hidden = o.id !== id;
|
||||
if (wasHidden && !o.hidden) { const body = o.querySelector('.card-body'); if (body) body.scrollTop = 0; }
|
||||
}
|
||||
syncModal();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ dialogs (menu, lobby, help, end are role=dialog)
|
||||
// While one is open the page behind it is inert (not focusable, not clickable, hidden from screen readers), focus moves into the
|
||||
// dialog onto its primary button, Tab stays inside it, and focus goes back to where it was when the dialog closes (code-8).
|
||||
// Overlays are also hidden and shown directly (`$('end').hidden = true`), so a MutationObserver keeps this in step.
|
||||
const modal = { open: null, opener: null, guard: 0 };
|
||||
const isShown = (el) => el.getClientRects().length > 0 && !el.disabled;
|
||||
function syncModal() {
|
||||
const ov = document.querySelector('.overlay:not([hidden])');
|
||||
if (ov === modal.open) return;
|
||||
const was = modal.open;
|
||||
modal.open = ov;
|
||||
if (ov && !was) { const a = document.activeElement; modal.opener = a && a !== document.body && a.isConnected ? a : null; } // (before the page behind it goes inert and drops focus)
|
||||
for (const id of ['topbar', 'stage', 'side']) { const el = $(id); if (el) el.toggleAttribute('inert', !!ov); }
|
||||
if (ov) {
|
||||
const btns = [...ov.querySelectorAll('button')].filter(isShown);
|
||||
const first = btns.find((b) => b.classList.contains('primary')) || btns[0]; // never a text field: on a phone that would raise the keyboard
|
||||
if (ov.id === 'end') modal.guard = performance.now() + 600; // (see the click guard below)
|
||||
if (first) first.focus({ preventScroll: true });
|
||||
} else if (was) {
|
||||
const o = modal.opener; modal.opener = null;
|
||||
if (o && o.isConnected && isShown(o) && !o.closest('[inert]')) o.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
root.addEventListener('keydown', (e) => { // Tab wraps inside the open dialog (browsers without `inert` would let it out)
|
||||
if (e.key !== 'Tab' || !modal.open) return;
|
||||
const items = [...modal.open.querySelectorAll('button, input, a[href]')].filter(isShown);
|
||||
if (!items.length) { e.preventDefault(); return; }
|
||||
const first = items[0], last = items[items.length - 1], a = document.activeElement;
|
||||
if (!modal.open.contains(a)) { e.preventDefault(); first.focus(); }
|
||||
else if (e.shiftKey && a === first) { e.preventDefault(); last.focus(); }
|
||||
else if (!e.shiftKey && a === last) { e.preventDefault(); first.focus(); }
|
||||
});
|
||||
{ const mo = new MutationObserver(syncModal); for (const o of document.querySelectorAll('.overlay')) mo.observe(o, { attributes: true, attributeFilter: ['hidden'] }); }
|
||||
// The game-over dialog takes focus the moment the game ends, and a player who was tapping Space / Enter to start waves would
|
||||
// press its focused "Play again" with the next key and never see the result. For the first 0.6 s only a pointer can press its buttons.
|
||||
$('end').addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
|
||||
function setScreen(name) {
|
||||
app.screen = name;
|
||||
$('app').dataset.screen = name;
|
||||
|
|
@ -99,11 +140,16 @@
|
|||
function useController(ctrl) {
|
||||
if (app.ctrl && app.ctrl !== ctrl && app.ctrl.kind === 'remote') { /* closed by caller */ }
|
||||
app.ctrl = ctrl;
|
||||
app.menuPaused = false;
|
||||
if (ctrl.kind !== 'remote') { ui.coop = false; ui.names = {}; app.prevPlayers = null; } // no co-op owner flags / join toasts left over in a solo game (code-17)
|
||||
ctrl.on('events', onEvents);
|
||||
ctrl.on('reject', onReject);
|
||||
ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); });
|
||||
ctrl.on('players', onPlayers);
|
||||
ctrl.on('newgame', () => { resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true; });
|
||||
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)
|
||||
});
|
||||
adoptBoard(true);
|
||||
}
|
||||
function adoptBoard(force) {
|
||||
|
|
@ -122,6 +168,7 @@
|
|||
}
|
||||
|
||||
function startSolo(mapId) {
|
||||
cancelPending(); // a co-op join that is still connecting must not take this game over (code-3)
|
||||
leaveRemote(true);
|
||||
app.mapId = mapId; store.set('nw.map', mapId);
|
||||
const c = new NW.LocalController({ map: mapId });
|
||||
|
|
@ -130,8 +177,14 @@
|
|||
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
|
||||
renderInfo(true);
|
||||
Audio.music('battle');
|
||||
app.bossMusic = false; Audio.music('battle');
|
||||
requestWakeLock();
|
||||
firstRunHelp();
|
||||
}
|
||||
// The first-run help opens once per install (storage) and at most once per page load, so a browser whose storage throws does not get it on every start (code-26).
|
||||
function firstRunHelp() {
|
||||
if (app.helpSeen) return;
|
||||
app.helpSeen = true;
|
||||
if (!store.get('nw.helped', false)) { store.set('nw.helped', true); showOverlay('help'); }
|
||||
}
|
||||
function previewMap(mapId) {
|
||||
|
|
@ -139,13 +192,14 @@
|
|||
c.paused = true;
|
||||
useController(c);
|
||||
app.inGame = false;
|
||||
releaseWakeLock(); // nobody is playing: the screen may sleep again (code-20)
|
||||
}
|
||||
|
||||
function leaveRemote(silent) {
|
||||
// keep: the connection was lost, not left on purpose, so the saved room stays and a reload or "Resume" can still try (coop-6)
|
||||
function leaveRemote(silent, keep) {
|
||||
const c = app.ctrl;
|
||||
if (c && c.kind === 'remote') { c.close(); }
|
||||
sess.del('nw.room'); store.del('nw.session');
|
||||
clearRoomFromUrl();
|
||||
if (!keep) { sess.del('nw.room'); store.del('nw.session'); clearRoomFromUrl(); }
|
||||
if (!silent) { /* caller handles screens */ }
|
||||
}
|
||||
function clearRoomFromUrl() {
|
||||
|
|
@ -173,6 +227,7 @@
|
|||
}
|
||||
let errSfxAt = -1e9;
|
||||
function onReject(r) {
|
||||
if (r.reason === 'stale') return; // the partner pressed the same Upgrade / Next wave an instant earlier: it already happened, say nothing (coop-5)
|
||||
toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad');
|
||||
// One buzzer per wall stroke (a stroke can reject dozens of cells), and never a burst: co-op rejects arrive after the finger has lifted (touch-16)
|
||||
const now = performance.now();
|
||||
|
|
@ -181,6 +236,8 @@
|
|||
}
|
||||
|
||||
// ------------------------------------------------------------------ palette + info panel
|
||||
// What building one more of this tower costs right now (the Orbital Uplink gets dearer for every one owned): same function the sim charges with
|
||||
function priceOf(type) { return TD.priceFor(type, app.ctrl && app.ctrl.view ? app.ctrl.view.towers : 0); }
|
||||
function buildPalette() {
|
||||
const pal = $('palette');
|
||||
pal.textContent = '';
|
||||
|
|
@ -189,10 +246,10 @@
|
|||
const def = TD.TOWERS[type];
|
||||
const b = document.createElement('button');
|
||||
b.className = 'tbtn'; b.dataset.type = type; b.type = 'button';
|
||||
b.setAttribute('aria-label', def.name + ', ' + def.levels[0].cost + ' credits');
|
||||
b.setAttribute('aria-label', def.name + ', ' + priceOf(type) + ' credits');
|
||||
b.innerHTML = '<span class="key">' + def.key + '</span><canvas></canvas><span class="nm"></span><span class="cost"></span>';
|
||||
b.querySelector('.nm').textContent = def.name;
|
||||
b.querySelector('.cost').textContent = String(def.levels[0].cost);
|
||||
b.querySelector('.cost').textContent = String(priceOf(type));
|
||||
b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); });
|
||||
pal.appendChild(b);
|
||||
}
|
||||
|
|
@ -245,12 +302,16 @@
|
|||
if (L.rate) out.push(['Fire rate', L.rate.toFixed(1) + '/s']);
|
||||
if (L.dmg && L.rate) out.push(['DPS', String(Math.round(L.dmg * L.rate))]);
|
||||
if (L.range) out.push(['Range', L.range.toFixed(1)]);
|
||||
if (L.stun) out.push(['Stun', L.stun.toFixed(1) + ' s']); // Sandbox
|
||||
if (L.pulse) out.push(['Pulse', 'every ' + L.pulse.toFixed(1) + ' s']);
|
||||
if (L.boost) out.push(['Fire rate', '+' + Math.round(L.boost * 100) + '%']); // Load Balancer: the bonus it gives the turrets in range
|
||||
if (L.splash) out.push(['Splash', L.splash.toFixed(1)]);
|
||||
if (L.slow) out.push(['Slows', Math.round(L.slow * 100) + '%']);
|
||||
if (L.chains) out.push(['Chains', String(L.chains)]);
|
||||
return out;
|
||||
}
|
||||
function targetsText(def) { return def.ground && def.air ? 'ground + air' : def.ground ? 'ground only' : 'none'; }
|
||||
function aimsAtTargets(def) { return def.role !== 'wall' && def.role !== 'control' && def.role !== 'support'; } // has a Target mode and can get kills
|
||||
|
||||
// The info panel is built ONCE per selection (tower id + owner, or armed build type) and then updated in place, so a
|
||||
// button is never replaced under a finger: partner actions bump view.rev constantly in co-op (code-2). A rebuild that
|
||||
|
|
@ -267,21 +328,21 @@
|
|||
if (tower) {
|
||||
if (ctrl.kind === 'remote' && ctrl.players.length > 1) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
|
||||
shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : '');
|
||||
} else if (app.selType) shape = 'b' + app.selType;
|
||||
} else if (app.selType) shape = 'b' + app.selType + ':' + priceOf(app.selType); // the price can change while armed (Orbital Uplink)
|
||||
if (!force && shape === info.shape) { if (tower) syncInfo(); return; }
|
||||
if (info.pressed) { info.dirty = true; return; } // never replace a node while a pointer is down on it
|
||||
info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false;
|
||||
if (!shape) { box.textContent = ''; return; }
|
||||
if (tower) {
|
||||
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall';
|
||||
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', aim = aimsAtTargets(def);
|
||||
box.innerHTML =
|
||||
'<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' +
|
||||
'<div class="desc"></div><div class="kv"></div><div class="actions">' +
|
||||
(wall ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
|
||||
'<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>' +
|
||||
(wall ? '' : '<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>') +
|
||||
(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">' + (wall ? '' : '<span id="infoKills"></span>') + (ownerP ? '<span class="dot" style="background:' + NW.SLOT_COLORS[ownerP.slot] + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
|
||||
'<div class="byline">' + (aim ? '<span id="infoKills"></span>' : '') + (ownerP ? '<span class="dot" style="background:' + slotColor(ownerP.slot) + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
|
||||
box.querySelector('.nm').textContent = def.name;
|
||||
box.querySelector('.desc').textContent = def.desc;
|
||||
if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name;
|
||||
|
|
@ -293,7 +354,7 @@
|
|||
if (app.selType !== 'wall') kv += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>';
|
||||
box.innerHTML = '<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div><div class="desc"></div><div class="kv">' + kv + '</div></div>';
|
||||
box.querySelector('.nm').textContent = def.name;
|
||||
box.querySelector('.lv').textContent = def.levels[0].cost + ' credits';
|
||||
box.querySelector('.lv').textContent = priceOf(app.selType) + ' credits';
|
||||
box.querySelector('.desc').textContent = def.desc;
|
||||
NW.drawIcon(box.querySelector('canvas'), app.selType, 1);
|
||||
}
|
||||
|
|
@ -304,7 +365,7 @@
|
|||
const box = $('info'), view = app.ctrl.view, t = view.towers.find((x) => x.id === app.selTower);
|
||||
if (!t || !box.firstChild) return;
|
||||
const def = TD.TOWERS[t.type], wall = t.type === 'wall', i = t.level - 1;
|
||||
const canUp = t.level < def.levels.length, upCost = canUp ? def.levels[t.level].cost : 0;
|
||||
const canUp = t.level < def.levels.length, upCost = canUp ? TD.upgradePrice(t.type, t.level, t.pm) : 0;
|
||||
const affordable = canUp && view.gold >= upCost;
|
||||
const sellVal = def.refund ? t.spent : Math.floor(t.spent * TD.SELL_RATIO);
|
||||
const sig = t.level + ':' + t.mode + ':' + sellVal + ':' + t.kills + ':' + (affordable ? 1 : 0);
|
||||
|
|
@ -372,6 +433,7 @@
|
|||
app.last.waveKey = key;
|
||||
const box = $('nextwave');
|
||||
if (view.state !== 'playing') { box.textContent = ''; return; }
|
||||
if (n % 10 === 9 || n % 10 === 0) Audio.preload('boss'); // the boss theme is fetched a wave or two ahead, so it starts with the boss instead of seconds later (code-12)
|
||||
const sum = TD.waveSummary(n);
|
||||
let html = '<div class="panel"><h4>Next · wave ' + n + '</h4><div class="wv">';
|
||||
let air = false;
|
||||
|
|
@ -399,14 +461,15 @@
|
|||
app.prevPlayers = list.map((p) => Object.assign({}, p));
|
||||
renderPlayers();
|
||||
if (ctrl.kind === 'remote') renderInfo(false); // the shape includes the owner, so only a changed roster rebuilds
|
||||
if (!$('end').hidden) syncEndButtons(); // the host left while the end screen is up: the promoted guest gets "Play again" (coop-3, code-11)
|
||||
}
|
||||
function renderPlayers() {
|
||||
const ctrl = app.ctrl, box = $('players');
|
||||
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
|
||||
box.hidden = false;
|
||||
let html = '<div class="panel"><h4>Room ' + (ctrl.room || '') + ' <span id="plPing" class="muted"></span></h4>';
|
||||
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + ' <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:' + NW.SLOT_COLORS[p.slot] + '"></span><span class="pn"></span>' +
|
||||
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
|
||||
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
|
||||
}
|
||||
if (ctrl.players.length < 2) html += '<div class="muted small">Waiting for a partner… share the invite link.</div>';
|
||||
|
|
@ -420,7 +483,7 @@
|
|||
if (b.dataset.act === 'invite') invite();
|
||||
if (b.dataset.act === 'leave') { leaveToMenu(); }
|
||||
});
|
||||
function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + app.ctrl.room; }
|
||||
function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + encodeURIComponent(app.ctrl.room); }
|
||||
function invite() {
|
||||
const url = inviteUrl(), text = 'Join my Netwall game (room ' + app.ctrl.room + ')';
|
||||
if (root.navigator.share) { root.navigator.share({ title: 'Netwall', text, url }).catch(() => {}); return; }
|
||||
|
|
@ -448,19 +511,24 @@
|
|||
const attn = idle && view.wave === 0 && view.state === 'playing';
|
||||
if (L.attn !== attn) { L.attn = attn; $('btnWave').classList.toggle('attn', attn); }
|
||||
if (L.auto !== view.auto) { L.auto = view.auto; $('btnAuto').setAttribute('aria-pressed', view.auto ? 'true' : 'false'); }
|
||||
if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; }
|
||||
if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; $('btnSpeed').setAttribute('aria-label', 'Game speed ' + view.speed + '×'); } // (the name carries the value: a screen reader hears the speed, not just "Game speed")
|
||||
if (L.paused !== view.paused) { // paused: dimmed board, a resume pill, and an amber pressed pause button (not a second play triangle)
|
||||
L.paused = view.paused; $('pausedTag').hidden = !view.paused; $('stage').classList.toggle('paused', !!view.paused);
|
||||
$('btnPause').setAttribute('aria-pressed', view.paused ? 'true' : 'false'); $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
|
||||
$('btnPause').setAttribute('aria-pressed', view.paused ? 'true' : 'false'); // a toggle keeps its name ("Pause") and announces "pressed" while paused
|
||||
}
|
||||
const offline = !$('reconnect').hidden;
|
||||
if (L.offline !== offline) { L.offline = offline; $('app').classList.toggle('offline', offline); }
|
||||
if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = '<svg class="ic"><use href="#i-' + (Audio.muted ? 'mute' : 'sound') + '"/></svg>'; }
|
||||
// palette affordability
|
||||
const gold = view.gold;
|
||||
if (L.palGold !== gold) {
|
||||
L.palGold = gold;
|
||||
for (const b of $('palette').children) b.classList.toggle('poor', gold < TD.TOWERS[b.dataset.type].levels[0].cost);
|
||||
const palKey = gold + ':' + view.towers.length; // prices can change when the tower count does (Orbital Uplink)
|
||||
if (L.palGold !== palKey) {
|
||||
L.palGold = palKey;
|
||||
for (const b of $('palette').children) {
|
||||
const def = TD.TOWERS[b.dataset.type], price = priceOf(b.dataset.type), poor = gold < price;
|
||||
b.classList.toggle('poor', poor);
|
||||
const c = b.querySelector('.cost'); if (c && c.textContent !== String(price)) c.textContent = String(price);
|
||||
b.setAttribute('aria-label', def.name + ', ' + price + ' credits' + (poor ? ', not enough credits' : ''));
|
||||
}
|
||||
}
|
||||
if (ctrl.kind === 'remote') {
|
||||
const chip = $('netChip');
|
||||
|
|
@ -484,17 +552,21 @@
|
|||
$('endTitle').textContent = won ? 'Server secured!' : 'Breach!';
|
||||
$('endTitle').style.color = won ? 'var(--green)' : 'var(--red)';
|
||||
const best = store.get('nw.best.' + ctrl.board.mapId, 0);
|
||||
if (!won && view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave);
|
||||
if (view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave); // a win counts too (code-25)
|
||||
$('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.';
|
||||
const walls = view.towers.filter((t) => t.type === 'wall').length;
|
||||
const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Best (map)', Math.max(best, view.wave)]];
|
||||
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + r[1] + '</b></div>').join('');
|
||||
const remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
|
||||
$('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
|
||||
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + esc(r[1]) + '</b></div>').join(''); // (in co-op these numbers come from the server)
|
||||
syncEndButtons();
|
||||
$('btnContinue').hidden = !won;
|
||||
showOverlay('end');
|
||||
Audio.music(null); Audio.stinger(won ? 'win' : 'lose');
|
||||
}
|
||||
// Only the host of a co-op room starts the next game: the others wait. Called when the end screen opens and whenever the roster changes.
|
||||
function syncEndButtons() {
|
||||
const ctrl = app.ctrl, remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
|
||||
$('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ placement + previews
|
||||
function cellFromEvent(e) {
|
||||
|
|
@ -504,7 +576,7 @@
|
|||
function placeAt(cell) {
|
||||
const ctrl = app.ctrl;
|
||||
if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) return false;
|
||||
const cost = TD.TOWERS[app.selType].levels[0].cost;
|
||||
const cost = priceOf(app.selType);
|
||||
if (ctrl.view.gold < cost) { onReject({ reason: 'gold' }); return false; }
|
||||
ctrl.send({ c: 'place', type: app.selType, x: cell.x, y: cell.y });
|
||||
app.previewDirty = true;
|
||||
|
|
@ -521,7 +593,7 @@
|
|||
if (!force && !app.previewDirty && now - app.lastPreviewAt < 250) return;
|
||||
app.previewDirty = false; app.lastPreviewAt = now;
|
||||
const pv = ctrl.preview(cell.x, cell.y, true);
|
||||
const cost = TD.TOWERS[app.selType].levels[0].cost;
|
||||
const cost = priceOf(app.selType);
|
||||
const poor = ctrl.view.gold < cost;
|
||||
ui.preview = pv; ui.valid = pv.ok && !poor;
|
||||
if (!pv.ok) hint('✕ ' + (REASONS[pv.reason] || pv.reason), 'bad');
|
||||
|
|
@ -537,7 +609,7 @@
|
|||
function updateConfirm() {
|
||||
const show = !!(app.pending && app.selType && app.selType !== 'wall');
|
||||
$('confirm').hidden = !show;
|
||||
if (show) { const cost = TD.TOWERS[app.selType].levels[0].cost; $('confirmText').textContent = 'Build · ' + cost; $('btnConfirmBuild').setAttribute('aria-label', 'Build for ' + cost + ' credits'); hint(hintText, hintKind); }
|
||||
if (show) { const cost = priceOf(app.selType); $('confirmText').textContent = 'Build · ' + cost; $('btnConfirmBuild').setAttribute('aria-label', 'Build for ' + cost + ' credits'); hint(hintText, hintKind); }
|
||||
else if (!ptrs.size) clearCursor(); // (no pending cell, no finger down: the partner's view of our touch cursor goes)
|
||||
layoutBars(true);
|
||||
}
|
||||
|
|
@ -837,8 +909,9 @@
|
|||
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
|
||||
if (e.ctrlKey || e.metaKey) return;
|
||||
if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6)
|
||||
if (e.key && e.key.toLowerCase() === 'm' && !e.altKey) { Audio.toggleMuted(); return; } // M mutes anywhere: in the menu, behind a dialog, on the end screen (code-13)
|
||||
if (!app.inGame) return;
|
||||
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; }
|
||||
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
|
||||
const ctrl = app.ctrl, view = ctrl.view;
|
||||
const k = e.key.toLowerCase();
|
||||
// Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8)
|
||||
|
|
@ -851,7 +924,6 @@
|
|||
case 'p': ctrl.ctl('pause', !view.paused); break;
|
||||
case 'f': ctrl.ctl('speed', view.speed % 3 + 1); break;
|
||||
case 'a': ctrl.send({ c: 'auto', v: !view.auto }); break;
|
||||
case 'm': Audio.toggleMuted(); break;
|
||||
case 'u': if (app.selTower) $('info').querySelector('[data-act="up"]') && $('info').querySelector('[data-act="up"]').click(); break;
|
||||
case 'x': case 'delete': case 'backspace': if (app.selTower) { $('info').querySelector('[data-act="sell"]') && $('info').querySelector('[data-act="sell"]').click(); e.preventDefault(); } break;
|
||||
case 't': if (app.selTower) $('info').querySelector('[data-act="mode"]') && $('info').querySelector('[data-act="mode"]').click(); break;
|
||||
|
|
@ -867,7 +939,21 @@
|
|||
$('btnAuto').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'auto', v: !app.ctrl.view.auto }); });
|
||||
$('btnSpeed').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('speed', app.ctrl.view.speed % 3 + 1); });
|
||||
$('btnPause').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', !app.ctrl.view.paused); });
|
||||
$('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); });
|
||||
// The sound switch exists three times: the top bar, and a text button in the menu and the end dialog (the top bar is behind a dialog). One function keeps them in step.
|
||||
let soundShown = null;
|
||||
function syncSound() {
|
||||
const m = Audio.muted;
|
||||
if (soundShown === m) return;
|
||||
soundShown = m;
|
||||
const b = $('btnSound');
|
||||
b.innerHTML = '<svg class="ic"><use href="#i-' + (m ? 'mute' : 'sound') + '"/></svg>';
|
||||
b.setAttribute('aria-label', m ? 'Unmute sound' : 'Mute sound'); // the name says what a press does; the icon shows what is the case
|
||||
b.title = (m ? 'Sound is off' : 'Sound is on') + ' (M)';
|
||||
for (const id of ['btnMenuSound', 'btnEndSound']) { const x = $(id); if (x) x.textContent = 'Sound: ' + (m ? 'off' : 'on'); }
|
||||
}
|
||||
const toggleSound = () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); syncSound(); };
|
||||
for (const id of ['btnSound', 'btnMenuSound', 'btnEndSound']) $(id).addEventListener('click', toggleSound);
|
||||
syncSound();
|
||||
$('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); });
|
||||
$('pausedTag').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', false); });
|
||||
$('netChip').addEventListener('click', () => { if (app.ctrl && app.ctrl.kind === 'remote') { Audio.sfx('click'); invite(); } }); // room code chip: tap to invite
|
||||
|
|
@ -905,7 +991,8 @@
|
|||
}
|
||||
|
||||
function openMenu() {
|
||||
if (app.inGame && app.ctrl.kind === 'local') app.ctrl.ctl('pause', true);
|
||||
// The menu pauses a solo game, and only the menu un-pauses it again: a game the player paused themselves stays paused (code-21).
|
||||
if (app.inGame && app.ctrl.kind === 'local' && !app.ctrl.view.paused) { app.ctrl.ctl('pause', true); app.menuPaused = true; }
|
||||
setScreen(app.inGame ? 'playing' : 'menu');
|
||||
$('btnCloseMenu').hidden = !app.inGame;
|
||||
$('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo';
|
||||
|
|
@ -915,11 +1002,13 @@
|
|||
}
|
||||
function closeOverlayToGame() {
|
||||
if (!app.inGame) return;
|
||||
if (!$('lobby').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
|
||||
showOverlay(null);
|
||||
if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false);
|
||||
if (app.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); }
|
||||
}
|
||||
function leaveToMenu() {
|
||||
leaveRemote(true);
|
||||
function leaveToMenu(keep) {
|
||||
cancelPending();
|
||||
leaveRemote(true, keep);
|
||||
app.prevPlayers = null;
|
||||
app.inGame = false;
|
||||
$('reconnect').hidden = true; $('players').hidden = true; $('netChip').hidden = true;
|
||||
|
|
@ -950,11 +1039,11 @@
|
|||
function openLobby(code) {
|
||||
showOverlay('lobby'); setScreen(app.inGame ? 'playing' : 'menu');
|
||||
$('inName').value = store.get('nw.name', '') || '';
|
||||
if (code) $('inCode').value = code;
|
||||
if (code) { $('inCode').value = code; $('btnJoin').focus({ preventScroll: true }); } // an invite link: Enter must join that room, not create a new one (the dialog's first button is Create room)
|
||||
lobbyMsg(root.location.protocol === 'file:' ? 'Co-op needs the Netwall server: run "npm start" and open its address (the page is currently opened as a file).' : '', root.location.protocol === 'file:');
|
||||
}
|
||||
$('btnCoop').addEventListener('click', () => { Audio.unlock(); openLobby(); });
|
||||
$('btnLobbyBack').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else openMenu(); });
|
||||
$('btnLobbyBack').addEventListener('click', () => { cancelPending(); lobbyMsg(''); if (app.inGame) closeOverlayToGame(); else openMenu(); });
|
||||
$('inCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
|
||||
$('btnCreate').addEventListener('click', () => connectRemote({ room: null, map: app.mapId }));
|
||||
$('btnJoin').addEventListener('click', () => {
|
||||
|
|
@ -964,34 +1053,64 @@
|
|||
});
|
||||
$('inCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnJoin').click(); });
|
||||
|
||||
// The co-op controller whose join is in progress. It becomes app.ctrl only once it has joined, so a failed join (wrong code, full room)
|
||||
// leaves the game that is running untouched (coop-4), Back / Play solo can cancel it (code-3), and only one attempt runs at a time (code-4).
|
||||
let pendingRc = null;
|
||||
const KEEP_SESSION = { connect: 1, lost: 1, replaced: 1 }; // after these the saved room is still worth another try; any other failure means it is gone
|
||||
function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume']) $(id).disabled = b; }
|
||||
function cancelPending() {
|
||||
const rc = pendingRc; pendingRc = null;
|
||||
if (rc) rc.close();
|
||||
setLobbyBusy(false);
|
||||
}
|
||||
// opts: { room, map, resume }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
|
||||
function connectRemote(opts) {
|
||||
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; }
|
||||
if (pendingRc) return; // a double click must not open two rooms and an orphan socket
|
||||
const live = app.inGame && app.ctrl && app.ctrl.kind === 'remote' ? app.ctrl : null;
|
||||
if (live && opts.room && live.room === opts.room) { closeOverlayToGame(); return; } // that is the room we are in
|
||||
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
|
||||
store.set('nw.name', name);
|
||||
if (app.ctrl && app.ctrl.kind === 'remote') app.ctrl.close();
|
||||
lobbyMsg('Connecting…');
|
||||
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map });
|
||||
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, resume: !!opts.resume });
|
||||
pendingRc = rc; setLobbyBusy(true);
|
||||
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); };
|
||||
let first = true;
|
||||
rc.on('joined', () => {
|
||||
sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() });
|
||||
if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over
|
||||
saveSession();
|
||||
$('reconnect').hidden = true;
|
||||
if (first) {
|
||||
first = false;
|
||||
first = false; pendingRc = null; setLobbyBusy(false);
|
||||
const old = app.ctrl; if (old && old !== rc && old.kind === 'remote') old.close(); // the room we were in is left only now that the new one is ours
|
||||
useController(rc);
|
||||
app.inGame = true; app.started = true; app.last = {}; app.endShown = false; app.prevPlayers = null;
|
||||
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||
onPlayers(rc.players);
|
||||
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + rc.room); } catch (e) { /* ignore */ }
|
||||
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
|
||||
toast('Room ' + rc.room + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good');
|
||||
Audio.music('battle'); requestWakeLock();
|
||||
firstRunHelp(); // an invited player is new to the game too (code-26)
|
||||
} else { toast('Reconnected', 'good'); adoptBoard(); }
|
||||
lobbyMsg('');
|
||||
});
|
||||
rc.on('status', (s) => { if (app.ctrl === rc && app.inGame) $('reconnect').hidden = s !== 'reconnecting'; });
|
||||
rc.on('status', (s) => {
|
||||
if (app.ctrl !== rc || !app.inGame) return;
|
||||
$('reconnect').hidden = s !== 'reconnecting';
|
||||
if (s === 'reconnecting') saveSession(); // the 15 minutes of "Resume" count from the last time we were in the room
|
||||
});
|
||||
rc.on('fatal', (f) => {
|
||||
sess.del('nw.room'); store.del('nw.session');
|
||||
if (app.ctrl === rc && app.inGame) { toast(f.msg, 'bad'); leaveToMenu(); openLobby(); lobbyMsg(f.msg, true); }
|
||||
else lobbyMsg(f.msg, true);
|
||||
if (pendingRc === rc) { pendingRc = null; setLobbyBusy(false); }
|
||||
const keep = !!KEEP_SESSION[f.code];
|
||||
if (app.ctrl === rc && app.inGame) { // the game we were playing is gone
|
||||
if (!keep) { sess.del('nw.room'); store.del('nw.session'); }
|
||||
toast(f.msg, 'bad'); leaveToMenu(keep); openLobby(); lobbyMsg(f.msg, true);
|
||||
return;
|
||||
}
|
||||
if (opts.resume && !keep) { sess.del('nw.room'); store.del('nw.session'); } // the saved game cannot be rejoined: forget it
|
||||
lobbyMsg(f.msg, true);
|
||||
if ($('lobby').hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
|
||||
updateResumeButton();
|
||||
});
|
||||
rc.connect();
|
||||
}
|
||||
|
|
@ -1006,13 +1125,26 @@
|
|||
const s = store.get('nw.session', null); if (!s) return;
|
||||
sess.set('nw.pid', s.pid);
|
||||
$('inName').value = s.name || '';
|
||||
connectRemote({ room: s.room });
|
||||
connectRemote({ room: s.room, resume: true });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ misc platform bits
|
||||
let wakeLock = null;
|
||||
let wakeLock = null, wakeAsk = false;
|
||||
function requestWakeLock() {
|
||||
try { if (navigator.wakeLock && !wakeLock) navigator.wakeLock.request('screen').then((l) => { wakeLock = l; l.addEventListener('release', () => { wakeLock = null; }); }).catch(() => {}); } catch (e) { /* ignore */ }
|
||||
if (wakeLock || wakeAsk) return;
|
||||
try {
|
||||
if (!navigator.wakeLock) return;
|
||||
wakeAsk = true;
|
||||
navigator.wakeLock.request('screen').then((l) => {
|
||||
wakeAsk = false;
|
||||
if (!app.inGame) { l.release().catch(() => {}); return; } // the game ended while the request was in flight
|
||||
wakeLock = l; l.addEventListener('release', () => { if (wakeLock === l) wakeLock = null; });
|
||||
}).catch(() => { wakeAsk = false; });
|
||||
} catch (e) { wakeAsk = false; }
|
||||
}
|
||||
function releaseWakeLock() { // back at the menu the screen may sleep again (code-20)
|
||||
const l = wakeLock; wakeLock = null;
|
||||
if (l) { try { l.release().catch(() => {}); } catch (e) { /* ignore */ } }
|
||||
}
|
||||
document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); });
|
||||
|
||||
|
|
@ -1066,20 +1198,25 @@
|
|||
const ctrl = app.ctrl; if (!ctrl) return;
|
||||
ctrl.update(now);
|
||||
const view = ctrl.view;
|
||||
syncSound(); // (M, the top bar, the menu and the end dialog can all flip it)
|
||||
if (app.inGame) {
|
||||
if (app.last.state !== view.state) {
|
||||
app.last.state = view.state;
|
||||
if (view.state === 'won' || view.state === 'lost') { if (!app.endShown) { app.endShown = true; endScreen(view); } }
|
||||
else if (app.endShown) { app.endShown = false; $('end').hidden = true; }
|
||||
else if (app.endShown) { // the game went on without this player pressing anything (the host's Keep going / Play again): its music starts here too (code-5)
|
||||
app.endShown = false; $('end').hidden = true;
|
||||
app.bossMusic = view.monsters.some((m) => m.kind === 'rootkit'); Audio.music(app.bossMusic ? 'boss' : 'battle');
|
||||
}
|
||||
}
|
||||
if (app.selTower && !view.towers.some((t) => t.id === app.selTower)) { app.selTower = 0; renderInfo(true); }
|
||||
if (app.pending && pendFree) { // the partner built on the cell being previewed: drop it and say so (coop-7)
|
||||
const t = towerAtCell(app.pending);
|
||||
if (t) { setPending(null); toast(((ui.names && ui.names[t.owner]) || 'Someone') + ' just built there', 'bad'); }
|
||||
}
|
||||
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(false); }
|
||||
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower || app.selType) renderInfo(false); }
|
||||
updateHud(view);
|
||||
layoutBars(false);
|
||||
updateFit(); // the Reset-zoom button always follows the camera, however it was reset (code-18, coop-8)
|
||||
if (now - app.lastBossCheck > 600 && view.state === 'playing') {
|
||||
app.lastBossCheck = now;
|
||||
const boss = view.monsters.some((m) => m.kind === 'rootkit');
|
||||
|
|
@ -1108,7 +1245,7 @@
|
|||
if (savedRoom && /^[A-Z0-9]{4}$/.test(savedRoom) && root.location.protocol !== 'file:' && (!codeParam || codeParam === savedRoom)) {
|
||||
// page reload in the same tab: slip straight back into the room
|
||||
$('inName').value = store.get('nw.name', '') || '';
|
||||
connectRemote({ room: savedRoom });
|
||||
connectRemote({ room: savedRoom, resume: true });
|
||||
} else if (/^[A-Z0-9]{4}$/.test(codeParam)) {
|
||||
openLobby(codeParam);
|
||||
lobbyMsg('Enter your name and press Join.');
|
||||
|
|
|
|||
|
|
@ -37,8 +37,8 @@
|
|||
}
|
||||
|
||||
// ------------------------------------------------------------------ tower glyphs (also used for UI icons)
|
||||
// S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation)
|
||||
function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot) {
|
||||
// S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation), fx = 0..1 flash right after a Sandbox pulse
|
||||
function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot, fx) {
|
||||
const def = TD.TOWERS[type]; if (!def) return;
|
||||
const col = def.color;
|
||||
ctx.save();
|
||||
|
|
@ -117,6 +117,43 @@
|
|||
}
|
||||
break;
|
||||
}
|
||||
case 'sandbox': {
|
||||
// containment cell: four corner brackets round a core that hums, held by thin tethers; it flashes when it pulses
|
||||
const g = fx || 0, p = 0.5 + 0.5 * Math.sin(t * 3), a = S * 0.22, k = S * 0.11;
|
||||
ctx.save(); ctx.translate(0, -S * 0.04);
|
||||
ctx.strokeStyle = rgba(col, 0.45); ctx.lineWidth = S * 0.03;
|
||||
ctx.beginPath();
|
||||
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * S * 0.09, sy * S * 0.09); ctx.lineTo(sx * (a - k * 0.35), sy * (a - k * 0.35)); }
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = col; ctx.lineWidth = S * 0.06;
|
||||
ctx.beginPath();
|
||||
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * a, sy * (a - k)); ctx.lineTo(sx * a, sy * a); ctx.lineTo(sx * (a - k), sy * a); }
|
||||
ctx.stroke();
|
||||
const c = S * (0.095 + 0.015 * p + 0.05 * g);
|
||||
ctx.beginPath(); ctx.moveTo(0, -c); ctx.lineTo(c, 0); ctx.lineTo(0, c); ctx.lineTo(-c, 0); ctx.closePath();
|
||||
ctx.fillStyle = g > 0 ? '#fff3dd' : rgba(col, 0.55 + 0.3 * p); ctx.fill();
|
||||
ctx.lineWidth = S * 0.035; ctx.stroke();
|
||||
ctx.restore();
|
||||
break;
|
||||
}
|
||||
case 'balancer': {
|
||||
// scales: post, a gently rocking beam and two hanging pans
|
||||
const dy = S * 0.27 * Math.sin(Math.sin(t * 1.4) * 0.07), ex = S * 0.27, top = -S * 0.21;
|
||||
ctx.save(); ctx.translate(0, -S * 0.02);
|
||||
ctx.lineWidth = S * 0.05; ctx.strokeStyle = col;
|
||||
ctx.beginPath(); ctx.moveTo(0, top); ctx.lineTo(0, S * 0.14); ctx.moveTo(-S * 0.12, S * 0.15); ctx.lineTo(S * 0.12, S * 0.15); ctx.stroke();
|
||||
ctx.beginPath(); ctx.moveTo(-ex, top - dy); ctx.lineTo(ex, top + dy); ctx.stroke();
|
||||
for (const sx of [-1, 1]) {
|
||||
const px = sx * ex, py = top + sx * dy, w = S * 0.1, d = S * 0.14;
|
||||
ctx.lineWidth = S * 0.03;
|
||||
ctx.beginPath(); ctx.moveTo(px - w, py + d); ctx.lineTo(px, py); ctx.lineTo(px + w, py + d); ctx.stroke();
|
||||
ctx.fillStyle = rgba(col, 0.55); ctx.beginPath(); ctx.arc(px, py + d, w, 0, Math.PI); ctx.closePath(); ctx.fill();
|
||||
ctx.lineWidth = S * 0.04; ctx.beginPath(); ctx.arc(px, py + d, w, 0, Math.PI); ctx.stroke();
|
||||
}
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, top, S * 0.05, 0, TAU); ctx.fill();
|
||||
ctx.restore();
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
// level pips: big enough to read at 14 px cells, with a dark halo so they show on any tile colour
|
||||
|
|
@ -129,8 +166,26 @@
|
|||
}
|
||||
|
||||
// ------------------------------------------------------------------ monsters
|
||||
function drawMonster(ctx, m, ang, t, flash, rot) {
|
||||
// Hit points and shield of one enemy, from either kind of view object. Solo hands the sim's monsters over (hp and shield apart:
|
||||
// m.shield / m.maxShield); co-op gets hp + shield out of maxhp + maxShield from the wire, and the split follows the kind's table
|
||||
// (the shield soaks first, so what is above the hit point part of the total is shield). Result is a shared scratch object.
|
||||
const VIT = { hp: 0, mh: 1, sh: 0, ms: 0 };
|
||||
function vitals(m, def) {
|
||||
if (!def.shield) { VIT.hp = m.hp; VIT.mh = m.maxhp; VIT.sh = 0; VIT.ms = 0; }
|
||||
else if (m.maxShield !== undefined) { VIT.hp = m.hp; VIT.mh = m.maxhp; VIT.sh = m.shield; VIT.ms = m.maxShield; }
|
||||
else {
|
||||
const mh = m.maxhp * def.hp / (def.hp + def.shield);
|
||||
VIT.mh = mh; VIT.ms = m.maxhp - mh; VIT.hp = Math.min(m.hp, mh); VIT.sh = Math.max(0, m.hp - mh);
|
||||
}
|
||||
return VIT;
|
||||
}
|
||||
const SWARM = { botnet: 1 }; // swarm units die in a hit or two: no bar, no ground shadow, few particles (there can be 100+)
|
||||
|
||||
// stun: true while the enemy is frozen by a Sandbox (the caller knows: the sim's stunT in solo, "slow flag and not moving" in co-op)
|
||||
function drawMonster(ctx, m, ang, t, flash, rot, stun) {
|
||||
const def = TD.ENEMIES[m.kind], r = def.r * C, col = def.color;
|
||||
const v = vitals(m, def), sf = v.ms > 0 ? clamp(v.sh / v.ms, 0, 1) : 0;
|
||||
const lift = m.kind === 'ghost' ? -7 : 0;
|
||||
ctx.save();
|
||||
ctx.translate(m.x * C, m.y * C);
|
||||
if (rot) { ctx.rotate(-rot); ang += rot; }
|
||||
|
|
@ -187,20 +242,72 @@
|
|||
ctx.fillStyle = rgba('#ff3b3b', 0.55 + Math.sin(t * 4) * 0.3); ctx.beginPath(); ctx.arc(0, 0, r * 0.45, 0, TAU); ctx.fill();
|
||||
break;
|
||||
}
|
||||
case 'daemon': {
|
||||
// healer: an upright plus (a medic cross), its core breathing in time with the heal pulse
|
||||
const a = r * 1.3, w = r * 0.38, br = 0.5 + 0.5 * Math.sin(t * 5 + m.id);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-w, -a); ctx.lineTo(w, -a); ctx.lineTo(w, -w); ctx.lineTo(a, -w); ctx.lineTo(a, w); ctx.lineTo(w, w);
|
||||
ctx.lineTo(w, a); ctx.lineTo(-w, a); ctx.lineTo(-w, w); ctx.lineTo(-a, w); ctx.lineTo(-a, -w); ctx.lineTo(-w, -w); ctx.closePath();
|
||||
ctx.fillStyle = '#0d2b17'; ctx.fill(); ctx.lineWidth = 2.8; ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.fillStyle = rgba('#d6ffe0', 0.5 + 0.4 * br);
|
||||
ctx.fillRect(-w * 0.45, -a * 0.62, w * 0.9, a * 1.24); ctx.fillRect(-a * 0.62, -w * 0.45, a * 1.24, w * 0.9);
|
||||
break;
|
||||
}
|
||||
case 'proxy': {
|
||||
// shielded relay: a heater-shield badge (never a hexagon: the Trojan is one) inside a bubble that thins as the shield goes
|
||||
if (sf > 0.01) {
|
||||
ctx.fillStyle = rgba('#7ab8ff', 0.07 + 0.2 * sf); ctx.beginPath(); ctx.arc(0, 0, r * 1.55, 0, TAU); ctx.fill();
|
||||
ctx.lineWidth = 0.9 + 2.3 * sf; ctx.strokeStyle = rgba('#b9dcff', 0.3 + 0.65 * sf); ctx.stroke();
|
||||
}
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-r * 0.92, -r * 0.8); ctx.lineTo(r * 0.92, -r * 0.8); ctx.lineTo(r * 0.92, r * 0.12); ctx.lineTo(0, r * 1.05); ctx.lineTo(-r * 0.92, r * 0.12); ctx.closePath();
|
||||
ctx.fillStyle = '#0d1a3a'; ctx.fill(); ctx.lineWidth = 2.8; ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.fillStyle = rgba(col, 0.9); ctx.beginPath(); ctx.arc(0, -r * 0.12, r * 0.3, 0, TAU); ctx.fill();
|
||||
ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(0, r * 0.2); ctx.lineTo(0, r * 0.72); ctx.stroke();
|
||||
break;
|
||||
}
|
||||
case 'botnet': {
|
||||
// a drone of a swarm: spinning X of two struts with a rotor at each tip, wobbling about its path
|
||||
const a = Math.max(r * 1.7, 8), wb = 2.5;
|
||||
ctx.translate(Math.sin(t * 6 + m.id * 1.9) * wb, Math.cos(t * 5 + m.id * 2.3) * wb);
|
||||
ctx.rotate(t * 7 + m.id);
|
||||
ctx.lineWidth = 3; ctx.strokeStyle = col;
|
||||
ctx.beginPath(); ctx.moveTo(-a, -a); ctx.lineTo(a, a); ctx.moveTo(a, -a); ctx.lineTo(-a, a); ctx.stroke();
|
||||
ctx.fillStyle = '#a6f2ea';
|
||||
ctx.beginPath();
|
||||
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(sx * a + 2.6, sy * a); ctx.arc(sx * a, sy * a, 2.6, 0, TAU); }
|
||||
ctx.fill();
|
||||
ctx.fillStyle = '#e8fffd'; ctx.beginPath(); ctx.arc(0, 0, r * 0.6, 0, TAU); ctx.fill();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, r, 0, TAU); ctx.fill();
|
||||
}
|
||||
if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; }
|
||||
if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r + 3.5, 0, TAU); ctx.stroke(); }
|
||||
if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, lift, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; }
|
||||
if (stun) {
|
||||
// frozen by a Sandbox: an ice shell with crackling crystal spikes (the cyan ring below is only a slow)
|
||||
const swarm = SWARM[m.kind], s = swarm ? 7 : Math.max(r * 1.3, 7) + 2;
|
||||
ctx.fillStyle = 'rgba(200,240,255,.24)'; ctx.beginPath(); ctx.arc(0, lift, s, 0, TAU); ctx.fill();
|
||||
ctx.lineWidth = swarm ? 1.4 : 2; ctx.strokeStyle = '#eefbff'; ctx.stroke();
|
||||
if (!swarm) {
|
||||
ctx.lineWidth = 2.2; ctx.beginPath();
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const a = i * TAU / 6 + 0.5, len = s + (Math.sin(t * 31 + i * 2.1 + m.id) > 0 ? 6 : 3.5);
|
||||
ctx.moveTo(Math.cos(a) * s, lift + Math.sin(a) * s); ctx.lineTo(Math.cos(a) * len, lift + Math.sin(a) * len);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
} else if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, lift, r + 3.5, 0, TAU); ctx.stroke(); }
|
||||
ctx.restore();
|
||||
// health bar
|
||||
if (m.hp < m.maxhp) {
|
||||
const w = Math.max(15, r * 2.3), y = -r - (m.kind === 'ghost' ? 16 : 9), x = -w / 2;
|
||||
const f = clamp(m.hp / m.maxhp, 0, 1);
|
||||
// health bar (a blue shield strip above it for shielded kinds)
|
||||
if (!SWARM[m.kind] && (v.hp < v.mh || v.sh < v.ms)) {
|
||||
const w = Math.max(15, r * 2.3), y = -r * (sf > 0.01 ? 1.55 : 1) - (m.kind === 'ghost' ? 16 : 9), x = -w / 2;
|
||||
const f = clamp(v.hp / v.mh, 0, 1);
|
||||
ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot);
|
||||
ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, 5);
|
||||
ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, v.ms > 0 ? 8 : 5);
|
||||
ctx.fillStyle = f > 0.5 ? '#35e0a1' : f > 0.25 ? '#ffd24d' : '#ff5c7a';
|
||||
ctx.fillRect(x, y, w * f, 3);
|
||||
ctx.fillRect(x, y + (v.ms > 0 ? 3 : 0), w * f, 3);
|
||||
if (v.ms > 0) { ctx.fillStyle = '#6fb4ff'; ctx.fillRect(x, y, w * sf, 2); }
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
|
@ -214,6 +321,8 @@
|
|||
this.cam = { zoom: 1, px: 0, py: 0 };
|
||||
this.board = null;
|
||||
this.parts = []; this.rings = []; this.lines = []; this.texts = []; this.marks = [];
|
||||
this.pulses = []; // heal / stun pulses: their own small pool, so a swarm of daemons can never starve the leak and boom rings
|
||||
this.glow = new Map(); // Sandbox cell index -> seconds of flash left after its pulse
|
||||
this.aim = new Map(); this.trk = new Map();
|
||||
this.wallGrid = null;
|
||||
this.shake = 0; this.flashCore = 0; this.lastNow = 0;
|
||||
|
|
@ -225,8 +334,8 @@
|
|||
setBoard(board) {
|
||||
this.board = board;
|
||||
this.wallGrid = new Uint8Array(board.cols * board.rows);
|
||||
this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0;
|
||||
this.aim.clear(); this.trk.clear();
|
||||
this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0; this.pulses.length = 0;
|
||||
this.aim.clear(); this.trk.clear(); this.glow.clear();
|
||||
this.resetCamera();
|
||||
}
|
||||
resize(w, h, dpr) {
|
||||
|
|
@ -296,6 +405,7 @@
|
|||
}
|
||||
}
|
||||
_ring(x, y, r0, r1, col, life, w) { if (this.rings.length < 40) this.rings.push({ x, y, r0, r1, col, life, max: life, w: w || 2 }); }
|
||||
_pulse(x, y, r0, r1, col, life, w, fill) { if (this.pulses.length < 24) this.pulses.push({ x, y, r0, r1, col, life, max: life, w, fill }); }
|
||||
_text(x, y, txt, col) { if (this.texts.length < 24) this.texts.push({ x, y, txt, col, life: 0.9, max: 0.9 }); }
|
||||
addMark(x, y, slot) { this.marks.push({ x, y, slot: slot | 0, life: 1.6, max: 1.6 }); if (this.marks.length > 12) this.marks.shift(); }
|
||||
addEvents(evs) {
|
||||
|
|
@ -303,7 +413,7 @@
|
|||
switch (e.e) {
|
||||
case 'kill': {
|
||||
const d = TD.ENEMIES[e.k];
|
||||
this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : 6, 90, 0.5);
|
||||
this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : SWARM[e.k] ? 2 : 6, 90, 0.5);
|
||||
if (e.rw >= 3) this._text(e.x * C, e.y * C - 8, '+' + e.rw, '#ffd24d');
|
||||
break;
|
||||
}
|
||||
|
|
@ -334,6 +444,15 @@
|
|||
case 'place': { const d = TD.TOWERS[e.type]; this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 34, d ? d.color : '#fff', 0.35, 2.5); this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, d ? d.color : '#fff', 5, 60, 0.35); break; }
|
||||
case 'sell': this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, '#9db4d8', 6, 70, 0.35); break;
|
||||
case 'up': this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 38, '#ffffff', 0.4, 2.5); break;
|
||||
case 'stun': { // Sandbox pulse: an amber wave out to its range, a white one inside it, and the glyph flashes
|
||||
const d = TD.TOWERS.sandbox, col = d ? d.color : '#ffa447', b = this.board;
|
||||
const rg = (e.r || 3) * C;
|
||||
this._pulse(e.x * C, e.y * C, 10, rg, col, 0.55, 3.5, 0.13);
|
||||
this._pulse(e.x * C, e.y * C, 8, rg * 0.6, '#fff3dd', 0.35, 2, 0);
|
||||
if (b) this.glow.set(Math.floor(e.y) * b.cols + Math.floor(e.x), 0.4);
|
||||
break;
|
||||
}
|
||||
case 'heal': this._pulse(e.x * C, e.y * C, 10, (e.r || 2.2) * C, '#7ee08a', 0.7, 2.2, 0.07); break; // soft green wave out to the daemon's range
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
|
@ -413,6 +532,9 @@
|
|||
const monById = new Map();
|
||||
for (let i = 0; i < view.monsters.length; i++) monById.set(view.monsters[i].id, view.monsters[i]);
|
||||
|
||||
if (this.glow.size) for (const [k, g] of this.glow) { if (g - dt <= 0) this.glow.delete(k); else this.glow.set(k, g - dt); }
|
||||
this._drawLinks(ctx, towers, ui, t);
|
||||
|
||||
const coop = ui.coop;
|
||||
for (let i = 0; i < towers.length; i++) {
|
||||
const tw = towers[i];
|
||||
|
|
@ -421,7 +543,8 @@
|
|||
const tg = tw.tgt ? monById.get(tw.tgt) : null;
|
||||
if (tg) { ang = lerpAngle(ang, Math.atan2(tg.y - (tw.y + 0.5), tg.x - (tw.x + 0.5)), 0.35); this.aim.set(tw.id, ang); }
|
||||
const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C;
|
||||
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot);
|
||||
const gl = tw.type === 'sandbox' && this.glow.size ? this.glow.get(tw.y * cols + tw.x) : 0;
|
||||
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot, gl ? Math.min(1, gl / 0.25) : 0);
|
||||
if (coop && tw.type !== 'wall') { // owner corner flag: at least ~5 CSS px, dark outline so it shows on a tile of the same colour
|
||||
const k = Math.max(12, 5.5 / sc), x0 = cx - C * 0.46, y0 = cy - C * 0.46;
|
||||
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + k, y0); ctx.lineTo(x0, y0 + k); ctx.closePath();
|
||||
|
|
@ -502,6 +625,47 @@
|
|||
if (labels.length) this._cursorLabels(ctx, labels);
|
||||
}
|
||||
|
||||
// Load Balancer links: dashed lines (flowing towards the turret) and an outline on every attack tower it boosts, only for the balancer that is
|
||||
// selected, hovered or about to be built, so a busy board stays calm. Same rule as the sim's updateAuras: attack role, centre to centre
|
||||
// within range. (The wire has no per-tower buff flag, so this is worked out here from the tower list.)
|
||||
_drawLinks(ctx, towers, ui, t) {
|
||||
let src = null;
|
||||
if (ui.selTower) { const st = towers.find((x) => x.id === ui.selTower); if (st) src = st; }
|
||||
if (!src && ui.hover) {
|
||||
for (let i = 0; i < towers.length; i++) if (towers[i].x === ui.hover.x && towers[i].y === ui.hover.y) { src = towers[i]; break; }
|
||||
if (!src && ui.selType && !ui.noGhost) src = { type: ui.selType, level: 1, x: ui.hover.x, y: ui.hover.y };
|
||||
}
|
||||
const def = src && TD.TOWERS[src.type];
|
||||
if (!def || def.role !== 'support') return;
|
||||
const lv = def.levels[src.level - 1] || def.levels[0], r2 = (lv.range || 0) * (lv.range || 0);
|
||||
const bx = (src.x + 0.5) * C, by = (src.y + 0.5) * C;
|
||||
let lines = null;
|
||||
for (let i = 0; i < towers.length; i++) {
|
||||
const tw = towers[i], d = TD.TOWERS[tw.type];
|
||||
if (!d || d.role !== 'attack' || tw === src) continue;
|
||||
const dx = tw.x - src.x, dy = tw.y - src.y;
|
||||
if (dx * dx + dy * dy > r2) continue;
|
||||
(lines || (lines = [])).push(tw);
|
||||
}
|
||||
if (!lines) return;
|
||||
const u = Math.max(1, 0.55 / this.scale), lw = Math.max(2, 1.2 / this.scale); // keep the dashes and arrowheads readable when the cells are small
|
||||
ctx.save();
|
||||
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
|
||||
ctx.strokeStyle = rgba(def.color, 0.75); ctx.lineWidth = lw; ctx.setLineDash([6 * u, 5 * u]); ctx.lineDashOffset = -t * 16;
|
||||
ctx.beginPath();
|
||||
for (const tw of lines) { ctx.moveTo(bx, by); ctx.lineTo((tw.x + 0.5) * C, (tw.y + 0.5) * C); }
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
ctx.fillStyle = rgba(def.color, 0.95); ctx.lineWidth = lw;
|
||||
for (const tw of lines) { // an arrowhead just outside the tile, and a frame round it
|
||||
const tx = (tw.x + 0.5) * C, ty = (tw.y + 0.5) * C, a = Math.atan2(ty - by, tx - bx), d = C * 0.62 + 4 * u;
|
||||
const ax = tx - Math.cos(a) * d, ay = ty - Math.sin(a) * d, ca = Math.cos(a), sa = Math.sin(a);
|
||||
ctx.beginPath(); ctx.moveTo(ax + ca * 6 * u, ay + sa * 6 * u); ctx.lineTo(ax - ca * 3 * u - sa * 5 * u, ay - sa * 3 * u + ca * 5 * u); ctx.lineTo(ax - ca * 3 * u + sa * 5 * u, ay - sa * 3 * u - ca * 5 * u); ctx.closePath(); ctx.fill();
|
||||
rr(ctx, tw.x * C + 1.5, tw.y * C + 1.5, C - 3, C - 3, 6); ctx.stroke();
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
_rangeRing(ctx, cx, cy, r, col) {
|
||||
ctx.fillStyle = rgba(col, 0.07); ctx.beginPath(); ctx.arc(cx, cy, r, 0, TAU); ctx.fill();
|
||||
ctx.strokeStyle = rgba(col, 0.55); ctx.lineWidth = 1.5; ctx.stroke();
|
||||
|
|
@ -559,17 +723,33 @@
|
|||
|
||||
_drawMonsters(ctx, view, t, dt, air, rot) {
|
||||
const trk = this.trk;
|
||||
if (!air) { // a Daemon's heal range, faint, all in one stroke
|
||||
let any = false;
|
||||
for (const m of view.monsters) {
|
||||
const d = TD.ENEMIES[m.kind];
|
||||
if (!d.healRange) continue;
|
||||
if (!any) { any = true; ctx.beginPath(); }
|
||||
ctx.moveTo(m.x * C + d.healRange * C, m.y * C); ctx.arc(m.x * C, m.y * C, d.healRange * C, 0, TAU);
|
||||
}
|
||||
if (any) { ctx.strokeStyle = rgba(TD.ENEMIES.daemon.color, 0.15); ctx.lineWidth = 1.5; ctx.stroke(); }
|
||||
}
|
||||
for (const m of view.monsters) {
|
||||
if (!!m.air !== air) continue;
|
||||
const def = TD.ENEMIES[m.kind];
|
||||
let k = trk.get(m.id);
|
||||
if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0 }; trk.set(m.id, k); }
|
||||
if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0, still: 0, sv: null }; trk.set(m.id, k); }
|
||||
const dm = def.shield && m.maxShield === undefined ? this._shieldView(k, m, def, dt) : m; // co-op: tell hp and shield apart (see there)
|
||||
const v = vitals(dm, def), cur = v.hp + v.sh;
|
||||
const dx = m.x - k.x, dy = m.y - k.y;
|
||||
if (dx * dx + dy * dy > 1e-6) k.ang = lerpAngle(k.ang, Math.atan2(dy, dx), 0.35);
|
||||
k.still = dx * dx + dy * dy < 1e-8 ? k.still + dt : 0;
|
||||
k.x = m.x; k.y = m.y;
|
||||
if (m.hp < k.hp) k.flash = 0.1;
|
||||
k.hp = m.hp; k.flash = Math.max(0, k.flash - dt);
|
||||
if (air) { const er = TD.ENEMIES[m.kind].r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
|
||||
drawMonster(ctx, m, k.ang, t, k.flash, rot);
|
||||
if (cur < k.hp) k.flash = 0.1;
|
||||
k.hp = cur; k.flash = Math.max(0, k.flash - dt);
|
||||
// stunned: solo knows (stunT); in co-op the wire only says "slowed or stunned", and a slowed packet still moves, so a flagged packet that stands still is stunned
|
||||
const stun = m.stunT !== undefined ? m.stunT > 0 : m.slow > 0 && k.still > 0.2 && !view.paused;
|
||||
if (air && !SWARM[m.kind]) { const er = def.r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
|
||||
drawMonster(ctx, dm, k.ang, t, k.flash, rot, stun);
|
||||
}
|
||||
if (air && trk.size > view.monsters.length + 60) { // drop stale trackers
|
||||
const live = new Set(view.monsters.map((x) => x.id));
|
||||
|
|
@ -577,6 +757,27 @@
|
|||
}
|
||||
}
|
||||
|
||||
// Co-op sends a shielded enemy as hp + shield out of maxhp + maxShield. A shield soaks first, so most of the time the split is plain from the
|
||||
// total, but once the hp is hurt and the shield has regrown the total alone is ambiguous (hp 20 + shield 120 looks like hp 90 + shield 50).
|
||||
// So the split is followed over time: a drop in the total hits the shield first, a rise after shieldDelay seconds without a hit refills the
|
||||
// shield, any other rise is a heal. Returns a solo-style view object (hp and shield apart) kept in the tracker entry.
|
||||
_shieldView(k, m, def, dt) {
|
||||
const mh = m.maxhp * def.hp / (def.hp + def.shield), ms = m.maxhp - mh;
|
||||
let s = k.sv;
|
||||
if (!s) s = k.sv = { id: m.id, kind: m.kind, air: m.air, x: 0, y: 0, hp: 0, maxhp: mh, shield: clamp(m.hp - mh, 0, ms), maxShield: ms, slow: 0, tot: m.hp, idle: 0 };
|
||||
else {
|
||||
const d = m.hp - s.tot;
|
||||
if (d < -0.5) { s.shield -= Math.min(s.shield, -d); s.idle = 0; }
|
||||
else if (d > 0.5 && s.idle >= def.shieldDelay - 0.25 && s.shield < ms) s.shield = Math.min(ms, s.shield + d);
|
||||
s.tot = m.hp; s.idle += dt;
|
||||
}
|
||||
s.maxhp = mh; s.maxShield = ms;
|
||||
if (m.hp - s.shield > mh) s.shield = clamp(m.hp - mh, 0, ms); // more than the hp part can hold: the rest is shield
|
||||
s.hp = clamp(m.hp - s.shield, 0, mh);
|
||||
s.x = m.x; s.y = m.y; s.slow = m.slow; s.air = m.air;
|
||||
return s;
|
||||
}
|
||||
|
||||
_drawFx(ctx, dt, sc, rot) {
|
||||
// lines (tracers, arcs)
|
||||
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
|
||||
|
|
@ -600,6 +801,15 @@
|
|||
ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU); ctx.stroke();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
for (let i = this.pulses.length - 1; i >= 0; i--) {
|
||||
const r = this.pulses[i]; r.life -= dt;
|
||||
if (r.life <= 0) { this.pulses.splice(i, 1); continue; }
|
||||
const k = 1 - r.life / r.max;
|
||||
ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU);
|
||||
if (r.fill) { ctx.globalAlpha = (1 - k) * r.fill; ctx.fillStyle = r.col; ctx.fill(); }
|
||||
ctx.globalAlpha = 1 - k; ctx.strokeStyle = r.col; ctx.lineWidth = r.w; ctx.stroke();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
for (let i = this.parts.length - 1; i >= 0; i--) {
|
||||
const p = this.parts[i]; p.life -= dt;
|
||||
if (p.life <= 0) { this.parts.splice(i, 1); continue; }
|
||||
|
|
@ -651,6 +861,7 @@
|
|||
NW.Renderer = Renderer;
|
||||
NW.drawIcon = drawIcon;
|
||||
NW.drawGlyph = drawGlyph;
|
||||
NW.drawMonster = drawMonster;
|
||||
NW.SLOT_COLORS = SLOT_COLORS;
|
||||
NW.CELL = C;
|
||||
NW.BOARD_MARGIN = MARGIN;
|
||||
|
|
|
|||
268
public/js/sim.js
268
public/js/sim.js
|
|
@ -201,16 +201,21 @@
|
|||
}
|
||||
|
||||
// ---------------------------------------------------------------- definitions
|
||||
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink'];
|
||||
// Every tower has a 'role' so the generic code does not have to know the types:
|
||||
// wall solid block, does nothing attack shoots (dmg/rate, picks a target, can be rate-boosted)
|
||||
// aura continuous effect in range control periodic pulse that stuns everything in range
|
||||
// support no attack of its own: boosts the 'attack' towers around it
|
||||
// Hotkeys: one unique key 1-9 per tower, in palette order.
|
||||
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink'];
|
||||
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
|
||||
const TOWERS = {
|
||||
wall: {
|
||||
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1,
|
||||
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1, role: 'wall',
|
||||
desc: 'Blocks the route. Cheap: use it to build a long maze.',
|
||||
levels: [{ cost: 5 }],
|
||||
},
|
||||
filter: {
|
||||
name: 'Packet Filter', key: '2', color: '#35e0a1', air: true, ground: true,
|
||||
name: 'Packet Filter', key: '2', color: '#35e0a1', role: 'attack', air: true, ground: true,
|
||||
desc: 'Fast, cheap rapid fire. Weak against armour.',
|
||||
levels: [
|
||||
{ cost: 25, dmg: 6, range: 3.2, rate: 3.0 },
|
||||
|
|
@ -220,7 +225,7 @@
|
|||
bulletSpeed: 14,
|
||||
},
|
||||
ids: {
|
||||
name: 'IDS Sniper', key: '3', color: '#b78cff', air: true, ground: true,
|
||||
name: 'IDS Sniper', key: '3', color: '#b78cff', role: 'attack', air: true, ground: true,
|
||||
desc: 'Long range, hard hitting, slow. Great against armour and bosses.',
|
||||
levels: [
|
||||
{ cost: 60, dmg: 50, range: 6.5, rate: 0.7 },
|
||||
|
|
@ -229,7 +234,7 @@
|
|||
],
|
||||
},
|
||||
mortar: {
|
||||
name: 'Flood Mortar', key: '4', color: '#d4f04a', air: false, ground: true,
|
||||
name: 'Flood Mortar', key: '4', color: '#d4f04a', role: 'attack', air: false, ground: true,
|
||||
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
|
||||
levels: [
|
||||
{ cost: 55, dmg: 28, range: 4.8, rate: 0.8, splash: 1.3 },
|
||||
|
|
@ -239,7 +244,7 @@
|
|||
shellSpeed: 5.5,
|
||||
},
|
||||
throttle: {
|
||||
name: 'Rate Limiter', key: '5', color: '#4de3ff', air: true, ground: true,
|
||||
name: 'Rate Limiter', key: '5', color: '#4de3ff', role: 'aura', air: true, ground: true,
|
||||
desc: 'Slows everything in range. Pair it with damage dealers.',
|
||||
levels: [
|
||||
{ cost: 40, range: 3.2, slow: 0.35 },
|
||||
|
|
@ -248,7 +253,7 @@
|
|||
],
|
||||
},
|
||||
arc: {
|
||||
name: 'Router Arc', key: '6', color: '#ff7ad9', air: true, ground: true,
|
||||
name: 'Router Arc', key: '6', color: '#ff7ad9', role: 'attack', air: true, ground: true,
|
||||
desc: 'Chain lightning that jumps between nearby packets.',
|
||||
levels: [
|
||||
{ cost: 75, dmg: 16, range: 3.6, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
|
||||
|
|
@ -256,27 +261,82 @@
|
|||
{ cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
|
||||
],
|
||||
},
|
||||
uplink: {
|
||||
name: 'Orbital Uplink', key: '7', color: '#ffe27a', air: true, ground: true,
|
||||
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Very expensive to build and to upgrade.',
|
||||
sandbox: {
|
||||
name: 'Sandbox', key: '7', color: '#ffa447', role: 'control', air: true, ground: true,
|
||||
desc: 'Control tower, no damage. Every few seconds it traps every packet in range, ground and air, and freezes it for a moment. Bosses resist and are frozen for half as long.',
|
||||
levels: [
|
||||
{ cost: 450, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
|
||||
{ cost: 500, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
|
||||
{ cost: 800, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
|
||||
{ cost: 1200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
|
||||
{ cost: 90, range: 2.6, pulse: 5.0, stun: 1.0 },
|
||||
{ cost: 80, range: 3.0, pulse: 4.5, stun: 1.3 },
|
||||
{ cost: 130, range: 3.4, pulse: 4.0, stun: 1.6 },
|
||||
],
|
||||
},
|
||||
balancer: {
|
||||
name: 'Load Balancer', key: '8', color: '#d3e0ee', role: 'support',
|
||||
desc: 'Support tower, no attack. Makes every turret in range fire faster. Several balancers do not stack (the best one counts) and a balancer does not boost another balancer.',
|
||||
levels: [
|
||||
{ cost: 70, range: 2.2, boost: 0.15 },
|
||||
{ cost: 70, range: 2.6, boost: 0.25 },
|
||||
{ cost: 110, range: 3.0, boost: 0.35 },
|
||||
],
|
||||
},
|
||||
uplink: {
|
||||
name: 'Orbital Uplink', key: '9', color: '#ffe27a', role: 'attack', air: true, ground: true,
|
||||
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Extremely expensive to build and to upgrade, and every Uplink you already own makes the next one 25% dearer, and its upgrades too.',
|
||||
priceGrowth: 1.25, // the Nth Uplink costs cost * 1.25^(N-1) to buy AND to upgrade (see priceMult), so kill rewards cannot buy a carpet of them
|
||||
levels: [
|
||||
{ cost: 1500, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
|
||||
{ cost: 1200, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
|
||||
{ cost: 2000, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
|
||||
{ cost: 3200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit'];
|
||||
// ENEMY_ORDER is part of the wire format (snapshots carry the index): only ever APPEND kinds.
|
||||
// buyCost is the price of one unit in the future versus mode (about 3x the kill reward).
|
||||
// What building one more `type` costs right now, given the towers already on the board (an array, or a plain count).
|
||||
// Most towers have a fixed price; a tower with `priceGrowth` gets dearer for every one already owned. Shared by the Sim and
|
||||
// the UI so the price shown is always the price charged.
|
||||
// The price multiplier a NEW tower of this type is bought at, given how many are already owned. Each tower remembers the multiplier it was
|
||||
// bought at (tower.pm) and its upgrades cost the same multiple, so the Nth Uplink is dearer to buy and to upgrade by the same factor.
|
||||
function priceMult(type, owned) {
|
||||
const def = TOWERS[type];
|
||||
if (!def || !def.priceGrowth) return 1;
|
||||
let n = 0;
|
||||
if (Array.isArray(owned)) { for (const t of owned) if (t.type === type) n++; } else n = owned | 0;
|
||||
return Math.pow(def.priceGrowth, n);
|
||||
}
|
||||
const roundPrice = (v) => Math.round(v / 10) * 10;
|
||||
function priceFor(type, owned) {
|
||||
const def = TOWERS[type];
|
||||
if (!def) return 0;
|
||||
const base = def.levels[0].cost, m = priceMult(type, owned);
|
||||
return m === 1 ? base : roundPrice(base * m);
|
||||
}
|
||||
// What upgrading a tower of `type` that is at `level` (1-based) to the next level costs, given the multiplier it was bought at (pm, default 1).
|
||||
function upgradePrice(type, level, pm) {
|
||||
const def = TOWERS[type], lv = def && def.levels[level];
|
||||
if (!lv) return null;
|
||||
return !pm || pm === 1 ? lv.cost : roundPrice(lv.cost * pm);
|
||||
}
|
||||
|
||||
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit', 'daemon', 'proxy', 'botnet'];
|
||||
const ENEMIES = {
|
||||
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a' },
|
||||
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43' },
|
||||
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b' },
|
||||
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166' },
|
||||
ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff' },
|
||||
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', slowRes: 0.5 },
|
||||
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a', buyCost: 10 },
|
||||
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43', buyCost: 6 },
|
||||
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b', buyCost: 30 },
|
||||
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166', buyCost: 3 },
|
||||
ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff', buyCost: 15 },
|
||||
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', buyCost: 300, slowRes: 0.5 },
|
||||
// Healer: every HEAL_EVERY s it restores 'heal' of the max hp of every other enemy within healRange (several daemons stack up to HEAL_CAP).
|
||||
daemon: { name: 'Daemon', hp: 70, speed: 1.1, armor: 0, reward: 8, leak: 1, air: false, r: 0.3, color: '#7ee08a', buyCost: 25, heal: 0.06, healRange: 2.2 },
|
||||
// Shielded: 'shield' extra hit points (scaled like hp) that soak damage first and regrow shieldRegen/s of their max after shieldDelay s unhurt.
|
||||
proxy: { name: 'Proxy', hp: 90, speed: 1.0, armor: 1, reward: 10, leak: 1, air: false, r: 0.34, color: '#7aa2ff', buyCost: 30, shield: 120, shieldRegen: 0.1, shieldDelay: 3 },
|
||||
// Swarm flyer.
|
||||
botnet: { name: 'Botnet', hp: 12, speed: 2.6, armor: 0, reward: 1, leak: 1, air: true, r: 0.14, color: '#4dd0c8', buyCost: 3 },
|
||||
};
|
||||
const HEAL_EVERY = 1; // seconds between daemon pulses (one global clock, so the 12%/s cap is exact)
|
||||
const HEAL_CAP = 0.12; // most max-hp fraction one enemy can be healed per pulse, however many daemons are near
|
||||
|
||||
// Wave n (1-based). The first eight waves introduce each unit type; later ones loop with bigger numbers.
|
||||
function waveGroups(n) {
|
||||
|
|
@ -293,12 +353,42 @@
|
|||
case 6: g = [{ k: 'ghost', c: c(8), gap: 0.6 }, { k: 'spam', c: c(16), gap: 0.2 }]; break;
|
||||
default: g = [{ k: 'ping', c: c(10), gap: 0.4 }, { k: 'trojan', c: c(3), gap: 1.0 }, { k: 'ghost', c: c(4), gap: 0.8 }];
|
||||
}
|
||||
if (n > 8) weave(g, n, c, (n - 1) % 8);
|
||||
if (n % 10 === 0) g.push({ k: 'rootkit', c: n / 10, gap: 3 });
|
||||
return g;
|
||||
}
|
||||
// From wave 9 the eight-wave cycle gets the newer kinds woven in (groups spawn one after the other, so a group
|
||||
// appended behind another trails it):
|
||||
// daemon the first healer rides with the pings of wave 9; from then on every trojan group has an escort that
|
||||
// spawns behind it and (it is faster) catches up and heals while passing through
|
||||
// proxy from wave 12 in the spam / mixed-flyer-and-trojan slots, more slots later
|
||||
// botnet swarms from wave 14, more slots (and bigger) later
|
||||
function weave(g, n, c, p) {
|
||||
const trojans = g.find((e) => e.k === 'trojan');
|
||||
if (trojans) g.push({ k: 'daemon', c: Math.max(1, Math.round(trojans.c / 2)), gap: 1.2 });
|
||||
else if (n === 9) g.push({ k: 'daemon', c: 2, gap: 1.2 });
|
||||
if (n >= 12) {
|
||||
if (p === 3) g.push({ k: 'proxy', c: c(2), gap: 1.6 });
|
||||
else if (p === 7) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
|
||||
else if (p === 5 && n >= 22) g.push({ k: 'proxy', c: c(2), gap: 1.4 });
|
||||
else if (p === 2 && n >= 19) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
|
||||
else if (p === 0 && n >= 25) g.push({ k: 'proxy', c: c(1), gap: 1.6 });
|
||||
}
|
||||
if (n >= 14) {
|
||||
if (p === 5) g.push({ k: 'botnet', c: c(8), gap: 0.12 });
|
||||
else if (p === 6) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
|
||||
else if (p === 1 && n >= 18) g.push({ k: 'botnet', c: c(6), gap: 0.1 });
|
||||
else if (p === 4 && n >= 21) g.push({ k: 'botnet', c: c(8), gap: 0.1 });
|
||||
else if (p === 7 && n >= 24) g.push({ k: 'botnet', c: c(6), gap: 0.12 });
|
||||
}
|
||||
}
|
||||
// What the wave list in the UI shows: one entry per kind (counts summed), in order of appearance, flyers flagged.
|
||||
function waveSummary(n) {
|
||||
const out = [];
|
||||
for (const g of waveGroups(n)) out.push({ k: g.k, c: g.c });
|
||||
const out = [], at = {};
|
||||
for (const g of waveGroups(n)) {
|
||||
if (at[g.k] === undefined) { at[g.k] = out.length; out.push({ k: g.k, c: 0, air: !!ENEMIES[g.k].air }); }
|
||||
out[at[g.k]].c += g.c;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function hpScale(n) { return 1 + 0.16 * (n - 1) + 0.022 * (n - 1) * (n - 1); }
|
||||
|
|
@ -487,6 +577,7 @@
|
|||
this.autoWaves = false;
|
||||
this.nextWaveIn = -1;
|
||||
this.spawnRR = 0;
|
||||
this.healT = 0; // seconds since the last daemon pulse (one clock for all daemons)
|
||||
|
||||
this.towers = [];
|
||||
this.towerAt = new Array(this.board.cols * this.board.rows).fill(null);
|
||||
|
|
@ -509,9 +600,9 @@
|
|||
switch (c.c) {
|
||||
case 'place': return this.place(c.type, c.x, c.y, c.by | 0);
|
||||
case 'sell': return this.sell(c.id);
|
||||
case 'upgrade': return this.upgrade(c.id);
|
||||
case 'upgrade': return this.upgrade(c.id, c.lv);
|
||||
case 'target': return this.setTargetMode(c.id, c.mode);
|
||||
case 'wave': return this.startWave();
|
||||
case 'wave': return this.startWave(c.n);
|
||||
case 'auto': return this.setAuto(!!c.v);
|
||||
case 'continue': return this.continueEndless();
|
||||
default: return { ok: false, reason: 'bad_cmd' };
|
||||
|
|
@ -548,13 +639,13 @@
|
|||
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
||||
if (typeof type !== 'string' || !Object.prototype.hasOwnProperty.call(TOWERS, type)) return { ok: false, reason: 'bad_type' };
|
||||
const def = TOWERS[type];
|
||||
const cost = def.levels[0].cost;
|
||||
const cost = priceFor(type, this.towers), pm = priceMult(type, this.towers);
|
||||
if (this.gold < cost) return { ok: false, reason: 'gold' };
|
||||
const t = this.preview(x, y, false);
|
||||
if (!t.ok) return { ok: false, reason: t.reason };
|
||||
const tower = {
|
||||
id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0,
|
||||
cd: 0, tgt: 0, kills: 0, dealt: 0,
|
||||
id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0, pm,
|
||||
cd: 0, tgt: 0, kills: 0, dealt: 0, buff: 0,
|
||||
};
|
||||
this.gold -= cost;
|
||||
this.towers.push(tower);
|
||||
|
|
@ -587,14 +678,14 @@
|
|||
return { ok: true, refund };
|
||||
}
|
||||
|
||||
upgradeCost(t) {
|
||||
const lv = TOWERS[t.type].levels[t.level];
|
||||
return lv ? lv.cost : null;
|
||||
}
|
||||
upgrade(id) {
|
||||
upgradeCost(t) { return upgradePrice(t.type, t.level, t.pm); }
|
||||
// `lv` is the level the sender SAW when it pressed Upgrade (absent: no check). Two players pressing it at the same moment send the
|
||||
// same command twice; the second one finds the tower already a level higher and is refused as 'stale' instead of being charged again.
|
||||
upgrade(id, lv) {
|
||||
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
||||
const t = this.towerById(id);
|
||||
if (!t) return { ok: false, reason: 'no_tower' };
|
||||
if (lv !== undefined && lv !== null && lv !== t.level) return { ok: false, reason: 'stale' };
|
||||
const cost = this.upgradeCost(t);
|
||||
if (cost === null) return { ok: false, reason: 'max' };
|
||||
if (this.gold < cost) return { ok: false, reason: 'gold' };
|
||||
|
|
@ -628,8 +719,11 @@
|
|||
return { ok: true };
|
||||
}
|
||||
|
||||
startWave() {
|
||||
// `expect` is the wave number the sender expects this command to start (the wave it saw + 1; absent: no check; the auto-wave timer
|
||||
// never passes one). A second "Next wave" pressed at the same moment by the other player is refused as 'stale', not started twice.
|
||||
startWave(expect) {
|
||||
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
||||
if (expect !== undefined && expect !== null && expect !== this.wave + 1) return { ok: false, reason: 'stale' };
|
||||
const n = ++this.wave;
|
||||
let t = this.time + 0.3;
|
||||
for (const g of waveGroups(n)) {
|
||||
|
|
@ -647,12 +741,15 @@
|
|||
const b = this.board;
|
||||
const s = b.spawns[this.spawnRR++ % b.spawns.length];
|
||||
const hp = Math.round(def.hp * hpScale(q.wave));
|
||||
const shield = def.shield ? Math.round(def.shield * hpScale(q.wave)) : 0;
|
||||
const m = {
|
||||
id: this.nid++, kind: q.k, air: !!def.air,
|
||||
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
|
||||
hp, maxhp: hp, armor: def.armor, speed: def.speed,
|
||||
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave))),
|
||||
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, rem: 0, dead: false, wave: q.wave,
|
||||
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
|
||||
shield, maxShield: shield, shieldT: 0,
|
||||
rem: 0, dead: false, wave: q.wave,
|
||||
};
|
||||
m.rem = m.air
|
||||
? Math.hypot(b.core.x - s.x, b.core.y - s.y)
|
||||
|
|
@ -672,7 +769,12 @@
|
|||
|
||||
for (const m of this.monsters) { // slow = lingering slow (Orbital Uplink) unless a Rate Limiter says more
|
||||
if (m.slowT > 0) { m.slow = m.slowAmt; m.slowT -= dt; } else m.slow = 0;
|
||||
if (m.stunT > 0) m.stunT -= dt;
|
||||
if (m.maxShield > 0) this.regenShield(m, dt);
|
||||
}
|
||||
this.healT += dt;
|
||||
if (this.healT >= HEAL_EVERY) { this.healT -= HEAL_EVERY; this.healPulse(); }
|
||||
this.updateAuras();
|
||||
for (const t of this.towers) this.updateTower(t, dt);
|
||||
this.updateBullets(dt);
|
||||
for (const m of this.monsters) if (!m.dead) this.moveMonster(m, dt);
|
||||
|
|
@ -704,6 +806,7 @@
|
|||
|
||||
// ---- monsters -------------------------------------------------------------------------
|
||||
moveMonster(m, dt) {
|
||||
if (m.stunT > 0) return; // stunned (Sandbox): frozen in place
|
||||
const b = this.board;
|
||||
const slowMul = 1 - Math.min(0.6, m.slow);
|
||||
let remaining = m.speed * slowMul * dt;
|
||||
|
|
@ -747,8 +850,13 @@
|
|||
|
||||
damage(m, raw, src, ignoreArmor) {
|
||||
if (m.dead) return;
|
||||
const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25);
|
||||
m.hp -= d;
|
||||
const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25); // armour applies once, to the damage dealt
|
||||
let hit = d;
|
||||
if (m.maxShield > 0) { // a shield soaks first, any damage restarts its regrow timer
|
||||
const soak = Math.min(m.shield, d);
|
||||
m.shield -= soak; hit = d - soak; m.shieldT = 0;
|
||||
}
|
||||
m.hp -= hit;
|
||||
if (src) src.dealt += d;
|
||||
if (m.hp <= 0) {
|
||||
m.dead = true;
|
||||
|
|
@ -759,6 +867,51 @@
|
|||
}
|
||||
}
|
||||
|
||||
// Shield: after shieldDelay s without damage it regrows shieldRegen of its maximum per second.
|
||||
regenShield(m, dt) {
|
||||
const def = ENEMIES[m.kind];
|
||||
m.shieldT += dt;
|
||||
const over = Math.min(dt, m.shieldT - def.shieldDelay);
|
||||
if (over > 0 && m.shield < m.maxShield) m.shield = Math.min(m.maxShield, m.shield + m.maxShield * def.shieldRegen * over);
|
||||
}
|
||||
|
||||
// Daemon pulse, once a second on the sim's own clock: every enemy gets healed by the daemons around it (never by itself),
|
||||
// together at most HEAL_CAP of its max hp, never above max. Shields are not healed.
|
||||
healPulse() {
|
||||
let ds = null;
|
||||
for (const m of this.monsters) if (!m.dead && ENEMIES[m.kind].heal) (ds || (ds = [])).push(m);
|
||||
if (!ds) return;
|
||||
const did = new Set();
|
||||
for (const m of this.monsters) {
|
||||
if (m.dead || m.hp >= m.maxhp) continue;
|
||||
let f = 0;
|
||||
for (const d of ds) {
|
||||
if (d === m) continue;
|
||||
const def = ENEMIES[d.kind], dx = m.x - d.x, dy = m.y - d.y;
|
||||
if (dx * dx + dy * dy > def.healRange * def.healRange) continue;
|
||||
f += def.heal; did.add(d);
|
||||
}
|
||||
if (f > 0) m.hp = Math.min(m.maxhp, m.hp + Math.min(f, HEAL_CAP) * m.maxhp);
|
||||
}
|
||||
for (const d of did) this.emit({ e: 'heal', x: round2(d.x), y: round2(d.y), r: ENEMIES[d.kind].healRange });
|
||||
}
|
||||
|
||||
// Load Balancer: each attack tower gets the best boost of the support towers in range (no stacking).
|
||||
updateAuras() {
|
||||
const ts = this.towers;
|
||||
let sup = null;
|
||||
for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support') (sup || (sup = [])).push(t); }
|
||||
if (!sup) return;
|
||||
for (const s of sup) {
|
||||
const st = TOWERS[s.type].levels[s.level - 1], r2 = st.range * st.range;
|
||||
for (const t of ts) {
|
||||
if (t.buff >= st.boost || TOWERS[t.type].role !== 'attack') continue;
|
||||
const dx = t.x - s.x, dy = t.y - s.y;
|
||||
if (dx * dx + dy * dy <= r2) t.buff = st.boost;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- towers ---------------------------------------------------------------------------
|
||||
findTarget(t, range, def) {
|
||||
const tx = t.x + 0.5, ty = t.y + 0.5, r2 = range * range;
|
||||
|
|
@ -771,7 +924,7 @@
|
|||
let v;
|
||||
switch (t.mode) {
|
||||
case 'last': v = m.rem; break;
|
||||
case 'strong': v = m.hp; break;
|
||||
case 'strong': v = m.hp + (m.shield || 0); break;
|
||||
case 'close': v = -d2; break;
|
||||
default: v = -m.rem; // 'first': smallest remaining distance wins
|
||||
}
|
||||
|
|
@ -781,11 +934,12 @@
|
|||
}
|
||||
|
||||
updateTower(t, dt) {
|
||||
if (t.type === 'wall') return;
|
||||
const def = TOWERS[t.type];
|
||||
if (def.role === 'wall' || def.role === 'support') return;
|
||||
const st = def.levels[t.level - 1];
|
||||
const cx = t.x + 0.5, cy = t.y + 0.5;
|
||||
if (t.type === 'throttle') {
|
||||
if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt); return; }
|
||||
if (def.role === 'aura') {
|
||||
const r2 = st.range * st.range;
|
||||
for (const m of this.monsters) {
|
||||
if (m.dead) continue;
|
||||
|
|
@ -796,7 +950,7 @@
|
|||
}
|
||||
return;
|
||||
}
|
||||
t.cd -= dt;
|
||||
t.cd -= dt * (1 + (t.buff || 0)); // a Load Balancer makes cooldowns elapse faster
|
||||
const m = this.findTarget(t, st.range, def);
|
||||
t.tgt = m ? m.id : 0;
|
||||
if (!m) { if (t.cd < 0) t.cd = 0; return; }
|
||||
|
|
@ -805,6 +959,27 @@
|
|||
this.fire(t, st, def, m, cx, cy);
|
||||
}
|
||||
|
||||
// Sandbox: when anything is in range it stuns everything in range (ground and air) for st.stun s, then recharges st.pulse s.
|
||||
// Enemies with slowRes (bosses) are stunned for (1 - slowRes) of that. Stunned enemies do not move.
|
||||
pulseStun(t, st, def, cx, cy, dt) {
|
||||
t.cd -= dt;
|
||||
t.tgt = 0;
|
||||
const r2 = st.range * st.range, hit = [];
|
||||
for (const m of this.monsters) {
|
||||
if (m.dead || (m.air ? !def.air : !def.ground)) continue;
|
||||
const dx = m.x - cx, dy = m.y - cy;
|
||||
if (dx * dx + dy * dy <= r2) hit.push(m);
|
||||
}
|
||||
if (!hit.length) { if (t.cd < 0) t.cd = 0; return; }
|
||||
if (t.cd > 0) return;
|
||||
t.cd += st.pulse;
|
||||
for (const m of hit) {
|
||||
const dur = st.stun * (1 - (ENEMIES[m.kind].slowRes || 0));
|
||||
if (dur > m.stunT) m.stunT = dur;
|
||||
}
|
||||
this.emit({ e: 'stun', x: round2(cx), y: round2(cy), r: st.range, n: hit.length });
|
||||
}
|
||||
|
||||
fire(t, st, def, m, cx, cy) {
|
||||
switch (t.type) {
|
||||
case 'filter':
|
||||
|
|
@ -819,7 +994,7 @@
|
|||
let gx = m.x, gy = m.y;
|
||||
if (m.tx >= 0) { // lead the target along its current step
|
||||
const ex = m.tx + 0.5 - m.x, ey = m.ty + 0.5 - m.y, el = Math.hypot(ex, ey) || 1;
|
||||
const T = Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed;
|
||||
const T = Math.max(0, Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed - (m.stunT > 0 ? m.stunT : 0));
|
||||
const lead = Math.min(el, m.speed * (1 - Math.min(0.6, m.slow)) * T);
|
||||
gx += (ex / el) * lead; gy += (ey / el) * lead;
|
||||
}
|
||||
|
|
@ -910,7 +1085,7 @@
|
|||
|
||||
// ---- views of the state ---------------------------------------------------------------
|
||||
towerList() {
|
||||
return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner]);
|
||||
return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner, t.pm === 1 ? 1 : round2(t.pm * 1000) / 1000]);
|
||||
}
|
||||
|
||||
// Everything a client needs to (re)build the board from scratch.
|
||||
|
|
@ -924,7 +1099,8 @@
|
|||
|
||||
// Compact per-tick state for the wire. Arrays, not objects, to keep it small.
|
||||
snapshot() {
|
||||
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp), m.maxhp, m.slow > 0 ? 1 : 0]);
|
||||
// a shield is sent as extra hp: hp + shield out of maxhp + maxShield (the client derives the shield part from the kind's table)
|
||||
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp + (m.shield || 0)), m.maxhp + (m.maxShield || 0), m.slow > 0 || m.stunT > 0 ? 1 : 0]);
|
||||
const bu = this.bullets.map((b) => [b.id, b.k === 'mortar' ? 1 : 0, round2(b.x), round2(b.y)]);
|
||||
const tt = [];
|
||||
for (const t of this.towers) if (t.type !== 'wall') tt.push([t.id, t.tgt, t.kills]);
|
||||
|
|
@ -940,9 +1116,9 @@
|
|||
function round2(v) { return Math.round(v * 100) / 100; }
|
||||
|
||||
return {
|
||||
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE,
|
||||
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP,
|
||||
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
|
||||
waveGroups, waveSummary, hpScale, rewardScale,
|
||||
priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale,
|
||||
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
|
||||
};
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue