From bc7a7407447d55eb51a4de8b022068ea0a5ebea8 Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 21:59:23 -0400 Subject: [PATCH 1/8] Add a synthesized deck-shuffle sound to the audio service playShuffleSound() generates a riffle of short noise clicks followed by a soft swish, played through a band-pass filter. No audio file is used. Refs #198 Co-Authored-By: Claude Opus 5.5 --- app/components/CLAUDE.md | 2 + app/components/audioService.js | 113 ++++++++++++++++++++ app/components/tests/audioService.test.js | 123 +++++++++++++++++++++- 3 files changed, 237 insertions(+), 1 deletion(-) diff --git a/app/components/CLAUDE.md b/app/components/CLAUDE.md index bf1a77a3..a643dfa2 100644 --- a/app/components/CLAUDE.md +++ b/app/components/CLAUDE.md @@ -70,6 +70,8 @@ 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 from noise clicks, 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. diff --git a/app/components/audioService.js b/app/components/audioService.js index b25781e2..42652711 100644 --- a/app/components/audioService.js +++ b/app/components/audioService.js @@ -106,6 +106,41 @@ const CARD_SWISH_PEAK_GAIN = 0.075; */ const CARD_FLIP_ATTACK_S = 0.002; +// ── Deck shuffle sound constants ────────────────────────────────────────────── + +/** Number of card clicks in the riffle (about half a deck, as the halves interleave). */ +const SHUFFLE_RIFFLE_CLICKS = 28; + +/** Duration (s) of the riffle, from the first card click to the last. */ +const SHUFFLE_RIFFLE_DURATION_S = 0.7; + +/** + * Largest random shift of each click, as a fraction of the click spacing. + * The unevenness keeps the riffle from sounding like a mechanical ticker. + */ +const SHUFFLE_CLICK_JITTER = 0.4; + +/** Decay time constant (s) of each click. Each click lasts five time constants. */ +const SHUFFLE_CLICK_DECAY_S = 0.004; + +/** Duration (s) of the soft swish as the riffled halves are pushed together. */ +const SHUFFLE_BRIDGE_DURATION_S = 0.25; + +/** Loudness of the bridge swish relative to a click. */ +const SHUFFLE_BRIDGE_LEVEL = 0.35; + +/** Center frequency (Hz) of the band-pass filter that gives the clicks a papery tone. */ +const SHUFFLE_FILTER_FREQ_HZ = 2500; + +/** Q of the shuffle band-pass filter. A low Q keeps the band wide. */ +const SHUFFLE_FILTER_Q = 0.7; + +/** Overall gain of the shuffle sound. */ +const SHUFFLE_PEAK_GAIN = 0.12; + +/** 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 +385,84 @@ export function playCardFlickSound() { } } +/** + * Write the shuffle waveform into a sample buffer. + * + * The riffle is a run of short, decaying noise clicks spread unevenly over + * SHUFFLE_RIFFLE_DURATION_S, one per card falling. A softer 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 riffleEnd = Math.floor(SHUFFLE_RIFFLE_DURATION_S * sampleRate); + const clickSpacingS = SHUFFLE_RIFFLE_DURATION_S / SHUFFLE_RIFFLE_CLICKS; + const decaySamples = SHUFFLE_CLICK_DECAY_S * sampleRate; + const clickLength = Math.ceil(decaySamples * 5); + + for (let k = 0; k < SHUFFLE_RIFFLE_CLICKS; k += 1) { + const jitterS = (Math.random() - 0.5) * SHUFFLE_CLICK_JITTER * clickSpacingS; + const start = Math.max(0, Math.round((k * clickSpacingS + jitterS) * sampleRate)); + for (let i = 0; i < clickLength && start + i < riffleEnd; i += 1) { + channelData[start + i] += (Math.random() * 2 - 1) * Math.exp(-i / decaySamples); + } + } + + const bridgeLength = channelData.length - riffleEnd; + for (let i = 0; i < bridgeLength; i += 1) { + const envelope = Math.sin((Math.PI * i) / bridgeLength); + channelData[riffleEnd + i] = (Math.random() * 2 - 1) * SHUFFLE_BRIDGE_LEVEL * envelope; + } +} + +/** + * Play a synthesized deck-shuffling sound: a riffle of card clicks, then the + * swish of the two halves being pushed together. + * + * The waveform is generated noise (see {@link fillShuffleSamples}) played + * through a band-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 = 'bandpass'; + 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..509ace84 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,121 @@ 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 riffle clicks and a bridge swish', () => { + const { mockCtx, restore } = useMockContext(); + // 0.75 makes every noise sample 0.5 and shifts every click by the same jitter. + 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 spacing = Math.round(44100 * (0.7 / 28)); + const firstClick = Math.round(44100 * 0.25 * 0.4 * (0.7 / 28)); + const riffleEnd = Math.floor(44100 * 0.7); + // Silence before the first click, a full-level onset, and a gap before the next click. + expect(samples[firstClick - 1]).toBe(0); + expect(samples[firstClick]).toBeCloseTo(0.5); + expect(samples[firstClick + spacing - 1]).toBe(0); + // The bridge swish rises from silence to a peak below the clicks. + const bridge = samples.subarray(riffleEnd); + expect(bridge[0]).toBe(0); + expect(Math.max(...bridge)).toBeCloseTo(0.5 * 0.35, 3); + randomSpy.mockRestore(); + restore(); + }); + + test('routes the noise through a band-pass filter', () => { + const { mockCtx, restore } = useMockContext(); + + playShuffleSound(); + + const filter = mockCtx.createBiquadFilter.mock.results[0].value; + expect(filter.type).toBe('bandpass'); + expect(filter.frequency.setValueAtTime).toHaveBeenCalledWith(2500, 0); + expect(filter.Q.setValueAtTime).toHaveBeenCalledWith(0.7, 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'); From 2718bdba3cff8ba7e8a1ab6239724dccfec6756d Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 21:59:23 -0400 Subject: [PATCH 2/8] Pause to shuffle the deck between Card Rat passes After the last card of a pass, the table clears and the status line reads "Shuffling". After a short pause, the deck card wiggles and the shuffle sound plays (unless Card sound is off), then the next pass is dealt. An unslapped trigger on the last card still counts as a miss. Slaps while shuffling are ignored, and the first card of a new pass cannot pair or sandwich with cards from the old one. Fixes #198 Co-Authored-By: Claude Opus 5.5 --- app/games/card-rat/CLAUDE.md | 16 +++- app/games/card-rat/game.js | 50 +++++++++++- app/games/card-rat/index.js | 58 +++++++++++++- app/games/card-rat/interface.html | 1 + app/games/card-rat/style.css | 33 +++++++- app/games/card-rat/tests/game.test.js | 65 +++++++++++++++ app/games/card-rat/tests/index.test.js | 105 +++++++++++++++++++++++++ 7 files changed, 319 insertions(+), 9 deletions(-) diff --git a/app/games/card-rat/CLAUDE.md b/app/games/card-rat/CLAUDE.md index 635211f2..588d9077 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 scores that card, starts + the new pass, and clears the table. With no card showing, slaps are `'ignored'`, and the + first card of the new pass never pairs or sandwiches with cards from the old one. + `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` hides the current card +(`card-rat__card--cleared`) and sets the status line to "Shuffling". 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..a0d25109 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 is cleared, 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,47 @@ 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; +} + +/** + * Clear the table and shuffle a fresh deck for the next pass. + * + * Finalizes the last card first, so an unslapped trigger counts as a miss. Then no card is + * showing, so slaps are ignored until the next deal, and the first card of the new pass + * cannot form a pair or sandwich with cards from the old one. + * + * @returns {{ missedTrigger: boolean, deckPasses: number }} + * @throws {Error} If the game is not running. + */ +export function shuffleForNextPass() { + if (!running) { + throw new Error('Game is not running.'); + } + + const missedTrigger = finalizeCurrentCard(); + startNewDeckPass(); + currentCard = null; + previousCard = null; + twoCardsAgo = null; + lateSlapPending = false; + + return { missedTrigger, 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 without clearing the table. * * @returns {{ * card: { rank: string, suit: string, isJoker: boolean, jokerVariant?: string }, @@ -349,6 +391,7 @@ export function finalizeCurrentCard() { * displayDurationMs: number, * deckIndex: number, * deckPasses: number, + * deckExhausted: boolean, * }} * @throws {Error} If the game is not running. */ @@ -360,9 +403,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 +424,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..56be5a02 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'; @@ -221,6 +222,7 @@ export function updateTrendChart() { export function renderCard(card) { if (!_cardEl) return; + _cardEl.classList.remove('card-rat__card--cleared'); const label = getCardLabel(card); _cardEl.setAttribute('aria-label', `Current card: ${label}`); @@ -247,6 +249,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 +262,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 +310,52 @@ export function beginDealLoop() { clearDealTimer(); _dealTimer = setTimeout(() => { - beginDealLoop(); + if (next.deckExhausted) { + beginShuffle(); + } else { + beginDealLoop(); + } }, next.displayDurationMs); } +/** + * Clear the table after the last card of a pass, then pause before shuffling. + * + * The status area reads "Shuffling" until the next deal replaces it. + */ +export function beginShuffle() { + if (!game.isRunning()) return; + + const { missedTrigger } = game.shuffleForNextPass(); + if (missedTrigger) { + playFailureSound(); + } + if (_cardEl) { + _cardEl.classList.add('card-rat__card--cleared'); + _cardEl.setAttribute('aria-label', 'No card showing'); + } + 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..bbbc08b8 100644 --- a/app/games/card-rat/style.css +++ b/app/games/card-rat/style.css @@ -62,6 +62,30 @@ transform: rotate(-8deg); } +/* The table is empty while the deck is shuffled between passes. */ +.card-rat__card--cleared { + visibility: hidden; +} + +.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 +168,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..dbae6f8d 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,70 @@ 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 with no card showing', () => { + startGame(); + for (let i = 0; i < getDeckSize(); i += 1) { + dealNextCard(); + } + + expect(shuffleForNextPass()).toEqual({ missedTrigger: false, deckPasses: 1 }); + expect(getDeckIndex()).toBe(0); + expect(getDeckPasses()).toBe(1); + expect(getCurrentCard()).toBeNull(); + expect(shouldReactNow()).toBe(false); + expect(respondToCurrentCard()).toBe('ignored'); + expect(getFalseAlarms()).toBe(0); + }); + + test('shuffleForNextPass scores an unslapped trigger as a miss', () => { + startGame(); + expect(dealUntilTrigger()).toBe(true); + + expect(shuffleForNextPass().missedTrigger).toBe(true); + expect(getMisses()).toBe(1); + }); + + test('a slap on the first card after a shuffle is not a late slap', () => { + startGame(); + expect(dealUntilTrigger()).toBe(true); + shuffleForNextPass(); + const { card, mustReact } = dealNextCard(); + expect(card.isJoker).toBe(false); + expect(mustReact).toBe(false); + + expect(respondToCurrentCard()).toBe('false-alarm'); + }); + + test('the first card after a shuffle never 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(false); + }); + + 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..a208d47f 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(() => ({ missedTrigger: false, deckPasses: 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,105 @@ 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').classList.contains('card-rat__card--cleared')) + .toBe(true); + }); + + 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'); + const card = container.querySelector('#cr-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(card.classList.contains('card-rat__card--cleared')).toBe(false); + expect(container.querySelector('#cr-feedback').textContent).not.toBe('Shuffling'); + }); + + test('beginShuffle plays the failure sound when the last card was a missed trigger', () => { + plugin.init(buildContainer()); + gameMock.shuffleForNextPass.mockReturnValueOnce({ missedTrigger: true, deckPasses: 1 }); + + beginShuffle(); + + expect(audioMock.playFailureSound).toHaveBeenCalled(); + }); + + 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); From 8a9dc766e47836dfaec5404f2ea5eab43d0cb834 Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 22:09:52 -0400 Subject: [PATCH 3/8] Keep Card Rat's game state unchanged through the shuffle The shuffle now only replaces the deck. The last card stays on the table and stays current, so slaps during the shuffle score as they would at any other time, a missed trigger is still scored when the next card is dealt, and pairs and sandwiches carry across into the new pass. Refs #198 Co-Authored-By: Claude Opus 5.5 --- app/games/card-rat/CLAUDE.md | 10 +++--- app/games/card-rat/game.js | 21 +++++-------- app/games/card-rat/index.js | 15 +++------ app/games/card-rat/style.css | 5 --- app/games/card-rat/tests/game.test.js | 43 ++++++++++++++++---------- app/games/card-rat/tests/index.test.js | 19 ++++++------ 6 files changed, 52 insertions(+), 61 deletions(-) diff --git a/app/games/card-rat/CLAUDE.md b/app/games/card-rat/CLAUDE.md index 588d9077..8d15338b 100644 --- a/app/games/card-rat/CLAUDE.md +++ b/app/games/card-rat/CLAUDE.md @@ -13,9 +13,9 @@ A joker never forms a pair or sandwich with a card next to it. - `game.js`: builds a 55-card deck (52 + `joker1..3`), reshuffles after each full pass (`deckPasses`), and detects triggers. `dealNextCard()` sets `deckExhausted` on the last card - of a pass; the controller then calls `shuffleForNextPass()`, which scores that card, starts - the new pass, and clears the table. With no card showing, slaps are `'ignored'`, and the - first card of the new pass never pairs or sandwiches with cards from the old one. + 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 @@ -33,8 +33,8 @@ A joker never forms a pair or sandwich with a card next to it. ## Shuffling between passes -After the last card's display time, `beginShuffle()` in `index.js` hides the current card -(`card-rat__card--cleared`) and sets the status line to "Shuffling". After `SHUFFLE_PAUSE_MS`, +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. diff --git a/app/games/card-rat/game.js b/app/games/card-rat/game.js index a0d25109..2b60420d 100644 --- a/app/games/card-rat/game.js +++ b/app/games/card-rat/game.js @@ -42,7 +42,7 @@ 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 is cleared, before the shuffle starts. */ +/** 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. */ @@ -352,13 +352,12 @@ function startNewDeckPass() { } /** - * Clear the table and shuffle a fresh deck for the next pass. + * Shuffle a fresh deck for the next pass. * - * Finalizes the last card first, so an unslapped trigger counts as a miss. Then no card is - * showing, so slaps are ignored until the next deal, and the first card of the new pass - * cannot form a pair or sandwich with cards from the old one. + * 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 {{ missedTrigger: boolean, deckPasses: number }} + * @returns {number} The number of completed deck passes. * @throws {Error} If the game is not running. */ export function shuffleForNextPass() { @@ -366,14 +365,8 @@ export function shuffleForNextPass() { throw new Error('Game is not running.'); } - const missedTrigger = finalizeCurrentCard(); startNewDeckPass(); - currentCard = null; - previousCard = null; - twoCardsAgo = null; - lateSlapPending = false; - - return { missedTrigger, deckPasses }; + return deckPasses; } /** @@ -382,7 +375,7 @@ export function shuffleForNextPass() { * This function finalizes the previous card window first, then deals the next * 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 without clearing the table. + * deck is reshuffled here. * * @returns {{ * card: { rank: string, suit: string, isJoker: boolean, jokerVariant?: string }, diff --git a/app/games/card-rat/index.js b/app/games/card-rat/index.js index 56be5a02..c6d941f6 100644 --- a/app/games/card-rat/index.js +++ b/app/games/card-rat/index.js @@ -222,7 +222,6 @@ export function updateTrendChart() { export function renderCard(card) { if (!_cardEl) return; - _cardEl.classList.remove('card-rat__card--cleared'); const label = getCardLabel(card); _cardEl.setAttribute('aria-label', `Current card: ${label}`); @@ -319,21 +318,15 @@ export function beginDealLoop() { } /** - * Clear the table after the last card of a pass, then pause before shuffling. + * Shuffle a fresh deck after the last card of a pass, pausing before the shuffle starts. * - * The status area reads "Shuffling" until the next deal replaces it. + * 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; - const { missedTrigger } = game.shuffleForNextPass(); - if (missedTrigger) { - playFailureSound(); - } - if (_cardEl) { - _cardEl.classList.add('card-rat__card--cleared'); - _cardEl.setAttribute('aria-label', 'No card showing'); - } + game.shuffleForNextPass(); if (_feedbackEl) _feedbackEl.textContent = 'Shuffling'; updateStats(); diff --git a/app/games/card-rat/style.css b/app/games/card-rat/style.css index bbbc08b8..4a46013c 100644 --- a/app/games/card-rat/style.css +++ b/app/games/card-rat/style.css @@ -62,11 +62,6 @@ transform: rotate(-8deg); } -/* The table is empty while the deck is shuffled between passes. */ -.card-rat__card--cleared { - visibility: hidden; -} - .card-rat__card--deck.card-rat__card--shuffling { animation: card-rat-shuffle 0.3s ease-in-out 4; } diff --git a/app/games/card-rat/tests/game.test.js b/app/games/card-rat/tests/game.test.js index dbae6f8d..51f4946d 100644 --- a/app/games/card-rat/tests/game.test.js +++ b/app/games/card-rat/tests/game.test.js @@ -535,41 +535,50 @@ describe('deal and response flow', () => { expect(flags.filter(Boolean)).toHaveLength(1); }); - test('shuffleForNextPass starts a new pass with no card showing', () => { + test('shuffleForNextPass starts a new pass and leaves the last card current', () => { startGame(); + let last = null; for (let i = 0; i < getDeckSize(); i += 1) { - dealNextCard(); + last = dealNextCard().card; } - expect(shuffleForNextPass()).toEqual({ missedTrigger: false, deckPasses: 1 }); + expect(shuffleForNextPass()).toBe(1); expect(getDeckIndex()).toBe(0); expect(getDeckPasses()).toBe(1); - expect(getCurrentCard()).toBeNull(); - expect(shouldReactNow()).toBe(false); - expect(respondToCurrentCard()).toBe('ignored'); - expect(getFalseAlarms()).toBe(0); + expect(getCurrentCard()).toBe(last); }); - test('shuffleForNextPass scores an unslapped trigger as a miss', () => { + test('a slap during the shuffle scores against the last card as usual', () => { startGame(); expect(dealUntilTrigger()).toBe(true); + shuffleForNextPass(); - expect(shuffleForNextPass().missedTrigger).toBe(true); - expect(getMisses()).toBe(1); + expect(respondToCurrentCard()).toBe('hit'); + expect(respondToCurrentCard()).toBe('ignored'); + expect(getTriggerHits()).toBe(1); }); - test('a slap on the first card after a shuffle is not a late slap', () => { + test('a false alarm during the shuffle counts as usual', () => { startGame(); - expect(dealUntilTrigger()).toBe(true); + dealNextCard(); + expect(shouldReactNow()).toBe(false); shuffleForNextPass(); - const { card, mustReact } = dealNextCard(); - expect(card.isJoker).toBe(false); - expect(mustReact).toBe(false); 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 never pairs with the last card before it', () => { + 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) { @@ -582,7 +591,7 @@ describe('deal and response flow', () => { const next = dealNextCard(); expect(next.card).toEqual(last); - expect(next.mustReact).toBe(false); + expect(next.mustReact).toBe(true); }); test('shuffleForNextPass throws when the game is not running', () => { diff --git a/app/games/card-rat/tests/index.test.js b/app/games/card-rat/tests/index.test.js index a208d47f..4b1d7982 100644 --- a/app/games/card-rat/tests/index.test.js +++ b/app/games/card-rat/tests/index.test.js @@ -82,7 +82,7 @@ jest.unstable_mockModule('../game.js', () => ({ deckIndex: 1, deckPasses: 0, })), - shuffleForNextPass: jest.fn(() => ({ missedTrigger: false, deckPasses: 1 })), + shuffleForNextPass: jest.fn(() => 1), respondToCurrentCard: jest.fn(() => 'hit'), getScore: jest.fn(() => 3), getTriggerHits: jest.fn(() => 2), @@ -610,8 +610,8 @@ describe('shuffling between deck passes', () => { expect(gameMock.shuffleForNextPass).toHaveBeenCalledTimes(1); expect(gameMock.dealNextCard).not.toHaveBeenCalled(); expect(container.querySelector('#cr-feedback').textContent).toBe('Shuffling'); - expect(container.querySelector('#cr-card').classList.contains('card-rat__card--cleared')) - .toBe(true); + 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 () => { @@ -620,7 +620,6 @@ describe('shuffling between deck passes', () => { gameMock.dealNextCard.mockReturnValueOnce(LAST_CARD_DEAL); await plugin.start(); const deckCard = container.querySelector('#cr-deck-card'); - const card = container.querySelector('#cr-card'); jest.advanceTimersByTime(1200); jest.advanceTimersByTime(499); @@ -635,17 +634,19 @@ describe('shuffling between deck passes', () => { jest.advanceTimersByTime(1); expect(gameMock.dealNextCard).toHaveBeenCalledTimes(1); expect(deckCard.classList.contains('card-rat__card--shuffling')).toBe(false); - expect(card.classList.contains('card-rat__card--cleared')).toBe(false); expect(container.querySelector('#cr-feedback').textContent).not.toBe('Shuffling'); }); - test('beginShuffle plays the failure sound when the last card was a missed trigger', () => { - plugin.init(buildContainer()); - gameMock.shuffleForNextPass.mockReturnValueOnce({ missedTrigger: true, deckPasses: 1 }); - + 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', () => { From 545eb7476118240b481fd6126b82ed741905e517 Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 22:09:52 -0400 Subject: [PATCH 4/8] Give the shuffle sound a smoother texture Replace the separate noise clicks with continuous softened noise whose level flutters smoothly, quickly at first and slower as the last cards fall, through a low-pass filter instead of a band-pass filter. Refs #198 Co-Authored-By: Claude Opus 5.5 --- app/components/CLAUDE.md | 4 +- app/components/audioService.js | 94 +++++++++++++---------- app/components/tests/audioService.test.js | 33 ++++---- 3 files changed, 74 insertions(+), 57 deletions(-) diff --git a/app/components/CLAUDE.md b/app/components/CLAUDE.md index a643dfa2..7d0f78ee 100644 --- a/app/components/CLAUDE.md +++ b/app/components/CLAUDE.md @@ -70,8 +70,8 @@ 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 from noise clicks, then a soft swish. It lasts - `SHUFFLE_SOUND_DURATION_S`. +- `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. diff --git a/app/components/audioService.js b/app/components/audioService.js index 42652711..094ac380 100644 --- a/app/components/audioService.js +++ b/app/components/audioService.js @@ -108,35 +108,48 @@ const CARD_FLIP_ATTACK_S = 0.002; // ── Deck shuffle sound constants ────────────────────────────────────────────── -/** Number of card clicks in the riffle (about half a deck, as the halves interleave). */ -const SHUFFLE_RIFFLE_CLICKS = 28; +/** Duration (s) of the riffle, while the two halves fall together. */ +const SHUFFLE_RIFFLE_DURATION_S = 0.75; -/** Duration (s) of the riffle, from the first card click to the last. */ -const SHUFFLE_RIFFLE_DURATION_S = 0.7; +/** + * 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; /** - * Largest random shift of each click, as a fraction of the click spacing. - * The unevenness keeps the riffle from sounding like a mechanical ticker. + * 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_CLICK_JITTER = 0.4; +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; -/** Decay time constant (s) of each click. Each click lasts five time constants. */ -const SHUFFLE_CLICK_DECAY_S = 0.004; +/** + * 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.35; /** Duration (s) of the soft swish as the riffled halves are pushed together. */ -const SHUFFLE_BRIDGE_DURATION_S = 0.25; +const SHUFFLE_BRIDGE_DURATION_S = 0.3; -/** Loudness of the bridge swish relative to a click. */ -const SHUFFLE_BRIDGE_LEVEL = 0.35; +/** Loudness of the bridge swish relative to the riffle. */ +const SHUFFLE_BRIDGE_LEVEL = 0.6; -/** Center frequency (Hz) of the band-pass filter that gives the clicks a papery tone. */ -const SHUFFLE_FILTER_FREQ_HZ = 2500; +/** Cutoff frequency (Hz) of the low-pass filter that takes the edge off the noise. */ +const SHUFFLE_FILTER_FREQ_HZ = 3000; -/** Q of the shuffle band-pass filter. A low Q keeps the band wide. */ -const SHUFFLE_FILTER_Q = 0.7; +/** 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.12; +const SHUFFLE_PEAK_GAIN = 0.25; /** 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; @@ -388,40 +401,43 @@ export function playCardFlickSound() { /** * Write the shuffle waveform into a sample buffer. * - * The riffle is a run of short, decaying noise clicks spread unevenly over - * SHUFFLE_RIFFLE_DURATION_S, one per card falling. A softer noise swish - * follows, rising and falling over SHUFFLE_BRIDGE_DURATION_S. + * 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 riffleEnd = Math.floor(SHUFFLE_RIFFLE_DURATION_S * sampleRate); - const clickSpacingS = SHUFFLE_RIFFLE_DURATION_S / SHUFFLE_RIFFLE_CLICKS; - const decaySamples = SHUFFLE_CLICK_DECAY_S * sampleRate; - const clickLength = Math.ceil(decaySamples * 5); - - for (let k = 0; k < SHUFFLE_RIFFLE_CLICKS; k += 1) { - const jitterS = (Math.random() - 0.5) * SHUFFLE_CLICK_JITTER * clickSpacingS; - const start = Math.max(0, Math.round((k * clickSpacingS + jitterS) * sampleRate)); - for (let i = 0; i < clickLength && start + i < riffleEnd; i += 1) { - channelData[start + i] += (Math.random() * 2 - 1) * Math.exp(-i / decaySamples); + 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; } } - - const bridgeLength = channelData.length - riffleEnd; - for (let i = 0; i < bridgeLength; i += 1) { - const envelope = Math.sin((Math.PI * i) / bridgeLength); - channelData[riffleEnd + i] = (Math.random() * 2 - 1) * SHUFFLE_BRIDGE_LEVEL * envelope; - } } /** - * Play a synthesized deck-shuffling sound: a riffle of card clicks, then the + * 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 band-pass filter, so no audio file is needed. It lasts + * through a low-pass filter, so no audio file is needed. It lasts * SHUFFLE_SOUND_DURATION_S. * * Uses the shared AudioContext from {@link getAudioContext}. @@ -445,7 +461,7 @@ export function playShuffleSound() { source.buffer = buffer; const filter = ctx.createBiquadFilter(); - filter.type = 'bandpass'; + filter.type = 'lowpass'; filter.frequency.setValueAtTime(SHUFFLE_FILTER_FREQ_HZ, now); filter.Q.setValueAtTime(SHUFFLE_FILTER_Q, now); diff --git a/app/components/tests/audioService.test.js b/app/components/tests/audioService.test.js index 509ace84..eca3e833 100644 --- a/app/components/tests/audioService.test.js +++ b/app/components/tests/audioService.test.js @@ -545,39 +545,40 @@ describe('playShuffleSound', () => { restore(); }); - test('fills the buffer with riffle clicks and a bridge swish', () => { + test('fills the buffer with a smooth riffle and a bridge swish', () => { const { mockCtx, restore } = useMockContext(); - // 0.75 makes every noise sample 0.5 and shifts every click by the same jitter. + // 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 spacing = Math.round(44100 * (0.7 / 28)); - const firstClick = Math.round(44100 * 0.25 * 0.4 * (0.7 / 28)); - const riffleEnd = Math.floor(44100 * 0.7); - // Silence before the first click, a full-level onset, and a gap before the next click. - expect(samples[firstClick - 1]).toBe(0); - expect(samples[firstClick]).toBeCloseTo(0.5); - expect(samples[firstClick + spacing - 1]).toBe(0); - // The bridge swish rises from silence to a peak below the clicks. - const bridge = samples.subarray(riffleEnd); + 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.35, 3); + expect(Math.max(...bridge)).toBeCloseTo(0.5 * 0.6, 3); randomSpy.mockRestore(); restore(); }); - test('routes the noise through a band-pass filter', () => { + 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('bandpass'); - expect(filter.frequency.setValueAtTime).toHaveBeenCalledWith(2500, 0); - expect(filter.Q.setValueAtTime).toHaveBeenCalledWith(0.7, 0); + expect(filter.type).toBe('lowpass'); + expect(filter.frequency.setValueAtTime).toHaveBeenCalledWith(3000, 0); + expect(filter.Q.setValueAtTime).toHaveBeenCalledWith(0.5, 0); restore(); }); From a33e22ac8f0bdecbb7cab95033a583fb320f2a3a Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 22:09:52 -0400 Subject: [PATCH 5/8] Add a sound harness for hearing audio service sounds alone npm run sound-harness opens a separate Electron window with a button for each play* function in audioService.js that takes no arguments, so a sound can be heard and tuned without playing a game. It lives in scripts/, which Forge does not package. Refs #198 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 + app/components/CLAUDE.md | 4 +- eslint.config.js | 9 ++++ package.json | 1 + scripts/sound-harness/harness.css | 10 ++++ scripts/sound-harness/harness.js | 62 +++++++++++++++++++++++++ scripts/sound-harness/harness.test.js | 66 +++++++++++++++++++++++++++ scripts/sound-harness/index.html | 18 ++++++++ scripts/sound-harness/main.js | 35 ++++++++++++++ 9 files changed, 206 insertions(+), 1 deletion(-) create mode 100644 scripts/sound-harness/harness.css create mode 100644 scripts/sound-harness/harness.js create mode 100644 scripts/sound-harness/harness.test.js create mode 100644 scripts/sound-harness/index.html create mode 100644 scripts/sound-harness/main.js diff --git a/CLAUDE.md b/CLAUDE.md index 99f0c27d..7cf93fb0 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 with a button per audioService sound, to hear one alone ``` 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 7d0f78ee..d7b7a0c9 100644 --- a/app/components/CLAUDE.md +++ b/app/components/CLAUDE.md @@ -77,7 +77,9 @@ where Web Audio is missing. Every sound resumes a suspended context and swallows 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/`) +shows a button for every exported `play*` function that takes no arguments, so a new sound +can be heard and tuned without playing a game. ## `syllableService.js` 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..e42f3ec9 --- /dev/null +++ b/scripts/sound-harness/harness.css @@ -0,0 +1,10 @@ +/* Sound harness layout. Buttons use the app's shared .game-btn styles. */ + +#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..2e5bccfc --- /dev/null +++ b/scripts/sound-harness/harness.js @@ -0,0 +1,62 @@ +/** + * harness.js — Page script for the sound test harness. + * + * Builds one button per sound effect that audioService.js exports. A sound + * effect is any exported `play*` function that takes no arguments, so a new + * sound shows up here without changes to the harness. + * + * @file Sound harness page. + */ +import * as audio from '../../app/components/audioService.js'; + +/** + * 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 Object.keys(soundModule) + .filter((key) => key.startsWith('play') + && typeof soundModule[key] === 'function' + && soundModule[key].length === 0) + .sort(); +} + +/** + * 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 words.charAt(0).toUpperCase() + words.slice(1); +} + +/** + * Add a play button to the list for each sound effect in the module. + * + * @param {HTMLElement|null} listEl - The `

      ` to fill. + * @param {Record} soundModule + */ +export function renderSoundButtons(listEl, soundModule) { + if (!listEl) return; + + listSoundEffects(soundModule).forEach((exportName) => { + const item = document.createElement('li'); + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'game-btn game-btn--primary'; + button.textContent = getSoundLabel(exportName); + button.addEventListener('click', () => soundModule[exportName]()); + item.appendChild(button); + listEl.appendChild(item); + }); +} + +renderSoundButtons(document.querySelector('#sound-list'), audio); diff --git a/scripts/sound-harness/harness.test.js b/scripts/sound-harness/harness.test.js new file mode 100644 index 00000000..d2b96baa --- /dev/null +++ b/scripts/sound-harness/harness.test.js @@ -0,0 +1,66 @@ +/** + * harness.test.js - Unit tests for the sound harness page script. + */ +import { + jest, + describe, + test, + expect, +} from '@jest/globals'; + +const { listSoundEffects, getSoundLabel, renderSoundButtons } = await import('./harness.js'); + +/** + * Build a stand-in for audioService.js with sounds, a sound that needs arguments, and a helper. + * + * @returns {Record} + */ +function buildSoundModule() { + return { + playShuffleSound: jest.fn(() => {}), + playCardFlickSound: jest.fn(() => {}), + playSweepPair: (sequence, options) => [sequence, options], + getAudioContext: () => null, + SWEEP_LOW_FREQ_HZ: 300, + }; +} + +describe('listSoundEffects', () => { + test('lists only play functions that take no arguments, sorted', () => { + expect(listSoundEffects(buildSoundModule())).toEqual([ + 'playCardFlickSound', + 'playShuffleSound', + ]); + }); + + test('finds the shuffle sound in the real audio service', async () => { + const audio = await import('../../app/components/audioService.js'); + expect(listSoundEffects(audio)).toContain('playShuffleSound'); + }); +}); + +describe('getSoundLabel', () => { + test('drops the play prefix and Sound suffix and splits the words', () => { + expect(getSoundLabel('playCardFlickSound')).toBe('Card flick'); + expect(getSoundLabel('playShuffleSound')).toBe('Shuffle'); + }); +}); + +describe('renderSoundButtons', () => { + test('adds one button per sound that plays it when clicked', () => { + const list = document.createElement('ul'); + const sounds = buildSoundModule(); + + renderSoundButtons(list, sounds); + + const buttons = list.querySelectorAll('li > button'); + expect(Array.from(buttons, (button) => button.textContent)).toEqual(['Card flick', 'Shuffle']); + buttons[1].click(); + expect(sounds.playShuffleSound).toHaveBeenCalledTimes(1); + expect(sounds.playCardFlickSound).not.toHaveBeenCalled(); + }); + + test('does nothing without a list element', () => { + expect(() => renderSoundButtons(null, buildSoundModule())).not.toThrow(); + }); +}); diff --git a/scripts/sound-harness/index.html b/scripts/sound-harness/index.html new file mode 100644 index 00000000..5e977660 --- /dev/null +++ b/scripts/sound-harness/index.html @@ -0,0 +1,18 @@ + + + + + + Sound Harness + + + + + +
      +

      Sound Harness

      +

      Play each sound effect from audioService.js on its own.

      +
        +
        + + diff --git a/scripts/sound-harness/main.js b/scripts/sound-harness/main.js new file mode 100644 index 00000000..08da5770 --- /dev/null +++ b/scripts/sound-harness/main.js @@ -0,0 +1,35 @@ +/** + * main.js — Electron entry point for the sound test harness. + * + * Opens one window with a button for each sound effect in + * app/components/audioService.js, so a sound can be heard without playing a + * game. Run it with `npm run sound-harness`. Forge does not package scripts/. + * + * @file Sound harness main process. + */ +import { app, BrowserWindow } from 'electron'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** Directory holding this harness's files. */ +const HARNESS_DIR = path.dirname(fileURLToPath(import.meta.url)); + +/** + * Open the harness window. + */ +function createWindow() { + const win = new BrowserWindow({ + width: 520, + height: 600, + title: 'Sound Harness', + webPreferences: { + nodeIntegration: false, + contextIsolation: true, + sandbox: true, + }, + }); + win.loadFile(path.join(HARNESS_DIR, 'index.html')); +} + +app.whenReady().then(createWindow); +app.on('window-all-closed', () => app.quit()); From b805c453ed567b258795b53ed78bb64fcca64f91 Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 22:16:06 -0400 Subject: [PATCH 6/8] Make the shuffle sound quieter and less hissy Lower its gain from 0.25 to 0.15, and darken the noise: a stronger one-pole smoothing (0.35 to 0.2) and a lower low-pass cutoff (3000 Hz to 2000 Hz) cut the white-noise hiss. Refs #198 Co-Authored-By: Claude Opus 5.5 --- app/components/audioService.js | 6 +++--- app/components/tests/audioService.test.js | 12 +++++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/app/components/audioService.js b/app/components/audioService.js index 094ac380..a9797f4a 100644 --- a/app/components/audioService.js +++ b/app/components/audioService.js @@ -134,7 +134,7 @@ 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.35; +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; @@ -143,13 +143,13 @@ const SHUFFLE_BRIDGE_DURATION_S = 0.3; 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 = 3000; +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.25; +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; diff --git a/app/components/tests/audioService.test.js b/app/components/tests/audioService.test.js index eca3e833..ee2202c0 100644 --- a/app/components/tests/audioService.test.js +++ b/app/components/tests/audioService.test.js @@ -577,11 +577,21 @@ describe('playShuffleSound', () => { const filter = mockCtx.createBiquadFilter.mock.results[0].value; expect(filter.type).toBe('lowpass'); - expect(filter.frequency.setValueAtTime).toHaveBeenCalledWith(3000, 0); + 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'); From b607c940e73c7cd50d53c7b03e3134ff2e2d6bb9 Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 22:16:06 -0400 Subject: [PATCH 7/8] Let the sound harness play every audio service sound Add presets for the sounds that need arguments: success and failure through playFeedbackSound, and all four playSweepPair sequences, with inputs for the sweep length and gap. A test fails if the audio service exports a play* function the harness cannot play. Refs #198 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- app/components/CLAUDE.md | 5 +- scripts/sound-harness/harness.css | 23 ++++ scripts/sound-harness/harness.js | 155 ++++++++++++++++++++++---- scripts/sound-harness/harness.test.js | 145 ++++++++++++++++++++++-- scripts/sound-harness/index.html | 13 ++- 6 files changed, 308 insertions(+), 35 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7cf93fb0..329f5d14 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,7 +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 with a button per audioService sound, to hear one alone +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. diff --git a/app/components/CLAUDE.md b/app/components/CLAUDE.md index d7b7a0c9..949ce632 100644 --- a/app/components/CLAUDE.md +++ b/app/components/CLAUDE.md @@ -78,8 +78,9 @@ where Web Audio is missing. Every sound resumes a suspended context and swallows Add new sounds here, with their tuning values as named constants at the top of the file. Speech sounds go in `syllableService.js` instead. `npm run sound-harness` (in `scripts/sound-harness/`) -shows a button for every exported `play*` function that takes no arguments, so a new sound -can be heard and tuned without playing a game. +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`; `harness.test.js` fails until it has one. ## `syllableService.js` diff --git a/scripts/sound-harness/harness.css b/scripts/sound-harness/harness.css index e42f3ec9..978ee6c1 100644 --- a/scripts/sound-harness/harness.css +++ b/scripts/sound-harness/harness.css @@ -1,5 +1,28 @@ /* 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; diff --git a/scripts/sound-harness/harness.js b/scripts/sound-harness/harness.js index 2e5bccfc..17cd90c8 100644 --- a/scripts/sound-harness/harness.js +++ b/scripts/sound-harness/harness.js @@ -1,14 +1,67 @@ /** * harness.js — Page script for the sound test harness. * - * Builds one button per sound effect that audioService.js exports. A sound - * effect is any exported `play*` function that takes no arguments, so a new - * sound shows up here without changes to the 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; `listUncoveredSounds` names any that are missing, and the + * harness test fails until a preset 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); +} + +/** + * 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([ + { exportName: 'playFeedbackSound', label: 'Feedback: success', getArgs: () => [true] }, + { exportName: 'playFeedbackSound', label: 'Feedback: failure', getArgs: () => [false] }, + ...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. * @@ -16,11 +69,19 @@ import * as audio from '../../app/components/audioService.js'; * @returns {string[]} Export names, such as `playShuffleSound`, sorted. */ export function listSoundEffects(soundModule) { - return Object.keys(soundModule) - .filter((key) => key.startsWith('play') - && typeof soundModule[key] === 'function' - && soundModule[key].length === 0) - .sort(); + return listPlayFunctions(soundModule).filter((key) => soundModule[key].length === 0); +} + +/** + * List the sounds that need arguments but have no preset, 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)); } /** @@ -35,28 +96,82 @@ export function getSoundLabel(exportName) { .replace(/Sound$/, '') .replace(/([a-z])([A-Z])/g, '$1 $2') .toLowerCase(); - return words.charAt(0).toUpperCase() + words.slice(1); + 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; } /** - * Add a play button to the list for each sound effect in the module. + * 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 `
          ` to fill. * @param {Record} soundModule + * @param {() => { sweepDurationMs: number, isiMs: number }} [readSettings] - Called on each + * click, so preset buttons use the current inputs. */ -export function renderSoundButtons(listEl, soundModule) { +export function renderSoundButtons( + listEl, + soundModule, + readSettings = () => DEFAULT_SWEEP_SETTINGS, +) { if (!listEl) return; listSoundEffects(soundModule).forEach((exportName) => { - const item = document.createElement('li'); - const button = document.createElement('button'); - button.type = 'button'; - button.className = 'game-btn game-btn--primary'; - button.textContent = getSoundLabel(exportName); - button.addEventListener('click', () => soundModule[exportName]()); - item.appendChild(button); - listEl.appendChild(item); + addButton(listEl, getSoundLabel(exportName), () => soundModule[exportName]()); }); + + SOUND_PRESETS + .filter((preset) => typeof soundModule[preset.exportName] === 'function') + .forEach((preset) => { + addButton(listEl, preset.label, () => { + soundModule[preset.exportName](...preset.getArgs(readSettings())); + }); + }); } -renderSoundButtons(document.querySelector('#sound-list'), audio); +renderSoundButtons(document.querySelector('#sound-list'), audio, () => readSweepSettings(document)); diff --git a/scripts/sound-harness/harness.test.js b/scripts/sound-harness/harness.test.js index d2b96baa..33f73eae 100644 --- a/scripts/sound-harness/harness.test.js +++ b/scripts/sound-harness/harness.test.js @@ -8,10 +8,20 @@ import { expect, } from '@jest/globals'; -const { listSoundEffects, getSoundLabel, renderSoundButtons } = await import('./harness.js'); +const { + DEFAULT_SWEEP_SETTINGS, + SOUND_PRESETS, + listSoundEffects, + listUncoveredSounds, + getSoundLabel, + readSweepSettings, + renderSoundButtons, +} = await import('./harness.js'); +const audio = await import('../../app/components/audioService.js'); /** - * Build a stand-in for audioService.js with sounds, a sound that needs arguments, and a helper. + * Build a stand-in for audioService.js with sounds that take no arguments, sounds that + * need them, and a helper that is not a sound. * * @returns {Record} */ @@ -19,12 +29,47 @@ function buildSoundModule() { return { playShuffleSound: jest.fn(() => {}), playCardFlickSound: jest.fn(() => {}), - playSweepPair: (sequence, options) => [sequence, options], + playFeedbackSound: jest.fn((isSuccess) => isSuccess), + playSweepPair: jest.fn((sequence, options) => [sequence, options]), getAudioContext: () => null, SWEEP_LOW_FREQ_HZ: 300, }; } +/** + * Build sweep timing inputs like the ones in index.html. + * + * @param {string} duration - Value of the sweep length input. + * @param {string} isi - Value of the gap input. + * @returns {HTMLElement} + */ +function buildSettings(duration, isi) { + const root = document.createElement('div'); + root.innerHTML = ` + + + `; + return root; +} + +describe('the real audio service', () => { + test('every sound it exports has a harness button', () => { + expect(listUncoveredSounds(audio)).toEqual([]); + expect(listSoundEffects(audio)).toEqual(expect.arrayContaining([ + 'playCardFlickSound', + 'playFailureSound', + 'playShuffleSound', + 'playSuccessSound', + ])); + }); + + test('every preset names a function the service exports', () => { + SOUND_PRESETS.forEach((preset) => { + expect(typeof audio[preset.exportName]).toBe('function'); + }); + }); +}); + describe('listSoundEffects', () => { test('lists only play functions that take no arguments, sorted', () => { expect(listSoundEffects(buildSoundModule())).toEqual([ @@ -32,10 +77,12 @@ describe('listSoundEffects', () => { 'playShuffleSound', ]); }); +}); - test('finds the shuffle sound in the real audio service', async () => { - const audio = await import('../../app/components/audioService.js'); - expect(listSoundEffects(audio)).toContain('playShuffleSound'); +describe('listUncoveredSounds', () => { + test('names a sound that needs arguments and has no preset', () => { + const sounds = { ...buildSoundModule(), playChordSound: (notes) => notes }; + expect(listUncoveredSounds(sounds)).toEqual(['playChordSound']); }); }); @@ -46,20 +93,96 @@ describe('getSoundLabel', () => { }); }); +describe('readSweepSettings', () => { + test('reads whole milliseconds from the inputs', () => { + expect(readSweepSettings(buildSettings('80', '40.4'))).toEqual({ + sweepDurationMs: 80, + isiMs: 40, + }); + }); + + test('falls back to the defaults for missing, empty, or non-positive values', () => { + expect(readSweepSettings(document.createElement('div'))).toEqual(DEFAULT_SWEEP_SETTINGS); + expect(readSweepSettings(buildSettings('', '0'))).toEqual(DEFAULT_SWEEP_SETTINGS); + }); +}); + describe('renderSoundButtons', () => { - test('adds one button per sound that plays it when clicked', () => { + test('adds the no-argument sounds first, then the presets', () => { const list = document.createElement('ul'); - const sounds = buildSoundModule(); + renderSoundButtons(list, buildSoundModule()); + + const labels = Array.from(list.querySelectorAll('li > button'), (b) => b.textContent); + expect(labels).toEqual([ + 'Card flick', + 'Shuffle', + 'Feedback: success', + 'Feedback: failure', + 'Sweeps: Up-Up', + 'Sweeps: Up-Down', + 'Sweeps: Down-Up', + 'Sweeps: Down-Down', + ]); + }); + + test('a no-argument button plays only its own sound', () => { + const list = document.createElement('ul'); + const sounds = buildSoundModule(); renderSoundButtons(list, sounds); - const buttons = list.querySelectorAll('li > button'); - expect(Array.from(buttons, (button) => button.textContent)).toEqual(['Card flick', 'Shuffle']); - buttons[1].click(); + list.querySelectorAll('button')[1].click(); + expect(sounds.playShuffleSound).toHaveBeenCalledTimes(1); expect(sounds.playCardFlickSound).not.toHaveBeenCalled(); }); + test('preset buttons pass their arguments and read the sweep timing on each click', () => { + const list = document.createElement('ul'); + const sounds = buildSoundModule(); + const readSettings = jest.fn() + .mockReturnValueOnce({ sweepDurationMs: 600, isiMs: 600 }) + .mockReturnValue({ sweepDurationMs: 20, isiMs: 10 }); + renderSoundButtons(list, sounds, readSettings); + const byLabel = (label) => Array.from(list.querySelectorAll('button')) + .find((button) => button.textContent === label); + + byLabel('Sweeps: Up-Down').click(); + byLabel('Sweeps: Down-Down').click(); + byLabel('Feedback: failure').click(); + + expect(sounds.playFeedbackSound).toHaveBeenCalledWith(false); + expect(sounds.playSweepPair).toHaveBeenNthCalledWith( + 1, + ['up', 'down'], + { sweepDurationMs: 600, isiMs: 600 }, + ); + expect(sounds.playSweepPair).toHaveBeenNthCalledWith( + 2, + ['down', 'down'], + { sweepDurationMs: 20, isiMs: 10 }, + ); + }); + + test('uses the default sweep timing without a settings reader', () => { + const list = document.createElement('ul'); + const sounds = buildSoundModule(); + renderSoundButtons(list, sounds); + + Array.from(list.querySelectorAll('button')) + .find((button) => button.textContent === 'Sweeps: Up-Up') + .click(); + + expect(sounds.playSweepPair).toHaveBeenCalledWith(['up', 'up'], DEFAULT_SWEEP_SETTINGS); + }); + + test('skips presets for sounds the module does not export', () => { + const list = document.createElement('ul'); + renderSoundButtons(list, { playShuffleSound: () => {} }); + + expect(list.querySelectorAll('button')).toHaveLength(1); + }); + test('does nothing without a list element', () => { expect(() => renderSoundButtons(null, buildSoundModule())).not.toThrow(); }); diff --git a/scripts/sound-harness/index.html b/scripts/sound-harness/index.html index 5e977660..b8352d45 100644 --- a/scripts/sound-harness/index.html +++ b/scripts/sound-harness/index.html @@ -11,7 +11,18 @@

          Sound Harness

          -

          Play each sound effect from audioService.js on its own.

          +

          Play each sound from audioService.js on its own.

          +
          + Sweep timing + + +
            From 05b9ea59bc2a902de8cba88d1f8bfad1e6c4ab76 Mon Sep 17 00:00:00 2001 From: Aaron Crosman Date: Sat, 24 Oct 2026 22:19:58 -0400 Subject: [PATCH 8/8] Give each sound one harness button playFeedbackSound only calls playSuccessSound or playFailureSound, so its two buttons repeated the Success and Failure buttons. SOUND_WRAPPERS now lists it as a wrapper, which gets no buttons of its own; the harness test checks that each wrapper's sounds have buttons. Refs #198 Co-Authored-By: Claude Opus 5.5 --- app/components/CLAUDE.md | 3 ++- scripts/sound-harness/harness.js | 24 ++++++++++++++++++------ scripts/sound-harness/harness.test.js | 19 ++++++++++++++----- 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/app/components/CLAUDE.md b/app/components/CLAUDE.md index 949ce632..e8963db1 100644 --- a/app/components/CLAUDE.md +++ b/app/components/CLAUDE.md @@ -80,7 +80,8 @@ Add new sounds here, with their tuning values as named constants at the top of t 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`; `harness.test.js` fails until it has one. +`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/scripts/sound-harness/harness.js b/scripts/sound-harness/harness.js index 17cd90c8..55becee6 100644 --- a/scripts/sound-harness/harness.js +++ b/scripts/sound-harness/harness.js @@ -4,8 +4,9 @@ * 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; `listUncoveredSounds` names any that are missing, and the - * harness test fails until a preset is added. + * 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. */ @@ -30,6 +31,16 @@ 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}. @@ -41,8 +52,6 @@ function capitalize(word) { * }>} */ export const SOUND_PRESETS = Object.freeze([ - { exportName: 'playFeedbackSound', label: 'Feedback: success', getArgs: () => [true] }, - { exportName: 'playFeedbackSound', label: 'Feedback: failure', getArgs: () => [false] }, ...SWEEP_SEQUENCES.map((sequence) => ({ exportName: 'playSweepPair', label: `Sweeps: ${sequence.map(capitalize).join('-')}`, @@ -73,7 +82,8 @@ export function listSoundEffects(soundModule) { } /** - * List the sounds that need arguments but have no preset, so the harness cannot play them. + * 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. @@ -81,7 +91,9 @@ export function listSoundEffects(soundModule) { 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)); + .filter((key) => soundModule[key].length > 0 + && !presetNames.has(key) + && !Object.hasOwn(SOUND_WRAPPERS, key)); } /** diff --git a/scripts/sound-harness/harness.test.js b/scripts/sound-harness/harness.test.js index 33f73eae..5bc609c0 100644 --- a/scripts/sound-harness/harness.test.js +++ b/scripts/sound-harness/harness.test.js @@ -11,6 +11,7 @@ import { const { DEFAULT_SWEEP_SETTINGS, SOUND_PRESETS, + SOUND_WRAPPERS, listSoundEffects, listUncoveredSounds, getSoundLabel, @@ -63,6 +64,14 @@ describe('the real audio service', () => { ])); }); + test('every wrapper only chooses between sounds that have their own buttons', () => { + const buttonSounds = listSoundEffects(audio); + Object.entries(SOUND_WRAPPERS).forEach(([wrapper, sounds]) => { + expect(typeof audio[wrapper]).toBe('function'); + expect(buttonSounds).toEqual(expect.arrayContaining(sounds)); + }); + }); + test('every preset names a function the service exports', () => { SOUND_PRESETS.forEach((preset) => { expect(typeof audio[preset.exportName]).toBe('function'); @@ -80,6 +89,10 @@ describe('listSoundEffects', () => { }); describe('listUncoveredSounds', () => { + test('skips wrappers, which have no buttons of their own', () => { + expect(listUncoveredSounds(buildSoundModule())).toEqual([]); + }); + test('names a sound that needs arguments and has no preset', () => { const sounds = { ...buildSoundModule(), playChordSound: (notes) => notes }; expect(listUncoveredSounds(sounds)).toEqual(['playChordSound']); @@ -117,8 +130,6 @@ describe('renderSoundButtons', () => { expect(labels).toEqual([ 'Card flick', 'Shuffle', - 'Feedback: success', - 'Feedback: failure', 'Sweeps: Up-Up', 'Sweeps: Up-Down', 'Sweeps: Down-Up', @@ -137,7 +148,7 @@ describe('renderSoundButtons', () => { expect(sounds.playCardFlickSound).not.toHaveBeenCalled(); }); - test('preset buttons pass their arguments and read the sweep timing on each click', () => { + test('sweep buttons pass their sequence and read the sweep timing on each click', () => { const list = document.createElement('ul'); const sounds = buildSoundModule(); const readSettings = jest.fn() @@ -149,9 +160,7 @@ describe('renderSoundButtons', () => { byLabel('Sweeps: Up-Down').click(); byLabel('Sweeps: Down-Down').click(); - byLabel('Feedback: failure').click(); - expect(sounds.playFeedbackSound).toHaveBeenCalledWith(false); expect(sounds.playSweepPair).toHaveBeenNthCalledWith( 1, ['up', 'down'],