Improve game audio and add battle and casualty sounds

This commit is contained in:
coyotte508 2026-10-14 22:05:56 +02:00
commit 8c0a5ed559
9 changed files with 145 additions and 10 deletions

View file

@ -349,3 +349,5 @@ Viewer 0.1.114 / engine 0.4.83 corrects E17 (A Splendid Year) to grant its state
Viewer 0.1.115 / engine 0.4.84 separates the natural influence die roll from advance bonuses in journal messages, for example “rolls a 2 (+1 bonus = 3)”, including success and failure outcomes.
Viewer 0.1.116 / engine 0.4.85 shortens influence roll bonuses to “rolls a 2 (+1)”.
Viewer 0.1.117 makes hover more audible, sustains action sounds longer, and adds battle-roll, unit-loss and ship-sinking cues. Action sounds wait for browser audio to resume and respect mute cancellation. Adds a local-only sound tester. Engine remains 0.4.85.

View file

@ -99,6 +99,7 @@
<option value="spectator">Spectator</option></select
><button id="reset">New game</button><button id="theme">Theme</button
>
<a href="/sounds.html" target="_blank" rel="noopener">Test sounds</a>
<span id="status">Connecting to local game…</span>
</div>
<div id="host-error" role="alert"></div>

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.116",
"version": "0.1.117",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.116",
"version": "0.1.117",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.116",
"version": "0.1.117",
"private": true,
"type": "module",
"scripts": {

29
web-client/sounds.html Normal file
View file

@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Clash · Sound preview</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; background: #192e39; color: #edf4f4; font: 16px system-ui; }
main { max-width: 800px; margin: 60px auto; padding: 24px; }
h1 { font-weight: 500; }
p { color: #b6c9d1; line-height: 1.6; }
#sounds { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; margin-top: 28px; }
button { text-align: left; background: #254450; color: inherit; border: 1px solid #51717b; border-radius: 8px; padding: 20px; cursor: pointer; font: inherit; }
button:hover, button:focus-visible { background: #30616b; outline: 2px solid #c8b77f; }
button span { display: block; color: #b6c9d1; font-size: 13px; margin-top: 8px; }
#status { min-height: 24px; margin-top: 24px; }
</style>
</head>
<body>
<main>
<h1>Sound preview</h1>
<p>Click a sound to hear it at the game’s current volume. These use the same audio as the game. Hover is softer than action sounds.</p>
<div id="sounds"></div>
<p id="status" role="status">Choose a sound to play.</p>
</main>
<script type="module" src="/src/sound-preview.ts"></script>
</body>
</html>

View file

@ -1,7 +1,7 @@
import type { Move } from './types.ts';
export type SoundCue =
'hover' | 'select' | 'collect' | 'build' | 'research' | 'draw' | 'move' | 'confirm' | 'undo' | 'error';
'hover' | 'select' | 'collect' | 'build' | 'research' | 'draw' | 'move' | 'confirm' | 'undo' | 'error' | 'battle' | 'casualty' | 'sink';
// Keep action cues audible without making repeated map hovers intrusive.
const MASTER_GAIN = 0.4;
const notes: Record<SoundCue, number[]> = {
@ -15,6 +15,9 @@ const notes: Record<SoundCue, number[]> = {
confirm: [392, 494],
undo: [330, 220],
error: [180, 160],
battle: [110, 165, 110, 220],
casualty: [294, 196, 98],
sink: [220, 165, 110, 55],
};
export function moveSound(move: Move | null): SoundCue {
@ -37,6 +40,7 @@ export class GameAudio {
private enabled = false;
private disposed = false;
private lastHover = -Infinity;
private soundGeneration = 0;
private createContext: () => AudioContext;
constructor(createContext: () => AudioContext = () => new AudioContext()) {
this.createContext = createContext;
@ -70,29 +74,44 @@ export class GameAudio {
this.disposed ||
!context ||
!this.volume ||
context.state !== 'running' ||
(typeof document !== 'undefined' && document.hidden)
)
return;
if (this.voices.size >= 12) return;
if (context.state === 'suspended') {
if (cue !== 'hover') {
const generation = this.soundGeneration;
void context.resume().then(() => {
if (context.state === 'running' && generation === this.soundGeneration) this.play(cue);
}).catch(() => {});
}
return;
}
if (context.state !== 'running') return;
if (this.voices.size >= 12) {
if (cue === 'hover') return;
this.stop();
}
if (cue === 'hover') {
if (context.currentTime - this.lastHover < 0.09) return;
this.lastHover = context.currentTime;
}
const duration =
cue === 'hover' ? 0.025 : cue === 'select' ? 0.075 : cue === 'research' || cue === 'draw' ? 0.24 : 0.18;
cue === 'hover' ? 0.055 : cue === 'select' ? 0.075 : cue === 'sink' ? 0.32 : cue === 'casualty' ? 0.22 : cue === 'research' || cue === 'draw' ? 0.24 : 0.18;
notes[cue].forEach((frequency, index) => {
const start = context.currentTime + index * (cue === 'research' ? 0.075 : 0.055);
const oscillator = context.createOscillator();
const gain = context.createGain();
oscillator.type = cue === 'build' || cue === 'move' ? 'triangle' : 'sine';
oscillator.type = ['build', 'move', 'battle', 'casualty', 'sink'].includes(cue) ? 'triangle' : 'sine';
oscillator.frequency.setValueAtTime(frequency, start);
oscillator.frequency.exponentialRampToValueAtTime(frequency * 0.96, start + duration);
oscillator.frequency.exponentialRampToValueAtTime(frequency * (cue === 'sink' ? 0.4 : cue === 'casualty' ? 0.65 : 0.96), start + duration);
gain.gain.setValueAtTime(0, start);
gain.gain.linearRampToValueAtTime(
cue === 'hover' ? 0.025 : cue === 'select' ? 0.25 : 0.4,
cue === 'hover' ? 0.18 : cue === 'select' ? 0.25 : 0.4,
start + 0.006,
);
if (cue !== 'hover') {
gain.gain.setValueAtTime(cue === 'select' ? 0.25 : 0.4, start + duration * 0.35);
}
gain.gain.exponentialRampToValueAtTime(0.001, start + duration);
oscillator.connect(gain);
gain.connect(this.volume!);
@ -108,6 +127,7 @@ export class GameAudio {
}
private stop() {
this.soundGeneration++;
for (const [oscillator, gain] of this.voices) {
oscillator.stop();
oscillator.disconnect();

View file

@ -139,6 +139,7 @@ export class Controller {
private destroyed = false;
private playbackTimer: ReturnType<typeof setTimeout> | undefined;
private effectTimer: ReturnType<typeof setTimeout> | undefined;
private battleSoundTimers: ReturnType<typeof setTimeout>[] = [];
private battleTimer: ReturnType<typeof setTimeout> | undefined;
private chatOff: () => void;
constructor(
@ -882,15 +883,34 @@ export class Controller {
}
private showBattles(battles: BattleCue[], animate = true) {
clearTimeout(this.battleTimer);
const previous = get(this.session).battles?.[0];
if (!battles.length) this.clearBattleSounds();
else if (battles[0].key !== previous?.key) this.playBattleSounds(battles[0]);
this.patch({ battles, battleAnimate: animate && !get(this.session).reducedMotion });
this.scheduleBattle();
}
private clearBattleSounds() {
for (const timer of this.battleSoundTimers) clearTimeout(timer);
this.battleSoundTimers = [];
}
private playBattleSounds(battle: BattleCue) {
this.clearBattleSounds();
const cues: ('battle' | 'casualty' | 'sink')[] = [];
if (battle.roll) cues.push('battle');
if (battle.losses.some((loss) => !/ships?/i.test(loss.label))) cues.push('casualty');
if (battle.losses.some((loss) => /ships?/i.test(loss.label))) cues.push('sink');
cues.forEach((cue, index) => {
if (index === 0) this.audio.play(cue);
else this.battleSoundTimers.push(setTimeout(() => this.audio.play(cue), index * 450));
});
}
private scheduleBattle() {
if (!get(this.session).battles?.length) return;
this.battleTimer = setTimeout(() => {
const s = get(this.session);
if (s.playback && s.battles?.length === 1) return; // Keep the result readable when stepping manually.
this.patch({ battles: s.battles?.slice(1) ?? [] });
if (s.battles?.[1]) this.playBattleSounds(s.battles[1]);
this.scheduleBattle();
}, BATTLE_DURATION);
}
@ -1929,6 +1949,7 @@ export class Controller {
clearTimeout(this.timer);
clearTimeout(this.refreshTimer);
this.chatOff();
this.clearBattleSounds();
this.audio.destroy();
}
}

View file

@ -253,3 +253,26 @@ test('home-at-bottom rotation is opt-in and only accepts an enabled boolean pref
assert.equal(readPreferences({}).homeAtBottom, false);
assert.equal(readPreferences({ homeAtBottom: true }).homeAtBottom, true);
});
test('action sounds wait for browser audio to resume, and mute cancels them', async () => {
const { device, voices } = audioDevice();
let finish!: () => void;
device.resume = () => new Promise<void>((resolve) => {
finish = () => { device.state = 'running'; resolve(); };
});
const audio = new GameAudio(() => device as unknown as AudioContext);
audio.setEnabled(true);
audio.unlock();
audio.play('collect');
assert.equal(voices.length, 0);
finish();
await Promise.resolve();
assert.equal(voices.length, 2);
device.state = 'suspended';
audio.play('battle');
audio.setEnabled(false);
finish();
await Promise.resolve();
assert.equal(voices.length, 2, 'Muted pending sounds must not play later');
audio.destroy();
});

View file

@ -0,0 +1,39 @@
import { GameAudio, type SoundCue } from './audio.ts';
const context = new AudioContext();
const audio = new GameAudio(() => context);
audio.setEnabled(true);
const cues: [SoundCue, string, string][] = [
['hover', 'Hover', 'Moving over an interactive target'],
['select', 'Select', 'Selecting a unit or option'],
['collect', 'Collect', 'Collecting resources'],
['build', 'Build / recruit', 'Constructing, founding or recruiting'],
['research', 'Research', 'Gaining an advance'],
['draw', 'Draw card', 'Drawing a card'],
['move', 'Move', 'Moving units'],
['confirm', 'Confirm', 'Other confirmed actions'],
['undo', 'Undo', 'Reversing an action'],
['battle', 'Battle rolls', 'Dice rolling in a battle'],
['casualty', 'Unit loss', 'Land units or leaders lost in battle'],
['sink', 'Ship sinking', 'Ships lost in battle'],
['error', 'Error', 'An action could not be completed'],
];
for (const [cue, title, description] of cues) {
const button = document.createElement('button');
button.textContent = `▶ ${title}`;
const detail = document.createElement('span');
detail.textContent = description;
button.append(detail);
button.addEventListener('click', async () => {
try {
audio.unlock();
await context.resume();
audio.play(cue);
document.querySelector('#status')!.textContent = `Played: ${title}`;
} catch {
document.querySelector('#status')!.textContent = 'Audio could not start. Check your browser’s sound permissions.';
}
});
document.querySelector('#sounds')!.append(button);
}
window.addEventListener('pagehide', () => audio.destroy());