Game · project 20 of 37

Clock Knockout.

A clock-reading game two young directors dreamed up: Clock School teaches a 4-year-old the clock from zero, with light-saber hands and a friendly voice, then you read the clock to knock out silly villains and fish snacks out of a chocolate river.

Open the project ↗Get the skill and the code
After: Their own clock game: Clock School teaches the clock from zero with light-saber hands, a friendly voice and a pointing hand, then they read the clock to knock out silly villains and fish snacks from a chocolate river. Before: A paper worksheet of clocks to fill in, and a four-year-old who would rather fight a narwhal.

BeforeA paper worksheet of clocks to fill in, and a four-year-old who would rather fight a narwhal.

AfterTheir own clock game: Clock School teaches the clock from zero with light-saber hands, a friendly voice and a pointing hand, then they read the clock to knock out silly villains and fish snacks from a chocolate river.

What it is worthReading a clock learned by playing a game the children designed themselves, free, with no ads and nothing to buy. Instead of clock worksheets, and app games full of ads and timers.

More like this: games to play ›

How to use it

  1. Open it with the sound up and tap Learn the clock. It starts the next lesson right away. Sound plays even when an iPhone is on silent.
  2. Follow the voice and the pointing hand: meet the short red saber (hour) and the long blue saber (minutes), light up 1 to 12, point the short saber at the hour, count the long saber by fives, make minutes, then read whole times. Try the Saber Clock to drag the sabers and hear any time.
  3. Then tap 1 Player or 2 Players (Versus or Team up) and pick Nova or Blaze. On the clock map, tap the glowing hour and pick the time the clock shows. Tap Show me how to hear the clock read step by step; a wrong answer does the same.
  4. Your first right answer in a mission unlocks that hour's light saber. The minutes pick the challenge: tap POW to knock out the villain, or tap the snacks in the chocolate river. The third clock is the boss. From hour 7 you also set the clock yourself.
  5. Spend snacks on saber power at the bottom of the map. With a game controller: D-pad or stick moves, Cross picks and punches, Triangle is Show me how, Options goes back to the map, the stick turns the long saber in the Saber Clock, and a second controller is player 2.

Where it helps most

  • Children about 4 to 9 learning to read an analog clock, at home or in class, on a phone, a tablet, a computer or a TV with game controllers, and two siblings or friends who want to play together.
  • Parents and teachers who want a free clock game with no ads, no accounts and nothing to buy, and anyone who wants to see a child's own game idea turned into a real game, with the master prompt and the code to build their own.

The idea

Two young players wrote the brief themselves: learn to read the clock, every hour is a mission, the minutes decide the challenge, right answers unlock lightsabers, cartoon knockouts, Genghis Khan on a horse, superheroes, a narwhal, funny penguins, dancing little helpers, chocolate rivers, fruit, muffins, donuts and pretzels, kids fighting over tablets, someone watching TV, someone picking his nose, a smoky campfire, a girl on her phone and a guy who does not care about anything. Their only rules: no cats, no T-rex or dinosaurs, and no cupcakes. Every idea on their list is in the game, and they get the credit on the title screen.

The build

Built by Claude in one session from the children's list, with a five-minute first playable version and a second version the same evening. It is one page of plain HTML, CSS and JavaScript with no libraries or images: every character, scene and clock is drawn in SVG, the snack river is a canvas, and the sound effects are made on the fly with the Web Audio API: soft bells and chimes from sine and triangle waves through a low-pass filter and a compressor, turned down while the voice talks. The voice is Kokoro "af_heart", the same natural voice as the site's other children's games: about 1,300 short MP3 clips, each one a whole sentence (every time on the clock has its own "It is three twenty."), named by a hash of the sentence and played through Web Audio. Every clip was read back with Whisper; words it misheard were respelled. If a clip is missing, the device voice reads the line instead. Clock School waits for the child: nothing moves on until the right tap, a wrong tap is named ("Oops! That is five o'clock."), and after seven seconds the voice asks again and a hand points to the answer. The clock hands are exact: the hour hand turns half a degree per minute, so at 4:45 it sits three quarters of the way to 5, which is the mistake the game is built to teach. Wrong answers are chosen on purpose (the next hour, the previous hour, swapped hands, the wrong minute) and each one gets its own hint. Characters inspired by films the children love are original designs, not copies. Progress, light sabers, snacks and saber power are saved only in the visitor's browser. Game controllers use the standard mapping (PS5 DualSense, Xbox, 8BitDo, Amazon Luna): D-pad or stick moves between buttons, Cross picks, Cross is the punch in battles, the stick steers a grab ring in the snack river, Options goes to the map, and the first two controllers are player 1 and player 2; pads rumble on hits where the browser allows. Like every game under /games/, it works offline after the first open and can be added to a phone's Home Screen with its own icon. On iPhones the page asks for "playback" audio on the first tap, so it plays with the phone on silent. Limits: the device voice sounds different on each device; it was tested in a headless browser with simulated controllers, not yet with real controllers, a real TV or a real iPhone on 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: Clock Knockout

You are a game developer building a clock-reading game for children aged about 4 to 9. Two children are the creative directors; show "CLOCK KNOCKOUT" and "Created and directed by two young players" on the title screen. Build one self-contained page (HTML, CSS, JavaScript, SVG and canvas; no libraries or images; the voice is a folder of recorded clips) that plays at once on a phone, a tablet, a computer and a TV.

CLOCK SCHOOL (for a 4-year-old who does not know the clock at all; the title screen's first button starts the next unfinished lesson, and it is offered after picking a hero until a lesson is done): seven voice-led lessons on one big clock whose hands are light sabers (short red saber with a grey hilt and white core = hour, long blue saber = minutes), every number a 50 px tap target, a coach avatar with a caption of what the voice says, and a white pointing hand plus a pulsing yellow ring that show where to tap. The lesson waits for the right tap; a wrong tap is named; after 7 s of waiting the voice asks again and the hand appears. 0 Meet the Sabers: show each saber flashing with the hand on it, run the long saber once around while the short one moves one number, then the child taps the short saber or the long saber when asked (the sabers are tap targets only here). 1 Number Hunt: the numbers start dark; tap 1 to 12 in order, each lights up with a chime and is said. 2 The Short Saber: "Make it 3 o'clock, tap the 3" (the saber swings to whatever is tapped and wrong ones are named), then "Where is the short saber pointing?" three times. 3 Count by Fives: tap 1 to 12; the long saber jumps 5 minutes each time, a cyan light trail fills the face, the minute number appears outside, the voice counts five to sixty; then the short saber is shown on the next number. 4 Minute Missions: make 10, 20, 30, 15, 45, 50 minutes by tapping where the long saber stops; it counts there out loud; times are always said the digital way ("six forty-five"), never "quarter to" or "half past". 5 Little Minutes: +5 and +1 buttons to make 3, 7, 12, 23 and 38 minutes, counted out loud. 6 Read It All: 3:00, 3:20, 8:05, 10:30, 5:45: tap the hour ("close, pick the number it just passed" for the next hour), then the minute number, then it counts and says the time. Free play Saber Clock: drag the long saber (or turn the controller stick), the short saber follows, digital time and words, ±1 and ±5 buttons, Say the time, Surprise time. Each lesson gives three stars and 3 fruit; all seven make a Clock School graduate.

SHOW ME HOW (missions): a big button under the answers, and automatic after any wrong answer. On the mission clock: ring the hour number and flash the short saber ("The short red saber points to four. The hour is four.", or "is just past four" after the half hour), then flash the long saber and step it from 12 by fives with the light trail and the minute numbers shown outside the face, a chime and a spoken number on each step, then single minutes, then "So... It is four thirty.", then make the right answer glow. Answers are locked while it talks; an answer after the guide earns 50 points instead of 100.

THE CHILDREN'S IDEAS (keep every one): learning to read analog clocks; every hour is a mission; minutes decide the challenge; correct answers unlock lightsabers (call them light sabers); cartoon knockout battles with no blood; Genghis Khan riding a horse; superhero battles; a narwhal; funny penguins; dancing little helpers; chocolate waves and rivers; collecting fruit, muffins, donuts and pretzels; characters fighting over a tablet; a character watching TV; a character picking his nose; a character by a smoky campfire; a character distracted by her phone; a tired character who does not care. Strict exclusions: no cats, no T-rex or dinosaurs, no cupcakes (draw muffins with a paper cup and a big golden top). Characters inspired by films must be original designs, never copies.

WORLD: the map is a giant clock with 12 mission bubbles at the hour positions; locked hours show a padlock, finished hours show 1 to 3 stars; a glowing saber hand points to the next hour. Twelve missions, one villain each, each with a sky, ground, intro line, three taunts and a knockout line: 1 Couch Kingdom (TV watcher), 2 Tablet Tug-of-War (twins), 3 Booger Canyon (nose picker), 4 Smoky Campfire, 5 Phone Zone, 6 Meh Meadow (tired guy, Zzz), 7 Penguin Pier, 8 Bopper Bean Disco (three dancing beans), 9 Chocolate Falls (a chocolate wave with eyes), 10 Grand Steppe (Genghis Khan on a horse), 11 Hero Tower (Mega Magnet), 12 Narwhal Bay (Sir Tusk). Characters bounce, dance, waddle, flicker or puff smoke with CSS animation.

CLOCK: an accurate SVG clock: 60 ticks, numbers 1 to 12, light-saber hands: a short red hour saber turned (hour mod 12) × 30 + minutes × 0.5 degrees, a long blue minute saber turned minutes × 6 degrees, and a legend. Minute numbers (00, 5, 10 ...) outside the face and a light trail from 12 to the minute saber in hours 1 and 2 and during Show me how.

COLOURS AND WORDS: the hour numbers 1 to 12 are the same red as the short saber, and the minute numbers (5, 10 ... 55), the little minute ticks and the light trail are the same blue as the long saber, so each saber points at numbers of its own colour. Times are always said and shown the digital way: "It is six forty-five.", "six oh five", "six o'clock"; never "quarter to", "half past" or "minutes past". When counting single minutes, the little ticks light up blue and get their own small numbers (21, 22, 23).

QUESTIONS: mission H always shows H:MM. Minutes by level: hours 1-3 use 0 and 30; 4-6 add 15 and 45; 7-9 any multiple of 5; 10-12 half the time any minute. Round 1 prefers minutes under 20, round 2 20-39, round 3 40 or more, no minute twice in a mission. Four big answer buttons: the right time plus three distractors from the next hour, the previous hour, swapped hands, and a wrong minute. Hints per mistake: next-hour trap ("the short hand has not reached 5 yet"), right minutes wrong hour, right hour wrong minutes, swapped hands. Say the time the digital way ("It is six forty-five."). From hour 7, round 2 is set-the-clock: Hour −/+ and Minute −/+ buttons (±5, plus ±1 from hour 10) move accurate hands, then Check. Points: 100 first try, 50 later; 150 or 75 for setting the clock.

AFTER A RIGHT ANSWER: the first in a mission unlocks that hour's light saber (12 colours, the last a rainbow) in a pop-up; then the minutes pick the challenge and the pop-up says so: 0-19 knockout battle, 20-39 chocolate river snack hunt, 40-59 super power battle (double damage, hero glows); round 3 is always the boss (more energy). BATTLE: an SVG arena with the hero (cape, mask, clock emblem, glowing saber) left and the villain right, an energy bar, a giant POW button and tapping the villain; each hit lunges the hero, shakes the villain and pops POW!, BONK!, ZAP!; every fourth hit may be BLOCKED; knockout spins the villain away with its knockout line and gives fruit. SNACK RIVER: a canvas chocolate river with moving waves, 12 seconds, fruit, muffins, donuts and pretzels drawn in code floating across, tap to grab; counts by kind go to the inventory, 10 points each.

PLAYERS: 1 Player (pick Nova or Blaze), or 2 Players: Versus (turns alternate each round, separate scores, the leader shown) or Team up (turns alternate on the clock, both heroes in the arena, two POW buttons, more boss energy). Saber power: spend 8, 16, then 24 snacks for levels 1 to 3; damage per hit is 1 plus the level. Save unlocked hours, stars, sabers, snacks, saber level and points in localStorage with try/catch; Restart asks in a built-in dialog first.

CONTROLS AND ACCESS: big touch targets (answers at least 64 px high), mouse, keys 1 to 4 for answers. Game controllers through the Gamepad API standard mapping: D-pad or left stick moves focus to the nearest button in that direction (with a held repeat), Cross picks, Triangle is Hint, Circle is Back, Options is Home; in battles any face button punches (pad 1 is player 1, pad 2 is player 2 in Team up) with a rumble; in the snack river each pad steers its own grab ring with the stick and Cross grabs. Ignore Cross for 0.7 s after a dialog or a new question, so a child mashing POW does not pick an answer by accident. A toast says when a controller connects. VOICE: record every line with Kokoro "af_heart" (kokoro-onnx, speed 0.95) as one MP3 per whole sentence, named by a 32-bit djb2-xor hash of the sentence; every clock time gets its own "It is ..." sentence and every set-the-clock time its own "Set the clock to ...", so no sentence is glued from pieces. Play clips through Web Audio in a queue that a new line or screen cuts off; the device voice only for a missing clip; read every clip back with Whisper and respell what it mishears. SOUND EFFECTS: soft bells and chimes only (sine and triangle, 12 ms attack, low-pass at 2.8 kHz, a compressor), turned down while the voice talks. Mute silences everything.

SOUND: Web Audio synth effects (tap, correct arpeggio, wrong wobble, POW noise burst, block, knockout fanfare, grab blip, saber hum, win tune). iPhone silent-mode fix: create and resume the AudioContext on the first tap, set navigator.audioSession.type to 'playback', fall back to a looping silent MP3 at audio/silence.mp3 on older iPhones, resume on every tap and when the page is shown again; add the line "No sound? Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent."

FINISH: candy-night purple ground, sunny yellow, bubblegum pink and glow cyan; Fredoka for all text; one column on phones, clock beside answers on wide or sideways screens; on a sideways phone shrink the scene and buttons so POW fits without scrolling; reduced motion turns animations off. For a strict security policy, put no inline style attributes in the markup (keep looks in data-s and apply them through the style object). Add a web manifest and 180, 192 and 512 px icons so it can go on the Home Screen, and make it work offline.

STRESS TEST: play every mission type at 320×568, 393×700, 740×360 and 1366×800; check the hour hand position at :15, :30 and :45; mash POW and the controller buttons through every dialog; play the snack river with touch and with a controller; finish hour 12; restart; reload and check the save; check there is no console error and no sideways scrolling.
Get the code5 files, exactly as they run on this site · free under the MIT license

These files are exactly what runs at sghadimi.com/games/clock-knockout. The page also needs the site's Fredoka font files (../fonts/), a one-second silent MP3 at audio/silence.mp3 for older iPhones, and the three icon PNGs. The voice is about 1,300 MP3 clips in v/, recorded with voices.py from the game's own sentence list (__lines() in the browser console, saved as docs/clock-knockout/lines.json). No images or models are used: the characters, scenes and clocks are SVG drawn in code, and the sound effects are made in the browser. The single-file version (the same as the Claude preview) is docs/clock-knockout/clock-knockout.html in the repository; docs/clock-knockout/split-for-site.py turns it into these files.

clock.js (the whole game: clock, missions, battles, snack river, controllers, sound)1,007 lines

Raw file

{
/* ---------- iPhone: Web Audio is muted by the silent switch unless the page asks for "playback" audio ---------- */
let AC=null,silentEl=null,master=null;
function iosUnlock(){
  try{if(navigator.audioSession&&navigator.audioSession.type!=='playback')navigator.audioSession.type='playback';}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){}
    audioGraph();
  }catch(e){AC=null;}
}
window.__audio=()=>AC;window.__iosUnlock=iosUnlock;

/* ---------- inline looks: data-s is applied through the style object, so no inline style attributes are needed ---------- */
const applyS=root=>{if(root.nodeType!==1)return;const list=root.matches&&root.matches('[data-s]')?[root,...root.querySelectorAll('[data-s]')]:root.querySelectorAll('[data-s]');for(const el of list){el.style.cssText=el.getAttribute('data-s');el.removeAttribute('data-s');}};
new MutationObserver(ms=>{for(const m of ms)for(const n of m.addedNodes)applyS(n);}).observe(document.documentElement,{childList:true,subtree:true});
const SITE_LINKS='<a href="/games/">All games</a> · <a href="/cases/clock-knockout/">How it was made</a>';

/* ---------- state and saving ---------- */
let muted=false;
const KEY='iack-v1';
const fresh=()=>({school:{},lvl:0,unlocked:1,stars:{},swords:[],inv:{fruit:0,muffin:0,donut:0,pretzel:0},points:0,hero:'Nova'});
let P=fresh();
try{const s=JSON.parse(localStorage.getItem(KEY)||'null');if(s&&s.unlocked)P=Object.assign(fresh(),s);muted=localStorage.getItem(KEY+'m')==='1';}catch(e){}
function save(){try{localStorage.setItem(KEY,JSON.stringify(P));localStorage.setItem(KEY+'m',muted?'1':'0');}catch(e){}}

