feat: create a large randomized library of playful game sounds and audio combos
This commit is contained in:
+11
-8
@@ -21,6 +21,7 @@
|
||||
setEnabled: async () => false, setVolume: () => {}, setReduced: () => {}, play: () => false, setPageHidden: () => {}, cleanup: () => {}
|
||||
};
|
||||
const audio = globalThis.BattleshipAudio?.createAudioEngine?.() || silentAudio;
|
||||
const sounds = globalThis.BattleshipSounds?.createSoundDirector?.({ engine: audio }) || { play: () => false, reset: () => {} };
|
||||
let token = localStorage.getItem(storage.token) || '';
|
||||
let role = '';
|
||||
let info;
|
||||
@@ -176,7 +177,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
function showFeedback(event) {
|
||||
function showFeedback(event, version, summary = false) {
|
||||
const content = pickReaction(event?.type);
|
||||
if (!content) return;
|
||||
let { motion, burst } = content;
|
||||
@@ -195,6 +196,7 @@
|
||||
void document.body.offsetWidth;
|
||||
document.body.classList.add(kind === 'damage' ? 'fx-damage' : 'fx-hit');
|
||||
if (navigator.vibrate) navigator.vibrate(vibration);
|
||||
sounds.play(event.type, { version, combo: hitStreak, reduced: audio.getPreferences().reduced, summary });
|
||||
effectTimer = window.setTimeout(() => {
|
||||
ui.effects.hidden = true; document.body.classList.remove('fx-hit', 'fx-damage');
|
||||
}, kind === 'victory' ? 2200 : combo ? 1800 : 1350);
|
||||
@@ -218,7 +220,7 @@
|
||||
clearRecoveryTimers();
|
||||
if (socket) { socket.onclose = null; socket.close(); socket = undefined; }
|
||||
selectedTarget = undefined; firePending = false; cumulativeStatistics = undefined; statisticsGameId = undefined;
|
||||
activeBoard = 'own'; hitStreak = 0; state = undefined; role = ''; info = undefined; targetActivator = undefined; audio.cleanup();
|
||||
activeBoard = 'own'; hitStreak = 0; state = undefined; role = ''; info = undefined; targetActivator = undefined; sounds.reset(); audio.cleanup();
|
||||
document.body.classList.remove('fx-hit', 'fx-damage'); ui.effects.hidden = true; notify('');
|
||||
const soundKeys = new Set(['battleship.soundEnabled', 'battleship.soundVolume', 'battleship.soundReduced']);
|
||||
Object.keys(localStorage).filter(key => key.startsWith('battleship.') && !soundKeys.has(key)).forEach(key => localStorage.removeItem(key));
|
||||
@@ -246,7 +248,7 @@
|
||||
}
|
||||
|
||||
function openRecovery() {
|
||||
if (!token) return; recoveryOpener = document.activeElement; ui.recoveryDialog.hidden = false; ui.recoveryButton.setAttribute('aria-expanded', 'true');
|
||||
if (!token) return; sounds.play('recovery-open', { reduced: audio.getPreferences().reduced }); recoveryOpener = document.activeElement; ui.recoveryDialog.hidden = false; ui.recoveryButton.setAttribute('aria-expanded', 'true');
|
||||
ui.recoveryChoices.hidden = false; ui.recoveryConfirmation.hidden = true; ui.recoveryGlobal.hidden = !isPlayer(); ui.recoveryClose.focus();
|
||||
}
|
||||
|
||||
@@ -263,7 +265,7 @@
|
||||
if (action === 'leave') await request('/api/session/leave', { method: 'POST', headers: headers(), body: JSON.stringify({ token, gameId: state?.gameId || 0 }) });
|
||||
else if (action === 'profile') await request('/api/session/profile-reset', { method: 'POST', headers: headers(), body: JSON.stringify({ token, gameId: state?.gameId || 0 }) });
|
||||
else await request('/api/game/reset', { method: 'POST', headers: headers(), body: JSON.stringify({ token, gameId: state?.gameId || 0 }) });
|
||||
clearLocalProfile(action !== 'leave');
|
||||
sounds.play(`recovery-${action}`, { reduced: audio.getPreferences().reduced }); clearLocalProfile(action !== 'leave');
|
||||
} catch (error) { recoveryPending = false; ui.recoveryConfirm.disabled = false; ui.recoveryLive.textContent = 'Не получилось. Можно повторить или отменить.'; notify(error.message, true); }
|
||||
}
|
||||
|
||||
@@ -373,7 +375,7 @@
|
||||
selectedTarget = selectedTarget && payload.boards[opponentIndex()][selectedTarget.y * 10 + selectedTarget.x] === '0' ? selectedTarget : undefined;
|
||||
document.title = `Морской бой — версия ${payload.version}`;
|
||||
render();
|
||||
showFeedback(globalThis.BattleshipTargetInteraction.detectFeedback(previousState, payload, role));
|
||||
showFeedback(globalThis.BattleshipTargetInteraction.detectFeedback(previousState, payload, role), payload.version, hadGap);
|
||||
}
|
||||
|
||||
function isPlayer() { return role === 'player1' || role === 'player2'; }
|
||||
@@ -401,6 +403,7 @@
|
||||
renderGame();
|
||||
try {
|
||||
await post('/api/game/shot', { token, gameId: state.gameId, ...target });
|
||||
sounds.play('shot', { reduced: audio.getPreferences().reduced });
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
@@ -414,7 +417,7 @@
|
||||
if (!targetActivator) {
|
||||
targetActivator = globalThis.BattleshipTargetInteraction.createTargetActivator({
|
||||
canFire: canFireTarget,
|
||||
select: nextTarget => { selectedTarget = nextTarget; renderGame(); },
|
||||
select: nextTarget => { selectedTarget = nextTarget; sounds.play('select', { reduced: audio.getPreferences().reduced }); renderGame(); },
|
||||
fire: fireTarget,
|
||||
});
|
||||
}
|
||||
@@ -710,7 +713,7 @@
|
||||
ui.fire.addEventListener('click', () => { if (selectedTarget) fireTarget(selectedTarget); });
|
||||
ui.cancel.addEventListener('click', () => { selectedTarget = undefined; renderGame(); });
|
||||
ui.abort.addEventListener('click', () => post('/api/game/abort', { token, gameId: state.gameId }));
|
||||
ui.rematch.addEventListener('click', () => post('/api/game/rematch', { token, gameId: state.gameId }));
|
||||
ui.rematch.addEventListener('click', () => { post('/api/game/rematch', { token, gameId: state.gameId }).then(() => sounds.play('rematch', { reduced: audio.getPreferences().reduced })).catch(() => {}); });
|
||||
el('retry-button').addEventListener('click', () => { refreshInfo(); pollState(); connectSocket(); });
|
||||
ui.recoveryButton.addEventListener('click', openRecovery);
|
||||
ui.soundToggle.addEventListener('click', async () => {
|
||||
@@ -723,7 +726,7 @@
|
||||
ui.soundReduced.addEventListener('change', () => { audio.setReduced(ui.soundReduced.checked); syncSoundControls(); });
|
||||
ui.recoverySoundMute.addEventListener('click', async () => { await audio.setEnabled(false); syncSoundControls(); });
|
||||
ui.recoveryClose.addEventListener('click', closeRecovery);
|
||||
ui.recoveryCancel.addEventListener('click', () => { recoveryAction = undefined; ui.recoveryConfirmation.hidden = true; ui.recoveryChoices.hidden = false; ui.recoveryClose.focus(); });
|
||||
ui.recoveryCancel.addEventListener('click', () => { sounds.play('recovery-cancel', { reduced: audio.getPreferences().reduced }); recoveryAction = undefined; ui.recoveryConfirmation.hidden = true; ui.recoveryChoices.hidden = false; ui.recoveryClose.focus(); });
|
||||
ui.recoveryChoices.addEventListener('click', event => {
|
||||
const choice = event.target.closest('[data-recovery-action]');
|
||||
if (choice && !choice.hidden) showRecoveryConfirmation(choice.dataset.recoveryAction);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
(() => {
|
||||
const COUNTS = Object.freeze({ select: 4, shot: 8, miss: 10, hit: 10, sunk: 8, dodged: 6, damage: 6, turn: 6, waiting: 4, start: 6, victory: 8, defeat: 5, recovery: 5 });
|
||||
const PRIORITY = Object.freeze({ waiting: 0, select: 0, recovery: 1, shot: 2, turn: 3, miss: 4, dodged: 4, damage: 5, hit: 5, sunk: 6, start: 6, defeat: 7, victory: 8, summary: 8 });
|
||||
const BASE = Object.freeze({ select: [540, 100], shot: [190, 220], miss: [410, 260], hit: [155, 280], sunk: [120, 720], dodged: [460, 190], damage: [135, 260], turn: [620, 160], waiting: [350, 120], start: [250, 460], victory: [330, 850], defeat: [310, 430], recovery: [480, 150] });
|
||||
|
||||
function presetsFor(family, count) {
|
||||
const [frequency, durationMs] = BASE[family];
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
id: `${family}-${index + 1}`, family, priority: PRIORITY[family], frequency: Math.max(100, frequency + ((index * 67) % 240) - 90),
|
||||
endFrequency: Math.max(100, frequency + ((index * 43) % 180) - 70), durationMs: Math.min(900, durationMs + (index % 4) * 35),
|
||||
filterHz: 900 + (index * 347) % 2600, gain: family === 'select' || family === 'waiting' ? 0.18 : family === 'recovery' ? 0.14 : 0.7,
|
||||
wave: ['sine', 'triangle', 'square', 'sawtooth'][index % 4], noise: ['miss', 'hit', 'sunk', 'damage', 'dodged'].includes(family) && index % 3 === 1,
|
||||
pan: ((index % 5) - 2) * 0.18, delayMs: index % 3 === 2 ? 28 : 0
|
||||
}));
|
||||
}
|
||||
const CATALOG = Object.freeze(Object.fromEntries(Object.entries(COUNTS).map(([family, count]) => [family, presetsFor(family, count)])));
|
||||
const EVENT_FAMILY = Object.freeze({ 'watch-miss': 'miss', 'watch-hit': 'hit', 'watch-sunk': 'sunk', 'sunk-damage': 'damage', finish: 'victory', rematch: 'defeat', summary: 'victory', 'recovery-open': 'recovery', 'recovery-cancel': 'recovery', 'recovery-leave': 'recovery', 'recovery-profile': 'recovery', 'recovery-game': 'recovery' });
|
||||
const RECOVERY_PRESET = Object.freeze({ 'recovery-open': 0, 'recovery-cancel': 1, 'recovery-leave': 2, 'recovery-profile': 3, 'recovery-game': 4 });
|
||||
|
||||
function createSoundDirector({ engine, random = Math.random, now = () => Date.now(), historyLimit = 3, waitingIntervalMs = 12000 } = {}) {
|
||||
const history = new Map();
|
||||
let lastVersion = -1; let lastWaitingMs = -waitingIntervalMs;
|
||||
function select(family) {
|
||||
const presets = CATALOG[family] || [];
|
||||
if (!presets.length) return undefined;
|
||||
const previous = history.get(family) || [];
|
||||
const options = presets.filter(preset => !previous.includes(preset.id));
|
||||
const pool = options.length ? options : presets.filter(preset => preset.id !== previous.at(-1));
|
||||
const preset = pool[Math.min(pool.length - 1, Math.max(0, Math.floor(random() * pool.length)))];
|
||||
history.set(family, [...previous, preset.id].slice(-historyLimit));
|
||||
return preset;
|
||||
}
|
||||
function play(event, { version, combo = 0, reduced = false, summary = false } = {}) {
|
||||
if (Number.isInteger(version)) { if (version <= lastVersion) return false; lastVersion = version; }
|
||||
let family = summary ? 'summary' : EVENT_FAMILY[event] || event;
|
||||
if (family === 'summary') family = 'victory';
|
||||
if (!CATALOG[family]) return false;
|
||||
if (family === 'waiting') { if (reduced || now() - lastWaitingMs < waitingIntervalMs) return false; lastWaitingMs = now(); }
|
||||
const forcedPreset = RECOVERY_PRESET[event];
|
||||
const preset = forcedPreset === undefined ? select(family) : CATALOG.recovery[forcedPreset];
|
||||
if (!preset) return false;
|
||||
const played = engine?.playPreset?.(preset);
|
||||
if (!played) return false;
|
||||
if (!reduced && (event === 'hit' || event === 'sunk') && combo >= 2) {
|
||||
const comboPreset = { ...select(combo >= 4 ? 'victory' : combo === 3 ? 'turn' : 'hit'), id: `combo-${combo}`, priority: PRIORITY.sunk, gain: 0.12, durationMs: combo >= 4 ? 380 : 160, delayMs: 55 };
|
||||
engine.playPreset(comboPreset);
|
||||
}
|
||||
return { preset, combo: combo >= 4 ? 'ultra' : combo === 3 ? 'mega' : combo === 2 ? 'combo' : undefined };
|
||||
}
|
||||
return { play, select, getCatalog: () => CATALOG, getHistory: family => [...(history.get(family) || [])], reset: () => { history.clear(); lastVersion = -1; lastWaitingMs = -waitingIntervalMs; }, getPriority: event => PRIORITY[EVENT_FAMILY[event] || event] || 0 };
|
||||
}
|
||||
const api = { createSoundDirector, CATALOG, COUNTS, PRIORITY };
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
||||
else globalThis.BattleshipSounds = api;
|
||||
})();
|
||||
@@ -77,6 +77,7 @@
|
||||
<div id="recovery-dialog" class="recovery-overlay" role="dialog" aria-modal="true" aria-labelledby="recovery-title" hidden><section class="recovery-dialog"><button id="recovery-close" class="text-button recovery-close" type="button" aria-label="Закрыть меню">×</button><h2 id="recovery-title">Помощь с игрой</h2><p id="recovery-description" class="muted">Выберите, что нужно сделать.</p><button id="recovery-sound-mute" type="button" class="secondary recovery-sound-mute" hidden>Выключить звук</button><div id="recovery-choices" class="recovery-choices"><button type="button" data-recovery-action="leave"><svg class="ui-icon" aria-hidden="true"><use href="/ship-sprite.svg#icon-person"></use></svg><span><strong>Выйти из игры</strong><small>Имя останется на этом устройстве.</small></span></button><button type="button" data-recovery-action="profile"><svg class="ui-icon" aria-hidden="true"><use href="/ship-sprite.svg#icon-person"></use></svg><span><strong>Сбросить мой профиль</strong><small>Очистить имя и данные этого устройства.</small></span></button><button id="recovery-global-choice" type="button" data-recovery-action="game" class="recovery-global"><svg class="ui-icon" aria-hidden="true"><use href="/ship-sprite.svg#icon-players"></use></svg><span><strong>Сбросить всю игру</strong><small>Вернуть всех к началу.</small></span></button></div><div id="recovery-confirmation" class="recovery-confirmation" hidden><span id="recovery-scope-icon" class="recovery-scope-icon" aria-hidden="true"></span><h3 id="recovery-confirm-title"></h3><p id="recovery-confirm-text"></p><p id="recovery-hold-note" class="muted" hidden>Удерживайте кнопку 2 секунды.</p><div class="recovery-confirm-actions"><button id="recovery-cancel" type="button" class="secondary">Отмена</button><button id="recovery-confirm" type="button" class="recovery-confirm"><span id="recovery-confirm-label"></span><span id="recovery-hold-progress" class="recovery-hold-progress" aria-hidden="true"></span></button></div></div><p id="recovery-live" class="sr-only" aria-live="polite"></p></section></div>
|
||||
<script src="/target_interaction.js" defer></script>
|
||||
<script src="/web_audio.js" defer></script>
|
||||
<script src="/game_sounds.js" defer></script>
|
||||
<script src="/app.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+23
-10
@@ -51,20 +51,22 @@
|
||||
if (!voices.delete(voice)) return;
|
||||
timer.clearTimeout(voice.timeout);
|
||||
try { voice.source.stop(); } catch (_) { /* It may have ended naturally. */ }
|
||||
disconnect(voice.source); disconnect(voice.filter); disconnect(voice.gain);
|
||||
disconnect(voice.source); disconnect(voice.filter); disconnect(voice.gain); disconnect(voice.panner);
|
||||
}
|
||||
function makeVoice(priority, durationMs, sourceFactory) {
|
||||
function makeVoice(priority, durationMs, sourceFactory, settings = {}) {
|
||||
if (!preferences.enabled || hidden || !ensureContext() || voices.size >= MAX_VOICES && !replaceVoice(priority)) return false;
|
||||
const startedAt = context.currentTime;
|
||||
const startedAt = context.currentTime + Math.max(0, settings.delayMs || 0) / 1000;
|
||||
const duration = Math.max(0.1, Math.min(durationMs, 2500) / 1000) * (preferences.reduced ? 0.65 : 1);
|
||||
let source; let gain; let filter;
|
||||
let source; let gain; let filter; let panner;
|
||||
try {
|
||||
source = sourceFactory(); gain = context.createGain(); filter = context.createBiquadFilter();
|
||||
filter.type = 'lowpass'; filter.frequency.setValueAtTime(2400, startedAt);
|
||||
gain.gain.setValueAtTime(0.0001, startedAt); gain.gain.exponentialRampToValueAtTime(0.23, startedAt + 0.012); gain.gain.exponentialRampToValueAtTime(0.0001, startedAt + duration);
|
||||
source.connect(filter); filter.connect(gain); gain.connect(master); source.start(startedAt); source.stop(startedAt + duration + 0.02);
|
||||
} catch (_) { disconnect(source); disconnect(filter); disconnect(gain); return false; }
|
||||
const voice = { source, filter, gain, priority, timeout: undefined };
|
||||
filter.type = 'lowpass'; filter.frequency.setValueAtTime(settings.filterHz || 2400, startedAt);
|
||||
const peak = Math.min(0.75, Math.max(0.04, settings.gain || 0.55));
|
||||
gain.gain.setValueAtTime(0.0001, startedAt); gain.gain.exponentialRampToValueAtTime(peak, startedAt + 0.012); gain.gain.exponentialRampToValueAtTime(0.0001, startedAt + duration);
|
||||
if (typeof context.createStereoPanner === 'function') { panner = context.createStereoPanner(); panner.pan.setValueAtTime(Math.max(-0.4, Math.min(0.4, settings.pan || 0)), startedAt); }
|
||||
source.connect(filter); filter.connect(gain); if (panner) { gain.connect(panner); panner.connect(master); } else gain.connect(master); source.start(startedAt); source.stop(startedAt + duration + 0.02);
|
||||
} catch (_) { disconnect(source); disconnect(filter); disconnect(gain); disconnect(panner); return false; }
|
||||
const voice = { source, filter, gain, panner, priority, timeout: undefined };
|
||||
voice.timeout = timer.setTimeout(() => release(voice), Math.ceil(duration * 1000) + 80);
|
||||
voices.add(voice); return true;
|
||||
}
|
||||
@@ -92,13 +94,24 @@
|
||||
const oscillator = context.createOscillator(); oscillator.type = kind === 'major' ? 'triangle' : 'sine'; oscillator.frequency.setValueAtTime(kind === 'major' ? 392 : 660, context.currentTime); oscillator.frequency.exponentialRampToValueAtTime(kind === 'major' ? 196 : 440, context.currentTime + 0.16); return oscillator;
|
||||
});
|
||||
}
|
||||
function playPreset(preset) {
|
||||
if (!preset || !preferences.enabled || hidden || !ensureContext()) return false;
|
||||
return makeVoice(preset.priority || 1, preset.durationMs || 180, () => {
|
||||
if (preset.noise) { const source = context.createBufferSource(); source.buffer = ensureNoise(); return source; }
|
||||
const oscillator = context.createOscillator(); oscillator.type = preset.wave || 'sine';
|
||||
const startedAt = context.currentTime + Math.max(0, preset.delayMs || 0) / 1000;
|
||||
oscillator.frequency.setValueAtTime(Math.max(100, preset.frequency || 440), startedAt);
|
||||
oscillator.frequency.exponentialRampToValueAtTime(Math.max(100, preset.endFrequency || preset.frequency || 440), startedAt + Math.min(0.8, (preset.durationMs || 180) / 1000));
|
||||
return oscillator;
|
||||
}, preset);
|
||||
}
|
||||
async function setPageHidden(nextHidden) {
|
||||
hidden = Boolean(nextHidden); cancel();
|
||||
if (!context) return;
|
||||
try { if (hidden) await context.suspend(); else if (preferences.enabled && context.state === 'suspended') await context.resume(); } catch (_) { /* Sound remains optional. */ }
|
||||
}
|
||||
function cleanup() { cancel(); lastVersion = -1; if (context) { try { context.close(); } catch (_) { /* Already closed. */ } } context = undefined; master = undefined; limiter = undefined; noiseBuffer = undefined; }
|
||||
return { getPreferences: () => ({ ...preferences }), enable, setEnabled, setVolume: volume => { preferences.volume = validVolume(volume); save(); updateGain(); }, setReduced: reduced => { preferences.reduced = Boolean(reduced); save(); }, play, cancel, setPageHidden, cleanup, getVoiceCount: () => voices.size, getNoiseBuffer: () => noiseBuffer, getMaxGain: () => MAX_GAIN, now };
|
||||
return { getPreferences: () => ({ ...preferences }), enable, setEnabled, setVolume: volume => { preferences.volume = validVolume(volume); save(); updateGain(); }, setReduced: reduced => { preferences.reduced = Boolean(reduced); save(); }, play, playPreset, cancel, setPageHidden, cleanup, getVoiceCount: () => voices.size, getNoiseBuffer: () => noiseBuffer, getMaxGain: () => MAX_GAIN, now };
|
||||
}
|
||||
|
||||
const api = { createAudioEngine, MAX_VOICES, MAX_GAIN, VOLUME_GAINS, PREFERENCES };
|
||||
|
||||
Reference in New Issue
Block a user