Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ npm test # Jest (runs with --experimental-vm-modules for native ES
npm test -- app/games/fast-piggie # run a subset of tests by path
npm run test:coverage # enforces the coverage thresholds below
npm run make # build installers with Electron Forge (forge.config.cjs)
npm run sound-harness # window that plays each audioService sound on its own
```

Before calling work done, run `npm run lint` and `npm test`. Run `npm audit` before merging.
Expand Down Expand Up @@ -85,6 +86,7 @@ app/progress/ progressManager.js: load/save/reset of the progress JSO
app/games/ Game plugins plus registry.js (main-process manifest scanner)
__mocks__/ electron.js and electron-log.js mocks for Jest
scripts/build-icons.js Icon generation (console output allowed here)
scripts/sound-harness/ Dev-only Electron window that plays each audioService sound
```

## Process boundaries and IPC
Expand Down
8 changes: 7 additions & 1 deletion app/components/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,18 @@ where Web Audio is missing. Every sound resumes a suspended context and swallows

- Feedback: `playSuccessSound()`, `playFailureSound()`, and `playFeedbackSound(isSuccess)`.
- `playCardFlickSound()`: a short card snap.
- `playShuffleSound()`: a deck riffle, generated as softened noise that flutters as the cards
fall, then a soft swish. It lasts `SHUFFLE_SOUND_DURATION_S`.
- `playSweepPair(['up' | 'down', 'up' | 'down'], { sweepDurationMs, isiMs })` schedules two
frequency sweeps between `SWEEP_LOW_FREQ_HZ` and `SWEEP_HIGH_FREQ_HZ` on the context clock and
returns at once. Invalid input schedules nothing.

Add new sounds here, with their tuning values as named constants at the top of the file. Speech
sounds go in `syllableService.js` instead.
sounds go in `syllableService.js` instead. `npm run sound-harness` (in `scripts/sound-harness/`)
plays every sound here without a game. Each exported `play*` function that takes no arguments
gets a button by itself. A sound that needs arguments needs an entry in `SOUND_PRESETS` in
`harness.js`, or in `SOUND_WRAPPERS` if it only picks between other sounds (as
`playFeedbackSound` does); `harness.test.js` fails until it has one.

## `syllableService.js`

Expand Down
129 changes: 129 additions & 0 deletions app/components/audioService.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,54 @@ const CARD_SWISH_PEAK_GAIN = 0.075;
*/
const CARD_FLIP_ATTACK_S = 0.002;

// ── Deck shuffle sound constants ──────────────────────────────────────────────

/** Duration (s) of the riffle, while the two halves fall together. */
const SHUFFLE_RIFFLE_DURATION_S = 0.75;

/**
* Flutter rate (Hz) at the start of the riffle: how many times a second the
* level dips as cards fall. It slows to SHUFFLE_FLUTTER_END_HZ as the last
* cards drop.
*/
const SHUFFLE_FLUTTER_START_HZ = 45;

/** Flutter rate (Hz) at the end of the riffle. */
const SHUFFLE_FLUTTER_END_HZ = 18;

/**
* How far each flutter dips the level, from 0 (steady noise) to 1 (separate
* clicks). Keeping it well below 1 gives a smooth paper texture.
*/
const SHUFFLE_FLUTTER_DEPTH = 0.45;

/** Fade-in and fade-out time (s) at each end of the riffle. */
const SHUFFLE_RIFFLE_FADE_S = 0.06;

/**
* Coefficient (0–1) of the one-pole low-pass applied to the raw noise.
* Lower values give a darker, softer hiss.
*/
const SHUFFLE_NOISE_SMOOTHING = 0.2;

/** Duration (s) of the soft swish as the riffled halves are pushed together. */
const SHUFFLE_BRIDGE_DURATION_S = 0.3;

/** Loudness of the bridge swish relative to the riffle. */
const SHUFFLE_BRIDGE_LEVEL = 0.6;

/** Cutoff frequency (Hz) of the low-pass filter that takes the edge off the noise. */
const SHUFFLE_FILTER_FREQ_HZ = 2000;

/** Q of the shuffle low-pass filter. Below 0.707 so the cutoff has no resonant peak. */
const SHUFFLE_FILTER_Q = 0.5;

/** Overall gain of the shuffle sound. */
const SHUFFLE_PEAK_GAIN = 0.15;

/** Total duration (s) of the shuffle sound: the riffle, then the bridge swish. */
export const SHUFFLE_SOUND_DURATION_S = SHUFFLE_RIFFLE_DURATION_S + SHUFFLE_BRIDGE_DURATION_S;

// ── Frequency sweep constants ─────────────────────────────────────────────────

/**
Expand Down Expand Up @@ -350,6 +398,87 @@ export function playCardFlickSound() {
}
}

/**
* Write the shuffle waveform into a sample buffer.
*
* The riffle is softened noise whose level flutters smoothly, quickly at first
* and slower as the last cards fall, with a fade at each end. A gentler noise
* swish follows, rising and falling over SHUFFLE_BRIDGE_DURATION_S.
*
* @param {Float32Array} channelData - Buffer of SHUFFLE_SOUND_DURATION_S worth of samples.
* @param {number} sampleRate - Samples per second.
*/
function fillShuffleSamples(channelData, sampleRate) {
const riffleLength = Math.floor(SHUFFLE_RIFFLE_DURATION_S * sampleRate);
const fadeLength = SHUFFLE_RIFFLE_FADE_S * sampleRate;
const bridgeLength = channelData.length - riffleLength;
const flutterSpanHz = SHUFFLE_FLUTTER_END_HZ - SHUFFLE_FLUTTER_START_HZ;
let noise = 0;
let flutterPhase = 0;

for (let i = 0; i < channelData.length; i += 1) {
noise += SHUFFLE_NOISE_SMOOTHING * (Math.random() * 2 - 1 - noise);

if (i < riffleLength) {
const flutterHz = SHUFFLE_FLUTTER_START_HZ + flutterSpanHz * (i / riffleLength);
flutterPhase += (2 * Math.PI * flutterHz) / sampleRate;
const flutter = 1 - SHUFFLE_FLUTTER_DEPTH * (0.5 + 0.5 * Math.cos(flutterPhase));
const fade = Math.min(1, i / fadeLength, (riffleLength - i) / fadeLength);
channelData[i] = noise * flutter * fade;
} else {
const envelope = Math.sin((Math.PI * (i - riffleLength)) / bridgeLength);
channelData[i] = noise * SHUFFLE_BRIDGE_LEVEL * envelope;
}
}
}

/**
* Play a synthesized deck-shuffling sound: the flutter of a riffle, then the
* swish of the two halves being pushed together.
*
* The waveform is generated noise (see {@link fillShuffleSamples}) played
* through a low-pass filter, so no audio file is needed. It lasts
* SHUFFLE_SOUND_DURATION_S.
*
* Uses the shared AudioContext from {@link getAudioContext}.
*/
export function playShuffleSound() {
const ctx = getAudioContext();
if (!ctx) return;

try {
if (ctx.state === 'suspended') {
ctx.resume().catch(() => { });
}

const now = ctx.currentTime;

const bufferSize = Math.ceil(ctx.sampleRate * SHUFFLE_SOUND_DURATION_S);
const buffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
fillShuffleSamples(buffer.getChannelData(0), ctx.sampleRate);

const source = ctx.createBufferSource();
source.buffer = buffer;

const filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(SHUFFLE_FILTER_FREQ_HZ, now);
filter.Q.setValueAtTime(SHUFFLE_FILTER_Q, now);

const gain = ctx.createGain();
gain.gain.setValueAtTime(SHUFFLE_PEAK_GAIN, now);

source.connect(filter);
filter.connect(gain);
gain.connect(ctx.destination);

source.start(now);
source.stop(now + SHUFFLE_SOUND_DURATION_S);
} catch {
// Ignore audio errors in unsupported environments.
}
}

