diff --git a/CLAUDE.md b/CLAUDE.md index 99f0c27d..329f5d14 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. @@ -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 diff --git a/app/components/CLAUDE.md b/app/components/CLAUDE.md index bf1a77a3..e8963db1 100644 --- a/app/components/CLAUDE.md +++ b/app/components/CLAUDE.md @@ -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` diff --git a/app/components/audioService.js b/app/components/audioService.js index b25781e2..a9797f4a 100644 --- a/app/components/audioService.js +++ b/app/components/audioService.js @@ -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 ───────────────────────────────────────────────── /** @@ -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. * diff --git a/app/components/tests/audioService.test.js b/app/components/tests/audioService.test.js index 6cc95b8d..ee2202c0 100644 --- a/app/components/tests/audioService.test.js +++ b/app/components/tests/audioService.test.js @@ -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, @@ -54,6 +55,9 @@ function buildMockAudioContext(state = 'running') { frequency: { setValueAtTime: jest.fn(), }, + Q: { + setValueAtTime: jest.fn(), + }, }); const mockCtx = { @@ -83,6 +87,8 @@ const { playFailureSound, playFeedbackSound, playCardFlickSound, + playShuffleSound, + SHUFFLE_SOUND_DURATION_S, playSweepPair, SWEEP_LOW_FREQ_HZ, SWEEP_HIGH_FREQ_HZ, @@ -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'); diff --git a/app/games/card-rat/CLAUDE.md b/app/games/card-rat/CLAUDE.md index 635211f2..8d15338b 100644 --- a/app/games/card-rat/CLAUDE.md +++ b/app/games/card-rat/CLAUDE.md @@ -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, @@ -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 diff --git a/app/games/card-rat/game.js b/app/games/card-rat/game.js index ae4952f8..2b60420d 100644 --- a/app/games/card-rat/game.js +++ b/app/games/card-rat/game.js @@ -42,6 +42,12 @@ export const DISPLAY_SPEED_FACTOR = 0.85; /** Upper bound on the speed level (prevents runaway acceleration). */ export const MAX_SPEED_LEVEL = 50; +/** Pause (ms) after the last card of a pass, before the shuffle starts. */ +export const SHUFFLE_PAUSE_MS = 500; + +/** Time (ms) the shuffle takes, from the start of its sound to the next deal. */ +export const SHUFFLE_DURATION_MS = 1200; + /** @type {number} */ let score = 0; @@ -336,11 +342,40 @@ export function finalizeCurrentCard() { return missedTrigger; } +/** + * Replace the deck with a freshly shuffled one and count the finished pass. + */ +function startNewDeckPass() { + deck = shuffleDeck(createGameplayDeck()); + deckIndex = 0; + deckPasses += 1; +} + +/** + * Shuffle a fresh deck for the next pass. + * + * Only the deck changes. The last card dealt stays current, so slaps on it score as usual, + * and the first card of the new pass can form a pair or sandwich with the cards before it. + * + * @returns {number} The number of completed deck passes. + * @throws {Error} If the game is not running. + */ +export function shuffleForNextPass() { + if (!running) { + throw new Error('Game is not running.'); + } + + startNewDeckPass(); + return deckPasses; +} + /** * Draw the next card to show. * * This function finalizes the previous card window first, then deals the next - * card. The full 55-card deck is reshuffled after each complete pass. + * card. `deckExhausted` is true once the last card of the pass is dealt; the + * caller then runs {@link shuffleForNextPass}. If it deals again instead, the + * deck is reshuffled here. * * @returns {{ * card: { rank: string, suit: string, isJoker: boolean, jokerVariant?: string }, @@ -349,6 +384,7 @@ export function finalizeCurrentCard() { * displayDurationMs: number, * deckIndex: number, * deckPasses: number, + * deckExhausted: boolean, * }} * @throws {Error} If the game is not running. */ @@ -360,9 +396,7 @@ export function dealNextCard() { const missedTrigger = finalizeCurrentCard(); if (deckIndex >= deck.length) { - deck = shuffleDeck(createGameplayDeck()); - deckIndex = 0; - deckPasses += 1; + startNewDeckPass(); } const card = deck[deckIndex]; @@ -383,6 +417,7 @@ export function dealNextCard() { displayDurationMs, deckIndex, deckPasses, + deckExhausted: deckIndex >= deck.length, }; } diff --git a/app/games/card-rat/index.js b/app/games/card-rat/index.js index 005f5a36..c6d941f6 100644 --- a/app/games/card-rat/index.js +++ b/app/games/card-rat/index.js @@ -12,6 +12,7 @@ import { playSuccessSound, playFailureSound, playCardFlickSound, + playShuffleSound, } from '../../components/audioService.js'; import { saveScore } from '../../components/scoreService.js'; import { focusHeading, returnToMainMenu } from '../../components/gameUtils.js'; @@ -247,6 +248,7 @@ export function renderCard(card) { */ export function renderDeckBack() { if (!_deckCardEl) return; + _deckCardEl.classList.remove('card-rat__card--shuffling'); _deckCardEl.setAttribute('aria-label', 'Deck back'); applyCardImage(_deckCardEl, getDeckBackImagePath()); } @@ -259,11 +261,20 @@ export function updateHintVisibility() { _feedbackEl.hidden = Boolean(_hintToggleEl && !_hintToggleEl.checked); } +/** + * Return whether card sounds (dealing and shuffling) are on. + * + * @returns {boolean} + */ +function areCardSoundsOn() { + return !_cardSoundToggleEl || _cardSoundToggleEl.checked; +} + /** * Play the card flick sound, unless the player turned card sounds off. */ function playDealSound() { - if (!_cardSoundToggleEl || _cardSoundToggleEl.checked) { + if (areCardSoundsOn()) { playCardFlickSound(); } } @@ -298,10 +309,46 @@ export function beginDealLoop() { clearDealTimer(); _dealTimer = setTimeout(() => { - beginDealLoop(); + if (next.deckExhausted) { + beginShuffle(); + } else { + beginDealLoop(); + } }, next.displayDurationMs); } +/** + * Shuffle a fresh deck after the last card of a pass, pausing before the shuffle starts. + * + * The last card stays on the table and slaps on it score as usual. The status area reads + * "Shuffling" until a slap or the next deal replaces it. + */ +export function beginShuffle() { + if (!game.isRunning()) return; + + game.shuffleForNextPass(); + if (_feedbackEl) _feedbackEl.textContent = 'Shuffling'; + updateStats(); + + clearDealTimer(); + _dealTimer = setTimeout(playShuffle, game.SHUFFLE_PAUSE_MS); +} + +/** + * Shuffle the deck with its sound and animation, then deal the first card of the new pass. + */ +export function playShuffle() { + if (_deckCardEl) _deckCardEl.classList.add('card-rat__card--shuffling'); + if (areCardSoundsOn()) { + playShuffleSound(); + } + + _dealTimer = setTimeout(() => { + renderDeckBack(); + beginDealLoop(); + }, game.SHUFFLE_DURATION_MS); +} + /** * Show the feedback text and play the sound for a slap's outcome. * diff --git a/app/games/card-rat/interface.html b/app/games/card-rat/interface.html index 4b344548..b4c4ccc0 100644 --- a/app/games/card-rat/interface.html +++ b/app/games/card-rat/interface.html @@ -12,6 +12,7 @@

How to Play

  • Valid slap targets are pairs, sandwiches, and jokers.
  • Do not react on non-matching cards.
  • You must react before the next card is dealt.
  • +
  • When the whole deck has been dealt, it is shuffled before the next deal.
  • Every streak of 3 correct slaps speeds up future deals.
  • diff --git a/app/games/card-rat/style.css b/app/games/card-rat/style.css index e203a227..4a46013c 100644 --- a/app/games/card-rat/style.css +++ b/app/games/card-rat/style.css @@ -62,6 +62,25 @@ transform: rotate(-8deg); } +.card-rat__card--deck.card-rat__card--shuffling { + animation: card-rat-shuffle 0.3s ease-in-out 4; +} + +@keyframes card-rat-shuffle { + 0%, + 100% { + transform: rotate(-8deg); + } + + 25% { + transform: translateX(-6px) rotate(-14deg); + } + + 75% { + transform: translateX(6px) rotate(-2deg); + } +} + @media (width <=720px) { .card-rat__card { width: min(50vw, 158px); @@ -144,4 +163,11 @@ width: 34.1%; height: 9.6%; color: var(--callout-3); -} \ No newline at end of file +} + +/* The shuffle wiggle is decoration between passes, not part of a trial. */ +@media (prefers-reduced-motion: reduce) { + .card-rat__card--deck.card-rat__card--shuffling { + animation: none; + } +} diff --git a/app/games/card-rat/tests/game.test.js b/app/games/card-rat/tests/game.test.js index 1982e805..51f4946d 100644 --- a/app/games/card-rat/tests/game.test.js +++ b/app/games/card-rat/tests/game.test.js @@ -29,6 +29,7 @@ import { stopGame, finalizeCurrentCard, dealNextCard, + shuffleForNextPass, respondToCurrentCard, getScore, getTriggerHits, @@ -524,6 +525,79 @@ describe('deal and response flow', () => { expect(getDeckPasses()).toBeGreaterThanOrEqual(1); }); + test('dealNextCard reports deckExhausted only on the last card of a pass', () => { + startGame(); + const flags = []; + for (let i = 0; i < getDeckSize(); i += 1) { + flags.push(dealNextCard().deckExhausted); + } + expect(flags.indexOf(true)).toBe(getDeckSize() - 1); + expect(flags.filter(Boolean)).toHaveLength(1); + }); + + test('shuffleForNextPass starts a new pass and leaves the last card current', () => { + startGame(); + let last = null; + for (let i = 0; i < getDeckSize(); i += 1) { + last = dealNextCard().card; + } + + expect(shuffleForNextPass()).toBe(1); + expect(getDeckIndex()).toBe(0); + expect(getDeckPasses()).toBe(1); + expect(getCurrentCard()).toBe(last); + }); + + test('a slap during the shuffle scores against the last card as usual', () => { + startGame(); + expect(dealUntilTrigger()).toBe(true); + shuffleForNextPass(); + + expect(respondToCurrentCard()).toBe('hit'); + expect(respondToCurrentCard()).toBe('ignored'); + expect(getTriggerHits()).toBe(1); + }); + + test('a false alarm during the shuffle counts as usual', () => { + startGame(); + dealNextCard(); + expect(shouldReactNow()).toBe(false); + shuffleForNextPass(); + + expect(respondToCurrentCard()).toBe('false-alarm'); + expect(getFalseAlarms()).toBe(1); + }); + + test('an unslapped trigger before the shuffle is a miss when the next card is dealt', () => { + startGame(); + expect(dealUntilTrigger()).toBe(true); + shuffleForNextPass(); + expect(getMisses()).toBe(0); + + expect(dealNextCard().missedTrigger).toBe(true); + expect(getMisses()).toBe(1); + }); + + test('the first card after a shuffle pairs with the last card before it', () => { + startGame(); + let last = null; + for (let i = 0; i < getDeckSize(); i += 1) { + last = dealNextCard().card; + } + // Math.random() near 1 makes the shuffle keep the deck in order, so the new pass starts + // with the same card that ended the old one. + randomSpy.mockReturnValue(0.999999); + shuffleForNextPass(); + const next = dealNextCard(); + + expect(next.card).toEqual(last); + expect(next.mustReact).toBe(true); + }); + + test('shuffleForNextPass throws when the game is not running', () => { + expect(() => shuffleForNextPass()).toThrow('Game is not running.'); + }); + test('display duration does not go below minimum', () => { startGame(); for (let i = 0; i < 90; i += 1) { diff --git a/app/games/card-rat/tests/index.test.js b/app/games/card-rat/tests/index.test.js index 634f4c97..4b1d7982 100644 --- a/app/games/card-rat/tests/index.test.js +++ b/app/games/card-rat/tests/index.test.js @@ -32,6 +32,7 @@ jest.unstable_mockModule('../../../components/audioService.js', () => ({ playSuccessSound: jest.fn(), playFailureSound: jest.fn(), playCardFlickSound: jest.fn(), + playShuffleSound: jest.fn(), })); jest.unstable_mockModule('../../../components/trendChartService.js', () => ({ @@ -59,6 +60,8 @@ jest.unstable_mockModule('../game.js', () => ({ GAME_ID: 'card-rat', RANKS: ['A', '2', '3'], SUITS: ['hearts', 'spades'], + SHUFFLE_PAUSE_MS: 500, + SHUFFLE_DURATION_MS: 1200, initGame: jest.fn(), startGame: jest.fn(), stopGame: jest.fn(() => ({ @@ -79,6 +82,7 @@ jest.unstable_mockModule('../game.js', () => ({ deckIndex: 1, deckPasses: 0, })), + shuffleForNextPass: jest.fn(() => 1), respondToCurrentCard: jest.fn(() => 'hit'), getScore: jest.fn(() => 3), getTriggerHits: jest.fn(() => 2), @@ -123,6 +127,8 @@ const { renderCard, renderDeckBack, beginDealLoop, + beginShuffle, + playShuffle, handleReaction, handleKeyDown, attachGlobalKeyListener, @@ -580,6 +586,106 @@ describe('hint toggle', () => { }); +describe('shuffling between deck passes', () => { + /** The deal result for the last card of a pass. */ + const LAST_CARD_DEAL = { + card: { rank: 'K', suit: 'spades', isJoker: false }, + mustReact: false, + missedTrigger: false, + displayDurationMs: 1200, + deckIndex: 55, + deckPasses: 0, + deckExhausted: true, + }; + + test('the last card of a pass leads to a shuffle, not another deal', async () => { + const container = buildContainer(); + plugin.init(container); + gameMock.dealNextCard.mockReturnValueOnce(LAST_CARD_DEAL); + await plugin.start(); + + gameMock.dealNextCard.mockClear(); + jest.advanceTimersByTime(1200); + + expect(gameMock.shuffleForNextPass).toHaveBeenCalledTimes(1); + expect(gameMock.dealNextCard).not.toHaveBeenCalled(); + expect(container.querySelector('#cr-feedback').textContent).toBe('Shuffling'); + expect(container.querySelector('#cr-card').getAttribute('aria-label')) + .toBe('Current card: K♠'); + }); + + test('pauses, plays the shuffle, then deals the first card of the new pass', async () => { + const container = buildContainer(); + plugin.init(container); + gameMock.dealNextCard.mockReturnValueOnce(LAST_CARD_DEAL); + await plugin.start(); + const deckCard = container.querySelector('#cr-deck-card'); + + jest.advanceTimersByTime(1200); + jest.advanceTimersByTime(499); + expect(audioMock.playShuffleSound).not.toHaveBeenCalled(); + jest.advanceTimersByTime(1); + expect(audioMock.playShuffleSound).toHaveBeenCalledTimes(1); + expect(deckCard.classList.contains('card-rat__card--shuffling')).toBe(true); + + gameMock.dealNextCard.mockClear(); + jest.advanceTimersByTime(1199); + expect(gameMock.dealNextCard).not.toHaveBeenCalled(); + jest.advanceTimersByTime(1); + expect(gameMock.dealNextCard).toHaveBeenCalledTimes(1); + expect(deckCard.classList.contains('card-rat__card--shuffling')).toBe(false); + expect(container.querySelector('#cr-feedback').textContent).not.toBe('Shuffling'); + }); + + test('a slap during the shuffle is scored and shown as usual', () => { + const container = buildContainer(); + plugin.init(container); + beginShuffle(); + + gameMock.respondToCurrentCard.mockReturnValueOnce('false-alarm'); + handleReaction(); + + expect(audioMock.playFailureSound).toHaveBeenCalled(); + expect(container.querySelector('#cr-feedback').textContent).toContain('Too soon'); + }); + + test('beginShuffle does nothing when the game is not running', () => { + plugin.init(buildContainer()); + gameMock.isRunning.mockReturnValueOnce(false); + + beginShuffle(); + + expect(gameMock.shuffleForNextPass).not.toHaveBeenCalled(); + }); + + test('playShuffle skips the shuffle sound when card sounds are off', () => { + const container = buildContainer(); + plugin.init(container); + container.querySelector('#cr-card-sound-toggle').checked = false; + + playShuffle(); + + expect(audioMock.playShuffleSound).not.toHaveBeenCalled(); + expect(container.querySelector('#cr-deck-card').classList + .contains('card-rat__card--shuffling')).toBe(true); + }); + + test('ending the game during the shuffle cancels the next deal', async () => { + const container = buildContainer(); + plugin.init(container); + gameMock.dealNextCard.mockReturnValueOnce(LAST_CARD_DEAL); + await plugin.start(); + jest.advanceTimersByTime(1200); + + plugin.stop(); + gameMock.dealNextCard.mockClear(); + jest.advanceTimersByTime(5000); + + expect(audioMock.playShuffleSound).not.toHaveBeenCalled(); + expect(gameMock.dealNextCard).not.toHaveBeenCalled(); + }); +}); + describe('beginDealLoop guard', () => { test('returns early when game is not running', () => { gameMock.isRunning.mockReturnValueOnce(false); diff --git a/eslint.config.js b/eslint.config.js index 1454945f..715e00c1 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -30,6 +30,15 @@ export default [ 'no-console': 'off', }, }, + // Sound harness page script (runs in the browser) + { + files: ['scripts/sound-harness/harness.js'], + languageOptions: { + globals: { + ...globals.browser, + }, + }, + }, // Main process and Node.js backend — use electron-log, not console { files: ['main.js', 'app/games/registry.js', 'app/progress/**/*.js'], diff --git a/package.json b/package.json index 67005564..516e89dd 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "test:watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch", "test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage", "build:icons": "node scripts/build-icons.js", + "sound-harness": "electron scripts/sound-harness/main.js", "package": "electron-forge package", "make": "electron-forge make", "publish": "electron-forge publish" diff --git a/scripts/sound-harness/harness.css b/scripts/sound-harness/harness.css new file mode 100644 index 00000000..978ee6c1 --- /dev/null +++ b/scripts/sound-harness/harness.css @@ -0,0 +1,33 @@ +/* Sound harness layout. Buttons use the app's shared .game-btn styles. */ + +.sound-harness__settings { + display: flex; + flex-wrap: wrap; + gap: 1rem; + margin: 1rem 0 0; + padding: 0.75rem 1rem; + border: 1px solid var(--border-color); + border-radius: var(--radius-md); +} + +.sound-harness__settings label { + display: flex; + flex-direction: column; + gap: 0.25rem; + font-weight: 600; +} + +.sound-harness__settings input { + width: 8rem; + padding: 0.35rem 0.5rem; + font: inherit; +} + +#sound-list { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + margin: 1rem 0 0; + padding: 0; + list-style: none; +} diff --git a/scripts/sound-harness/harness.js b/scripts/sound-harness/harness.js new file mode 100644 index 00000000..55becee6 --- /dev/null +++ b/scripts/sound-harness/harness.js @@ -0,0 +1,189 @@ +/** + * harness.js — Page script for the sound test harness. + * + * Builds one button per sound that audioService.js can make. Every exported + * `play*` function that takes no arguments gets a button without changes to + * the harness. A sound that needs arguments gets its buttons from + * SOUND_PRESETS, unless SOUND_WRAPPERS lists it as only choosing between + * other sounds. `listUncoveredSounds` names any that are missing, and the + * harness test fails until one is added. + * + * @file Sound harness page. + */ +import * as audio from '../../app/components/audioService.js'; + +/** + * Sweep timing used when the inputs are missing or invalid: Sound Sweep's easiest level. + * @type {Readonly<{ sweepDurationMs: number, isiMs: number }>} + */ +export const DEFAULT_SWEEP_SETTINGS = Object.freeze({ sweepDurationMs: 600, isiMs: 600 }); + +/** Every sweep direction pair `playSweepPair` accepts. */ +const SWEEP_SEQUENCES = [['up', 'up'], ['up', 'down'], ['down', 'up'], ['down', 'down']]; + +/** + * Capitalize the first letter of a word. + * + * @param {string} word + * @returns {string} + */ +function capitalize(word) { + return word.charAt(0).toUpperCase() + word.slice(1); +} + +/** + * Functions that only play other sounds, mapped to the sounds they choose between. They get + * no buttons of their own, so each sound has exactly one button. + * + * @type {Readonly>>} + */ +export const SOUND_WRAPPERS = Object.freeze({ + playFeedbackSound: Object.freeze(['playSuccessSound', 'playFailureSound']), +}); + +/** + * Buttons for sounds that need arguments. `getArgs(settings)` returns the arguments to pass, + * where `settings` is the page's current sweep timing from {@link readSweepSettings}. + * + * @type {ReadonlyArray<{ + * exportName: string, + * label: string, + * getArgs: (settings: { sweepDurationMs: number, isiMs: number }) => unknown[], + * }>} + */ +export const SOUND_PRESETS = Object.freeze([ + ...SWEEP_SEQUENCES.map((sequence) => ({ + exportName: 'playSweepPair', + label: `Sweeps: ${sequence.map(capitalize).join('-')}`, + getArgs: (settings) => [sequence, settings], + })), +]); + +/** + * Return the exported `play*` functions of a module. + * + * @param {Record} soundModule + * @returns {string[]} Export names, sorted. + */ +function listPlayFunctions(soundModule) { + return Object.keys(soundModule) + .filter((key) => key.startsWith('play') && typeof soundModule[key] === 'function') + .sort(); +} + +/** + * List the sound effects a module exports that play with no arguments. + * + * @param {Record} soundModule + * @returns {string[]} Export names, such as `playShuffleSound`, sorted. + */ +export function listSoundEffects(soundModule) { + return listPlayFunctions(soundModule).filter((key) => soundModule[key].length === 0); +} + +/** + * List the sounds that need arguments but have no preset and are not wrappers, so the + * harness cannot play them. + * + * @param {Record} soundModule + * @returns {string[]} Export names, sorted. + */ +export function listUncoveredSounds(soundModule) { + const presetNames = new Set(SOUND_PRESETS.map((preset) => preset.exportName)); + return listPlayFunctions(soundModule) + .filter((key) => soundModule[key].length > 0 + && !presetNames.has(key) + && !Object.hasOwn(SOUND_WRAPPERS, key)); +} + +/** + * Turn an export name into a button label, for example `playCardFlickSound` → `Card flick`. + * + * @param {string} exportName + * @returns {string} + */ +export function getSoundLabel(exportName) { + const words = exportName + .replace(/^play/, '') + .replace(/Sound$/, '') + .replace(/([a-z])([A-Z])/g, '$1 $2') + .toLowerCase(); + return capitalize(words); +} + +/** + * Read one positive whole number of milliseconds from an input. + * + * @param {HTMLInputElement|null} inputEl + * @param {number} fallback - Used when the input is missing or not a positive number. + * @returns {number} + */ +function readMs(inputEl, fallback) { + const value = Number(inputEl?.value); + return Number.isFinite(value) && value > 0 ? Math.round(value) : fallback; +} + +/** + * Read the sweep timing inputs on the page. + * + * @param {ParentNode} root - Holds `#sweep-duration-ms` and `#sweep-isi-ms`. + * @returns {{ sweepDurationMs: number, isiMs: number }} + */ +export function readSweepSettings(root) { + return { + sweepDurationMs: readMs( + root.querySelector('#sweep-duration-ms'), + DEFAULT_SWEEP_SETTINGS.sweepDurationMs, + ), + isiMs: readMs(root.querySelector('#sweep-isi-ms'), DEFAULT_SWEEP_SETTINGS.isiMs), + }; +} + +/** + * Add a list item holding one play button. + * + * @param {HTMLElement} listEl + * @param {string} label + * @param {() => void} onClick + */ +function addButton(listEl, label, onClick) { + const item = document.createElement('li'); + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'game-btn game-btn--primary'; + button.textContent = label; + button.addEventListener('click', onClick); + item.appendChild(button); + listEl.appendChild(item); +} + +/** + * Add a play button to the list for each sound in the module: the sounds that need no + * arguments first, then the presets for sounds that do. + * + * @param {HTMLElement|null} listEl - The `