/* ---------- sounds: soft synth (sine and triangle only, gentle attack, low-pass), quieter while the voice talks ---------- */
let fxBus=null;
function audioGraph(){
  const comp=AC.createDynamicsCompressor();comp.threshold.value=-18;comp.ratio.value=4;comp.connect(AC.destination);
  master=AC.createGain();master.gain.value=muted?0:1;master.connect(comp);
  const lp=AC.createBiquadFilter();lp.type='lowpass';lp.frequency.value=2800;lp.Q.value=.3;lp.connect(master);
  fxBus=AC.createGain();fxBus.gain.value=.32;fxBus.connect(lp);
}
let musBus=null,musT=0,musStep=0,musOn=true;
function duck(on){if(!fxBus)return;try{fxBus.gain.setTargetAtTime(on?.1:.32,AC.currentTime,.05);if(musBus)musBus.gain.setTargetAtTime(on?.035:.09,AC.currentTime,.12);}catch(e){}}
/* a cheerful 8-bar tune in C major (bells over a soft bass), scheduled a little ahead */
const TUNE=[[523,659],[0,784],[659,0],[784,880],[880,0],[784,659],[659,0],[523,0],[587,698],[0,784],[698,0],[880,784],[784,0],[698,587],[659,0],[0,0]];
const BASS=[131,0,196,0,175,0,196,0,147,0,196,0,131,0,196,0];
function music(){
  if(!AC||!fxBus)return;
  if(!musBus){musBus=AC.createGain();musBus.gain.value=.09;const lp=AC.createBiquadFilter();lp.type='lowpass';lp.frequency.value=2200;musBus.connect(lp);lp.connect(master);musT=AC.currentTime+.2;}
  const beat=60/112/2;
  while(musT<AC.currentTime+.6){
    if(!muted&&musOn){const st=musStep%16,[a,b]=TUNE[st],t=musT-AC.currentTime;
      [a,b].forEach(f=>{if(f){const o=AC.createOscillator(),g=AC.createGain();o.type='triangle';o.frequency.value=f;g.gain.setValueAtTime(0,musT);g.gain.linearRampToValueAtTime(.5,musT+.01);g.gain.exponentialRampToValueAtTime(.001,musT+beat*1.8);o.connect(g);g.connect(musBus);o.start(musT);o.stop(musT+beat*2);}});
      const bf=BASS[st];if(bf){const o=AC.createOscillator(),g=AC.createGain();o.type='sine';o.frequency.value=bf;g.gain.setValueAtTime(0,musT);g.gain.linearRampToValueAtTime(.9,musT+.02);g.gain.exponentialRampToValueAtTime(.001,musT+beat*1.6);o.connect(g);g.connect(musBus);o.start(musT);o.stop(musT+beat*2);}
      if(st%4===2){const o=AC.createOscillator(),g=AC.createGain();o.type='sine';o.frequency.setValueAtTime(1800,musT);o.frequency.exponentialRampToValueAtTime(900,musT+.05);g.gain.setValueAtTime(.12,musT);g.gain.exponentialRampToValueAtTime(.001,musT+.06);o.connect(g);g.connect(musBus);o.start(musT);o.stop(musT+.08);}}
    musT+=beat;musStep++;
  }
}
setInterval(music,200);
function tone(f,d,type='sine',v=.3,slide=0,when=0){
  if(!AC||muted||!fxBus)return;if(type!=='sine'&&type!=='triangle')type='triangle';
  const t=AC.currentTime+when,o=AC.createOscillator(),g=AC.createGain();
  o.type=type;o.frequency.setValueAtTime(f,t);if(slide)o.frequency.exponentialRampToValueAtTime(Math.max(40,f+slide),t+d);
  g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(v,t+.012);g.gain.exponentialRampToValueAtTime(.0008,t+d);
  o.connect(g);g.connect(fxBus);o.start(t);o.stop(t+d+.05);
}
function bell(f,v=.22,when=0,d=.9){tone(f,d,'sine',v,0,when);tone(f*2,d*.5,'sine',v*.25,0,when);tone(f*3,d*.25,'sine',v*.08,0,when);}
const PENTA=[523,587,659,784,880,1047,1175,1319,1568,1760,2093,2349];
function chime(i){bell(PENTA[Math.max(0,Math.min(PENTA.length-1,i))],.18,0,.7);}
function noise(d,v=.3,cut=700){
  if(!AC||muted||!fxBus)return;const b=AC.createBuffer(1,Math.max(1,AC.sampleRate*d|0),AC.sampleRate),a=b.getChannelData(0);
  for(let i=0;i<a.length;i++)a[i]=(Math.random()*2-1)*Math.pow(1-i/a.length,2);
  const s=AC.createBufferSource(),g=AC.createGain(),f=AC.createBiquadFilter();f.type='lowpass';f.frequency.value=cut;
  s.buffer=b;g.gain.value=v;s.connect(f);f.connect(g);g.connect(fxBus);s.start();
}
const SFX={
  tap:()=>tone(880,.08,'sine',.12),
  yes:()=>{[784,988,1175,1568].forEach((f,i)=>bell(f,.2,i*.09,.8));},
  no:()=>{tone(392,.18,'sine',.18,-40);tone(330,.26,'sine',.16,-30,.15);},
  pow:()=>{noise(.14,.45,600);tone(160,.2,'sine',.35,-90);},
  block:()=>bell(1320,.12,0,.25),
  ko:()=>{[523,659,784,1047,1319].forEach((f,i)=>bell(f,.18,i*.08,.6));noise(.35,.2,500);},
  grab:()=>bell(1047+Math.floor(Math.random()*4)*131,.16,0,.35),
  saber:()=>{tone(98,.55,'sine',.22,40);tone(147,.55,'triangle',.08,60);noise(.3,.08,900);},
  win:()=>{[523,659,784,659,784,1047].forEach((f,i)=>bell(f,.2,i*.15,.7));},
  boing:()=>tone(300,.3,'sine',.2,250)
};

/* ---------- world data: the children's ideas ---------- */
const M=[
 {name:'Couch Kingdom',v:'Remote Rodney',art:'tv',sky:['#ff9a3c','#ff5f6d'],gr:'#7a3cff',intro:'He will not stop watching TV!',lines:['Shh! My show is on!','Five more episodes!','Move, you are blocking the TV!'],ko:'Fine! I will go play outside!'},
 {name:'Tablet Tug-of-War',v:'The Grabby Twins',art:'tablets',sky:['#45d4ff','#2b6cff'],gr:'#2fbf55',intro:'They are fighting over one tablet!',lines:['MINE!','No, MINE!','It is MY turn!'],ko:'OK, OK! We will take turns!'},
 {name:'Booger Canyon',v:'Picky Pete',art:'nose',sky:['#b5ff6b','#2fbf8a'],gr:'#8a5a2b',intro:'He is picking his nose. Yuck!',lines:['Found a big one!','Want to see it?','Hold on, I am digging...'],ko:'Fine! I will get a tissue!'},
 {name:'Smoky Campfire',v:'Smoky Sam',art:'fire',sky:['#2b1a6e','#ff7a3c'],gr:'#3a5a2b',intro:'His campfire is SO smoky!',lines:['Ahem, ahem! So smoky!','Who wants a marshmallow?','The smoke follows me!'],ko:'Argh! Too much smoke! I give up!'},
 {name:'Phone Zone',v:'Scrolling Sally',art:'phone',sky:['#ff7ad9','#7a3cff'],gr:'#3b2a6e',intro:'She cannot stop looking at her phone!',lines:['One more video...','Did you see this?','Huh? Did you say something?'],ko:'My battery died! Oh, hi everyone!'},
 {name:'Meh Meadow',v:'Whatever Walt',art:'tired',sky:['#c9c9d9','#8a8aa8'],gr:'#9aa06b',intro:'He is too tired to care about anything.',lines:['Whatever.','I do not care...','Zzzz...'],ko:'Okay... that was kind of fun.'},
 {name:'Penguin Pier',v:'The Waddle Squad',art:'penguins',sky:['#bff3ff','#5ab8ff'],gr:'#ffffff',intro:'Silly penguins want your snacks!',lines:['Smile and waddle!','Belly slide attack!','Snack break!'],ko:'Retreat! Waddle away!'},
 {name:'Bopper Bean Disco',v:'The Bopper Beans',art:'beans',sky:['#ff4fa2','#ffd23f'],gr:'#3a1c7a',intro:'The Bopper Beans will not stop dancing!',lines:['Dance, dance, dance!','Dance battle!','Wiggle wiggle!'],ko:'Boo-hoo-dee-doo! You win!'},
 {name:'Chocolate Falls',v:'Choco Wave',art:'choco',sky:['#ffb36b','#ff7a3c'],gr:'#6b3a1f',intro:'A giant chocolate wave is coming!',lines:['Splash!','Taste my chocolate wave!','I am extra fudgy!'],ko:'I am melting into a puddle!'},
 {name:'Grand Steppe',v:'Genghis Khan',art:'khan',sky:['#9fe3ff','#ffe08a'],gr:'#c9b25a',intro:'Genghis Khan gallops in on his horse!',lines:['Faster, my horse!','Gallop gallop!','Yee-haw!'],ko:'Whoa, horsey! You are a great warrior!'},
 {name:'Hero Tower',v:'Mega Magnet',art:'magnet',sky:['#1b1b4a','#3b6bff'],gr:'#555a7a',intro:'Mega Magnet wants to steal every sword!',lines:['My magnet pulls your sword!','CLANG!','Mwa-ha-ha!'],ko:'Oh no! My magnet is upside down!'},
 {name:'Narwhal Bay',v:'Sir Tusk the Narwhal',art:'narwhal',sky:['#7fe0ff','#2b6cff'],gr:'#1e88e5',intro:'The giant narwhal wants a sword fight!',lines:['Splash attack!','My tusk is the best sword in the sea!','Blub blub!'],ko:'Okay! Let us high-five with my tusk!'}
];
const SW=[['Ruby Saber','#ff3b3b'],['Orange Blaze','#ff8a00'],['Lemon Zap','#ffe600'],['Lime Laser','#7dff3a'],['Ocean Glow','#00e0ff'],['Blue Bolt','#3b7bff'],['Grape Beam','#b05bff'],['Pink Sparkle','#ff4fd8'],['Snow Star','#ffffff'],['Choco Ray','#c07a4a'],['Gold King','#ffc83b'],['Rainbow Max','rainbow']];
const POWS=['POW!','BONK!','ZAP!','BOING!','KAPOW!','WHAM!','BOOP!'];

/* ---------- drawing ---------- */
const DEFS=`<defs><filter id="gl" x="-80%" y="-30%" width="260%" height="160%"><feGaussianBlur stdDeviation="3.5" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter>
<linearGradient id="rb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ff3b3b"/><stop offset=".2" stop-color="#ff8a00"/><stop offset=".4" stop-color="#ffe600"/><stop offset=".6" stop-color="#3bff6b"/><stop offset=".8" stop-color="#3b7bff"/><stop offset="1" stop-color="#b05bff"/></linearGradient></defs>`;
const blade=c=>c==='rainbow'?'url(#rb)':c;
function swordSVG(c,on=true){return `<svg viewBox="0 0 24 70" aria-hidden="true">${DEFS}<rect x="9" y="4" width="6" height="46" rx="3" fill="${on?blade(c):'#ffffff33'}" ${on?'filter="url(#gl)"':''}/><rect x="6" y="50" width="12" height="16" rx="3" fill="${on?'#666':'#ffffff22'}"/><rect x="4" y="49" width="16" height="4" rx="2" fill="${on?'#999':'#ffffff22'}"/></svg>`;}
function clockSVG(h,m,o={}){
  if(typeof o==='boolean')o={hint:o};
  const hint=!!o.hint,ha=((h%12)*30+m*.5),ma=m*6;
  let s=`<svg viewBox="-30 -30 360 360" role="img" aria-label="Analog clock">${DEFS}<circle cx="150" cy="150" r="144" fill="#ffd23f"/><circle cx="150" cy="150" r="132" fill="#fff"/>`;
  if((hint||o.trail)&&m>0){const a=ma*Math.PI/180;s+=m>=60?`<circle cx="150" cy="150" r="132" fill="#3ee0ff" opacity=".3"/>`:`<path d="M150,150 L150,18 A132,132 0 ${m>30?1:0} 1 ${150+Math.sin(a)*132},${150-Math.cos(a)*132} Z" fill="#3ee0ff" opacity=".3"/>`;}
  for(let i=0;i<60;i++){const a=i*6*Math.PI/180,big=i%5===0,r1=big?116:122;
    s+=`<line x1="${150+Math.sin(a)*(big?r1:(hint?114:r1))}" y1="${150-Math.cos(a)*(big?r1:(hint?114:r1))}" x2="${150+Math.sin(a)*128}" y2="${150-Math.cos(a)*128}" stroke="${big?'#2a1650':'#1f7fe0'}" stroke-opacity="${big||hint?1:.45}" stroke-width="${big?4:(hint?3:2)}" stroke-linecap="round"/>`;
    if(o.ones&&!big&&i<=m&&i>Math.floor(m/5)*5)s+=`<text x="${150+Math.sin(a)*152}" y="${150-Math.cos(a)*152+5}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="13" fill="#1f7fe0">${i}</text>`;}
  for(let n=1;n<=12;n++){const a=n*30*Math.PI/180,x=150+Math.sin(a)*96,y=150-Math.cos(a)*96;
    if(o.ringH===n)s+=`<circle class="ringpulse" cx="${x}" cy="${y}" r="25" fill="#ffe1e6" stroke="#e8264a" stroke-width="5"/>`;
    if(o.ringM===n)s+=`<circle class="ringpulse" cx="${x}" cy="${y}" r="25" fill="#dff3ff" stroke="#1f7fe0" stroke-width="5"/>`;
    s+=`<text x="${x}" y="${y+11}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="32" fill="#e8264a">${n}</text>`;
    if(hint)s+=`<text x="${150+Math.sin(a)*163}" y="${150-Math.cos(a)*163+7}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="21" fill="#1f7fe0">${(n*5)%60===0?'00':n*5}</text>`;}
  s+=`<g class="${o.flash==='h'?'flash':''}" transform="rotate(${ha} 150 150)"><rect x="144" y="132" width="12" height="26" rx="4" fill="#8d8fa3"/><rect x="141" y="128" width="18" height="6" rx="2" fill="#c9cbd8"/><rect x="143" y="72" width="14" height="58" rx="7" fill="#e8264a" filter="url(#gl)"/><rect x="147" y="76" width="6" height="50" rx="3" fill="#ffd0d8"/></g>`;
  s+=`<g class="${o.flash==='m'?'flash':''}" transform="rotate(${ma} 150 150)"><rect x="146" y="128" width="8" height="30" rx="3" fill="#8d8fa3"/><rect x="143" y="124" width="14" height="6" rx="2" fill="#c9cbd8"/><rect x="146" y="32" width="8" height="94" rx="4" fill="#1f7fe0" filter="url(#gl)"/><rect x="148.5" y="35" width="3" height="88" rx="1.5" fill="#d6f0ff"/></g>`;
  s+=`<circle cx="150" cy="150" r="11" fill="#2a1650"/><circle cx="150" cy="150" r="4" fill="#ffd23f"/></svg>`;
  return s;
}

