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
|
|
@ -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);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue