Animation · project 34 of 37
Silly Sound Squad.
A silly speech game that listens: four friends teach TH, F, V and S, the child's own voice blows bubbles and feeds them, and every try gets a cheer and a playful tip.
BeforeA speech worksheet for TH, F, V and S: say each word ten times, and a four-year-old who runs away when he hears "practice".
AfterFour silly friends, one per sound, a game that hears him, and a cheer plus a playful tip on every try.
What it is worthPractice between therapy sessions that he asks for, with every sound modeled correctly. Instead of drills, "say it again" and "no, not like that".
How to use it
- Press Tap to start with the volume up (it plays even when an iPhone is on silent) and tap Allow so the friends can hear him. Then Play, and hand it over: it runs as one loop and nobody has to find the next game.
- The first time, sit with him for the mouth mirror: the big mouth shows each step slowly (tongue peeks out, bunny teeth on the lip, buzzy motor, teeth together and hiss), then it is his turn and the friend cheers.
- In 👪 For grown-ups, tick only this week's sounds; the friends for those sounds take turns.
- Whenever the listener misses (it cannot tell TH from F, and for V it only hears that he used his voice), tap 👍 Said it right. Without a microphone, the game shows tap buttons instead.
- Let him press 🤪 and 💃 as often as he likes: the giant puppy, the toots and the dance party are the reward that brings him back tomorrow.
Where it helps most
- Play practice for a child of three to six working on TH, F, V or S, at home on a tablet or phone with a grown-up nearby.
- A pattern for any speech-sound game: one character per sound, show the mouth, let the child's own voice drive the fun, and turn every miss into a friend's sound plus one tip.
- A worked example of on-device voice analysis in a web page, with an honest list of what a microphone can and cannot tell.
The idea
Some young children find TH, F, V and S hard to say. A first TH game did not work: it talked at the child and never heard them. I wanted something a child would beg to play, where practice is a side effect of being silly, that answers the child's own voice with cheers and a gentle tip, never a buzzer, and that a grown-up can point at this week's sounds.
The build
Claude rebuilt it from scratch as one web page: four SVG characters with idle and action animations, an animated mouth that shows each step of each sound, six stations in a loop that never goes back to a menu, costumes, a freeze-dance party, jokes and a silly button. The listener is new: the microphone is analysed on the device frame by frame (loudness, low/mid/high bands, zero crossings, spectral flatness, centroid). For a word, it finds the vowel and measures the hiss beside it: how long, how loud against the vowel, how flat (S is a narrow, sharp hiss; TH and F are soft and spread), and how abruptly it starts (a T or D is a burst, not a hiss). On recorded test sets it sorted 161 of 164 TH tries and 141 of 148 S, F and V tries correctly. The narrator is Kokoro's free "Heart" voice made bouncier (the WORLD vocoder stretches its melody and lifts its pitch), and each friend speaks in its own cartoon voice (a different Kokoro voice, pitched up and shrunk). Every target word and friend's name inside a narrator line is a separately checked take that is never pitch-shifted, because shifting turned "thumb" into "some": Whisper must hear the word, a TH must measure as a TH and not an S, and the game's own listener must call each take what it should be. Honest limits: it cannot tell TH from F (they sound almost the same), for V it only checks that it heard a voice, it was tested on recorded voices and not yet on a child, and it is play practice, not therapy. A grown-up's "Said it right" button covers every miss. Nothing is saved or sent. It also plays on an iPhone set to silent.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
# Master prompt: Silly Sound Squad
You are a children's game designer, a speech-sound coach and a creative coder. Build "Silly Sound Squad": a narrated web game for a 4-year-old practising TH, F, V and S. The child learns as a side effect of playing; nothing ever feels like a test. One page (HTML, CSS, JavaScript, inline SVG, Web Audio), no frameworks, no reading needed, works on an iPad and an iPhone.
CHARACTERS (one per sound, using common mouth cues)
- Thunder the puppy, TH: the tongue peeks out, then a soft breeze.
- Fifi the bunny, F: bunny teeth on the bottom lip, then blow softly.
- Vinny the race car, V: bunny teeth on the lip, then turn on the buzzy motor (the lip tickles).
- Sunny the snake, S: smile, teeth together, tongue hiding, a happy hiss.
Draw each as a round, friendly SVG with an idle bob, ear wiggle and an "action" state that shows the sound (tongue out, air puffs, spinning wheels, a flicking snake tongue). Costumes are a hat and a held item.
ONE LOOP, NEVER BACK TO A MENU
Play runs six stations per friend, then the next friend (only the sounds a grown-up ticks for this week): 1 a knocking door that opens on the friend, 2 a mouth mirror (a big animated mouth shows each step, slowly, with pauses, then "Your turn!"), 3 a power game his own sound drives (Thunder blows bubbles, Fifi blows out birthday candles, Vinny races to the flag, Sunny fills a balloon), 4 Who said it? (hear a word, tap the friend whose sound it starts with), 5 Feed the friend (three picture words: model, his turn, the food flies into the friend's mouth with a chomp), 6 a present with a new costume, a freeze-dance party with the whole squad and a joke. A trail of six icons shows where he is; it remembers where he stopped. Silly button: a giant puppy rises from the hills, a toot, a honk.
LISTENING (the microphone, analysed on the device, never saved or sent)
- getUserMedia with echo cancellation, noise suppression and auto gain off; a ScriptProcessor feeds 1024-sample frames.
- Per frame: level, low/mid/high band energy, zero crossings, spectral flatness, centroid. Live kinds: soft hiss (TH/F: flat, spread), sharp hiss (S: flatness under 0.25 and loud), voice, buzz.
- Per word take: track the room's noise floor, find the vowel (first long voiced run for a first sound, last for a last sound), measure the hiss next to it (length, loudness against the vowel, flatness, centroid, how abruptly it starts) and call it soft, sharp, pop (T, P, D: under 40 ms or a burst), voice or quiet.
- Wait 250 ms after the narrator stops before recording (speaker echo), stop 650 ms after he goes quiet, ignore the mic while the narrator talks, ask again once if he started before the listening did.
- It cannot tell TH from F, and for V it only checks it heard a voice: say so to grown-ups, and show a "Said it right" button for four seconds after any miss.
SILLY ON PURPOSE
Googly eyes that blink and follow the finger, a squash-and-stretch bounce, a random trick on every tap (spin, jelly wobble, flip, boing, eye-pop, squish) with a giggle, comic WOW/YAY/KA-POW bursts and a kazoo fanfare on every win, a sun in sunglasses, clouds with faces, dancing flowers, a rainbow, silly visitors wandering across (a cow on a balloon, a running chicken, a UFO), a bouncy background tune that goes silent whenever the game is listening.
ALWAYS POSITIVE
Another sound is never wrong: it is another friend's sound ("Hee hee! That was Sunny's snake hiss. For Thunder, let your tongue peek out"), and that friend pops in to wave. One tip, then "Let's do it together, slowly" with a slow model; after two tries the friend eats the word anyway and the child still gets a star. Praise like "Yes! Good job!", with the child's name if a grown-up typed one.
VOICE THAT MODELS EVERY SOUND CORRECTLY
Pre-record every line with Kokoro af_heart (misaki US phonemes). Every target word and every friend's name inside a line is a separately checked take: Whisper must hear the word, TH takes must measure as a quiet spread hiss and not an S (splice a synthesized TH when needed), and the game's own listener must call each take what it should be (F/TH soft, S sharp, V voice). Cut Kokoro's stray first sound with a hidden "Okay." before each line. One voice channel; it never talks over itself. Captions always show the line. Make the narrator excited, not flat: exaggerate the pitch swings about two times and lift the pitch about two semitones with the WORLD vocoder (a little less for instructions, which also go slower). Give each friend its own cartoon voice that speaks its own lines (hello, giggle when tapped, cheer, yum, bye): a different Kokoro voice, pitched up four to nine semitones with the formants shrunk; keep the strength Whisper still understands. Never pitch-shift a target word: splice the checked, natural take.
SOUND ON IPHONE
Set navigator.audioSession.type to "playback" on the first tap ("play-and-record" while the mic is on), loop a silent same-origin MP3 on older iPhones, resume the AudioContext on every tap and on return to the page.
GROWN-UPS PANEL
Name, this week's sounds, microphone on/off with its state, a backup device voice, what the listener can and cannot tell, privacy, start over.
FINISH AND TEST
No inline script or style (strict security policy), local Fredoka font. Test at 320x568, 393x700, 740x360 and 1366x800; play whole rounds in Chromium with a recorded word as the fake microphone (right sound, another friend's sound, a stop, silence) and with taps only; check no screen overflows and nothing stalls.
Get the code15 files, exactly as they run on this site · free under the MIT license
The first three files are exactly what runs at sghadimi.com/sounds, with the three Fredoka font files in fonts/ (SIL Open Font License) and 189 voice clips in audio/. The kit is the source, the listener on its own, the voice pipeline that made and checked the clips (Kokoro af_heart, misaki, Whisper base.en through sherpa-onnx) and the two browser tests; kit/README.txt gives the order. Without the clips, every line still shows as a caption and the device voice reads it.
sounds.js (the whole game, the listener and the list of voice clips)669 lines
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const shuffle=a=>{for(let i=a.length-1;i>0;i--){const j=Math.random()*(i+1)|0;[a[i],a[j]]=[a[j],a[i]]}return a};
const pick=a=>a[Math.random()*a.length|0];
const store={get(k,d){try{const v=localStorage.getItem('squad1_'+k);return v==null?d:JSON.parse(v)}catch(e){return d}},set(k,v){try{localStorage.setItem('squad1_'+k,JSON.stringify(v))}catch(e){}}};
const state={stars:store.get('stars',0),stickers:store.get('stickers',[]),name:store.get('name',''),voiceName:store.get('voice',null),music:store.get('music',true),
sounds:store.get('sounds',['th','f','v','s']),micWanted:store.get('mic',true)};
const J=Object.assign({round:0,station:0,joke:0,costume:0,lastCostume:{}},store.get('journey',{}));
const saveJ=()=>store.set('journey',J);
/* ---------- THE SILLY SOUND SQUAD ---------- */
// Each friend shows the mouth for its sound: Thunder's tongue peeks out (TH), Fifi's teeth sit on her lip (F),
// Vinny the race car has buck teeth on his bumper-lip and a buzzy motor (V), Sunny smiles with her teeth together (S).
function puppySVG(){return `<svg class="ch ch-th" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="188" rx="52" ry="8" fill="#0002"/>
<path class="ear l" d="M50 50 C18 58 16 124 40 132 C58 124 64 88 64 64Z" fill="#8b5a2b"/>
<path class="ear r" d="M150 50 C182 58 184 124 160 132 C142 124 136 88 136 64Z" fill="#8b5a2b"/>
<ellipse cx="100" cy="170" rx="44" ry="20" fill="#e9b46a"/>
<circle cx="100" cy="96" r="62" fill="#f2c27b"/>
<ellipse cx="129" cy="78" rx="22" ry="19" fill="#d99a4e" opacity=".55"/>
<ellipse cx="100" cy="124" rx="37" ry="28" fill="#fbe3bd"/>
<g class="eyes"><circle cx="78" cy="82" r="15" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="122" cy="82" r="15" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="78" cy="83" r="8" fill="#2b2b3a"/><circle cx="80.8" cy="79.8" r="2.6" fill="#fff"/><circle cx="122" cy="83" r="8" fill="#2b2b3a"/><circle cx="124.8" cy="79.8" r="2.6" fill="#fff"/></g><ellipse class="lid" cx="78" cy="82" rx="16.5" ry="16.5" fill="#f2c27b"/><ellipse class="lid" cx="122" cy="82" rx="16.5" ry="16.5" fill="#f2c27b"/></g>
<ellipse cx="100" cy="109" rx="13" ry="9" fill="#2b2b3a"/><ellipse cx="96" cy="106" rx="4" ry="2.4" fill="#fff" opacity=".6"/>
<path d="M82 125 Q100 138 118 125" stroke="#2b2b3a" stroke-width="4" fill="none" stroke-linecap="round"/>
<g class="tg"><path d="M89 129 Q100 166 111 129 Z" fill="#ff7a9a" stroke="#d9546f" stroke-width="2"/><path d="M100 132 L100 148" stroke="#d9546f" stroke-width="2"/></g>
<ellipse cx="62" cy="120" rx="10" ry="6" fill="#ff9aa8" opacity=".6"/><ellipse cx="138" cy="120" rx="10" ry="6" fill="#ff9aa8" opacity=".6"/>
<g class="puff"><path d="M126 150 q14 -4 24 4" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/><path d="M130 166 q16 -2 28 8" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/></g>
</g></svg>`}
function bunnySVG(){return `<svg class="ch ch-f" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="190" rx="50" ry="8" fill="#0002"/>
<g class="ear l"><ellipse cx="70" cy="42" rx="17" ry="46" fill="#e9dcff"/><ellipse cx="70" cy="46" rx="8" ry="34" fill="#ffb3c7"/></g>
<g class="ear r"><ellipse cx="130" cy="42" rx="17" ry="46" fill="#e9dcff"/><ellipse cx="130" cy="46" rx="8" ry="34" fill="#ffb3c7"/></g>
<ellipse cx="100" cy="172" rx="42" ry="20" fill="#e2d4fb"/>
<circle cx="100" cy="112" r="58" fill="#f3ecff"/>
<g class="eyes"><circle cx="78" cy="98" r="14" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="122" cy="98" r="14" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="78" cy="99" r="7.5" fill="#2b2b3a"/><circle cx="80.625" cy="96.0" r="2.4" fill="#fff"/><circle cx="122" cy="99" r="7.5" fill="#2b2b3a"/><circle cx="124.625" cy="96.0" r="2.4" fill="#fff"/></g><ellipse class="lid" cx="78" cy="98" rx="15.5" ry="15.5" fill="#f3ecff"/><ellipse class="lid" cx="122" cy="98" rx="15.5" ry="15.5" fill="#f3ecff"/></g>
<path d="M93 116 L107 116 L100 124 Z" fill="#ff8fb1"/>
<path d="M100 124 Q92 132 84 128 M100 124 Q108 132 116 128" stroke="#2b2b3a" stroke-width="3" fill="none" stroke-linecap="round"/>
<path d="M84 144 Q100 152 116 144" stroke="#ff8fb1" stroke-width="7" fill="none" stroke-linecap="round"/>
<rect x="89" y="127" width="11" height="17" rx="3" fill="#fff" stroke="#c9c4d6" stroke-width="2"/><rect x="100" y="127" width="11" height="17" rx="3" fill="#fff" stroke="#c9c4d6" stroke-width="2"/>
<path d="M58 118 L30 112 M58 124 L28 126 M142 118 L170 112 M142 124 L172 126" stroke="#b9b1c9" stroke-width="2" stroke-linecap="round"/>
<ellipse cx="66" cy="132" rx="9" ry="5.5" fill="#ff9aa8" opacity=".55"/><ellipse cx="134" cy="132" rx="9" ry="5.5" fill="#ff9aa8" opacity=".55"/>
<g class="puff"><path d="M120 150 q14 -4 24 4" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/><path d="M124 166 q16 -2 28 8" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/></g>
</g></svg>`}
function carSVG(){return `<svg class="ch ch-v" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="186" rx="76" ry="9" fill="#0002"/>
<path d="M50 96 Q58 52 100 50 Q142 52 150 96 Z" fill="#ff5252"/>
<path d="M62 94 Q68 62 100 60 Q132 62 138 94 Z" fill="#bfe9ff" stroke="#fff" stroke-width="3"/>
<g class="eyes"><circle cx="85" cy="77" r="12.5" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="115" cy="77" r="12.5" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="85" cy="78" r="6.5" fill="#2b2b3a"/><circle cx="87.275" cy="75.4" r="2.1" fill="#fff"/><circle cx="115" cy="78" r="6.5" fill="#2b2b3a"/><circle cx="117.275" cy="75.4" r="2.1" fill="#fff"/></g><ellipse class="lid" cx="85" cy="77" rx="14.0" ry="14.0" fill="#bfe9ff"/><ellipse class="lid" cx="115" cy="77" rx="14.0" ry="14.0" fill="#bfe9ff"/></g>
<rect x="22" y="92" width="156" height="66" rx="26" fill="#ff3b3b"/>
<rect x="30" y="98" width="140" height="10" rx="5" fill="#ff7b7b"/>
<text x="100" y="128" text-anchor="middle" font-size="18" font-weight="700" fill="#fff" font-family="Fredoka">V</text>
<circle cx="44" cy="124" r="11" fill="#ffe27a" stroke="#fff" stroke-width="3"/><circle cx="156" cy="124" r="11" fill="#ffe27a" stroke="#fff" stroke-width="3"/>
<path d="M64 146 Q100 160 136 146" stroke="#2b2b3a" stroke-width="10" fill="none" stroke-linecap="round"/>
<rect x="88" y="132" width="11" height="15" rx="3" fill="#fff" stroke="#ccc" stroke-width="2"/><rect x="101" y="132" width="11" height="15" rx="3" fill="#fff" stroke="#ccc" stroke-width="2"/>
<g class="wheel"><circle cx="54" cy="164" r="20" fill="#2b2b3a"/><circle cx="54" cy="164" r="8" fill="#ccc"/><path d="M54 150 L54 178 M40 164 L68 164" stroke="#888" stroke-width="3"/></g>
<g class="wheel w2"><circle cx="146" cy="164" r="20" fill="#2b2b3a"/><circle cx="146" cy="164" r="8" fill="#ccc"/><path d="M146 150 L146 178 M132 164 L160 164" stroke="#888" stroke-width="3"/></g>
<g class="puff"><path d="M176 104 l12 -6 M180 118 l14 0 M176 132 l12 6" stroke="#ffb300" stroke-width="5" stroke-linecap="round"/></g>
</g></svg>`}
function snakeSVG(){return `<svg class="ch ch-s" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="190" rx="66" ry="8" fill="#0002"/>
<ellipse cx="100" cy="170" rx="70" ry="20" fill="#5cc96b"/><ellipse cx="100" cy="166" rx="56" ry="9" fill="#ffe27a" opacity=".8"/>
<ellipse cx="100" cy="140" rx="54" ry="18" fill="#6fd57c"/><ellipse cx="100" cy="137" rx="42" ry="7" fill="#ffe27a" opacity=".8"/>
<path d="M80 128 Q76 100 100 96 Q124 100 120 128 Z" fill="#6fd57c"/>
<circle cx="100" cy="78" r="44" fill="#7ee08a"/>
<circle cx="80" cy="54" r="6" fill="#5cc96b"/><circle cx="118" cy="50" r="5" fill="#5cc96b"/><circle cx="104" cy="40" r="4" fill="#5cc96b"/>
<g class="eyes"><circle cx="84" cy="66" r="13" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="116" cy="66" r="13" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="84" cy="67" r="7" fill="#2b2b3a"/><circle cx="86.45" cy="64.2" r="2.2" fill="#fff"/><circle cx="116" cy="67" r="7" fill="#2b2b3a"/><circle cx="118.45" cy="64.2" r="2.2" fill="#fff"/></g><ellipse class="lid" cx="84" cy="66" rx="14.5" ry="14.5" fill="#7ee08a"/><ellipse class="lid" cx="116" cy="66" rx="14.5" ry="14.5" fill="#7ee08a"/></g>
<path d="M72 88 Q100 112 128 88 Z" fill="#2b2b3a"/>
<rect x="78" y="88" width="44" height="9" rx="3" fill="#fff"/><path d="M80 92.5 L120 92.5" stroke="#d6d6d6" stroke-width="1.5"/>
<g class="flick"><path d="M100 104 L100 116 L95 122 M100 116 L105 122" stroke="#ff4d6d" stroke-width="3" fill="none" stroke-linecap="round"/></g>
<ellipse cx="66" cy="84" rx="8" ry="5" fill="#ff9aa8" opacity=".6"/><ellipse cx="134" cy="84" rx="8" ry="5" fill="#ff9aa8" opacity=".6"/>
<g class="puff"><path d="M136 100 q12 -6 22 -2 M138 112 q14 -2 24 4" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/></g>
</g></svg>`}
const SQUAD={
th:{key:'th',name:'Thunder',animal:'puppy',icon:'🐶',svg:puppySVG,color:'#f2a64a',pose:'thAir',rest:'th',want:'soft',her:'him',
steps:[['open','Open wide, just a tiny bit.'],['th','Let your tongue peek out, like a puppy tongue!'],['thAir','Now blow softly, like a little breeze.']],
words:[['thumb','👍','I'],['three','3️⃣','I'],['think','🤔','I'],['thunder','⛈️','I'],['bath','🛁','F'],['teeth','🦷','F'],['mouth','👄','F']],
game:'bubbles'},
f:{key:'f',name:'Fifi',animal:'bunny',icon:'🐰',svg:bunnySVG,color:'#a98bff',pose:'f',rest:'fRest',want:'soft',her:'her',
steps:[['fRest','Make bunny teeth! Put them on your bottom lip.'],['f','Now blow softly, like a little breeze.']],
words:[['fish','🐟','I'],['fan','🪭','I'],['feet','🦶','I'],['fox','🦊','I'],['fork','🍴','I'],['five','5️⃣','I']],
game:'candles'},
v:{key:'v',name:'Vinny',animal:'race car',icon:'🏎️',svg:carSVG,color:'#ff4d4d',pose:'v',rest:'fRest',want:'voice',her:'him',
steps:[['fRest','Make bunny teeth! Put them on your bottom lip.'],['v','Now turn on your motor, and make it buzz. Your lip will tickle!']],
words:[['van','🚐','V'],['vase','🏺','V'],['violin','🎻','V'],['volcano','🌋','V']],
game:'race'},
s:{key:'s',name:'Sunny',animal:'snake',icon:'🐍',svg:snakeSVG,color:'#3fbf74',pose:'s',rest:'sRest',want:'sharp',her:'her',
steps:[['smile','Smile big, and put your teeth together.'],['sRest','Keep your tongue hiding inside.'],['s','Now let the air hiss out, like a happy snake.']],
words:[['sun','☀️','I'],['sock','🧦','I'],['soap','🧼','I'],['soup','🍲','I'],['six','6️⃣','I'],['sandwich','🥪','I']],
game:'balloon'}};
const COSTUMES=[['Super','🦸','⚡'],['Pirate','🏴☠️','🦜'],['Space','👩🚀','🚀'],['Wizard','🧙','🪄'],['Chef','👨🍳','🍕'],['Firefighter','🚒','🧯'],['Rock Star','🎸','🎤']];
const HATS={Super:'🦸',Pirate:'🏴☠️',Space:'🪐',Wizard:'🎩',Chef:'🍳',Firefighter:'⛑️','Rock Star':'👑'};
function charHTML(k,extra=''){return `<div class="chwrap ${extra}" data-ch="${k}">${SQUAD[k].svg()}<span class="hat"></span><span class="hold"></span></div>`}
function dress(el,costume){const h=el.querySelector('.hat'),o=el.querySelector('.hold');if(!h)return;if(!costume){h.textContent='';o.textContent='';return}
const c=COSTUMES.find(x=>x[0]===costume);h.textContent=HATS[costume]||'';o.textContent=c?c[2]:''}
function act(el,on){if(el)el.classList.toggle('act',!!on)}
function hop(el){if(!el)return;el.classList.remove('hop');void el.offsetWidth;el.classList.add('hop')}
/* ---------- AUDIO ---------- */
let AC=null,master=null,musicGain=null,voiceGain=null,whooshNode=null,noiseBuf=null,speaking=false;
/* iPhone: Web Audio is muted by the silent switch unless the page asks for "playback" audio. */
let silentEl=null;
function iosUnlock(){try{const want=(typeof mic!=='undefined'&&mic.state==='on')?'play-and-record':'playback';if(navigator.audioSession&&navigator.audioSession.type!==want)navigator.audioSession.type=want}catch(e){}
if(!('audioSession' in navigator)){try{if(!silentEl){silentEl=new Audio('audio/silence.mp3');silentEl.loop=true;silentEl.setAttribute('playsinline','')}const p=silentEl.play();if(p&&p.catch)p.catch(()=>{})}catch(e){}}}
function wake(){iosUnlock();if(AC&&AC.state!=='running'){try{const p=AC.resume();if(p&&p.catch)p.catch(()=>{})}catch(e){}}}
['pointerdown','touchend','click','keydown'].forEach(ev=>document.addEventListener(ev,wake,{passive:true,capture:true}));
document.addEventListener('visibilitychange',()=>{if(!document.hidden)wake()});
function initAudio(){iosUnlock();if(AC){wake();return}try{AC=new(window.AudioContext||window.webkitAudioContext)();try{AC.resume()}catch(e){}master=AC.createGain();master.gain.value=.5;master.connect(AC.destination);musicGain=AC.createGain();musicGain.gain.value=.6;musicGain.connect(master);voiceGain=AC.createGain();voiceGain.gain.value=1.7;voiceGain.connect(AC.destination)}catch(e){AC=null}}
function tone(f,d,type='sine',v=.2,when=0,slide,dest){if(!AC)return;const t=AC.currentTime+when,o=AC.createOscillator(),g=AC.createGain();o.type=type;o.frequency.setValueAtTime(f,t);if(slide)o.frequency.exponentialRampToValueAtTime(slide,t+d);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(v,t+.015);g.gain.exponentialRampToValueAtTime(.0001,t+d);o.connect(g);g.connect(dest||master);o.start(t);o.stop(t+d+.05)}
const sfx={chime(){[523,659,784,1047].forEach((f,i)=>tone(f,.4,'triangle',.17,i*.09))},pop(){tone(760,.16,'sine',.22,0,260)},boing(){tone(330,.45,'sine',.2,0,130)},hop(){tone(380,.16,'square',.05,0,820)},tap(){tone(900,.07,'sine',.1)},
fanfare(){[392,523,659,784,659,784,1047].forEach((f,i)=>tone(f,.32,'triangle',.17,i*.13))},
drum(){for(let i=0;i<14;i++)tone(140+i*6,.06,'triangle',.12+i*.008,i*.07)},
rimshot(){tone(200,.12,'square',.12);tone(900,.25,'triangle',.12,.12);tone(1300,.35,'triangle',.08,.16)},
silly(){tone(500,.18,'sine',.18,0,900);tone(900,.18,'sine',.18,.18,400);tone(400,.3,'sine',.18,.36,700)},
slide(){tone(300,.5,'sine',.15,0,1200)},
sparkle(){[1319,1568,2093,2637].forEach((f,i)=>tone(f,.25,'sine',.08,i*.06))},
bloop(){tone(180,.35,'sine',.3,0,520);tone(520,.25,'sine',.15,.3,260)},
scratch(){tone(900,.35,'sawtooth',.08,0,90)},
slideUp(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='sine';o.frequency.setValueAtTime(400,t);o.frequency.exponentialRampToValueAtTime(1600,t+.5);l.frequency.value=12;lg.gain.value=25;l.connect(lg);lg.connect(o.frequency);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.16,t+.03);g.gain.exponentialRampToValueAtTime(.001,t+.55);o.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.6);l.stop(t+.6)},
slideDown(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain();o.type='sine';o.frequency.setValueAtTime(1400,t);o.frequency.exponentialRampToValueAtTime(300,t+.6);g.gain.setValueAtTime(.15,t);g.gain.exponentialRampToValueAtTime(.001,t+.65);o.connect(g);g.connect(master);o.start(t);o.stop(t+.7)},
boing2(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='triangle';o.frequency.value=220;l.frequency.setValueAtTime(18,t);l.frequency.exponentialRampToValueAtTime(4,t+.6);lg.gain.setValueAtTime(120,t);lg.gain.exponentialRampToValueAtTime(5,t+.6);l.connect(lg);lg.connect(o.frequency);g.gain.setValueAtTime(.22,t);g.gain.exponentialRampToValueAtTime(.001,t+.65);o.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.7);l.stop(t+.7)},
kazoo(){if(!AC)return;[523,659,784,1047,784,1047].forEach((f,i)=>{const t=AC.currentTime+i*.12,o=AC.createOscillator(),bp=AC.createBiquadFilter(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='sawtooth';o.frequency.value=f;l.frequency.value=7;lg.gain.value=f*.02;l.connect(lg);lg.connect(o.frequency);bp.type='bandpass';bp.frequency.value=1400;bp.Q.value=2;g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.12,t+.02);g.gain.exponentialRampToValueAtTime(.001,t+(i===5?.5:.16));o.connect(bp);bp.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.55);l.stop(t+.55)})},
honk2(){tone(330,.16,'square',.1);tone(262,.25,'square',.1,.18)},
chomp(){noiseHit(.07,900,'bandpass',.5);noiseHit(.07,900,'bandpass',.5,.16);tone(220,.1,'square',.06,0,120)},
toot(){tone(110,.55,'sawtooth',.16,0,70);tone(95,.5,'square',.06,.05,60)},
honk(){tone(392,.22,'square',.12);tone(330,.3,'square',.12,.26)}};
function noiseHit(dur,freq,type,v,when=0){if(!AC)return;if(!noiseBuf){noiseBuf=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);const d=noiseBuf.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1}
const t=AC.currentTime+when,s=AC.createBufferSource();s.buffer=noiseBuf;const f=AC.createBiquadFilter();f.type=type;f.frequency.value=freq;const g=AC.createGain();g.gain.setValueAtTime(v,t);g.gain.exponentialRampToValueAtTime(.0001,t+dur);s.connect(f);f.connect(g);g.connect(master);s.start(t,Math.random());s.stop(t+dur+.02)}
let beatTimer=null,beatStep=0;const BASS=[110,0,110,0,131,0,98,0,110,0,110,0,147,0,131,0],ARP=[523,659,784,659,587,698,880,698];
function kick(){if(!AC)return;const t=AC.currentTime,o=AC.createOscillator(),g=AC.createGain();o.frequency.setValueAtTime(150,t);o.frequency.exponentialRampToValueAtTime(45,t+.15);g.gain.setValueAtTime(.55,t);g.gain.exponentialRampToValueAtTime(.001,t+.2);o.connect(g);g.connect(master);o.start(t);o.stop(t+.22)}
function beatStart(){initAudio();if(!AC||beatTimer)return;beatStep=0;beatTimer=setInterval(()=>{const s=beatStep%16;if(s%4===0)kick();if(s===4||s===12)noiseHit(.13,1800,'highpass',.3);if(s%2===0)noiseHit(.03,7000,'highpass',.09);if(BASS[s])tone(BASS[s],.2,'square',.06);if(s%2===1)tone(ARP[(beatStep>>1)%8],.13,'triangle',.06);beatStep++},125)}
function beatStop(){clearInterval(beatTimer);beatTimer=null}
function whoosh(on){if(!AC)return;const now=AC.currentTime;if(on){if(whooshNode)return;if(!noiseBuf){noiseBuf=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);const d=noiseBuf.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1}
const s=AC.createBufferSource();s.buffer=noiseBuf;s.loop=true;const f=AC.createBiquadFilter();f.type='highpass';f.frequency.value=1200;f.Q.value=.5;const g=AC.createGain();g.gain.setValueAtTime(0,now);g.gain.linearRampToValueAtTime(.1,now+.25);s.connect(f);f.connect(g);g.connect(master);s.start();whooshNode={s,g}}
else if(whooshNode){const{s,g}=whooshNode;g.gain.cancelScheduledValues(now);g.gain.setValueAtTime(g.gain.value,now);g.gain.linearRampToValueAtTime(0,now+.25);s.stop(now+.3);whooshNode=null}}
function whooshPuff(ms){whoosh(true);setTimeout(()=>whoosh(false),ms)}
let musicTimer=null,mStep=0;const GROOVE=[523,0,659,0,784,0,659,784,880,0,784,0,659,0,587,0,523,0,659,0,784,0,1047,0,988,0,880,0,784,659,587,0],BASS2=[131,131,175,175,196,196,131,196];const MEL=[523,659,784,659,587,698,880,698,523,659,784,1047,880,784,659,587];
function setMusic(on){state.music=on;$('#musicBtn').classList.toggle('off',!on);clearInterval(musicTimer);musicTimer=null;if(on){initAudio();if(!AC)return;duck(speaking);musicTimer=setInterval(()=>{const s=mStep++%32,f=GROOVE[s];if(f)tone(f,.16,'triangle',.07,0,null,musicGain);if(s%4===0)tone(BASS2[(s>>2)%8],.22,'triangle',.09,0,null,musicGain);if(s%8===4)tone(1800,.03,'square',.012,0,null,musicGain)},190)}}
function duck(on){if(!musicGain||!AC)return;const e=document.getElementById('ear');const lis=(e&&e.classList.contains('on'))||(typeof mic!=='undefined'&&mic.rec);musicGain.gain.setTargetAtTime(lis?0:(on?.12:.5),AC.currentTime,.08)}
/* ---------- VOICE: Kokoro Heart clips, never overlapping ---------- */
let voice=null;
function enVoices(){if(!('speechSynthesis' in window))return[];return speechSynthesis.getVoices().filter(v=>/^en([-_]|$)/i.test(v.lang))}
function pickVoice(){const en=enVoices();if(!en.length)return;if(state.voiceName){const v=en.find(v=>v.name===state.voiceName);if(v){voice=v;return}}
const sc=v=>{let s=0;if(/en[-_]US/i.test(v.lang))s+=3;if(/premium/i.test(v.name))s+=7;if(/enhanced|neural|natural/i.test(v.name))s+=5;if(/Ava|Samantha|Allison|Aria|Jenny|Google US English/i.test(v.name))s+=3;if(/Albert|Bad News|Bahh|Bells|Boing|Bubbles|Cellos|Wobble|Zarvox|Trinoids|Whisper|Jester|Organ|Superstar|Fred|Ralph|Junior|Grandma|Grandpa|Rocko|Good News/i.test(v.name))s-=20;return s};
voice=en.slice().sort((a,b)=>sc(b)-sc(a))[0]}
function fillVoiceSel(){const sel=$('#voiceSel');const en=enVoices();sel.innerHTML=en.map(v=>`<option value="${v.name.replace(/"/g,'"')}">${v.name} (${v.lang})</option>`).join('')||'<option>Default voice</option>';if(voice)sel.value=voice.name}
if('speechSynthesis' in window){speechSynthesis.onvoiceschanged=()=>{pickVoice();fillVoiceSel()};pickVoice()}
function setCaption(t){$('#cap').textContent=t}
const CLIPS={"open wide just a tiny bit": "366e7e8a92.mp3", "let your tongue peek out like a puppy tongue": "bc497ca990.mp3", "now blow softly like a little breeze": "6e02f3efdc.mp3", "w:thumb": "be868afff3.mp3", "slow:thumb": "0770c1fe60.mp3", "your turn say thumb": "4eda773f21.mp3", "w:three": "54f7f97599.mp3", "slow:three": "659ab9f0e7.mp3", "your turn say three": "fc3ed7cf89.mp3", "w:think": "d588c62718.mp3", "slow:think": "659b75e53c.mp3", "your turn say think": "04a37d6fe7.mp3", "w:thunder": "d14cad4b10.mp3", "slow:thunder": "b103dc271b.mp3", "your turn say thunder": "b230c1027e.mp3", "w:bath": "b1bfb698e1.mp3", "slow:bath": "ee65d6f86b.mp3", "your turn say bath": "a3549cc069.mp3", "w:teeth": "1d711a2f5f.mp3", "slow:teeth": "f97e6f1ec1.mp3", "your turn say teeth": "c7e35ce3f5.mp3", "w:mouth": "ac736979b3.mp3", "slow:mouth": "573fbab9ac.mp3", "your turn say mouth": "952c954836.mp3", "it's thunder the puppy thunder's sound has a peeking tongue like in thumb": "d19a11610e.mp3", "your turn make thunder's sound": "4f55a6ae7d.mp3", "woohoo that's thunder's sound": "28cf63ca23.mp3", "thunder loves bubbles make thunder's sound to blow bubbles keep going": "b175749f70.mp3", "look at all those bubbles thunder is so happy": "d303b1d123.mp3", "thunder is hungry say each word to feed him": "d1b402d329.mp3", "you found thunder": "e7e8942ecc.mp3", "ta da it's super thunder": "0ad02d0602.mp3", "ta da it's pirate thunder": "385e8b9d94.mp3", "ta da it's space thunder": "8e3cfc0bd5.mp3", "ta da it's wizard thunder": "ca567fd41c.mp3", "ta da it's chef thunder": "5822552e06.mp3", "ta da it's firefighter thunder": "fb090d6335.mp3", "ta da it's rock star thunder": "35d16341e3.mp3", "bye bye thunder who's next": "71d983132c.mp3", "make bunny teeth put them on your bottom lip": "6a507440fb.mp3", "w:fish": "e606954544.mp3", "slow:fish": "4721ff2d46.mp3", "your turn say fish": "f879f58145.mp3", "w:fan": "01475a9ede.mp3", "slow:fan": "6da44e3ebb.mp3", "your turn say fan": "229020cae8.mp3", "w:feet": "c8b88c2d9e.mp3", "slow:feet": "f4bc85da4c.mp3", "your turn say feet": "68232706a8.mp3", "w:fox": "0d3c39d6bc.mp3", "slow:fox": "dbd73fe4a5.mp3", "your turn say fox": "a61bd4e6a7.mp3", "w:fork": "1d6e9dde95.mp3", "slow:fork": "de13eb1454.mp3", "your turn say fork": "d798fc5c51.mp3", "w:five": "04ebd423c4.mp3", "slow:five": "449dcbe297.mp3", "your turn say five": "2117c0e42a.mp3", "it's fifi the bunny fifi's sound has bunny teeth like in fish": "3379b10785.mp3", "your turn make fifi's sound": "af878b4d7e.mp3", "hooray that's fifi's sound": "bdc31816bd.mp3", "fifi has a party cake make fifi's sound to blow out the candles": "5ba57420dc.mp3", "you blew out all the candles hooray for fifi": "8b8bfa5849.mp3", "fifi is hungry say each word to feed her": "d2cf3a3cdf.mp3", "you found fifi": "663e9dfadd.mp3", "ta da it's super fifi": "cc5df5f983.mp3", "ta da it's pirate fifi": "258c249c99.mp3", "ta da it's space fifi": "4fe6feff41.mp3", "ta da it's wizard fifi": "05bac0f8d2.mp3", "ta da it's chef fifi": "0ea9a3e14b.mp3", "ta da it's firefighter fifi": "934068d3ca.mp3", "ta da it's rock star fifi": "ce7a5e8eaa.mp3", "bye bye fifi who's next": "28c9c55a0c.mp3", "now turn on your motor and make it buzz your lip will tickle": "3cf00bac19.mp3", "w:van": "c42e8fb1be.mp3", "slow:van": "b08cfdd8d4.mp3", "your turn say van": "00cad95a48.mp3", "w:vase": "de519e077d.mp3", "slow:vase": "137d1b614c.mp3", "your turn say vase": "df6f5ffba1.mp3", "w:violin": "0b54fa5687.mp3", "slow:violin": "9bf0a189a7.mp3", "your turn say violin": "1426c72ad9.mp3", "w:volcano": "9a9a001af1.mp3", "slow:volcano": "e048f4ef6e.mp3", "your turn say volcano": "849756ae45.mp3", "it's vinny the race car vinny's sound is a buzzy motor like in van": "be87fa3010.mp3", "your turn make vinny's motor sound": "81a1f82476.mp3", "yippee that's vinny's sound": "eb4ed3a895.mp3", "help vinny win the race make vinny's motor sound to drive keep going": "99eb7e65b9.mp3", "vinny wins the race hooray": "4c9860eb70.mp3", "vinny needs fuel say each word to fill him up": "19008f0500.mp3", "you found vinny": "8c1e3ff92d.mp3", "ta da it's super vinny": "eff4ea5c7a.mp3", "ta da it's pirate vinny": "bc938393af.mp3", "ta da it's space vinny": "10ba8b4059.mp3", "ta da it's wizard vinny": "712ecc74fb.mp3", "ta da it's chef vinny": "513d1dde64.mp3", "ta da it's firefighter vinny": "c52d4a26e5.mp3", "ta da it's rock star vinny": "d79055be34.mp3", "bye bye vinny who's next": "4f73317bba.mp3", "smile big and put your teeth together": "ba8ddb359f.mp3", "keep your tongue hiding inside": "393d2b6de5.mp3", "now let the air hiss out like a happy snake": "024f0db743.mp3", "w:sun": "31234f0b9d.mp3", "slow:sun": "fa3b4a0692.mp3", "your turn say sun": "93ccf1ebf5.mp3", "w:sock": "6ca5215f78.mp3", "slow:sock": "7e30f3666e.mp3", "your turn say sock": "1ac3d10398.mp3", "w:soap": "c7f57800fb.mp3", "slow:soap": "490698060e.mp3", "your turn say soap": "87828d2eb8.mp3", "w:soup": "070fd95c24.mp3", "slow:soup": "0a9f7d7d7a.mp3", "your turn say soup": "cfc7aad5ec.mp3", "w:six": "c14739374c.mp3", "slow:six": "641571012c.mp3", "your turn say six": "57d747d0be.mp3", "w:sandwich": "6ace1d926c.mp3", "slow:sandwich": "8f05c2f49c.mp3", "your turn say sandwich": "816c62a2a7.mp3", "it's sunny the snake sunny's sound is a happy hiss like in sun": "b6e8638118.mp3", "your turn make sunny's hissy sound": "1eb317ae26.mp3", "yes that's sunny's sound": "d83f294c3d.mp3", "sunny wants to fly a balloon make sunny's sound to fill it up": "1d30b46d31.mp3", "up up and away sunny's balloon is flying": "44e096da5d.mp3", "sunny is hungry say each word to feed her": "e90a82727d.mp3", "you found sunny": "91821c4f89.mp3", "ta da it's super sunny": "84e486c171.mp3", "ta da it's pirate sunny": "af6aa308cc.mp3", "ta da it's space sunny": "904c30839c.mp3", "ta da it's wizard sunny": "1b31e5097c.mp3", "ta da it's chef sunny": "846435c7c9.mp3", "ta da it's firefighter sunny": "91a4f59be9.mp3", "ta da it's rock star sunny": "6bef30dabd.mp3", "bye bye sunny who's next": "4bc7c7d36b.mp3", "hee hee that was a snake hiss like sunny's for thunder let your tongue peek out and blow softly": "b6c16b425e.mp3", "pop that was quick for thunder let your tongue peek out and make it long like a breeze": "0e1974c024.mp3", "hee hee that was sunny's snake hiss for fifi put your top teeth on your lip and blow softly": "f48bb3ff6b.mp3", "pop that was quick for fifi put your teeth on your lip and make it long like a breeze": "5298be6843.mp3", "ooh a soft breezy sound like thunder's for sunny put your teeth together smile and hiss": "b4526d9e85.mp3", "pop that was quick for sunny make it long like a snake teeth together and hiss": "b5e4a508e4.mp3", "ooh a hissy sound for vinny put your teeth on your lip and turn on your buzzy motor": "616a31a852.mp3", "i can't hear you can you say it with a big lion voice": "3bcd852714.mp3", "here comes a yummy word": "4114898785.mp3", "ooh what's this": "0e1eba694a.mp3", "next one": "47660cec0d.mp3", "what do you call a sleeping dinosaur": "12c2d19ca8.mp3", "a dino snore": "a08a73cd60.mp3", "what do you call a snake that builds houses": "bfe5ef69ce.mp3", "a boa constructor": "409f7787fd.mp3", "what does a race car eat": "617cdd6c65.mp3", "fast food": "2b50b29ca6.mp3", "what is a puppy's favorite snack": "a4bbd56bec.mp3", "pup corn": "3fb22243ec.mp3", "knock knock who's there lettuce": "31c4c9e693.mp3", "lettuce who lettuce play some more": "d9a54517df.mp3", "where do dogs park their cars": "eacde12a0d.mp3", "in the barking lot": "6877c458eb.mp3", "v_th:woof woof hi hi hi wanna play with me": "0d8ed8f141.mp3", "v_th:hee hee hee that tickles": "461bdf23af.mp3", "v_th:woof do it again": "4309f62b16.mp3", "v_th:woof you did it yippee": "ad29266c38.mp3", "v_th:woof woof hooray": "7344e7f879.mp3", "v_th:yum yum yum woof": "444a050b65.mp3", "v_th:burp oops woof": "65ee6b6194.mp3", "v_th:bye bye woof woof": "da523fd800.mp3", "v_th:woof woof dance with me": "c8e68f8104.mp3", "v_f:hop hop hop hello let's play": "e4a5930422.mp3", "v_f:hee hee bunny giggles": "5bbdc28fc0.mp3", "v_f:yippee you did it": "266394760d.mp3", "v_f:crunchy munchy yum": "162de2fa42.mp3", "v_f:nom nom nom yummy": "c5eb0f3a68.mp3", "v_f:bye bye hop hop": "ec6dd3ec8e.mp3", "v_f:hop hop dance with me": "dae13eaa76.mp3", "v_v:beep beep ready set go": "2645adb918.mp3", "v_v:beep hee hee that tickles": "7431716012.mp3", "v_v:beep beep beep hee hee": "27464536e8.mp3", "v_v:beep beep you're a superstar": "19854a6648.mp3", "v_v:glug glug glug yummy": "43f795bb40.mp3", "v_v:beep beep bye bye": "6ffccbed98.mp3", "v_v:beep beep dance with me": "5c0e18d0a4.mp3", "v_s:hiss hiss hello hello i'm so happy": "acc2dffdc2.mp3", "v_s:hee hee wiggle wiggle": "4a62c88a2b.mp3", "v_s:hee hee hee that tickles": "66cd27e406.mp3", "v_s:yes yes yes you did it": "461b0a5962.mp3", "v_s:slurp yummy yummy": "0df19aa80e.mp3", "v_s:slurp slurp yum": "f5f3dfebfc.mp3", "v_s:bye bye hiss hiss": "1e56f98d82.mp3", "v_s:wiggle wiggle dance with me": "f10e8b4b4e.mp3", "wiggle wiggle": "a2bdcab01d.mp3", "spin around": "279e2d8240.mp3", "wiggle your tongue peek peek peek": "0c8f95baf0.mp3", "knock knock who is coming to play today tap the door": "1b4fdb2a7c.mp3", "who said it listen and tap the friend whose sound you hear": "631614473e.mp3", "listen again": "5c6d8951db.mp3", "let's do it together slowly": "f016159d20.mp3", "ooh nice try": "ed2c58fe1c.mp3", "prize time tap the present": "9922373dc2.mp3", "ready for a joke": "697c82a59c.mp3", "hee hee hee": "316a3fadca.mp3", "oops was that a toot hee hee": "01ff1b5015.mp3", "beep beep coming through": "f6160d68d3.mp3", "peekaboo i see you": "0b4669bd8d.mp3", "squad dance party dance with your friends": "40db5a56ad.mp3", "freeze": "eb47960527.mp3", "dance": "3355d92c04.mp3", "v_f:hop hop hee hee": "14d75e8d31.mp3", "v_f:yay you did it hop hop": "f35e1f7ef3.mp3", "v_v:yay beep beep you did it": "c60e7abe2b.mp3", "v_v:yummy burp beep beep": "7d8d4aea48.mp3", "v_s:yay wiggle wiggle": "7e47bdfe86.mp3"};
const bufCache={};let curSrc=null,sayId=0;
function ckey(t){return t.toLowerCase().replace(/’/g,"'").replace(/[^a-z0-9' ]+/g,' ').replace(/\s+/g,' ').trim()}
function loadClip(fn){if(!bufCache[fn])bufCache[fn]=fetch('audio/'+fn).then(r=>{if(!r.ok)throw 0;return r.arrayBuffer()}).then(b=>new Promise((res,rej)=>AC.decodeAudioData(b,res,rej))).catch(e=>{delete bufCache[fn];throw e});return bufCache[fn]}
function preloadClips(){if(!AC)return;let i=0;const fns=Object.values(CLIPS);const next=()=>{if(i>=fns.length)return;loadClip(fns[i++]).catch(()=>{}).finally(next)};for(let k=0;k<4;k++)next()}
function stopVoice(){sayId++;if(curSrc){const c=curSrc;curSrc=null;try{c.stop()}catch(e){}}if('speechSynthesis' in window)speechSynthesis.cancel()}
const nm=()=>state.name?', '+state.name:'';
function say(text,o={}){setCaption(o.caption!=null?o.caption:text);stopVoice();const id=sayId;const fn=CLIPS[(o.pre||'')+ckey(text)];
return new Promise(res=>{let done=false,tm=null;const fin=()=>{if(done)return;done=true;clearTimeout(tm);if(id===sayId){speaking=false;duck(false)}res()};
speaking=true;duck(true);
const tts=()=>{if(id!==sayId)return fin();if(!('speechSynthesis' in window)){tm=setTimeout(fin,900+text.length*70);return}
const u=new SpeechSynthesisUtterance(text);if(voice)u.voice=voice;u.lang=voice?voice.lang:'en-US';u.rate=(o.rate||.9)*.85;u.pitch=1.1;u.onend=fin;u.onerror=fin;tm=setTimeout(fin,2000+text.length*140/u.rate);setTimeout(()=>{if(!done)speechSynthesis.speak(u)},70)};
if(fn&&AC){loadClip(fn).then(buf=>{if(id!==sayId)return fin();const src=AC.createBufferSource();src.buffer=buf;src.connect(voiceGain);src.onended=fin;curSrc=src;src.start();tm=setTimeout(fin,buf.duration*1000+1500)}).catch(tts)}else tts()})}
/* ---------- MOUTH ---------- */
const BASE={open:.06,spread:.3,tOut:0,tUp:0,bite:0,air:0,buzz:0};
const POSES={rest:{},open:{open:.34,spread:.38},th:{open:.6,spread:.45,tOut:1,tUp:.5},thAir:{open:.6,spread:.45,tOut:1,tUp:.5,air:1},thBuzz:{open:.6,spread:.45,tOut:1,tUp:.5,buzz:1},
f:{open:.5,spread:.5,bite:1,air:1},d:{open:.75,spread:.4,tUp:1},s:{open:.36,spread:.95,air:1},smile:{open:.38,spread:.95},fRest:{open:.5,spread:.5,bite:1},v:{open:.5,spread:.5,bite:1,buzz:1},sRest:{open:.36,spread:.95}};
const mouths=[];let mid=0;
function mouthMarkup(id){let up='',lo='';for(let i=0;i<6;i++){up+=`<rect x="${107+i*31}" y="-36" width="29" height="54" rx="8"/>`;lo+=`<rect x="${116+i*28}" y="-16" width="27" height="50" rx="7"/>`}
return `<svg viewBox="0 0 400 300"><defs><clipPath id="mc${id}"><path class="mInt"/></clipPath></defs>
<ellipse cx="200" cy="150" rx="198" ry="148" fill="#ffd6bd"/><ellipse cx="58" cy="172" rx="36" ry="24" fill="#ff9aa8" opacity=".35"/><ellipse cx="342" cy="172" rx="36" ry="24" fill="#ff9aa8" opacity=".35"/>
<path d="M166 34 Q183 58 200 50 Q217 58 234 34" fill="none" stroke="#e3a888" stroke-width="6" stroke-linecap="round"/>
<g class="jit"><path class="mOut" fill="#e8687c" stroke="#c94e63" stroke-width="2.5"/><path class="mIntF" fill="#4e1328"/>
<g clip-path="url(#mc${id})"><ellipse class="tBack" cx="200" rx="82" ry="40" fill="#e45d7b"/>
<g class="tUp" fill="#fff" stroke="#e2e2ea" stroke-width="2">${up}</g><g class="tLo" fill="#fbfbff" stroke="#e2e2ea" stroke-width="2">${lo}</g></g>
<g class="tFront"><ellipse class="tFrontE" cx="200" rx="60" ry="1" fill="#f47a93" stroke="#d9546f" stroke-width="2.5"/>
<g class="tEyes"><circle cx="185" cy="0" r="6.5" fill="#fff"/><circle cx="215" cy="0" r="6.5" fill="#fff"/><circle cx="186.5" cy="1" r="3.3" fill="#222"/><circle cx="216.5" cy="1" r="3.3" fill="#222"/></g></g>
<g class="air"></g><g class="buzz"><path class="bzL" fill="none" stroke="#ffb300" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/><path class="bzR" fill="none" stroke="#ffb300" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<text x="40" y="250" font-size="34" font-weight="700" fill="#ffb300" font-family="Fredoka">bzz</text><text x="300" y="250" font-size="34" font-weight="700" fill="#ffb300" font-family="Fredoka">bzz</text></g></g></svg>`}
function makeMouth(el){const id=++mid;el.innerHTML=mouthMarkup(id);const q=s=>el.querySelector(s);
const m={el,p:{...BASE},t:{...BASE},pt:[],spawn:0,
P:{out:q('.mOut'),int:q('.mInt'),intF:q('.mIntF'),up:q('.tUp'),lo:q('.tLo'),back:q('.tBack'),fG:q('.tFront'),fE:q('.tFrontE'),eyes:q('.tEyes'),air:q('.air'),buzz:q('.buzz'),bzL:q('.bzL'),bzR:q('.bzR'),jit:q('.jit')},
set(n){this.t={...BASE,...(POSES[n]||{})}}};
for(let i=0;i<14;i++){const c=document.createElementNS('http://www.w3.org/2000/svg','circle');c.setAttribute('fill','#ffffff55');c.setAttribute('stroke','#fff');c.setAttribute('stroke-width','3');c.setAttribute('r','0');m.P.air.appendChild(c);m.pt.push({c,life:0})}
mouths.push(m);updateMouth(m,1);return m}
function updateMouth(m,dt){const p=m.p,t=m.t,k=Math.min(1,dt*5);for(const key in p)p[key]+=(t[key]-p[key])*k;
const cx=200,cy=150,hw=105+p.spread*28,gap=6+p.open*70,uy=cy-gap/2,ly0=cy+gap/2,ly=ly0+(uy+14-ly0)*p.bite;
m.P.out.setAttribute('d',`M${cx-hw},${cy} C${cx-hw*.55},${uy-30} ${cx-34},${uy-36} ${cx},${uy-21} C${cx+34},${uy-36} ${cx+hw*.55},${uy-30} ${cx+hw},${cy} C${cx+hw*.7},${ly+42} ${cx-hw*.7},${ly+42} ${cx-hw},${cy}Z`);
const xi=hw-12,Yu=(8*uy-2*cy)/6,Yl=(8*ly-2*cy)/6,d=`M${cx-xi},${cy} C${cx-xi*.5},${Yu} ${cx+xi*.5},${Yu} ${cx+xi},${cy} C${cx+xi*.5},${Yl} ${cx-xi*.5},${Yl} ${cx-xi},${cy}Z`;
m.P.int.setAttribute('d',d);m.P.intF.setAttribute('d',d);
m.P.up.setAttribute('transform',`translate(0,${uy.toFixed(1)})`);m.P.lo.setAttribute('transform',`translate(0,${ly0.toFixed(1)})`);
m.P.back.setAttribute('cy',((ly0+26)+((uy+14)-(ly0+26))*p.tUp).toFixed(1));
const top=uy+15,full=Math.max(0,(ly0+24-top)/2),ry=Math.max(.01,full*p.tOut);
m.P.fE.setAttribute('ry',ry.toFixed(2));m.P.fE.setAttribute('cy',(top+ry).toFixed(1));m.P.fG.style.opacity=Math.min(1,p.tOut*3);
m.P.eyes.setAttribute('transform',`translate(0,${(top+ry*1.05).toFixed(1)})`);m.P.eyes.style.opacity=Math.max(0,Math.min(1,(p.tOut-.75)/.25));
m.spawn-=dt;if(p.air>.5&&m.spawn<=0){m.spawn=.11;const s=m.pt.find(o=>o.life<=0);if(s){s.life=1;s.x=cx+(Math.random()-.5)*40;s.y=(uy+ly)/2+6;s.vx=(Math.random()-.5)*50;s.r=6}}
for(const s of m.pt){if(s.life>0){s.life-=dt*.9;s.r+=dt*40;s.y+=dt*32;s.x+=s.vx*dt;s.c.setAttribute('cx',s.x.toFixed(1));s.c.setAttribute('cy',s.y.toFixed(1));s.c.setAttribute('r',s.r.toFixed(1));s.c.style.opacity=Math.max(0,s.life*.8)}else s.c.style.opacity=0}
m.P.buzz.style.opacity=p.buzz;
if(p.buzz>.05){const z=x0=>{let s=`M${x0},96`;for(let i=1;i<=8;i++)s+=` L${x0+(i%2?1:-1)*(9+Math.random()*7)},${96+i*14}`;return s};m.P.bzL.setAttribute('d',z(44));m.P.bzR.setAttribute('d',z(356));
m.P.jit.setAttribute('transform',`translate(${((Math.random()-.5)*2*p.buzz).toFixed(1)},${((Math.random()-.5)*2*p.buzz).toFixed(1)})`)}else m.P.jit.removeAttribute('transform')}
/* ---------- FX ---------- */
const fx=$('#fx'),fctx=fx.getContext('2d');let conf=[];
function sizeFx(){fx.width=innerWidth*devicePixelRatio;fx.height=innerHeight*devicePixelRatio}addEventListener('resize',sizeFx);sizeFx();
function confetti(n=110){const cols=['#ff5d8f','#ffc93c','#3fbf74','#36a9e1','#8a6cff','#ff9f43'];for(let i=0;i<n;i++)conf.push({x:innerWidth/2+(Math.random()-.5)*260,y:innerHeight*.5,vx:(Math.random()-.5)*15,vy:-Math.random()*15-5,w:Math.random()*8+6,c:cols[i%6],a:Math.random()*6,va:(Math.random()-.5)*.4,life:1})}
function drawConf(dt){const r=devicePixelRatio;fctx.clearRect(0,0,fx.width,fx.height);conf=conf.filter(c=>c.life>0&&c.y<innerHeight+40);for(const c of conf){c.vy+=30*dt;c.x+=c.vx*dt*30;c.y+=c.vy*dt*30;c.a+=c.va;c.life-=dt*.35;fctx.save();fctx.translate(c.x*r,c.y*r);fctx.rotate(c.a);fctx.fillStyle=c.c;fctx.globalAlpha=Math.min(1,c.life*2);fctx.fillRect(-c.w*r/2,-c.w*r/4,c.w*r,c.w*r/2);fctx.restore()}}
function floater(e,a){const s=document.createElement('div');s.className='flo '+a;s.textContent=e;
if(a==='leap'){s.style.left=(25+Math.random()*50)+'vw';s.style.top='55vh'}else if(a==='fly'){s.style.left='0';s.style.top=(35+Math.random()*25)+'vh'}else if(a==='run'){s.style.left='0';s.style.top='76vh'}else if(a==='swim'){s.style.left='0';s.style.top='86vh';s.style.fontSize='60px'}else{s.style.left=(15+Math.random()*70)+'vw';s.style.top='95vh'}
$('#fxLayer').appendChild(s);setTimeout(()=>s.remove(),9500)}
let btBusy=false;
function bigRise(talk=true){if(btBusy)return;btBusy=true;const b=$('#bigTurtle');const side=pick([18,82,22,78,50]);b.style.left=side+'vw';b.classList.remove('up');void b.offsetWidth;b.classList.add('up');sfx.bloop();
for(let i=0;i<6;i++)setTimeout(()=>{const d=document.createElement('div');d.className='flo leap';d.textContent=pick(['✨','⭐','💛']);d.style.left=(parseFloat(b.style.left)-10+Math.random()*20)+'vw';d.style.top='78vh';d.style.fontSize='34px';$('#fxLayer').appendChild(d);setTimeout(()=>d.remove(),2100)},300+i*90);
setTimeout(()=>{if(talk&&!speaking){sfx.silly();say('Peekaboo! I see you!')}},3300);setTimeout(()=>{b.classList.remove('up');btBusy=false},5600)}
function surprise(){const r=Math.random();sfx.pop();
if(r<.28)return bigRise();
if(r<.40)return floater('🐶','swim');
const[e,a]=pick([['🐟','leap'],['🐬','leap'],['🦋','fly'],['🚀','rise'],['🎈','rise'],['🦀','fly'],['🦄','fly'],['🐙','leap'],['🦖','fly'],['🐸','leap'],['🌈','rise'],['🐳','leap']]);floater(e,a);if(Math.random()<.4)setTimeout(()=>floater(pick(['🎈','🫧','⭐']),'rise'),400)}
let last=performance.now();
function loop(now){const dt=Math.min(.05,(now-last)/1000);last=now;for(const m of mouths)if(m.el.offsetParent!==null)updateMouth(m,dt);powerTick(dt);earTick();drawConf(dt);requestAnimationFrame(loop)}
requestAnimationFrame(loop);
/* Silly Sound Squad listener: finds the word in a short recording and measures the hiss next to the vowel.
Verdicts: soft (a soft, spread hiss: TH or F), sharp (a loud, narrow S/Z hiss), pop (no long hiss: T, P, D),
voice (voicing, used for V), quiet (nothing heard). TH and F sound almost the same, so the listener
cannot tell them apart: the mouth picture and a grown-up cover that one. Nothing is saved or sent. */
(function (G) {
function fft(re, im) {
const n = re.length;
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
}
for (let len = 2; len <= n; len <<= 1) {
const a = -2 * Math.PI / len, wr = Math.cos(a), wi = Math.sin(a);
for (let i = 0; i < n; i += len) {
let cr = 1, ci = 0;
for (let k = 0; k < len / 2; k++) {
const ur = re[i + k], ui = im[i + k];
const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
re[i + k] = ur + vr; im[i + k] = ui + vi;
re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;
}
}
}
}
const winCache = {};
function hann(N) { if (!winCache[N]) { const w = new Float32Array(N); for (let i = 0; i < N; i++) w[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (N - 1)); winCache[N] = w; } return winCache[N]; }
function frameSize(sr) { return sr > 32000 ? 1024 : 512; }
// One frame of features from N samples starting at s.
function frame(x, s, N, sr) {
const w = hann(N), re = new Float64Array(N), im = new Float64Array(N);
let sq = 0, zc = 0, prev = x[s];
for (let i = 0; i < N; i++) { const v = x[s + i]; sq += v * v; re[i] = v * w[i]; if ((v >= 0) !== (prev >= 0)) zc++; prev = v; }
fft(re, im);
const bin = sr / N, half = N / 2, top = Math.min(11000, sr / 2 - bin);
let low = 0, mid = 0, high = 0, cn = 0, cd = 0, fl = 0, fa = 0, fc = 0, mx = 0, ca = 0, cc = 0;
for (let k = 1; k < half; k++) {
const f = k * bin, p = re[k] * re[k] + im[k] * im[k] + 1e-12;
if (f >= 80 && f < 900) low += p; else if (f >= 900 && f < 3000) mid += p; else if (f >= 3000 && f <= top) high += p;
if (f >= 1000 && f <= top) { cn += f * p; cd += p; }
if (f >= 1500 && f <= Math.min(10000, top)) { fl += Math.log(p); fa += p; fc++; }
if (f >= 3000 && f <= Math.min(10000, top)) { if (p > mx) mx = p; ca += p; cc++; }
}
const rms = Math.sqrt(sq / N);
return { db: 20 * Math.log10(rms + 1e-9), low, mid, high, zcr: zc / N,
cen: cd ? cn / cd : 0, flat: fc ? Math.exp(fl / fc) / (fa / fc) : 0, crest: cc ? mx / (ca / cc) : 0 };
}
function features(x, sr) {
const N = frameSize(sr), H = N / 2, out = [];
for (let s = 0; s + N <= x.length; s += H) { const f = frame(x, s, N, sr); f.t = s / sr; out.push(f); }
out.hopMs = 1000 * H / sr;
return out;
}
// The hiss right before (dir -1) or after (dir +1) the vowel.
function hissNear(F, from, dir, floor) {
const got = []; let miss = 0;
for (let i = from, n = 0; i >= 0 && i < F.length && n < 45; i += dir, n++) {
const f = F[i];
const fric = f.db > floor + 6 && f.high > f.low * 1.2 && f.zcr > 0.15;
if (fric) { got.push(f); miss = 0; }
else if (f.db < floor + 6) { if (++miss > 2 && got.length) break; if (miss > 4) break; }
else { if (++miss > 3) break; }
}
return got;
}
function analyze(x, sr, kind) {
const F = features(x, sr), hop = F.hopMs;
if (F.length < 8) return { verdict: 'quiet' };
const sorted = F.map(f => f.db).sort((a, b) => a - b);
const floor = Math.max(-75, sorted[Math.floor(sorted.length * 0.1)]), peak = sorted[sorted.length - 1];
if (peak - floor < 15) return { verdict: 'quiet', floor, peak };
// The vowel: the longest run of loud, low-pitched frames.
const voiced = F.map(f => f.db > peak - 24 && f.low > f.high && f.zcr < 0.2);
let best = null, s = -1, gap = 0; const runs = [];
for (let i = 0; i <= F.length; i++) {
if (i < F.length && voiced[i]) { if (s < 0) s = i; gap = 0; }
else if (s >= 0) {
if (i < F.length && ++gap <= 2) continue;
const e = i - gap; runs.push({ s, e }); if (!best || e - s > best.e - best.s) best = { s, e }; s = -1; gap = 0;
}
}
if (!best || (best.e - best.s + 1) * hop < 50) return { verdict: 'quiet', floor, peak };
const big = runs.filter(r => (r.e - r.s + 1) * hop >= 50);
if (kind === 'I' || kind === 'dhI' || kind === 'V') best = big[0]; else if (kind === 'F') best = big[big.length - 1];
let vpk = -200; for (let i = best.s; i <= best.e; i++) vpk = Math.max(vpk, F[i].db);
const info = { floor, peak, vowelMs: Math.round((best.e - best.s + 1) * hop) };
if (kind === 'thM' || kind === 'V') {
// Buzzy sounds (V, buzzy TH) and sounds in the middle of a word: heard is enough, unless a loud sharp hiss starts it (Z).
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3), rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const fl = pre.reduce((a, f) => a + f.flat, 0) / pre.length;
if (rel > -16 && fl < 0.25) return Object.assign({ verdict: 'sharp', rel, flat: fl }, info);
}
return Object.assign({ verdict: 'voice' }, info);
}
if (kind === 'dhI') {
// Buzzy TH: a soft start. D starts with a sudden burst; Z starts with a loud hiss.
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = pre.reduce((a, f) => a + f.cen, 0) / pre.length;
info.rel = rel; info.cen = cen;
if (rel > -16 && cen > 4000) return Object.assign({ verdict: 'sharp' }, info);
}
// Rise time from first sound to near the vowel's peak.
let on = best.s; while (on > 0 && F[on - 1].db > floor + 8) on--;
let r = on; while (r < F.length && F[r].db < vpk - 8) r++;
info.rise = (r - on) * hop;
let jump = 0; for (let i = Math.max(1, on - 1); i <= Math.min(r, F.length - 1); i++) jump = Math.max(jump, F[i].db - F[i - 1].db);
info.jump = jump; info.onHigh = F[on].high / (F[on].low + 1e-12); info.onDb = F[on].db - vpk;
const quietBefore = on > 0 && F[on - 1].db < floor + 6;
return Object.assign({ verdict: 'voice' }, info);
}
const fr = kind === 'F' ? hissNear(F, best.e + 1, 1, floor) : hissNear(F, best.s - 1, -1, floor);
info.hissMs = Math.round(fr.length * hop);
if (fr.length) { const chron = kind === 'F' ? fr : fr.slice().reverse(), mx = Math.max(...fr.map(f => f.db));
info.attack = Math.max(chron[0].db, (chron[1] || chron[0]).db) - mx; info.mean = fr.reduce((a, f) => a + f.db, 0) / fr.length - vpk;
info.flat = fr.reduce((a, f) => a + f.flat, 0) / fr.length; }
if (fr.length * hop < 40) return Object.assign({ verdict: 'pop' }, info);
const top = fr.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = fr.reduce((a, f) => a + f.cen, 0) / fr.length;
const crest = fr.reduce((a, f) => a + f.crest, 0) / fr.length;
Object.assign(info, { rel, cen, crest });
// A T or D: a loud puff that starts all at once and is over quickly.
if (kind === 'I' && info.mean > -13.5 && info.attack > -5 && info.hissMs <= 120) return Object.assign({ verdict: 'pop' }, info);
if (kind === 'I' && info.hissMs <= 65 && info.attack > -3.5) return Object.assign({ verdict: 'pop' }, info);
// An S: a narrow, sharp hiss (low flatness) that is fairly loud next to the vowel.
if (info.flat < 0.25 && info.mean > -18.5) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -11) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -20.5 && cen > 8000 && crest >= 10) return Object.assign({ verdict: 'sharp' }, info);
return Object.assign({ verdict: 'soft' }, info);
}
// Live sound for the blowing game: is this frame a soft TH breeze, a snake hiss or a voice?
function liveKind(f, floor) {
if (f.db < floor + 9) return 'none';
const hissy = f.high > f.low && f.zcr > 0.15;
if (hissy) return (f.flat < 0.25 && f.db > floor + 22) ? 'sharp' : 'soft';
if (f.low > f.high && f.zcr < 0.18) return (f.high > f.low * 0.05 || f.mid > f.low * 0.3) ? 'buzz' : 'voice';
return 'none';
}
G.SoundEar = { features, analyze, frame, frameSize, liveKind };
})(typeof window !== 'undefined' ? window : globalThis);
/* ---------- DANCE PARTY (freeze dance) ---------- */
const MOVES=[['mv-bounce',null],['mv-wiggle','Wiggle, wiggle!'],['mv-spin','Spin around!'],['mv-peek','Wiggle your tongue! Peek, peek, peek!'],['mv-jump',null]];
function setMove(m){const p=$('#partyTheo');MOVES.forEach(x=>p.classList.remove(x[0]));p.classList.add(m)}
let partyResume='home';
async function partyRun(T,dur,auto){const P=$('#party');P.classList.toggle('auto',!!auto);P.classList.remove('frozen');P.classList.add('on');$('#partyTheo').innerHTML=active().map(k=>charHTML(k,'act')).join('');setMove('mv-bounce');
await say('Squad dance party! Dance with your friends!');if(T!==tok)return;{const k=active()[J.round%active().length];await fsay(k,'dance',$(`#partyTheo .chwrap[data-ch="${k}"]`));if(T!==tok)return}
beatStart();const t0=Date.now();let nextFreeze=Date.now()+5000+Math.random()*3000,nextMove=Date.now()+3500,mi=0;
while(T===tok&&(dur==null||Date.now()-t0<dur*1000)){await wait(200);if(T!==tok)break;
if(Date.now()>nextMove){mi=(mi+1+Math.floor(Math.random()*(MOVES.length-1)))%MOVES.length;const[m,line]=MOVES[mi];setMove(m);if(line)say(line);nextMove=Date.now()+4500}
if(Date.now()>nextFreeze){beatStop();sfx.scratch();P.classList.add('frozen');await say('Freeze!');if(T!==tok)break;await wait(2300);if(T!==tok)break;P.classList.remove('frozen');await say('Dance!');if(T!==tok)break;beatStart();nextFreeze=Date.now()+6500+Math.random()*4000}}
beatStop();if(T!==tok)return;P.classList.remove('frozen');await say(`Great dancing${nm()}!`);P.classList.remove('on','auto')}
$('#danceBtn').onclick=()=>{sfx.tap();partyResume=$('#s-home').classList.contains('on')?'home':'journey';const T=newTok();partyRun(T,null,false)};
$('#partyX').onclick=()=>{sfx.tap();newTok();if(partyResume==='home')homeScene();else journeyGo()};
$('#partyTheo').onclick=()=>{sfx.silly();const p=$('#partyTheo');p.animate([{transform:'scale(1)'},{transform:'scale(1.15) rotate(-8deg)'},{transform:'scale(1)'}],{duration:400})};
/* ---------- MICROPHONE (the game listens) ---------- */
const mic={state:'off',stream:null,proc:null,floorArr:[],floor:-60,rec:null,onLive:null,level:-90,kind:'none'};
async function micStart(){
if(!state.micWanted){mic.state='off';return false}
if(mic.state==='on')return true;
if(!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)){mic.state='unsupported';return false}
try{if(navigator.audioSession)navigator.audioSession.type='play-and-record'}catch(e){}
try{
const st=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:false,noiseSuppression:false,autoGainControl:false,channelCount:1}});
initAudio();mic.stream=st;const src=AC.createMediaStreamSource(st);const proc=AC.createScriptProcessor(1024,1,1);const mute=AC.createGain();mute.gain.value=0;
src.connect(proc);proc.connect(mute);mute.connect(AC.destination);mic.proc=proc;mic.src=src;
proc.onaudioprocess=e=>{const d=e.inputBuffer.getChannelData(0),sr=AC.sampleRate,N=Math.min(SoundEar.frameSize(sr),d.length);const f=SoundEar.frame(d,0,N,sr);
if(mic.rec)mic.rec.push(new Float32Array(d));else if(!speaking){mic.floorArr.push(f.db);if(mic.floorArr.length>240)mic.floorArr.shift();const s=mic.floorArr.slice().sort((a,b)=>a-b);mic.floor=Math.max(-85,s[Math.floor(s.length*.2)])}
mic.level=f.db;mic.kind=SoundEar.liveKind(f,mic.floor);if(mic.onLive)mic.onLive(f,mic.kind)};
mic.state='on';return true
}catch(e){mic.state='denied';try{if(navigator.audioSession)navigator.audioSession.type='playback'}catch(_){}return false}}
function micStop(){try{if(mic.stream)mic.stream.getTracks().forEach(t=>t.stop());if(mic.proc){mic.proc.onaudioprocess=null;mic.proc.disconnect()}if(mic.src)mic.src.disconnect()}catch(e){}mic.stream=mic.proc=mic.src=null;mic.state='off';try{if(navigator.audioSession)navigator.audioSession.type='playback'}catch(e){}}
const hearing=()=>mic.state==='on';
// The listening badge: a big pulsing ear that glows with the sound it hears.
const KCOL={soft:'#7fd3ff',sharp:'#7ee08a',voice:'#ffc93c',buzz:'#ffb347',none:'#ffffff'};
function earShow(on,label){const e=$('#ear');e.classList.toggle('on',on);if(label)$('#earLbl').textContent=label;duck(speaking)}// music goes quiet while listening
function earTick(){const e=$('#ear');if(!e.classList.contains('on'))return;const lv=Math.max(0,Math.min(1,(mic.level-mic.floor)/40));
e.style.setProperty('--lv',lv.toFixed(3));e.style.setProperty('--kc',KCOL[mic.kind]||'#fff')}
// Record one try. Stops early once the child has spoken and gone quiet.
async function listenTake(T,maxMs=4200){earShow(true,'Listening…');await wait(250);if(T!==tok){earShow(false);return new Float32Array(0)}// skip the speaker's echo
mic.rec=[];const early=mic.level>mic.floor+16;const t0=Date.now();let spoke=0,quietSince=0;
while(T===tok&&Date.now()-t0<maxMs){await wait(60);if(mic.level>mic.floor+16){spoke=Date.now();quietSince=0}else if(spoke&&!quietSince)quietSince=Date.now();
if(spoke&&quietSince&&Date.now()-quietSince>650&&Date.now()-t0>1100)break}
const parts=mic.rec||[];mic.rec=null;earShow(false);let n=0;parts.forEach(p=>n+=p.length);const x=new Float32Array(n);let o=0;parts.forEach(p=>{x.set(p,o);o+=p.length});x.early=early;return x}
function judge(F,verdict){if(verdict==='quiet')return'quiet';
if(F.want==='voice')return(verdict==='voice'||verdict==='buzz')?'yes':(verdict==='sharp'?'sharp':'yes');
return verdict===F.want?'yes':verdict}
/* ---------- JOURNEY (one loop, never back to a menu) ---------- */
let tok=0;
function newTok(){tok++;stopVoice();beatStop();whoosh(false);$('#turn').classList.remove('on');earShow(false);mic.onLive=null;mic.rec=null;PW.active=false;PW.holding=false;whoPick=null;
const P=$('#party');if(P)P.classList.remove('on','frozen','auto');$$('.override').forEach(b=>b.remove());return tok}
function show(id){$$('.screen').forEach(s=>s.classList.toggle('on',s.id==='s-'+id));$('#trail').style.visibility=id==='home'?'hidden':'visible'}
const STATIONS=['reveal','mirror','power','who','feed','prize'];
const STATION_INFO=[['🚪','Who is here?'],['👄','Mouth mirror'],['⚡','Power play'],['👂','Who said it?'],['🍎','Feed the friend'],['🎁','Prize time']];
function active(){const a=state.sounds.filter(k=>SQUAD[k]);return a.length?a:['th','f','v','s']}
function cur(){const a=active();return SQUAD[a[J.round%a.length]]}
function setTrail(i){$$('#trail i').forEach((e,j)=>{e.classList.toggle('done',j<i);e.classList.toggle('now',j===i)})}
async function journeyGo(){const T=newTok();const i=J.station%6;setTrail(i);const[ic,nm]=STATION_INFO[i];
const w=$('#wave');$('#waveWhere').textContent=ic+' '+nm;$('#waveCh').innerHTML=charHTML(cur().key);w.classList.remove('go');void w.offsetWidth;w.classList.add('go');whooshPuff(1200);sfx.slideUp();
await wait(900);if(T!==tok)return;show(STATIONS[i]);PREP[STATIONS[i]]();await wait(1300);if(T!==tok)return;w.classList.remove('go');SCENES[STATIONS[i]](T)}
function sceneDone(T){if(T!==tok)return;J.station++;if(J.station>=6){J.station=0;J.round++}saveJ();journeyGo()}
function addStar(){state.stars++;store.set('stars',state.stars);$('#starN').textContent=state.stars;const s=$('#stars');s.classList.remove('bump');void s.offsetWidth;s.classList.add('bump')}
async function cheer(T,el,line,k){confetti(160);burst();pick([sfx.kazoo,sfx.chime])();addStar();hop(el);trick(el);if(Math.random()<.15)bigRise(false);await say(line||`Yes! Good job${nm()}!`);if(T!==tok)return;if(k){await fsay(k,'yay',el);if(T!==tok)return}await wait(400)}
function choose(el,items){el.innerHTML='';return new Promise(res=>{items.forEach(([label,val,cls])=>{const b=document.createElement('button');b.className='btn popIn '+(cls||'');b.innerHTML=label;b.onclick=()=>{sfx.tap();el.innerHTML='';res(val)};el.appendChild(b)})})}
// A grown-up can always say "he got it" when the listener is unsure.
function override(){return new Promise(res=>{const b=document.createElement('button');b.className='override';b.textContent='👍 Said it right';b.onclick=()=>{sfx.tap();b.remove();res(true)};document.body.appendChild(b);setTimeout(()=>{if(b.isConnected){b.remove();res(false)}},4200)})}
async function yourTurnNoMic(T,line){await say(line);if(T!==tok)return false;const r=$('#turn');r.classList.remove('on');void r.offsetWidth;r.classList.add('on');await wait(4200);r.classList.remove('on');return T===tok}
/* Friendly tips when a different sound comes out: never "wrong", always another friend's sound. */
const TIP={
th_sharp:'Hee hee! That was a snake hiss, like Sunny’s. For Thunder, let your tongue peek out, and blow softly.',
th_pop:'Pop! That was quick. For Thunder, let your tongue peek out, and make it long, like a breeze.',
f_sharp:'Hee hee! That was Sunny’s snake hiss. For Fifi, put your top teeth on your lip, and blow softly.',
f_pop:'Pop! That was quick. For Fifi, put your teeth on your lip, and make it long, like a breeze.',
s_soft:'Ooh, a soft breezy sound, like Thunder’s! For Sunny, put your teeth together, smile, and hiss.',
s_pop:'Pop! That was quick. For Sunny, make it long, like a snake. Teeth together, and hiss.',
v_sharp:'Ooh, a hissy sound! For Vinny, put your teeth on your lip, and turn on your buzzy motor.',
quiet:'I can’t hear you! Can you say it with a big lion voice?'};
const YAY={th:'Woohoo! That’s Thunder’s sound!',f:'Hooray! That’s Fifi’s sound!',v:'Yippee! That’s Vinny’s sound!',s:'Yes! That’s Sunny’s sound!'};
const INTRO={th:'It’s Thunder the puppy! Thunder’s sound has a peeking tongue. Like in thumb.',f:'It’s Fifi the bunny! Fifi’s sound has bunny teeth. Like in fish.',
v:'It’s Vinny the race car! Vinny’s sound is a buzzy motor. Like in van.',s:'It’s Sunny the snake! Sunny’s sound is a happy hiss. Like in sun.'};
const TURN={th:'Your turn! Make Thunder’s sound.',f:'Your turn! Make Fifi’s sound.',v:'Your turn! Make Vinny’s motor sound.',s:'Your turn! Make Sunny’s hissy sound.'};
const POWER={th:['Thunder loves bubbles! Make Thunder’s sound to blow bubbles. Keep going!','Look at all those bubbles! Thunder is so happy!'],
f:['Fifi has a party cake! Make Fifi’s sound to blow out the candles.','You blew out all the candles! Hooray for Fifi!'],
v:['Help Vinny win the race! Make Vinny’s motor sound to drive. Keep going!','Vinny wins the race! Hooray!'],
s:['Sunny wants to fly a balloon! Make Sunny’s sound to fill it up.','Up, up, and away! Sunny’s balloon is flying!']};
const FEED={th:'Thunder is hungry! Say each word to feed him.',f:'Fifi is hungry! Say each word to feed her.',v:'Vinny needs fuel! Say each word to fill him up.',s:'Sunny is hungry! Say each word to feed her.'};
const FOUND={th:'You found Thunder!',f:'You found Fifi!',v:'You found Vinny!',s:'You found Sunny!'};
const EAT=['Chomp, chomp! Yummy!','Yum! Delicious!','Nom, nom, nom!','Burp! Oh, excuse me! Hee hee!'];
const NEXTWORD=['Here comes a yummy word!','Ooh, what’s this?','Next one!'];
/* ---------- 1. WHO IS HERE? (surprise reveal) ---------- */
function prepReveal(){$('#door').className='door';$('#revealCh').innerHTML='';$('#revealName').textContent=''}
async function revealScene(T){const F=cur();const d=$('#door');d.classList.add('wiggle');const tapped=new Promise(r=>{d.onclick=()=>{d.onclick=null;stopVoice();r()}});
say('Knock, knock! Who is coming to play today? Tap the door!');await tapped;if(T!==tok)return;
d.classList.remove('wiggle');d.classList.add('open');sfx.fanfare();await wait(400);
$('#revealCh').innerHTML=charHTML(F.key,'big popOut');const ch=$('#revealCh .chwrap');dress(ch,J.lastCostume&&J.lastCostume[F.key]);$('#revealName').textContent=F.icon+' '+F.name;confetti(80);
sfx.boing2();await fsay(F.key,'hi',ch);if(T!==tok)return;await wait(300);act(ch,true);await say(INTRO[F.key]);act(ch,false);if(T!==tok)return;await wait(700);sceneDone(T)}
/* ---------- 2. MOUTH MIRROR ---------- */
let mirrorMouth;
function prepMirror(){const F=cur();$('#mirrorCh').innerHTML=charHTML(F.key);$('#stepBig').innerHTML='';$('#mirrorCtl').innerHTML='';mirrorMouth.set('rest')}
function stepBig(icon,label){const e=$('#stepBig');e.innerHTML=`<span>${icon}</span>${label}`;e.classList.remove('popIn');void e.offsetWidth;e.classList.add('popIn')}
async function sustainedTry(T,F,ms=3200){// counts what kind of sound comes out for a few seconds
const c={soft:0,sharp:0,voice:0,buzz:0,none:0};mic.onLive=(f,k)=>{if(!speaking)c[k]=(c[k]||0)+1};earShow(true,'Listening…');const t0=Date.now();
while(T===tok&&Date.now()-t0<ms)await wait(80);mic.onLive=null;earShow(false);
const want=F.want==='voice'?(c.voice+c.buzz):c[F.want];const other=Object.entries(c).filter(([k])=>k!=='none'&&k!==F.want&&!(F.want==='voice'&&(k==='voice'||k==='buzz'))).sort((a,b)=>b[1]-a[1])[0];
if(want>=18)return'yes';if(other&&other[1]>=18)return other[0];if(want+(other?other[1]:0)<10)return'quiet';return'yes'}
async function mirrorScene(T){const F=cur(),ch=$('#mirrorCh .chwrap');
for(const[pose,line]of F.steps){mirrorMouth.set(pose);stepBig(F.icon,line.split(/[,.!]/)[0]);act(ch,/Air|^f$|^v$|^s$/.test(pose));await say(line);if(T!==tok)return;await wait(900);if(T!==tok)return}
mirrorMouth.set(F.pose);act(ch,true);stepBig('🗣️','Your turn!');
for(let tries=0;tries<3;tries++){
let r;
if(hearing()){await say(TURN[F.key]);if(T!==tok)return;r=await sustainedTry(T,F);if(T!==tok)return}
else{if(!await yourTurnNoMic(T,TURN[F.key]))return;await choose($('#mirrorCtl'),[['⭐ I did it!','ok','gold big']]);if(T!==tok)return;r='yes'}
if(r==='yes'){await cheer(T,ch,YAY[F.key],F.key);if(T!==tok)return;break}
if(r==='quiet'&&tries<2){await say(TIP.quiet);if(T!==tok)return;continue}
if(tries>=1){await cheer(T,ch,`Great trying${nm()}!`);if(T!==tok)return;break}
const tip=TIP[F.key+'_'+r];if(tip){popFriendFor(r);await say(tip);if(T!==tok)return}await wait(400)}
act(ch,false);mirrorMouth.set('rest');sceneDone(T)}
// The friend whose sound came out pops in to wave (never as a "wrong" signal).
function popFriendFor(kind){const k=kind==='sharp'?'s':(kind==='soft'?'th':null);if(!k)return;const p=document.createElement('div');p.className='cameo';p.innerHTML=charHTML(k);document.body.appendChild(p);sfx.pop();setTimeout(()=>p.remove(),3600)}
/* ---------- 3. POWER PLAY (the child's sound drives it) ---------- */
const PW={active:false,holding:false,prog:0,t:0,idle:0,done:null,game:'bubbles',lastK:'none',bub:0};
function prepPower(){const F=cur();PW.game=F.game;PW.prog=0;PW.active=false;$('#pbar').style.width='0';const fld=$('#field');fld.className='field g-'+F.game;
let h='';
if(F.game==='bubbles')h=`<div class="pwCh">${charHTML('th')}</div><div class="wand">🫧</div>`;
if(F.game==='candles')h=`<div class="pwCh">${charHTML('f')}</div><div class="cake"><div class="flames">${'<i></i>'.repeat(5)}</div><div class="cakeBody">🎂</div></div>`;
if(F.game==='race')h=`<div class="track"></div><div class="flag">🏁</div><div class="racer">${charHTML('v')}</div>`;
if(F.game==='balloon')h=`<div class="pwCh">${charHTML('s')}</div><div class="balloon"><div class="bl"></div><div class="str"></div></div>`;
fld.innerHTML=h;$('#holdBtn').classList.add('disabled');$('#holdBtn').style.display=hearing()?'none':'flex';powerDraw()}
function powerDraw(){const p=PW.prog,f=$('#field');$('#pbar').style.width=(p*100)+'%';
if(PW.game==='candles'){f.querySelectorAll('.flames i').forEach((c,i)=>c.classList.toggle('out',p>=(i+1)/5-0.001))}
if(PW.game==='race'){const r=f.querySelector('.racer');if(r)r.style.left=(4+p*74)+'%'}
if(PW.game==='balloon'){const b=f.querySelector('.balloon');if(b){b.style.transform=`translate(-50%,${-p*40}%) scale(${.35+p*.85})`}}}
function powerTick(dt){if(!PW.active)return;const F=cur();let rate=0,k='none';
if(hearing()&&!speaking){k=mic.kind;const ok=F.want==='voice'?(k==='voice'||k==='buzz'):k===F.want;rate=ok?.36:(k!=='none'?.1:0)}
if(PW.holding){rate=.36;k=F.want}
PW.prog=Math.min(1,PW.prog+rate*dt);PW.idle=rate?0:PW.idle+dt;const f=$('#field');
const ch=f.querySelector('.chwrap');act(ch,rate>0);
if(rate>0&&PW.game==='bubbles'&&Math.random()<dt*(rate>.2?14:5)){const b=document.createElement('div');b.className='pbub';const s=24+Math.random()*44;b.style.width=b.style.height=s+'px';b.style.left=(26+Math.random()*10)+'%';b.style.top=(40+Math.random()*20)+'%';f.appendChild(b);
b.animate([{transform:'translate(0,0) scale(.3)',opacity:1},{transform:`translate(${200+Math.random()*400}px,${-60-Math.random()*120}px) scale(1)`,opacity:.9}],{duration:2200+Math.random()*900,easing:'ease-out'});setTimeout(()=>b.remove(),3000)}
if(rate>0&&PW.game==='race'){f.querySelectorAll('.wheel').forEach(w=>w.classList.add('spin'))}else if(PW.game==='race'){f.querySelectorAll('.wheel').forEach(w=>w.classList.remove('spin'))}
if(rate>0&&Math.random()<dt*6){const w=document.createElement('div');w.className='windline';w.style.left=(30+Math.random()*30)+'%';w.style.top=(30+Math.random()*40)+'%';w.style.width=(40+Math.random()*60)+'px';f.appendChild(w);w.animate([{opacity:0,transform:'translateX(0)'},{opacity:.9},{opacity:0,transform:'translateX(140px)'}],{duration:800});setTimeout(()=>w.remove(),820)}
const prev=PW.lastStage||0,stage=Math.floor(PW.prog*5);if(stage>prev){sfx.sparkle();PW.lastStage=stage}
powerDraw();if(PW.prog>=1){PW.active=false;PW.holding=false;$('#holdBtn').classList.remove('pressed');const d=PW.done;PW.done=null;d&&d()}}
const hb=$('#holdBtn');
hb.addEventListener('pointerdown',e=>{e.preventDefault();if(!PW.active)return;initAudio();PW.holding=true;hb.classList.add('pressed')});
['pointerup','pointercancel','pointerleave'].forEach(ev=>hb.addEventListener(ev,()=>{PW.holding=false;hb.classList.remove('pressed')}));
hb.addEventListener('contextmenu',e=>e.preventDefault());
async function powerScene(T){const F=cur();PW.lastStage=0;await say(POWER[F.key][0]);if(T!==tok)return;
if(hearing())earShow(true,'Your turn!');hb.classList.remove('disabled');PW.active=true;PW.idle=0;
const t0=Date.now();let nudged=0;
const done=new Promise(r=>PW.done=r);
while(T===tok&&PW.active){await wait(250);if(PW.idle>7&&nudged<2&&!speaking){nudged++;PW.idle=0;say(TURN[F.key])}
if(Date.now()-t0>30000){PW.prog=1}}
await done;if(T!==tok)return;earShow(false);hb.classList.add('disabled');
if(F.game==='balloon'){const b=$('#field .balloon');if(b)b.animate([{transform:b.style.transform},{transform:'translate(-50%,-260%) scale(1.2)'}],{duration:1600,fill:'forwards'})}
surprise();await cheer(T,$('#field .chwrap'),POWER[F.key][1],F.key);if(T!==tok)return;await wait(400);sceneDone(T)}
/* ---------- 4. WHO SAID IT? (tap the friend whose sound you hear) ---------- */
let whoPick=null;
function prepWho(){$('#whoRow').innerHTML='';$('#whoProg').textContent=''}
async function whoScene(T){const act_=active(),pool=act_.length>=3?act_:[...new Set([...act_,...shuffle(['th','f','v','s'])])].slice(0,3);
const friends=shuffle(pool.slice());$('#whoRow').innerHTML=friends.map(k=>`<button class="whoBtn" data-k="${k}">${charHTML(k)}<b>${SQUAD[k].name}</b></button>`).join('');
$$('.whoBtn').forEach(b=>b.onclick=()=>{if(whoPick){const f=whoPick;whoPick=null;f(b.dataset.k)}});
await say('Who said it? Listen, and tap the friend whose sound you hear.');if(T!==tok)return;
const order=shuffle(act_.slice());
for(let r=0;r<3;r++){$('#whoProg').textContent='⭐'.repeat(r)+'🔊'.repeat(3-r);const k=order[r%order.length];const[w]=pick(SQUAD[k].words);
const play=()=>say(w,{pre:'w:',caption:'👂 Listen…'});$('#whoSpk').onclick=()=>{sfx.tap();play()};
await wait(400);await play();if(T!==tok)return;let tries=0;
while(true){const got=await new Promise(res=>whoPick=res);if(T!==tok)return;
if(got===k)break;tries++;const b=$(`.whoBtn[data-k="${got}"]`);b.classList.add('nope');setTimeout(()=>b.classList.remove('nope'),700);
if(tries>=2){$(`.whoBtn[data-k="${k}"]`).classList.add('hint')}await say('Listen again.');if(T!==tok)return;await play();if(T!==tok)return}
const wb=$(`.whoBtn[data-k="${k}"]`);wb.classList.remove('hint');act(wb.querySelector('.chwrap'),true);await cheer(T,wb.querySelector('.chwrap'),FOUND[k],k);act(wb.querySelector('.chwrap'),false);if(T!==tok)return}
$('#whoProg').textContent='⭐⭐⭐';await wait(300);sceneDone(T)}
/* ---------- 5. FEED THE FRIEND (say the words) ---------- */
let feedMouth;
function hl(w,k){const re={th:/th/i,f:/f/i,v:/v/i,s:/s/i}[k];return w.replace(re,m=>`<span class="hl">${m}</span>`)}
function prepFeed(){const F=cur();$('#feedCh').innerHTML=charHTML(F.key,'big');$('#food').textContent='';$('#foodWord').innerHTML='';$('#feedCtl').innerHTML='';feedMouth.set('rest')}
async function feedScene(T){const F=cur(),ch=$('#feedCh .chwrap');const words=shuffle(F.words.slice()).slice(0,3);
await say(FEED[F.key]);if(T!==tok)return;
for(const[w,e,kind]of words){const fd=$('#food');fd.textContent=e;fd.className='popIn';$('#foodWord').innerHTML=hl(w,F.key);feedMouth.set('rest');
await say(pick(NEXTWORD));if(T!==tok)return;await wait(400);feedMouth.set(F.pose);await say(w,{pre:'w:'});if(T!==tok)return;await wait(500);
let ok=false;
for(let tries=0,quiet=0,redo=0;tries<2;){
let res;
if(hearing()){await say(`Your turn! Say: ${w}.`);if(T!==tok)return;const x=await listenTake(T);if(T!==tok)return;res=judge(F,SoundEar.analyze(x,AC.sampleRate,kind).verdict);
if(x.early&&res!=='yes'&&!redo){redo=1;continue}// he started before the listening did: just ask again
if(res!=='yes'){let ovPressed=false;override().then(v=>{ovPressed=v});
if(res==='quiet'&&quiet<1){quiet++;await say(TIP.quiet);if(T!==tok)return;if(ovPressed)res='yes';else continue}
else if(tries===0){const tip=TIP[F.key+'_'+res];if(tip){popFriendFor(res);await say(tip)}else await say('Ooh, nice try!');if(T!==tok)return;if(ovPressed)res='yes'}
else{await wait(1800);if(T!==tok)return;if(ovPressed)res='yes'}}}
else{if(!await yourTurnNoMic(T,`Your turn! Say: ${w}.`))return;res=await choose($('#feedCtl'),[['👍 Said it!','yes','green big'],['🔁 Again','again']]);if(T!==tok)return}
if(res==='yes'){ok=true;break}
tries++;if(tries<2){feedMouth.set(F.rest);await say('Let’s do it together, slowly.');if(T!==tok)return;feedMouth.set(F.pose);await say(w,{pre:'slow:'});if(T!==tok)return;await wait(400)}}
// eat it either way: effort always wins
const r=fd.getBoundingClientRect(),c=ch.getBoundingClientRect();const fly=fd.cloneNode(true);fly.className='flyFood';fly.style.left=(r.left+r.width/2)+'px';fly.style.top=(r.top+r.height/2)+'px';document.body.appendChild(fly);fd.textContent='';
const a=fly.animate([{left:fly.style.left,top:fly.style.top,transform:'translate(-50%,-50%) scale(1)'},{left:(c.left+c.width/2)+'px',top:(c.top+c.height*.62)+'px',transform:'translate(-50%,-50%) scale(.2)'}],{duration:700,easing:'ease-in',fill:'forwards'});
await a.finished.catch(()=>{});fly.remove();sfx.chomp();act(ch,true);
if(ok){confetti(140);burst();sfx.kazoo();addStar();hop(ch);await fsay(F.key,'yum',ch)}else{hop(ch);addStar();await say(`Great trying${nm()}!`);if(T!==tok)return;await fsay(F.key,'yum',ch)}
act(ch,false);if(T!==tok)return;await wait(500)}
sceneDone(T)}
/* ---------- 6. PRIZE: a costume, a dance party and a joke ---------- */
const JOKES=[['What do you call a sleeping dinosaur?','A dino-snore!','🦕'],['What do you call a snake that builds houses?','A boa constructor!','🐍'],['What does a race car eat?','Fast food!','🍔'],
['What is a puppy’s favorite snack?','Pup-corn!','🍿'],['Knock knock! Who’s there? Lettuce.','Lettuce who? Lettuce play some more!','🥬'],['Where do dogs park their cars?','In the barking lot!','🚗']];
function prepPrize(){const b=$('#box');b.textContent='🎁';b.className='';b.style.display='';$('#prizeCh').innerHTML='';$('#prizeName').textContent='';$('#jokeBox').textContent=''}
async function prizeScene(T){const F=cur(),b=$('#box');b.className='shake';const tapped=new Promise(r=>{b.onclick=()=>{b.onclick=null;stopVoice();r()}});
say('Prize time! Tap the present!');await tapped;if(T!==tok)return;
const[cname,cicon]=COSTUMES[J.costume%COSTUMES.length];J.costume++;J.lastCostume=Object.assign({},J.lastCostume||{},{[F.key]:cname});saveJ();
sfx.fanfare();b.style.display='none';$('#prizeCh').innerHTML=charHTML(F.key,'big popOut');const ch=$('#prizeCh .chwrap');dress(ch,cname);confetti(180);
$('#prizeName').textContent=cicon+' '+cname+' '+F.name+' '+cicon;state.stickers.push([F.key,cname]);store.set('stickers',state.stickers);addStar();
await say(`Ta-da! It’s ${cname} ${F.name}!`);if(T!==tok)return;await fsay(F.key,'yay',ch);if(T!==tok)return;await wait(700);
await partyRun(T,16,true);if(T!==tok)return;await wait(400);
const[q,ans,em]=JOKES[J.joke%JOKES.length];J.joke++;saveJ();
await say('Ready for a joke?');if(T!==tok)return;await wait(600);$('#jokeBox').textContent='🤔';await say(q);if(T!==tok)return;sfx.drum();await wait(1500);if(T!==tok)return;
$('#jokeBox').textContent=em;$('#jokeBox').classList.remove('popIn');void $('#jokeBox').offsetWidth;$('#jokeBox').classList.add('popIn');
await say(ans);if(T!==tok)return;sfx.rimshot();hop(ch);await wait(400);await say('Hee hee hee!');if(T!==tok)return;await wait(700);
await fsay(F.key,'bye',ch);if(T!==tok)return;await say(`Bye bye, ${F.name}! Who’s next?`);if(T!==tok)return;sceneDone(T)}
/* ---------- SILLY BUTTON and the giant puppy ---------- */
async function silly(){sfx.tap();const r=Math.random(),chs=$$('.screen.on .chwrap');if(r<.3){bigRise(true);return}
if(r<.55){sfx.toot();chs.forEach(c=>{hop(c);trick(c)});if(!speaking)say('Oops! Was that a toot? Hee hee!');return}
if(r<.8){visitor();chs.forEach(trick);return}
sfx.kazoo();burst();confetti(80);chs.forEach(trick);if(!speaking)say('Beep, beep! Coming through!')}
/* ---------- HOME ---------- */
let greeted=false;
function homeScene(){newTok();show('home');$('#homeRow').innerHTML=['th','f','v','s'].map(k=>charHTML(k,'homeCh')).join('');
$('#shelf').innerHTML=state.stickers.length?'<b>Sticker book:</b>'+state.stickers.slice(-14).map(([k,c])=>`<span title="${c} ${SQUAD[k].name}">${SQUAD[k].icon}${HATS[c]||''}</span>`).join(''):'';
say(greeted?`Tap play${nm()}!`:`Hi${state.name?' '+state.name:''}! Meet the Silly Sound Squad! Tap the big play button!`);greeted=true}
const SCENES={reveal:revealScene,mirror:mirrorScene,power:powerScene,who:whoScene,feed:feedScene,prize:prizeScene};
const PREP={reveal:prepReveal,mirror:prepMirror,power:prepPower,who:prepWho,feed:prepFeed,prize:prepPrize};
/* Every line the game can say (the recording script reads this). */
function allLines(n){const L=[];const add=(t,pre='')=>L.push([t,pre]);
Object.values(SQUAD).forEach(F=>{F.steps.forEach(s=>add(s[1]));F.words.forEach(([w])=>{add(w,'w:');add(w,'slow:');add(`Your turn! Say: ${w}.`)});add(INTRO[F.key]);add(TURN[F.key]);add(YAY[F.key]);POWER[F.key].forEach(x=>add(x));add(FEED[F.key]);add(FOUND[F.key]);
COSTUMES.forEach(c=>add(`Ta-da! It’s ${c[0]} ${F.name}!`));add(`Bye bye, ${F.name}! Who’s next?`)});
Object.values(TIP).forEach(x=>add(x));NEXTWORD.forEach(x=>add(x));
JOKES.forEach(j=>{add(j[0]);add(j[1])});Object.entries(FRIEND).forEach(([k,o])=>Object.values(o).flat().forEach(t=>add(t,'v_'+k+':')));MOVES.forEach(m=>{if(m[1])add(m[1])});
['Knock, knock! Who is coming to play today? Tap the door!','Who said it? Listen, and tap the friend whose sound you hear.','Listen again.','Let’s do it together, slowly.','Ooh, nice try!',
'Prize time! Tap the present!','Ready for a joke?','Hee hee hee!','Oops! Was that a toot? Hee hee!','Beep, beep! Coming through!','Peekaboo! I see you!','Squad dance party! Dance with your friends!','Freeze!','Dance!',
`Great dancing, ${n}!`,`Yes! Good job, ${n}!`,`Great trying, ${n}!`,`Tap play, ${n}!`,`Hi ${n}! Meet the Silly Sound Squad! Tap the big play button!`].forEach(x=>add(x));
return L}
/* ---------- SILLY EXTRAS: friend voices, googly eyes, tap tricks, visitors, comic bursts ---------- */
// Each friend talks in its own cartoon voice (clips keyed "v_<friend>:<line>"). No friend line uses a practice sound
// except where a checked word is spliced in, so the voices are silly without modelling a sound wrong.
const FRIEND={
th:{hi:'Woof woof! Hi hi hi! Wanna play with me?',tickle:['Hee hee hee! That tickles!','Woof! Do it again!'],yay:['Woof! You did it! Yippee!','Woof woof! Hooray!'],yum:['Yum yum yum! Woof!','Burp! Oops! Woof!'],bye:'Bye bye! Woof woof!',dance:'Woof woof! Dance with me!'},
f:{hi:'Hop hop hop! Hello! Let’s play!',tickle:['Hee hee! Bunny giggles!','Hop hop! Hee hee!'],yay:['Yay! You did it! Hop hop!','Yippee! You did it!'],yum:['Crunchy munchy! Yum!','Nom nom nom! Yummy!'],bye:'Bye bye! Hop hop!',dance:'Hop hop! Dance with me!'},
v:{hi:'Beep beep! Ready, set, go!',tickle:['Beep! Hee hee! That tickles!','Beep beep beep! Hee hee!'],yay:['Beep beep! You’re a superstar!','Yay! Beep beep! You did it!'],yum:['Glug glug glug! Yummy!','Yummy! Burp! Beep beep!'],bye:'Beep beep! Bye bye!',dance:'Beep beep! Dance with me!'},
s:{hi:'Hiss hiss! Hello, hello! I’m so happy!',tickle:['Hee hee! Wiggle wiggle!','Hee hee hee! That tickles!'],yay:['Yes yes yes! You did it!','Yay! Wiggle wiggle!'],yum:['Slurp! Yummy yummy!','Slurp slurp! Yum!'],bye:'Bye bye! Hiss hiss!',dance:'Wiggle wiggle! Dance with me!'}};
const fline=(k,kind)=>{const v=FRIEND[k][kind];return Array.isArray(v)?pick(v):v};
function fsay(k,kind,el){const t=fline(k,kind);if(el){act(el,true);trick(el)}const p=say(t,{pre:'v_'+k+':'});if(el)p.then(()=>act(el,false));return p}
// Tap any friend: a giggle and a random trick (never while the game is listening).
const TRICKS=['r-spin','r-jelly','r-flip','r-boing','r-eyes','r-squish'];
function trick(el){if(!el)return;TRICKS.forEach(c=>el.classList.remove(c));void el.offsetWidth;const c=pick(TRICKS);el.classList.add(c);setTimeout(()=>el.classList.remove(c),900)}
document.addEventListener('click',e=>{const el=e.target.closest('.chwrap');if(!el||e.target.closest('.whoBtn'))return;const k=el.dataset.ch;
if(!k)return;pick([sfx.boing2,sfx.slideUp,sfx.pop])();trick(el);if(!speaking&&!mic.rec&&!PW.active&&!$('#ear').classList.contains('on'))fsay(k,'tickle',el)});
// Googly eyes follow the finger or mouse.
function lookAt(x,y){const r=document.documentElement;r.style.setProperty('--ex',(((x/innerWidth)-.5)*7).toFixed(2)+'px');r.style.setProperty('--ey',(((y/innerHeight)-.5)*6).toFixed(2)+'px')}
['pointermove','pointerdown'].forEach(ev=>addEventListener(ev,e=>lookAt(e.clientX,e.clientY),{passive:true}));
setInterval(()=>{if(Math.random()<.5)lookAt(Math.random()*innerWidth,Math.random()*innerHeight)},2600);
// Comic burst words on every win.
const BURSTS=['WOW!','YAY!','SUPER!','BOOM!','WOO-HOO!','YES!','KA-POW!'];
function burst(){const b=document.createElement('div');b.className='burst';b.textContent=pick(BURSTS);b.style.left=(25+Math.random()*50)+'vw';b.style.top=(28+Math.random()*25)+'vh';b.style.setProperty('--r',(Math.random()*24-12).toFixed(0)+'deg');document.body.appendChild(b);setTimeout(()=>b.remove(),1300)}
// Silly visitors wander across now and then.
const VISITORS=[['🐄🎈','rise'],['🐔','run'],['🦆','run'],['🛸','fly'],['🐸','leap'],['🦕','run'],['🐷🎈','rise'],['🐒','leap'],['🦒','run'],['🍕','fly'],['🐳','swim'],['🦄','fly']];
function visitor(){if($('#party').classList.contains('on')||mic.rec||$('#ear').classList.contains('on')||$('#start'))return;const[e,a]=pick(VISITORS);floater(e,a);pick([sfx.slideUp,sfx.boing2,sfx.honk2])()}
setInterval(()=>{if(Math.random()<.55)visitor()},14000);
/* ---------- WIRING ---------- */
mirrorMouth=makeMouth($('#mirrorMouth'));feedMouth=makeMouth($('#feedMouth'));
$('#starN').textContent=state.stars;
$('#startRow').innerHTML=['th','f','v','s'].map(k=>charHTML(k)).join('');
setInterval(()=>{if($('#s-home').classList.contains('on')&&!speaking&&!$('#party').classList.contains('on'))bigRise(false)},16000);
$('#playBtn').onclick=()=>{sfx.tap();journeyGo()};
$('#homeBtn').onclick=()=>{sfx.tap();homeScene()};
$('#sillyBtn').onclick=silly;
$('#musicBtn').onclick=()=>{setMusic(!state.music);store.set('music',state.music)};
$('#fsBtn').onclick=()=>{const el=document.documentElement;try{if(document.fullscreenElement||document.webkitFullscreenElement){(document.exitFullscreen||document.webkitExitFullscreen).call(document)}else{const f=el.requestFullscreen||el.webkitRequestFullscreen;const p=f&&f.call(el);if(p&&p.catch)p.catch(()=>{})}}catch(e){}};
function micText(){const m={on:'🎤 The friends can hear him.',off:'Microphone is off. You tap “He did it” instead.',denied:'The microphone was blocked. Allow it in the browser settings, then reload. Until then you tap instead.',unsupported:'This browser cannot share the microphone here. You tap instead.'};$('#micState').textContent=m[mic.state]||''}
$('#grownBtn').onclick=()=>{$('#nameIn').value=state.name;fillVoiceSel();$$('#soundPick input').forEach(c=>c.checked=state.sounds.includes(c.value));$('#micIn').checked=state.micWanted;micText();$('#grown').classList.add('on')};
$('#micIn').onchange=async()=>{state.micWanted=$('#micIn').checked;store.set('mic',state.micWanted);if(state.micWanted){initAudio();await micStart()}else micStop();micText()};
$('#closeGrown').onclick=()=>{const n=$('#nameIn').value.trim();if(n){state.name=n;store.set('name',n)}const v=$('#voiceSel').value;const vv=enVoices().find(x=>x.name===v);if(vv){voice=vv;state.voiceName=v;store.set('voice',v)}
const s=$$('#soundPick input').filter(c=>c.checked).map(c=>c.value);const changed=s.join()!==state.sounds.join();state.sounds=s.length?s:['th','f','v','s'];store.set('sounds',state.sounds);
$('#grown').classList.remove('on');if(changed){J.station=0;saveJ();homeScene()}};
$('#resetBtn').onclick=()=>{state.stars=0;state.stickers=[];Object.assign(J,{round:0,station:0,joke:0,costume:0,lastCostume:{}});saveJ();store.set('stars',0);store.set('stickers',[]);$('#starN').textContent=0;$('#grown').classList.remove('on');homeScene()};
$('#startBtn').onclick=async()=>{const b=$('#startBtn');if(b.disabled)return;b.disabled=true;initAudio();preloadClips();pickVoice();if(state.micWanted)await micStart();$('#start').remove();setMusic(state.music);homeScene()};
index.html147 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
<meta name="description" content="A silly speech-practice game for little kids: four friends teach TH, F, V and S, and the game listens through the microphone and cheers every try.">
<meta name="theme-color" content="#8fd8ff">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Sound Squad">
<link rel="icon" href="./icon-192.png" type="image/png">
<link rel="apple-touch-icon" href="./icon-192.png">
<title>Silly Sound Squad – TH, F, V and S for little talkers</title>
<link rel="preload" href="./fonts/fredoka-600.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="./sounds.css">
</head>
<body>
<div id="app">
<div class="sky"><i class="st s1"></i><i class="st s2"></i><i class="st s3"></i><i class="st s4"></i><i class="st s5"></i><i class="st s6"></i></div>
<div class="cloud c1"></div>
<div class="cloud c2"></div>
<div id="bigTurtle"><svg viewBox="0 0 400 300">
<path d="M70 120 C20 130 10 250 60 262 C96 250 104 170 104 140Z" fill="#8b5a2b"/><path d="M330 120 C380 130 390 250 340 262 C304 250 296 170 296 140Z" fill="#8b5a2b"/>
<ellipse cx="200" cy="200" rx="150" ry="125" fill="#f2c27b"/><ellipse cx="250" cy="160" rx="46" ry="40" fill="#d99a4e" opacity=".5"/>
<ellipse cx="200" cy="240" rx="80" ry="58" fill="#fbe3bd"/>
<circle cx="145" cy="160" r="30" fill="#fff"/><circle class="pupil" cx="150" cy="164" r="17" fill="#1d2b3a"/><circle cx="156" cy="156" r="5" fill="#fff"/>
<circle cx="255" cy="160" r="30" fill="#fff"/><circle class="pupil" cx="260" cy="164" r="17" fill="#1d2b3a"/><circle cx="266" cy="156" r="5" fill="#fff"/>
<rect class="lid r" x="223" y="128" width="64" height="64" rx="32" fill="#e0a35a"/>
<ellipse cx="200" cy="212" rx="28" ry="20" fill="#2b2b3a"/>
<path d="M160 246 Q200 270 240 246" stroke="#2b2b3a" stroke-width="7" fill="none" stroke-linecap="round"/>
<g class="bt-tongue"><path d="M178 254 Q200 320 222 254 Z" fill="#ff7a9a" stroke="#d9546f" stroke-width="4"/></g>
<ellipse cx="105" cy="230" rx="22" ry="13" fill="#ff9aa8" opacity=".7"/><ellipse cx="295" cy="230" rx="22" ry="13" fill="#ff9aa8" opacity=".7"/>
</svg></div>
<div class="sun"><svg viewBox="0 0 200 200"><g class="rays" stroke="#ffc93c" stroke-width="12" stroke-linecap="round"><path d="M100 8v26M100 166v26M8 100h26M166 100h26M35 35l18 18M147 147l18 18M35 165l18-18M147 53l18-18"/></g>
<circle cx="100" cy="100" r="54" fill="#ffd23f"/><path d="M58 88h84" stroke="#2b2b3a" stroke-width="6"/><rect x="58" y="80" width="38" height="24" rx="10" fill="#2b2b3a"/><rect x="104" y="80" width="38" height="24" rx="10" fill="#2b2b3a"/><path d="M66 86l10 0" stroke="#fff" stroke-width="4" stroke-linecap="round" opacity=".7"/>
<path d="M76 122 Q100 146 124 122" stroke="#2b2b3a" stroke-width="6" fill="none" stroke-linecap="round"/><ellipse cx="66" cy="118" rx="9" ry="6" fill="#ff9a5a" opacity=".7"/><ellipse cx="134" cy="118" rx="9" ry="6" fill="#ff9a5a" opacity=".7"/></svg></div>
<div class="rainbow"></div>
<div class="hills"></div>
<div class="flowers"><span>🌼</span><span>🌷</span><span>🍄</span><span>🌻</span><span>🌸</span><span>🌼</span><span>🌷</span></div>
<header>
<button class="ib" id="homeBtn" aria-label="Home">🏠</button>
<div class="stars" id="stars">⭐ <span id="starN">0</span></div>
<div class="trail" id="trail"><i>🚪</i><i>👄</i><i>⚡</i><i>👂</i><i>🍎</i><i>🎁</i></div>
<div class="sp"></div>
<button class="ib" id="sillyBtn" aria-label="Silly surprise">🤪</button>
<button class="ib" id="danceBtn" aria-label="Dance party">💃</button>
<button class="ib off" id="musicBtn" aria-label="Music">🎵</button>
<button class="ib" id="fsBtn" aria-label="Full screen">⛶</button>
<button class="ib" id="grownBtn" aria-label="For grown-ups">👪</button>
</header>
<div id="bubble"><div id="cap">Hi!</div></div>
<section class="screen" id="s-home">
<h1>Silly <b>Sound</b> Squad</h1>
<div class="homeRow" id="homeRow"></div>
<button class="btn green big" id="playBtn">▶ Play!</button>
<div class="shelf" id="shelf"></div>
</section>
<section class="screen" id="s-reveal">
<div class="revealStage"><div id="door" class="door"><div class="doorL"></div><div class="knob"></div><span>?</span></div><div id="revealCh"></div></div>
<div class="bigName" id="revealName"></div>
</section>
<section class="screen" id="s-mirror">
<div id="stepBig"></div>
<div class="mirrorRow"><div id="mirrorCh"></div><div class="mouth bigMouth" id="mirrorMouth"></div></div>
<div class="ctl" id="mirrorCtl"></div>
</section>
<section class="screen" id="s-power">
<div class="field" id="field"></div>
<div class="bar"><i id="pbar"></i></div>
<button id="holdBtn" class="disabled"><span>👆</span><b>HOLD ME</b></button>
</section>
<section class="screen" id="s-who">
<div class="prog" id="whoProg"></div>
<button class="ib" id="whoSpk" aria-label="Hear it again">🔊</button>
<div class="whoRow" id="whoRow"></div>
</section>
<section class="screen" id="s-feed">
<div class="feedRow"><div id="feedCh"></div><div class="foodCard"><div id="food"></div><div id="foodWord"></div><div class="mouth" id="feedMouth"></div></div></div>
<div class="ctl" id="feedCtl"></div>
</section>
<section class="screen" id="s-prize">
<div id="box">🎁</div>
<div id="prizeCh"></div>
<div class="bigName" id="prizeName"></div>
<div id="jokeBox"></div>
</section>
<div id="ear"><div class="ring"></div><div class="core">🎤</div><b id="earLbl">Listening…</b></div>
<div id="turn"><svg viewBox="0 0 150 150"><circle cx="75" cy="75" r="68"/></svg><div class="in"><span>🗣️</span>Your turn!</div></div>
<div id="party"><div class="beam b1"></div><div class="beam b2"></div><div class="beam b3"></div><div class="beam b4"></div><div class="ball">🪩</div><div id="freezeTxt">FREEZE!</div>
<div id="partyTheo"></div>
<div class="friends"><span>🎈</span><span>⭐</span><span>🎉</span><span>🌈</span><span>🎈</span></div>
<button class="ib" id="partyX" aria-label="Stop dancing">✖</button></div>
<div id="wave"><div class="surf" id="waveCh"></div><div class="where" id="waveWhere"></div></div>
<div id="fxLayer"></div>
<canvas id="fx"></canvas>
<div class="modal" id="grown">
<div class="sheet">
<h2>👪 For grown-ups</h2>
<label>Child's name (optional; names use the device voice)</label>
<input id="nameIn" maxlength="20">
<label>This week's sounds</label>
<div class="soundPick" id="soundPick">
<label><input type="checkbox" value="th"> 🐶 TH (Thunder)</label>
<label><input type="checkbox" value="f"> 🐰 F (Fifi)</label>
<label><input type="checkbox" value="v"> 🏎️ V (Vinny)</label>
<label><input type="checkbox" value="s"> 🐍 S (Sunny)</label>
</div>
<label class="micRow"><input type="checkbox" id="micIn"> 🎤 Listen with the microphone</label>
<p class="micState" id="micState"></p>
<label>Backup device voice</label>
<select id="voiceSel"></select>
<ul>
<li><b>How it flows:</b> one Play tap runs a loop. Each round a friend visits: the door, the mouth mirror, a power game the child's voice drives, Who said it?, Feed the friend, then a prize costume, a dance party and a joke. It remembers where you stopped.</li>
<li><b>What the microphone can tell:</b> a soft breezy hiss (TH or F), a sharp snake hiss (S), a quick pop (T, P, D) and a voice. It cannot tell TH from F, and for V it only checks that it heard a voice. The mouth picture and you cover the rest: tap <b>👍 Said it right</b> whenever it misses.</li>
<li><b>Always positive:</b> another sound is never "wrong"; it is another friend's sound. After two tries the friend eats the word anyway and the child gets a star.</li>
<li><b>Play, not therapy.</b> This is a game for practice at home. If a professional is helping your child, follow their cues first.</li>
<li><b>No sound?</b> Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent. Sound comes out of the speaker while the microphone is on.</li>
<li><b>Privacy:</b> the child's voice is analysed on this device while they speak and is never saved or sent anywhere.</li>
</ul>
<p class="more"><a href="/">More free tools by Shahrouz Ghadimi</a></p>
<div class="sheetBtns">
<button class="btn" id="resetBtn">Start over</button>
<button class="btn green" id="closeGrown">Done</button>
</div>
</div>
</div>
<div id="start">
<div class="startRow" id="startRow"></div>
<h1>Silly <b>Sound</b> Squad</h1>
<p>A sound game for little talkers. Turn the sound on 🔊, then tap Allow so the friends can hear you.</p>
<button class="btn green big" id="startBtn">Tap to start</button>
</div>
</div>
<script src="./sounds.js"></script>
</body>
</html>
sounds.css (look, layout, characters and the Fredoka font)405 lines
@font-face{font-family:Fredoka;font-weight:500;font-display:swap;src:url(./fonts/fredoka-500.woff2) format("woff2")}
@font-face{font-family:Fredoka;font-weight:600;font-display:swap;src:url(./fonts/fredoka-600.woff2) format("woff2")}
@font-face{font-family:Fredoka;font-weight:700;font-display:swap;src:url(./fonts/fredoka-700.woff2) format("woff2")}
.cloud.c1{top:16%;width:160px;height:46px;animation-duration:70s;animation-delay:-20s}
.cloud.c2{top:30%;width:110px;height:34px;animation-duration:95s;animation-delay:-60s}
#earMouth{width:min(200px,32vw);aspect-ratio:4/3}
.sheetBtns{display:flex;gap:10px;flex-wrap:wrap}
:root{--ink:#24324f;--pink:#ff5d8f;--gold:#ffc93c;--green:#3fbf74;--blue:#36a9e1;--purple:#8a6cff;--card:#ffffffee}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent;user-select:none;-webkit-user-select:none}
html,body{margin:0;height:100%;overflow:hidden;font-family:Fredoka,system-ui,sans-serif;color:var(--ink)}
body{background:linear-gradient(180deg,#8fdcff 0%,#c8f1ff 55%,#fff1c4 100%)}
#app{position:fixed;inset:0;padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)}
.cloud{position:absolute;background:#fff;border-radius:60px;opacity:.7;animation:drift linear infinite}
.cloud:before,.cloud:after{content:"";position:absolute;background:#fff;border-radius:50%}
.cloud:before{width:55%;height:150%;left:15%;top:-60%}.cloud:after{width:40%;height:120%;right:12%;top:-40%}
@keyframes drift{from{transform:translateX(-30vw)}to{transform:translateX(130vw)}}
.waves{position:absolute;left:0;right:0;bottom:0;height:11vh;background:radial-gradient(circle at 50% 0,#5cc8f0 30%,transparent 31%) 0 0/80px 40px repeat-x,linear-gradient(#5cc8f0,#36a9e1);opacity:.5;pointer-events:none;animation:lap 4s ease-in-out infinite}
@keyframes lap{50%{transform:translateY(6px)}}
header{position:absolute;top:calc(env(safe-area-inset-top) + 10px);left:12px;right:12px;display:flex;gap:10px;align-items:center;z-index:30}
.ib{border:0;background:#fff;border-radius:18px;width:54px;height:54px;font-size:26px;box-shadow:0 5px 0 #0002;cursor:pointer;font-family:inherit}
.ib:active{transform:translateY(3px);box-shadow:0 2px 0 #0002}
.ib.off{opacity:.45}
.stars{background:#fff;border-radius:18px;height:54px;padding:0 16px;display:flex;align-items:center;gap:6px;font-size:26px;font-weight:700;box-shadow:0 5px 0 #0002}
.stars.bump{animation:bump .5s}
@keyframes bump{50%{transform:scale(1.35) rotate(-6deg)}}
.trail{display:flex;gap:6px;background:#ffffffcc;border-radius:18px;height:54px;padding:0 12px;align-items:center;font-size:24px;box-shadow:0 5px 0 #0002}
.trail i{font-style:normal;opacity:.35;transition:all .3s}
.trail i.done{opacity:.8}
.trail i.now{opacity:1;transform:scale(1.35)}
.sp{flex:1}
#bubble{position:absolute;top:calc(env(safe-area-inset-top) + 76px);left:50%;transform:translateX(-50%);width:min(720px,90vw);background:#fff;border-radius:24px;padding:8px 18px;display:flex;align-items:center;min-height:54px;box-shadow:0 6px 0 #0001;z-index:25}
#cap{font-size:clamp(16px,2.1vw,21px);font-weight:500;line-height:1.25;width:100%;text-align:center}
.screen{position:absolute;inset:0;padding:calc(env(safe-area-inset-top) + 146px) 12px 16px;display:none;flex-direction:column;align-items:center;justify-content:center;gap:16px;overflow:hidden}
.screen.on{display:flex}
.btn{border:0;font-family:inherit;font-weight:700;font-size:clamp(20px,2.6vw,28px);padding:16px 26px;border-radius:24px;background:#fff;color:var(--ink);box-shadow:0 6px 0 #0002;cursor:pointer}
.btn:active{transform:translateY(4px);box-shadow:0 2px 0 #0002}
.btn.gold{background:var(--gold)}.btn.green{background:var(--green);color:#fff}
.btn.big{font-size:clamp(26px,3.6vw,38px);padding:20px 40px;animation:pulse 1.6s ease-in-out infinite}
@keyframes pulse{50%{transform:scale(1.07)}}
h1{margin:0;font-size:clamp(36px,6vw,64px);color:#fff;text-shadow:0 4px 0 #2a7fb8,0 8px 18px #0003;text-align:center;line-height:1}
h1 b{color:var(--gold)}
/* THEO */
.theo{width:100%;height:auto;overflow:visible}
.theo .th-head{animation:peek 4s ease-in-out infinite}
@keyframes peek{0%,15%{transform:translateX(-72px)}32%,78%{transform:translateX(0)}92%,100%{transform:translateX(-72px)}}
.theo .hat{font-size:50px}
#homeTheo{width:min(330px,58vw);filter:drop-shadow(0 10px 8px #0002);animation:bob 2.4s ease-in-out infinite}
@keyframes bob{50%{transform:translateY(-8px)}}
#buddy{position:fixed;left:max(8px,env(safe-area-inset-left));bottom:max(6px,env(safe-area-inset-bottom));width:min(190px,24vw);z-index:22;cursor:pointer;filter:drop-shadow(0 6px 6px #0002);display:none}
#buddy.show{display:block}
#buddy svg{transform-origin:50% 90%}
.peekOut .th-head{animation:none!important;transform:none!important;transition:transform .4s}
.dance svg{animation:dance .45s ease-in-out 4}
@keyframes dance{25%{transform:rotate(-10deg) translateY(-14px)}75%{transform:rotate(10deg) translateY(-14px)}}
.laugh svg{animation:laugh .18s ease-in-out 10}
@keyframes laugh{50%{transform:scale(1.06,.94) translateY(4px)}}
.tiles{display:grid;grid-template-columns:repeat(4,minmax(0,150px));gap:12px}
.tile{border:0;font-family:inherit;background:var(--card);border-radius:24px;padding:12px 6px;box-shadow:0 6px 0 #0002;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:2px;font-size:16px;font-weight:600;color:var(--ink)}
.tile span{font-size:42px}
.shelf{display:flex;gap:6px;font-size:32px;background:#ffffff99;border-radius:18px;padding:4px 14px;max-width:92vw;overflow:hidden;align-items:center}
.shelf:empty{display:none}
.shelf b{font-size:16px;margin-right:6px}
@media (max-width:700px){.tiles{grid-template-columns:repeat(2,minmax(0,150px))}.trail{display:none}}
/* MOUTH */
.bigMouth{width:min(520px,80vw,calc((100vh - 360px)*1.33));aspect-ratio:4/3;min-width:240px}
.mouth svg{width:100%;height:100%;display:block;filter:drop-shadow(0 8px 10px #0002)}
#stepBig{font-size:clamp(26px,3.8vw,40px);font-weight:700;color:#fff;text-shadow:0 3px 0 #2a7fb8;display:flex;gap:12px;align-items:center;min-height:56px}
#stepBig span{font-size:1.4em}
.popIn{animation:popIn .5s cubic-bezier(.3,1.6,.5,1)}
@keyframes popIn{from{transform:scale(.3);opacity:0}}
.ctl{min-height:80px;display:flex;gap:12px;flex-wrap:wrap;justify-content:center;align-items:center}
/* TURN */
#turn{position:fixed;right:3vw;top:50%;transform:translateY(-50%) scale(0);width:150px;height:150px;z-index:40;transition:transform .35s cubic-bezier(.3,1.6,.5,1);pointer-events:none}
#turn.on{transform:translateY(-50%) scale(1)}
#turn .in{position:absolute;inset:14px;background:#fff;border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;font-weight:700;font-size:20px;box-shadow:0 8px 20px #0003}
#turn .in span{font-size:46px;animation:laugh .5s infinite}
#turn svg{position:absolute;inset:0;transform:rotate(-90deg)}
#turn circle{fill:none;stroke:var(--pink);stroke-width:12;stroke-linecap:round;stroke-dasharray:440;stroke-dashoffset:440}
#turn.on circle{animation:ring 5s linear forwards}
@keyframes ring{to{stroke-dashoffset:0}}
/* FEATHER */
.field{position:relative;width:min(880px,90vw);height:min(250px,30vh);background:linear-gradient(#bfe9ff,#f1fbff);border-radius:30px;box-shadow:inset 0 -12px 0 #9fe0a9;overflow:hidden}
#mover{position:absolute;left:7%;top:42%;font-size:clamp(54px,8vw,84px);transform:translate(-50%,-50%)}
#goal{position:absolute;right:4%;top:50%;transform:translateY(-50%);font-size:clamp(64px,10vw,104px)}
.windline{position:absolute;height:6px;border-radius:3px;background:#fff;opacity:0}
.bar{width:min(880px,90vw);height:20px;background:#ffffffaa;border-radius:12px;overflow:hidden}
.bar i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--green),var(--gold));border-radius:12px}
#holdBtn{width:min(240px,34vh);height:min(240px,34vh);border-radius:50%;border:8px solid #fff;background:radial-gradient(circle at 40% 35%,#9cf0b4,#3fbf74);box-shadow:0 10px 0 #2a8a52,0 16px 30px #0003;display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;touch-action:none;padding:0;font-family:inherit}
#holdBtn.pressed{transform:translateY(8px) scale(.97);box-shadow:0 2px 0 #2a8a52}
#holdBtn.disabled{filter:grayscale(.7);opacity:.6}
#holdBtn.ready{animation:pulse 1.2s infinite}
#holdBtn .mouth{width:72%;aspect-ratio:4/3}
#holdBtn b{color:#fff;font-size:22px;text-shadow:0 2px 0 #0003}
/* EAR */
.earWrap{display:flex;gap:24px;align-items:center;justify-content:center;flex-wrap:wrap}
.ecard{border:0;font-family:inherit;width:min(250px,36vw);aspect-ratio:1;background:#fff;border-radius:34px;box-shadow:0 8px 0 #0002;display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;color:var(--ink);transition:transform .3s,opacity .3s}
.ecard span{font-size:clamp(70px,11vw,120px);line-height:1.1}
.ecard em{font-style:normal;font-size:clamp(22px,3vw,32px);font-weight:600}
.ecard.hide{transform:scale(0) rotate(-20deg);opacity:0}
.ecard.wrong{animation:shake .5s}
.ecard.right{background:#d6f7e2;animation:jump .7s}
.ecard.hint{box-shadow:0 0 0 8px var(--gold),0 8px 0 #0002}
@keyframes shake{20%,60%{transform:translateX(-12px)}40%,80%{transform:translateX(12px)}}
@keyframes jump{40%{transform:translateY(-30px) scale(1.08)}}
#earBtn{font-size:58px;width:106px;height:106px;border-radius:50%}
.prog{font-size:30px;letter-spacing:6px}
/* SAY */
.path{position:relative;width:min(640px,84vw);height:92px;background:linear-gradient(#5cc8f0,#36a9e1);border-radius:46px}
.stone{position:absolute;top:50%;width:62px;height:44px;transform:translate(-50%,-50%);background:#f3dfae;border-radius:50%;box-shadow:0 5px 0 #c9b07a;display:flex;align-items:center;justify-content:center;font-size:22px}
.stone.done{background:#ffe680}
.stone.chest{width:74px;height:74px;background:none;box-shadow:none;font-size:50px}
#walker{position:absolute;top:40%;font-size:50px;transform:translate(-50%,-50%) scaleX(-1);transition:left .9s ease-in-out;z-index:2}
#walker.hop{animation:hop .9s}
@keyframes hop{50%{top:-5%}}
.wordCard{display:flex;align-items:center;gap:clamp(10px,3vw,30px);background:var(--card);border-radius:34px;padding:14px 26px;box-shadow:0 8px 0 #0002;flex-wrap:wrap;justify-content:center}
#wEmoji{font-size:clamp(80px,13vw,130px);line-height:1}
#wText{font-size:clamp(46px,8vw,84px);font-weight:700;letter-spacing:2px}
#wText .th{color:var(--pink);text-decoration:underline wavy;text-underline-offset:10px}
#wText.oops{color:#b9b9c9;text-decoration:line-through}
#sayMouth{width:min(240px,34vw);aspect-ratio:4/3}
/* TREASURE */
#chest{font-size:clamp(130px,22vw,210px);cursor:pointer;line-height:1}
#chest.shake{animation:wiggle .8s ease-in-out infinite}
@keyframes wiggle{20%{transform:rotate(-8deg)}40%{transform:rotate(8deg) scale(1.05)}60%{transform:rotate(-5deg)}80%{transform:rotate(0)}}
#chest.open{animation:popIn .6s}
#jokeBox{font-size:clamp(70px,12vw,130px);min-height:1.2em}
.flyHat{position:fixed;font-size:130px;z-index:58;pointer-events:none;transform:translate(-50%,-50%)}
/* WAVE TRANSITION */
#wave{position:fixed;inset:-5vh -10vw;z-index:65;pointer-events:none;transform:translateX(120%);background:linear-gradient(160deg,#5fd0f5,#2b9fd6);border-radius:40vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px}
#wave.go{animation:waveGo 2.4s ease-in-out forwards}
@keyframes waveGo{0%{transform:translateX(120%)}30%,70%{transform:translateX(0)}100%{transform:translateX(-120%)}}
#wave .surf{font-size:150px;animation:surf 1s ease-in-out infinite}
@keyframes surf{50%{transform:translateY(-20px) rotate(-8deg)}}
#wave .where{font-size:clamp(36px,6vw,60px);color:#fff;font-weight:700;text-shadow:0 4px 0 #0002}
/* FLOATERS */
#fxLayer{position:fixed;inset:0;pointer-events:none;z-index:50;overflow:hidden}
.flo{position:absolute;font-size:70px}
.fly{animation:fly 3s ease-in-out forwards}
@keyframes fly{0%{transform:translate(-15vw,0) rotate(0)}50%{transform:translate(50vw,-20vh) rotate(20deg)}100%{transform:translate(115vw,0) rotate(0)}}
.leap{animation:leap 2s ease-in-out forwards}
@keyframes leap{0%{transform:translateY(40vh) rotate(-40deg)}50%{transform:translateY(-10vh) rotate(0)}100%{transform:translateY(40vh) rotate(40deg)}}
.rise{animation:rise 3.2s ease-in forwards}
@keyframes rise{to{transform:translateY(-120vh)}}
.flo.swim{animation:swim 9s linear forwards}
canvas#fx{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:55}
.modal{position:fixed;inset:0;background:#0006;display:none;align-items:center;justify-content:center;z-index:70;padding:16px}
.modal.on{display:flex}
.sheet{background:#fff;border-radius:26px;max-width:620px;width:100%;max-height:88vh;overflow:auto;padding:22px 24px;font-size:17px;line-height:1.45;user-select:text;-webkit-user-select:text}
.sheet h2{margin:0 0 8px}.sheet li{margin-bottom:8px}
.sheet input,.sheet select{font-family:inherit;font-size:18px;padding:8px 12px;border-radius:12px;border:2px solid #ccd;width:100%;margin:4px 0 12px}
#start{position:fixed;inset:0;z-index:80;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;background:linear-gradient(180deg,#8fdcff,#c8f1ff 60%,#fff1c4);padding:20px;text-align:center}
#start p{font-size:20px;margin:0;color:#3a5a7a}
#startTheo{width:min(300px,56vw)}
.screen{z-index:2}
.theo .cape{transform-origin:200px 85px;animation:flutter 1.1s ease-in-out infinite}
@keyframes flutter{50%{transform:skewY(5deg) scaleX(1.05)}}
.c-shell,.c-hold{transition:opacity .3s}
#showTheo{width:min(360px,56vw);display:none;filter:drop-shadow(0 10px 10px #0003)}
#showTheo.on{display:block;animation:popOut 1s cubic-bezier(.3,1.6,.5,1)}
#showTheo.on svg{animation:dance .5s ease-in-out 1s 6}
@keyframes popOut{from{transform:translateY(160px) scale(.2) rotate(-30deg);opacity:0}}
#costumeName{font-size:clamp(30px,5vw,50px);font-weight:700;color:#fff;text-shadow:0 3px 0 #2a7fb8;min-height:1.2em}
.flyPiece{position:fixed;z-index:58;pointer-events:none;transform:translate(-50%,-50%);font-size:110px;line-height:1}
.sparkle{position:fixed;z-index:59;pointer-events:none;font-size:34px;animation:spk .9s ease-out forwards}
@keyframes spk{from{transform:translate(-50%,-50%) scale(.3);opacity:1}to{transform:translate(calc(-50% + var(--dx)),calc(-50% + var(--dy))) scale(1.2);opacity:0}}
/* PARTY */
#party{position:fixed;inset:0;z-index:62;display:none;background:radial-gradient(circle at 50% 35%,#4a2287,#140a2b);overflow:hidden;flex-direction:column;align-items:center;justify-content:center;gap:2vh}
#party.on{display:flex}
.beam{position:absolute;top:-8vh;left:50%;width:22vmin;height:125vh;margin-left:-11vmin;transform-origin:50% 0;border-radius:0 0 50% 50%;opacity:.55;pointer-events:none;will-change:transform;animation:beam 3.2s ease-in-out infinite alternate}
.beam.b1{background:linear-gradient(#ff5d8f,transparent 85%);animation-delay:-.4s}.beam.b2{background:linear-gradient(#ffd23f,transparent 85%);animation-delay:-1.3s;animation-duration:2.6s}
.beam.b3{background:linear-gradient(#36a9e1,transparent 85%);animation-delay:-2.1s;animation-duration:3.8s}.beam.b4{background:linear-gradient(#3fbf74,transparent 85%);animation-delay:-.9s;animation-duration:2.9s}
@keyframes beam{from{transform:rotate(-38deg)}to{transform:rotate(38deg)}}
.ball{position:absolute;top:calc(env(safe-area-inset-top) + 4px);font-size:76px;animation:swing 1s ease-in-out infinite alternate;transform-origin:50% -60px}
@keyframes swing{from{transform:rotate(-14deg)}to{transform:rotate(14deg)}}
#partyTheo{width:min(430px,66vw,60vh);position:relative;z-index:2;filter:drop-shadow(0 0 24px #fff5)}
#partyTheo svg{transform-origin:50% 90%}
.mv-bounce svg{animation:pBounce .5s ease-in-out infinite}
.mv-wiggle svg{animation:pWig .5s ease-in-out infinite}
.mv-spin svg{animation:pSpin 1s linear infinite}
.mv-jump svg{animation:pJump 1s ease-in-out infinite}
.mv-peek svg{animation:pBounce 1s ease-in-out infinite}
.mv-peek .th-head{animation:peekFast .5s ease-in-out infinite!important}
@keyframes pBounce{50%{transform:translateY(-28px) scaleY(1.04)}}
@keyframes pWig{25%{transform:rotate(-14deg)}75%{transform:rotate(14deg)}}
@keyframes pSpin{to{transform:rotateY(360deg)}}
@keyframes pJump{0%,100%{transform:translateY(0)}40%{transform:translateY(-80px) scale(1.08,.95)}}
@keyframes peekFast{0%,100%{transform:translateX(-72px)}50%{transform:translateX(0)}}
.friends{display:flex;gap:4vw;font-size:clamp(44px,7vw,72px);z-index:2}
.friends span{display:inline-block;animation:pBounce .5s ease-in-out infinite}
.friends span:nth-child(even){animation-name:pWig}
#party.frozen *{animation-play-state:paused!important}
#party.frozen #partyTheo{filter:drop-shadow(0 0 30px #9ef) saturate(.4) brightness(1.2)}
#freezeTxt{position:absolute;top:22%;font-size:clamp(56px,11vw,120px);font-weight:700;color:#d6f6ff;text-shadow:0 0 24px #6cf,0 6px 0 #1b6fa8;opacity:0;transform:scale(.3);transition:all .35s cubic-bezier(.3,1.6,.5,1);z-index:3;pointer-events:none}
#party.frozen #freezeTxt{opacity:1;transform:scale(1)}
#partyX{position:absolute;top:calc(env(safe-area-inset-top) + 12px);right:14px;z-index:4}
#party.auto #partyX{display:none}
/* BUBBLES */
#bubbleLayer{position:fixed;inset:0;z-index:57;pointer-events:none;display:none;overflow:hidden}
#bubbleLayer.on{display:block}
.bub{position:absolute;bottom:-160px;border-radius:50%;background:radial-gradient(circle at 30% 28%,#fff 0 8%,#e6f8ffcc 14%,#9fdcff66 45%,#ffffff22 70%);box-shadow:inset 0 0 20px #ffffffaa,0 0 14px #ffffff88;pointer-events:auto;animation:bubUp linear forwards;cursor:pointer}
@keyframes bubUp{50%{margin-left:30px}to{transform:translateY(-135vh)}}
/* BIG BACKGROUND TURTLE */
#bigTurtle{position:absolute;left:50%;bottom:-2vh;width:min(440px,58vw);transform:translate(-50%,115%);z-index:1;pointer-events:none}
#bigTurtle.up{animation:btRise 5.5s ease-in-out forwards}
@keyframes btRise{0%{transform:translate(-50%,115%)}16%{transform:translate(-50%,4%)}22%{transform:translate(-50%,10%)}78%{transform:translate(-50%,7%)}100%{transform:translate(-50%,118%)}}
#bigTurtle .pupil{transform-box:fill-box;transform-origin:center}
#bigTurtle.up .pupil{animation:look 5.5s ease-in-out}
@keyframes look{0%,25%{transform:translate(0,0)}35%{transform:translate(-14px,2px)}48%{transform:translate(14px,2px)}60%,100%{transform:translate(0,6px)}}
#bigTurtle .bt-tongue{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(0)}
#bigTurtle.up .bt-tongue{animation:btTongue 5.5s ease-in-out}
@keyframes btTongue{0%,55%{transform:scaleY(0)}62%,74%{transform:scaleY(1)}80%,100%{transform:scaleY(0)}}
#bigTurtle .lid{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(0)}
#bigTurtle.up .lid.r{animation:wink 5.5s ease-in-out}
@keyframes wink{0%,66%{transform:scaleY(0)}69%,72%{transform:scaleY(1)}75%,100%{transform:scaleY(0)}}
.waves{z-index:1}
.swim{animation:swim 9s linear forwards}
@keyframes swim{from{transform:translateX(-12vw) scaleX(-1)}to{transform:translateX(112vw) scaleX(-1)}}
.screen{overflow-y:auto;justify-content:flex-start;-webkit-overflow-scrolling:touch}
.screen>:first-child{margin-top:auto}.screen>:last-child{margin-bottom:auto}
@media (max-width:420px){header{gap:6px;left:8px;right:8px}header .ib{width:44px;height:44px;font-size:22px;border-radius:14px}.stars{height:44px;padding:0 10px;font-size:22px}#fsBtn{display:none}
#bubble{top:calc(env(safe-area-inset-top) + 64px)}.screen{padding-top:calc(env(safe-area-inset-top) + 132px)}}
@media (max-height:620px){header{top:calc(env(safe-area-inset-top) + 6px)}header .ib{width:44px;height:44px;font-size:22px;border-radius:14px}.stars,.trail{height:44px;font-size:21px}
#bubble{top:calc(env(safe-area-inset-top) + 58px);min-height:40px;padding:4px 14px}#cap{font-size:15px}
.screen{padding-top:calc(env(safe-area-inset-top) + 112px);padding-bottom:10px;gap:10px}
h1{font-size:32px}#homeTheo{width:min(200px,34vh)}
.btn{font-size:18px;padding:10px 18px}.btn.big{font-size:24px;padding:12px 26px}
.tile{padding:6px 4px;font-size:13px}.tile span{font-size:30px}
.bigMouth{width:min(400px,80vw,calc((100vh - 260px)*1.33));min-width:180px}#stepBig{font-size:24px;min-height:40px}
.wordCard{padding:8px 16px;gap:10px}#wEmoji{font-size:60px}#wText{font-size:38px}#sayMouth{width:min(160px,28vw)}
.path{height:66px}.stone{width:48px;height:34px}.stone.chest{font-size:38px}#walker{font-size:38px}
#holdBtn{width:min(190px,32vh);height:min(190px,32vh)}.field{height:min(200px,26vh)}
.ecard{width:min(190px,30vw,36vh)}.ecard span{font-size:min(80px,12vh)}#earBtn{width:80px;height:80px;font-size:42px}#earMouth{width:min(150px,26vw)}
#turn{width:110px;height:110px}#turn .in span{font-size:34px}#turn .in{font-size:15px}
#chest{font-size:min(130px,24vh)}#showTheo{width:min(260px,40vh)}#costumeName{font-size:26px}#jokeBox{font-size:60px}
.ctl{min-height:56px}#buddy{width:min(130px,20vw)}}
@media (max-height:420px){.screen{padding-top:calc(env(safe-area-inset-top) + 92px);gap:8px}#stepBig{font-size:20px;min-height:30px}.ctl{min-height:50px}#bubble{width:min(600px,70vw)}h1{font-size:24px}#homeTheo{width:min(150px,30vh)}
.tiles{grid-template-columns:repeat(4,minmax(0,120px))}.bigMouth{width:min(300px,50vw,calc((100vh - 235px)*1.33));min-width:150px}#partyTheo{width:min(260px,50vh)}.friends{font-size:36px}}
@media (max-width:420px){.tiles{grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;width:100%}.tile{padding:6px 2px;font-size:11px;border-radius:16px}.tile span{font-size:28px}h1{font-size:30px}#homeTheo{width:min(220px,30vh)}}
/* ---------- SILLY SOUND SQUAD ---------- */
body{background:linear-gradient(180deg,#8fd8ff 0%,#c9efff 55%,#fff4c7 100%)}
.sky .st{position:absolute;width:10px;height:10px;background:#fff;border-radius:50%;opacity:.0;animation:tw 3s ease-in-out infinite}
.hills{position:absolute;left:-5%;right:-5%;bottom:0;height:13vh;z-index:1;pointer-events:none;background:radial-gradient(ellipse 40% 100% at 20% 100%,#7ed957 98%,transparent 100%),radial-gradient(ellipse 45% 90% at 75% 100%,#63c94d 98%,transparent 100%),linear-gradient(#7ed95700,#7ed95700)}
.chwrap{position:relative;display:inline-block;width:100%;line-height:0}
.chwrap .ch{width:100%;height:auto;overflow:visible}
.chwrap .bob{transform-origin:50% 95%;animation:chBob 2.2s ease-in-out infinite;transform-box:fill-box}
@keyframes chBob{50%{transform:translateY(-4%) scale(1.02,.98)}}
.chwrap .ear{transform-box:fill-box;transform-origin:50% 10%;animation:earW 2.6s ease-in-out infinite}
.chwrap .ear.r{animation-delay:-1.3s}
@keyframes earW{50%{transform:rotate(-6deg)}}
.chwrap .tg{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(.55);transition:transform .25s}
.chwrap.act .tg{transform:scaleY(1.25)}
.chwrap .puff{opacity:0;transition:opacity .2s}
.chwrap.act .puff{opacity:1;animation:puffy .5s ease-in-out infinite}
@keyframes puffy{50%{transform:translateX(4px)}}
.chwrap .wheel{transform-box:fill-box;transform-origin:center}
.chwrap .wheel.spin,.chwrap.act .wheel{animation:spinW .4s linear infinite}
@keyframes spinW{to{transform:rotate(360deg)}}
.chwrap.act .ch-v .bob{animation:vroom .08s linear infinite}
@keyframes vroom{50%{transform:translate(1.5px,-1px)}}
.chwrap .flick{transform-box:fill-box;transform-origin:50% 0;animation:flick 2.4s ease-in-out infinite}
@keyframes flick{0%,70%,100%{transform:scaleY(0)}78%,90%{transform:scaleY(1)}}
.chwrap.act .ch-s .bob{animation:sway 1s ease-in-out infinite}
@keyframes sway{25%{transform:rotate(-4deg)}75%{transform:rotate(4deg)}}
.chwrap .hat,.chwrap .hold{position:absolute;line-height:1;pointer-events:none;font-size:calc(var(--cw,200px)*.26)}
.chwrap .hat{top:-14%;left:50%;transform:translateX(-50%) rotate(-6deg)}
.chwrap .hold{right:-8%;bottom:4%}
.chwrap.hop{animation:chHop .6s cubic-bezier(.3,1.6,.5,1)}
@keyframes chHop{40%{transform:translateY(-22%) rotate(-6deg)}70%{transform:translateY(0) rotate(4deg)}}
.popOut{animation:popOut .9s cubic-bezier(.3,1.6,.5,1)}
@keyframes popOut{from{transform:translateY(40%) scale(.2) rotate(-25deg);opacity:0}}
h1{font-size:clamp(38px,6.4vw,70px)}
.homeRow{display:flex;gap:clamp(6px,2vw,26px);align-items:flex-end;justify-content:center}
.homeRow .chwrap{width:min(170px,21vw);cursor:pointer}
.startRow{display:flex;gap:10px;justify-content:center}.startRow .chwrap{width:min(110px,20vw)}
.shelf span{font-size:30px;margin:0 2px}
/* door reveal */
.revealStage{position:relative;width:min(320px,58vw,46vh);aspect-ratio:3/4}
.door{position:absolute;inset:0;border-radius:46% 46% 14px 14px/34% 34% 14px 14px;background:linear-gradient(90deg,#c9772f,#e39a4e);border:8px solid #8a4a1c;box-shadow:0 12px 0 #0002;cursor:pointer;overflow:hidden;transform-origin:0 50%;transition:transform .8s cubic-bezier(.5,0,.3,1),opacity .8s}
.door .doorL{position:absolute;inset:12% 14%;border:6px solid #b0622a;border-radius:40% 40% 8px 8px/30% 30% 8px 8px}
.door .knob{position:absolute;right:12%;top:52%;width:28px;height:28px;border-radius:50%;background:#ffd23f;box-shadow:inset -4px -4px 0 #d9a400}
.door span{position:absolute;left:50%;top:22%;transform:translateX(-50%);font-size:clamp(60px,10vh,110px);font-weight:700;color:#fff6;line-height:1}
.door.wiggle{animation:knock 1s ease-in-out infinite}
@keyframes knock{10%,30%{transform:rotate(-2deg)}20%,40%{transform:rotate(2deg)}50%{transform:none}}
.door.open{transform:perspective(900px) rotateY(-100deg);opacity:.0;pointer-events:none}
#revealCh{position:absolute;inset:6% 0 0 0;display:flex;align-items:flex-end;justify-content:center}
#revealCh .chwrap{width:96%}
.bigName{font-size:clamp(30px,5.5vw,56px);font-weight:700;color:#fff;text-shadow:0 4px 0 #2a7fb8;min-height:1.2em}
/* mirror */
.mirrorRow{display:flex;align-items:center;gap:clamp(8px,2vw,24px)}
#mirrorCh{width:min(190px,22vw)}
/* power */
.field{position:relative;width:min(900px,92vw);height:min(330px,36vh);border-radius:30px;overflow:hidden;background:linear-gradient(#c9efff,#f6fdff);box-shadow:inset 0 -14px 0 #9fe0a9}
.field .pwCh{position:absolute;left:3%;bottom:4%;width:min(190px,22%)}
.field .wand{position:absolute;left:24%;top:46%;font-size:min(80px,9vh)}
.pbub{position:absolute;border-radius:50%;background:radial-gradient(circle at 30% 28%,#fff 0 8%,#e6f8ffcc 14%,#9fdcff66 45%,#ffffff22 70%);box-shadow:inset 0 0 14px #fff9;pointer-events:none}
.field .cake{position:absolute;left:52%;bottom:6%;transform:translateX(-50%);text-align:center}
.cakeBody{font-size:min(180px,20vh);line-height:1}
.flames{display:flex;gap:min(18px,2vh);justify-content:center;margin-bottom:-14px}
.flames i{display:block;width:16px;height:46px;border-radius:8px;background:linear-gradient(#ffe066 0 40%,#ff7aa8 40%);position:relative}
.flames i:before{content:"";position:absolute;left:50%;top:-26px;width:18px;height:26px;margin-left:-9px;border-radius:50% 50% 50% 50%/60% 60% 40% 40%;background:radial-gradient(circle at 50% 70%,#fff6b0,#ffb300 60%,#ff6a00);animation:flick2 .3s ease-in-out infinite alternate;transition:opacity .3s,transform .3s}
.flames i.out:before{opacity:0;transform:translateY(-14px) scale(.4)}
@keyframes flick2{to{transform:scale(.9,1.08) rotate(3deg)}}
.field .track{position:absolute;left:0;right:0;bottom:12%;height:22%;background:repeating-linear-gradient(90deg,#555 0 60px,#666 60px 120px);border-top:5px dashed #fff}
.field .flag{position:absolute;right:3%;bottom:22%;font-size:min(90px,10vh)}
.field .racer{position:absolute;left:4%;bottom:14%;width:min(180px,22%);transition:left .15s linear}
.field .balloon{position:absolute;left:62%;top:58%;transform:translate(-50%,0) scale(.35);transform-origin:50% 100%}
.balloon .bl{width:150px;height:180px;border-radius:50% 50% 48% 48%/55% 55% 45% 45%;background:radial-gradient(circle at 35% 30%,#fff9,#ff5d8f 30%,#e83f78);box-shadow:inset -10px -16px 0 #0001}
.balloon .str{width:3px;height:120px;background:#555;margin:0 auto}
#holdBtn{flex-direction:column}
#holdBtn span{font-size:56px}
/* listening badge */
#ear{position:fixed;left:50%;bottom:max(18px,env(safe-area-inset-bottom));transform:translateX(-50%) scale(0);z-index:45;width:150px;height:150px;transition:transform .3s cubic-bezier(.3,1.6,.5,1);pointer-events:none;--lv:0;--kc:#fff}
#ear.on{transform:translateX(-50%) scale(1)}
#ear .ring{position:absolute;inset:0;border-radius:50%;background:var(--kc);opacity:.55;transform:scale(calc(.55 + var(--lv)*.65));transition:transform .08s,background .15s}
#ear .core{position:absolute;inset:30px;border-radius:50%;background:#fff;display:flex;align-items:center;justify-content:center;font-size:44px;box-shadow:0 6px 16px #0003;animation:pulse 1.2s ease-in-out infinite}
#ear b{position:absolute;left:50%;bottom:-10px;transform:translateX(-50%);white-space:nowrap;background:#fff;border-radius:12px;padding:2px 10px;font-size:15px;box-shadow:0 3px 0 #0002}
.override{position:fixed;right:14px;bottom:max(14px,env(safe-area-inset-bottom));z-index:46;border:0;border-radius:16px;background:#fff;color:#24324f;font:600 15px Fredoka,system-ui;padding:10px 14px;box-shadow:0 4px 0 #0002;opacity:.92}
.cameo{position:fixed;right:3vw;bottom:14vh;width:min(180px,26vw);z-index:44;animation:cameo 3.6s ease-in-out forwards;pointer-events:none}
@keyframes cameo{0%{transform:translateX(140%) rotate(20deg)}15%,80%{transform:translateX(0) rotate(-4deg)}100%{transform:translateX(160%) rotate(10deg)}}
/* who said it */
#whoSpk{font-size:58px;width:110px;height:110px;border-radius:50%}
.whoRow{display:flex;gap:clamp(8px,2vw,22px);flex-wrap:wrap;justify-content:center}
.whoBtn{border:0;background:#fff;border-radius:28px;padding:10px 10px 6px;width:min(190px,27vw);box-shadow:0 7px 0 #0002;cursor:pointer;font-family:inherit;display:flex;flex-direction:column;align-items:center;gap:4px;color:#24324f}
.whoBtn b{font-size:clamp(16px,2.2vw,22px)}
.whoBtn.nope{animation:wob .6s}
@keyframes wob{25%{transform:rotate(-5deg)}75%{transform:rotate(5deg)}}
.whoBtn.hint{box-shadow:0 0 0 7px var(--gold),0 7px 0 #0002}
/* feed */
.feedRow{display:flex;align-items:center;gap:clamp(10px,3vw,40px);flex-wrap:wrap;justify-content:center}
#feedCh{width:min(250px,30vw)}
.foodCard{background:#fffffff0;border-radius:32px;padding:14px 22px;box-shadow:0 8px 0 #0002;display:flex;flex-direction:column;align-items:center;gap:4px;min-width:min(300px,60vw)}
#food{font-size:clamp(70px,12vw,120px);line-height:1.05;min-height:1.05em}
#foodWord{font-size:clamp(40px,7vw,72px);font-weight:700;letter-spacing:2px;line-height:1.1}
#foodWord .hl{color:var(--pink);text-decoration:underline wavy;text-underline-offset:8px}
#feedMouth{width:min(170px,30vw);aspect-ratio:4/3}
.flyFood{position:fixed;z-index:58;pointer-events:none;font-size:110px;line-height:1}
/* prize */
#box{font-size:clamp(120px,22vw,200px);cursor:pointer;line-height:1}
#box.shake{animation:wiggle .8s ease-in-out infinite}
#prizeCh{width:min(280px,46vh)}
#prizeCh:empty{display:none}
/* party friends + transition */
#partyTheo{display:flex;gap:2vw;width:min(860px,94vw);justify-content:center}
#partyTheo .chwrap{width:min(200px,22vw,26vh)}
#wave .surf{width:min(220px,40vw);font-size:inherit;animation:surf 1s ease-in-out infinite}
@media (max-height:620px){.field{height:min(240px,32vh)}#whoSpk{width:80px;height:80px;font-size:40px}.whoBtn{width:min(150px,24vw,30vh)}#feedCh{width:min(180px,26vw)}#food{font-size:64px}#foodWord{font-size:36px}#feedMouth{width:120px}
.revealStage{width:min(240px,44vw,48vh)}#mirrorCh{width:min(140px,20vw)}#ear{width:110px;height:110px}#ear .core{inset:22px;font-size:32px}#prizeCh{width:min(200px,40vh)}}
@media (max-width:420px){.homeRow .chwrap{width:22vw}.mirrorRow{flex-direction:column}#mirrorCh{width:30vw}.feedRow{flex-direction:column}#feedCh{width:38vw}}
@keyframes tw{50%{opacity:.9}}
.soundPick{display:flex;flex-wrap:wrap;gap:6px 14px;margin:4px 0 12px}
.soundPick label,.micRow{display:flex;align-items:center;gap:6px;font-size:18px;font-weight:600}
.sheet .soundPick input,.sheet .micRow input{width:24px;height:24px;margin:0}
.micState{margin:2px 0 12px;font-size:15px;color:#4a5a78}
.chwrap{container-type:inline-size}
.chwrap .hat,.chwrap .hold{font-size:26cqw}
#s-power #holdBtn{width:min(130px,18vh);height:min(130px,18vh);border-width:6px}
#s-power #holdBtn span{font-size:min(44px,6vh)}
#party #partyTheo{display:flex;gap:2vw;width:min(860px,94vw);justify-content:center}
#partyTheo .chwrap:nth-child(2) svg{animation-delay:-.15s}#partyTheo .chwrap:nth-child(3) svg{animation-delay:-.3s}#partyTheo .chwrap:nth-child(4) svg{animation-delay:-.45s}
#ear{left:auto;right:max(14px,env(safe-area-inset-right));transform:scale(0)}
#ear.on{transform:scale(1)}
.override{right:auto;left:14px}
.screen>*{flex-shrink:0}
.bigName{color:#ff5d8f;text-shadow:0 3px 0 #fff,0 0 14px #fff;text-align:center;line-height:1.15}
/* ---------- sillier look ---------- */
.chwrap .pup{transform:translate(var(--ex,0px),var(--ey,0px));transition:transform .25s cubic-bezier(.3,1.8,.5,1)}
.chwrap .lid{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(0);animation:blink 4.7s infinite}
.chwrap[data-ch="f"] .lid{animation-delay:-1.2s}.chwrap[data-ch="v"] .lid{animation-delay:-2.6s;animation-duration:5.3s}.chwrap[data-ch="s"] .lid{animation-delay:-3.7s;animation-duration:4.1s}
@keyframes blink{0%,93%,100%{transform:scaleY(0)}96%{transform:scaleY(1)}}
.chwrap.act .pup{animation:jiggle .18s linear infinite}
@keyframes jiggle{50%{transform:translate(calc(var(--ex,0px) + 1.5px),calc(var(--ey,0px) - 1px))}}
.chwrap .bob{animation:chBob2 1.1s ease-in-out infinite}
@keyframes chBob2{0%,100%{transform:translateY(0) scale(1.04,.96)}50%{transform:translateY(-7%) scale(.97,1.04)}}
.chwrap.r-spin svg{animation:rSpin .8s cubic-bezier(.4,1.6,.5,1)}@keyframes rSpin{to{transform:rotate(360deg)}}
.chwrap.r-jelly svg{animation:rJelly .8s}@keyframes rJelly{15%{transform:scale(1.25,.75)}30%{transform:scale(.8,1.2)}45%{transform:scale(1.12,.9)}60%{transform:scale(.95,1.05)}}
.chwrap.r-flip svg{animation:rFlip .8s ease-in-out}@keyframes rFlip{40%{transform:translateY(-30%) rotate(-180deg)}80%{transform:translateY(0) rotate(-360deg)}100%{transform:rotate(-360deg)}}
.chwrap.r-boing svg{animation:rBoing .8s cubic-bezier(.3,1.8,.5,1)}@keyframes rBoing{30%{transform:translateY(-40%) scale(.9,1.15)}60%{transform:translateY(0) scale(1.2,.8)}}
.chwrap.r-eyes .eyes{animation:rEyes .8s}.chwrap.r-eyes .eyes{transform-box:fill-box;transform-origin:center}@keyframes rEyes{20%,70%{transform:scale(1.6)}}
.chwrap.r-squish svg{transform-origin:50% 100%;animation:rSquish .8s}@keyframes rSquish{25%{transform:scale(1.4,.55)}55%{transform:scale(.85,1.25)}}
.burst{position:fixed;z-index:60;pointer-events:none;transform:translate(-50%,-50%) rotate(var(--r));font:700 clamp(34px,7vw,64px) Fredoka,system-ui;color:#fff;-webkit-text-stroke:3px #2b2b3a;paint-order:stroke;padding:.55em .8em;
background:#ffd23f;clip-path:polygon(50% 0,61% 24%,88% 8%,78% 36%,100% 46%,77% 58%,90% 88%,61% 74%,50% 100%,39% 74%,10% 90%,23% 58%,0 46%,22% 36%,12% 8%,39% 24%);animation:burstPop 1.3s cubic-bezier(.3,1.7,.5,1) forwards}
@keyframes burstPop{0%{transform:translate(-50%,-50%) rotate(var(--r)) scale(0)}25%{transform:translate(-50%,-50%) rotate(var(--r)) scale(1.15)}75%{transform:translate(-50%,-50%) rotate(var(--r)) scale(1);opacity:1}100%{transform:translate(-50%,-50%) rotate(var(--r)) scale(.6);opacity:0}}
.sun{position:absolute;right:4vw;top:calc(env(safe-area-inset-top) + 64px);width:min(120px,18vw);z-index:0;pointer-events:none;animation:sunBob 3s ease-in-out infinite}
.sun .rays{transform-origin:100px 100px;animation:spinW 14s linear infinite}
@keyframes sunBob{50%{transform:translateY(8px) rotate(6deg)}}
.cloud:before,.cloud:after{content:"";position:absolute;top:38%;width:7px;height:7px;border-radius:50%;background:#2b2b3a;opacity:.7;left:40%;box-shadow:16px 0 0 #2b2b3a}
.cloud:after{top:58%;left:46%;width:12px;height:5px;border-radius:0 0 12px 12px;box-shadow:none;background:#ff8fb1}
.flowers{position:absolute;left:0;right:0;bottom:1vh;z-index:1;display:flex;justify-content:space-around;pointer-events:none;font-size:clamp(22px,4vw,40px)}
.flowers span{display:inline-block;transform-origin:50% 100%;animation:flowerDance 1.2s ease-in-out infinite}
.flowers span:nth-child(even){animation-delay:-.6s}
@keyframes flowerDance{0%,100%{transform:rotate(-12deg) scaleY(1)}50%{transform:rotate(12deg) scaleY(.9)}}
.flo.run{animation:run 7s linear forwards;font-size:64px}
@keyframes run{from{transform:translateX(-12vw)}to{transform:translateX(112vw)}}
.flo.run:after{content:"";}
.screen{z-index:2}
.sun{top:calc(env(safe-area-inset-top) + 128px);width:min(100px,17vw)}
@media (min-width:700px){.sun{top:calc(env(safe-area-inset-top) + 70px);width:min(120px,12vw)}}
.rainbow{position:absolute;left:-8vw;bottom:6vh;width:min(420px,55vw);aspect-ratio:2/1;border-radius:50% 50% 0 0/100% 100% 0 0;z-index:0;pointer-events:none;opacity:.55;
background:radial-gradient(circle at 50% 100%,transparent 0 46%,#8a6cff 46% 52%,#36a9e1 52% 58%,#3fbf74 58% 64%,#ffd23f 64% 70%,#ff9f43 70% 76%,#ff5d8f 76% 82%,transparent 82%)}
@media (max-width:420px){#mirrorCh{width:40vw}#feedCh{width:44vw}}
#revealCh{pointer-events:none}#revealCh .chwrap{pointer-events:auto}
.more{margin:6px 0 14px}.more a{color:#1b6fa8;font-weight:600}
kit/listen.js (the listener on its own)149 lines
/* Silly Sound Squad listener: finds the word in a short recording and measures the hiss next to the vowel.
Verdicts: soft (a soft, spread hiss: TH or F), sharp (a loud, narrow S/Z hiss), pop (no long hiss: T, P, D),
voice (voicing, used for V), quiet (nothing heard). TH and F sound almost the same, so the listener
cannot tell them apart: the mouth picture and a grown-up cover that one. Nothing is saved or sent. */
(function (G) {
function fft(re, im) {
const n = re.length;
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
}
for (let len = 2; len <= n; len <<= 1) {
const a = -2 * Math.PI / len, wr = Math.cos(a), wi = Math.sin(a);
for (let i = 0; i < n; i += len) {
let cr = 1, ci = 0;
for (let k = 0; k < len / 2; k++) {
const ur = re[i + k], ui = im[i + k];
const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
re[i + k] = ur + vr; im[i + k] = ui + vi;
re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;
}
}
}
}
const winCache = {};
function hann(N) { if (!winCache[N]) { const w = new Float32Array(N); for (let i = 0; i < N; i++) w[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (N - 1)); winCache[N] = w; } return winCache[N]; }
function frameSize(sr) { return sr > 32000 ? 1024 : 512; }
// One frame of features from N samples starting at s.
function frame(x, s, N, sr) {
const w = hann(N), re = new Float64Array(N), im = new Float64Array(N);
let sq = 0, zc = 0, prev = x[s];
for (let i = 0; i < N; i++) { const v = x[s + i]; sq += v * v; re[i] = v * w[i]; if ((v >= 0) !== (prev >= 0)) zc++; prev = v; }
fft(re, im);
const bin = sr / N, half = N / 2, top = Math.min(11000, sr / 2 - bin);
let low = 0, mid = 0, high = 0, cn = 0, cd = 0, fl = 0, fa = 0, fc = 0, mx = 0, ca = 0, cc = 0;
for (let k = 1; k < half; k++) {
const f = k * bin, p = re[k] * re[k] + im[k] * im[k] + 1e-12;
if (f >= 80 && f < 900) low += p; else if (f >= 900 && f < 3000) mid += p; else if (f >= 3000 && f <= top) high += p;
if (f >= 1000 && f <= top) { cn += f * p; cd += p; }
if (f >= 1500 && f <= Math.min(10000, top)) { fl += Math.log(p); fa += p; fc++; }
if (f >= 3000 && f <= Math.min(10000, top)) { if (p > mx) mx = p; ca += p; cc++; }
}
const rms = Math.sqrt(sq / N);
return { db: 20 * Math.log10(rms + 1e-9), low, mid, high, zcr: zc / N,
cen: cd ? cn / cd : 0, flat: fc ? Math.exp(fl / fc) / (fa / fc) : 0, crest: cc ? mx / (ca / cc) : 0 };
}
function features(x, sr) {
const N = frameSize(sr), H = N / 2, out = [];
for (let s = 0; s + N <= x.length; s += H) { const f = frame(x, s, N, sr); f.t = s / sr; out.push(f); }
out.hopMs = 1000 * H / sr;
return out;
}
// The hiss right before (dir -1) or after (dir +1) the vowel.
function hissNear(F, from, dir, floor) {
const got = []; let miss = 0;
for (let i = from, n = 0; i >= 0 && i < F.length && n < 45; i += dir, n++) {
const f = F[i];
const fric = f.db > floor + 6 && f.high > f.low * 1.2 && f.zcr > 0.15;
if (fric) { got.push(f); miss = 0; }
else if (f.db < floor + 6) { if (++miss > 2 && got.length) break; if (miss > 4) break; }
else { if (++miss > 3) break; }
}
return got;
}
function analyze(x, sr, kind) {
const F = features(x, sr), hop = F.hopMs;
if (F.length < 8) return { verdict: 'quiet' };
const sorted = F.map(f => f.db).sort((a, b) => a - b);
const floor = Math.max(-75, sorted[Math.floor(sorted.length * 0.1)]), peak = sorted[sorted.length - 1];
if (peak - floor < 15) return { verdict: 'quiet', floor, peak };
// The vowel: the longest run of loud, low-pitched frames.
const voiced = F.map(f => f.db > peak - 24 && f.low > f.high && f.zcr < 0.2);
let best = null, s = -1, gap = 0; const runs = [];
for (let i = 0; i <= F.length; i++) {
if (i < F.length && voiced[i]) { if (s < 0) s = i; gap = 0; }
else if (s >= 0) {
if (i < F.length && ++gap <= 2) continue;
const e = i - gap; runs.push({ s, e }); if (!best || e - s > best.e - best.s) best = { s, e }; s = -1; gap = 0;
}
}
if (!best || (best.e - best.s + 1) * hop < 50) return { verdict: 'quiet', floor, peak };
const big = runs.filter(r => (r.e - r.s + 1) * hop >= 50);
if (kind === 'I' || kind === 'dhI' || kind === 'V') best = big[0]; else if (kind === 'F') best = big[big.length - 1];
let vpk = -200; for (let i = best.s; i <= best.e; i++) vpk = Math.max(vpk, F[i].db);
const info = { floor, peak, vowelMs: Math.round((best.e - best.s + 1) * hop) };
if (kind === 'thM' || kind === 'V') {
// Buzzy sounds (V, buzzy TH) and sounds in the middle of a word: heard is enough, unless a loud sharp hiss starts it (Z).
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3), rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const fl = pre.reduce((a, f) => a + f.flat, 0) / pre.length;
if (rel > -16 && fl < 0.25) return Object.assign({ verdict: 'sharp', rel, flat: fl }, info);
}
return Object.assign({ verdict: 'voice' }, info);
}
if (kind === 'dhI') {
// Buzzy TH: a soft start. D starts with a sudden burst; Z starts with a loud hiss.
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = pre.reduce((a, f) => a + f.cen, 0) / pre.length;
info.rel = rel; info.cen = cen;
if (rel > -16 && cen > 4000) return Object.assign({ verdict: 'sharp' }, info);
}
// Rise time from first sound to near the vowel's peak.
let on = best.s; while (on > 0 && F[on - 1].db > floor + 8) on--;
let r = on; while (r < F.length && F[r].db < vpk - 8) r++;
info.rise = (r - on) * hop;
let jump = 0; for (let i = Math.max(1, on - 1); i <= Math.min(r, F.length - 1); i++) jump = Math.max(jump, F[i].db - F[i - 1].db);
info.jump = jump; info.onHigh = F[on].high / (F[on].low + 1e-12); info.onDb = F[on].db - vpk;
const quietBefore = on > 0 && F[on - 1].db < floor + 6;
return Object.assign({ verdict: 'voice' }, info);
}
const fr = kind === 'F' ? hissNear(F, best.e + 1, 1, floor) : hissNear(F, best.s - 1, -1, floor);
info.hissMs = Math.round(fr.length * hop);
if (fr.length) { const chron = kind === 'F' ? fr : fr.slice().reverse(), mx = Math.max(...fr.map(f => f.db));
info.attack = Math.max(chron[0].db, (chron[1] || chron[0]).db) - mx; info.mean = fr.reduce((a, f) => a + f.db, 0) / fr.length - vpk;
info.flat = fr.reduce((a, f) => a + f.flat, 0) / fr.length; }
if (fr.length * hop < 40) return Object.assign({ verdict: 'pop' }, info);
const top = fr.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = fr.reduce((a, f) => a + f.cen, 0) / fr.length;
const crest = fr.reduce((a, f) => a + f.crest, 0) / fr.length;
Object.assign(info, { rel, cen, crest });
// A T or D: a loud puff that starts all at once and is over quickly.
if (kind === 'I' && info.mean > -13.5 && info.attack > -5 && info.hissMs <= 120) return Object.assign({ verdict: 'pop' }, info);
if (kind === 'I' && info.hissMs <= 65 && info.attack > -3.5) return Object.assign({ verdict: 'pop' }, info);
// An S: a narrow, sharp hiss (low flatness) that is fairly loud next to the vowel.
if (info.flat < 0.25 && info.mean > -18.5) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -11) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -20.5 && cen > 8000 && crest >= 10) return Object.assign({ verdict: 'sharp' }, info);
return Object.assign({ verdict: 'soft' }, info);
}
// Live sound for the blowing game: is this frame a soft TH breeze, a snake hiss or a voice?
function liveKind(f, floor) {
if (f.db < floor + 9) return 'none';
const hissy = f.high > f.low && f.zcr > 0.15;
if (hissy) return (f.flat < 0.25 && f.db > floor + 22) ? 'sharp' : 'soft';
if (f.low > f.high && f.zcr < 0.18) return (f.high > f.low * 0.05 || f.mid > f.low * 0.3) ? 'buzz' : 'voice';
return 'none';
}
G.SoundEar = { features, analyze, frame, frameSize, liveKind };
})(typeof window !== 'undefined' ? window : globalThis);
kit/index.src.txt (the source the page is split from)1,215 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
<title>Silly Sound Squad – TH, F, V and S for little talkers</title>
<style>
@font-face{font-family:Fredoka;font-weight:500;font-display:swap;src:url(./fonts/fredoka-500.woff2) format("woff2")}
@font-face{font-family:Fredoka;font-weight:600;font-display:swap;src:url(./fonts/fredoka-600.woff2) format("woff2")}
@font-face{font-family:Fredoka;font-weight:700;font-display:swap;src:url(./fonts/fredoka-700.woff2) format("woff2")}
.cloud.c1{top:16%;width:160px;height:46px;animation-duration:70s;animation-delay:-20s}
.cloud.c2{top:30%;width:110px;height:34px;animation-duration:95s;animation-delay:-60s}
#earMouth{width:min(200px,32vw);aspect-ratio:4/3}
.sheetBtns{display:flex;gap:10px;flex-wrap:wrap}
:root{--ink:#24324f;--pink:#ff5d8f;--gold:#ffc93c;--green:#3fbf74;--blue:#36a9e1;--purple:#8a6cff;--card:#ffffffee}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent;user-select:none;-webkit-user-select:none}
html,body{margin:0;height:100%;overflow:hidden;font-family:Fredoka,system-ui,sans-serif;color:var(--ink)}
body{background:linear-gradient(180deg,#8fdcff 0%,#c8f1ff 55%,#fff1c4 100%)}
#app{position:fixed;inset:0;padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)}
.cloud{position:absolute;background:#fff;border-radius:60px;opacity:.7;animation:drift linear infinite}
.cloud:before,.cloud:after{content:"";position:absolute;background:#fff;border-radius:50%}
.cloud:before{width:55%;height:150%;left:15%;top:-60%}.cloud:after{width:40%;height:120%;right:12%;top:-40%}
@keyframes drift{from{transform:translateX(-30vw)}to{transform:translateX(130vw)}}
.waves{position:absolute;left:0;right:0;bottom:0;height:11vh;background:radial-gradient(circle at 50% 0,#5cc8f0 30%,transparent 31%) 0 0/80px 40px repeat-x,linear-gradient(#5cc8f0,#36a9e1);opacity:.5;pointer-events:none;animation:lap 4s ease-in-out infinite}
@keyframes lap{50%{transform:translateY(6px)}}
header{position:absolute;top:calc(env(safe-area-inset-top) + 10px);left:12px;right:12px;display:flex;gap:10px;align-items:center;z-index:30}
.ib{border:0;background:#fff;border-radius:18px;width:54px;height:54px;font-size:26px;box-shadow:0 5px 0 #0002;cursor:pointer;font-family:inherit}
.ib:active{transform:translateY(3px);box-shadow:0 2px 0 #0002}
.ib.off{opacity:.45}
.stars{background:#fff;border-radius:18px;height:54px;padding:0 16px;display:flex;align-items:center;gap:6px;font-size:26px;font-weight:700;box-shadow:0 5px 0 #0002}
.stars.bump{animation:bump .5s}
@keyframes bump{50%{transform:scale(1.35) rotate(-6deg)}}
.trail{display:flex;gap:6px;background:#ffffffcc;border-radius:18px;height:54px;padding:0 12px;align-items:center;font-size:24px;box-shadow:0 5px 0 #0002}
.trail i{font-style:normal;opacity:.35;transition:all .3s}
.trail i.done{opacity:.8}
.trail i.now{opacity:1;transform:scale(1.35)}
.sp{flex:1}
#bubble{position:absolute;top:calc(env(safe-area-inset-top) + 76px);left:50%;transform:translateX(-50%);width:min(720px,90vw);background:#fff;border-radius:24px;padding:8px 18px;display:flex;align-items:center;min-height:54px;box-shadow:0 6px 0 #0001;z-index:25}
#cap{font-size:clamp(16px,2.1vw,21px);font-weight:500;line-height:1.25;width:100%;text-align:center}
.screen{position:absolute;inset:0;padding:calc(env(safe-area-inset-top) + 146px) 12px 16px;display:none;flex-direction:column;align-items:center;justify-content:center;gap:16px;overflow:hidden}
.screen.on{display:flex}
.btn{border:0;font-family:inherit;font-weight:700;font-size:clamp(20px,2.6vw,28px);padding:16px 26px;border-radius:24px;background:#fff;color:var(--ink);box-shadow:0 6px 0 #0002;cursor:pointer}
.btn:active{transform:translateY(4px);box-shadow:0 2px 0 #0002}
.btn.gold{background:var(--gold)}.btn.green{background:var(--green);color:#fff}
.btn.big{font-size:clamp(26px,3.6vw,38px);padding:20px 40px;animation:pulse 1.6s ease-in-out infinite}
@keyframes pulse{50%{transform:scale(1.07)}}
h1{margin:0;font-size:clamp(36px,6vw,64px);color:#fff;text-shadow:0 4px 0 #2a7fb8,0 8px 18px #0003;text-align:center;line-height:1}
h1 b{color:var(--gold)}
/* THEO */
.theo{width:100%;height:auto;overflow:visible}
.theo .th-head{animation:peek 4s ease-in-out infinite}
@keyframes peek{0%,15%{transform:translateX(-72px)}32%,78%{transform:translateX(0)}92%,100%{transform:translateX(-72px)}}
.theo .hat{font-size:50px}
#homeTheo{width:min(330px,58vw);filter:drop-shadow(0 10px 8px #0002);animation:bob 2.4s ease-in-out infinite}
@keyframes bob{50%{transform:translateY(-8px)}}
#buddy{position:fixed;left:max(8px,env(safe-area-inset-left));bottom:max(6px,env(safe-area-inset-bottom));width:min(190px,24vw);z-index:22;cursor:pointer;filter:drop-shadow(0 6px 6px #0002);display:none}
#buddy.show{display:block}
#buddy svg{transform-origin:50% 90%}
.peekOut .th-head{animation:none!important;transform:none!important;transition:transform .4s}
.dance svg{animation:dance .45s ease-in-out 4}
@keyframes dance{25%{transform:rotate(-10deg) translateY(-14px)}75%{transform:rotate(10deg) translateY(-14px)}}
.laugh svg{animation:laugh .18s ease-in-out 10}
@keyframes laugh{50%{transform:scale(1.06,.94) translateY(4px)}}
.tiles{display:grid;grid-template-columns:repeat(4,minmax(0,150px));gap:12px}
.tile{border:0;font-family:inherit;background:var(--card);border-radius:24px;padding:12px 6px;box-shadow:0 6px 0 #0002;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:2px;font-size:16px;font-weight:600;color:var(--ink)}
.tile span{font-size:42px}
.shelf{display:flex;gap:6px;font-size:32px;background:#ffffff99;border-radius:18px;padding:4px 14px;max-width:92vw;overflow:hidden;align-items:center}
.shelf:empty{display:none}
.shelf b{font-size:16px;margin-right:6px}
@media (max-width:700px){.tiles{grid-template-columns:repeat(2,minmax(0,150px))}.trail{display:none}}
/* MOUTH */
.bigMouth{width:min(520px,80vw,calc((100vh - 360px)*1.33));aspect-ratio:4/3;min-width:240px}
.mouth svg{width:100%;height:100%;display:block;filter:drop-shadow(0 8px 10px #0002)}
#stepBig{font-size:clamp(26px,3.8vw,40px);font-weight:700;color:#fff;text-shadow:0 3px 0 #2a7fb8;display:flex;gap:12px;align-items:center;min-height:56px}
#stepBig span{font-size:1.4em}
.popIn{animation:popIn .5s cubic-bezier(.3,1.6,.5,1)}
@keyframes popIn{from{transform:scale(.3);opacity:0}}
.ctl{min-height:80px;display:flex;gap:12px;flex-wrap:wrap;justify-content:center;align-items:center}
/* TURN */
#turn{position:fixed;right:3vw;top:50%;transform:translateY(-50%) scale(0);width:150px;height:150px;z-index:40;transition:transform .35s cubic-bezier(.3,1.6,.5,1);pointer-events:none}
#turn.on{transform:translateY(-50%) scale(1)}
#turn .in{position:absolute;inset:14px;background:#fff;border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;font-weight:700;font-size:20px;box-shadow:0 8px 20px #0003}
#turn .in span{font-size:46px;animation:laugh .5s infinite}
#turn svg{position:absolute;inset:0;transform:rotate(-90deg)}
#turn circle{fill:none;stroke:var(--pink);stroke-width:12;stroke-linecap:round;stroke-dasharray:440;stroke-dashoffset:440}
#turn.on circle{animation:ring 5s linear forwards}
@keyframes ring{to{stroke-dashoffset:0}}
/* FEATHER */
.field{position:relative;width:min(880px,90vw);height:min(250px,30vh);background:linear-gradient(#bfe9ff,#f1fbff);border-radius:30px;box-shadow:inset 0 -12px 0 #9fe0a9;overflow:hidden}
#mover{position:absolute;left:7%;top:42%;font-size:clamp(54px,8vw,84px);transform:translate(-50%,-50%)}
#goal{position:absolute;right:4%;top:50%;transform:translateY(-50%);font-size:clamp(64px,10vw,104px)}
.windline{position:absolute;height:6px;border-radius:3px;background:#fff;opacity:0}
.bar{width:min(880px,90vw);height:20px;background:#ffffffaa;border-radius:12px;overflow:hidden}
.bar i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--green),var(--gold));border-radius:12px}
#holdBtn{width:min(240px,34vh);height:min(240px,34vh);border-radius:50%;border:8px solid #fff;background:radial-gradient(circle at 40% 35%,#9cf0b4,#3fbf74);box-shadow:0 10px 0 #2a8a52,0 16px 30px #0003;display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;touch-action:none;padding:0;font-family:inherit}
#holdBtn.pressed{transform:translateY(8px) scale(.97);box-shadow:0 2px 0 #2a8a52}
#holdBtn.disabled{filter:grayscale(.7);opacity:.6}
#holdBtn.ready{animation:pulse 1.2s infinite}
#holdBtn .mouth{width:72%;aspect-ratio:4/3}
#holdBtn b{color:#fff;font-size:22px;text-shadow:0 2px 0 #0003}
/* EAR */
.earWrap{display:flex;gap:24px;align-items:center;justify-content:center;flex-wrap:wrap}
.ecard{border:0;font-family:inherit;width:min(250px,36vw);aspect-ratio:1;background:#fff;border-radius:34px;box-shadow:0 8px 0 #0002;display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;color:var(--ink);transition:transform .3s,opacity .3s}
.ecard span{font-size:clamp(70px,11vw,120px);line-height:1.1}
.ecard em{font-style:normal;font-size:clamp(22px,3vw,32px);font-weight:600}
.ecard.hide{transform:scale(0) rotate(-20deg);opacity:0}
.ecard.wrong{animation:shake .5s}
.ecard.right{background:#d6f7e2;animation:jump .7s}
.ecard.hint{box-shadow:0 0 0 8px var(--gold),0 8px 0 #0002}
@keyframes shake{20%,60%{transform:translateX(-12px)}40%,80%{transform:translateX(12px)}}
@keyframes jump{40%{transform:translateY(-30px) scale(1.08)}}
#earBtn{font-size:58px;width:106px;height:106px;border-radius:50%}
.prog{font-size:30px;letter-spacing:6px}
/* SAY */
.path{position:relative;width:min(640px,84vw);height:92px;background:linear-gradient(#5cc8f0,#36a9e1);border-radius:46px}
.stone{position:absolute;top:50%;width:62px;height:44px;transform:translate(-50%,-50%);background:#f3dfae;border-radius:50%;box-shadow:0 5px 0 #c9b07a;display:flex;align-items:center;justify-content:center;font-size:22px}
.stone.done{background:#ffe680}
.stone.chest{width:74px;height:74px;background:none;box-shadow:none;font-size:50px}
#walker{position:absolute;top:40%;font-size:50px;transform:translate(-50%,-50%) scaleX(-1);transition:left .9s ease-in-out;z-index:2}
#walker.hop{animation:hop .9s}
@keyframes hop{50%{top:-5%}}
.wordCard{display:flex;align-items:center;gap:clamp(10px,3vw,30px);background:var(--card);border-radius:34px;padding:14px 26px;box-shadow:0 8px 0 #0002;flex-wrap:wrap;justify-content:center}
#wEmoji{font-size:clamp(80px,13vw,130px);line-height:1}
#wText{font-size:clamp(46px,8vw,84px);font-weight:700;letter-spacing:2px}
#wText .th{color:var(--pink);text-decoration:underline wavy;text-underline-offset:10px}
#wText.oops{color:#b9b9c9;text-decoration:line-through}
#sayMouth{width:min(240px,34vw);aspect-ratio:4/3}
/* TREASURE */
#chest{font-size:clamp(130px,22vw,210px);cursor:pointer;line-height:1}
#chest.shake{animation:wiggle .8s ease-in-out infinite}
@keyframes wiggle{20%{transform:rotate(-8deg)}40%{transform:rotate(8deg) scale(1.05)}60%{transform:rotate(-5deg)}80%{transform:rotate(0)}}
#chest.open{animation:popIn .6s}
#jokeBox{font-size:clamp(70px,12vw,130px);min-height:1.2em}
.flyHat{position:fixed;font-size:130px;z-index:58;pointer-events:none;transform:translate(-50%,-50%)}
/* WAVE TRANSITION */
#wave{position:fixed;inset:-5vh -10vw;z-index:65;pointer-events:none;transform:translateX(120%);background:linear-gradient(160deg,#5fd0f5,#2b9fd6);border-radius:40vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px}
#wave.go{animation:waveGo 2.4s ease-in-out forwards}
@keyframes waveGo{0%{transform:translateX(120%)}30%,70%{transform:translateX(0)}100%{transform:translateX(-120%)}}
#wave .surf{font-size:150px;animation:surf 1s ease-in-out infinite}
@keyframes surf{50%{transform:translateY(-20px) rotate(-8deg)}}
#wave .where{font-size:clamp(36px,6vw,60px);color:#fff;font-weight:700;text-shadow:0 4px 0 #0002}
/* FLOATERS */
#fxLayer{position:fixed;inset:0;pointer-events:none;z-index:50;overflow:hidden}
.flo{position:absolute;font-size:70px}
.fly{animation:fly 3s ease-in-out forwards}
@keyframes fly{0%{transform:translate(-15vw,0) rotate(0)}50%{transform:translate(50vw,-20vh) rotate(20deg)}100%{transform:translate(115vw,0) rotate(0)}}
.leap{animation:leap 2s ease-in-out forwards}
@keyframes leap{0%{transform:translateY(40vh) rotate(-40deg)}50%{transform:translateY(-10vh) rotate(0)}100%{transform:translateY(40vh) rotate(40deg)}}
.rise{animation:rise 3.2s ease-in forwards}
@keyframes rise{to{transform:translateY(-120vh)}}
.flo.swim{animation:swim 9s linear forwards}
canvas#fx{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:55}
.modal{position:fixed;inset:0;background:#0006;display:none;align-items:center;justify-content:center;z-index:70;padding:16px}
.modal.on{display:flex}
.sheet{background:#fff;border-radius:26px;max-width:620px;width:100%;max-height:88vh;overflow:auto;padding:22px 24px;font-size:17px;line-height:1.45;user-select:text;-webkit-user-select:text}
.sheet h2{margin:0 0 8px}.sheet li{margin-bottom:8px}
.sheet input,.sheet select{font-family:inherit;font-size:18px;padding:8px 12px;border-radius:12px;border:2px solid #ccd;width:100%;margin:4px 0 12px}
#start{position:fixed;inset:0;z-index:80;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;background:linear-gradient(180deg,#8fdcff,#c8f1ff 60%,#fff1c4);padding:20px;text-align:center}
#start p{font-size:20px;margin:0;color:#3a5a7a}
#startTheo{width:min(300px,56vw)}
.screen{z-index:2}
.theo .cape{transform-origin:200px 85px;animation:flutter 1.1s ease-in-out infinite}
@keyframes flutter{50%{transform:skewY(5deg) scaleX(1.05)}}
.c-shell,.c-hold{transition:opacity .3s}
#showTheo{width:min(360px,56vw);display:none;filter:drop-shadow(0 10px 10px #0003)}
#showTheo.on{display:block;animation:popOut 1s cubic-bezier(.3,1.6,.5,1)}
#showTheo.on svg{animation:dance .5s ease-in-out 1s 6}
@keyframes popOut{from{transform:translateY(160px) scale(.2) rotate(-30deg);opacity:0}}
#costumeName{font-size:clamp(30px,5vw,50px);font-weight:700;color:#fff;text-shadow:0 3px 0 #2a7fb8;min-height:1.2em}
.flyPiece{position:fixed;z-index:58;pointer-events:none;transform:translate(-50%,-50%);font-size:110px;line-height:1}
.sparkle{position:fixed;z-index:59;pointer-events:none;font-size:34px;animation:spk .9s ease-out forwards}
@keyframes spk{from{transform:translate(-50%,-50%) scale(.3);opacity:1}to{transform:translate(calc(-50% + var(--dx)),calc(-50% + var(--dy))) scale(1.2);opacity:0}}
/* PARTY */
#party{position:fixed;inset:0;z-index:62;display:none;background:radial-gradient(circle at 50% 35%,#4a2287,#140a2b);overflow:hidden;flex-direction:column;align-items:center;justify-content:center;gap:2vh}
#party.on{display:flex}
.beam{position:absolute;top:-8vh;left:50%;width:22vmin;height:125vh;margin-left:-11vmin;transform-origin:50% 0;border-radius:0 0 50% 50%;opacity:.55;pointer-events:none;will-change:transform;animation:beam 3.2s ease-in-out infinite alternate}
.beam.b1{background:linear-gradient(#ff5d8f,transparent 85%);animation-delay:-.4s}.beam.b2{background:linear-gradient(#ffd23f,transparent 85%);animation-delay:-1.3s;animation-duration:2.6s}
.beam.b3{background:linear-gradient(#36a9e1,transparent 85%);animation-delay:-2.1s;animation-duration:3.8s}.beam.b4{background:linear-gradient(#3fbf74,transparent 85%);animation-delay:-.9s;animation-duration:2.9s}
@keyframes beam{from{transform:rotate(-38deg)}to{transform:rotate(38deg)}}
.ball{position:absolute;top:calc(env(safe-area-inset-top) + 4px);font-size:76px;animation:swing 1s ease-in-out infinite alternate;transform-origin:50% -60px}
@keyframes swing{from{transform:rotate(-14deg)}to{transform:rotate(14deg)}}
#partyTheo{width:min(430px,66vw,60vh);position:relative;z-index:2;filter:drop-shadow(0 0 24px #fff5)}
#partyTheo svg{transform-origin:50% 90%}
.mv-bounce svg{animation:pBounce .5s ease-in-out infinite}
.mv-wiggle svg{animation:pWig .5s ease-in-out infinite}
.mv-spin svg{animation:pSpin 1s linear infinite}
.mv-jump svg{animation:pJump 1s ease-in-out infinite}
.mv-peek svg{animation:pBounce 1s ease-in-out infinite}
.mv-peek .th-head{animation:peekFast .5s ease-in-out infinite!important}
@keyframes pBounce{50%{transform:translateY(-28px) scaleY(1.04)}}
@keyframes pWig{25%{transform:rotate(-14deg)}75%{transform:rotate(14deg)}}
@keyframes pSpin{to{transform:rotateY(360deg)}}
@keyframes pJump{0%,100%{transform:translateY(0)}40%{transform:translateY(-80px) scale(1.08,.95)}}
@keyframes peekFast{0%,100%{transform:translateX(-72px)}50%{transform:translateX(0)}}
.friends{display:flex;gap:4vw;font-size:clamp(44px,7vw,72px);z-index:2}
.friends span{display:inline-block;animation:pBounce .5s ease-in-out infinite}
.friends span:nth-child(even){animation-name:pWig}
#party.frozen *{animation-play-state:paused!important}
#party.frozen #partyTheo{filter:drop-shadow(0 0 30px #9ef) saturate(.4) brightness(1.2)}
#freezeTxt{position:absolute;top:22%;font-size:clamp(56px,11vw,120px);font-weight:700;color:#d6f6ff;text-shadow:0 0 24px #6cf,0 6px 0 #1b6fa8;opacity:0;transform:scale(.3);transition:all .35s cubic-bezier(.3,1.6,.5,1);z-index:3;pointer-events:none}
#party.frozen #freezeTxt{opacity:1;transform:scale(1)}
#partyX{position:absolute;top:calc(env(safe-area-inset-top) + 12px);right:14px;z-index:4}
#party.auto #partyX{display:none}
/* BUBBLES */
#bubbleLayer{position:fixed;inset:0;z-index:57;pointer-events:none;display:none;overflow:hidden}
#bubbleLayer.on{display:block}
.bub{position:absolute;bottom:-160px;border-radius:50%;background:radial-gradient(circle at 30% 28%,#fff 0 8%,#e6f8ffcc 14%,#9fdcff66 45%,#ffffff22 70%);box-shadow:inset 0 0 20px #ffffffaa,0 0 14px #ffffff88;pointer-events:auto;animation:bubUp linear forwards;cursor:pointer}
@keyframes bubUp{50%{margin-left:30px}to{transform:translateY(-135vh)}}
/* BIG BACKGROUND TURTLE */
#bigTurtle{position:absolute;left:50%;bottom:-2vh;width:min(440px,58vw);transform:translate(-50%,115%);z-index:1;pointer-events:none}
#bigTurtle.up{animation:btRise 5.5s ease-in-out forwards}
@keyframes btRise{0%{transform:translate(-50%,115%)}16%{transform:translate(-50%,4%)}22%{transform:translate(-50%,10%)}78%{transform:translate(-50%,7%)}100%{transform:translate(-50%,118%)}}
#bigTurtle .pupil{transform-box:fill-box;transform-origin:center}
#bigTurtle.up .pupil{animation:look 5.5s ease-in-out}
@keyframes look{0%,25%{transform:translate(0,0)}35%{transform:translate(-14px,2px)}48%{transform:translate(14px,2px)}60%,100%{transform:translate(0,6px)}}
#bigTurtle .bt-tongue{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(0)}
#bigTurtle.up .bt-tongue{animation:btTongue 5.5s ease-in-out}
@keyframes btTongue{0%,55%{transform:scaleY(0)}62%,74%{transform:scaleY(1)}80%,100%{transform:scaleY(0)}}
#bigTurtle .lid{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(0)}
#bigTurtle.up .lid.r{animation:wink 5.5s ease-in-out}
@keyframes wink{0%,66%{transform:scaleY(0)}69%,72%{transform:scaleY(1)}75%,100%{transform:scaleY(0)}}
.waves{z-index:1}
.swim{animation:swim 9s linear forwards}
@keyframes swim{from{transform:translateX(-12vw) scaleX(-1)}to{transform:translateX(112vw) scaleX(-1)}}
.screen{overflow-y:auto;justify-content:flex-start;-webkit-overflow-scrolling:touch}
.screen>:first-child{margin-top:auto}.screen>:last-child{margin-bottom:auto}
@media (max-width:420px){header{gap:6px;left:8px;right:8px}header .ib{width:44px;height:44px;font-size:22px;border-radius:14px}.stars{height:44px;padding:0 10px;font-size:22px}#fsBtn{display:none}
#bubble{top:calc(env(safe-area-inset-top) + 64px)}.screen{padding-top:calc(env(safe-area-inset-top) + 132px)}}
@media (max-height:620px){header{top:calc(env(safe-area-inset-top) + 6px)}header .ib{width:44px;height:44px;font-size:22px;border-radius:14px}.stars,.trail{height:44px;font-size:21px}
#bubble{top:calc(env(safe-area-inset-top) + 58px);min-height:40px;padding:4px 14px}#cap{font-size:15px}
.screen{padding-top:calc(env(safe-area-inset-top) + 112px);padding-bottom:10px;gap:10px}
h1{font-size:32px}#homeTheo{width:min(200px,34vh)}
.btn{font-size:18px;padding:10px 18px}.btn.big{font-size:24px;padding:12px 26px}
.tile{padding:6px 4px;font-size:13px}.tile span{font-size:30px}
.bigMouth{width:min(400px,80vw,calc((100vh - 260px)*1.33));min-width:180px}#stepBig{font-size:24px;min-height:40px}
.wordCard{padding:8px 16px;gap:10px}#wEmoji{font-size:60px}#wText{font-size:38px}#sayMouth{width:min(160px,28vw)}
.path{height:66px}.stone{width:48px;height:34px}.stone.chest{font-size:38px}#walker{font-size:38px}
#holdBtn{width:min(190px,32vh);height:min(190px,32vh)}.field{height:min(200px,26vh)}
.ecard{width:min(190px,30vw,36vh)}.ecard span{font-size:min(80px,12vh)}#earBtn{width:80px;height:80px;font-size:42px}#earMouth{width:min(150px,26vw)}
#turn{width:110px;height:110px}#turn .in span{font-size:34px}#turn .in{font-size:15px}
#chest{font-size:min(130px,24vh)}#showTheo{width:min(260px,40vh)}#costumeName{font-size:26px}#jokeBox{font-size:60px}
.ctl{min-height:56px}#buddy{width:min(130px,20vw)}}
@media (max-height:420px){.screen{padding-top:calc(env(safe-area-inset-top) + 92px);gap:8px}#stepBig{font-size:20px;min-height:30px}.ctl{min-height:50px}#bubble{width:min(600px,70vw)}h1{font-size:24px}#homeTheo{width:min(150px,30vh)}
.tiles{grid-template-columns:repeat(4,minmax(0,120px))}.bigMouth{width:min(300px,50vw,calc((100vh - 235px)*1.33));min-width:150px}#partyTheo{width:min(260px,50vh)}.friends{font-size:36px}}
@media (max-width:420px){.tiles{grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;width:100%}.tile{padding:6px 2px;font-size:11px;border-radius:16px}.tile span{font-size:28px}h1{font-size:30px}#homeTheo{width:min(220px,30vh)}}
/* ---------- SILLY SOUND SQUAD ---------- */
body{background:linear-gradient(180deg,#8fd8ff 0%,#c9efff 55%,#fff4c7 100%)}
.sky .st{position:absolute;width:10px;height:10px;background:#fff;border-radius:50%;opacity:.0;animation:tw 3s ease-in-out infinite}
.hills{position:absolute;left:-5%;right:-5%;bottom:0;height:13vh;z-index:1;pointer-events:none;background:radial-gradient(ellipse 40% 100% at 20% 100%,#7ed957 98%,transparent 100%),radial-gradient(ellipse 45% 90% at 75% 100%,#63c94d 98%,transparent 100%),linear-gradient(#7ed95700,#7ed95700)}
.chwrap{position:relative;display:inline-block;width:100%;line-height:0}
.chwrap .ch{width:100%;height:auto;overflow:visible}
.chwrap .bob{transform-origin:50% 95%;animation:chBob 2.2s ease-in-out infinite;transform-box:fill-box}
@keyframes chBob{50%{transform:translateY(-4%) scale(1.02,.98)}}
.chwrap .ear{transform-box:fill-box;transform-origin:50% 10%;animation:earW 2.6s ease-in-out infinite}
.chwrap .ear.r{animation-delay:-1.3s}
@keyframes earW{50%{transform:rotate(-6deg)}}
.chwrap .tg{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(.55);transition:transform .25s}
.chwrap.act .tg{transform:scaleY(1.25)}
.chwrap .puff{opacity:0;transition:opacity .2s}
.chwrap.act .puff{opacity:1;animation:puffy .5s ease-in-out infinite}
@keyframes puffy{50%{transform:translateX(4px)}}
.chwrap .wheel{transform-box:fill-box;transform-origin:center}
.chwrap .wheel.spin,.chwrap.act .wheel{animation:spinW .4s linear infinite}
@keyframes spinW{to{transform:rotate(360deg)}}
.chwrap.act .ch-v .bob{animation:vroom .08s linear infinite}
@keyframes vroom{50%{transform:translate(1.5px,-1px)}}
.chwrap .flick{transform-box:fill-box;transform-origin:50% 0;animation:flick 2.4s ease-in-out infinite}
@keyframes flick{0%,70%,100%{transform:scaleY(0)}78%,90%{transform:scaleY(1)}}
.chwrap.act .ch-s .bob{animation:sway 1s ease-in-out infinite}
@keyframes sway{25%{transform:rotate(-4deg)}75%{transform:rotate(4deg)}}
.chwrap .hat,.chwrap .hold{position:absolute;line-height:1;pointer-events:none;font-size:calc(var(--cw,200px)*.26)}
.chwrap .hat{top:-14%;left:50%;transform:translateX(-50%) rotate(-6deg)}
.chwrap .hold{right:-8%;bottom:4%}
.chwrap.hop{animation:chHop .6s cubic-bezier(.3,1.6,.5,1)}
@keyframes chHop{40%{transform:translateY(-22%) rotate(-6deg)}70%{transform:translateY(0) rotate(4deg)}}
.popOut{animation:popOut .9s cubic-bezier(.3,1.6,.5,1)}
@keyframes popOut{from{transform:translateY(40%) scale(.2) rotate(-25deg);opacity:0}}
h1{font-size:clamp(38px,6.4vw,70px)}
.homeRow{display:flex;gap:clamp(6px,2vw,26px);align-items:flex-end;justify-content:center}
.homeRow .chwrap{width:min(170px,21vw);cursor:pointer}
.startRow{display:flex;gap:10px;justify-content:center}.startRow .chwrap{width:min(110px,20vw)}
.shelf span{font-size:30px;margin:0 2px}
/* door reveal */
.revealStage{position:relative;width:min(320px,58vw,46vh);aspect-ratio:3/4}
.door{position:absolute;inset:0;border-radius:46% 46% 14px 14px/34% 34% 14px 14px;background:linear-gradient(90deg,#c9772f,#e39a4e);border:8px solid #8a4a1c;box-shadow:0 12px 0 #0002;cursor:pointer;overflow:hidden;transform-origin:0 50%;transition:transform .8s cubic-bezier(.5,0,.3,1),opacity .8s}
.door .doorL{position:absolute;inset:12% 14%;border:6px solid #b0622a;border-radius:40% 40% 8px 8px/30% 30% 8px 8px}
.door .knob{position:absolute;right:12%;top:52%;width:28px;height:28px;border-radius:50%;background:#ffd23f;box-shadow:inset -4px -4px 0 #d9a400}
.door span{position:absolute;left:50%;top:22%;transform:translateX(-50%);font-size:clamp(60px,10vh,110px);font-weight:700;color:#fff6;line-height:1}
.door.wiggle{animation:knock 1s ease-in-out infinite}
@keyframes knock{10%,30%{transform:rotate(-2deg)}20%,40%{transform:rotate(2deg)}50%{transform:none}}
.door.open{transform:perspective(900px) rotateY(-100deg);opacity:.0;pointer-events:none}
#revealCh{position:absolute;inset:6% 0 0 0;display:flex;align-items:flex-end;justify-content:center}
#revealCh .chwrap{width:96%}
.bigName{font-size:clamp(30px,5.5vw,56px);font-weight:700;color:#fff;text-shadow:0 4px 0 #2a7fb8;min-height:1.2em}
/* mirror */
.mirrorRow{display:flex;align-items:center;gap:clamp(8px,2vw,24px)}
#mirrorCh{width:min(190px,22vw)}
/* power */
.field{position:relative;width:min(900px,92vw);height:min(330px,36vh);border-radius:30px;overflow:hidden;background:linear-gradient(#c9efff,#f6fdff);box-shadow:inset 0 -14px 0 #9fe0a9}
.field .pwCh{position:absolute;left:3%;bottom:4%;width:min(190px,22%)}
.field .wand{position:absolute;left:24%;top:46%;font-size:min(80px,9vh)}
.pbub{position:absolute;border-radius:50%;background:radial-gradient(circle at 30% 28%,#fff 0 8%,#e6f8ffcc 14%,#9fdcff66 45%,#ffffff22 70%);box-shadow:inset 0 0 14px #fff9;pointer-events:none}
.field .cake{position:absolute;left:52%;bottom:6%;transform:translateX(-50%);text-align:center}
.cakeBody{font-size:min(180px,20vh);line-height:1}
.flames{display:flex;gap:min(18px,2vh);justify-content:center;margin-bottom:-14px}
.flames i{display:block;width:16px;height:46px;border-radius:8px;background:linear-gradient(#ffe066 0 40%,#ff7aa8 40%);position:relative}
.flames i:before{content:"";position:absolute;left:50%;top:-26px;width:18px;height:26px;margin-left:-9px;border-radius:50% 50% 50% 50%/60% 60% 40% 40%;background:radial-gradient(circle at 50% 70%,#fff6b0,#ffb300 60%,#ff6a00);animation:flick2 .3s ease-in-out infinite alternate;transition:opacity .3s,transform .3s}
.flames i.out:before{opacity:0;transform:translateY(-14px) scale(.4)}
@keyframes flick2{to{transform:scale(.9,1.08) rotate(3deg)}}
.field .track{position:absolute;left:0;right:0;bottom:12%;height:22%;background:repeating-linear-gradient(90deg,#555 0 60px,#666 60px 120px);border-top:5px dashed #fff}
.field .flag{position:absolute;right:3%;bottom:22%;font-size:min(90px,10vh)}
.field .racer{position:absolute;left:4%;bottom:14%;width:min(180px,22%);transition:left .15s linear}
.field .balloon{position:absolute;left:62%;top:58%;transform:translate(-50%,0) scale(.35);transform-origin:50% 100%}
.balloon .bl{width:150px;height:180px;border-radius:50% 50% 48% 48%/55% 55% 45% 45%;background:radial-gradient(circle at 35% 30%,#fff9,#ff5d8f 30%,#e83f78);box-shadow:inset -10px -16px 0 #0001}
.balloon .str{width:3px;height:120px;background:#555;margin:0 auto}
#holdBtn{flex-direction:column}
#holdBtn span{font-size:56px}
/* listening badge */
#ear{position:fixed;left:50%;bottom:max(18px,env(safe-area-inset-bottom));transform:translateX(-50%) scale(0);z-index:45;width:150px;height:150px;transition:transform .3s cubic-bezier(.3,1.6,.5,1);pointer-events:none;--lv:0;--kc:#fff}
#ear.on{transform:translateX(-50%) scale(1)}
#ear .ring{position:absolute;inset:0;border-radius:50%;background:var(--kc);opacity:.55;transform:scale(calc(.55 + var(--lv)*.65));transition:transform .08s,background .15s}
#ear .core{position:absolute;inset:30px;border-radius:50%;background:#fff;display:flex;align-items:center;justify-content:center;font-size:44px;box-shadow:0 6px 16px #0003;animation:pulse 1.2s ease-in-out infinite}
#ear b{position:absolute;left:50%;bottom:-10px;transform:translateX(-50%);white-space:nowrap;background:#fff;border-radius:12px;padding:2px 10px;font-size:15px;box-shadow:0 3px 0 #0002}
.override{position:fixed;right:14px;bottom:max(14px,env(safe-area-inset-bottom));z-index:46;border:0;border-radius:16px;background:#fff;color:#24324f;font:600 15px Fredoka,system-ui;padding:10px 14px;box-shadow:0 4px 0 #0002;opacity:.92}
.cameo{position:fixed;right:3vw;bottom:14vh;width:min(180px,26vw);z-index:44;animation:cameo 3.6s ease-in-out forwards;pointer-events:none}
@keyframes cameo{0%{transform:translateX(140%) rotate(20deg)}15%,80%{transform:translateX(0) rotate(-4deg)}100%{transform:translateX(160%) rotate(10deg)}}
/* who said it */
#whoSpk{font-size:58px;width:110px;height:110px;border-radius:50%}
.whoRow{display:flex;gap:clamp(8px,2vw,22px);flex-wrap:wrap;justify-content:center}
.whoBtn{border:0;background:#fff;border-radius:28px;padding:10px 10px 6px;width:min(190px,27vw);box-shadow:0 7px 0 #0002;cursor:pointer;font-family:inherit;display:flex;flex-direction:column;align-items:center;gap:4px;color:#24324f}
.whoBtn b{font-size:clamp(16px,2.2vw,22px)}
.whoBtn.nope{animation:wob .6s}
@keyframes wob{25%{transform:rotate(-5deg)}75%{transform:rotate(5deg)}}
.whoBtn.hint{box-shadow:0 0 0 7px var(--gold),0 7px 0 #0002}
/* feed */
.feedRow{display:flex;align-items:center;gap:clamp(10px,3vw,40px);flex-wrap:wrap;justify-content:center}
#feedCh{width:min(250px,30vw)}
.foodCard{background:#fffffff0;border-radius:32px;padding:14px 22px;box-shadow:0 8px 0 #0002;display:flex;flex-direction:column;align-items:center;gap:4px;min-width:min(300px,60vw)}
#food{font-size:clamp(70px,12vw,120px);line-height:1.05;min-height:1.05em}
#foodWord{font-size:clamp(40px,7vw,72px);font-weight:700;letter-spacing:2px;line-height:1.1}
#foodWord .hl{color:var(--pink);text-decoration:underline wavy;text-underline-offset:8px}
#feedMouth{width:min(170px,30vw);aspect-ratio:4/3}
.flyFood{position:fixed;z-index:58;pointer-events:none;font-size:110px;line-height:1}
/* prize */
#box{font-size:clamp(120px,22vw,200px);cursor:pointer;line-height:1}
#box.shake{animation:wiggle .8s ease-in-out infinite}
#prizeCh{width:min(280px,46vh)}
#prizeCh:empty{display:none}
/* party friends + transition */
#partyTheo{display:flex;gap:2vw;width:min(860px,94vw);justify-content:center}
#partyTheo .chwrap{width:min(200px,22vw,26vh)}
#wave .surf{width:min(220px,40vw);font-size:inherit;animation:surf 1s ease-in-out infinite}
@media (max-height:620px){.field{height:min(240px,32vh)}#whoSpk{width:80px;height:80px;font-size:40px}.whoBtn{width:min(150px,24vw,30vh)}#feedCh{width:min(180px,26vw)}#food{font-size:64px}#foodWord{font-size:36px}#feedMouth{width:120px}
.revealStage{width:min(240px,44vw,48vh)}#mirrorCh{width:min(140px,20vw)}#ear{width:110px;height:110px}#ear .core{inset:22px;font-size:32px}#prizeCh{width:min(200px,40vh)}}
@media (max-width:420px){.homeRow .chwrap{width:22vw}.mirrorRow{flex-direction:column}#mirrorCh{width:30vw}.feedRow{flex-direction:column}#feedCh{width:38vw}}
@keyframes tw{50%{opacity:.9}}
.soundPick{display:flex;flex-wrap:wrap;gap:6px 14px;margin:4px 0 12px}
.soundPick label,.micRow{display:flex;align-items:center;gap:6px;font-size:18px;font-weight:600}
.sheet .soundPick input,.sheet .micRow input{width:24px;height:24px;margin:0}
.micState{margin:2px 0 12px;font-size:15px;color:#4a5a78}
.chwrap{container-type:inline-size}
.chwrap .hat,.chwrap .hold{font-size:26cqw}
#s-power #holdBtn{width:min(130px,18vh);height:min(130px,18vh);border-width:6px}
#s-power #holdBtn span{font-size:min(44px,6vh)}
#party #partyTheo{display:flex;gap:2vw;width:min(860px,94vw);justify-content:center}
#partyTheo .chwrap:nth-child(2) svg{animation-delay:-.15s}#partyTheo .chwrap:nth-child(3) svg{animation-delay:-.3s}#partyTheo .chwrap:nth-child(4) svg{animation-delay:-.45s}
#ear{left:auto;right:max(14px,env(safe-area-inset-right));transform:scale(0)}
#ear.on{transform:scale(1)}
.override{right:auto;left:14px}
.screen>*{flex-shrink:0}
.bigName{color:#ff5d8f;text-shadow:0 3px 0 #fff,0 0 14px #fff;text-align:center;line-height:1.15}
/* ---------- sillier look ---------- */
.chwrap .pup{transform:translate(var(--ex,0px),var(--ey,0px));transition:transform .25s cubic-bezier(.3,1.8,.5,1)}
.chwrap .lid{transform-box:fill-box;transform-origin:50% 0;transform:scaleY(0);animation:blink 4.7s infinite}
.chwrap[data-ch="f"] .lid{animation-delay:-1.2s}.chwrap[data-ch="v"] .lid{animation-delay:-2.6s;animation-duration:5.3s}.chwrap[data-ch="s"] .lid{animation-delay:-3.7s;animation-duration:4.1s}
@keyframes blink{0%,93%,100%{transform:scaleY(0)}96%{transform:scaleY(1)}}
.chwrap.act .pup{animation:jiggle .18s linear infinite}
@keyframes jiggle{50%{transform:translate(calc(var(--ex,0px) + 1.5px),calc(var(--ey,0px) - 1px))}}
.chwrap .bob{animation:chBob2 1.1s ease-in-out infinite}
@keyframes chBob2{0%,100%{transform:translateY(0) scale(1.04,.96)}50%{transform:translateY(-7%) scale(.97,1.04)}}
.chwrap.r-spin svg{animation:rSpin .8s cubic-bezier(.4,1.6,.5,1)}@keyframes rSpin{to{transform:rotate(360deg)}}
.chwrap.r-jelly svg{animation:rJelly .8s}@keyframes rJelly{15%{transform:scale(1.25,.75)}30%{transform:scale(.8,1.2)}45%{transform:scale(1.12,.9)}60%{transform:scale(.95,1.05)}}
.chwrap.r-flip svg{animation:rFlip .8s ease-in-out}@keyframes rFlip{40%{transform:translateY(-30%) rotate(-180deg)}80%{transform:translateY(0) rotate(-360deg)}100%{transform:rotate(-360deg)}}
.chwrap.r-boing svg{animation:rBoing .8s cubic-bezier(.3,1.8,.5,1)}@keyframes rBoing{30%{transform:translateY(-40%) scale(.9,1.15)}60%{transform:translateY(0) scale(1.2,.8)}}
.chwrap.r-eyes .eyes{animation:rEyes .8s}.chwrap.r-eyes .eyes{transform-box:fill-box;transform-origin:center}@keyframes rEyes{20%,70%{transform:scale(1.6)}}
.chwrap.r-squish svg{transform-origin:50% 100%;animation:rSquish .8s}@keyframes rSquish{25%{transform:scale(1.4,.55)}55%{transform:scale(.85,1.25)}}
.burst{position:fixed;z-index:60;pointer-events:none;transform:translate(-50%,-50%) rotate(var(--r));font:700 clamp(34px,7vw,64px) Fredoka,system-ui;color:#fff;-webkit-text-stroke:3px #2b2b3a;paint-order:stroke;padding:.55em .8em;
background:#ffd23f;clip-path:polygon(50% 0,61% 24%,88% 8%,78% 36%,100% 46%,77% 58%,90% 88%,61% 74%,50% 100%,39% 74%,10% 90%,23% 58%,0 46%,22% 36%,12% 8%,39% 24%);animation:burstPop 1.3s cubic-bezier(.3,1.7,.5,1) forwards}
@keyframes burstPop{0%{transform:translate(-50%,-50%) rotate(var(--r)) scale(0)}25%{transform:translate(-50%,-50%) rotate(var(--r)) scale(1.15)}75%{transform:translate(-50%,-50%) rotate(var(--r)) scale(1);opacity:1}100%{transform:translate(-50%,-50%) rotate(var(--r)) scale(.6);opacity:0}}
.sun{position:absolute;right:4vw;top:calc(env(safe-area-inset-top) + 64px);width:min(120px,18vw);z-index:0;pointer-events:none;animation:sunBob 3s ease-in-out infinite}
.sun .rays{transform-origin:100px 100px;animation:spinW 14s linear infinite}
@keyframes sunBob{50%{transform:translateY(8px) rotate(6deg)}}
.cloud:before,.cloud:after{content:"";position:absolute;top:38%;width:7px;height:7px;border-radius:50%;background:#2b2b3a;opacity:.7;left:40%;box-shadow:16px 0 0 #2b2b3a}
.cloud:after{top:58%;left:46%;width:12px;height:5px;border-radius:0 0 12px 12px;box-shadow:none;background:#ff8fb1}
.flowers{position:absolute;left:0;right:0;bottom:1vh;z-index:1;display:flex;justify-content:space-around;pointer-events:none;font-size:clamp(22px,4vw,40px)}
.flowers span{display:inline-block;transform-origin:50% 100%;animation:flowerDance 1.2s ease-in-out infinite}
.flowers span:nth-child(even){animation-delay:-.6s}
@keyframes flowerDance{0%,100%{transform:rotate(-12deg) scaleY(1)}50%{transform:rotate(12deg) scaleY(.9)}}
.flo.run{animation:run 7s linear forwards;font-size:64px}
@keyframes run{from{transform:translateX(-12vw)}to{transform:translateX(112vw)}}
.flo.run:after{content:"";}
.screen{z-index:2}
.sun{top:calc(env(safe-area-inset-top) + 128px);width:min(100px,17vw)}
@media (min-width:700px){.sun{top:calc(env(safe-area-inset-top) + 70px);width:min(120px,12vw)}}
.rainbow{position:absolute;left:-8vw;bottom:6vh;width:min(420px,55vw);aspect-ratio:2/1;border-radius:50% 50% 0 0/100% 100% 0 0;z-index:0;pointer-events:none;opacity:.55;
background:radial-gradient(circle at 50% 100%,transparent 0 46%,#8a6cff 46% 52%,#36a9e1 52% 58%,#3fbf74 58% 64%,#ffd23f 64% 70%,#ff9f43 70% 76%,#ff5d8f 76% 82%,transparent 82%)}
@media (max-width:420px){#mirrorCh{width:40vw}#feedCh{width:44vw}}
#revealCh{pointer-events:none}#revealCh .chwrap{pointer-events:auto}
</style>
</head>
<body>
<div id="app">
<div class="sky"><i class="st s1"></i><i class="st s2"></i><i class="st s3"></i><i class="st s4"></i><i class="st s5"></i><i class="st s6"></i></div>
<div class="cloud c1"></div>
<div class="cloud c2"></div>
<div id="bigTurtle"><svg viewBox="0 0 400 300">
<path d="M70 120 C20 130 10 250 60 262 C96 250 104 170 104 140Z" fill="#8b5a2b"/><path d="M330 120 C380 130 390 250 340 262 C304 250 296 170 296 140Z" fill="#8b5a2b"/>
<ellipse cx="200" cy="200" rx="150" ry="125" fill="#f2c27b"/><ellipse cx="250" cy="160" rx="46" ry="40" fill="#d99a4e" opacity=".5"/>
<ellipse cx="200" cy="240" rx="80" ry="58" fill="#fbe3bd"/>
<circle cx="145" cy="160" r="30" fill="#fff"/><circle class="pupil" cx="150" cy="164" r="17" fill="#1d2b3a"/><circle cx="156" cy="156" r="5" fill="#fff"/>
<circle cx="255" cy="160" r="30" fill="#fff"/><circle class="pupil" cx="260" cy="164" r="17" fill="#1d2b3a"/><circle cx="266" cy="156" r="5" fill="#fff"/>
<rect class="lid r" x="223" y="128" width="64" height="64" rx="32" fill="#e0a35a"/>
<ellipse cx="200" cy="212" rx="28" ry="20" fill="#2b2b3a"/>
<path d="M160 246 Q200 270 240 246" stroke="#2b2b3a" stroke-width="7" fill="none" stroke-linecap="round"/>
<g class="bt-tongue"><path d="M178 254 Q200 320 222 254 Z" fill="#ff7a9a" stroke="#d9546f" stroke-width="4"/></g>
<ellipse cx="105" cy="230" rx="22" ry="13" fill="#ff9aa8" opacity=".7"/><ellipse cx="295" cy="230" rx="22" ry="13" fill="#ff9aa8" opacity=".7"/>
</svg></div>
<div class="sun"><svg viewBox="0 0 200 200"><g class="rays" stroke="#ffc93c" stroke-width="12" stroke-linecap="round"><path d="M100 8v26M100 166v26M8 100h26M166 100h26M35 35l18 18M147 147l18 18M35 165l18-18M147 53l18-18"/></g>
<circle cx="100" cy="100" r="54" fill="#ffd23f"/><path d="M58 88h84" stroke="#2b2b3a" stroke-width="6"/><rect x="58" y="80" width="38" height="24" rx="10" fill="#2b2b3a"/><rect x="104" y="80" width="38" height="24" rx="10" fill="#2b2b3a"/><path d="M66 86l10 0" stroke="#fff" stroke-width="4" stroke-linecap="round" opacity=".7"/>
<path d="M76 122 Q100 146 124 122" stroke="#2b2b3a" stroke-width="6" fill="none" stroke-linecap="round"/><ellipse cx="66" cy="118" rx="9" ry="6" fill="#ff9a5a" opacity=".7"/><ellipse cx="134" cy="118" rx="9" ry="6" fill="#ff9a5a" opacity=".7"/></svg></div>
<div class="rainbow"></div>
<div class="hills"></div>
<div class="flowers"><span>🌼</span><span>🌷</span><span>🍄</span><span>🌻</span><span>🌸</span><span>🌼</span><span>🌷</span></div>
<header>
<button class="ib" id="homeBtn" aria-label="Home">🏠</button>
<div class="stars" id="stars">⭐ <span id="starN">0</span></div>
<div class="trail" id="trail"><i>🚪</i><i>👄</i><i>⚡</i><i>👂</i><i>🍎</i><i>🎁</i></div>
<div class="sp"></div>
<button class="ib" id="sillyBtn" aria-label="Silly surprise">🤪</button>
<button class="ib" id="danceBtn" aria-label="Dance party">💃</button>
<button class="ib off" id="musicBtn" aria-label="Music">🎵</button>
<button class="ib" id="fsBtn" aria-label="Full screen">⛶</button>
<button class="ib" id="grownBtn" aria-label="For grown-ups">👪</button>
</header>
<div id="bubble"><div id="cap">Hi!</div></div>
<section class="screen" id="s-home">
<h1>Silly <b>Sound</b> Squad</h1>
<div class="homeRow" id="homeRow"></div>
<button class="btn green big" id="playBtn">▶ Play!</button>
<div class="shelf" id="shelf"></div>
</section>
<section class="screen" id="s-reveal">
<div class="revealStage"><div id="door" class="door"><div class="doorL"></div><div class="knob"></div><span>?</span></div><div id="revealCh"></div></div>
<div class="bigName" id="revealName"></div>
</section>
<section class="screen" id="s-mirror">
<div id="stepBig"></div>
<div class="mirrorRow"><div id="mirrorCh"></div><div class="mouth bigMouth" id="mirrorMouth"></div></div>
<div class="ctl" id="mirrorCtl"></div>
</section>
<section class="screen" id="s-power">
<div class="field" id="field"></div>
<div class="bar"><i id="pbar"></i></div>
<button id="holdBtn" class="disabled"><span>👆</span><b>HOLD ME</b></button>
</section>
<section class="screen" id="s-who">
<div class="prog" id="whoProg"></div>
<button class="ib" id="whoSpk" aria-label="Hear it again">🔊</button>
<div class="whoRow" id="whoRow"></div>
</section>
<section class="screen" id="s-feed">
<div class="feedRow"><div id="feedCh"></div><div class="foodCard"><div id="food"></div><div id="foodWord"></div><div class="mouth" id="feedMouth"></div></div></div>
<div class="ctl" id="feedCtl"></div>
</section>
<section class="screen" id="s-prize">
<div id="box">🎁</div>
<div id="prizeCh"></div>
<div class="bigName" id="prizeName"></div>
<div id="jokeBox"></div>
</section>
<div id="ear"><div class="ring"></div><div class="core">🎤</div><b id="earLbl">Listening…</b></div>
<div id="turn"><svg viewBox="0 0 150 150"><circle cx="75" cy="75" r="68"/></svg><div class="in"><span>🗣️</span>Your turn!</div></div>
<div id="party"><div class="beam b1"></div><div class="beam b2"></div><div class="beam b3"></div><div class="beam b4"></div><div class="ball">🪩</div><div id="freezeTxt">FREEZE!</div>
<div id="partyTheo"></div>
<div class="friends"><span>🎈</span><span>⭐</span><span>🎉</span><span>🌈</span><span>🎈</span></div>
<button class="ib" id="partyX" aria-label="Stop dancing">✖</button></div>
<div id="wave"><div class="surf" id="waveCh"></div><div class="where" id="waveWhere"></div></div>
<div id="fxLayer"></div>
<canvas id="fx"></canvas>
<div class="modal" id="grown">
<div class="sheet">
<h2>👪 For grown-ups</h2>
<label>Child's name (optional; names use the device voice)</label>
<input id="nameIn" maxlength="20">
<label>This week's sounds</label>
<div class="soundPick" id="soundPick">
<label><input type="checkbox" value="th"> 🐶 TH (Thunder)</label>
<label><input type="checkbox" value="f"> 🐰 F (Fifi)</label>
<label><input type="checkbox" value="v"> 🏎️ V (Vinny)</label>
<label><input type="checkbox" value="s"> 🐍 S (Sunny)</label>
</div>
<label class="micRow"><input type="checkbox" id="micIn"> 🎤 Listen with the microphone</label>
<p class="micState" id="micState"></p>
<label>Backup device voice</label>
<select id="voiceSel"></select>
<ul>
<li><b>How it flows:</b> one Play tap runs a loop. Each round a friend visits: the door, the mouth mirror, a power game the child's voice drives, Who said it?, Feed the friend, then a prize costume, a dance party and a joke. It remembers where you stopped.</li>
<li><b>What the microphone can tell:</b> a soft breezy hiss (TH or F), a sharp snake hiss (S), a quick pop (T, P, D) and a voice. It cannot tell TH from F, and for V it only checks that it heard a voice. The mouth picture and you cover the rest: tap <b>👍 Said it right</b> whenever it misses.</li>
<li><b>Always positive:</b> another sound is never "wrong"; it is another friend's sound. After two tries the friend eats the word anyway and the child gets a star.</li>
<li><b>Play, not therapy.</b> This is a game for practice at home. If a professional is helping your child, follow their cues first.</li>
<li><b>No sound?</b> Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent. Sound comes out of the speaker while the microphone is on.</li>
<li><b>Privacy:</b> the child's voice is analysed on this device while they speak and is never saved or sent anywhere.</li>
</ul>
<div class="sheetBtns">
<button class="btn" id="resetBtn">Start over</button>
<button class="btn green" id="closeGrown">Done</button>
</div>
</div>
</div>
<div id="start">
<div class="startRow" id="startRow"></div>
<h1>Silly <b>Sound</b> Squad</h1>
<p>A sound game for little talkers. Turn the sound on 🔊, then tap Allow so the friends can hear you.</p>
<button class="btn green big" id="startBtn">Tap to start</button>
</div>
</div>
<script>
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const shuffle=a=>{for(let i=a.length-1;i>0;i--){const j=Math.random()*(i+1)|0;[a[i],a[j]]=[a[j],a[i]]}return a};
const pick=a=>a[Math.random()*a.length|0];
const store={get(k,d){try{const v=localStorage.getItem('squad1_'+k);return v==null?d:JSON.parse(v)}catch(e){return d}},set(k,v){try{localStorage.setItem('squad1_'+k,JSON.stringify(v))}catch(e){}}};
const state={stars:store.get('stars',0),stickers:store.get('stickers',[]),name:store.get('name',''),voiceName:store.get('voice',null),music:store.get('music',true),
sounds:store.get('sounds',['th','f','v','s']),micWanted:store.get('mic',true)};
const J=Object.assign({round:0,station:0,joke:0,costume:0,lastCostume:{}},store.get('journey',{}));
const saveJ=()=>store.set('journey',J);
/* ---------- THE SILLY SOUND SQUAD ---------- */
// Each friend shows the mouth for its sound: Thunder's tongue peeks out (TH), Fifi's teeth sit on her lip (F),
// Vinny the race car has buck teeth on his bumper-lip and a buzzy motor (V), Sunny smiles with her teeth together (S).
function puppySVG(){return `<svg class="ch ch-th" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="188" rx="52" ry="8" fill="#0002"/>
<path class="ear l" d="M50 50 C18 58 16 124 40 132 C58 124 64 88 64 64Z" fill="#8b5a2b"/>
<path class="ear r" d="M150 50 C182 58 184 124 160 132 C142 124 136 88 136 64Z" fill="#8b5a2b"/>
<ellipse cx="100" cy="170" rx="44" ry="20" fill="#e9b46a"/>
<circle cx="100" cy="96" r="62" fill="#f2c27b"/>
<ellipse cx="129" cy="78" rx="22" ry="19" fill="#d99a4e" opacity=".55"/>
<ellipse cx="100" cy="124" rx="37" ry="28" fill="#fbe3bd"/>
<g class="eyes"><circle cx="78" cy="82" r="15" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="122" cy="82" r="15" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="78" cy="83" r="8" fill="#2b2b3a"/><circle cx="80.8" cy="79.8" r="2.6" fill="#fff"/><circle cx="122" cy="83" r="8" fill="#2b2b3a"/><circle cx="124.8" cy="79.8" r="2.6" fill="#fff"/></g><ellipse class="lid" cx="78" cy="82" rx="16.5" ry="16.5" fill="#f2c27b"/><ellipse class="lid" cx="122" cy="82" rx="16.5" ry="16.5" fill="#f2c27b"/></g>
<ellipse cx="100" cy="109" rx="13" ry="9" fill="#2b2b3a"/><ellipse cx="96" cy="106" rx="4" ry="2.4" fill="#fff" opacity=".6"/>
<path d="M82 125 Q100 138 118 125" stroke="#2b2b3a" stroke-width="4" fill="none" stroke-linecap="round"/>
<g class="tg"><path d="M89 129 Q100 166 111 129 Z" fill="#ff7a9a" stroke="#d9546f" stroke-width="2"/><path d="M100 132 L100 148" stroke="#d9546f" stroke-width="2"/></g>
<ellipse cx="62" cy="120" rx="10" ry="6" fill="#ff9aa8" opacity=".6"/><ellipse cx="138" cy="120" rx="10" ry="6" fill="#ff9aa8" opacity=".6"/>
<g class="puff"><path d="M126 150 q14 -4 24 4" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/><path d="M130 166 q16 -2 28 8" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/></g>
</g></svg>`}
function bunnySVG(){return `<svg class="ch ch-f" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="190" rx="50" ry="8" fill="#0002"/>
<g class="ear l"><ellipse cx="70" cy="42" rx="17" ry="46" fill="#e9dcff"/><ellipse cx="70" cy="46" rx="8" ry="34" fill="#ffb3c7"/></g>
<g class="ear r"><ellipse cx="130" cy="42" rx="17" ry="46" fill="#e9dcff"/><ellipse cx="130" cy="46" rx="8" ry="34" fill="#ffb3c7"/></g>
<ellipse cx="100" cy="172" rx="42" ry="20" fill="#e2d4fb"/>
<circle cx="100" cy="112" r="58" fill="#f3ecff"/>
<g class="eyes"><circle cx="78" cy="98" r="14" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="122" cy="98" r="14" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="78" cy="99" r="7.5" fill="#2b2b3a"/><circle cx="80.625" cy="96.0" r="2.4" fill="#fff"/><circle cx="122" cy="99" r="7.5" fill="#2b2b3a"/><circle cx="124.625" cy="96.0" r="2.4" fill="#fff"/></g><ellipse class="lid" cx="78" cy="98" rx="15.5" ry="15.5" fill="#f3ecff"/><ellipse class="lid" cx="122" cy="98" rx="15.5" ry="15.5" fill="#f3ecff"/></g>
<path d="M93 116 L107 116 L100 124 Z" fill="#ff8fb1"/>
<path d="M100 124 Q92 132 84 128 M100 124 Q108 132 116 128" stroke="#2b2b3a" stroke-width="3" fill="none" stroke-linecap="round"/>
<path d="M84 144 Q100 152 116 144" stroke="#ff8fb1" stroke-width="7" fill="none" stroke-linecap="round"/>
<rect x="89" y="127" width="11" height="17" rx="3" fill="#fff" stroke="#c9c4d6" stroke-width="2"/><rect x="100" y="127" width="11" height="17" rx="3" fill="#fff" stroke="#c9c4d6" stroke-width="2"/>
<path d="M58 118 L30 112 M58 124 L28 126 M142 118 L170 112 M142 124 L172 126" stroke="#b9b1c9" stroke-width="2" stroke-linecap="round"/>
<ellipse cx="66" cy="132" rx="9" ry="5.5" fill="#ff9aa8" opacity=".55"/><ellipse cx="134" cy="132" rx="9" ry="5.5" fill="#ff9aa8" opacity=".55"/>
<g class="puff"><path d="M120 150 q14 -4 24 4" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/><path d="M124 166 q16 -2 28 8" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/></g>
</g></svg>`}
function carSVG(){return `<svg class="ch ch-v" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="186" rx="76" ry="9" fill="#0002"/>
<path d="M50 96 Q58 52 100 50 Q142 52 150 96 Z" fill="#ff5252"/>
<path d="M62 94 Q68 62 100 60 Q132 62 138 94 Z" fill="#bfe9ff" stroke="#fff" stroke-width="3"/>
<g class="eyes"><circle cx="85" cy="77" r="12.5" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="115" cy="77" r="12.5" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="85" cy="78" r="6.5" fill="#2b2b3a"/><circle cx="87.275" cy="75.4" r="2.1" fill="#fff"/><circle cx="115" cy="78" r="6.5" fill="#2b2b3a"/><circle cx="117.275" cy="75.4" r="2.1" fill="#fff"/></g><ellipse class="lid" cx="85" cy="77" rx="14.0" ry="14.0" fill="#bfe9ff"/><ellipse class="lid" cx="115" cy="77" rx="14.0" ry="14.0" fill="#bfe9ff"/></g>
<rect x="22" y="92" width="156" height="66" rx="26" fill="#ff3b3b"/>
<rect x="30" y="98" width="140" height="10" rx="5" fill="#ff7b7b"/>
<text x="100" y="128" text-anchor="middle" font-size="18" font-weight="700" fill="#fff" font-family="Fredoka">V</text>
<circle cx="44" cy="124" r="11" fill="#ffe27a" stroke="#fff" stroke-width="3"/><circle cx="156" cy="124" r="11" fill="#ffe27a" stroke="#fff" stroke-width="3"/>
<path d="M64 146 Q100 160 136 146" stroke="#2b2b3a" stroke-width="10" fill="none" stroke-linecap="round"/>
<rect x="88" y="132" width="11" height="15" rx="3" fill="#fff" stroke="#ccc" stroke-width="2"/><rect x="101" y="132" width="11" height="15" rx="3" fill="#fff" stroke="#ccc" stroke-width="2"/>
<g class="wheel"><circle cx="54" cy="164" r="20" fill="#2b2b3a"/><circle cx="54" cy="164" r="8" fill="#ccc"/><path d="M54 150 L54 178 M40 164 L68 164" stroke="#888" stroke-width="3"/></g>
<g class="wheel w2"><circle cx="146" cy="164" r="20" fill="#2b2b3a"/><circle cx="146" cy="164" r="8" fill="#ccc"/><path d="M146 150 L146 178 M132 164 L160 164" stroke="#888" stroke-width="3"/></g>
<g class="puff"><path d="M176 104 l12 -6 M180 118 l14 0 M176 132 l12 6" stroke="#ffb300" stroke-width="5" stroke-linecap="round"/></g>
</g></svg>`}
function snakeSVG(){return `<svg class="ch ch-s" viewBox="0 0 200 200"><g class="bob">
<ellipse cx="100" cy="190" rx="66" ry="8" fill="#0002"/>
<ellipse cx="100" cy="170" rx="70" ry="20" fill="#5cc96b"/><ellipse cx="100" cy="166" rx="56" ry="9" fill="#ffe27a" opacity=".8"/>
<ellipse cx="100" cy="140" rx="54" ry="18" fill="#6fd57c"/><ellipse cx="100" cy="137" rx="42" ry="7" fill="#ffe27a" opacity=".8"/>
<path d="M80 128 Q76 100 100 96 Q124 100 120 128 Z" fill="#6fd57c"/>
<circle cx="100" cy="78" r="44" fill="#7ee08a"/>
<circle cx="80" cy="54" r="6" fill="#5cc96b"/><circle cx="118" cy="50" r="5" fill="#5cc96b"/><circle cx="104" cy="40" r="4" fill="#5cc96b"/>
<g class="eyes"><circle cx="84" cy="66" r="13" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><circle cx="116" cy="66" r="13" fill="#fff" stroke="#2b2b3a" stroke-width="2.5"/><g class="pup"><circle cx="84" cy="67" r="7" fill="#2b2b3a"/><circle cx="86.45" cy="64.2" r="2.2" fill="#fff"/><circle cx="116" cy="67" r="7" fill="#2b2b3a"/><circle cx="118.45" cy="64.2" r="2.2" fill="#fff"/></g><ellipse class="lid" cx="84" cy="66" rx="14.5" ry="14.5" fill="#7ee08a"/><ellipse class="lid" cx="116" cy="66" rx="14.5" ry="14.5" fill="#7ee08a"/></g>
<path d="M72 88 Q100 112 128 88 Z" fill="#2b2b3a"/>
<rect x="78" y="88" width="44" height="9" rx="3" fill="#fff"/><path d="M80 92.5 L120 92.5" stroke="#d6d6d6" stroke-width="1.5"/>
<g class="flick"><path d="M100 104 L100 116 L95 122 M100 116 L105 122" stroke="#ff4d6d" stroke-width="3" fill="none" stroke-linecap="round"/></g>
<ellipse cx="66" cy="84" rx="8" ry="5" fill="#ff9aa8" opacity=".6"/><ellipse cx="134" cy="84" rx="8" ry="5" fill="#ff9aa8" opacity=".6"/>
<g class="puff"><path d="M136 100 q12 -6 22 -2 M138 112 q14 -2 24 4" stroke="#7fd3ff" stroke-width="5" fill="none" stroke-linecap="round"/></g>
</g></svg>`}
const SQUAD={
th:{key:'th',name:'Thunder',animal:'puppy',icon:'🐶',svg:puppySVG,color:'#f2a64a',pose:'thAir',rest:'th',want:'soft',her:'him',
steps:[['open','Open wide, just a tiny bit.'],['th','Let your tongue peek out, like a puppy tongue!'],['thAir','Now blow softly, like a little breeze.']],
words:[['thumb','👍','I'],['three','3️⃣','I'],['think','🤔','I'],['thunder','⛈️','I'],['bath','🛁','F'],['teeth','🦷','F'],['mouth','👄','F']],
game:'bubbles'},
f:{key:'f',name:'Fifi',animal:'bunny',icon:'🐰',svg:bunnySVG,color:'#a98bff',pose:'f',rest:'fRest',want:'soft',her:'her',
steps:[['fRest','Make bunny teeth! Put them on your bottom lip.'],['f','Now blow softly, like a little breeze.']],
words:[['fish','🐟','I'],['fan','🪭','I'],['feet','🦶','I'],['fox','🦊','I'],['fork','🍴','I'],['five','5️⃣','I']],
game:'candles'},
v:{key:'v',name:'Vinny',animal:'race car',icon:'🏎️',svg:carSVG,color:'#ff4d4d',pose:'v',rest:'fRest',want:'voice',her:'him',
steps:[['fRest','Make bunny teeth! Put them on your bottom lip.'],['v','Now turn on your motor, and make it buzz. Your lip will tickle!']],
words:[['van','🚐','V'],['vase','🏺','V'],['violin','🎻','V'],['volcano','🌋','V']],
game:'race'},
s:{key:'s',name:'Sunny',animal:'snake',icon:'🐍',svg:snakeSVG,color:'#3fbf74',pose:'s',rest:'sRest',want:'sharp',her:'her',
steps:[['smile','Smile big, and put your teeth together.'],['sRest','Keep your tongue hiding inside.'],['s','Now let the air hiss out, like a happy snake.']],
words:[['sun','☀️','I'],['sock','🧦','I'],['soap','🧼','I'],['soup','🍲','I'],['six','6️⃣','I'],['sandwich','🥪','I']],
game:'balloon'}};
const COSTUMES=[['Super','🦸','⚡'],['Pirate','🏴☠️','🦜'],['Space','👩🚀','🚀'],['Wizard','🧙','🪄'],['Chef','👨🍳','🍕'],['Firefighter','🚒','🧯'],['Rock Star','🎸','🎤']];
const HATS={Super:'🦸',Pirate:'🏴☠️',Space:'🪐',Wizard:'🎩',Chef:'🍳',Firefighter:'⛑️','Rock Star':'👑'};
function charHTML(k,extra=''){return `<div class="chwrap ${extra}" data-ch="${k}">${SQUAD[k].svg()}<span class="hat"></span><span class="hold"></span></div>`}
function dress(el,costume){const h=el.querySelector('.hat'),o=el.querySelector('.hold');if(!h)return;if(!costume){h.textContent='';o.textContent='';return}
const c=COSTUMES.find(x=>x[0]===costume);h.textContent=HATS[costume]||'';o.textContent=c?c[2]:''}
function act(el,on){if(el)el.classList.toggle('act',!!on)}
function hop(el){if(!el)return;el.classList.remove('hop');void el.offsetWidth;el.classList.add('hop')}
/* ---------- AUDIO ---------- */
let AC=null,master=null,musicGain=null,voiceGain=null,whooshNode=null,noiseBuf=null,speaking=false;
/* iPhone: Web Audio is muted by the silent switch unless the page asks for "playback" audio. */
let silentEl=null;
function iosUnlock(){try{const want=(typeof mic!=='undefined'&&mic.state==='on')?'play-and-record':'playback';if(navigator.audioSession&&navigator.audioSession.type!==want)navigator.audioSession.type=want}catch(e){}
if(!('audioSession' in navigator)){try{if(!silentEl){silentEl=new Audio('audio/silence.mp3');silentEl.loop=true;silentEl.setAttribute('playsinline','')}const p=silentEl.play();if(p&&p.catch)p.catch(()=>{})}catch(e){}}}
function wake(){iosUnlock();if(AC&&AC.state!=='running'){try{const p=AC.resume();if(p&&p.catch)p.catch(()=>{})}catch(e){}}}
['pointerdown','touchend','click','keydown'].forEach(ev=>document.addEventListener(ev,wake,{passive:true,capture:true}));
document.addEventListener('visibilitychange',()=>{if(!document.hidden)wake()});
function initAudio(){iosUnlock();if(AC){wake();return}try{AC=new(window.AudioContext||window.webkitAudioContext)();try{AC.resume()}catch(e){}master=AC.createGain();master.gain.value=.5;master.connect(AC.destination);musicGain=AC.createGain();musicGain.gain.value=.6;musicGain.connect(master);voiceGain=AC.createGain();voiceGain.gain.value=1.7;voiceGain.connect(AC.destination)}catch(e){AC=null}}
function tone(f,d,type='sine',v=.2,when=0,slide,dest){if(!AC)return;const t=AC.currentTime+when,o=AC.createOscillator(),g=AC.createGain();o.type=type;o.frequency.setValueAtTime(f,t);if(slide)o.frequency.exponentialRampToValueAtTime(slide,t+d);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(v,t+.015);g.gain.exponentialRampToValueAtTime(.0001,t+d);o.connect(g);g.connect(dest||master);o.start(t);o.stop(t+d+.05)}
const sfx={chime(){[523,659,784,1047].forEach((f,i)=>tone(f,.4,'triangle',.17,i*.09))},pop(){tone(760,.16,'sine',.22,0,260)},boing(){tone(330,.45,'sine',.2,0,130)},hop(){tone(380,.16,'square',.05,0,820)},tap(){tone(900,.07,'sine',.1)},
fanfare(){[392,523,659,784,659,784,1047].forEach((f,i)=>tone(f,.32,'triangle',.17,i*.13))},
drum(){for(let i=0;i<14;i++)tone(140+i*6,.06,'triangle',.12+i*.008,i*.07)},
rimshot(){tone(200,.12,'square',.12);tone(900,.25,'triangle',.12,.12);tone(1300,.35,'triangle',.08,.16)},
silly(){tone(500,.18,'sine',.18,0,900);tone(900,.18,'sine',.18,.18,400);tone(400,.3,'sine',.18,.36,700)},
slide(){tone(300,.5,'sine',.15,0,1200)},
sparkle(){[1319,1568,2093,2637].forEach((f,i)=>tone(f,.25,'sine',.08,i*.06))},
bloop(){tone(180,.35,'sine',.3,0,520);tone(520,.25,'sine',.15,.3,260)},
scratch(){tone(900,.35,'sawtooth',.08,0,90)},
slideUp(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='sine';o.frequency.setValueAtTime(400,t);o.frequency.exponentialRampToValueAtTime(1600,t+.5);l.frequency.value=12;lg.gain.value=25;l.connect(lg);lg.connect(o.frequency);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.16,t+.03);g.gain.exponentialRampToValueAtTime(.001,t+.55);o.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.6);l.stop(t+.6)},
slideDown(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain();o.type='sine';o.frequency.setValueAtTime(1400,t);o.frequency.exponentialRampToValueAtTime(300,t+.6);g.gain.setValueAtTime(.15,t);g.gain.exponentialRampToValueAtTime(.001,t+.65);o.connect(g);g.connect(master);o.start(t);o.stop(t+.7)},
boing2(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='triangle';o.frequency.value=220;l.frequency.setValueAtTime(18,t);l.frequency.exponentialRampToValueAtTime(4,t+.6);lg.gain.setValueAtTime(120,t);lg.gain.exponentialRampToValueAtTime(5,t+.6);l.connect(lg);lg.connect(o.frequency);g.gain.setValueAtTime(.22,t);g.gain.exponentialRampToValueAtTime(.001,t+.65);o.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.7);l.stop(t+.7)},
kazoo(){if(!AC)return;[523,659,784,1047,784,1047].forEach((f,i)=>{const t=AC.currentTime+i*.12,o=AC.createOscillator(),bp=AC.createBiquadFilter(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='sawtooth';o.frequency.value=f;l.frequency.value=7;lg.gain.value=f*.02;l.connect(lg);lg.connect(o.frequency);bp.type='bandpass';bp.frequency.value=1400;bp.Q.value=2;g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.12,t+.02);g.gain.exponentialRampToValueAtTime(.001,t+(i===5?.5:.16));o.connect(bp);bp.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.55);l.stop(t+.55)})},
honk2(){tone(330,.16,'square',.1);tone(262,.25,'square',.1,.18)},
chomp(){noiseHit(.07,900,'bandpass',.5);noiseHit(.07,900,'bandpass',.5,.16);tone(220,.1,'square',.06,0,120)},
toot(){tone(110,.55,'sawtooth',.16,0,70);tone(95,.5,'square',.06,.05,60)},
honk(){tone(392,.22,'square',.12);tone(330,.3,'square',.12,.26)}};
function noiseHit(dur,freq,type,v,when=0){if(!AC)return;if(!noiseBuf){noiseBuf=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);const d=noiseBuf.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1}
const t=AC.currentTime+when,s=AC.createBufferSource();s.buffer=noiseBuf;const f=AC.createBiquadFilter();f.type=type;f.frequency.value=freq;const g=AC.createGain();g.gain.setValueAtTime(v,t);g.gain.exponentialRampToValueAtTime(.0001,t+dur);s.connect(f);f.connect(g);g.connect(master);s.start(t,Math.random());s.stop(t+dur+.02)}
let beatTimer=null,beatStep=0;const BASS=[110,0,110,0,131,0,98,0,110,0,110,0,147,0,131,0],ARP=[523,659,784,659,587,698,880,698];
function kick(){if(!AC)return;const t=AC.currentTime,o=AC.createOscillator(),g=AC.createGain();o.frequency.setValueAtTime(150,t);o.frequency.exponentialRampToValueAtTime(45,t+.15);g.gain.setValueAtTime(.55,t);g.gain.exponentialRampToValueAtTime(.001,t+.2);o.connect(g);g.connect(master);o.start(t);o.stop(t+.22)}
function beatStart(){initAudio();if(!AC||beatTimer)return;beatStep=0;beatTimer=setInterval(()=>{const s=beatStep%16;if(s%4===0)kick();if(s===4||s===12)noiseHit(.13,1800,'highpass',.3);if(s%2===0)noiseHit(.03,7000,'highpass',.09);if(BASS[s])tone(BASS[s],.2,'square',.06);if(s%2===1)tone(ARP[(beatStep>>1)%8],.13,'triangle',.06);beatStep++},125)}
function beatStop(){clearInterval(beatTimer);beatTimer=null}
function whoosh(on){if(!AC)return;const now=AC.currentTime;if(on){if(whooshNode)return;if(!noiseBuf){noiseBuf=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);const d=noiseBuf.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1}
const s=AC.createBufferSource();s.buffer=noiseBuf;s.loop=true;const f=AC.createBiquadFilter();f.type='highpass';f.frequency.value=1200;f.Q.value=.5;const g=AC.createGain();g.gain.setValueAtTime(0,now);g.gain.linearRampToValueAtTime(.1,now+.25);s.connect(f);f.connect(g);g.connect(master);s.start();whooshNode={s,g}}
else if(whooshNode){const{s,g}=whooshNode;g.gain.cancelScheduledValues(now);g.gain.setValueAtTime(g.gain.value,now);g.gain.linearRampToValueAtTime(0,now+.25);s.stop(now+.3);whooshNode=null}}
function whooshPuff(ms){whoosh(true);setTimeout(()=>whoosh(false),ms)}
let musicTimer=null,mStep=0;const GROOVE=[523,0,659,0,784,0,659,784,880,0,784,0,659,0,587,0,523,0,659,0,784,0,1047,0,988,0,880,0,784,659,587,0],BASS2=[131,131,175,175,196,196,131,196];const MEL=[523,659,784,659,587,698,880,698,523,659,784,1047,880,784,659,587];
function setMusic(on){state.music=on;$('#musicBtn').classList.toggle('off',!on);clearInterval(musicTimer);musicTimer=null;if(on){initAudio();if(!AC)return;duck(speaking);musicTimer=setInterval(()=>{const s=mStep++%32,f=GROOVE[s];if(f)tone(f,.16,'triangle',.07,0,null,musicGain);if(s%4===0)tone(BASS2[(s>>2)%8],.22,'triangle',.09,0,null,musicGain);if(s%8===4)tone(1800,.03,'square',.012,0,null,musicGain)},190)}}
function duck(on){if(!musicGain||!AC)return;const e=document.getElementById('ear');const lis=(e&&e.classList.contains('on'))||(typeof mic!=='undefined'&&mic.rec);musicGain.gain.setTargetAtTime(lis?0:(on?.12:.5),AC.currentTime,.08)}
/* ---------- VOICE: Kokoro Heart clips, never overlapping ---------- */
let voice=null;
function enVoices(){if(!('speechSynthesis' in window))return[];return speechSynthesis.getVoices().filter(v=>/^en([-_]|$)/i.test(v.lang))}
function pickVoice(){const en=enVoices();if(!en.length)return;if(state.voiceName){const v=en.find(v=>v.name===state.voiceName);if(v){voice=v;return}}
const sc=v=>{let s=0;if(/en[-_]US/i.test(v.lang))s+=3;if(/premium/i.test(v.name))s+=7;if(/enhanced|neural|natural/i.test(v.name))s+=5;if(/Ava|Samantha|Allison|Aria|Jenny|Google US English/i.test(v.name))s+=3;if(/Albert|Bad News|Bahh|Bells|Boing|Bubbles|Cellos|Wobble|Zarvox|Trinoids|Whisper|Jester|Organ|Superstar|Fred|Ralph|Junior|Grandma|Grandpa|Rocko|Good News/i.test(v.name))s-=20;return s};
voice=en.slice().sort((a,b)=>sc(b)-sc(a))[0]}
function fillVoiceSel(){const sel=$('#voiceSel');const en=enVoices();sel.innerHTML=en.map(v=>`<option value="${v.name.replace(/"/g,'"')}">${v.name} (${v.lang})</option>`).join('')||'<option>Default voice</option>';if(voice)sel.value=voice.name}
if('speechSynthesis' in window){speechSynthesis.onvoiceschanged=()=>{pickVoice();fillVoiceSel()};pickVoice()}
function setCaption(t){$('#cap').textContent=t}
const CLIPS=__CLIPS__;
const bufCache={};let curSrc=null,sayId=0;
function ckey(t){return t.toLowerCase().replace(/’/g,"'").replace(/[^a-z0-9' ]+/g,' ').replace(/\s+/g,' ').trim()}
function loadClip(fn){if(!bufCache[fn])bufCache[fn]=fetch('audio/'+fn).then(r=>{if(!r.ok)throw 0;return r.arrayBuffer()}).then(b=>new Promise((res,rej)=>AC.decodeAudioData(b,res,rej))).catch(e=>{delete bufCache[fn];throw e});return bufCache[fn]}
function preloadClips(){if(!AC)return;let i=0;const fns=Object.values(CLIPS);const next=()=>{if(i>=fns.length)return;loadClip(fns[i++]).catch(()=>{}).finally(next)};for(let k=0;k<4;k++)next()}
function stopVoice(){sayId++;if(curSrc){const c=curSrc;curSrc=null;try{c.stop()}catch(e){}}if('speechSynthesis' in window)speechSynthesis.cancel()}
const nm=()=>state.name?', '+state.name:'';
function say(text,o={}){setCaption(o.caption!=null?o.caption:text);stopVoice();const id=sayId;const fn=CLIPS[(o.pre||'')+ckey(text)];
return new Promise(res=>{let done=false,tm=null;const fin=()=>{if(done)return;done=true;clearTimeout(tm);if(id===sayId){speaking=false;duck(false)}res()};
speaking=true;duck(true);
const tts=()=>{if(id!==sayId)return fin();if(!('speechSynthesis' in window)){tm=setTimeout(fin,900+text.length*70);return}
const u=new SpeechSynthesisUtterance(text);if(voice)u.voice=voice;u.lang=voice?voice.lang:'en-US';u.rate=(o.rate||.9)*.85;u.pitch=1.1;u.onend=fin;u.onerror=fin;tm=setTimeout(fin,2000+text.length*140/u.rate);setTimeout(()=>{if(!done)speechSynthesis.speak(u)},70)};
if(fn&&AC){loadClip(fn).then(buf=>{if(id!==sayId)return fin();const src=AC.createBufferSource();src.buffer=buf;src.connect(voiceGain);src.onended=fin;curSrc=src;src.start();tm=setTimeout(fin,buf.duration*1000+1500)}).catch(tts)}else tts()})}
/* ---------- MOUTH ---------- */
const BASE={open:.06,spread:.3,tOut:0,tUp:0,bite:0,air:0,buzz:0};
const POSES={rest:{},open:{open:.34,spread:.38},th:{open:.6,spread:.45,tOut:1,tUp:.5},thAir:{open:.6,spread:.45,tOut:1,tUp:.5,air:1},thBuzz:{open:.6,spread:.45,tOut:1,tUp:.5,buzz:1},
f:{open:.5,spread:.5,bite:1,air:1},d:{open:.75,spread:.4,tUp:1},s:{open:.36,spread:.95,air:1},smile:{open:.38,spread:.95},fRest:{open:.5,spread:.5,bite:1},v:{open:.5,spread:.5,bite:1,buzz:1},sRest:{open:.36,spread:.95}};
const mouths=[];let mid=0;
function mouthMarkup(id){let up='',lo='';for(let i=0;i<6;i++){up+=`<rect x="${107+i*31}" y="-36" width="29" height="54" rx="8"/>`;lo+=`<rect x="${116+i*28}" y="-16" width="27" height="50" rx="7"/>`}
return `<svg viewBox="0 0 400 300"><defs><clipPath id="mc${id}"><path class="mInt"/></clipPath></defs>
<ellipse cx="200" cy="150" rx="198" ry="148" fill="#ffd6bd"/><ellipse cx="58" cy="172" rx="36" ry="24" fill="#ff9aa8" opacity=".35"/><ellipse cx="342" cy="172" rx="36" ry="24" fill="#ff9aa8" opacity=".35"/>
<path d="M166 34 Q183 58 200 50 Q217 58 234 34" fill="none" stroke="#e3a888" stroke-width="6" stroke-linecap="round"/>
<g class="jit"><path class="mOut" fill="#e8687c" stroke="#c94e63" stroke-width="2.5"/><path class="mIntF" fill="#4e1328"/>
<g clip-path="url(#mc${id})"><ellipse class="tBack" cx="200" rx="82" ry="40" fill="#e45d7b"/>
<g class="tUp" fill="#fff" stroke="#e2e2ea" stroke-width="2">${up}</g><g class="tLo" fill="#fbfbff" stroke="#e2e2ea" stroke-width="2">${lo}</g></g>
<g class="tFront"><ellipse class="tFrontE" cx="200" rx="60" ry="1" fill="#f47a93" stroke="#d9546f" stroke-width="2.5"/>
<g class="tEyes"><circle cx="185" cy="0" r="6.5" fill="#fff"/><circle cx="215" cy="0" r="6.5" fill="#fff"/><circle cx="186.5" cy="1" r="3.3" fill="#222"/><circle cx="216.5" cy="1" r="3.3" fill="#222"/></g></g>
<g class="air"></g><g class="buzz"><path class="bzL" fill="none" stroke="#ffb300" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/><path class="bzR" fill="none" stroke="#ffb300" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<text x="40" y="250" font-size="34" font-weight="700" fill="#ffb300" font-family="Fredoka">bzz</text><text x="300" y="250" font-size="34" font-weight="700" fill="#ffb300" font-family="Fredoka">bzz</text></g></g></svg>`}
function makeMouth(el){const id=++mid;el.innerHTML=mouthMarkup(id);const q=s=>el.querySelector(s);
const m={el,p:{...BASE},t:{...BASE},pt:[],spawn:0,
P:{out:q('.mOut'),int:q('.mInt'),intF:q('.mIntF'),up:q('.tUp'),lo:q('.tLo'),back:q('.tBack'),fG:q('.tFront'),fE:q('.tFrontE'),eyes:q('.tEyes'),air:q('.air'),buzz:q('.buzz'),bzL:q('.bzL'),bzR:q('.bzR'),jit:q('.jit')},
set(n){this.t={...BASE,...(POSES[n]||{})}}};
for(let i=0;i<14;i++){const c=document.createElementNS('http://www.w3.org/2000/svg','circle');c.setAttribute('fill','#ffffff55');c.setAttribute('stroke','#fff');c.setAttribute('stroke-width','3');c.setAttribute('r','0');m.P.air.appendChild(c);m.pt.push({c,life:0})}
mouths.push(m);updateMouth(m,1);return m}
function updateMouth(m,dt){const p=m.p,t=m.t,k=Math.min(1,dt*5);for(const key in p)p[key]+=(t[key]-p[key])*k;
const cx=200,cy=150,hw=105+p.spread*28,gap=6+p.open*70,uy=cy-gap/2,ly0=cy+gap/2,ly=ly0+(uy+14-ly0)*p.bite;
m.P.out.setAttribute('d',`M${cx-hw},${cy} C${cx-hw*.55},${uy-30} ${cx-34},${uy-36} ${cx},${uy-21} C${cx+34},${uy-36} ${cx+hw*.55},${uy-30} ${cx+hw},${cy} C${cx+hw*.7},${ly+42} ${cx-hw*.7},${ly+42} ${cx-hw},${cy}Z`);
const xi=hw-12,Yu=(8*uy-2*cy)/6,Yl=(8*ly-2*cy)/6,d=`M${cx-xi},${cy} C${cx-xi*.5},${Yu} ${cx+xi*.5},${Yu} ${cx+xi},${cy} C${cx+xi*.5},${Yl} ${cx-xi*.5},${Yl} ${cx-xi},${cy}Z`;
m.P.int.setAttribute('d',d);m.P.intF.setAttribute('d',d);
m.P.up.setAttribute('transform',`translate(0,${uy.toFixed(1)})`);m.P.lo.setAttribute('transform',`translate(0,${ly0.toFixed(1)})`);
m.P.back.setAttribute('cy',((ly0+26)+((uy+14)-(ly0+26))*p.tUp).toFixed(1));
const top=uy+15,full=Math.max(0,(ly0+24-top)/2),ry=Math.max(.01,full*p.tOut);
m.P.fE.setAttribute('ry',ry.toFixed(2));m.P.fE.setAttribute('cy',(top+ry).toFixed(1));m.P.fG.style.opacity=Math.min(1,p.tOut*3);
m.P.eyes.setAttribute('transform',`translate(0,${(top+ry*1.05).toFixed(1)})`);m.P.eyes.style.opacity=Math.max(0,Math.min(1,(p.tOut-.75)/.25));
m.spawn-=dt;if(p.air>.5&&m.spawn<=0){m.spawn=.11;const s=m.pt.find(o=>o.life<=0);if(s){s.life=1;s.x=cx+(Math.random()-.5)*40;s.y=(uy+ly)/2+6;s.vx=(Math.random()-.5)*50;s.r=6}}
for(const s of m.pt){if(s.life>0){s.life-=dt*.9;s.r+=dt*40;s.y+=dt*32;s.x+=s.vx*dt;s.c.setAttribute('cx',s.x.toFixed(1));s.c.setAttribute('cy',s.y.toFixed(1));s.c.setAttribute('r',s.r.toFixed(1));s.c.style.opacity=Math.max(0,s.life*.8)}else s.c.style.opacity=0}
m.P.buzz.style.opacity=p.buzz;
if(p.buzz>.05){const z=x0=>{let s=`M${x0},96`;for(let i=1;i<=8;i++)s+=` L${x0+(i%2?1:-1)*(9+Math.random()*7)},${96+i*14}`;return s};m.P.bzL.setAttribute('d',z(44));m.P.bzR.setAttribute('d',z(356));
m.P.jit.setAttribute('transform',`translate(${((Math.random()-.5)*2*p.buzz).toFixed(1)},${((Math.random()-.5)*2*p.buzz).toFixed(1)})`)}else m.P.jit.removeAttribute('transform')}
/* ---------- FX ---------- */
const fx=$('#fx'),fctx=fx.getContext('2d');let conf=[];
function sizeFx(){fx.width=innerWidth*devicePixelRatio;fx.height=innerHeight*devicePixelRatio}addEventListener('resize',sizeFx);sizeFx();
function confetti(n=110){const cols=['#ff5d8f','#ffc93c','#3fbf74','#36a9e1','#8a6cff','#ff9f43'];for(let i=0;i<n;i++)conf.push({x:innerWidth/2+(Math.random()-.5)*260,y:innerHeight*.5,vx:(Math.random()-.5)*15,vy:-Math.random()*15-5,w:Math.random()*8+6,c:cols[i%6],a:Math.random()*6,va:(Math.random()-.5)*.4,life:1})}
function drawConf(dt){const r=devicePixelRatio;fctx.clearRect(0,0,fx.width,fx.height);conf=conf.filter(c=>c.life>0&&c.y<innerHeight+40);for(const c of conf){c.vy+=30*dt;c.x+=c.vx*dt*30;c.y+=c.vy*dt*30;c.a+=c.va;c.life-=dt*.35;fctx.save();fctx.translate(c.x*r,c.y*r);fctx.rotate(c.a);fctx.fillStyle=c.c;fctx.globalAlpha=Math.min(1,c.life*2);fctx.fillRect(-c.w*r/2,-c.w*r/4,c.w*r,c.w*r/2);fctx.restore()}}
function floater(e,a){const s=document.createElement('div');s.className='flo '+a;s.textContent=e;
if(a==='leap'){s.style.left=(25+Math.random()*50)+'vw';s.style.top='55vh'}else if(a==='fly'){s.style.left='0';s.style.top=(35+Math.random()*25)+'vh'}else if(a==='run'){s.style.left='0';s.style.top='76vh'}else if(a==='swim'){s.style.left='0';s.style.top='86vh';s.style.fontSize='60px'}else{s.style.left=(15+Math.random()*70)+'vw';s.style.top='95vh'}
$('#fxLayer').appendChild(s);setTimeout(()=>s.remove(),9500)}
let btBusy=false;
function bigRise(talk=true){if(btBusy)return;btBusy=true;const b=$('#bigTurtle');const side=pick([18,82,22,78,50]);b.style.left=side+'vw';b.classList.remove('up');void b.offsetWidth;b.classList.add('up');sfx.bloop();
for(let i=0;i<6;i++)setTimeout(()=>{const d=document.createElement('div');d.className='flo leap';d.textContent=pick(['✨','⭐','💛']);d.style.left=(parseFloat(b.style.left)-10+Math.random()*20)+'vw';d.style.top='78vh';d.style.fontSize='34px';$('#fxLayer').appendChild(d);setTimeout(()=>d.remove(),2100)},300+i*90);
setTimeout(()=>{if(talk&&!speaking){sfx.silly();say('Peekaboo! I see you!')}},3300);setTimeout(()=>{b.classList.remove('up');btBusy=false},5600)}
function surprise(){const r=Math.random();sfx.pop();
if(r<.28)return bigRise();
if(r<.40)return floater('🐶','swim');
const[e,a]=pick([['🐟','leap'],['🐬','leap'],['🦋','fly'],['🚀','rise'],['🎈','rise'],['🦀','fly'],['🦄','fly'],['🐙','leap'],['🦖','fly'],['🐸','leap'],['🌈','rise'],['🐳','leap']]);floater(e,a);if(Math.random()<.4)setTimeout(()=>floater(pick(['🎈','🫧','⭐']),'rise'),400)}
let last=performance.now();
function loop(now){const dt=Math.min(.05,(now-last)/1000);last=now;for(const m of mouths)if(m.el.offsetParent!==null)updateMouth(m,dt);powerTick(dt);earTick();drawConf(dt);requestAnimationFrame(loop)}
requestAnimationFrame(loop);
/* Silly Sound Squad listener: finds the word in a short recording and measures the hiss next to the vowel.
Verdicts: soft (a soft, spread hiss: TH or F), sharp (a loud, narrow S/Z hiss), pop (no long hiss: T, P, D),
voice (voicing, used for V), quiet (nothing heard). TH and F sound almost the same, so the listener
cannot tell them apart: the mouth picture and a grown-up cover that one. Nothing is saved or sent. */
(function (G) {
function fft(re, im) {
const n = re.length;
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
}
for (let len = 2; len <= n; len <<= 1) {
const a = -2 * Math.PI / len, wr = Math.cos(a), wi = Math.sin(a);
for (let i = 0; i < n; i += len) {
let cr = 1, ci = 0;
for (let k = 0; k < len / 2; k++) {
const ur = re[i + k], ui = im[i + k];
const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
re[i + k] = ur + vr; im[i + k] = ui + vi;
re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;
}
}
}
}
const winCache = {};
function hann(N) { if (!winCache[N]) { const w = new Float32Array(N); for (let i = 0; i < N; i++) w[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (N - 1)); winCache[N] = w; } return winCache[N]; }
function frameSize(sr) { return sr > 32000 ? 1024 : 512; }
// One frame of features from N samples starting at s.
function frame(x, s, N, sr) {
const w = hann(N), re = new Float64Array(N), im = new Float64Array(N);
let sq = 0, zc = 0, prev = x[s];
for (let i = 0; i < N; i++) { const v = x[s + i]; sq += v * v; re[i] = v * w[i]; if ((v >= 0) !== (prev >= 0)) zc++; prev = v; }
fft(re, im);
const bin = sr / N, half = N / 2, top = Math.min(11000, sr / 2 - bin);
let low = 0, mid = 0, high = 0, cn = 0, cd = 0, fl = 0, fa = 0, fc = 0, mx = 0, ca = 0, cc = 0;
for (let k = 1; k < half; k++) {
const f = k * bin, p = re[k] * re[k] + im[k] * im[k] + 1e-12;
if (f >= 80 && f < 900) low += p; else if (f >= 900 && f < 3000) mid += p; else if (f >= 3000 && f <= top) high += p;
if (f >= 1000 && f <= top) { cn += f * p; cd += p; }
if (f >= 1500 && f <= Math.min(10000, top)) { fl += Math.log(p); fa += p; fc++; }
if (f >= 3000 && f <= Math.min(10000, top)) { if (p > mx) mx = p; ca += p; cc++; }
}
const rms = Math.sqrt(sq / N);
return { db: 20 * Math.log10(rms + 1e-9), low, mid, high, zcr: zc / N,
cen: cd ? cn / cd : 0, flat: fc ? Math.exp(fl / fc) / (fa / fc) : 0, crest: cc ? mx / (ca / cc) : 0 };
}
function features(x, sr) {
const N = frameSize(sr), H = N / 2, out = [];
for (let s = 0; s + N <= x.length; s += H) { const f = frame(x, s, N, sr); f.t = s / sr; out.push(f); }
out.hopMs = 1000 * H / sr;
return out;
}
// The hiss right before (dir -1) or after (dir +1) the vowel.
function hissNear(F, from, dir, floor) {
const got = []; let miss = 0;
for (let i = from, n = 0; i >= 0 && i < F.length && n < 45; i += dir, n++) {
const f = F[i];
const fric = f.db > floor + 6 && f.high > f.low * 1.2 && f.zcr > 0.15;
if (fric) { got.push(f); miss = 0; }
else if (f.db < floor + 6) { if (++miss > 2 && got.length) break; if (miss > 4) break; }
else { if (++miss > 3) break; }
}
return got;
}
function analyze(x, sr, kind) {
const F = features(x, sr), hop = F.hopMs;
if (F.length < 8) return { verdict: 'quiet' };
const sorted = F.map(f => f.db).sort((a, b) => a - b);
const floor = Math.max(-75, sorted[Math.floor(sorted.length * 0.1)]), peak = sorted[sorted.length - 1];
if (peak - floor < 15) return { verdict: 'quiet', floor, peak };
// The vowel: the longest run of loud, low-pitched frames.
const voiced = F.map(f => f.db > peak - 24 && f.low > f.high && f.zcr < 0.2);
let best = null, s = -1, gap = 0; const runs = [];
for (let i = 0; i <= F.length; i++) {
if (i < F.length && voiced[i]) { if (s < 0) s = i; gap = 0; }
else if (s >= 0) {
if (i < F.length && ++gap <= 2) continue;
const e = i - gap; runs.push({ s, e }); if (!best || e - s > best.e - best.s) best = { s, e }; s = -1; gap = 0;
}
}
if (!best || (best.e - best.s + 1) * hop < 50) return { verdict: 'quiet', floor, peak };
const big = runs.filter(r => (r.e - r.s + 1) * hop >= 50);
if (kind === 'I' || kind === 'dhI' || kind === 'V') best = big[0]; else if (kind === 'F') best = big[big.length - 1];
let vpk = -200; for (let i = best.s; i <= best.e; i++) vpk = Math.max(vpk, F[i].db);
const info = { floor, peak, vowelMs: Math.round((best.e - best.s + 1) * hop) };
if (kind === 'thM' || kind === 'V') {
// Buzzy sounds (V, buzzy TH) and sounds in the middle of a word: heard is enough, unless a loud sharp hiss starts it (Z).
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3), rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const fl = pre.reduce((a, f) => a + f.flat, 0) / pre.length;
if (rel > -16 && fl < 0.25) return Object.assign({ verdict: 'sharp', rel, flat: fl }, info);
}
return Object.assign({ verdict: 'voice' }, info);
}
if (kind === 'dhI') {
// Buzzy TH: a soft start. D starts with a sudden burst; Z starts with a loud hiss.
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = pre.reduce((a, f) => a + f.cen, 0) / pre.length;
info.rel = rel; info.cen = cen;
if (rel > -16 && cen > 4000) return Object.assign({ verdict: 'sharp' }, info);
}
// Rise time from first sound to near the vowel's peak.
let on = best.s; while (on > 0 && F[on - 1].db > floor + 8) on--;
let r = on; while (r < F.length && F[r].db < vpk - 8) r++;
info.rise = (r - on) * hop;
let jump = 0; for (let i = Math.max(1, on - 1); i <= Math.min(r, F.length - 1); i++) jump = Math.max(jump, F[i].db - F[i - 1].db);
info.jump = jump; info.onHigh = F[on].high / (F[on].low + 1e-12); info.onDb = F[on].db - vpk;
const quietBefore = on > 0 && F[on - 1].db < floor + 6;
return Object.assign({ verdict: 'voice' }, info);
}
const fr = kind === 'F' ? hissNear(F, best.e + 1, 1, floor) : hissNear(F, best.s - 1, -1, floor);
info.hissMs = Math.round(fr.length * hop);
if (fr.length) { const chron = kind === 'F' ? fr : fr.slice().reverse(), mx = Math.max(...fr.map(f => f.db));
info.attack = Math.max(chron[0].db, (chron[1] || chron[0]).db) - mx; info.mean = fr.reduce((a, f) => a + f.db, 0) / fr.length - vpk;
info.flat = fr.reduce((a, f) => a + f.flat, 0) / fr.length; }
if (fr.length * hop < 40) return Object.assign({ verdict: 'pop' }, info);
const top = fr.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = fr.reduce((a, f) => a + f.cen, 0) / fr.length;
const crest = fr.reduce((a, f) => a + f.crest, 0) / fr.length;
Object.assign(info, { rel, cen, crest });
// A T or D: a loud puff that starts all at once and is over quickly.
if (kind === 'I' && info.mean > -13.5 && info.attack > -5 && info.hissMs <= 120) return Object.assign({ verdict: 'pop' }, info);
if (kind === 'I' && info.hissMs <= 65 && info.attack > -3.5) return Object.assign({ verdict: 'pop' }, info);
// An S: a narrow, sharp hiss (low flatness) that is fairly loud next to the vowel.
if (info.flat < 0.25 && info.mean > -18.5) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -11) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -20.5 && cen > 8000 && crest >= 10) return Object.assign({ verdict: 'sharp' }, info);
return Object.assign({ verdict: 'soft' }, info);
}
// Live sound for the blowing game: is this frame a soft TH breeze, a snake hiss or a voice?
function liveKind(f, floor) {
if (f.db < floor + 9) return 'none';
const hissy = f.high > f.low && f.zcr > 0.15;
if (hissy) return (f.flat < 0.25 && f.db > floor + 22) ? 'sharp' : 'soft';
if (f.low > f.high && f.zcr < 0.18) return (f.high > f.low * 0.05 || f.mid > f.low * 0.3) ? 'buzz' : 'voice';
return 'none';
}
G.SoundEar = { features, analyze, frame, frameSize, liveKind };
})(typeof window !== 'undefined' ? window : globalThis);
/* ---------- DANCE PARTY (freeze dance) ---------- */
const MOVES=[['mv-bounce',null],['mv-wiggle','Wiggle, wiggle!'],['mv-spin','Spin around!'],['mv-peek','Wiggle your tongue! Peek, peek, peek!'],['mv-jump',null]];
function setMove(m){const p=$('#partyTheo');MOVES.forEach(x=>p.classList.remove(x[0]));p.classList.add(m)}
let partyResume='home';
async function partyRun(T,dur,auto){const P=$('#party');P.classList.toggle('auto',!!auto);P.classList.remove('frozen');P.classList.add('on');$('#partyTheo').innerHTML=active().map(k=>charHTML(k,'act')).join('');setMove('mv-bounce');
await say('Squad dance party! Dance with your friends!');if(T!==tok)return;{const k=active()[J.round%active().length];await fsay(k,'dance',$(`#partyTheo .chwrap[data-ch="${k}"]`));if(T!==tok)return}
beatStart();const t0=Date.now();let nextFreeze=Date.now()+5000+Math.random()*3000,nextMove=Date.now()+3500,mi=0;
while(T===tok&&(dur==null||Date.now()-t0<dur*1000)){await wait(200);if(T!==tok)break;
if(Date.now()>nextMove){mi=(mi+1+Math.floor(Math.random()*(MOVES.length-1)))%MOVES.length;const[m,line]=MOVES[mi];setMove(m);if(line)say(line);nextMove=Date.now()+4500}
if(Date.now()>nextFreeze){beatStop();sfx.scratch();P.classList.add('frozen');await say('Freeze!');if(T!==tok)break;await wait(2300);if(T!==tok)break;P.classList.remove('frozen');await say('Dance!');if(T!==tok)break;beatStart();nextFreeze=Date.now()+6500+Math.random()*4000}}
beatStop();if(T!==tok)return;P.classList.remove('frozen');await say(`Great dancing${nm()}!`);P.classList.remove('on','auto')}
$('#danceBtn').onclick=()=>{sfx.tap();partyResume=$('#s-home').classList.contains('on')?'home':'journey';const T=newTok();partyRun(T,null,false)};
$('#partyX').onclick=()=>{sfx.tap();newTok();if(partyResume==='home')homeScene();else journeyGo()};
$('#partyTheo').onclick=()=>{sfx.silly();const p=$('#partyTheo');p.animate([{transform:'scale(1)'},{transform:'scale(1.15) rotate(-8deg)'},{transform:'scale(1)'}],{duration:400})};
/* ---------- MICROPHONE (the game listens) ---------- */
const mic={state:'off',stream:null,proc:null,floorArr:[],floor:-60,rec:null,onLive:null,level:-90,kind:'none'};
async function micStart(){
if(!state.micWanted){mic.state='off';return false}
if(mic.state==='on')return true;
if(!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)){mic.state='unsupported';return false}
try{if(navigator.audioSession)navigator.audioSession.type='play-and-record'}catch(e){}
try{
const st=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:false,noiseSuppression:false,autoGainControl:false,channelCount:1}});
initAudio();mic.stream=st;const src=AC.createMediaStreamSource(st);const proc=AC.createScriptProcessor(1024,1,1);const mute=AC.createGain();mute.gain.value=0;
src.connect(proc);proc.connect(mute);mute.connect(AC.destination);mic.proc=proc;mic.src=src;
proc.onaudioprocess=e=>{const d=e.inputBuffer.getChannelData(0),sr=AC.sampleRate,N=Math.min(SoundEar.frameSize(sr),d.length);const f=SoundEar.frame(d,0,N,sr);
if(mic.rec)mic.rec.push(new Float32Array(d));else if(!speaking){mic.floorArr.push(f.db);if(mic.floorArr.length>240)mic.floorArr.shift();const s=mic.floorArr.slice().sort((a,b)=>a-b);mic.floor=Math.max(-85,s[Math.floor(s.length*.2)])}
mic.level=f.db;mic.kind=SoundEar.liveKind(f,mic.floor);if(mic.onLive)mic.onLive(f,mic.kind)};
mic.state='on';return true
}catch(e){mic.state='denied';try{if(navigator.audioSession)navigator.audioSession.type='playback'}catch(_){}return false}}
function micStop(){try{if(mic.stream)mic.stream.getTracks().forEach(t=>t.stop());if(mic.proc){mic.proc.onaudioprocess=null;mic.proc.disconnect()}if(mic.src)mic.src.disconnect()}catch(e){}mic.stream=mic.proc=mic.src=null;mic.state='off';try{if(navigator.audioSession)navigator.audioSession.type='playback'}catch(e){}}
const hearing=()=>mic.state==='on';
// The listening badge: a big pulsing ear that glows with the sound it hears.
const KCOL={soft:'#7fd3ff',sharp:'#7ee08a',voice:'#ffc93c',buzz:'#ffb347',none:'#ffffff'};
function earShow(on,label){const e=$('#ear');e.classList.toggle('on',on);if(label)$('#earLbl').textContent=label;duck(speaking)}// music goes quiet while listening
function earTick(){const e=$('#ear');if(!e.classList.contains('on'))return;const lv=Math.max(0,Math.min(1,(mic.level-mic.floor)/40));
e.style.setProperty('--lv',lv.toFixed(3));e.style.setProperty('--kc',KCOL[mic.kind]||'#fff')}
// Record one try. Stops early once the child has spoken and gone quiet.
async function listenTake(T,maxMs=4200){earShow(true,'Listening…');await wait(250);if(T!==tok){earShow(false);return new Float32Array(0)}// skip the speaker's echo
mic.rec=[];const early=mic.level>mic.floor+16;const t0=Date.now();let spoke=0,quietSince=0;
while(T===tok&&Date.now()-t0<maxMs){await wait(60);if(mic.level>mic.floor+16){spoke=Date.now();quietSince=0}else if(spoke&&!quietSince)quietSince=Date.now();
if(spoke&&quietSince&&Date.now()-quietSince>650&&Date.now()-t0>1100)break}
const parts=mic.rec||[];mic.rec=null;earShow(false);let n=0;parts.forEach(p=>n+=p.length);const x=new Float32Array(n);let o=0;parts.forEach(p=>{x.set(p,o);o+=p.length});x.early=early;return x}
function judge(F,verdict){if(verdict==='quiet')return'quiet';
if(F.want==='voice')return(verdict==='voice'||verdict==='buzz')?'yes':(verdict==='sharp'?'sharp':'yes');
return verdict===F.want?'yes':verdict}
/* ---------- JOURNEY (one loop, never back to a menu) ---------- */
let tok=0;
function newTok(){tok++;stopVoice();beatStop();whoosh(false);$('#turn').classList.remove('on');earShow(false);mic.onLive=null;mic.rec=null;PW.active=false;PW.holding=false;whoPick=null;
const P=$('#party');if(P)P.classList.remove('on','frozen','auto');$$('.override').forEach(b=>b.remove());return tok}
function show(id){$$('.screen').forEach(s=>s.classList.toggle('on',s.id==='s-'+id));$('#trail').style.visibility=id==='home'?'hidden':'visible'}
const STATIONS=['reveal','mirror','power','who','feed','prize'];
const STATION_INFO=[['🚪','Who is here?'],['👄','Mouth mirror'],['⚡','Power play'],['👂','Who said it?'],['🍎','Feed the friend'],['🎁','Prize time']];
function active(){const a=state.sounds.filter(k=>SQUAD[k]);return a.length?a:['th','f','v','s']}
function cur(){const a=active();return SQUAD[a[J.round%a.length]]}
function setTrail(i){$$('#trail i').forEach((e,j)=>{e.classList.toggle('done',j<i);e.classList.toggle('now',j===i)})}
async function journeyGo(){const T=newTok();const i=J.station%6;setTrail(i);const[ic,nm]=STATION_INFO[i];
const w=$('#wave');$('#waveWhere').textContent=ic+' '+nm;$('#waveCh').innerHTML=charHTML(cur().key);w.classList.remove('go');void w.offsetWidth;w.classList.add('go');whooshPuff(1200);sfx.slideUp();
await wait(900);if(T!==tok)return;show(STATIONS[i]);PREP[STATIONS[i]]();await wait(1300);if(T!==tok)return;w.classList.remove('go');SCENES[STATIONS[i]](T)}
function sceneDone(T){if(T!==tok)return;J.station++;if(J.station>=6){J.station=0;J.round++}saveJ();journeyGo()}
function addStar(){state.stars++;store.set('stars',state.stars);$('#starN').textContent=state.stars;const s=$('#stars');s.classList.remove('bump');void s.offsetWidth;s.classList.add('bump')}
async function cheer(T,el,line,k){confetti(160);burst();pick([sfx.kazoo,sfx.chime])();addStar();hop(el);trick(el);if(Math.random()<.15)bigRise(false);await say(line||`Yes! Good job${nm()}!`);if(T!==tok)return;if(k){await fsay(k,'yay',el);if(T!==tok)return}await wait(400)}
function choose(el,items){el.innerHTML='';return new Promise(res=>{items.forEach(([label,val,cls])=>{const b=document.createElement('button');b.className='btn popIn '+(cls||'');b.innerHTML=label;b.onclick=()=>{sfx.tap();el.innerHTML='';res(val)};el.appendChild(b)})})}
// A grown-up can always say "he got it" when the listener is unsure.
function override(){return new Promise(res=>{const b=document.createElement('button');b.className='override';b.textContent='👍 Said it right';b.onclick=()=>{sfx.tap();b.remove();res(true)};document.body.appendChild(b);setTimeout(()=>{if(b.isConnected){b.remove();res(false)}},4200)})}
async function yourTurnNoMic(T,line){await say(line);if(T!==tok)return false;const r=$('#turn');r.classList.remove('on');void r.offsetWidth;r.classList.add('on');await wait(4200);r.classList.remove('on');return T===tok}
/* Friendly tips when a different sound comes out: never "wrong", always another friend's sound. */
const TIP={
th_sharp:'Hee hee! That was a snake hiss, like Sunny’s. For Thunder, let your tongue peek out, and blow softly.',
th_pop:'Pop! That was quick. For Thunder, let your tongue peek out, and make it long, like a breeze.',
f_sharp:'Hee hee! That was Sunny’s snake hiss. For Fifi, put your top teeth on your lip, and blow softly.',
f_pop:'Pop! That was quick. For Fifi, put your teeth on your lip, and make it long, like a breeze.',
s_soft:'Ooh, a soft breezy sound, like Thunder’s! For Sunny, put your teeth together, smile, and hiss.',
s_pop:'Pop! That was quick. For Sunny, make it long, like a snake. Teeth together, and hiss.',
v_sharp:'Ooh, a hissy sound! For Vinny, put your teeth on your lip, and turn on your buzzy motor.',
quiet:'I can’t hear you! Can you say it with a big lion voice?'};
const YAY={th:'Woohoo! That’s Thunder’s sound!',f:'Hooray! That’s Fifi’s sound!',v:'Yippee! That’s Vinny’s sound!',s:'Yes! That’s Sunny’s sound!'};
const INTRO={th:'It’s Thunder the puppy! Thunder’s sound has a peeking tongue. Like in thumb.',f:'It’s Fifi the bunny! Fifi’s sound has bunny teeth. Like in fish.',
v:'It’s Vinny the race car! Vinny’s sound is a buzzy motor. Like in van.',s:'It’s Sunny the snake! Sunny’s sound is a happy hiss. Like in sun.'};
const TURN={th:'Your turn! Make Thunder’s sound.',f:'Your turn! Make Fifi’s sound.',v:'Your turn! Make Vinny’s motor sound.',s:'Your turn! Make Sunny’s hissy sound.'};
const POWER={th:['Thunder loves bubbles! Make Thunder’s sound to blow bubbles. Keep going!','Look at all those bubbles! Thunder is so happy!'],
f:['Fifi has a party cake! Make Fifi’s sound to blow out the candles.','You blew out all the candles! Hooray for Fifi!'],
v:['Help Vinny win the race! Make Vinny’s motor sound to drive. Keep going!','Vinny wins the race! Hooray!'],
s:['Sunny wants to fly a balloon! Make Sunny’s sound to fill it up.','Up, up, and away! Sunny’s balloon is flying!']};
const FEED={th:'Thunder is hungry! Say each word to feed him.',f:'Fifi is hungry! Say each word to feed her.',v:'Vinny needs fuel! Say each word to fill him up.',s:'Sunny is hungry! Say each word to feed her.'};
const FOUND={th:'You found Thunder!',f:'You found Fifi!',v:'You found Vinny!',s:'You found Sunny!'};
const EAT=['Chomp, chomp! Yummy!','Yum! Delicious!','Nom, nom, nom!','Burp! Oh, excuse me! Hee hee!'];
const NEXTWORD=['Here comes a yummy word!','Ooh, what’s this?','Next one!'];
/* ---------- 1. WHO IS HERE? (surprise reveal) ---------- */
function prepReveal(){$('#door').className='door';$('#revealCh').innerHTML='';$('#revealName').textContent=''}
async function revealScene(T){const F=cur();const d=$('#door');d.classList.add('wiggle');const tapped=new Promise(r=>{d.onclick=()=>{d.onclick=null;stopVoice();r()}});
say('Knock, knock! Who is coming to play today? Tap the door!');await tapped;if(T!==tok)return;
d.classList.remove('wiggle');d.classList.add('open');sfx.fanfare();await wait(400);
$('#revealCh').innerHTML=charHTML(F.key,'big popOut');const ch=$('#revealCh .chwrap');dress(ch,J.lastCostume&&J.lastCostume[F.key]);$('#revealName').textContent=F.icon+' '+F.name;confetti(80);
sfx.boing2();await fsay(F.key,'hi',ch);if(T!==tok)return;await wait(300);act(ch,true);await say(INTRO[F.key]);act(ch,false);if(T!==tok)return;await wait(700);sceneDone(T)}
/* ---------- 2. MOUTH MIRROR ---------- */
let mirrorMouth;
function prepMirror(){const F=cur();$('#mirrorCh').innerHTML=charHTML(F.key);$('#stepBig').innerHTML='';$('#mirrorCtl').innerHTML='';mirrorMouth.set('rest')}
function stepBig(icon,label){const e=$('#stepBig');e.innerHTML=`<span>${icon}</span>${label}`;e.classList.remove('popIn');void e.offsetWidth;e.classList.add('popIn')}
async function sustainedTry(T,F,ms=3200){// counts what kind of sound comes out for a few seconds
const c={soft:0,sharp:0,voice:0,buzz:0,none:0};mic.onLive=(f,k)=>{if(!speaking)c[k]=(c[k]||0)+1};earShow(true,'Listening…');const t0=Date.now();
while(T===tok&&Date.now()-t0<ms)await wait(80);mic.onLive=null;earShow(false);
const want=F.want==='voice'?(c.voice+c.buzz):c[F.want];const other=Object.entries(c).filter(([k])=>k!=='none'&&k!==F.want&&!(F.want==='voice'&&(k==='voice'||k==='buzz'))).sort((a,b)=>b[1]-a[1])[0];
if(want>=18)return'yes';if(other&&other[1]>=18)return other[0];if(want+(other?other[1]:0)<10)return'quiet';return'yes'}
async function mirrorScene(T){const F=cur(),ch=$('#mirrorCh .chwrap');
for(const[pose,line]of F.steps){mirrorMouth.set(pose);stepBig(F.icon,line.split(/[,.!]/)[0]);act(ch,/Air|^f$|^v$|^s$/.test(pose));await say(line);if(T!==tok)return;await wait(900);if(T!==tok)return}
mirrorMouth.set(F.pose);act(ch,true);stepBig('🗣️','Your turn!');
for(let tries=0;tries<3;tries++){
let r;
if(hearing()){await say(TURN[F.key]);if(T!==tok)return;r=await sustainedTry(T,F);if(T!==tok)return}
else{if(!await yourTurnNoMic(T,TURN[F.key]))return;await choose($('#mirrorCtl'),[['⭐ I did it!','ok','gold big']]);if(T!==tok)return;r='yes'}
if(r==='yes'){await cheer(T,ch,YAY[F.key],F.key);if(T!==tok)return;break}
if(r==='quiet'&&tries<2){await say(TIP.quiet);if(T!==tok)return;continue}
if(tries>=1){await cheer(T,ch,`Great trying${nm()}!`);if(T!==tok)return;break}
const tip=TIP[F.key+'_'+r];if(tip){popFriendFor(r);await say(tip);if(T!==tok)return}await wait(400)}
act(ch,false);mirrorMouth.set('rest');sceneDone(T)}
// The friend whose sound came out pops in to wave (never as a "wrong" signal).
function popFriendFor(kind){const k=kind==='sharp'?'s':(kind==='soft'?'th':null);if(!k)return;const p=document.createElement('div');p.className='cameo';p.innerHTML=charHTML(k);document.body.appendChild(p);sfx.pop();setTimeout(()=>p.remove(),3600)}
/* ---------- 3. POWER PLAY (the child's sound drives it) ---------- */
const PW={active:false,holding:false,prog:0,t:0,idle:0,done:null,game:'bubbles',lastK:'none',bub:0};
function prepPower(){const F=cur();PW.game=F.game;PW.prog=0;PW.active=false;$('#pbar').style.width='0';const fld=$('#field');fld.className='field g-'+F.game;
let h='';
if(F.game==='bubbles')h=`<div class="pwCh">${charHTML('th')}</div><div class="wand">🫧</div>`;
if(F.game==='candles')h=`<div class="pwCh">${charHTML('f')}</div><div class="cake"><div class="flames">${'<i></i>'.repeat(5)}</div><div class="cakeBody">🎂</div></div>`;
if(F.game==='race')h=`<div class="track"></div><div class="flag">🏁</div><div class="racer">${charHTML('v')}</div>`;
if(F.game==='balloon')h=`<div class="pwCh">${charHTML('s')}</div><div class="balloon"><div class="bl"></div><div class="str"></div></div>`;
fld.innerHTML=h;$('#holdBtn').classList.add('disabled');$('#holdBtn').style.display=hearing()?'none':'flex';powerDraw()}
function powerDraw(){const p=PW.prog,f=$('#field');$('#pbar').style.width=(p*100)+'%';
if(PW.game==='candles'){f.querySelectorAll('.flames i').forEach((c,i)=>c.classList.toggle('out',p>=(i+1)/5-0.001))}
if(PW.game==='race'){const r=f.querySelector('.racer');if(r)r.style.left=(4+p*74)+'%'}
if(PW.game==='balloon'){const b=f.querySelector('.balloon');if(b){b.style.transform=`translate(-50%,${-p*40}%) scale(${.35+p*.85})`}}}
function powerTick(dt){if(!PW.active)return;const F=cur();let rate=0,k='none';
if(hearing()&&!speaking){k=mic.kind;const ok=F.want==='voice'?(k==='voice'||k==='buzz'):k===F.want;rate=ok?.36:(k!=='none'?.1:0)}
if(PW.holding){rate=.36;k=F.want}
PW.prog=Math.min(1,PW.prog+rate*dt);PW.idle=rate?0:PW.idle+dt;const f=$('#field');
const ch=f.querySelector('.chwrap');act(ch,rate>0);
if(rate>0&&PW.game==='bubbles'&&Math.random()<dt*(rate>.2?14:5)){const b=document.createElement('div');b.className='pbub';const s=24+Math.random()*44;b.style.width=b.style.height=s+'px';b.style.left=(26+Math.random()*10)+'%';b.style.top=(40+Math.random()*20)+'%';f.appendChild(b);
b.animate([{transform:'translate(0,0) scale(.3)',opacity:1},{transform:`translate(${200+Math.random()*400}px,${-60-Math.random()*120}px) scale(1)`,opacity:.9}],{duration:2200+Math.random()*900,easing:'ease-out'});setTimeout(()=>b.remove(),3000)}
if(rate>0&&PW.game==='race'){f.querySelectorAll('.wheel').forEach(w=>w.classList.add('spin'))}else if(PW.game==='race'){f.querySelectorAll('.wheel').forEach(w=>w.classList.remove('spin'))}
if(rate>0&&Math.random()<dt*6){const w=document.createElement('div');w.className='windline';w.style.left=(30+Math.random()*30)+'%';w.style.top=(30+Math.random()*40)+'%';w.style.width=(40+Math.random()*60)+'px';f.appendChild(w);w.animate([{opacity:0,transform:'translateX(0)'},{opacity:.9},{opacity:0,transform:'translateX(140px)'}],{duration:800});setTimeout(()=>w.remove(),820)}
const prev=PW.lastStage||0,stage=Math.floor(PW.prog*5);if(stage>prev){sfx.sparkle();PW.lastStage=stage}
powerDraw();if(PW.prog>=1){PW.active=false;PW.holding=false;$('#holdBtn').classList.remove('pressed');const d=PW.done;PW.done=null;d&&d()}}
const hb=$('#holdBtn');
hb.addEventListener('pointerdown',e=>{e.preventDefault();if(!PW.active)return;initAudio();PW.holding=true;hb.classList.add('pressed')});
['pointerup','pointercancel','pointerleave'].forEach(ev=>hb.addEventListener(ev,()=>{PW.holding=false;hb.classList.remove('pressed')}));
hb.addEventListener('contextmenu',e=>e.preventDefault());
async function powerScene(T){const F=cur();PW.lastStage=0;await say(POWER[F.key][0]);if(T!==tok)return;
if(hearing())earShow(true,'Your turn!');hb.classList.remove('disabled');PW.active=true;PW.idle=0;
const t0=Date.now();let nudged=0;
const done=new Promise(r=>PW.done=r);
while(T===tok&&PW.active){await wait(250);if(PW.idle>7&&nudged<2&&!speaking){nudged++;PW.idle=0;say(TURN[F.key])}
if(Date.now()-t0>30000){PW.prog=1}}
await done;if(T!==tok)return;earShow(false);hb.classList.add('disabled');
if(F.game==='balloon'){const b=$('#field .balloon');if(b)b.animate([{transform:b.style.transform},{transform:'translate(-50%,-260%) scale(1.2)'}],{duration:1600,fill:'forwards'})}
surprise();await cheer(T,$('#field .chwrap'),POWER[F.key][1],F.key);if(T!==tok)return;await wait(400);sceneDone(T)}
/* ---------- 4. WHO SAID IT? (tap the friend whose sound you hear) ---------- */
let whoPick=null;
function prepWho(){$('#whoRow').innerHTML='';$('#whoProg').textContent=''}
async function whoScene(T){const act_=active(),pool=act_.length>=3?act_:[...new Set([...act_,...shuffle(['th','f','v','s'])])].slice(0,3);
const friends=shuffle(pool.slice());$('#whoRow').innerHTML=friends.map(k=>`<button class="whoBtn" data-k="${k}">${charHTML(k)}<b>${SQUAD[k].name}</b></button>`).join('');
$$('.whoBtn').forEach(b=>b.onclick=()=>{if(whoPick){const f=whoPick;whoPick=null;f(b.dataset.k)}});
await say('Who said it? Listen, and tap the friend whose sound you hear.');if(T!==tok)return;
const order=shuffle(act_.slice());
for(let r=0;r<3;r++){$('#whoProg').textContent='⭐'.repeat(r)+'🔊'.repeat(3-r);const k=order[r%order.length];const[w]=pick(SQUAD[k].words);
const play=()=>say(w,{pre:'w:',caption:'👂 Listen…'});$('#whoSpk').onclick=()=>{sfx.tap();play()};
await wait(400);await play();if(T!==tok)return;let tries=0;
while(true){const got=await new Promise(res=>whoPick=res);if(T!==tok)return;
if(got===k)break;tries++;const b=$(`.whoBtn[data-k="${got}"]`);b.classList.add('nope');setTimeout(()=>b.classList.remove('nope'),700);
if(tries>=2){$(`.whoBtn[data-k="${k}"]`).classList.add('hint')}await say('Listen again.');if(T!==tok)return;await play();if(T!==tok)return}
const wb=$(`.whoBtn[data-k="${k}"]`);wb.classList.remove('hint');act(wb.querySelector('.chwrap'),true);await cheer(T,wb.querySelector('.chwrap'),FOUND[k],k);act(wb.querySelector('.chwrap'),false);if(T!==tok)return}
$('#whoProg').textContent='⭐⭐⭐';await wait(300);sceneDone(T)}
/* ---------- 5. FEED THE FRIEND (say the words) ---------- */
let feedMouth;
function hl(w,k){const re={th:/th/i,f:/f/i,v:/v/i,s:/s/i}[k];return w.replace(re,m=>`<span class="hl">${m}</span>`)}
function prepFeed(){const F=cur();$('#feedCh').innerHTML=charHTML(F.key,'big');$('#food').textContent='';$('#foodWord').innerHTML='';$('#feedCtl').innerHTML='';feedMouth.set('rest')}
async function feedScene(T){const F=cur(),ch=$('#feedCh .chwrap');const words=shuffle(F.words.slice()).slice(0,3);
await say(FEED[F.key]);if(T!==tok)return;
for(const[w,e,kind]of words){const fd=$('#food');fd.textContent=e;fd.className='popIn';$('#foodWord').innerHTML=hl(w,F.key);feedMouth.set('rest');
await say(pick(NEXTWORD));if(T!==tok)return;await wait(400);feedMouth.set(F.pose);await say(w,{pre:'w:'});if(T!==tok)return;await wait(500);
let ok=false;
for(let tries=0,quiet=0,redo=0;tries<2;){
let res;
if(hearing()){await say(`Your turn! Say: ${w}.`);if(T!==tok)return;const x=await listenTake(T);if(T!==tok)return;res=judge(F,SoundEar.analyze(x,AC.sampleRate,kind).verdict);
if(x.early&&res!=='yes'&&!redo){redo=1;continue}// he started before the listening did: just ask again
if(res!=='yes'){let ovPressed=false;override().then(v=>{ovPressed=v});
if(res==='quiet'&&quiet<1){quiet++;await say(TIP.quiet);if(T!==tok)return;if(ovPressed)res='yes';else continue}
else if(tries===0){const tip=TIP[F.key+'_'+res];if(tip){popFriendFor(res);await say(tip)}else await say('Ooh, nice try!');if(T!==tok)return;if(ovPressed)res='yes'}
else{await wait(1800);if(T!==tok)return;if(ovPressed)res='yes'}}}
else{if(!await yourTurnNoMic(T,`Your turn! Say: ${w}.`))return;res=await choose($('#feedCtl'),[['👍 Said it!','yes','green big'],['🔁 Again','again']]);if(T!==tok)return}
if(res==='yes'){ok=true;break}
tries++;if(tries<2){feedMouth.set(F.rest);await say('Let’s do it together, slowly.');if(T!==tok)return;feedMouth.set(F.pose);await say(w,{pre:'slow:'});if(T!==tok)return;await wait(400)}}
// eat it either way: effort always wins
const r=fd.getBoundingClientRect(),c=ch.getBoundingClientRect();const fly=fd.cloneNode(true);fly.className='flyFood';fly.style.left=(r.left+r.width/2)+'px';fly.style.top=(r.top+r.height/2)+'px';document.body.appendChild(fly);fd.textContent='';
const a=fly.animate([{left:fly.style.left,top:fly.style.top,transform:'translate(-50%,-50%) scale(1)'},{left:(c.left+c.width/2)+'px',top:(c.top+c.height*.62)+'px',transform:'translate(-50%,-50%) scale(.2)'}],{duration:700,easing:'ease-in',fill:'forwards'});
await a.finished.catch(()=>{});fly.remove();sfx.chomp();act(ch,true);
if(ok){confetti(140);burst();sfx.kazoo();addStar();hop(ch);await fsay(F.key,'yum',ch)}else{hop(ch);addStar();await say(`Great trying${nm()}!`);if(T!==tok)return;await fsay(F.key,'yum',ch)}
act(ch,false);if(T!==tok)return;await wait(500)}
sceneDone(T)}
/* ---------- 6. PRIZE: a costume, a dance party and a joke ---------- */
const JOKES=[['What do you call a sleeping dinosaur?','A dino-snore!','🦕'],['What do you call a snake that builds houses?','A boa constructor!','🐍'],['What does a race car eat?','Fast food!','🍔'],
['What is a puppy’s favorite snack?','Pup-corn!','🍿'],['Knock knock! Who’s there? Lettuce.','Lettuce who? Lettuce play some more!','🥬'],['Where do dogs park their cars?','In the barking lot!','🚗']];
function prepPrize(){const b=$('#box');b.textContent='🎁';b.className='';b.style.display='';$('#prizeCh').innerHTML='';$('#prizeName').textContent='';$('#jokeBox').textContent=''}
async function prizeScene(T){const F=cur(),b=$('#box');b.className='shake';const tapped=new Promise(r=>{b.onclick=()=>{b.onclick=null;stopVoice();r()}});
say('Prize time! Tap the present!');await tapped;if(T!==tok)return;
const[cname,cicon]=COSTUMES[J.costume%COSTUMES.length];J.costume++;J.lastCostume=Object.assign({},J.lastCostume||{},{[F.key]:cname});saveJ();
sfx.fanfare();b.style.display='none';$('#prizeCh').innerHTML=charHTML(F.key,'big popOut');const ch=$('#prizeCh .chwrap');dress(ch,cname);confetti(180);
$('#prizeName').textContent=cicon+' '+cname+' '+F.name+' '+cicon;state.stickers.push([F.key,cname]);store.set('stickers',state.stickers);addStar();
await say(`Ta-da! It’s ${cname} ${F.name}!`);if(T!==tok)return;await fsay(F.key,'yay',ch);if(T!==tok)return;await wait(700);
await partyRun(T,16,true);if(T!==tok)return;await wait(400);
const[q,ans,em]=JOKES[J.joke%JOKES.length];J.joke++;saveJ();
await say('Ready for a joke?');if(T!==tok)return;await wait(600);$('#jokeBox').textContent='🤔';await say(q);if(T!==tok)return;sfx.drum();await wait(1500);if(T!==tok)return;
$('#jokeBox').textContent=em;$('#jokeBox').classList.remove('popIn');void $('#jokeBox').offsetWidth;$('#jokeBox').classList.add('popIn');
await say(ans);if(T!==tok)return;sfx.rimshot();hop(ch);await wait(400);await say('Hee hee hee!');if(T!==tok)return;await wait(700);
await fsay(F.key,'bye',ch);if(T!==tok)return;await say(`Bye bye, ${F.name}! Who’s next?`);if(T!==tok)return;sceneDone(T)}
/* ---------- SILLY BUTTON and the giant puppy ---------- */
async function silly(){sfx.tap();const r=Math.random(),chs=$$('.screen.on .chwrap');if(r<.3){bigRise(true);return}
if(r<.55){sfx.toot();chs.forEach(c=>{hop(c);trick(c)});if(!speaking)say('Oops! Was that a toot? Hee hee!');return}
if(r<.8){visitor();chs.forEach(trick);return}
sfx.kazoo();burst();confetti(80);chs.forEach(trick);if(!speaking)say('Beep, beep! Coming through!')}
/* ---------- HOME ---------- */
let greeted=false;
function homeScene(){newTok();show('home');$('#homeRow').innerHTML=['th','f','v','s'].map(k=>charHTML(k,'homeCh')).join('');
$('#shelf').innerHTML=state.stickers.length?'<b>Sticker book:</b>'+state.stickers.slice(-14).map(([k,c])=>`<span title="${c} ${SQUAD[k].name}">${SQUAD[k].icon}${HATS[c]||''}</span>`).join(''):'';
say(greeted?`Tap play${nm()}!`:`Hi${state.name?' '+state.name:''}! Meet the Silly Sound Squad! Tap the big play button!`);greeted=true}
const SCENES={reveal:revealScene,mirror:mirrorScene,power:powerScene,who:whoScene,feed:feedScene,prize:prizeScene};
const PREP={reveal:prepReveal,mirror:prepMirror,power:prepPower,who:prepWho,feed:prepFeed,prize:prepPrize};
/* Every line the game can say (the recording script reads this). */
function allLines(n){const L=[];const add=(t,pre='')=>L.push([t,pre]);
Object.values(SQUAD).forEach(F=>{F.steps.forEach(s=>add(s[1]));F.words.forEach(([w])=>{add(w,'w:');add(w,'slow:');add(`Your turn! Say: ${w}.`)});add(INTRO[F.key]);add(TURN[F.key]);add(YAY[F.key]);POWER[F.key].forEach(x=>add(x));add(FEED[F.key]);add(FOUND[F.key]);
COSTUMES.forEach(c=>add(`Ta-da! It’s ${c[0]} ${F.name}!`));add(`Bye bye, ${F.name}! Who’s next?`)});
Object.values(TIP).forEach(x=>add(x));NEXTWORD.forEach(x=>add(x));
JOKES.forEach(j=>{add(j[0]);add(j[1])});Object.entries(FRIEND).forEach(([k,o])=>Object.values(o).flat().forEach(t=>add(t,'v_'+k+':')));MOVES.forEach(m=>{if(m[1])add(m[1])});
['Knock, knock! Who is coming to play today? Tap the door!','Who said it? Listen, and tap the friend whose sound you hear.','Listen again.','Let’s do it together, slowly.','Ooh, nice try!',
'Prize time! Tap the present!','Ready for a joke?','Hee hee hee!','Oops! Was that a toot? Hee hee!','Beep, beep! Coming through!','Peekaboo! I see you!','Squad dance party! Dance with your friends!','Freeze!','Dance!',
`Great dancing, ${n}!`,`Yes! Good job, ${n}!`,`Great trying, ${n}!`,`Tap play, ${n}!`,`Hi ${n}! Meet the Silly Sound Squad! Tap the big play button!`].forEach(x=>add(x));
return L}
/* ---------- SILLY EXTRAS: friend voices, googly eyes, tap tricks, visitors, comic bursts ---------- */
// Each friend talks in its own cartoon voice (clips keyed "v_<friend>:<line>"). No friend line uses a practice sound
// except where a checked word is spliced in, so the voices are silly without modelling a sound wrong.
const FRIEND={
th:{hi:'Woof woof! Hi hi hi! Wanna play with me?',tickle:['Hee hee hee! That tickles!','Woof! Do it again!'],yay:['Woof! You did it! Yippee!','Woof woof! Hooray!'],yum:['Yum yum yum! Woof!','Burp! Oops! Woof!'],bye:'Bye bye! Woof woof!',dance:'Woof woof! Dance with me!'},
f:{hi:'Hop hop hop! Hello! Let’s play!',tickle:['Hee hee! Bunny giggles!','Hop hop! Hee hee!'],yay:['Yay! You did it! Hop hop!','Yippee! You did it!'],yum:['Crunchy munchy! Yum!','Nom nom nom! Yummy!'],bye:'Bye bye! Hop hop!',dance:'Hop hop! Dance with me!'},
v:{hi:'Beep beep! Ready, set, go!',tickle:['Beep! Hee hee! That tickles!','Beep beep beep! Hee hee!'],yay:['Beep beep! You’re a superstar!','Yay! Beep beep! You did it!'],yum:['Glug glug glug! Yummy!','Yummy! Burp! Beep beep!'],bye:'Beep beep! Bye bye!',dance:'Beep beep! Dance with me!'},
s:{hi:'Hiss hiss! Hello, hello! I’m so happy!',tickle:['Hee hee! Wiggle wiggle!','Hee hee hee! That tickles!'],yay:['Yes yes yes! You did it!','Yay! Wiggle wiggle!'],yum:['Slurp! Yummy yummy!','Slurp slurp! Yum!'],bye:'Bye bye! Hiss hiss!',dance:'Wiggle wiggle! Dance with me!'}};
const fline=(k,kind)=>{const v=FRIEND[k][kind];return Array.isArray(v)?pick(v):v};
function fsay(k,kind,el){const t=fline(k,kind);if(el){act(el,true);trick(el)}const p=say(t,{pre:'v_'+k+':'});if(el)p.then(()=>act(el,false));return p}
// Tap any friend: a giggle and a random trick (never while the game is listening).
const TRICKS=['r-spin','r-jelly','r-flip','r-boing','r-eyes','r-squish'];
function trick(el){if(!el)return;TRICKS.forEach(c=>el.classList.remove(c));void el.offsetWidth;const c=pick(TRICKS);el.classList.add(c);setTimeout(()=>el.classList.remove(c),900)}
document.addEventListener('click',e=>{const el=e.target.closest('.chwrap');if(!el||e.target.closest('.whoBtn'))return;const k=el.dataset.ch;
if(!k)return;pick([sfx.boing2,sfx.slideUp,sfx.pop])();trick(el);if(!speaking&&!mic.rec&&!PW.active&&!$('#ear').classList.contains('on'))fsay(k,'tickle',el)});
// Googly eyes follow the finger or mouse.
function lookAt(x,y){const r=document.documentElement;r.style.setProperty('--ex',(((x/innerWidth)-.5)*7).toFixed(2)+'px');r.style.setProperty('--ey',(((y/innerHeight)-.5)*6).toFixed(2)+'px')}
['pointermove','pointerdown'].forEach(ev=>addEventListener(ev,e=>lookAt(e.clientX,e.clientY),{passive:true}));
setInterval(()=>{if(Math.random()<.5)lookAt(Math.random()*innerWidth,Math.random()*innerHeight)},2600);
// Comic burst words on every win.
const BURSTS=['WOW!','YAY!','SUPER!','BOOM!','WOO-HOO!','YES!','KA-POW!'];
function burst(){const b=document.createElement('div');b.className='burst';b.textContent=pick(BURSTS);b.style.left=(25+Math.random()*50)+'vw';b.style.top=(28+Math.random()*25)+'vh';b.style.setProperty('--r',(Math.random()*24-12).toFixed(0)+'deg');document.body.appendChild(b);setTimeout(()=>b.remove(),1300)}
// Silly visitors wander across now and then.
const VISITORS=[['🐄🎈','rise'],['🐔','run'],['🦆','run'],['🛸','fly'],['🐸','leap'],['🦕','run'],['🐷🎈','rise'],['🐒','leap'],['🦒','run'],['🍕','fly'],['🐳','swim'],['🦄','fly']];
function visitor(){if($('#party').classList.contains('on')||mic.rec||$('#ear').classList.contains('on')||$('#start'))return;const[e,a]=pick(VISITORS);floater(e,a);pick([sfx.slideUp,sfx.boing2,sfx.honk2])()}
setInterval(()=>{if(Math.random()<.55)visitor()},14000);
/* ---------- WIRING ---------- */
mirrorMouth=makeMouth($('#mirrorMouth'));feedMouth=makeMouth($('#feedMouth'));
$('#starN').textContent=state.stars;
$('#startRow').innerHTML=['th','f','v','s'].map(k=>charHTML(k)).join('');
setInterval(()=>{if($('#s-home').classList.contains('on')&&!speaking&&!$('#party').classList.contains('on'))bigRise(false)},16000);
$('#playBtn').onclick=()=>{sfx.tap();journeyGo()};
$('#homeBtn').onclick=()=>{sfx.tap();homeScene()};
$('#sillyBtn').onclick=silly;
$('#musicBtn').onclick=()=>{setMusic(!state.music);store.set('music',state.music)};
$('#fsBtn').onclick=()=>{const el=document.documentElement;try{if(document.fullscreenElement||document.webkitFullscreenElement){(document.exitFullscreen||document.webkitExitFullscreen).call(document)}else{const f=el.requestFullscreen||el.webkitRequestFullscreen;const p=f&&f.call(el);if(p&&p.catch)p.catch(()=>{})}}catch(e){}};
function micText(){const m={on:'🎤 The friends can hear him.',off:'Microphone is off. You tap “He did it” instead.',denied:'The microphone was blocked. Allow it in the browser settings, then reload. Until then you tap instead.',unsupported:'This browser cannot share the microphone here. You tap instead.'};$('#micState').textContent=m[mic.state]||''}
$('#grownBtn').onclick=()=>{$('#nameIn').value=state.name;fillVoiceSel();$$('#soundPick input').forEach(c=>c.checked=state.sounds.includes(c.value));$('#micIn').checked=state.micWanted;micText();$('#grown').classList.add('on')};
$('#micIn').onchange=async()=>{state.micWanted=$('#micIn').checked;store.set('mic',state.micWanted);if(state.micWanted){initAudio();await micStart()}else micStop();micText()};
$('#closeGrown').onclick=()=>{const n=$('#nameIn').value.trim();if(n){state.name=n;store.set('name',n)}const v=$('#voiceSel').value;const vv=enVoices().find(x=>x.name===v);if(vv){voice=vv;state.voiceName=v;store.set('voice',v)}
const s=$$('#soundPick input').filter(c=>c.checked).map(c=>c.value);const changed=s.join()!==state.sounds.join();state.sounds=s.length?s:['th','f','v','s'];store.set('sounds',state.sounds);
$('#grown').classList.remove('on');if(changed){J.station=0;saveJ();homeScene()}};
$('#resetBtn').onclick=()=>{state.stars=0;state.stickers=[];Object.assign(J,{round:0,station:0,joke:0,costume:0,lastCostume:{}});saveJ();store.set('stars',0);store.set('stickers',[]);$('#starN').textContent=0;$('#grown').classList.remove('on');homeScene()};
$('#startBtn').onclick=async()=>{const b=$('#startBtn');if(b.disabled)return;b.disabled=true;initAudio();preloadClips();pickVoice();if(state.micWanted)await micStart();$('#start').remove();setMusic(state.music);homeScene()};
</script>
</body>
</html>
kit/make.py (splits the source into index.html, sounds.css, sounds.js)28 lines
# Builds the page as separate files (no inline code): index.html, sounds.css, sounds.js.
# usage: python3 make.py <outdir> [--site]
import re, sys, os, shutil
out=sys.argv[1]; site='--site' in sys.argv
s=open('index.src.txt').read()
css=re.search(r'<style>\n?(.*?)</style>',s,re.S).group(1)
js=re.search(r'<script>\n?(.*?)</script>',s,re.S).group(1).replace('__CLIPS__',open('manifest.json').read().strip())
html=s.replace(re.search(r'<style>.*?</style>',s,re.S).group(0),'<link rel="preload" href="./fonts/fredoka-600.woff2" as="font" type="font/woff2" crossorigin>\n<link rel="stylesheet" href="./sounds.css">')
html=html.replace(re.search(r'<script>.*?</script>',html,re.S).group(0),'<script src="./sounds.js"></script>')
meta='''<meta name="description" content="A silly speech-practice game for little kids: four friends teach TH, F, V and S, the game listens through the microphone and cheers every try, with costumes, a dance party and jokes.">
<meta name="theme-color" content="#8fd8ff">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Sound Squad">
'''
if site:
meta+='<link rel="icon" href="./icon-192.png" type="image/png">\n<link rel="apple-touch-icon" href="./icon-192.png">\n'
html=html.replace('</ul>\n <div class="sheetBtns">','</ul>\n <p class="more"><a href="/">More free tools by Shahrouz Ghadimi</a></p>\n <div class="sheetBtns">',1)
assert 'class="more"' in html
html=html.replace('<title>',meta+'<title>',1)
os.makedirs(out,exist_ok=True)
open(os.path.join(out,'index.html'),'w').write(html)
open(os.path.join(out,'sounds.css'),'w').write(css.strip()+'\n.more{margin:6px 0 14px}.more a{color:#1b6fa8;font-weight:600}\n')
open(os.path.join(out,'sounds.js'),'w').write(js.strip()+'\n')
for d in ('audio','fonts'):
if os.path.exists(os.path.join(out,d)): shutil.rmtree(os.path.join(out,d))
shutil.copytree(d,os.path.join(out,d))
print('built',out,'site' if site else 'preview', len(os.listdir(os.path.join(out,'audio'))),'clips')
kit/words.py (makes and checks every target word and name)27 lines
# Makes and checks every word the narrator models (and the four names).
# A take is kept only when Whisper hears the right word; TH words must also measure as a quiet,
# spread hiss (-34 to -18 dB below the vowel). Then chkwords.cjs runs the game's own listener on
# every take: F and TH words must come out "soft", S words "sharp", V words "voice".
import soundfile as sf, numpy as np, pick
from pick import *
pick.FB.update({"fifi":"fˈifi","vinny":"vˈɪni","sunny":"sˈʌni","fifi's":"fˈifiz","vinny's":"vˈɪniz","sunny's":"sˈʌniz"})
SAME={"six":{"six"},"sun":{"sun","son"},"fifi's":{"feefies","fifis"},"vinny":{"vinny","vinnie"},"vinny's":{"vinnys","vinnies"},"sunny's":{"sunnys","sunnies"}}
def take(w,speeds,tag,pos=None):
ps=ph(w); acc=SAME.get(w,{norm(w)})
for maker in (cand_final,cand_mid):
for sp in speeds:
a=maker(ps,sp); f,e,z=frames(a); pk=e.max(); s=np.where(e>0.02*pk)[0][0]; a=a[max(0,s-2)*f:]
if norm(asr(a).replace("6","six").replace("3","three")) not in acc: continue
if pos:
lv=th_level(a,pos)
if lv is None or not -34<=lv<=-18: continue
sf.write(f"words/{tag}{w}.wav",a,SR); print("OK",tag+w,maker.__name__,sp); return
print("FAIL",tag+w)
import os; os.makedirs("words",exist_ok=True)
TH={"thumb":"initial","three":"initial","think":"initial","thunder":"initial","thunder's":"initial","bath":"final","teeth":"final","mouth":"final"}
PLAIN=["fish","fan","feet","fox","fork","five","van","vase","violin","volcano","sun","sock","soap","soup","six","sandwich"]
for w,pos in TH.items(): take(w,[.88,.84,.92,.8],"w_",pos); take(w,[.76,.72,.8,.84],"slow_",pos)
for w in PLAIN: take(w,[.88,.84,.92,.8],"w_"); take(w,[.76,.72,.8,.84],"slow_")
for w in ["thunder","fifi","fifi's","vinny's","sunny","sunny's"]: take(w,[.92,.96,.88],"n_",TH.get(w)) # quicker takes for running speech
for w in ["fifi","fifi's","vinny","vinny's","sunny","sunny's"]: take(w,[.88,.84,.92,.8],"w_")
kit/chkwords.cjs (runs the listener over every word take)6 lines
require('./listen.js');const fs=require('fs');
function readWav(p){const b=fs.readFileSync(p);let o=12,sr=0,data=null;while(o<b.length){const id=b.toString('ascii',o,o+4),sz=b.readUInt32LE(o+4);if(id==='fmt ')sr=b.readUInt32LE(o+12);if(id==='data')data=b.subarray(o+8,o+8+sz);o+=8+sz+(sz&1)}const n=data.length/2,x=new Float32Array(n);for(let i=0;i<n;i++)x[i]=data.readInt16LE(i*2)/32768;return {x,sr}}
const T={th:['thumb','three','think','thunder'],thF:['bath','teeth','mouth'],f:['fish','fan','feet','fox','fork','five'],v:['van','vase','violin','volcano'],s:['sun','sock','soap','soup','six','sandwich']};
const K={th:'I',thF:'F',f:'I',v:'V',s:'I'},E={th:'soft',thF:'soft',f:'soft',v:'voice',s:'sharp'};
for(const g in T)for(const w of T[g])for(const t of ['w_','slow_']){const p='/tmp/wchk/'+t+w+'.wav';if(!fs.existsSync(p))continue;const {x,sr}=readWav(p);const r=SoundEar.analyze(x,sr,K[g]);console.log(r.verdict===E[g]?'ok ':'MISS',t+w,r.verdict)}
kit/gen_squad.py (builds every line and the clip list)116 lines
import json, subprocess, hashlib, os, re, sys, numpy as np, soundfile as sf
import pick
from pick import K, frames, after_okay, SR, ph, fade, asr, clean_onset_plain
import difflib
from expr import excite
from kokoro_onnx import Kokoro
pick.FB.update({"fifi":"fˈifi","vinny":"vˈɪni","woohoo":"wˌuhˈu","vroom":"vɹˈum","nom":"nˈɑm","pup":"pˈʌp","snore":"snˈɔɹ","dino":"dˈInO","ta":"tə","da":"dˈɑ","mmm":"mˈʌm","woof":"wˈʊf","wanna":"wˈɑnə","boing":"bˈɔɪŋ","munchy":"mˈʌnʧi","glug":"ɡlˈʌɡ","slurp":"slˈɜɹp","yippee":"jˈɪpi","hiss":"hˈɪs","fifi’s":"fˈifiz","fifi's":"fˈifiz","vinny’s":"vˈɪniz","vinny's":"vˈɪniz","sunny’s":"sˈʌniz","sunny's":"sˈʌniz"})
L=json.load(open('/tmp/squad_lines.json'))
def key(t):
t=t.lower().replace("’","'"); t=re.sub(r"[^a-z0-9' ]+"," ",t); return re.sub(r"\s+"," ",t).strip()
gap=lambda s:np.zeros(int(s*SR),np.float32)
def wclip(w,slow=False,mid=False):
w=w.lower()
cands=([f"/tmp/words/n_{w}.wav"] if mid else [])+[f"/tmp/words/{'slow_' if slow else 'w_'}{w}.wav",f"/tmp/words/w_{w}.wav"]
for p in cands:
if os.path.exists(p): a,_=sf.read(p,dtype='float32'); return a
raise SystemExit("no clip "+w)
TARGET=["thunder's","thunder","fifi's","fifi","vinny's","vinny","sunny's","sunny","teeth","mouth","thumb","three","think","bath","fish","fan","feet","fox","fork","five","van","vase","violin","volcano","sun","sock","soap","soup","six","sandwich"]
TRE=re.compile(r"\b("+"|".join(re.escape(w).replace("'","[’']") for w in TARGET)+r")\b",re.I)
_NC={}
def _sc(t,a):
n=lambda x:re.sub(r"[^a-z ]","",x.lower().replace("’","'").replace("'","")).split()
return difflib.SequenceMatcher(None,n(t),n(asr(a))).ratio()
MODE={'calm':(.9,1.7,1.5),'hype':(.97,2.1,2.0)}
CUR=['hype']
CALM=re.compile(r"(Your turn|tongue|teeth|lip|blow|[Ss]mile|hiss out|motor|Listen|[Tt]ap |Say each|Make .*sound|Open wide|Keep your|together|Put them|For (Thunder|Fifi|Vinny|Sunny)|make it long|can’t hear)")
def narr_chunk(t,speed=None):
sp,g,sh=MODE[CUR[0]]
key=(t,CUR[0])
if key in _NC: return _NC[key]
_NC[key]=excite(_narr_raw(t,sp),g,sh)
return _NC[key]
def _narr_raw(t,speed=.9):
a,_=K().create("ˈOkA. "+ph(t),voice="af_heart",speed=speed,is_phonemes=True,trim=False)
a=after_okay(a); f,e,z=frames(a); pk=e.max(); idx=np.where(e>0.01*pk)[0]
c1=fade(a[max(0,idx[0]-1)*f:min(len(a),(idx[-1]+6)*f)],25)
b,_=K().create(ph(t),voice="af_heart",speed=speed,is_phonemes=True,trim=False)
c2=fade(clean_onset_plain(b),25)
s1,s2=_sc(t,c1),_sc(t,c2)
return c1 if s1>=s2 else c2
def sentence(p):
"""One sentence: Kokoro for the words around, verified clips for the target sounds."""
out=[];pos=0;ms=list(TRE.finditer(p))
for i,m in enumerate(ms):
before=p[pos:m.start()].strip()
if re.search(r"[A-Za-z]",before):
out.append(narr_chunk(before)); out.append(gap(.12 if before[-1] not in ",.!?:" else .3))
w=m.group(1).lower().replace("’","'")
nxt=p[m.end():].strip()
out.append(wclip(w,mid=bool(re.match(r"[a-z]",nxt))))
pos=m.end()
rest=p[pos:].lstrip()
if re.search(r"[A-Za-z]",rest): out.append(gap(.35 if rest[:1] in ",.!?:" else .1))
pos=m.end()
# drop punctuation right after the word
mm=re.match(r"\s*[,.!?:]+",p[pos:]);
if mm: pos+=mm.end()
tail=p[pos:].strip()
if re.search(r"[A-Za-z]",tail): out.append(narr_chunk(tail))
return np.concatenate(out)
def narr(t):
parts=[p.strip() for p in re.findall(r'[^.!?:]+[.!?:]*',t) if p.strip()]
out=[]
for i,p in enumerate(parts):
out.append(sentence(p))
if i<len(parts)-1:
short=len(p.split())<=2 or len(parts[i+1].split())<=2
out.append(gap(1.0 if short else .6))
return np.concatenate(out)
VOICE={'th':('af_kore',1.0,1.8,6,1.15),'f':('af_jessica',1.0,1.6,9,1.22),'v':('am_liam',1.1,1.8,4,1.1),'s':('af_sky',.92,2.2,2,1.05)}
def friend(text,k):
"""Cartoon voice for a friend: tries several takes and strengths and keeps the one Whisper understands best."""
v,sp,g,sh,fm=VOICE[k]; best=None
for strength in (1.0,.7,.45):
for s2 in (sp,sp*.95):
for carrier in (False,True):
if carrier:
a,_=K().create("ˈOkA. "+ph(text),voice=v,speed=s2,is_phonemes=True,trim=False); a=pick.after_gap(a)
else:
a,_=K().create(ph(text),voice=v,speed=s2,is_phonemes=True,trim=False)
a=fade(clean_onset_plain(a),25)
y=excite(a,1+(g-1)*strength,sh*strength,formant=1+(fm-1)*strength); sc=_sc(text,y)
if best is None or sc>best[0]+.05: best=(sc,y,strength)
if sc>=.85: return y
if best[0]>=.7: break
print(' friend best',round(best[0],2),'strength',best[2],text,flush=True)
return best[1]
def build(text,pre):
if pre in("w:","slow:"): return wclip(text,pre=="slow:")
if pre.startswith("v_"): return friend(text,pre[2:-1])
CUR[0]='calm' if CALM.search(text) else 'hype'
m=re.fullmatch(r"Your turn! Say: (.+)\.",text)
if m: return np.concatenate([narr("Your turn! Say:"),gap(.35),wclip(m.group(1))])
return narr(text)
out=sys.argv[1]; os.makedirs(out,exist_ok=True)
if not os.environ.get('ONLY'):
for f in os.listdir(out):
if f!="silence.mp3": os.remove(os.path.join(out,f))
os.makedirs("/tmp/sqclips",exist_ok=True)
man={};log={}
ONLY=os.environ.get('ONLY')
if ONLY: man=json.load(open(sys.argv[2])); log=json.load(open('/tmp/sqcliplog.json'))
for text,pre in L:
kk=pre+key(text)
if ONLY and not pre.startswith(ONLY): continue
if kk in man and not ONLY: continue
a=np.concatenate([gap(.04),build(text,pre),gap(.05)]).astype(np.float32)
a=a/max(1e-6,np.abs(a).max())*0.89
fn=hashlib.md5(kk.encode()).hexdigest()[:10]
wav=f"/tmp/sqclips/{fn}.wav"; sf.write(wav,a,SR)
subprocess.run(["ffmpeg","-y","-loglevel","error","-i",wav,"-ac","1","-b:a","64k",f"{out}/{fn}.mp3"],check=True)
man[kk]=fn+".mp3"; log[kk]=(text,wav)
print(len(man),text[:70],flush=True)
json.dump(man,open(sys.argv[2],"w")); json.dump(log,open("/tmp/sqcliplog.json","w"))
print("clips",len(man))
kit/expr.py (makes the narrator excited and the friends' cartoon voices)24 lines
import numpy as np, pyworld as pw, soundfile as sf
SR=24000
def f0stats(a):
x=a.astype(np.float64); f0,t=pw.harvest(x,SR,f0_floor=80,f0_ceil=700,frame_period=5)
v=f0[f0>0]; st=12*np.log2(v/np.median(v))
return float(np.median(v)), float(st.std()), float(np.percentile(st,95)-np.percentile(st,5))
def excite(a,gain=1.6,shift=2.0,tempo=1.0,formant=1.0):
"""Exaggerate the melody (gain x the pitch swings), raise it (shift semitones), optional formant scale (>1 = smaller, cartoon)."""
x=a.astype(np.float64)
f0,t=pw.harvest(x,SR,f0_floor=80,f0_ceil=700,frame_period=5)
sp=pw.cheaptrick(x,f0,t,SR); ap=pw.d4c(x,f0,t,SR)
v=f0>0; lf=np.log2(np.where(v,f0,1)); m=np.median(lf[v])
# smooth a bit so exaggeration does not amplify jitter
lf2=lf.copy(); lf2[v]=m+gain*(lf[v]-m)+shift/12
f0n=np.where(v,2**lf2,0)
if formant!=1.0:
n=sp.shape[1]; idx=np.clip(np.arange(n)/formant,0,n-1)
sp=np.array([np.interp(idx,np.arange(n),r) for r in sp])
if tempo!=1.0:
k=np.arange(0,len(f0n),tempo); i=np.minimum(np.round(k).astype(int),len(f0n)-1)
f0n,sp,ap=f0n[i],sp[i],ap[i]
y=pw.synthesize(np.ascontiguousarray(f0n),np.ascontiguousarray(sp),np.ascontiguousarray(ap),SR,frame_period=5)
return (y/np.abs(y).max()*0.89).astype(np.float32)
kit/pick.py (phonemes, takes, Whisper and the TH measure)93 lines
import numpy as np, re, json, sherpa_onnx, soundfile as sf
from thfix import K, frames, after_gap, SR, fix
from misaki import en
d="sherpa-onnx-whisper-base.en/"
rec=sherpa_onnx.OfflineRecognizer.from_whisper(encoder=d+"base.en-encoder.onnx",decoder=d+"base.en-decoder.onnx",tokens=d+"base.en-tokens.txt")
def asr(a):
p=np.zeros(int(.3*SR),np.float32);s=rec.create_stream();s.accept_waveform(SR,np.concatenate([p,a,p]));rec.decode_stream(s);return s.result.text.strip()
norm=lambda t:re.sub(r"[^a-z ]","",t.lower().replace("3","three")).strip()
FB={"theo":"θˈiO","hee":"hˈi","buzzy":"bˈʌzi","fum":"fˈʌm"}
MISS=[]
def fb(tok):
p=FB.get(tok.text.lower())
if p is None: MISS.append(tok.text)
return (p or "",1)
g2p=en.G2P(trf=False,british=False,fallback=fb)
WRONG={"fumb":"fˈʌm","free":"fɹˈi","fink":"fˈɪŋk","baf":"bˈæf","mouf":"mˈWf","dis":"dˈɪs","dat":"dˈæt","mudder":"mˈʌdəɹ","fum":"fˈʌm"}
def ph(t):
if t.lower() in WRONG: return WRONG[t.lower()]
MISS.clear(); p,_=g2p(t)
if MISS: raise SystemExit(f"OOV {t}: {MISS}")
return p
def fade(x,ms=30):
n=min(len(x),int(ms/1000*SR)); x=x.copy(); x[len(x)-n:]*=np.linspace(1,0,n); return x
def cand_final(ps,sp): # word last in utterance
a,_=K().create("ˈOkA. "+ps+".",voice="af_heart",speed=sp,is_phonemes=True,trim=False); return after_gap(a)
def cand_mid(ps,sp): # word mid-phrase, cut after its last consonant
a,_=K().create("ˈOkA. "+ps+", ˈOkA.",voice="af_heart",speed=sp,is_phonemes=True,trim=False)
a=after_gap(a); f,e,z=frames(a); pk=e.max()
voiced=(e>0.1*pk)&(z<0.2)
v=np.where(voiced)[0]; i=v[0]
while i+1<len(e) and voiced[i+1]: i+=1
# skip the word's own trailing consonants: walk while not (2 consecutive voiced frames) and not long silence
j=i+1; quiet=0
while j+1<len(e):
if voiced[j] and voiced[j+1]: break
quiet=quiet+1 if e[j]<0.01*pk else 0
if quiet>=3: break
j+=1
return np.concatenate([fade(a[:j*f]),np.zeros(int(.08*SR),np.float32)])
def th_level(a,pos):
f,e,z=frames(a); pk=e.max(); v=np.where((e>0.15*pk)&(z<0.15))[0]
if not len(v): return None
seg=e[:v[0]] if pos=='initial' else e[v[-1]+1:]
zz=z[:v[0]] if pos=='initial' else z[v[-1]+1:]
fr=seg[(zz>0.25)&(seg>0.005*pk)]
if len(fr)<3: return None
return 20*np.log10(fr.mean()/pk)
def best_word(w,pos,speeds,wrong=False):
ps=ph(w); tried=[]
for maker in (cand_final,cand_mid):
for sp in speeds:
a=maker(ps,sp)
# trim leading silence
f,e,z=frames(a); pk=e.max(); s=np.where(e>0.02*pk)[0][0]; a=a[max(0,s-2)*f:]
h=asr(a); ok=norm(h)==norm(w) or (w=="three" and norm(h) in("three",))
lv=th_level(a,pos) if pos else None
thok=True if not pos else (lv is not None and -34<=lv<=-18)
tried.append((maker.__name__,sp,h,None if lv is None else round(float(lv),1)))
if (ok or wrong) and thok: return a,tried[-1],True
# fallback: splice a correct TH into the best ASR-correct candidate
for maker in (cand_final,cand_mid):
for sp in speeds:
a=fix(maker(ps,sp),pos) if pos else maker(ps,sp)
h=asr(a)
if norm(h)==norm(w) or wrong: return a,(maker.__name__+"+splice",sp,h,th_level(a,pos) if pos else None),True
return None,tried,False
_OK={}
def okay_len(speed=.9):
if speed not in _OK:
a,_=K().create("ˈOkA.",voice="af_heart",speed=speed,is_phonemes=True,trim=False)
f,e,z=frames(a); pk=e.max(); act=np.where(e>0.02*pk)[0]; _OK[speed]=act[-1]-act[0]+1
return _OK[speed]
def after_okay(a,speed=.9):
f,e,z=frames(a); pk=e.max()
i=np.where(e>0.02*pk)[0][0]; L=okay_len(speed)
lo=i+int(L*.8); hi=min(len(e)-1,i+int(L*1.6))
k=lo+int(np.argmin(e[lo:hi])) # quietest point just after "Okay"
while k+1<len(e) and e[k+1]<0.03*pk: k+=1
return a[max(0,k-1)*f:]
def boost_initial(a,target=-24.0):
f,e,z=frames(a); pk=e.max(); v=np.where((e>0.15*pk)&(z<0.15))[0][0]
fr=e[:v][(z[:v]>0.25)&(e[:v]>0.005*pk)]
if len(fr)<3: return a
lv=20*np.log10(fr.mean()/pk)
if lv>=target: return a
g=10**((target-lv)/20); b=a.copy(); n=v*f; xf=int(.01*SR)
ramp=np.ones(n); ramp[-xf:]=np.linspace(g,1,xf)/g
b[:n]*=g*ramp; return b
def clean_onset_plain(a):
f,e,z=frames(a); pk=e.max(); idx=np.where(e>0.01*pk)[0]
return a[max(0,idx[0]-1)*f:min(len(a),(idx[-1]+6)*f)]
kit/thfix.py (cuts and the synthesized TH)68 lines
import numpy as np
from kokoro_onnx import Kokoro
_k=None
def K():
global _k
if _k is None: _k=Kokoro("kokoro-v1.0.onnx","voices-v1.0.bin")
return _k
SR=24000
def frames(a,ms=10):
f=int(SR*ms/1000); n=len(a)//f
fr=a[:n*f].reshape(n,f)
e=np.sqrt((fr**2).mean(1)); z=(np.abs(np.diff(np.sign(fr),axis=1))>0).mean(1)
return f,e,z
def clean_onset(a):
f,e,z=frames(a); pk=e.max(); act=e>0.03*pk
idx=np.where(act)[0]
# split into blobs separated by >=5 silent frames; drop tiny leading blobs
blobs=[];s=idx[0];p=idx[0]
for i in idx[1:]:
if i-p>5: blobs.append((s,p));s=i
p=i
blobs.append((s,p))
while len(blobs)>1 and (blobs[0][1]-blobs[0][0])<12 and e[blobs[0][0]:blobs[0][1]+1].max()<0.5*pk: blobs.pop(0)
st=max(0,blobs[0][0]-2)*f; en=min(len(a),(blobs[-1][1]+4)*f)
return a[st:en]
def th_noise(dur,level,rng=np.random.default_rng(7)):
n=int(SR*dur); x=rng.standard_normal(n+2048)
X=np.fft.rfft(x); fq=np.fft.rfftfreq(len(x),1/SR)
H=np.clip((fq-1200)/600,0,1)*np.clip((11000-fq)/2000,0,1)
y=np.fft.irfft(X*H)[:n]; y/=np.sqrt((y**2).mean())
env=np.ones(n);a=int(.03*SR);r=int(.06*SR)
env[:a]=np.sin(np.linspace(0,np.pi/2,a))**2; env[-r:]=np.cos(np.linspace(0,np.pi/2,r))**2
return (y*env*level).astype(np.float32)
def voiced_bounds(a):
f,e,z=frames(a); pk=e.max()
v=np.where((e>0.15*pk)&(z<0.15))[0]
return f,e,v[0],v[-1],e[v].mean()
def fix(a,pos,db=-22.0):
a=clean_onset(a)
if pos is None: return a
f,e,v0,v1,vr=voiced_bounds(a); lvl=vr*10**(db/20); xf=int(.012*SR)
if pos=='initial':
body=a[max(0,v0-1)*f:].copy(); th=th_noise(.15,lvl)
ramp=np.linspace(0,1,xf); body[:xf]*=ramp
out=np.concatenate([th[:-xf],th[-xf:]*ramp[::-1]+body[:xf],body[xf:]])
else:
body=a[:(v1+2)*f].copy(); body[-xf:]*=np.linspace(1,0,xf)
th=th_noise(.22,lvl); out=np.concatenate([body[:-xf],body[-xf:]+th[:xf]*np.linspace(0,1,xf),th[xf:],np.zeros(int(.08*SR),np.float32)])
return out.astype(np.float32)
def word(ps,speed=.88,pos=None):
a,sr=K().create(ps,voice="af_heart",speed=speed,is_phonemes=True,trim=False)
return fix(a,pos)
def after_gap(a):
f,e,z=frames(a); pk=e.max(); sil=e<0.01*pk
best=(0,0);i=0
while i<len(sil):
if sil[i]:
j=i
while j<len(sil) and sil[j]: j+=1
if i>5 and j<len(sil)-5 and j-i>best[1]-best[0]: best=(i,j)
i=j
else: i+=1
return a[max(0,best[1]-1)*f:]
def word2(ps,speed=.88,pos=None,db=-22.0):
a,_=K().create("ˈOkA. "+ps+".",voice="af_heart",speed=speed,is_phonemes=True,trim=False)
a=after_gap(a)
return fix(a,pos,db)
kit/readback.py (reads every clip back with Whisper)13 lines
import json,re,difflib,soundfile as sf
from pick import asr
log=json.load(open('/tmp/sqcliplog.json'))
n=lambda x:re.sub(r"[^a-z ]","",x.lower().replace("’","").replace("'","").replace("-"," ").replace("6","six").replace("3","three").replace("5","five")).split()
res=[]
for k,(t,w) in log.items():
if k.startswith(('w:','slow:')): continue
a,sr=sf.read(w,dtype='float32'); h=asr(a)
r=difflib.SequenceMatcher(None,n(t),n(h)).ratio(); res.append((r,t,h))
res.sort()
for r,t,h in res[:40]: print(f"{r:.2f} | {t} | {h}")
print('n',len(res),'below .85:',sum(1 for r,*_ in res if r<.85))
kit/mictest.py (the real microphone path with a recorded word)14 lines
import asyncio,sys
from playwright.async_api import async_playwright
w,kind=sys.argv[1],sys.argv[2]
async def main():
async with async_playwright() as p:
b=await p.chromium.launch(args=['--autoplay-policy=no-user-gesture-required','--use-fake-device-for-media-stream','--use-fake-ui-for-media-stream',f'--use-file-for-fake-audio-capture=/tmp/fakemic/{w}.wav'])
pg=await b.new_page()
await pg.goto('http://localhost:8771/index.html');await pg.wait_for_timeout(300)
await pg.evaluate("document.getElementById('startBtn').click()");await pg.wait_for_timeout(1500)
r=await pg.evaluate(f"""(async()=>{{newTok();const T=tok;const out=[];for(let i=0;i<3;i++){{const x=await listenTake(T,4200);const r=SoundEar.analyze(x,AC.sampleRate,'{kind}');out.push(r.verdict+' '+(x.length/AC.sampleRate).toFixed(1)+'s floor '+mic.floor.toFixed(0))}}return out}})()""")
print(w,kind,r)
await b.close()
asyncio.run(main())
kit/flowtest.py (plays a whole round, with the mic or taps)32 lines
import asyncio,sys,time
from playwright.async_api import async_playwright
wav,sound,usemic=sys.argv[1],sys.argv[2],sys.argv[3]=='1'
async def main():
async with async_playwright() as p:
b=await p.chromium.launch(args=['--autoplay-policy=no-user-gesture-required','--use-fake-device-for-media-stream','--use-fake-ui-for-media-stream',f'--use-file-for-fake-audio-capture=/tmp/fakemic/{wav}.wav'])
pg=await b.new_page(viewport={'width':393,'height':700})
errs=[];pg.on('pageerror',lambda e:errs.append(str(e)))
await pg.goto('http://localhost:8771/index.html')
await pg.evaluate(f"localStorage.clear();localStorage.setItem('squad1_sounds',JSON.stringify(['{sound}']));localStorage.setItem('squad1_mic',{'true' if usemic else 'false'})")
await pg.reload();await pg.wait_for_timeout(300)
await pg.evaluate("document.getElementById('startBtn').click()");await pg.wait_for_timeout(1200)
await pg.evaluate("document.getElementById('playBtn').click()")
t0=time.time();last=None;log=[]
while time.time()-t0<420:
await pg.wait_for_timeout(500)
st=await pg.evaluate("[J.round,J.station,($('.screen.on')||{}).id,$('#cap').textContent,mic.state]")
if st[:3]!=last: log.append((round(time.time()-t0,1),st[:3],st[3][:50]));last=st[:3]
if st[0]>=1: break
await pg.evaluate("""(()=>{const d=$('#door.wiggle');if(d)d.click();const bx=$('#box.shake');if(bx)bx.click();
const h=$('.whoBtn.hint');if(h)h.click();else{const bs=$$('.whoBtn');if(bs.length&&whoPick)bs[Math.random()*bs.length|0].click()}
const c=$$('#mirrorCtl .btn,#feedCtl .btn');if(c.length)c[0].click();})()""")
if not usemic:
await pg.evaluate("(()=>{const t=$('#turn');})()")
# hold button for power play when no mic
on=await pg.evaluate("PW.active&&!speaking")
if on: await pg.evaluate("PW.holding=true")
for l in log: print(l)
print('errors',errs[:5],'stars',await pg.evaluate("state.stars"),'time',round(time.time()-t0))
await b.close()
asyncio.run(main())
Need an interactive piece for your business or audience?
A product explainer, a training walkthrough, a simulation people can play with. This one is free to take. I can build yours for a fixed price agreed up front, and the first call is free.