function heroG(w,c){
  const I=w==='Nova',cape=I?'#a34bff':'#ff7a00',shirt=I?'#ff4fa2':'#2b8cff',hair=I?'#4a2511':'#1f140c',skin=I?'#f2c29b':'#d9a273';
  const hairP=I?`<path d="M-27,-104 a27,27 0 0 1 54,0 l3,40 l-13,0 l-5,-34 a20,14 0 0 0 -24,0 l-5,34 l-13,0z" fill="${hair}"/><circle cx="20" cy="-128" r="8" fill="${cape}"/>`:`<path d="M-25,-106 a25,24 0 0 1 50,0 q-6,-10 -25,-8 q-19,-2 -25,8z" fill="${hair}"/>`;
  return `<path d="M-20,-78 L-44,-6 L26,-6 L20,-78Z" fill="${cape}"/>
  <rect x="-15" y="-36" width="12" height="36" rx="5" fill="#2a2f5a"/><rect x="3" y="-36" width="12" height="36" rx="5" fill="#2a2f5a"/>
  <rect x="-21" y="-82" width="42" height="52" rx="15" fill="${shirt}"/><circle cy="-60" r="10" fill="#fff"/><path d="M0,-60 v-7 M0,-60 h6" stroke="#2a1650" stroke-width="2.5" stroke-linecap="round"/>
  <circle cy="-104" r="25" fill="${skin}"/>${hairP}
  <rect x="-21" y="-113" width="42" height="12" rx="6" fill="${cape}"/><circle cx="-9" cy="-107" r="3.5" fill="#fff"/><circle cx="9" cy="-107" r="3.5" fill="#fff"/>
  <path d="M-9,-94 q9,9 18,0" stroke="#6a2a1a" stroke-width="3.5" fill="none" stroke-linecap="round"/>
  <g transform="rotate(25 30 -70)"><rect x="18" y="-80" width="11" height="30" rx="5" fill="${skin}"/><rect x="19" y="-98" width="9" height="20" rx="2" fill="#555"/><rect x="15" y="-100" width="17" height="5" rx="2" fill="#999"/><rect x="20" y="-182" width="7" height="84" rx="3.5" fill="${blade(c)}" filter="url(#gl)"/></g>`;
}
function eyes(t){
  if(t==='sleepy')return `<path d="M-14,-110 h10 M4,-110 h10" stroke="#222" stroke-width="3.5" stroke-linecap="round"/><path d="M-15,-115 q5,-3 11,0 M4,-115 q5,-3 11,0" stroke="#222" stroke-width="2" fill="none"/>`;
  const dy=t==='down'?4:0;
  return `<circle cx="-9" cy="-110" r="7" fill="#fff"/><circle cx="9" cy="-110" r="7" fill="#fff"/><circle cx="${t==='side'?-6:-9}" cy="${-110+dy}" r="3.5" fill="#222"/><circle cx="${t==='side'?12:9}" cy="${-110+dy}" r="3.5" fill="#222"/>`;
}
function mouth(t){
  return {smile:'<path d="M-9,-96 q9,8 18,0" stroke="#6a2a1a" stroke-width="3.5" fill="none" stroke-linecap="round"/>',
  o:'<ellipse cy="-94" rx="5" ry="6" fill="#6a2a1a"/>',flat:'<path d="M-8,-95 h16" stroke="#6a2a1a" stroke-width="3.5" stroke-linecap="round"/>',
  grin:'<path d="M-11,-98 q11,12 22,0z" fill="#fff" stroke="#6a2a1a" stroke-width="2.5"/>',mad:'<path d="M-9,-92 q9,-7 18,0" stroke="#6a2a1a" stroke-width="3.5" fill="none" stroke-linecap="round"/>'}[t];
}
function person(o){
  const {skin='#f0c08f',shirt='#3aa0ff',pants='#333a66',hair='#3b2414',e='open',mo='smile',extra='',long=false}=o;
  return `<rect x="-15" y="-36" width="12" height="36" rx="5" fill="${pants}"/><rect x="3" y="-36" width="12" height="36" rx="5" fill="${pants}"/>
  <rect x="-24" y="-84" width="48" height="54" rx="16" fill="${shirt}"/><circle cy="-108" r="26" fill="${skin}"/>
  <path d="M-26,-110 a26,26 0 0 1 52,0 ${long?'l3,40 l-12,0 l-4,-34 h-24 l-4,34 l-12,0z':'q-8,-10 -26,-9 q-18,-1 -26,9z'}" fill="${hair}"/>${eyes(e)}${mouth(mo)}${extra}`;
}
function penguin(x,s,hat,d){return `<g transform="translate(${x},0) scale(${s})"><g class="waddle" data-s="animation-delay:${d}s"><ellipse cy="-55" rx="34" ry="52" fill="#1e2233"/><ellipse cy="-48" rx="23" ry="40" fill="#fff"/><circle cx="-9" cy="-82" r="7" fill="#fff"/><circle cx="9" cy="-82" r="7" fill="#fff"/><circle cx="-7" cy="-82" r="3.5" fill="#111"/><circle cx="11" cy="-82" r="3.5" fill="#111"/><path d="M-8,-72 l8,10 l8,-10z" fill="#ff9a1a"/><ellipse cx="-14" cy="-2" rx="12" ry="5" fill="#ff9a1a"/><ellipse cx="14" cy="-2" rx="12" ry="5" fill="#ff9a1a"/><path d="M-33,-60 q-14,18 -6,34 M33,-60 q14,18 6,34" stroke="#1e2233" stroke-width="9" fill="none" stroke-linecap="round"/>${hat}</g></g>`;}
function bean(x,c,d){return `<g transform="translate(${x},0)"><g class="dance" data-s="animation-delay:${d}s"><rect x="-26" y="-108" width="52" height="102" rx="26" fill="${c}"/><path d="M0,-108 v-16" stroke="${c}" stroke-width="4"/><circle cy="-128" r="6" fill="#ffd23f"/><circle cx="-10" cy="-78" r="10" fill="#fff"/><circle cx="10" cy="-78" r="10" fill="#fff"/><circle cx="-8" cy="-76" r="4.5" fill="#222"/><circle cx="12" cy="-76" r="4.5" fill="#222"/><path d="M-12,-56 q12,12 24,0" stroke="#222" stroke-width="3.5" fill="#fff"/><path d="M-26,-60 l-16,-18 M26,-60 l16,-18" stroke="${c}" stroke-width="8" stroke-linecap="round"/><rect x="-18" y="-10" width="12" height="12" rx="4" fill="#222"/><rect x="6" y="-10" width="12" height="12" rx="4" fill="#222"/></g></g>`;}
function villainG(art){
  switch(art){
  case 'tv':return `<rect x="-95" y="-80" width="120" height="44" rx="16" fill="#e74c3c"/><rect x="-100" y="-46" width="130" height="40" rx="14" fill="#c0392b"/>
    <g transform="translate(-35,-14) scale(.8)">${person({shirt:'#2ecc71',e:'side',mo:'o',extra:'<rect x="18" y="-70" width="10" height="22" rx="3" fill="#222"/><circle cx="23" cy="-66" r="2.5" fill="#f33"/>'})}</g>
    <g transform="translate(70,-30)"><rect x="-6" y="-8" width="4" height="30" fill="#333" transform="rotate(10)"/><rect x="2" y="-8" width="4" height="30" fill="#333" transform="rotate(-10)"/><rect x="-32" y="-62" width="64" height="50" rx="7" fill="#222"/><rect class="flick" x="-26" y="-56" width="52" height="38" rx="4" fill="#7ff6ff"/><circle cx="-10" cy="-38" r="6" fill="#ff4fa2" class="flick"/></g>`;
  case 'tablets':return `<g transform="translate(-48,0) scale(.82)">${person({shirt:'#ff7a00',mo:'mad'})}</g><g transform="translate(48,0) scale(.82)">${person({shirt:'#ff7a00',mo:'mad',hair:'#7a3b14'})}</g>
    <g class="tug"><rect x="-22" y="-80" width="44" height="32" rx="5" fill="#222"/><rect x="-18" y="-76" width="36" height="24" rx="3" fill="#7ff6ff"/><path d="M-30,-60 h-8 M30,-60 h8" stroke="#f0c08f" stroke-width="9" stroke-linecap="round"/></g>
    <text x="-60" y="-140" font-family="Fredoka,sans-serif" font-weight="700" font-size="20" fill="#fff" class="float">MINE!</text>`;
  case 'nose':return `${person({shirt:'#9b59b6',mo:'o',e:'side',extra:'<path d="M20,-60 Q30,-90 3,-100" stroke="#f0c08f" stroke-width="10" fill="none" stroke-linecap="round"/><circle cx="12" cy="-90" r="4" fill="#8bd650"/>'})}
    <text x="34" y="-120" font-family="Fredoka,sans-serif" font-weight="700" font-size="18" fill="#fff" class="float">pick pick</text>`;
  case 'fire':return `<g transform="translate(-45,-6) scale(.85)">${person({shirt:'#c0392b',mo:'grin',hair:'#6b3a1f',extra:'<path d="M20,-62 L80,-90" stroke="#8a5a2b" stroke-width="4"/><circle cx="82" cy="-91" r="7" fill="#fff8e0"/>'})}</g>
    <g transform="translate(55,0)"><rect x="-30" y="-12" width="60" height="12" rx="6" fill="#6b3a1f" transform="rotate(12)"/><rect x="-30" y="-12" width="60" height="12" rx="6" fill="#8a5a2b" transform="rotate(-12)"/>
    <path class="flick" d="M-18,-10 Q-22,-40 -6,-58 Q-4,-38 4,-48 Q16,-30 18,-10z" fill="#ff7a00"/><path d="M-9,-10 Q-10,-28 0,-38 Q8,-24 9,-10z" fill="#ffd23f"/>
    <circle class="puff" cx="0" cy="-60" r="12" fill="#9a9aa8"/><circle class="puff" data-s="animation-delay:.8s" cx="-6" cy="-60" r="10" fill="#b0b0bb"/><circle class="puff" data-s="animation-delay:1.6s" cx="6" cy="-60" r="11" fill="#8a8a99"/></g>`;
  case 'phone':return `${person({shirt:'#ff4fa2',hair:'#2b1408',long:true,e:'down',mo:'smile',extra:'<rect x="-14" y="-74" width="22" height="34" rx="5" fill="#222" transform="rotate(-10)"/><rect class="flick" x="-11" y="-71" width="16" height="26" rx="3" fill="#9df" transform="rotate(-10)"/>'})}
    <path class="float" d="M40,-110 c0,-8 12,-8 12,0 c0,-8 12,-8 12,0 c0,10 -12,16 -12,18 c0,-2 -12,-8 -12,-18z" fill="#ff4fa2"/>`;
  case 'tired':return `<g transform="rotate(6)">${person({shirt:'#8a8aa8',pants:'#555',hair:'#666',e:'sleepy',mo:'flat'})}</g>
    <text class="float" x="30" y="-130" font-family="Fredoka,sans-serif" font-weight="700" font-size="26" fill="#fff">Z</text><text class="float" data-s="animation-delay:.7s" x="48" y="-150" font-family="Fredoka,sans-serif" font-weight="700" font-size="20" fill="#fff">z</text><text x="-70" y="-150" font-family="Fredoka,sans-serif" font-weight="700" font-size="20" fill="#fff">meh.</text>`;
  case 'penguins':return penguin(-60,.8,'',0)+penguin(0,1,'<rect x="-14" y="-118" width="28" height="12" rx="3" fill="#ff3b3b"/><rect x="-20" y="-108" width="40" height="5" fill="#ff3b3b"/>',.15)+penguin(60,.75,'<path d="M-14,-100 l10,4 M14,-100 l-10,4" stroke="#111" stroke-width="3"/>',.3);
  case 'beans':return bean(-55,'#8e5cff',0)+bean(0,'#ff7a00',.2)+bean(55,'#2fbf8a',.4);
  case 'choco':return `<path d="M-100,0 Q-100,-140 10,-150 Q90,-150 100,-80 Q70,-110 40,-90 Q60,-60 100,-40 L100,0z" fill="#6b3a1f"/><path d="M-70,-40 Q-60,-120 10,-128" stroke="#a0613a" stroke-width="10" fill="none" stroke-linecap="round"/>
    <circle cx="-20" cy="-90" r="16" fill="#fff"/><circle cx="20" cy="-95" r="16" fill="#fff"/><circle cx="-24" cy="-88" r="7" fill="#222"/><circle cx="16" cy="-93" r="7" fill="#222"/><path d="M-30,-55 q30,24 60,-4z" fill="#3a1c0c"/><path d="M-20,-52 l6,8 l6,-8 M6,-54 l6,8 l6,-8" fill="#fff"/>
    <path d="M60,-40 q4,16 0,20 q-4,-4 0,-20z M-80,-10 q4,14 0,18 q-4,-4 0,-18z" fill="#6b3a1f"/>`;
  case 'khan':return `<g><ellipse cx="0" cy="-58" rx="60" ry="28" fill="#8a5a2b"/><rect x="-48" y="-40" width="12" height="40" rx="5" fill="#6b3a1f"/><rect x="-28" y="-40" width="12" height="40" rx="5" fill="#6b3a1f"/><rect x="22" y="-40" width="12" height="40" rx="5" fill="#6b3a1f"/><rect x="40" y="-40" width="12" height="40" rx="5" fill="#6b3a1f"/>
    <path d="M-50,-72 Q-80,-120 -95,-104 Q-96,-86 -70,-80z" fill="#8a5a2b"/><ellipse cx="-92" cy="-104" rx="18" ry="12" fill="#8a5a2b"/><circle cx="-96" cy="-108" r="3" fill="#111"/><path d="M-58,-92 q-8,-24 -26,-26" stroke="#2a1408" stroke-width="7" fill="none"/><path d="M58,-64 q24,6 26,36" stroke="#2a1408" stroke-width="9" fill="none" stroke-linecap="round"/>
    <g transform="translate(5,-62) scale(.8)">${person({shirt:'#1e5bb8',pants:'#1e5bb8',skin:'#e0b080',hair:'#2a1408',mo:'grin',extra:'<path d="M-30,-120 q30,-40 60,0z" fill="#8a5a2b"/><rect x="-32" y="-124" width="64" height="12" rx="6" fill="#f5f0e0"/><path d="M-14,-100 q14,-6 28,0" stroke="#2a1408" stroke-width="5" fill="none" stroke-linecap="round"/>'})}</g></g>`;
  case 'magnet':return `<path d="M-30,-80 L-50,-6 L40,-6 L30,-80z" fill="#6a1b9a"/>${person({shirt:'#555a7a',pants:'#333',skin:'#bfc6d6',hair:'#333',mo:'mad',extra:'<rect x="-22" y="-120" width="44" height="12" rx="6" fill="#ff3b3b"/>'})}
    <g transform="translate(40,-120)"><path d="M-22,0 v-20 a22,22 0 0 1 44,0 v20 h-12 v-20 a10,10 0 0 0 -20,0 v20z" fill="#ff3b3b"/><rect x="-22" y="0" width="12" height="10" fill="#ddd"/><rect x="10" y="0" width="12" height="10" fill="#ddd"/></g><path d="M20,-70 L36,-108" stroke="#bfc6d6" stroke-width="10" stroke-linecap="round"/>`;
  case 'narwhal':return `<ellipse cx="10" cy="-60" rx="80" ry="48" fill="#6f8fb0"/><ellipse cx="10" cy="-40" rx="62" ry="24" fill="#cfe3f5"/><path d="M84,-70 q30,-30 26,10 q20,-10 8,24 q-14,-10 -30,-14z" fill="#6f8fb0"/>
    <path d="M-64,-78 L-150,-110 L-62,-66z" fill="#fff8e0"/><path d="M-80,-80 l-4,8 M-100,-88 l-4,8 M-120,-95 l-4,8" stroke="#d9c89a" stroke-width="3"/>
    <circle cx="-38" cy="-74" r="9" fill="#fff"/><circle cx="-40" cy="-73" r="4.5" fill="#111"/><path d="M-50,-50 q14,10 28,0" stroke="#2a3a55" stroke-width="3.5" fill="none" stroke-linecap="round"/>
    <circle cx="20" cy="-90" r="5" fill="#5a7898"/><circle cx="40" cy="-80" r="4" fill="#5a7898"/><circle cx="0" cy="-96" r="3" fill="#5a7898"/>
    <path d="M-110,0 q20,-14 40,0 t40,0 t40,0 t40,0 t40,0 v10 h-200z" fill="#3ee0ff" opacity=".8"/>`;
  }
}
function sceneSVG(H,heroW,sw,opt={}){
  const m=M[H-1],id='s'+H+(opt.k||'');
  return `<svg viewBox="0 -60 400 310" aria-label="${m.name}">${DEFS}<defs><linearGradient id="${id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${m.sky[0]}"/><stop offset="1" stop-color="${m.sky[1]}"/></linearGradient></defs>
  <rect y="-60" width="400" height="310" fill="url(#${id})"/><circle cx="340" cy="46" r="26" fill="#fff" opacity=".35"/><circle cx="60" cy="60" r="14" fill="#fff" opacity=".25"/>
  <rect y="210" width="400" height="40" fill="${m.gr}"/><path d="M0,210 q50,-12 100,0 t100,0 t100,0 t100,0" fill="${m.gr}"/>
  ${opt.hero2?`<g transform="translate(34,214) scale(.6)">${heroG(opt.hero2,SW[H-1][1])}</g>`:''}${opt.hero?`<g transform="translate(${opt.hero2?110:80},214) scale(.78)"><g id="heroA" data-s="transform-box:fill-box">${heroG(heroW,sw)}</g></g>`:''}
  <g transform="translate(${opt.hero?290:200},214) scale(${opt.hero?.78:.95})"><g id="vil" data-s="transform-box:fill-box;transform-origin:center"><g class="${['penguins','beans'].includes(m.art)?'':'bob'}">${villainG(m.art)}</g></g></g></svg>`;
}
const STAR=on=>`<svg viewBox="0 0 24 24"><path d="M12 2l3 7 7 .6-5.4 4.7 1.7 7.2L12 17.8 5.7 21.5l1.7-7.2L2 9.6 9 9z" fill="${on?'#ffd23f':'#ffffff33'}" stroke="${on?'#c48a00':'none'}"/></svg>`;
const ICON={
 fruit:`<svg viewBox="0 0 30 30"><circle cx="15" cy="17" r="11" fill="#ff3b3b"/><path d="M15 7q1-4 4-5" stroke="#6b3a1f" stroke-width="2" fill="none"/><ellipse cx="20" cy="6" rx="4" ry="2" fill="#2fbf55"/></svg>`,
 muffin:`<svg viewBox="0 0 30 30"><path d="M6 15h18l-3 13H9z" fill="#c9a26b"/><path d="M2 16q0-11 13-11t13 11z" fill="#d08a3a"/><circle cx="11" cy="10" r="1.6" fill="#3a1c0c"/><circle cx="18" cy="12" r="1.6" fill="#3a1c0c"/></svg>`,
 donut:`<svg viewBox="0 0 30 30"><circle cx="15" cy="15" r="12" fill="#e0a060"/><circle cx="15" cy="15" r="10" fill="#ff6fb8"/><circle cx="15" cy="15" r="4" fill="#24124f"/><path d="M9 9l2 1M20 8l1 2M21 19l-2 1M9 20l2-1" stroke="#fff" stroke-width="1.6"/></svg>`,
 pretzel:`<svg viewBox="0 0 30 30"><path d="M8 25Q2 14 9 8q6-4 6 6 0-10 6-6 7 6 1 17M7 20q8-6 16 0" stroke="#a0612a" stroke-width="4" fill="none" stroke-linecap="round"/></svg>`
};
const SPK=on=>on?'<svg viewBox="0 0 24 24"><path d="M3 9h4l5-5v16l-5-5H3z" fill="#fff"/><path d="M15 8q3 4 0 8M18 5q6 7 0 14" stroke="#fff" stroke-width="2" fill="none"/></svg>':'<svg viewBox="0 0 24 24"><path d="M3 9h4l5-5v16l-5-5H3z" fill="#fff"/><path d="M16 9l6 6M22 9l-6 6" stroke="#fff" stroke-width="2"/></svg>';

/* ---------- helpers ---------- */
const $=s=>document.querySelector(s),app=$('#app');
const rnd=a=>a[Math.floor(Math.random()*a.length)];
const shuffle=a=>{for(let i=a.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[a[i],a[j]]=[a[j],a[i]];}return a;};
const hr=h=>((h-1+12)%12)+1;
const fmt=(h,m)=>`${hr(h)}:${String(m).padStart(2,'0')}`;
function say(h,m){return fmt(h,m);}
function modal(html,btns){
  const o=document.createElement('div');o.className='overlay';o.innerHTML=`<div class="modal" role="dialog">${html}<div class="row" data-s="margin-top:16px"></div></div>`;
  const r=o.querySelector('.row');btns.forEach(([t,cls,fn])=>{const b=document.createElement('button');b.className='btn '+cls;b.textContent=t;b.onclick=()=>{SFX.tap();o.remove();fn&&fn();};r.appendChild(b);});
  document.body.appendChild(o);r.querySelector('button').focus();if(window.__pad)window.__pad.lock=performance.now()+700;
}
/* ---------- words for the voice ---------- */
const ONES=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
const TENS=['','','twenty','thirty','forty','fifty','sixty'];
const W=n=>n<20?ONES[n]:TENS[Math.floor(n/10)]+(n%10?'-'+ONES[n%10]:'');
const cap=s=>s.charAt(0).toUpperCase()+s.slice(1);
function phrase(h,m){h=hr(h);if(m===0)return `${W(h)} o'clock`;return `${W(h)} ${m<10?'oh '+W(m):W(m)}`;}
const itIs=(h,m)=>`It is ${phrase(h,m)}.`;
const setTo=(h,m)=>`Set the clock to ${phrase(h,m)}.`;
const num=n=>cap(W(n))+'.';
/* ---------- voice: Kokoro "af_heart", one whole sentence per clip, played through Web Audio (plays on silent iPhones); device voice only if a clip is missing ---------- */
const clipName=line=>{let v=5381;for(let i=0;i<line.length;i++)v=(Math.imul(v,33)^line.charCodeAt(i))>>>0;return ('0000000'+v.toString(16)).slice(-8)+'.mp3';};
const CLIPS={},SAID=new Set();let vGain=null,vSrc=null,talkId=0;
function clip(line){
  if(!AC)return Promise.resolve(null);
  if(!(line in CLIPS))CLIPS[line]=fetch('v/'+clipName(line)).then(r=>{if(!r.ok)throw 0;return r.arrayBuffer();})
    .then(b=>new Promise((res,rej)=>AC.decodeAudioData(b,res,rej))).catch(()=>{delete CLIPS[line];return null;});
  return CLIPS[line];
}
function preload(lines){lines.forEach(l=>clip(l));}
function devSay(line){return new Promise(res=>{try{const u=new SpeechSynthesisUtterance(line);u.rate=.9;u.pitch=1.1;u.onend=res;u.onerror=res;speechSynthesis.speak(u);setTimeout(res,800+line.length*95);}catch(e){res();}});}
function playBuf(b){return new Promise(res=>{try{
  if(!vGain){vGain=AC.createGain();vGain.gain.value=1;vGain.connect(master);}
  const s=AC.createBufferSource();s.buffer=b;s.connect(vGain);vSrc=s;let done=false;const fin=()=>{if(!done){done=true;res();}};
  s.onended=fin;s.start();setTimeout(fin,b.duration*1000+250);}catch(e){res();}});}
function hush(){talkId++;try{if(vSrc)vSrc.stop();}catch(e){}vSrc=null;duck(false);try{speechSynthesis.cancel();}catch(e){}}
async function talk(...parts){
  parts=parts.flat().filter(Boolean);hush();const id=talkId;
  parts.forEach(p=>SAID.add(p));
  if(muted)return;
  for(let i=0;i<parts.length;i++){
    const line=parts[i];const b=await clip(line);if(id!==talkId)return;
    duck(true);if(b)await playBuf(b);else await devSay(line);
    if(id!==talkId)return;
    if(i<parts.length-1)await new Promise(r=>setTimeout(r,180));
  }
  duck(false);
}
function speak(t){talk(t);}

let G=null; // current game session
let timers=[];const later=(f,t)=>{const id=setTimeout(f,t);timers.push(id);return id;};
function clearT(){timers.forEach(clearTimeout);timers=[];if(raf)cancelAnimationFrame(raf);raf=0;LT++;hush();FREE=null;FREE_SAY=null;}
let raf=0;

