/* game-sfx.js v0.2.0 — semantic sound effects for the games (cards, dice, board pieces, UI, jingles). * * * GameSfx.play('cardPlace'); // by meaning, not by file * GameSfx.play('diceThrow', { volume: 0.6, rate: 1.1 }); * GameSfx.preload(['cardPlace', 'deal', 'win']); // optional: decode ahead of time * GameSfx.muted / GameSfx.mute(true) / GameSfx.toggle() // remembered across games (localStorage) * * Names and their files come from public/assets/sfx.json (generated by tools/assets/build.py). Each name * has several variants; one is chosen at random, never the same twice in a row, with a little pitch * variation so repeated sounds do not sound mechanical. play() never throws and never blocks the game: * if audio is unavailable or a file fails to load it silently does nothing. * * Every sound starts at its first audible sample (leading silence under -50 dBFS is skipped, up to 0.25 s). * * A small speaker button (bottom-right) mutes everything; call GameSfx.hideButton() to remove it. * Paths are built at runtime (never a bare quoted directory) so crawlers do not mistake them for pages. */ (function (global) { 'use strict'; const BASE = ['', 'assets', ''].join('/'); const KEY = 'zuujis.sfx.muted'; let map = null, loading = null, ac = null, master = null, btn = null; const buffers = {}, lastPlay = {}, lastPick = {}; let muted = false; try { muted = localStorage.getItem(KEY) === '1'; } catch (_) {} function audio() { if (!ac) { const AC = global.AudioContext || global.webkitAudioContext; if (!AC) return null; try { ac = new AC(); master = ac.createGain(); master.gain.value = 0.9; master.connect(ac.destination); } catch (_) { ac = null; return null; } } if (ac.state === 'suspended') ac.resume().catch(() => {}); return ac; } ['pointerdown', 'keydown', 'touchstart'].forEach(ev => global.addEventListener(ev, () => { audio(); }, { passive: true })); const enc = p => p.split('/').map(encodeURIComponent).join('/'); function loadMap() { if (!loading) { loading = fetch(BASE + 'sfx.json').then(r => r.ok ? r.json() : Promise.reject(r.status)) .then(j => { map = j; return j; }) .catch(() => { map = { sounds: {}, gain: {}, rate: {} }; return map; }); } return loading; } function buffer(path) { if (!buffers[path]) { buffers[path] = fetch(BASE + enc(path)).then(r => r.ok ? r.arrayBuffer() : Promise.reject(r.status)) .then(b => new Promise((res, rej) => { const c = audio(); c ? c.decodeAudioData(b, res, rej) : rej(new Error('no audio')); })) .catch(() => null); } return buffers[path]; } // Seconds of near-silence (under -50 dBFS) a sound starts with, less 3 ms, at most 0.25 s: played from there, so a // file that begins late (many Kenney "digital" sounds wait 60-170 ms) still sounds the moment the game asks for it. function leadOf(buf) { if (buf._lead != null) return buf._lead; const t = 0.00316, max = Math.floor(buf.sampleRate * 0.25); let first = max; for (let ch = 0; ch < buf.numberOfChannels; ch++) { const d = buf.getChannelData(ch), n = Math.min(d.length, first); for (let i = 0; i < n; i++) if (d[i] > t || d[i] < -t) { first = i; break; } } return (buf._lead = first >= max ? 0 : Math.max(0, first / buf.sampleRate - 0.003)); } async function play(name, o) { try { if (muted) return null; o = o || {}; const c = audio(); if (!c) return null; const now = (global.performance || Date).now(); if (lastPlay[name] && now - lastPlay[name] < 35) return null; // ignore accidental double-fires lastPlay[name] = now; const m = map || await loadMap(); const list = m.sounds && m.sounds[name]; if (!list || !list.length) return null; let i = Math.floor(Math.random() * list.length); if (list.length > 1 && i === lastPick[name]) i = (i + 1) % list.length; lastPick[name] = i; const buf = await buffer(list[i]); if (!buf || muted) return null; const src = c.createBufferSource(), g = c.createGain(); const base = o.rate != null ? o.rate : (m.rate && m.rate[name]) || 1; src.buffer = buf; src.playbackRate.value = base * (0.97 + Math.random() * 0.06); g.gain.value = ((m.gain && m.gain[name]) != null ? m.gain[name] : 1) * (o.volume != null ? o.volume : 1); src.connect(g); g.connect(master); src.start(0, leadOf(buf)); return src; } catch (_) { return null; } } async function preload(names) { try { const m = map || await loadMap(); await Promise.all((names || Object.keys(m.sounds)).flatMap(n => (m.sounds[n] || []).map(buffer))); } catch (_) {} } function paintButton() { if (btn) { btn.textContent = muted ? '🔇' : '🔊'; btn.title = muted ? 'Sound off (click to turn on)' : 'Sound on (click to mute)'; btn.setAttribute('aria-label', btn.title); } } function mute(v) { muted = !!v; try { localStorage.setItem(KEY, muted ? '1' : '0'); } catch (_) {} paintButton(); if (!muted) { audio(); play('toggle'); } } function showButton() { if (btn || !global.document || !document.body) return; btn = document.createElement('button'); btn.type = 'button'; btn.id = 'gsfx-btn'; btn.style.cssText = 'position:fixed;right:10px;bottom:10px;z-index:2147483000;width:34px;height:34px;padding:0;border:1px solid rgba(255,255,255,.18);border-radius:50%;background:rgba(0,0,0,.45);color:#fff;font:16px/1 system-ui,sans-serif;cursor:pointer;opacity:.55;transition:opacity .2s;-webkit-tap-highlight-color:transparent'; btn.onmouseenter = () => { btn.style.opacity = '1'; }; btn.onmouseleave = () => { btn.style.opacity = '.55'; }; btn.addEventListener('click', e => { e.stopPropagation(); mute(!muted); btn.blur(); }); // give the keyboard back to the game btn.addEventListener('keydown', e => { e.stopPropagation(); }); // Space/Enter on the button must not reach the game btn.addEventListener('pointerdown', e => { e.stopPropagation(); }); // nor a click on it start a move document.body.appendChild(btn); paintButton(); } function hideButton() { if (btn) { btn.remove(); btn = null; } } if (global.document) { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', showButton); else showButton(); } global.GameSfx = { play, preload, mute, hideButton, showButton, audio, toggle() { mute(!muted); }, get muted() { return muted; }, }; })(window);