/**
* Schedule a single frequency sweep on the Web Audio graph.
*
Expand Down
134 changes: 133 additions & 1 deletion app/components/tests/audioService.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
* audioService.test.js - Unit tests for the central audio service.
*
* Covers all exported functions: getAudioContext, playSuccessSound,
* playFailureSound, playFeedbackSound, playCardFlickSound, and playSweepPair.
* playFailureSound, playFeedbackSound, playCardFlickSound, playShuffleSound, and
* playSweepPair.
*/
import {
jest,
Expand Down Expand Up @@ -54,6 +55,9 @@ function buildMockAudioContext(state = 'running') {
frequency: {
setValueAtTime: jest.fn(),
},
Q: {
setValueAtTime: jest.fn(),
},
});

const mockCtx = {
Expand Down Expand Up @@ -83,6 +87,8 @@ const {
playFailureSound,
playFeedbackSound,
playCardFlickSound,
playShuffleSound,
SHUFFLE_SOUND_DURATION_S,
playSweepPair,
SWEEP_LOW_FREQ_HZ,
SWEEP_HIGH_FREQ_HZ,
Expand Down Expand Up @@ -509,6 +515,132 @@ describe('playCardFlickSound', () => {
});


describe('playShuffleSound', () => {
/**
* Install a fresh mock AudioContext for one test.
*
* @param {string} [state='running']
* @returns {{ mockCtx: object, restore: () => void }}
*/
function useMockContext(state = 'running') {
const { mockCtx, MockAC } = buildMockAudioContext(state);
const existing = getAudioContext();
if (existing) existing.state = 'closed';
const original = globalThis.AudioContext;
globalThis.AudioContext = MockAC;
return { mockCtx, restore: () => { globalThis.AudioContext = original; } };
}

test('plays one generated buffer for the full shuffle duration', () => {
const { mockCtx, restore } = useMockContext();

playShuffleSound();

const expectedLength = Math.ceil(44100 * SHUFFLE_SOUND_DURATION_S);
expect(mockCtx.createBuffer).toHaveBeenCalledWith(1, expectedLength, 44100);
const source = mockCtx.createBufferSource.mock.results[0].value;
expect(source.buffer).toBe(mockCtx.createBuffer.mock.results[0].value);
expect(source.start).toHaveBeenCalledWith(0);
expect(source.stop).toHaveBeenCalledWith(SHUFFLE_SOUND_DURATION_S);
restore();
});

test('fills the buffer with a smooth riffle and a bridge swish', () => {
const { mockCtx, restore } = useMockContext();
// 0.75 makes every raw noise sample 0.5, so the level shows the envelope alone.
const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0.75);

playShuffleSound();

const buffer = mockCtx.createBuffer.mock.results[0].value;
const samples = buffer.getChannelData.mock.results[0].value;
const riffleEnd = Math.floor(44100 * 0.75);
const fadeEnd = Math.ceil(44100 * 0.06);
// The riffle fades in from silence.
expect(samples[0]).toBe(0);
// Between the fades the flutter dips the level but never to silence, so there are no clicks.
const middle = Array.from(samples.subarray(fadeEnd, riffleEnd - fadeEnd));
expect(Math.min(...middle)).toBeGreaterThan(0.5 * (1 - 0.45) * 0.99);
expect(Math.max(...middle)).toBeLessThanOrEqual(0.5);
// The bridge swish rises from silence to a peak below the riffle.
const bridge = Array.from(samples.subarray(riffleEnd));
expect(bridge[0]).toBe(0);
expect(Math.max(...bridge)).toBeCloseTo(0.5 * 0.6, 3);
randomSpy.mockRestore();
restore();
});

test('routes the noise through a low-pass filter', () => {
const { mockCtx, restore } = useMockContext();

playShuffleSound();

const filter = mockCtx.createBiquadFilter.mock.results[0].value;
expect(filter.type).toBe('lowpass');
expect(filter.frequency.setValueAtTime).toHaveBeenCalledWith(2000, 0);
expect(filter.Q.setValueAtTime).toHaveBeenCalledWith(0.5, 0);
restore();
});

test('plays at the shuffle gain', () => {
const { mockCtx, restore } = useMockContext();

playShuffleSound();

const gain = mockCtx.createGain.mock.results[0].value;
expect(gain.gain.setValueAtTime).toHaveBeenCalledWith(0.15, 0);
restore();
});

test('resumes a suspended context before playing', () => {
const { mockCtx, restore } = useMockContext('suspended');

playShuffleSound();

expect(mockCtx.resume).toHaveBeenCalled();
restore();
});

test('handles resume rejection gracefully', async () => {
const { mockCtx, restore } = useMockContext('suspended');
mockCtx.resume = jest.fn().mockRejectedValue(new Error('cannot resume'));

expect(() => playShuffleSound()).not.toThrow();
await new Promise((resolve) => { setTimeout(resolve, 0); });

restore();
});

test('does not throw when no AudioContext is available', () => {
const existing = getAudioContext();
if (existing) existing.state = 'closed';
const original = globalThis.AudioContext;
delete globalThis.AudioContext;
if (globalThis.window) delete globalThis.window.webkitAudioContext;

expect(() => playShuffleSound()).not.toThrow();

globalThis.AudioContext = original;
});

test('swallows errors thrown during audio node setup', () => {
const existing = getAudioContext();
if (existing) existing.state = 'closed';
const original = globalThis.AudioContext;
globalThis.AudioContext = jest.fn(() => ({
state: 'running',
currentTime: 0,
sampleRate: 44100,
destination: {},
createBuffer: jest.fn(() => { throw new Error('buffer error'); }),
}));

expect(() => playShuffleSound()).not.toThrow();

globalThis.AudioContext = original;
});
});

describe('playSweepPair', () => {
test('exported frequency constants are positive numbers', () => {
expect(typeof SWEEP_LOW_FREQ_HZ).toBe('number');
Expand Down
16 changes: 14 additions & 2 deletions app/games/card-rat/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ A joker never forms a pair or sandwich with a card next to it.
## Files

- `game.js`: builds a 55-card deck (52 + `joker1..3`), reshuffles after each full pass
(`deckPasses`), and detects triggers. `dealNextCard()` first calls `finalizeCurrentCard()`, so
**a miss is scored when the next card is dealt**, not when a timer fires.
(`deckPasses`), and detects triggers. `dealNextCard()` sets `deckExhausted` on the last card
of a pass; the controller then calls `shuffleForNextPass()`, which only replaces the deck.
The last card stays current through the shuffle, so slaps on it score as usual, and pairs
and sandwiches carry across into the new pass.
`dealNextCard()` first calls `finalizeCurrentCard()`, so **a miss is scored when the next
card is dealt**, not when a timer fires.
`respondToCurrentCard()` returns `'hit' | 'false-alarm' | 'ignored'`. A second slap on the
same trigger returns `'ignored'`. A late slap is also `'ignored'`: when the previous card was a
missed trigger and the current card is not a trigger, the first slap on it scores nothing,
Expand All @@ -27,6 +31,14 @@ A joker never forms a pair or sandwich with a card next to it.
sprite changes.
- `tutorial/`: the first-run tutorial. See [tutorial/CLAUDE.md](tutorial/CLAUDE.md).

## Shuffling between passes

After the last card's display time, `beginShuffle()` in `index.js` shuffles a new deck and sets
the status line to "Shuffling"; the last card stays on the table. After `SHUFFLE_PAUSE_MS`,
`playShuffle()` wiggles the deck card (`card-rat__card--shuffling`, off under reduced motion)
and plays `playShuffleSound()` unless Card sound is off. The next deal comes
`SHUFFLE_DURATION_MS` later. Both steps run on `_dealTimer`, so End Game cancels them.

## Difficulty

Display time per card is `round(1400 × 0.85^level)`, with a floor of 120 ms and a maximum level
Expand Down
Loading
Loading