/* ---------- screens ---------- */
function title(){
  clearT();
  app.innerHTML=`<section class="title center">
   <h1><span>Clock Knockout</span></h1>
   <p>Created and directed by two young players</p>
   <svg class="hero-clock" viewBox="0 0 300 300" aria-hidden="true">${DEFS}<circle cx="150" cy="150" r="140" fill="#ffd23f"/><circle cx="150" cy="150" r="126" fill="#fff"/>
    ${Array.from({length:12},(_,i)=>{const a=(i+1)*30*Math.PI/180;return `<text x="${150+Math.sin(a)*98}" y="${150-Math.cos(a)*98+11}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="30" fill="#2a1650">${i+1}</text>`}).join('')}
    <g class="spin2"><rect x="144" y="80" width="12" height="76" rx="6" fill="#ff3b3b" filter="url(#gl)"/></g>
    <g class="spin"><rect x="147" y="34" width="7" height="122" rx="3.5" fill="#00e0ff" filter="url(#gl)"/></g><circle cx="150" cy="150" r="11" fill="#2a1650"/></svg>
   <div class="row" data-s="margin-top:10px"><button class="btn cyan" id="learn">Learn the clock</button><button class="btn" id="p1">1 Player</button><button class="btn pink" id="p2">2 Players</button></div>
   ${SITE_LINKS?`<p class="note sitelinks">${SITE_LINKS}</p>`:''}
   <p class="note">Read the clock. Win light sabers. Knock out silly villains. Collect snacks from the chocolate river.<br>No sound? Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent.<br>Game controller (PS5 and others): D-pad or left stick moves, ✕ picks, ✕ is POW in battles, Options goes to the map. A second controller is player 2.</p>
  </section>`;
  if(PAD.on)setTimeout(()=>{const b=$(schoolDone()?'#p1':'#learn');b&&b.focus();},60);
  $('#p1').onclick=()=>{initAudio();SFX.saber();pickHero(1);};
  $('#learn').onclick=()=>{initAudio();SFX.saber();learn();};
  $('#p2').onclick=()=>{initAudio();SFX.saber();pickHero(2);};
}
function pickHero(n){
  let sel=P.hero||'Nova',coop=false;
  const draw=()=>{
    app.innerHTML=`<section class="center"><h2 data-s="font-size:40px;color:var(--sun);margin:14px 0">${n===1?'Pick your hero':'Player 1, pick your hero'}</h2>
    <div class="cards">${['Nova','Blaze'].map(w=>`<button class="pick ${sel===w?'on':''}" data-w="${w}"><svg viewBox="-70 -195 140 200">${DEFS}${heroG(w,w==='Nova'?'#ff4fd8':'#00e0ff')}</svg><b>${w}</b></button>`).join('')}</div>
    ${n===2?`<div class="row" data-s="margin:6px 0"><button class="btn ${coop?'ghost':'cyan'}" id="vs" data-s="font-size:22px">Versus</button><button class="btn ${coop?'cyan':'ghost'}" id="co" data-s="font-size:22px">Team up</button></div>
    <p>Player 2 plays as <b data-s="color:var(--cyan)">${sel==='Nova'?'Blaze':'Nova'}</b>. ${coop?'Take turns reading the clock, then fight side by side. Team points!':'Take turns. Most points wins!'}</p>`:''}
    <div class="row"><button class="btn" id="go">Let’s go!</button></div></section>`;
    app.querySelectorAll('.pick').forEach(b=>b.onclick=()=>{SFX.tap();sel=b.dataset.w;draw();});
    if(n===2){$('#vs').onclick=()=>{SFX.tap();coop=false;draw();};$('#co').onclick=()=>{SFX.tap();coop=true;draw();};}
    $('#go').onclick=()=>{SFX.saber();P.hero=sel;save();
      const other=sel==='Nova'?'Blaze':'Nova';
      G={mode:n,coop,pl:n===1?[{w:sel,pts:0}]:[{w:sel,pts:0},{w:other,pts:0}],turn:0};
      if(!schoolDone()){map();modal('<h2>New to clocks?</h2><p data-s="font-size:20px">Start in Clock School! Six short games teach the hour and the minutes with light sabers.</p>',[['Clock School','cyan',learn],['Missions','ghost',null]]);talk(T.newbie);}else map();};
  };draw();
}
function curSword(){const s=P.swords.length?Math.max(...P.swords):0;return s?SW[s-1][1]:'#ffffff';}
function map(){
  clearT();if(!G)G={mode:1,pl:[{w:P.hero,pts:0}],turn:0};
  const cx=200,cy=200,R=152,next=Math.min(P.unlocked,12);
  let b='';
  for(let h=1;h<=12;h++){const a=h*30*Math.PI/180,x=cx+Math.sin(a)*R,y=cy-Math.cos(a)*R,open=h<=P.unlocked,st=P.stars[h]||0;
    b+=`<g class="mb ${open?'':'lock'}" data-h="${h}" tabindex="0" role="button" aria-label="Mission ${h}: ${M[h-1].name}${open?'':' (locked)'}">
     <circle class="b" cx="${x}" cy="${y}" r="34" fill="${st?'#ffd23f':open?'#ff4fa2':'#5a4a8a'}" stroke="#fff" stroke-width="4"/>
     <text x="${x}" y="${y+12}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="34" fill="${st?'#3a1c00':'#fff'}">${h}</text>
     ${open?'':`<g transform="translate(${x+16},${y-26}) scale(.8)"><rect x="-9" y="0" width="18" height="14" rx="3" fill="#ffd23f"/><path d="M-5,0 v-5 a5,5 0 0 1 10,0 v5" stroke="#ffd23f" stroke-width="3" fill="none"/></g>`}
     ${st?`<text x="${x}" y="${y+5}" dy="-30" text-anchor="middle" font-size="15" fill="#ffd23f" font-family="Fredoka,sans-serif" font-weight="700">${'★'.repeat(st)}</text>`:''}</g>`;}
  const ha=next*30;
  app.innerHTML=`<div class="center" data-s="margin:6px 0 0"><h2 data-s="font-size:clamp(28px,6vw,42px);color:var(--sun)">The Clock World</h2><p data-s="margin:4px 0 0">Every hour is a mission. Tap a number!</p>
   <button class="btn cyan" id="toSchool" data-s="font-size:20px;min-height:50px;padding:6px 18px;margin-top:10px">Clock School${schoolDone()<LESSONS.length?` (${schoolDone()} of ${LESSONS.length})`:' ✓'}</button>
   ${P.unlocked<=12?`<button class="btn" id="playNext" data-s="font-size:26px;min-height:64px;margin:10px 0 0 10px">▶ Play mission ${next}</button>`:''}</div>
   <div class="stats">${G.pl.map((p,i)=>`<span class="chip">${p.w}: <b data-s="color:var(--sun)">${p.pts}</b> pts</span>`).join('')}
    <span class="chip">${ICON.fruit}${P.inv.fruit}</span><span class="chip">${ICON.muffin}${P.inv.muffin}</span><span class="chip">${ICON.donut}${P.inv.donut}</span><span class="chip">${ICON.pretzel}${P.inv.pretzel}</span></div>
   <svg class="map" viewBox="0 0 400 400">${DEFS}<circle cx="200" cy="200" r="196" fill="#ffd23f"/><circle cx="200" cy="200" r="184" fill="#3a1c7a"/><circle cx="200" cy="200" r="112" fill="#24124f"/>
    <g transform="rotate(${ha} 200 200)"><rect x="193" y="120" width="14" height="80" rx="7" fill="${blade(curSword())}" filter="url(#gl)"/></g>
    <circle cx="200" cy="200" r="12" fill="#ffd23f"/>
    <text x="200" y="250" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="18" fill="#fff">${P.unlocked>12?'Champion!':'Next: '+M[next-1].name}</text>${b}</svg>
   <div class="panel" data-s="margin-top:12px"><div class="center" data-s="margin-bottom:6px">Light saber collection: ${P.swords.length} of 12</div>
    <div class="rack">${SW.map((s,i)=>swordSVG(s[1],P.swords.includes(i+1))).join('')}</div>
    <div class="center" data-s="margin-top:10px">Saber power: <b data-s="color:var(--sun)">level ${P.lvl} of 3</b>${P.lvl<3?` <button class="btn cyan" id="upg" data-s="font-size:18px;min-height:48px;padding:6px 16px;margin:8px 0 0">Upgrade for ${(P.lvl+1)*8} snacks</button>`:' (max!)'}</div></div>
   <div class="strip" aria-hidden="true"><svg viewBox="0 0 800 110" preserveAspectRatio="xMidYMax slice"><rect y="96" width="800" height="14" fill="#6b3a1f"/>
    <g transform="translate(400,96) scale(.6)">${penguin(-330,1,'',0)}${bean(-200,'#8e5cff',0)}${penguin(-70,.85,'<rect x="-14" y="-118" width="28" height="12" rx="3" fill="#ff3b3b"/>',.2)}${bean(70,'#ff7a00',.3)}${penguin(200,.9,'<path d="M-14,-100 l10,4 M14,-100 l-10,4" stroke="#111" stroke-width="3"/>',.4)}${bean(330,'#2fbf8a',.5)}</g></svg></div>
   <p class="note">Progress saves on this device. Tap Restart at the top to start over.</p>`;
  if($('#upg'))$('#upg').onclick=upgrade;
  $('#toSchool').onclick=()=>{SFX.tap();school();};
  if($('#playNext'))$('#playNext').onclick=()=>{SFX.saber();startMission(next);};
  if(PAD.on)setTimeout(()=>{const g=app.querySelector(`.mb[data-h="${next}"]`);g&&g.focus();},60);
  app.querySelectorAll('.mb').forEach(g=>{const go=()=>{const h=+g.dataset.h;if(h>P.unlocked){SFX.no();return;}SFX.tap();startMission(h);};g.onclick=go;g.onkeydown=e=>{if(e.key==='Enter'||e.key===' ')go();};});
}
function minuteSet(H){
  if(H<=3)return [0,30];
  if(H<=6)return [0,15,30,45];
  const f=[];for(let m=0;m<60;m+=5)f.push(m);
  if(H<=9)return f;
  const any=[];for(let m=0;m<60;m++)if(m%5)any.push(m);return Math.random()<.5?any:f;
}
function makeQ(H,round,used){
  let set=minuteSet(H).filter(m=>!used.includes(m));if(!set.length)set=minuteSet(H);
  if(round===2){const hi=set.filter(m=>m>=40);if(hi.length)set=hi;}
  else if(round===0){const lo=set.filter(m=>m<20);if(lo.length)set=lo;}
  else{const mid=set.filter(m=>m>=20&&m<40);if(mid.length)set=mid;}
  const m=rnd(set),c=fmt(H,m),opts=new Set();
  opts.add(fmt(H+1,m));
  if(m>0&&m%5===0&&m/5!==H)opts.add(fmt(m/5,(H*5)%60));
  opts.add(fmt(H-1,m));
  opts.add(fmt(H,(m+30)%60));opts.add(fmt(H,(m+15)%60));
  opts.delete(c);
  const pick=shuffle([...opts]).slice(0,3);
  return {h:H,m,c,opts:shuffle([c,...pick])};
}
function startMission(H){
  G.H=H;G.round=0;G.used=[];G.first=0;G.unlockedNow=false;
  const m=M[H-1];
  app.innerHTML=`<div class="mhead"><h2>Mission ${H}: ${m.name}</h2></div><div class="scene">${sceneSVG(H,G.pl[G.turn].w,curSword(),{k:'i'})}<div class="bubble"><b>${m.v}</b><br>${m.intro}</div></div>
  <p class="rule">Read the clock to get your light saber. The minutes pick your challenge!</p>
  <div class="row" data-s="margin-top:12px"><button class="btn" id="go">Start mission</button><button class="btn ghost" id="back">Map</button></div>`;
  talk(`Mission ${W(H)}.`,m.name+'.',m.intro);
  if(PAD.on)setTimeout(()=>{const b=$('#go');b&&b.focus();},60);
  $('#go').onclick=()=>{SFX.saber();question();};$('#back').onclick=()=>{SFX.tap();map();};
}
function dotsHTML(){return `<div class="dots">${[0,1,2].map(i=>`<i class="${i<G.round?'done':i===G.round?'now':''}"></i>`).join('')}</div>`;}
function turnHTML(){return G.mode===2?`<span class="turn">${G.pl[G.turn].w}’s turn</span>`:'';}
function challengeOf(m,round){if(round===2)return 'boss';if(m<20)return 'battle';if(m<40)return 'collect';return 'super';}
const CH={battle:'Knockout battle!',collect:'Chocolate river snack hunt!',super:'Super power battle!',boss:'Boss knockout!'};
function question(){
  clearT();
  const H=G.H,q=makeQ(H,G.round,G.used);G.q=q;G.tries=0;G.done=false;G.guiding=false;G.acDone=false;G.used.push(q.m);
  if(H>=7&&G.round===1)return setClock(q);
  const hint=H<=2;
  app.innerHTML=`<div class="mhead"><h2>Mission ${H}</h2>${turnHTML()}${dotsHTML()}</div>
  <div class="qgrid"><div class="clockbox"><div id="clk">${clockSVG(q.h,q.m,hint)}</div>
   <div class="legend"><span><i data-s="background:#e8264a"></i>Short red saber = hour</span><span><i data-s="background:#1f7fe0"></i>Long blue saber = minutes</span></div></div>
   <div><div class="ask big">What time is it?</div><p class="gcap" id="gcap" aria-live="polite" hidden></p>
   <div class="ans">${q.opts.map(o=>`<button data-o="${o}" aria-label="${o}">${o}</button>`).join('')}</div>
   <div class="row" data-s="margin-top:14px"><button class="btn cyan" id="hint">Show me how</button></div>
   <div class="fb" id="fb" aria-live="polite"></div></div></div>`;
  talk(H<=6?T.whatHelp:T.what);
  $('#hint').onclick=()=>{SFX.boing();G.tries=Math.max(G.tries,1);guide(q);};
  app.querySelectorAll('.ans button').forEach(b=>b.onclick=()=>answer(b));
  PAD.lock=performance.now()+700;if(PAD.on)setTimeout(()=>{const b=app.querySelector('.ans button');b&&b.focus();},60);
}
/* "Show me how": reads this clock step by step, out loud, on the clock itself */
async function guide(q){
  if(G.guiding||G.done)return;G.guiding=true;const tok=++LT;
  const ans=[...app.querySelectorAll('.ans button')];ans.forEach(b=>b.disabled=true);
  const show=(m,o)=>{const c=$('#clk');if(c)c.innerHTML=clockSVG(q.h,m,o);};
  const gc=t=>{const e=$('#gcap');if(e){e.textContent=t;e.hidden=false;}};
  const h=hr(q.h),past=q.m>=30;
  try{
    $('#clk').scrollIntoView({block:'nearest',behavior:'smooth'});
    show(q.m,{ringH:h,flash:'h'});gc(past?`The short red saber is just past ${h}. The hour is ${h}.`:`The short red saber points to ${h}. The hour is ${h}.`);
    await talk(past?`The short red saber is just past ${W(h)}.`:`The short red saber points to ${W(h)}.`,`The hour is ${W(h)}.`);chk(tok);
    if(q.m===0){show(0,{ringM:12,flash:'m'});gc('The long blue saber points straight up to 12. That means o’clock.');await talk(T.upTop);chk(tok);}
    else{
      show(0,{hint:true,flash:'m'});gc('Now count the long blue saber by fives.');await talk(T.countLong);chk(tok);
      const f=Math.floor(q.m/5)*5;
      for(let k=5;k<=f;k+=5){show(k,{hint:true,ringM:k/5===12?12:k/5});gc(String(k));chime(k/5-1);await talk(num(k));chk(tok);}
      if(q.m>f){gc(`${f}, then little steps`);await talk(T.littleSteps);chk(tok);
        for(let k=f+1;k<=q.m;k++){show(k,{hint:true,ones:true});gc(String(k));chime(11);await talk(num(k));chk(tok);}}
    }
    show(q.m,{hint:true,ringH:h});gc(`So it is ${q.c}.`);await talk(T.soItIs,itIs(h,q.m));chk(tok);
    gc(`Now tap ${q.c}!`);ans.forEach(b=>{if(b.dataset.o===q.c)b.classList.add('glow');});await talk(T.tapIt);
  }catch(e){}
  G.guiding=false;ans.forEach(b=>{if(!b.classList.contains('no'))b.disabled=false;});
  const g=ans.find(b=>b.dataset.o===q.c);if(g){try{g.scrollIntoView({block:'center',behavior:'smooth'});}catch(e){}if(PAD.on)g.focus();}
}
function answer(b){
  const q=G.q,o=b.dataset.o;if(b.classList.contains('no')||G.done||G.guiding)return;
  if(o===q.c){
    G.done=true;b.classList.add('yes');SFX.yes();
    const pts=G.tries===0?100:50;G.pl[G.turn].pts+=pts;P.points+=pts;if(G.tries===0)G.first++;
    $('#fb').textContent=`YES! It is ${say(q.h,q.m)}! +${pts} points`;
    const go=()=>{if(G.q!==q||G.acDone)return;G.acDone=true;afterCorrect();};
    talk(cheer(),itIs(q.h,q.m)).then(()=>later(go,250));later(go,6000);
  }else{
    G.tries++;b.classList.add('no');b.disabled=true;SFX.no();
    $('#fb').textContent='Not that one. Let’s read the clock together!';
    talk(T.letsLook).then(()=>{if(G.q===q&&!G.done)guide(q);});
  }
}

function afterCorrect(){
  const H=G.H,first=!P.swords.includes(H)&&!G.unlockedNow,ch=challengeOf(G.q.m,G.round);
  const go=()=>{if(ch==='collect')collect();else battle(ch);};
  if(first){
    G.unlockedNow=true;P.swords.push(H);save();SFX.saber();
    modal(`<h2>Light saber unlocked!</h2>${swordSVG(SW[H-1][1]).replace('<svg','<svg class="sw"')}<p data-s="font-size:22px"><b>${SW[H-1][0]}</b></p><p>Minute ${G.q.m} → ${CH[ch]}</p>`,[['Fight!','',go]]);
  }else{
    modal(`<h2>${CH[ch]}</h2><p data-s="font-size:20px">Minute ${G.q.m} picked this challenge.</p>${ch==='super'?'<p>SUPER POWER: every hit counts double!</p>':''}`,[['Go!','',go]]);
  }
}
function battle(kind){
  clearT();
  const H=G.H,m=M[H-1],boss=kind==='boss',sup=kind==='super';
  let hp=4+Math.floor(H/3)+(boss?3:0)+(G.coop?4:0);const max=hp;let hits=0,over=false;const dmg=(sup?2:1)+P.lvl;
  app.innerHTML=`<div class="mhead"><h2>${boss?'BOSS: ':''}${m.v}</h2>${turnHTML()}${dotsHTML()}</div>
   <div class="arena scene" id="ar">${sceneSVG(H,G.pl[G.turn].w,SW[H-1][1],{hero:true,k:'b',hero2:G.coop?G.pl[1-G.turn].w:''})}<div class="bubble" id="vb">${rnd(m.lines)}</div></div>
   <div class="hp" aria-label="Villain energy"><div id="hpb" data-s="width:100%"></div></div>
   ${G.coop?`<div class="ans"><button class="btn pink hitme" id="hit" data-s="font-size:30px">${G.pl[0].w} POW!</button><button class="btn cyan hitme" id="hit2" data-s="font-size:30px">${G.pl[1].w} POW!</button></div>`:`<button class="btn pink hitme" id="hit">${sup?'SUPER ':''}POW!</button>`}<p class="rule">Tap POW or tap the villain as fast as you can!</p>`;
  if(sup||P.lvl)$('#heroA').classList.add('glowp');
  speak(rnd(m.lines));
  const ar=$('#ar'),vil=$('#vil'),hero=$('#heroA');
  const strike=e=>{
    if(over)return;hits++;
    hero.classList.remove('lunge');void hero.getBoundingClientRect();hero.classList.add('lunge');
    if(!sup&&hits%4===0&&Math.random()<.6){SFX.block();pop('BLOCKED!',e);$('#vb').textContent=rnd(m.lines);return;}
    SFX.pow();hp-=dmg;vil.classList.remove('hit');void vil.getBoundingClientRect();vil.classList.add('hit');
    pop(rnd(POWS),e);$('#hpb').style.width=Math.max(0,hp/max*100)+'%';
    if(hits%3===0)$('#vb').textContent=rnd(m.lines);
    if(hp<=0){over=true;vil.classList.remove('hit');vil.classList.add('ko');SFX.ko();$('#vb').textContent=m.ko;talk(T.knockout,m.ko);
      $('#hit').textContent='KNOCKOUT!';if($('#hit2'))$('#hit2').textContent='KNOCKOUT!';G.pl[G.turn].pts+=50;P.points+=50;const f=boss?3:1;P.inv.fruit+=f;save();
      later(()=>roundDone(`KNOCKOUT! +50 points and ${f} fruit${f>1?'s':''}.`),1700);}
  };
  const pop=(t,e)=>{const d=document.createElement('div');d.className='pow';d.textContent=t;const r=ar.getBoundingClientRect();
    let x=r.width*.62,y=r.height*.25;if(e&&e.clientX&&e.currentTarget===ar){x=e.clientX-r.left-40;y=e.clientY-r.top-40;}
    d.style.left=(x+Math.random()*40-20)+'px';d.style.top=(y+Math.random()*30-15)+'px';ar.appendChild(d);setTimeout(()=>d.remove(),800);};
  $('#hit').onclick=strike;if($('#hit2'))$('#hit2').onclick=strike;ar.addEventListener('pointerdown',strike);
}
const KINDS=[['fruit','apple'],['fruit','banana'],['fruit','orange'],['fruit','grapes'],['fruit','straw'],['fruit','melon'],['muffin','muffin'],['donut','donut'],['pretzel','pretzel']];
function drawItem(c,k,x,y,r){
  c.save();c.translate(x,y);c.lineCap='round';
  const circ=(cx,cy,rr,col)=>{c.fillStyle=col;c.beginPath();c.arc(cx,cy,rr,0,7);c.fill();};
  switch(k){
   case 'apple':circ(0,3,r,'#ff3b3b');c.strokeStyle='#6b3a1f';c.lineWidth=4;c.beginPath();c.moveTo(0,-r+4);c.lineTo(4,-r-8);c.stroke();c.fillStyle='#2fbf55';c.beginPath();c.ellipse(12,-r-6,9,4,-.4,0,7);c.fill();circ(-r*.4,-r*.2,r*.2,'#ffffff88');break;
   case 'banana':c.strokeStyle='#ffd23f';c.lineWidth=r*.7;c.beginPath();c.arc(0,-r*.6,r,0.3,Math.PI-.3);c.stroke();c.strokeStyle='#6b3a1f';c.lineWidth=4;c.beginPath();c.moveTo(r*.85,-r*.25);c.lineTo(r*1.05,-r*.35);c.stroke();break;
   case 'orange':circ(0,0,r,'#ff8a00');circ(0,-r+3,3,'#2fbf55');break;
   case 'grapes':[[0,-12],[-10,-2],[10,-2],[0,8],[-8,16],[8,16],[0,24]].forEach(([a,b])=>circ(a*r/28,b*r/28-4,r*.36,'#8e44ad'));break;
   case 'straw':c.fillStyle='#ff2d55';c.beginPath();c.moveTo(-r,-r*.4);c.quadraticCurveTo(0,-r*1.1,r,-r*.4);c.quadraticCurveTo(r*.6,r,0,r*1.1);c.quadraticCurveTo(-r*.6,r,-r,-r*.4);c.fill();c.fillStyle='#ffe';for(let i=0;i<6;i++){c.fillRect(-r*.5+(i%3)*r*.45,-r*.1+Math.floor(i/3)*r*.5,3,4);}c.fillStyle='#2fbf55';c.beginPath();c.ellipse(0,-r*.75,r*.6,r*.2,0,0,7);c.fill();break;
   case 'melon':c.fillStyle='#2fbf55';c.beginPath();c.arc(0,-r*.3,r*1.1,0,Math.PI);c.fill();c.fillStyle='#ff4f6d';c.beginPath();c.arc(0,-r*.3,r*.9,0,Math.PI);c.fill();c.fillStyle='#222';[-.4,0,.4].forEach(a=>c.fillRect(a*r-2,0,4,6));break;
   case 'muffin':c.fillStyle='#c9a26b';c.beginPath();c.moveTo(-r*.8,0);c.lineTo(r*.8,0);c.lineTo(r*.55,r);c.lineTo(-r*.55,r);c.fill();c.fillStyle='#d08a3a';c.beginPath();c.ellipse(0,0,r*1.1,r*.75,0,Math.PI,0);c.fill();c.strokeStyle='#a87e48';c.lineWidth=2;for(let i=-2;i<=2;i++){c.beginPath();c.moveTo(i*r*.25,2);c.lineTo(i*r*.18,r);c.stroke();}circ(-r*.35,-r*.4,3.5,'#3a1c0c');circ(r*.3,-r*.5,3.5,'#3a1c0c');circ(0,-r*.15,3.5,'#3a1c0c');break;
   case 'donut':c.fillStyle='#e0a060';c.beginPath();c.arc(0,0,r,0,7);c.arc(0,0,r*.36,0,7,true);c.fill('evenodd');c.fillStyle='#ff6fb8';c.beginPath();c.arc(0,0,r*.85,0,7);c.arc(0,0,r*.4,0,7,true);c.fill('evenodd');c.strokeStyle='#fff';c.lineWidth=3;[[.6,0],[-.5,.3],[0,-.6],[.2,.62],[-.55,-.4]].forEach(([a,b])=>{c.beginPath();c.moveTo(a*r,b*r);c.lineTo(a*r+5,b*r+3);c.stroke();});break;
   case 'pretzel':c.strokeStyle='#a0612a';c.lineWidth=r*.32;c.beginPath();c.moveTo(-r*.5,r*.9);c.quadraticCurveTo(-r*1.3,-r*.2,-r*.5,-r*.8);c.quadraticCurveTo(0,-r*1.1,0,-r*.1);c.quadraticCurveTo(0,-r*1.1,r*.5,-r*.8);c.quadraticCurveTo(r*1.3,-r*.2,r*.5,r*.9);c.moveTo(-r*.7,r*.3);c.lineTo(r*.7,r*.3);c.stroke();circ(-r*.4,-r*.5,2,'#fff');circ(r*.4,-r*.3,2,'#fff');break;
  }
  c.restore();
}
function collect(){
  clearT();
  const H=G.H;let got={fruit:0,muffin:0,donut:0,pretzel:0},n=0,left=12,items=[],t0=performance.now(),last=0,over=false;
  app.innerHTML=`<div class="mhead"><h2>Chocolate River!</h2>${turnHTML()}${dotsHTML()}</div>
   <div class="stats"><span class="chip">Time: <b id="tl">12</b></span><span class="chip">${ICON.fruit}<b id="cf">0</b></span><span class="chip">${ICON.muffin}<b id="cm">0</b></span><span class="chip">${ICON.donut}<b id="cd">0</b></span><span class="chip">${ICON.pretzel}<b id="cp">0</b></span></div>
   <canvas id="cv" aria-label="Chocolate river. Tap the snacks."></canvas><p class="rule">Tap the fruits, muffins, donuts and pretzels before they float away!</p>`;
  talk(T.snacks);
  const cv=$('#cv'),c=cv.getContext('2d');let W=0,Hh=0;
  const size=()=>{const r=cv.getBoundingClientRect(),d=Math.min(2,window.devicePixelRatio||1);W=r.width;Hh=r.height;cv.width=W*d;cv.height=Hh*d;c.setTransform(d,0,0,d,0,0);};size();
  const ro=new ResizeObserver(size);ro.observe(cv);
  const spawn=()=>{const [cat,k]=rnd(KINDS);items.push({cat,k,x:-40,y:70+Math.random()*(Hh-120),v:45+Math.random()*35+H*3,ph:Math.random()*6,r:32,got:0});};
  const grabAt=(x,y,rad,pi)=>{if(over)return;
    for(const it of items){if(!it.got&&Math.hypot(it.x-x,it.y-y)<it.r+rad){it.got=1;got[it.cat]++;n++;SFX.grab();if(pi!==undefined)rumble(pi,60,.4);
      $('#cf').textContent=got.fruit;$('#cm').textContent=got.muffin;$('#cd').textContent=got.donut;$('#cp').textContent=got.pretzel;break;}}};
  cv.addEventListener('pointerdown',e=>{const r=cv.getBoundingClientRect();grabAt(e.clientX-r.left,e.clientY-r.top,40);});
  const curs=[{x:0,y:0,s:0},{x:0,y:0,s:0}];curs.forEach((c,i)=>{c.x=W*(i?.62:.38);c.y=Hh/2;c.s=PAD.hits[i]||0;});
  const c2=(k,i)=>{c.strokeStyle=i?'#3ee0ff':'#ffd23f';c.lineWidth=5;c.beginPath();c.arc(k.x,k.y,30,0,7);c.stroke();c.beginPath();c.moveTo(k.x-40,k.y);c.lineTo(k.x-22,k.y);c.moveTo(k.x+22,k.y);c.lineTo(k.x+40,k.y);c.moveTo(k.x,k.y-40);c.lineTo(k.x,k.y-22);c.moveTo(k.x,k.y+22);c.lineTo(k.x,k.y+40);c.stroke();};
  const loop=t=>{
    const el=(t-t0)/1000,dt=Math.min(.05,(t-(last||t))/1000);last=t;
    if(!over&&t-(G.sp||0)>700){G.sp=t;spawn();}
    const g=c.createLinearGradient(0,0,0,Hh);g.addColorStop(0,'#ffb36b');g.addColorStop(.2,'#8a4a22');g.addColorStop(1,'#4a250f');c.fillStyle=g;c.fillRect(0,0,W,Hh);
    for(let w=0;w<5;w++){c.strokeStyle=w%2?'#a0613a':'#5a2e12';c.lineWidth=6;c.beginPath();const y0=50+w*(Hh-40)/5;
      for(let x=0;x<=W;x+=12)c.lineTo(x,y0+Math.sin(x/40+el*2+w)*8);c.stroke();}
    items.forEach(it=>{if(it.got){it.r-=dt*60;it.y-=dt*200;}else it.x+=it.v*dt;
      if(it.r>2)drawItem(c,it.k,it.x,it.y+Math.sin(el*3+it.ph)*8,it.r);});
    items=items.filter(it=>it.x<W+60&&it.r>2);
    if(PAD.on)pads().slice(0,2).forEach((p,i)=>{const c=curs[i],dz=v=>Math.abs(v)<.18?0:v;
      c.x=Math.max(10,Math.min(W-10,c.x+dz(p.axes[0]||0)*460*dt));c.y=Math.max(10,Math.min(Hh-10,c.y+dz(p.axes[1]||0)*460*dt));
      if((PAD.hits[i]||0)>c.s){c.s=PAD.hits[i];grabAt(c.x,c.y,48,i);}
      c.lineWidth=5;c2(c,i);});
    const tl=Math.max(0,Math.ceil(12-el));if($('#tl'))$('#tl').textContent=tl;
    if(!over&&el>=12){over=true;ro.disconnect();
      Object.keys(got).forEach(k=>P.inv[k]+=got[k]);const pts=n*10;G.pl[G.turn].pts+=pts;P.points+=pts;save();
      later(()=>roundDone(`You grabbed ${n} snacks! +${pts} points.`),400);}
    if(!over||items.length)raf=requestAnimationFrame(loop);
  };raf=requestAnimationFrame(loop);
}
function roundDone(msg){
  clearT();G.round++;
  const fin=G.round>=3;
  if(!fin){
    if(G.mode===2)G.turn=1-G.turn;
    modal(`<h2>Great job!</h2><p data-s="font-size:20px">${msg}</p>${G.mode===2?`<p>Next turn: <b>${G.pl[G.turn].w}</b></p>`:''}`,[['Next clock','',question]]);
  }else{
    const H=G.H,st=Math.max(1,G.first);P.stars[H]=Math.max(P.stars[H]||0,st);if(P.unlocked<=H)P.unlocked=H+1;save();SFX.win();
    if(G.mode===2)G.turn=1-G.turn;
    const champ=H===12;
    const lead=G.mode===2?(G.pl[0].pts===G.pl[1].pts?'It is a tie!':`${(G.pl[0].pts>G.pl[1].pts?G.pl[0]:G.pl[1]).w} is winning!`):'';
    modal(`<h2>${champ?'CLOCK CHAMPION!':'Mission complete!'}</h2><div class="stars">${[1,2,3].map(i=>STAR(i<=st)).join('')}</div>
     <p data-s="font-size:19px">${msg}</p><p>${M[H-1].v} is knocked out!${H<12?` Mission ${H+1} is open.`:' You beat all 12 hours!'}</p>${lead?`<p><b>${lead}</b></p>`:''}`,
     H<12?[['Next mission','',()=>startMission(H+1)],['Map','ghost',map]]:[['Map','',map]]);
    speak(champ?'You are the clock champion!':'Mission complete!');
  }
}

function upgrade(){
  const cost=(P.lvl+1)*8,have=Object.values(P.inv).reduce((a,b)=>a+b,0);
  if(have<cost){SFX.no();modal(`<h2>Need more snacks!</h2><p data-s="font-size:19px">You have ${have}. You need ${cost}. Win snacks in the chocolate river and in battles.</p>`,[['OK','',null]]);return;}
  let left=cost;['fruit','pretzel','muffin','donut'].forEach(k=>{const t=Math.min(left,P.inv[k]);P.inv[k]-=t;left-=t;});
  P.lvl++;save();SFX.saber();
  modal(`<h2>Saber power up!</h2>${swordSVG(curSword()).replace('<svg','<svg class="sw"')}<p data-s="font-size:20px">Level ${P.lvl}! Every hit does ${1+P.lvl} damage now.</p>`,[['Awesome!','',map]]);
}
function setClock(q){
  let h=hr(q.h)===12?6:12,m=0;const fine=G.H>=10;
  app.innerHTML=`<div class="mhead"><h2>Mission ${G.H}</h2>${turnHTML()}${dotsHTML()}</div>
  <div class="qgrid"><div class="clockbox"><div id="clk">${clockSVG(h,m,true)}</div>
   <div class="legend"><span><i data-s="background:#e8264a"></i>Short red saber = hour</span><span><i data-s="background:#1f7fe0"></i>Long blue saber = minutes</span></div></div>
   <div><div class="ask big">Set the clock to ${q.c}!</div>
   <div class="ans"><button id="hm" aria-label="Hour back">Hour −</button><button id="hp" aria-label="Hour forward">Hour +</button>
   <button id="mm" aria-label="Minutes back">−${fine?1:5} min</button><button id="mp" aria-label="Minutes forward">+${fine?1:5} min</button></div>
   ${fine?`<div class="ans" data-s="margin-top:14px"><button id="mm5" aria-label="Minutes back 5">−5 min</button><button id="mp5" aria-label="Minutes forward 5">+5 min</button></div>`:''}
   <div class="row" data-s="margin-top:14px"><button class="btn" id="chk">Check!</button></div>
   <div class="fb" id="fb" aria-live="polite">Now it shows ${fmt(h,m)}</div></div></div>`;
  app.querySelectorAll('.ans button').forEach(b=>b.style.fontSize='28px');
  talk(setTo(q.h,q.m));
  PAD.lock=performance.now()+700;if(PAD.on)setTimeout(()=>{const b=$('#mp');b&&b.focus();},60);
  const upd=()=>{$('#clk').innerHTML=clockSVG(h,m,true);$('#fb').textContent='Now it shows '+fmt(h,m);SFX.tap();};
  const addM=d=>{m+=d;while(m>=60){m-=60;h=hr(h+1);}while(m<0){m+=60;h=hr(h-1);}upd();};
  $('#hp').onclick=()=>{h=hr(h+1);upd();};$('#hm').onclick=()=>{h=hr(h-1);upd();};
  $('#mp').onclick=()=>addM(fine?1:5);$('#mm').onclick=()=>addM(fine?-1:-5);
  if(fine){$('#mp5').onclick=()=>addM(5);$('#mm5').onclick=()=>addM(-5);}
  $('#chk').onclick=()=>{
    if(G.done)return;
    if(hr(h)===hr(q.h)&&m===q.m){G.done=true;SFX.yes();const pts=G.tries===0?150:75;G.pl[G.turn].pts+=pts;P.points+=pts;if(G.tries===0)G.first++;
      $('#fb').textContent=`PERFECT! ${say(q.h,q.m)}! +${pts} points`;talk(T.perfect,itIs(q.h,q.m));later(()=>{G.done=false;afterCorrect();},1300);}
    else{G.tries++;SFX.no();$('#fb').textContent=hr(h)!==hr(q.h)?`Check the short red saber. It should point at ${hr(q.h)}${q.m>=30?' (a little past it)':''}.`:`Hour is right! Now move the long blue saber to ${q.m} minutes.`;talk(hr(h)!==hr(q.h)?T.setHour:T.setMin);}
  };
}

/* ---------- game controllers: PS5 DualSense, Xbox, 8BitDo, Luna (standard mapping) ---------- */
const PAD={prev:[],rep:[],hits:[0,0],on:false,lock:0};
function pads(){try{return [...(navigator.getGamepads?navigator.getGamepads():[])].filter(p=>p&&p.connected!==false&&p.buttons);}catch(e){return [];}}
function rumble(i,ms=80,s=.6){try{const p=pads()[i],va=p&&p.vibrationActuator;if(va&&va.playEffect){const r=va.playEffect('dual-rumble',{duration:ms,strongMagnitude:s,weakMagnitude:Math.min(1,s+.2)});if(r&&r.catch)r.catch(()=>{});}}catch(e){}}
function toast(t){document.querySelectorAll('.toast').forEach(x=>x.remove());const d=document.createElement('div');d.className='toast';d.setAttribute('role','status');d.textContent=t;document.body.appendChild(d);setTimeout(()=>d.remove(),4000);}
addEventListener('gamepadconnected',()=>{toast(pads().length>=2?'Player 2 controller ready! ✕ is POW in battles.':'Controller ready! D-pad moves, ✕ picks, Options = map.');});
function clickEl(el){if(!el)return;if(el instanceof HTMLElement)el.click();else el.dispatchEvent(new MouseEvent('click',{bubbles:true}));}
function focusables(){
  const ov=document.querySelector('.overlay'),root=ov||app;
  return [...root.querySelectorAll('button:not([disabled]),a[href],[tabindex="0"]')].filter(el=>{const r=el.getBoundingClientRect();return r.width>0&&r.height>0;});
}
function moveFocus(dx,dy){
  const list=focusables();if(!list.length)return;const cur=document.activeElement;
  if(!list.includes(cur)){list[0].focus();return;}
  const a=cur.getBoundingClientRect(),ax=a.left+a.width/2,ay=a.top+a.height/2;let best=null,bs=1e9;
  for(const el of list){if(el===cur)continue;const b=el.getBoundingClientRect(),vx=b.left+b.width/2-ax,vy=b.top+b.height/2-ay,along=vx*dx+vy*dy;
    if(along<=6)continue;const sc=along+Math.abs(vx*dy-vy*dx)*2.2;if(sc<bs){bs=sc;best=el;}}
  if(best){best.focus();try{best.scrollIntoView({block:'nearest',behavior:'smooth'});}catch(e){}SFX.tap();}
}
function padCtx(){if(document.querySelector('.overlay'))return 'menu';if($('#hit'))return 'battle';if($('#cv'))return 'collect';return 'menu';}
function padLoop(t){
  pads().forEach((p,i)=>{
    const now={};[0,1,2,3,8,9,12,13,14,15].forEach(k=>now[k]=!!(p.buttons[k]&&p.buttons[k].pressed));
    const prev=PAD.prev[i]||{},edge=k=>now[k]&&!prev[k],ax=p.axes[0]||0,ay=p.axes[1]||0;
    const free=!!(FREE&&$('#dig')),mag=Math.hypot(ax,ay);
    if(free){if(mag>.6){FREE(ax,ay);PAD.fh=1;}else if(PAD.fh){PAD.fh=0;FREE_SAY&&FREE_SAY();}}
    const dir=(now[12]||(!free&&ay<-.55))?'u':(now[13]||(!free&&ay>.55))?'d':(now[14]||(!free&&ax<-.55))?'l':(now[15]||(!free&&ax>.55))?'r':'';
    const any=[0,1,2,3,9].some(edge);
    if(any||dir){if(!PAD.on){PAD.on=true;document.body.classList.add('pad');}if(any)initAudio();}
    const ctx=padCtx(),act=edge(0)||edge(1)||edge(2);
    if(edge(9)){clickEl($('#bHome'));}
    else if(ctx==='battle'){if(act||edge(3)){clickEl(G&&G.coop?($(i===0?'#hit':'#hit2')||$('#hit')):$('#hit'));rumble(i,90,.7);}}
    else if(ctx==='collect'){if(act)PAD.hits[i]=(PAD.hits[i]||0)+1;}
    else{
      const r=PAD.rep[i]||{d:'',t:0,held:false};
      if(dir&&(dir!==r.d||t-r.t>(r.held?160:420))){moveFocus(dir==='l'?-1:dir==='r'?1:0,dir==='u'?-1:dir==='d'?1:0);PAD.rep[i]={d:dir,t,held:dir===r.d};}
      else if(!dir)PAD.rep[i]={d:'',t:0,held:false};
      if(edge(0)&&t>PAD.lock){const el=document.activeElement;if(el&&focusables().includes(el))clickEl(el);else{const f=focusables()[0];if(f)f.focus();}}
      if(edge(3)&&$('#hint'))clickEl($('#hint'));
      if(edge(1)&&$('#back'))clickEl($('#back'));
    }
    PAD.prev[i]=now;
  });
  requestAnimationFrame(padLoop);
}
requestAnimationFrame(padLoop);
document.addEventListener('pointerdown',()=>{if(PAD.on){PAD.on=false;document.body.classList.remove('pad');}},{passive:true});
window.__pad=PAD;window.__G=()=>G;
/* ---------- Clock School: learn the clock by playing (made for 4-year-olds: the voice leads, a hand shows where to tap) ---------- */
const LESSONS=[
 {id:'meet',name:'Meet the Sabers',blurb:'A clock has two light sabers.'},
 {id:'nums',name:'Number Hunt',blurb:'Light up the numbers, 1 to 12.'},
 {id:'hour',name:'The Short Saber',blurb:'The short red saber tells the hour.'},
 {id:'five',name:'Count by Fives',blurb:'The long blue saber counts minutes.'},
 {id:'mins',name:'Minute Missions',blurb:'Make 10, 20, 30, 45 minutes.'},
 {id:'ones',name:'Little Minutes',blurb:'Each tiny line is one minute.'},
 {id:'read',name:'Read It All',blurb:'Short saber first, then long saber.'}
];
const T={
 what:'What time is it?',whatHelp:'What time is it? Tap Show me how if you need help.',
 yes:'Yes!',again:'Try again!',perfect:'Perfect!',letsLook:"Not that one. Let's read the clock together!",
 countLong:'Now count the long blue saber by fives.',littleSteps:'Then little steps, one minute each.',
 upTop:"The long blue saber points straight up to twelve. That means o'clock.",
 soItIs:'So...',tapIt:'Now tap that time!',
 setHour:'Look at the short red saber. Is it pointing to the right hour?',setMin:'The hour is right! Now move the long blue saber.',
 knockout:'Knockout!',snacks:'Tap the snacks in the chocolate river!',missionDone:'Mission complete!',champ:'You are the clock champion!',
 school:'Welcome to Clock School! Tap the glowing lesson.',
 newbie:'New to clocks? Start in Clock School!',
 done:'Lesson done! You are amazing! Tap the big yellow button for the next lesson.',
 grad:'You finished Clock School! You can read a clock! Now go fight the villains!',
 meet1:'Look! This clock has two light sabers.',
 meet2:'The short red saber is the hour saber. It moves slowly.',
 meet3:'The long blue saber is the minute saber. It moves fast!',
 meet4:'Watch! The long saber runs all the way around the clock.',
 meet5:'And the short saber moved just one number. So slow!',
 tapShort:'Tap the short red saber!',tapLong:'Tap the long blue saber!',
 notShort:'That is the long blue saber. Find the short red one!',notLong:'That is the short red saber. Find the long blue one!',
 yesShort:'Yes! The short saber tells the hour.',yesLong:'Yes! The long saber tells the minutes.',
 meetDone:'Short saber: hour. Long saber: minutes. You got it!',
 n1:'This is a clock. The numbers go all the way around, like a circle.',
 n2:"Let's light them up! Tap the one.",
 nDone:'You lit up the whole clock! One to twelve, all the way around.',
 h1:'The short red saber tells the hour.',
 h2:"When the long blue saber points straight up, we say o'clock.",
 hWhere:'Where is the short red saber pointing? Tap that number.',
 hLook:'Look at the tip of the short red saber.',
 hDone:'Great job! Now you can read the hour!',
 f1:'The long blue saber counts the minutes.',
 f2:'Every number is five more minutes. Tap the numbers and count with me!',
 f60:'Sixty minutes! That is one whole hour.',
 fMove:"Look! The short saber moved to the next number. Now it is four o'clock.",
 fDone:'You counted by fives, all the way to sixty!',
 mHow:'Tap the number where the long saber should stop. We count by fives.',
 mDone:'Minute master! You can make minutes.',
 o1:'See the tiny lines between the numbers? Each tiny line is one minute.',
 o2:'Press plus five to jump five. Press plus one for one little step.',
 tooFar:"Oops, too far! Let's start again.",
 oDone:'Wow! You can count every single minute.',
 r1:"Let's read the whole time. First the short saber, then the long saber.",
 rShort:'First, the short red saber. Which number is it pointing to?',
 rClose:'Close! The short saber has not reached that number yet. Pick the number it just passed.',
 rLong:'Now the long blue saber. Tap the number it points to.',
 rLookLong:'Look at the tip of the long blue saber.',
 rDone:'You read the clock all by yourself! You are ready for the missions!',
 free:'This is the saber clock. Drag the long blue saber and listen.'
};
const MAKE_ONES=[3,7,12,23,38];
const PRAISE=['Yes!','Awesome!','Super job!','You got it!','Wow! Great job!','High five!','Woo-hoo!'];
const cheer=()=>rnd(PRAISE);
function allLines(){
  const s=new Set(Object.values(T));
  for(let n=0;n<=60;n++)s.add(num(n));
  for(let h=1;h<=12;h++)for(let m=0;m<60;m++)s.add(itIs(h,m));
  for(let h=7;h<=12;h++)for(let m=0;m<60;m++)if(h>=10||m%5===0)s.add(setTo(h,m));
  for(let n=1;n<=12;n++){
    s.add(`Tap number ${W(n)}.`);s.add(`Now tap number ${W(n)}.`);s.add(`Oops! Find number ${W(n)}.`);
    s.add(`Make it ${W(n)} o'clock! Tap number ${W(n)}.`);s.add(`Yes! ${cap(W(n))} o'clock!`);s.add(`Oops! That is ${W(n)} o'clock.`);
    s.add(`The short red saber points to ${W(n)}.`);s.add(`The short red saber is just past ${W(n)}.`);s.add(`The hour is ${W(n)}.`);s.add(`Yes! The hour is ${W(n)}.`);
    s.add(`Mission ${W(n)}.`);s.add(`That is ${W(n*5)} minutes.`);s.add(`Make ${W(n*5)} minutes!`);s.add(`Yes! ${cap(W(n*5))} minutes!`);s.add(`We need ${W(n*5)} minutes.`);
  }
  MAKE_ONES.forEach(m=>{s.add(`Make ${W(m)} minutes!`);s.add(`Yes! ${cap(W(m))} minutes!`);});
  PRAISE.forEach(x=>s.add(x));
  M.forEach(m=>{s.add(m.name+'.');s.add(m.intro);s.add(m.ko);m.lines.forEach(l=>s.add(l));});
  return [...s];
}
window.__lines=allLines;window.__said=()=>[...SAID];
let LT=0;const STOP='stop';
const chk=t=>{if(t!==LT)throw STOP;};
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
function schoolDone(){return LESSONS.filter(l=>P.school&&P.school[l.id]).length;}
function nextLesson(){const i=LESSONS.findIndex(l=>!(P.school&&P.school[l.id]));return i;}
function learn(){const i=nextLesson();if(i<0)school();else lesson(i);}
function school(){
  clearT();if(!P.school)P.school={};
  const nx=nextLesson();
  app.innerHTML=`<div class="center" data-s="margin:6px 0 10px"><h2 data-s="font-size:clamp(30px,6vw,46px);color:var(--sun)">Clock School</h2>
   <p data-s="margin:4px 0 0">Learn the clock by playing. Then go fight the villains!</p></div>
   <div class="lessons">${LESSONS.map((l,i)=>`<button class="lesson ${P.school[l.id]?'done':''} ${nx===i?'next':''}" data-l="${i}">
     <span class="ln">${i+1}</span><span class="lt"><b>${l.name}</b><small>${l.blurb}</small></span>${P.school[l.id]?STAR(true):''}</button>`).join('')}
    <button class="lesson free" id="freeBtn"><span class="ln">∞</span><span class="lt"><b>Saber Clock</b><small>Free play: drag the sabers and hear the time.</small></span></button></div>
   <div class="row" data-s="margin-top:16px"><button class="btn" id="toMissions">Go to the missions</button></div>
   <p class="note">Clock School: ${schoolDone()} of ${LESSONS.length} lessons done.</p>`;
  app.querySelectorAll('.lesson[data-l]').forEach(b=>b.onclick=()=>{initAudio();SFX.saber();lesson(+b.dataset.l);});
  $('#freeBtn').onclick=()=>{initAudio();SFX.saber();freePlay();};
  $('#toMissions').onclick=()=>{initAudio();SFX.tap();if(!G)G={mode:1,pl:[{w:P.hero||'Nova',pts:0}],turn:0};map();};
  if(PAD.on)setTimeout(()=>{const b=app.querySelector('.lesson.next')||app.querySelector('.lesson');b&&b.focus();},60);
  talk(T.school);
}
/* the lesson clock: light-saber hands, a light trail for the minutes, big tap targets, and a pointing hand */
function slice(n){const a0=(n*30-15)*Math.PI/180,a1=(n*30+15)*Math.PI/180,R=172,r=22,P=(a,rr)=>`${(150+Math.sin(a)*rr).toFixed(1)},${(150-Math.cos(a)*rr).toFixed(1)}`;
  return `M${P(a0,r)} L${P(a0,R)} A${R},${R} 0 0 1 ${P(a1,R)} L${P(a1,r)} A${r},${r} 0 0 0 ${P(a0,r)} Z`;}
