{ /* ---------- 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='All games · How it was made'; /* ---------- 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{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;itone(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=` `; const blade=c=>c==='rainbow'?'url(#rb)':c; function swordSVG(c,on=true){return ``;} 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=`${DEFS}`; if((hint||o.trail)&&m>0){const a=ma*Math.PI/180;s+=m>=60?``:``;} for(let i=0;i<60;i++){const a=i*6*Math.PI/180,big=i%5===0,r1=big?116:122; s+=``; if(o.ones&&!big&&i<=m&&i>Math.floor(m/5)*5)s+=`${i}`;} 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+=``; if(o.ringM===n)s+=``; s+=`${n}`; if(hint)s+=`${(n*5)%60===0?'00':n*5}`;} s+=``; s+=``; s+=``; 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?``:``; return ` ${hairP} `; } function eyes(t){ if(t==='sleepy')return ``; const dy=t==='down'?4:0; return ``; } function mouth(t){ return {smile:'', o:'',flat:'', grin:'',mad:''}[t]; } function person(o){ const {skin='#f0c08f',shirt='#3aa0ff',pants='#333a66',hair='#3b2414',e='open',mo='smile',extra='',long=false}=o; return ` ${eyes(e)}${mouth(mo)}${extra}`; } function penguin(x,s,hat,d){return `${hat}`;} function bean(x,c,d){return ``;} function villainG(art){ switch(art){ case 'tv':return ` ${person({shirt:'#2ecc71',e:'side',mo:'o',extra:''})} `; case 'tablets':return `${person({shirt:'#ff7a00',mo:'mad'})}${person({shirt:'#ff7a00',mo:'mad',hair:'#7a3b14'})} MINE!`; case 'nose':return `${person({shirt:'#9b59b6',mo:'o',e:'side',extra:''})} pick pick`; case 'fire':return `${person({shirt:'#c0392b',mo:'grin',hair:'#6b3a1f',extra:''})} `; case 'phone':return `${person({shirt:'#ff4fa2',hair:'#2b1408',long:true,e:'down',mo:'smile',extra:''})} `; case 'tired':return `${person({shirt:'#8a8aa8',pants:'#555',hair:'#666',e:'sleepy',mo:'flat'})} Zzmeh.`; case 'penguins':return penguin(-60,.8,'',0)+penguin(0,1,'',.15)+penguin(60,.75,'',.3); case 'beans':return bean(-55,'#8e5cff',0)+bean(0,'#ff7a00',.2)+bean(55,'#2fbf8a',.4); case 'choco':return ` `; case 'khan':return ` ${person({shirt:'#1e5bb8',pants:'#1e5bb8',skin:'#e0b080',hair:'#2a1408',mo:'grin',extra:''})}`; case 'magnet':return `${person({shirt:'#555a7a',pants:'#333',skin:'#bfc6d6',hair:'#333',mo:'mad',extra:''})} `; case 'narwhal':return ` `; } } function sceneSVG(H,heroW,sw,opt={}){ const m=M[H-1],id='s'+H+(opt.k||''); return `${DEFS} ${opt.hero2?`${heroG(opt.hero2,SW[H-1][1])}`:''}${opt.hero?`${heroG(heroW,sw)}`:''} ${villainG(m.art)}`; } const STAR=on=>``; const ICON={ fruit:``, muffin:``, donut:``, pretzel:`` }; const SPK=on=>on?'':''; /* ---------- 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=``; 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>>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;isetTimeout(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=`

Clock Knockout

Created and directed by two young players

${SITE_LINKS?``:''}

Read the clock. Win light sabers. Knock out silly villains. Collect snacks from the chocolate river.
No sound? Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent.
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.

`; 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=`

${n===1?'Pick your hero':'Player 1, pick your hero'}

${['Nova','Blaze'].map(w=>``).join('')}
${n===2?`

Player 2 plays as ${sel==='Nova'?'Blaze':'Nova'}. ${coop?'Take turns reading the clock, then fight side by side. Team points!':'Take turns. Most points wins!'}

`:''}
`; 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('

New to clocks?

Start in Clock School! Six short games teach the hour and the minutes with light sabers.

',[['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+=` ${h} ${open?'':``} ${st?`${'★'.repeat(st)}`:''}`;} const ha=next*30; app.innerHTML=`

The Clock World

Every hour is a mission. Tap a number!

`:''}
${G.pl.map((p,i)=>`${p.w}: ${p.pts} pts`).join('')} ${ICON.fruit}${P.inv.fruit}${ICON.muffin}${P.inv.muffin}${ICON.donut}${P.inv.donut}${ICON.pretzel}${P.inv.pretzel}
${DEFS} ${P.unlocked>12?'Champion!':'Next: '+M[next-1].name}${b}
Light saber collection: ${P.swords.length} of 12
${SW.map((s,i)=>swordSVG(s[1],P.swords.includes(i+1))).join('')}
Saber power: level ${P.lvl} of 3${P.lvl<3?` `:' (max!)'}

Progress saves on this device. Tap Restart at the top to start over.

`; 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=`

Mission ${H}: ${m.name}

${sceneSVG(H,G.pl[G.turn].w,curSword(),{k:'i'})}
${m.v}
${m.intro}

Read the clock to get your light saber. The minutes pick your challenge!

`; 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 `
${[0,1,2].map(i=>``).join('')}
`;} function turnHTML(){return G.mode===2?`${G.pl[G.turn].w}’s turn`:'';} 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=`

Mission ${H}

${turnHTML()}${dotsHTML()}
${clockSVG(q.h,q.m,hint)}
Short red saber = hourLong blue saber = minutes
What time is it?
${q.opts.map(o=>``).join('')}
`; 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(`

Light saber unlocked!

${swordSVG(SW[H-1][1]).replace('${SW[H-1][0]}

Minute ${G.q.m} → ${CH[ch]}

`,[['Fight!','',go]]); }else{ modal(`

${CH[ch]}

Minute ${G.q.m} picked this challenge.

${ch==='super'?'

SUPER POWER: every hit counts double!

':''}`,[['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=`

${boss?'BOSS: ':''}${m.v}

${turnHTML()}${dotsHTML()}
${sceneSVG(H,G.pl[G.turn].w,SW[H-1][1],{hero:true,k:'b',hero2:G.coop?G.pl[1-G.turn].w:''})}
${rnd(m.lines)}
${G.coop?`
`:``}

Tap POW or tap the villain as fast as you can!

`; 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=`

Chocolate River!

${turnHTML()}${dotsHTML()}
Time: 12${ICON.fruit}0${ICON.muffin}0${ICON.donut}0${ICON.pretzel}0

Tap the fruits, muffins, donuts and pretzels before they float away!

`; 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){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.x2); 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(`

Great job!

${msg}

${G.mode===2?`

Next turn: ${G.pl[G.turn].w}

`:''}`,[['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(`

${champ?'CLOCK CHAMPION!':'Mission complete!'}

${[1,2,3].map(i=>STAR(i<=st)).join('')}

${msg}

${M[H-1].v} is knocked out!${H<12?` Mission ${H+1} is open.`:' You beat all 12 hours!'}

${lead?`

${lead}

`:''}`, 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(haveNeed more snacks!

You have ${have}. You need ${cost}. Win snacks in the chocolate river and in battles.

`,[['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(`

Saber power up!

${swordSVG(curSword()).replace('Level ${P.lvl}! Every hit does ${1+P.lvl} damage now.

`,[['Awesome!','',map]]); } function setClock(q){ let h=hr(q.h)===12?6:12,m=0;const fine=G.H>=10; app.innerHTML=`

Mission ${G.H}

${turnHTML()}${dotsHTML()}
${clockSVG(h,m,true)}
Short red saber = hourLong blue saber = minutes
Set the clock to ${q.c}!
${fine?`
`:''}
Now it shows ${fmt(h,m)}
`; 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{ 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=`

Clock School

Learn the clock by playing. Then go fight the villains!

${LESSONS.map((l,i)=>``).join('')}

Clock School: ${schoolDone()} of ${LESSONS.length} lessons done.

`; 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=`${DEFS} `; for(let i=0;i<60;i++){const a=i*6*Math.PI/180,big=i%5===0,r1=big?116:121; s+=``; if(!big)s+=`${i}`;} 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+=`${n*5} ${n}`;} s+=` `; 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=`

${i>=0?`Lesson ${i+1}: `:''}${l.name}

${lessonClock()}

${extra}
`; $('#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)=>``).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(`

${all?'Clock School graduate!':'Lesson done!'}

${STAR(true)}${STAR(true)}${STAR(true)}

${LESSONS[i].name}: done! +3 fruit

`, 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;rnum(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
0 minutes
`); 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;rm){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=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,`
12:00
`); 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('

Start over?

This clears all missions, light sabers and snacks on this device.

',[['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(); }