function lessonClock(){
  let s=`<svg viewBox="-20 -20 340 340" id="lcs" role="group" aria-label="Clock">${DEFS}<circle cx="150" cy="150" r="146" fill="#ffd23f"/><circle cx="150" cy="150" r="134" fill="#fff"/>
   <path id="trail" d="" fill="#3ee0ff" opacity=".3"/>`;
  for(let i=0;i<60;i++){const a=i*6*Math.PI/180,big=i%5===0,r1=big?116:121;
    s+=`<line class="${big?'':'tick'}" x1="${150+Math.sin(a)*r1}" y1="${150-Math.cos(a)*r1}" x2="${150+Math.sin(a)*129}" y2="${150-Math.cos(a)*129}" stroke="${big?'#2a1650':'#1f7fe0'}" stroke-opacity="${big?1:.55}" stroke-width="${big?4:2.5}" stroke-linecap="round"/>`;
    if(!big)s+=`<text class="m1" data-i="${i}" x="${150+Math.sin(a)*145}" y="${150-Math.cos(a)*145+4}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="13" fill="#1f7fe0">${i}</text>`;}
  for(let n=1;n<=12;n++){const a=n*30*Math.PI/180,x=150+Math.sin(a)*94,y=150-Math.cos(a)*94;
    s+=`<text id="ml${n}" class="ml" x="${150+Math.sin(a)*156}" y="${150-Math.cos(a)*156+7}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="19" fill="#1f7fe0">${n*5}</text>
     <g class="nt" id="nt${n}" data-n="${n}" tabindex="0" role="button" aria-label="${n}"><path d="${slice(n)}" fill="#fff" opacity="0"/><circle class="ring" cx="${x}" cy="${y}" r="24" fill="#fff3a8" stroke="#ff4fa2" stroke-width="5" opacity="0"/>
     <text class="num" x="${x}" y="${y+11}" text-anchor="middle" font-family="Fredoka,sans-serif" font-weight="700" font-size="32" fill="#e8264a">${n}</text></g>`;}
  s+=`<g id="hh" class="saber" data-hand="h" tabindex="0" role="button" aria-label="Short red saber"><rect class="hit" x="112" y="56" width="76" height="104" fill="#fff" opacity="0"/><rect x="144" y="132" width="12" height="26" rx="4" fill="#8d8fa3"/><rect x="141" y="128" width="18" height="6" rx="2" fill="#c9cbd8"/>
     <rect x="143" y="70" width="14" height="60" rx="7" fill="#e8264a" filter="url(#gl)"/><rect x="147" y="74" width="6" height="52" rx="3" fill="#ffd0d8"/></g>
   <g id="mh" class="saber" data-hand="m" tabindex="0" role="button" aria-label="Long blue saber"><rect class="hit" x="116" y="10" width="68" height="150" fill="#fff" opacity="0"/><rect x="146" y="128" width="8" height="30" rx="3" fill="#8d8fa3"/><rect x="143" y="124" width="14" height="6" rx="2" fill="#c9cbd8"/>
     <rect x="146" y="30" width="8" height="96" rx="4" fill="#1f7fe0" filter="url(#gl)"/><rect x="148.5" y="33" width="3" height="90" rx="1.5" fill="#d6f0ff"/></g>
   <circle cx="150" cy="150" r="10" fill="#2a1650"/><circle cx="150" cy="150" r="4" fill="#ffd23f"/>
   <g id="hand" class="hand" opacity="0"><g class="handbob"><path d="M0,0 l-9,-26 q-2,-7 5,-8 q6,-1 8,6 l5,15 l1,-14 q1,-7 8,-6 q6,1 6,8 l1,9 q3,-6 9,-3 q5,3 3,10 l-1,6 q5,-3 9,1 q4,4 0,11 l-8,20 q-5,12 -18,12 h-10 q-12,0 -16,-12z" fill="#fff" stroke="#2a1650" stroke-width="3" stroke-linejoin="round" transform="rotate(200) scale(.9)"/></g></g></svg>`;
  return s;
}
const L={h:12,m:0,showH:true,showM:true,dimH:false,trail:false,labels:false,wait:null};
function drawHands(){
  const s=$('#lcs');if(!s)return;
  const ha=((L.h%12)*30+L.m*.5),ma=(L.m%60)*6;
  $('#hh').setAttribute('transform',`rotate(${ha} 150 150)`);$('#mh').setAttribute('transform',`rotate(${ma} 150 150)`);
  $('#hh').style.display=L.showH?'':'none';$('#hh').style.opacity=L.dimH?'.35':'1';$('#mh').style.display=L.showM?'':'none';
  let d='';const mm=Math.min(L.m,60);
  if(L.trail&&mm>0){if(mm>=60)d='M150,16 A134,134 0 1 1 149.99,16 Z';else{const a=mm*6*Math.PI/180;d=`M150,150 L150,16 A134,134 0 ${mm>30?1:0} 1 ${150+Math.sin(a)*134},${150-Math.cos(a)*134} Z`;}}
  $('#trail').setAttribute('d',d);
  s.querySelectorAll('.ml').forEach((t,i)=>t.style.display=(L.labels===true||(typeof L.labels==='number'&&(i+1)*5<=L.labels))?'':'none');
  const mr=Math.round(L.m),f5=Math.floor(mr/5)*5;s.querySelectorAll('.m1').forEach(t=>{const i=+t.dataset.i;t.style.display=(L.trail&&i<=mr&&i>f5)?'':'none';});
}
async function sweep(to,ms,tok){
  const from=L.m,t0=performance.now();
  while(true){chk(tok);const k=Math.min(1,(performance.now()-t0)/ms),e=k<.5?2*k*k:1-Math.pow(-2*k+2,2)/2;
    L.m=from+(to-from)*e;drawHands();if(k>=1)break;await new Promise(r=>requestAnimationFrame(r));}
  L.m=to;drawHands();
}
async function swingHour(to,tok){const from=L.h,t0=performance.now();let d=((to-from)%12+12)%12;if(d>6)d-=12;
  while(true){chk(tok);const k=Math.min(1,(performance.now()-t0)/650),e=1-Math.pow(1-k,3);L.h=from+d*e;drawHands();if(k>=1)break;await new Promise(r=>requestAnimationFrame(r));}
  L.h=hr(Math.round(to));drawHands();}
function light(n,on=true){const g=$('#nt'+n);if(g)g.classList.toggle('lit',on);}
/* the hint: a yellow ring and a pointing hand on number n (0 hides them) */
function pulse(n){
  app.querySelectorAll('.nt.pulse').forEach(g=>g.classList.remove('pulse'));const hand=$('#hand');
  if(!n){if(hand)hand.setAttribute('opacity','0');return;}
  const g=$('#nt'+n);if(g)g.classList.add('pulse');
  if(hand){const a=n*30*Math.PI/180,x=150+Math.sin(a)*62,y=150-Math.cos(a)*62;hand.setAttribute('transform',`translate(${x},${y}) rotate(${n*30+180})`);hand.setAttribute('opacity','1');}
}
function pointSaber(which){const hand=$('#hand');if(!hand)return;
  if(!which){hand.setAttribute('opacity','0');return;}
  const ang=which==='h'?((L.h%12)*30+L.m*.5):(L.m%60)*6,r=which==='h'?70:95,a=ang*Math.PI/180;
  hand.setAttribute('transform',`translate(${150+Math.sin(a)*r+Math.cos(a)*30},${150-Math.cos(a)*r+Math.sin(a)*30}) rotate(${ang+90})`);hand.setAttribute('opacity','1');}
function capt(t,big){const c=$('#cap');if(c){c.textContent=t;c.classList.toggle('big',!!big);}}
/* wait for a tap on a number; every 7 s of waiting, say the ask again and show the hand */
function waitTap(tok,o={}){
  return new Promise(res=>{
    let iv=setInterval(()=>{if(tok!==LT){clearInterval(iv);return;}if(o.again)talk(o.again);if(o.hint)pulse(o.hint);},7000);
    L.wait=n=>{clearInterval(iv);L.wait=null;res(n);};
    if(PAD.on)setTimeout(()=>{const g=$('#nt'+(o.hint||12));g&&g.focus();},40);
  });
}
function waitSaber(tok,o={}){
  return new Promise(res=>{let iv=setInterval(()=>{if(tok!==LT){clearInterval(iv);return;}if(o.again)talk(o.again);if(o.hint)pointSaber(o.hint);},7000);
    L.waitS=w=>{clearInterval(iv);L.waitS=null;res(w);};});
}
function waitBtn(ids){return new Promise(res=>{ids.forEach(id=>{const b=$('#'+id);if(b)b.onclick=()=>{SFX.tap();res(id);};});
  if(PAD.on)setTimeout(()=>{const b=$('#'+ids[0]);b&&b.focus();},40);});}
function lessonFrame(i,extra=''){
  const l=LESSONS[i]||{name:'Saber Clock'};
  app.innerHTML=`<div class="mhead"><h2>${i>=0?`Lesson ${i+1}: `:''}${l.name}</h2><div class="dots" id="ldots"></div></div>
   <div class="lgrid"><div class="clockbox lclock">${lessonClock()}</div>
   <div class="lside"><div class="coach"><svg viewBox="-34 -138 68 70" aria-hidden="true">${DEFS}${heroG(P.hero||'Nova','#00e0ff')}</svg><p id="cap" aria-live="polite"></p></div>
   <div id="lctl" class="lctl">${extra}</div><div class="row"><button class="btn ghost" id="lback" data-s="font-size:20px;min-height:52px">All lessons</button></div></div></div>`;
  $('#lback').onclick=()=>{SFX.tap();school();};
  app.querySelectorAll('.nt').forEach(g=>{g.onclick=()=>{if(L.wait){SFX.tap();L.wait(+g.dataset.n);}};g.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();g.dispatchEvent(new MouseEvent('click',{bubbles:true}));}};});
  app.querySelectorAll('.saber').forEach(g=>{g.onclick=()=>{if(L.waitS){SFX.tap();L.waitS(g.dataset.hand);}};g.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();g.dispatchEvent(new MouseEvent('click',{bubbles:true}));}};});
  Object.assign(L,{h:12,m:0,showH:true,showM:true,dimH:false,trail:false,labels:false,wait:null,waitS:null});drawHands();
}
function dots(k,n){const d=$('#ldots');if(d)d.innerHTML=Array.from({length:n},(_,i)=>`<i class="${i<k?'done':i===k?'now':''}"></i>`).join('');}
async function lessonDone(i,tok){
  chk(tok);SFX.win();P.school[LESSONS[i].id]=1;P.inv.fruit+=3;save();pulse(0);
  const all=schoolDone()>=LESSONS.length,last=i>=LESSONS.length-1;
  modal(`<h2>${all?'Clock School graduate!':'Lesson done!'}</h2><div class="stars">${STAR(true)}${STAR(true)}${STAR(true)}</div><p data-s="font-size:20px">${LESSONS[i].name}: done! +3 fruit</p>`,
   last?[['Go to the missions!','',()=>{if(!G)G={mode:1,pl:[{w:P.hero||'Nova',pts:0}],turn:0};map();}],['Lessons','ghost',school]]
       :[['Next lesson ▶','',()=>lesson(i+1)],['Lessons','ghost',school]]);
  talk(all?T.grad:T.done);
}
function lesson(i){
  clearT();const tok=++LT;
  const run=[lessonMeet,lessonNums,lessonHour,lessonFive,lessonMins,lessonOnes,lessonRead][i];
  run(i,tok).catch(e=>{if(e!==STOP)console.error(e);});
}
async function tell(t,tok,...voice){capt(t);await talk(voice.length?voice:[t]);chk(tok);}
/* 0. Meet the Sabers */
async function lessonMeet(i,tok){
  lessonFrame(i);app.querySelector('#lcs').classList.add('tapsabers');L.h=3;L.m=0;drawHands();dots(0,4);
  preload([T.meet1,T.meet2,T.meet3,T.meet4,T.meet5,T.tapShort,T.tapLong,T.notShort,T.notLong,T.yesShort,T.yesLong,T.meetDone]);
  await tell(T.meet1,tok);
  $('#hh').classList.add('flash');pointSaber('h');await tell(T.meet2,tok);$('#hh').classList.remove('flash');
  $('#mh').classList.add('flash');pointSaber('m');await tell(T.meet3,tok);$('#mh').classList.remove('flash');pointSaber(0);
  capt(T.meet4);const run=talk(T.meet4);await sweep(60,4200,tok);await run;chk(tok);L.h=4;L.m=0;drawHands();
  $('#hh').classList.add('flash');await tell(T.meet5,tok);$('#hh').classList.remove('flash');
  const asks=['h','m','m','h'];
  for(let r=0;r<asks.length;r++){
    const want=asks[r],ask=want==='h'?T.tapShort:T.tapLong;capt(ask,true);talk(ask);
    while(true){const w=await waitSaber(tok,{again:ask,hint:want});chk(tok);pointSaber(0);
      if(w===want){SFX.yes();chime(r*2+3);const g=$(want==='h'?'#hh':'#mh');g.classList.add('flash');await tell(want==='h'?T.yesShort:T.yesLong,tok);g.classList.remove('flash');break;}
      SFX.no();await tell(want==='h'?T.notShort:T.notLong,tok);pointSaber(want);}
    dots(r+1,4);
  }
  await tell(T.meetDone,tok);await lessonDone(i,tok);
}
/* 1. Number Hunt */
async function lessonNums(i,tok){
  lessonFrame(i);L.showH=false;L.showM=false;drawHands();dots(0,12);
  preload([T.n1,T.n2,T.nDone,...Array.from({length:12},(_,k)=>num(k+1)),...Array.from({length:12},(_,k)=>`Now tap number ${W(k+1)}.`)]);
  await tell(T.n1,tok);pulse(1);capt(T.n2);talk(T.n2);
  for(let n=1;n<=12;n++){
    pulse(n);
    while(true){
      const x=await waitTap(tok,{again:`Tap number ${W(n)}.`,hint:n});chk(tok);
      if(x===n){pulse(0);light(n);chime(n-1);dots(n,12);capt(`${n}!`,true);await talk(num(n));chk(tok);break;}
      SFX.no();capt(`Oops! Find ${n}.`);pulse(n);await talk(`Oops! Find number ${W(n)}.`);chk(tok);
    }
    if(n<12){capt(`Now tap ${n+1}!`);pulse(n+1);talk(`Now tap number ${W(n+1)}.`);}
  }
  L.showM=true;L.showH=true;L.h=12;L.m=0;drawHands();
  await tell(T.nDone,tok);await lessonDone(i,tok);
}
/* 2. The Short Saber */
async function lessonHour(i,tok){
  lessonFrame(i);L.m=0;L.h=12;drawHands();dots(0,6);
  preload([T.h1,T.h2,T.hWhere,T.hLook,T.hDone]);
  $('#hh').classList.add('flash');pointSaber('h');await tell(T.h1,tok);$('#hh').classList.remove('flash');
  $('#mh').classList.add('flash');pointSaber('m');await tell(T.h2,tok);$('#mh').classList.remove('flash');pointSaber(0);
  const hs=shuffle([1,2,3,4,5,6,7,8,9,10,11]).slice(0,6);
  for(let r=0;r<3;r++){
    const n=hs[r],ask=`Make it ${W(n)} o'clock! Tap number ${W(n)}.`;capt(`Make it ${n} o'clock! Tap the ${n}.`);talk(ask);
    let miss=0;
    while(true){
      const x=await waitTap(tok,{again:ask,hint:n});chk(tok);pulse(0);SFX.saber();await swingHour(x,tok);
      if(x===n){SFX.yes();light(n);capt(`Yes! ${n} o'clock!`,true);await talk(`Yes! ${cap(W(n))} o'clock!`);chk(tok);light(n,false);break;}
      SFX.no();miss++;capt(`That is ${x} o'clock. Find ${n}!`);await talk(`Oops! That is ${W(x)} o'clock.`,`Tap number ${W(n)}.`);chk(tok);pulse(n);
    }
    dots(r+1,6);
  }
  for(let r=3;r<6;r++){
    const n=hs[r];SFX.saber();await swingHour(n,tok);$('#hh').classList.add('flash');capt(T.hWhere);talk(T.hWhere);
    let miss=0;
    while(true){
      const x=await waitTap(tok,{again:T.hWhere,hint:n});chk(tok);
      if(x===n){$('#hh').classList.remove('flash');pulse(0);SFX.yes();light(n);capt(`Yes! It is ${n} o'clock!`,true);await talk(cheer(),itIs(n,0));chk(tok);light(n,false);break;}
      SFX.no();miss++;pointSaber('h');await tell(T.hLook,tok);pointSaber(0);if(miss>=2)pulse(n);
    }
    dots(r+1,6);
  }
  await tell(T.hDone,tok);await lessonDone(i,tok);
}
/* 3. Count by Fives */
async function lessonFive(i,tok){
  lessonFrame(i);L.h=3;L.m=0;L.trail=true;L.labels=0;L.dimH=true;drawHands();dots(0,12);
  preload([T.f1,T.f2,T.f60,T.fMove,T.fDone,...Array.from({length:12},(_,k)=>num((k+1)*5))]);
  $('#mh').classList.add('flash');pointSaber('m');await tell(T.f1,tok);$('#mh').classList.remove('flash');pointSaber(0);
  pulse(1);capt(T.f2);talk(T.f2);
  for(let n=1;n<=12;n++){
    pulse(n);capt(`Tap ${n}!`);
    while(true){const x=await waitTap(tok,{again:`Tap number ${W(n)}.`,hint:n});chk(tok);if(x===n)break;SFX.no();await talk(`Oops! Find number ${W(n)}.`);chk(tok);pulse(n);}
    pulse(0);light(n);const go=sweep(n*5,420,tok);L.labels=n*5;chime(n-1);
    capt(`${n*5} minutes`,true);await talk(num(n*5));await go;chk(tok);dots(n,12);
  }
  await tell(T.f60,tok);L.dimH=false;L.h=4;L.m=0;L.labels=0;drawHands();
  for(let n=1;n<=12;n++)light(n,false);
  $('#hh').classList.add('flash');pointSaber('h');await tell(T.fMove,tok);$('#hh').classList.remove('flash');pointSaber(0);
  await tell(T.fDone,tok);await lessonDone(i,tok);
}
async function countTo(m,tok){
  L.m=0;drawHands();const f=Math.floor(m/5)*5;
  for(let k=5;k<=f;k+=5){const go=sweep(k,300,tok);capt(`${k}`,true);chime(k/5-1);await talk(num(k));await go;chk(tok);}
  for(let k=f+1;k<=m;k++){const go=sweep(k,200,tok);capt(`${k}`,true);chime(11);await talk(num(k));await go;chk(tok);}
}
/* 4. Minute Missions */
async function lessonMins(i,tok){
  lessonFrame(i);L.h=2;L.m=0;L.trail=true;L.labels=true;L.dimH=true;drawHands();
  const list=[10,20,30,15,45,50];dots(0,list.length);preload([T.mHow,T.again,T.mDone]);
  await tell(T.mHow,tok);
  for(let r=0;r<list.length;r++){
    const m=list[r],ask=`Make ${W(m)} minutes!`;L.labels=r<3?true:0;L.m=0;drawHands();
    capt(`Make ${m} minutes!`,true);talk(ask);
    let miss=0;
    while(true){
      const x=await waitTap(tok,{again:ask,hint:miss?m/5:0});chk(tok);pulse(0);await countTo(x*5,tok);
      if(x*5===m){SFX.yes();capt(`Yes! ${m} minutes!`,true);await talk(`Yes! ${cap(W(m))} minutes!`);chk(tok);break;}
      SFX.no();miss++;L.labels=true;drawHands();capt(`That is ${x*5} minutes. We need ${m}.`);
      await talk(`That is ${W(x*5)} minutes.`,`We need ${W(m)} minutes.`,T.again);chk(tok);pulse(m/5);
    }
    dots(r+1,list.length);
  }
  await tell(T.mDone,tok);await lessonDone(i,tok);
}
/* 5. Little Minutes */
async function lessonOnes(i,tok){
  lessonFrame(i,`<div class="ans"><button id="p5">+5</button><button id="p1m">+1</button></div><div class="mcount" id="mcount">0 minutes</div>`);
  app.querySelectorAll('#lctl .ans button').forEach(b=>b.style.fontSize='40px');
  L.h=6;L.m=0;L.trail=true;L.labels=true;L.dimH=true;drawHands();
  app.querySelectorAll('.tick').forEach(t=>t.classList.add('tickon'));
  dots(0,MAKE_ONES.length);preload([T.o1,T.o2,T.tooFar,T.oDone]);
  await tell(T.o1,tok);await tell(T.o2,tok);
  for(let r=0;r<MAKE_ONES.length;r++){
    const m=MAKE_ONES[r];L.m=0;drawHands();$('#mcount').textContent='0 minutes';
    capt(`Make ${m} minutes!`,true);await talk(`Make ${W(m)} minutes!`);chk(tok);
    while(L.m!==m){
      const b=await waitBtn(['p5','p1m']);chk(tok);const step=b==='p5'?5:1;const to=L.m+step;
      const go=sweep(to,step===5?350:220,tok);$('#mcount').textContent=`${to} minute${to===1?'':'s'}`;chime(step===5?Math.min(11,to/5):11);
      await talk(num(to));await go;chk(tok);
      if(L.m>m){SFX.no();await tell(T.tooFar,tok);L.m=0;drawHands();$('#mcount').textContent='0 minutes';}
    }
    SFX.yes();capt(`Yes! ${m} minutes!`,true);await talk(`Yes! ${cap(W(m))} minutes!`);chk(tok);dots(r+1,MAKE_ONES.length);
  }
  await tell(T.oDone,tok);await lessonDone(i,tok);
}
/* 6. Read It All */
async function lessonRead(i,tok){
  lessonFrame(i);L.trail=false;L.labels=0;drawHands();
  const qs=[[3,0],[3,20],[8,5],[10,30],[5,45]];dots(0,qs.length);
  preload([T.r1,T.rShort,T.rClose,T.rLong,T.rLookLong,T.hLook,T.soItIs,T.upTop,T.rDone]);
  await tell(T.r1,tok);
  for(let r=0;r<qs.length;r++){
    const [h,m]=qs[r];L.trail=false;L.labels=0;L.h=h;L.m=m;drawHands();SFX.saber();
    $('#hh').classList.add('flash');capt(T.rShort);talk(T.rShort);let miss=0;
    while(true){const x=await waitTap(tok,{again:T.rShort,hint:miss?h:0});chk(tok);
      if(x===h){pulse(0);SFX.yes();light(h);capt(`Yes! The hour is ${h}.`,true);await talk(`Yes! The hour is ${W(h)}.`);chk(tok);light(h,false);break;}
      SFX.no();miss++;if(x===hr(h+1)&&m>=30)await tell(T.rClose,tok);else{pointSaber('h');await tell(T.hLook,tok);pointSaber(0);}if(miss>=1)pulse(h);}
    $('#hh').classList.remove('flash');
    if(m===0){$('#mh').classList.add('flash');await tell(T.upTop,tok);$('#mh').classList.remove('flash');}
    else{
      $('#mh').classList.add('flash');capt(T.rLong);talk(T.rLong);miss=0;
      while(true){const x=await waitTap(tok,{again:T.rLong,hint:miss?m/5:0});chk(tok);
        if(x===m/5){pulse(0);$('#mh').classList.remove('flash');L.trail=true;L.labels=true;await countTo(m,tok);break;}
        SFX.no();miss++;pointSaber('m');await tell(T.rLookLong,tok);pointSaber(0);pulse(m/5);}
    }
    SFX.yes();capt(`${h}:${String(m).padStart(2,'0')}`,true);await talk(T.soItIs,itIs(h,m));chk(tok);await sleep(400);chk(tok);dots(r+1,qs.length);
  }
  await tell(T.rDone,tok);await lessonDone(i,tok);
}
/* Saber Clock: free play */
let FREE=null,FREE_SAY=null;
function freePlay(){
  clearT();const tok=++LT;
  lessonFrame(-1,`<div class="digital" id="dig">12:00</div><div class="ans"><button id="fm5">−5</button><button id="fp5">+5</button><button id="fm1">−1</button><button id="fp1">+1</button></div>
   <div class="row" data-s="margin-top:12px"><button class="btn cyan" id="fsay" data-s="font-size:20px;min-height:52px">Say the time</button><button class="btn pink" id="frnd" data-s="font-size:20px;min-height:52px">Surprise time</button></div>`);
  app.querySelectorAll('#lctl .ans button').forEach(b=>b.style.fontSize='34px');
  $('#ldots').innerHTML='';L.trail=true;L.labels=true;L.h=12;L.m=0;let tot=0;
  const hm=()=>[hr(Math.floor(tot/60)%12||12),tot%60];
  const show=()=>{const [h,m]=hm();L.h=h;L.m=m;drawHands();$('#dig').textContent=`${h}:${String(m).padStart(2,'0')}`;capt(say(h,m),true);};
  const sayIt=()=>{const [h,m]=hm();talk(itIs(h,m));};
  const add=d=>{tot=((tot+d)%720+720)%720;show();tone(d>0?880:660,.08,'sine',.1);};
  $('#fm5').onclick=()=>add(-5);$('#fp5').onclick=()=>add(5);$('#fm1').onclick=()=>add(-1);$('#fp1').onclick=()=>add(1);
  $('#fsay').onclick=()=>{SFX.tap();sayIt();};
  $('#frnd').onclick=()=>{SFX.boing();tot=(Math.floor(Math.random()*12)*60)+Math.floor(Math.random()*12)*5;show();sayIt();};
  const svg=$('#lcs');let drag=false;
  const toMin=(cx,cy)=>{const r=svg.getBoundingClientRect(),x=(cx-r.left)/r.width*340-20-150,y=(cy-r.top)/r.height*340-20-150;
    let a=Math.atan2(x,-y)*180/Math.PI;if(a<0)a+=360;return Math.round(a/6)%60;};
  const setMin=m2=>{const m=tot%60;let d=m2-m;if(d>30)d-=60;if(d<-30)d+=60;if(d){tot=((tot+d)%720+720)%720;show();}};
  svg.addEventListener('pointerdown',e=>{drag=true;try{svg.setPointerCapture(e.pointerId);}catch(_){}setMin(toMin(e.clientX,e.clientY));});
  svg.addEventListener('pointermove',e=>{if(drag)setMin(toMin(e.clientX,e.clientY));});
  const up=()=>{if(drag){drag=false;sayIt();}};svg.addEventListener('pointerup',up);svg.addEventListener('pointercancel',up);
  FREE=(ax,ay)=>{if(!$('#lcs'))return;let a=Math.atan2(ax,-ay)*180/Math.PI;if(a<0)a+=360;setMin(Math.round(a/6)%60);};FREE_SAY=sayIt;
  show();capt(T.free);talk(T.free);
}
window.__school={lesson,freePlay,school,L};

/* ---------- top bar ---------- */
function setMute(){$('#bMute').innerHTML=SPK(!muted);if(master)master.gain.value=muted?0:1;if(muted)try{speechSynthesis.cancel();}catch(e){}}
$('#bMute').onclick=()=>{initAudio();muted=!muted;save();setMute();SFX.tap();};
$('#bHome').onclick=()=>{SFX.tap();clearT();document.querySelectorAll('.overlay').forEach(o=>o.remove());G?map():title();};
$('#bRestart').onclick=()=>{modal('<h2>Start over?</h2><p>This clears all missions, light sabers and snacks on this device.</p>',[['Yes, restart','pink',()=>{P=fresh();G=null;save();title();}],['No','ghost',null]]);};
document.addEventListener('keydown',e=>{const b=app.querySelectorAll('.ans button')[+e.key-1];if(b)b.click();});
setMute();title();
}
index.html30 lines

Raw file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Clock Knockout: a free clock-reading game for kids</title>
<meta name="description" content="A free clock-reading game for kids, made with two young directors: learn the clock from zero, then read it to win light sabers and knock out silly villains.">
<meta name="theme-color" content="#24124f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Clock KO">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="manifest" href="./manifest.webmanifest">
<link rel="apple-touch-icon" href="./icon-180.png">
<link rel="icon" href="./icon-192.png" type="image/png" sizes="192x192">
<link rel="preload" href="../fonts/fredoka-700.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="./clock.css">
</head>
<body>
<div class="bar">
  <div class="logo">Clock Knockout</div>
  <button class="ib" id="bHome" aria-label="Home"><svg viewBox="0 0 24 24"><path d="M3 11 12 3l9 8v10h-6v-6H9v6H3z" fill="#fff"/></svg></button>
  <button class="ib" id="bMute" aria-label="Sound on or off"></button>
  <button class="ib" id="bRestart" aria-label="Restart">Restart</button>
</div>
<div id="app" role="main"></div>
<script src="./clock.js"></script>
</body>
</html>
clock.css (looks, layouts and animations)170 lines

Raw file

@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')}
/* VOICE: loud, silly, kind. A cartoon arcade made for two young directors.
   IDEA: a giant wall clock is the world map; each hour is a door to a mission.
   PICTURE: the clock and the cartoon arena fill the screen; characters bounce and dance.
   COLOUR and TYPE: candy-night purple ground, sunny yellow, bubblegum pink, glow cyan; Fredoka for titles and body.
   LAYOUT: one column, big touch targets, clock first, answers under it; two columns only on wide screens. */
:root{--bg:#24124f;--bg2:#3a1c7a;--ink:#fff;--sun:#ffd23f;--pink:#ff4fa2;--cyan:#3ee0ff;--choc:#6b3a1f;--card:#ffffff;--cardink:#2a1650;color-scheme:dark}
*{box-sizing:border-box;min-width:0;-webkit-tap-highlight-color:transparent}
html{background:#24124f;touch-action:manipulation}html,body{margin:0;min-height:100%}
body{background:radial-gradient(1200px 700px at 50% -10%,#6a2fd1 0,var(--bg2) 40%,var(--bg) 80%);background-attachment:fixed;color:var(--ink);font:600 17px/1.4 Fredoka,system-ui,sans-serif;overflow-x:clip;padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);user-select:none;-webkit-user-select:none}
h1,h2,h3,.big{font-family:Fredoka,system-ui,sans-serif;font-weight:700;letter-spacing:.5px;margin:0;line-height:1.05;text-wrap:balance}
button{font:inherit;color:inherit;border:0;cursor:pointer;touch-action:manipulation}
button:focus-visible,[tabindex]:focus-visible{outline:4px solid var(--cyan);outline-offset:3px}
.bar{display:flex;align-items:center;gap:8px;padding:10px max(3vw,10px);position:sticky;top:0;z-index:20;background:rgba(36,18,79,.85);backdrop-filter:blur(6px)}
.bar .logo{font-family:Fredoka;font-weight:700;font-size:20px;flex:1;color:var(--sun);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ib{min-width:48px;height:48px;border-radius:16px;background:rgba(255,255,255,.14);font-size:15px;padding:0 12px;display:inline-flex;align-items:center;justify-content:center;gap:6px}
.ib svg{width:24px;height:24px}
#app{max-width:1100px;margin:0 auto;padding:8px max(3vw,12px) 40px}
.btn{min-height:64px;padding:12px 26px;border-radius:22px;font-family:Fredoka;font-weight:700;font-size:26px;background:var(--sun);color:#3a1c00;box-shadow:0 6px 0 #c48a00,0 10px 24px rgba(0,0,0,.3);transition:transform .08s}
.btn:active{transform:translateY(4px);box-shadow:0 2px 0 #c48a00}
.btn.pink{background:var(--pink);color:#fff;box-shadow:0 6px 0 #b0216a,0 10px 24px rgba(0,0,0,.3)}
.btn.cyan{background:var(--cyan);color:#062a3a;box-shadow:0 6px 0 #0a8fb0,0 10px 24px rgba(0,0,0,.3)}
.btn.ghost{background:rgba(255,255,255,.16);color:#fff;box-shadow:0 6px 0 rgba(0,0,0,.25)}
.row{display:flex;flex-wrap:wrap;gap:14px;justify-content:center}
.center{text-align:center}
.title{padding:18px 0 6px}
.title h1{font-size:clamp(40px,9vw,84px);color:var(--sun);text-shadow:0 5px 0 #b0216a,0 10px 30px rgba(0,0,0,.4)}
.title h1 span{display:block;color:#fff;font-size:.62em;text-shadow:0 4px 0 #2b6cff}
.title p{font-size:19px;color:var(--cyan);margin:12px 0 0}
.hero-clock{width:min(78vw,340px);margin:10px auto 6px;display:block}
.spin{animation:spin 6s linear infinite;transform-box:view-box;transform-origin:150px 150px}
.spin2{animation:spin 72s linear infinite;transform-box:view-box;transform-origin:150px 150px}
@keyframes spin{to{transform:rotate(360deg)}}
.cards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;max-width:560px;margin:14px auto}
.pick{background:var(--card);color:var(--cardink);border-radius:24px;padding:12px;text-align:center;box-shadow:0 8px 0 rgba(0,0,0,.25);border:5px solid transparent}
.pick.on{border-color:var(--sun)}
.pick svg{width:100%;height:170px}
.pick b{font-family:Fredoka;font-size:26px;font-weight:700}
.panel{background:rgba(255,255,255,.1);border-radius:26px;padding:14px}
.map{width:min(94vw,560px);display:block;margin:0 auto}
.mb{cursor:pointer}
.mb circle.b{transition:transform .15s;transform-box:fill-box;transform-origin:center}
.mb:hover circle.b{transform:scale(1.08)}
.lock{opacity:.55}
.stats{display:flex;flex-wrap:wrap;gap:10px;justify-content:center;margin:10px 0}
.chip{background:rgba(255,255,255,.14);border-radius:999px;padding:8px 14px;display:inline-flex;align-items:center;gap:6px;font-size:16px;white-space:nowrap}
.chip svg{width:26px;height:26px}
.rack{display:flex;flex-wrap:wrap;gap:3px;justify-content:center}
.rack svg{width:22px;height:64px}
.strip{height:110px;overflow:hidden;position:relative}
.strip svg{position:absolute;inset:0;width:100%;height:100%}
.mhead{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;margin:4px 0 10px}
.mhead h2{font-size:clamp(26px,5vw,38px);color:var(--sun)}
.dots{display:flex;gap:6px}
.dots i{width:18px;height:18px;border-radius:50%;background:rgba(255,255,255,.25);display:block}
.dots i.done{background:var(--sun)}.dots i.now{background:var(--cyan);box-shadow:0 0 0 4px rgba(62,224,255,.3)}
.qgrid{display:grid;grid-template-columns:minmax(0,1fr);gap:14px}
@media(min-width:820px){.qgrid{grid-template-columns:minmax(0,1.1fr) minmax(0,1fr);align-items:start}}
.clockbox{background:var(--card);border-radius:30px;padding:10px;box-shadow:0 10px 0 rgba(0,0,0,.25)}
.clockbox svg{width:100%;max-width:440px;display:block;margin:0 auto}
.ask{font-size:clamp(28px,5vw,40px);text-align:center;margin:4px 0 12px}
.ans{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.ans button{min-height:96px;border-radius:24px;background:#fff;color:var(--cardink);font-family:Fredoka;font-weight:700;font-size:clamp(34px,7vw,48px);box-shadow:0 7px 0 #b9a6e6;transition:transform .08s}
.ans button:active{transform:translateY(4px)}
.ans button.no{background:#ffd0d8;color:#a33;box-shadow:0 7px 0 #e59aa8;opacity:.6}
.ans button.yes{background:#9dffb0;box-shadow:0 7px 0 #2fbf55;animation:pop .5s}
@keyframes pop{50%{transform:scale(1.12)}}
.fb{min-height:54px;text-align:center;font-size:19px;margin:12px 0 0;color:var(--sun)}
.legend{display:flex;gap:10px;justify-content:center;flex-wrap:wrap;margin-top:8px;font-size:15px}
.legend span{display:inline-flex;align-items:center;gap:6px;color:var(--cardink)}
.legend i{display:inline-block;width:26px;height:8px;border-radius:4px}
.scene{border-radius:26px;overflow:hidden;position:relative;background:#000;box-shadow:0 10px 0 rgba(0,0,0,.25)}
.scene svg{display:block;width:100%;height:auto}
.bubble{position:absolute;top:8px;right:8px;max-width:66%;background:#fff;color:var(--cardink);border-radius:18px;padding:8px 12px;font-size:16px;box-shadow:0 4px 0 rgba(0,0,0,.2)}
.rule{font-size:15px;text-align:center;opacity:.9;margin:8px 0 0}
.arena{position:relative;touch-action:manipulation}
.pow{position:absolute;font-family:Fredoka;font-weight:700;font-size:44px;color:var(--sun);-webkit-text-stroke:2px #b0216a;pointer-events:none;animation:powup .8s forwards}
@keyframes powup{0%{transform:scale(.3) rotate(-10deg);opacity:1}40%{transform:scale(1.2) rotate(6deg)}100%{transform:translateY(-60px) scale(1);opacity:0}}
.hp{height:26px;border-radius:13px;background:rgba(0,0,0,.35);overflow:hidden;margin:10px 0}
.hp div{height:100%;background:linear-gradient(90deg,#ff4f6d,#ffd23f);transition:width .2s}
.hitme{width:100%;min-height:92px;font-size:44px;margin-top:6px}
.hit{animation:shake .3s}
@keyframes shake{25%{transform:translateX(12px) rotate(4deg)}75%{transform:translateX(-8px) rotate(-3deg)}}
.lunge{animation:lunge .25s}
@keyframes lunge{50%{transform:translateX(60px) rotate(8deg)}}
.ko{animation:ko 1.2s forwards}
@keyframes ko{to{transform:translate(260px,-300px) rotate(720deg) scale(.3);opacity:0}}
.bob{animation:bob 1.6s ease-in-out infinite}
@keyframes bob{50%{transform:translateY(-8px)}}
.dance{animation:dance .6s ease-in-out infinite alternate;transform-box:fill-box;transform-origin:50% 100%}
@keyframes dance{from{transform:rotate(-12deg) translateY(0)}to{transform:rotate(12deg) translateY(-14px)}}
.waddle{animation:waddle .5s ease-in-out infinite alternate;transform-box:fill-box;transform-origin:50% 100%}
@keyframes waddle{from{transform:rotate(-8deg)}to{transform:rotate(8deg)}}
.flick{animation:flick .25s steps(2) infinite}
@keyframes flick{50%{opacity:.6}}
.puff{animation:puff 2.4s ease-out infinite;transform-box:fill-box;transform-origin:center}
@keyframes puff{0%{transform:translate(0,0) scale(.5);opacity:.9}100%{transform:translate(20px,-90px) scale(2);opacity:0}}
.float{animation:float 2s ease-in-out infinite}
@keyframes float{0%{transform:translateY(0);opacity:1}100%{transform:translateY(-30px);opacity:0}}
.tug{animation:tug .7s ease-in-out infinite alternate}
@keyframes tug{from{transform:translateX(-10px)}to{transform:translateX(10px)}}
.run{animation:run 9s linear infinite}
@keyframes run{from{transform:translateX(-60px)}to{transform:translateX(1500px)}}
.glowp{filter:drop-shadow(0 0 10px #ffd23f)}
canvas{display:block;width:100%;height:300px;border-radius:26px;touch-action:none;box-shadow:0 10px 0 rgba(0,0,0,.25)}
.overlay{position:fixed;inset:0;background:rgba(20,8,50,.82);display:flex;align-items:center;justify-content:center;z-index:50;padding:20px}
.modal{background:var(--card);color:var(--cardink);border-radius:30px;padding:22px;max-width:440px;width:100%;text-align:center;animation:pop .5s}
.modal h2{font-size:36px;color:#b0216a;margin-bottom:6px}
.modal svg.sw{width:70px;height:200px;display:block;margin:0 auto}
.stars{font-size:0;display:flex;justify-content:center;gap:6px;margin:8px 0}
.stars svg{width:54px;height:54px}
.note{font-size:14px;opacity:.8;text-align:center;margin-top:18px;font-weight:700}
.turn{background:var(--pink);border-radius:999px;padding:6px 14px;font-size:16px;white-space:nowrap}
.toast{position:fixed;left:50%;bottom:calc(24px + env(safe-area-inset-bottom));transform:translateX(-50%);background:#fff;color:#2a1650;padding:12px 20px;border-radius:999px;z-index:60;font-weight:700;box-shadow:0 6px 20px rgba(0,0,0,.35);max-width:92vw;text-align:center}
.pad :focus{outline:5px solid #3ee0ff;outline-offset:4px}
.pad .mb:focus{outline:none}.pad .mb:focus circle.b{stroke:#3ee0ff;stroke-width:9}
.sitelinks a{color:var(--sun)}
.lessons{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:12px;max-width:900px;margin:0 auto}
.lesson{display:flex;align-items:center;gap:14px;text-align:left;background:rgba(255,255,255,.12);border-radius:22px;padding:12px 16px;min-height:78px;border:3px solid transparent}
.lesson .ln{flex:none;width:48px;height:48px;border-radius:50%;background:var(--cyan);color:#062a3a;font:700 26px/48px Fredoka,sans-serif;text-align:center}
.lesson .lt{flex:1;display:flex;flex-direction:column}.lesson b{font-size:21px}.lesson small{font-size:15px;opacity:.85;font-weight:600}
.lesson svg{width:34px;height:34px;flex:none}
.lesson.done .ln{background:var(--sun);color:#3a1c00}.lesson.next{border-color:var(--sun);animation:glowb 1.4s ease-in-out infinite alternate}
.lesson.free .ln{background:var(--pink);color:#fff}
@keyframes glowb{to{box-shadow:0 0 24px rgba(255,210,63,.55)}}
.lgrid{display:grid;grid-template-columns:minmax(0,1fr);gap:14px}
@media(min-width:820px){.lgrid{grid-template-columns:minmax(0,1.15fr) minmax(0,1fr);align-items:start}}
.lclock svg{width:100%;max-width:470px;display:block;margin:0 auto;touch-action:none}
.nt{cursor:pointer;outline:none}#hh,#mh,#trail,.ml,.m1{pointer-events:none}.nt .num{transition:fill .2s}
.nt.lit .num{fill:#ff4fa2;filter:url(#gl)}.nt.lit .ring{opacity:1;fill:#ffe7f3;stroke:#ff4fa2}
.nt:active .ring{opacity:1}
.nt.pulse .ring{opacity:1;animation:ring 1s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
@keyframes ring{50%{transform:scale(1.25);opacity:.4}}
.pad .nt:focus .ring{opacity:1;stroke:#3ee0ff;stroke-width:6}
.flash{animation:flash .7s ease-in-out infinite alternate}@keyframes flash{to{opacity:.45}}
.tickon{stroke:#1f7fe0;stroke-opacity:1;stroke-width:3.5}
.coach{display:flex;gap:10px;align-items:flex-start}.coach svg{flex:none;width:64px;height:66px;background:rgba(255,255,255,.12);border-radius:50%}
#cap{flex:1;margin:0;background:#fff;color:var(--cardink);border-radius:20px;padding:12px 16px;font-size:21px;min-height:64px;box-shadow:0 5px 0 rgba(0,0,0,.2)}
#cap.big{font-size:34px;text-align:center}
.lctl{margin:14px 0}.mcount,.digital{text-align:center;font:700 44px/1.1 Fredoka,sans-serif;color:var(--sun);margin:12px 0}
.digital{font-size:64px}

#clk,#lcs{scroll-margin-top:84px}
.modal .btn.ghost{background:#ece6ff;color:#2a1650;box-shadow:0 6px 0 #b9a6e6}
.gcap{background:#fff;color:var(--cardink);border-radius:20px;padding:12px 16px;font-size:22px;margin:0 0 12px;box-shadow:0 5px 0 rgba(0,0,0,.2);text-align:center}
.gcap[hidden]{display:none}
.ans button[disabled]{opacity:.55}
.ans button.glow{background:#fff3a8;box-shadow:0 0 0 6px #ffd23f,0 7px 0 #c48a00;animation:pop .8s ease-in-out infinite alternate}
#hint{font-size:24px}
.ringpulse{animation:ring 1s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
.hand{pointer-events:none;transition:opacity .2s}.handbob{animation:handbob .8s ease-in-out infinite alternate}
@keyframes handbob{to{transform:translateY(-10px)}}
.tapsabers #hh,.tapsabers #mh{pointer-events:auto;cursor:pointer}
@media(orientation:landscape) and (max-height:520px){
 .lgrid{grid-template-columns:minmax(0,1fr) minmax(0,1fr);align-items:start}.lclock svg{height:calc(100vh - 120px);width:100%}#cap{font-size:17px;min-height:0}#cap.big{font-size:26px}.coach svg{width:44px;height:46px}.digital{font-size:40px;margin:4px 0}
 .qgrid{grid-template-columns:minmax(0,1fr) minmax(0,1fr);align-items:start}
 .clockbox svg{height:calc(100vh - 150px);width:100%}.legend{display:none}
 .scene{background:#1b0d40}.scene svg{height:calc(100vh - 175px);width:100%}
 .bar{padding:4px 10px}.ib{height:40px;min-width:40px}
 canvas{height:calc(100vh - 170px)}
 .hitme{min-height:52px;font-size:30px;margin-top:0}.hp{margin:6px 0;height:18px}
 .ans button{min-height:62px}.ask{margin:0 0 8px}.mhead{margin:0 0 6px}.mhead h2{font-size:24px}
 .rule{display:none}.fb{min-height:0;margin-top:6px}
}
@media(orientation:portrait) and (max-height:640px){
 .clockbox svg{max-height:calc(100vh - 360px)}.legend{display:none}.ans button{min-height:68px}.ask{margin:2px 0 8px}
}
@media(prefers-reduced-motion:reduce){*{animation-duration:.01s!important;animation-iteration-count:1!important}}
manifest.webmanifest (Home Screen icon)17 lines

Raw file

{
 "name": "Clock Knockout",
 "short_name": "Clock KO",
 "description": "Read the analog clock to win light sabers and knock out silly villains. Every hour is a mission.",
 "id": "./",
 "start_url": "./",
 "scope": "./",
 "display": "fullscreen",
 "orientation": "any",
 "background_color": "#24124f",
 "theme_color": "#24124f",
 "icons": [
  { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" },
  { "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
 ]
}
voices.py (records every sentence in the Kokoro af_heart voice; the game's sentence list is lines.json)62 lines

Raw file

#!/usr/bin/env python3
"""Record every spoken line of Clock Knockout with Kokoro "af_heart", free and offline.

Each line becomes one small MP3 in v/ next to the game, named by a 32-bit hash of the line (the same
hash the game uses in clipName()), so no list has to be kept in the code. A line with no clip is read
by the device voice instead.

Setup (once): pip install kokoro-onnx soundfile numpy playwright ; ffmpeg on the path ;
  put kokoro-v1.0.onnx and voices-v1.0.bin (github.com/thewh1teagle/kokoro-onnx, release model-files-v1.0) next to this file.
Use:
  python3 docs/clock-knockout/voices.py docs/clock-knockout/lines.json public/games/clock-knockout/v/         record the missing lines
  python3 docs/clock-knockout/voices.py docs/clock-knockout/lines.json public/games/clock-knockout/v/ --all   record every line again
After changing a line in the game: run docs/clock-knockout/split-for-site.py, save a new lines.json, record, delete clips no line uses.
lines.json is the game's own list: open the game and run copy(JSON.stringify(__lines())) in the console.
"""
import json, os, re, subprocess, sys, tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
SAY_AS = {'Zzzz...': 'Zzzzz.', 'Gallop gallop!': 'Gallop, gallop!', 'Six.': 'six', 'six.': 'six', 'It is': "It's",
          "When the long blue saber points straight up to twelve, we say o'clock.": 'When the long blue saber points straight up to twelve, we say, oh clock.',
          "Great! The short saber tells the hour. You know o'clock!": 'Great! The short saber tells the hour. You know, oh clock!'}

def name_for(line):
    v = 5381
    for ch in line:
        v = ((v * 33) ^ ord(ch)) & 0xffffffff
    return '%08x.mp3' % v

def spoken(line):
    t = SAY_AS.get(line, line)
    t = re.sub(r"\b(say|means|read) o'clock", r'\1, oh clock', t)
    t = re.sub(r'\b(thir|four|fif|six|seven|eigh|nine)teen\b', r'\1-teen', t, flags=re.I)   # 'sixteen' was heard as 'sixty'   # a lone o'clock is swallowed as 'a clock'
    return re.sub(r'\b([A-Z]{2,})\b', lambda m: m.group(1).capitalize(), t)   # MINE! is read as a word, not spelled

def main(argv):
    if len(argv) < 2:
        print(__doc__); return 2
    lines = json.load(open(argv[0], encoding='utf-8')); out = argv[1]; redo = '--all' in argv
    os.makedirs(out, exist_ok=True)
    todo = [l for l in lines if redo or not os.path.exists(os.path.join(out, name_for(l)))]
    print(f'{len(lines)} lines, {len(todo)} to record')
    if not todo: return 0
    import numpy as np, soundfile as sf
    from kokoro_onnx import Kokoro
    k = Kokoro(os.path.join(HERE, 'kokoro-v1.0.onnx'), os.path.join(HERE, 'voices-v1.0.bin'))
    wav = os.path.join(tempfile.gettempdir(), 'clock-line.wav')
    for n, line in enumerate(todo, 1):
        s, sr = k.create(spoken(line), voice='af_heart', speed=0.95, lang='en-us')
        s = np.asarray(s, dtype=np.float32)
        loud = np.where(np.abs(s) > 0.012)[0]
        if len(loud):
            s = s[max(0, loud[0] - int(.03 * sr)):min(len(s), loud[-1] + int(.10 * sr))]
        s = s / max(1e-6, float(np.max(np.abs(s)))) * 0.86
        fade = int(.03 * sr); s[-fade:] *= np.linspace(1, 0, fade)
        sf.write(wav, s, sr)
        subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-i', wav, '-ac', '1', '-ar', '24000', '-b:a', '40k',
                        os.path.join(out, name_for(line))], check=True)
        if n % 25 == 0: print(f'  {n}/{len(todo)}')
    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

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.

How it works and what it costs Book a free call ↗

Or write to me · how to use what is here