Game · project 21 of 37
Kidopia: The Magical Game Shop.
Run a magic video game shop from a child's idea: customers walk in with game ideas, you make each game on a magic phone, it flies to the big TV, and you play it together on the couch.
BeforeA child's idea for a shop that makes video games, and no way to make even one game herself.
AfterHer shop, playable: customers bring ideas, she makes each game on a magic phone, it flies to the TV, and everyone plays it on the couch.
What it is worthA child's own idea turned into a real game about making games, free, with no ads, nothing to buy and no accounts. Instead of waiting to grow up and learn to code, and app games full of ads and things to buy.
How to use it
- Open it with the sound up and tap Open the shop (a 5-minute day) or Creative mode (no clock). Sound plays even when an iPhone is on silent.
- A customer walks in and asks for a game. Tap one of the three answers: their own idea, show some ideas (pick one, or pick two to mix them), or Surprise me. The magic engine then shows how the words became the game. Type any idea in the box under it (for example "a robot escaping lava at night and collecting gems") to make a new one.
- The magic phone opens. Change the game type, hero, world, power, goal, obstacles, music and level if you like; hearts show what the customer wished for. Then tap CREATE GAME and watch the game fly to the TV.
- Tap Play together. Each game has three levels and a boss; touch the gift box for a power-up, and grab the stars to zap the boss. Drag on the screen (or use the arrow keys) to move, and tap the big round button (or Space) to jump, boost or dash. In the puzzle, tap the cards.
- After each game you earn coins and stars and see how happy the customer is. Coins unlock new characters, worlds, controllers, decorations and phone upgrades. At the end of the day you get a shop rating, then play again or keep going in Creative mode.
Where it helps most
- Children about 4 to 10 who love inventing games: they get to be the game maker, mix ideas, and see their choices turn into something they can play, on a phone, a tablet or a computer.
- Parents and teachers who want a free, ad-free creative game with nothing to buy and no accounts, 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
A young player had the idea: a magic shop where children come in with ideas for video games, the owner makes the game on a phone, it appears on a big TV, and everyone sits on the couch and plays it. It is a game about making games, and about a child's imagination coming to life. The only rule for this one: no cats, because flying cats are saved for a separate game. The young designer gets the credit on the title screen.
The build
Built by Claude in one session from a young player's idea and a master prompt. It is one page of plain HTML, CSS and JavaScript with no libraries, images or sound files. The shop, the people, the TV and the couch are drawn on a canvas in code, the heroes and the enemies are cartoon drawings made in code (art.js), so they look the same on every device, and the other game art uses the device's own emoji, and every sound and the music are made in the browser with the Web Audio API. The "game generator" is a small engine, not AI: nine game types share the same pieces (hero, world colours and items, obstacles, powers, goals, music, level), so each choice on the phone changes what you play. Ideas are read by a separate word reader (idea.js), still with no AI and no network: a picture dictionary of about 260 creatures, vehicles, foods, things and dangers, plus word lists for places, kinds of play, powers, music, weather, night, sky colours and size. It looks at the words around each one, so "collect stars" makes stars into treats, "escape the lava" makes lava an enemy, "save the puppies" makes puppies friends to rescue, and "no sharks" leaves sharks out. Two kinds of play in one idea become a main game with a second one mixed in (more treats, more enemies, big treasure or a faster clock). Words for new places or heroes make a new world or hero on the spot. Ideas it cannot make become close alternatives with a short note. The customer sees the sentence with each used word lit up, then a chip for each choice, then the game name. Progress (coins, stars, unlocks, game names) is saved only in the visitor's browser; no names or personal details are asked for or sent. On iPhones the page asks for "playback" audio on the first tap, so sound plays with the phone on silent. Like every game under /games/, it works offline after the first open and can go on the Home Screen. A fresh reviewer checked it for children's content and rated it green. Limits: the mini-games are short and simple on purpose; emoji look a little different on each device; it was tested in a headless browser with simulated touch, mouse and keys at four screen sizes, not yet on a real iPhone on silent or with a real controller.
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: Kidopia, The Magical Game Shop
You are a small game studio building a free browser game for children from one child's idea. Credit the child without a name: the shop sign reads "The Magical Game Shop" and the title "Game idea by a young player". Build one page of plain HTML, CSS and JavaScript (canvas for the shop and the mini-games, DOM for the phone and the cards), with no libraries, images or sound files. It must play on iPhone, iPad, Mac and Windows with touch, mouse, keyboard or a game controller, cost nothing to run, and ask for no personal details. Strict rule: no cats anywhere (no cat or big-cat characters, emoji, words or decorations).
THE IDEA (keep it whole): the player owns a magic video game shop called Kidopia. Customers walk in and tell the owner their game ideas. The owner makes the game on a magic smartphone. The game flies from the phone to a big TV. The customer sits on the couch with a controller, the owner joins, and they play the new game together.
SHOP: a side view, 1600 x 900 world units, drawn in code: purple wall, checker floor, string lights that blink, a glowing KIDOPIA sign with each letter in its own colour, automatic sliding glass doors with an OPEN sign, shelves of game boxes, a pink counter with the owner behind it, bean bags with popcorn and juice in a waiting area, a plant, a big wall TV with a stand, a blue couch on a rug, controllers on the couch arms, swinging spotlights. People are drawn in code: random skin, hair colour and style, shirt, trousers, hats, glasses, a few friendly robot customers; they walk with swinging legs, blink, talk with moving mouths, wave, jump when happy and sit holding a controller. Speech bubbles above heads. The camera fits the whole shop on wide screens; on tall screens and when a card covers the bottom it zooms in on the people and follows the action (door, counter, TV). When the phone opens at the side of a short wide screen, the shop slides into the space that is left.
CUSTOMERS: a random first name, a look and a personality (excited, shy, silly, curious, dreamy) with its own lines. They walk in through the doors to the counter and say hello. Three big buttons: "I have my own game idea!" (the customer says a request such as "I want a racing game with a dragon in Donut World", and a text box lets the child type any idea instead), "Show me some game ideas!" (illustrated cards; pick one, or pick two to mix them), and "Surprise me!" (a random game, sometimes a secret combination). Ideas list: Unicorn Rainbow Racing, Candy Kingdom Adventure, Underwater Treasure Hunt, Space Explorer, Magical Ice Cream Factory, Flying Dragon Adventure, Princess Castle Adventure, Superhero City, Donut World, Pirate Island, Robot Adventure, Rainbow Obstacle Course. Every idea (typed, from a card, two cards mixed, or a surprise) goes through the magic engine and the customer sees it read.
MAGIC ENGINE (idea.js, no AI, no network): a separate script that exposes window.KidIdea.read(text). Join common phrases first ("ice cream", "under the sea", "lots of"), break the sentence at commas and at "mixed with", "then", "but". Keep a picture dictionary of about 260 words with an emoji and a kind (creature, vehicle, food, thing, danger; flags for flying and sea), and word lists for places (each maps to a base world, and new places such as the moon, a farm or a kitchen make a new tinted world), kinds of play (race, fly, jump, dig, explore, collect, dodge, puzzle, rescue), powers, music styles, levels, weather (rain, snow, bubbles, hearts, sparkles, leaves, confetti), night, sky colours and size words. Read word by word with a role from the verbs nearby: after collect/eat/find a thing is a treat; after dodge/escape/over/fight it is an enemy; after save/rescue/help it is a friend; after "I am" or "play as" it is the hero; "in", "on" and "at" end the role. With no verb, the first creature or vehicle is the hero, foods and things are treats, dangers are enemies, later creatures are friends. "No" or "without" leaves the next word out and says so. If no kind of play is named, guess it from the hero, place, treats, enemies or friends. A second kind of play becomes a mix (collect, rescue, dodge, treasure or clock). Return a plan with every choice and a note per used word. Show a sheet: the sentence with each used word lit up in its role colour, then chips that pop in one by one ("bunny → Hero", "lava → Enemies to dodge", "Mixed: + rescuing friends"), any notes, the game name, a "Make it on the phone!" button and a box to type a new idea. The plan fills the phone (a new hero or world appears as its own tile) and the game uses it: hero, world tint, enemy and treat emoji, friends, how many treats and enemies, hero size, night shade and weather on top. Ideas the engine cannot make become close alternatives (sports become a catching game, fighting becomes a friendly dodging game, monsters become silly ghosts) with a short note. Never echo typed words back in a speech bubble. Customers' own requests are made up from templates so each one is different.
MAGIC PHONE: a phone on screen with a game name box and a dice button for a made-up name, tabs with big icons for Game type, Hero, World, Power, Goal, Obstacles, Music and Level, and tiles with emoji. A heart marks each thing the customer wished for, and a line counts how many wishes the game keeps. A glowing CREATE GAME button plays a making animation (progress bar: drawing the hero, building the world, adding the music, adding magic), then the phone shrinks away and coloured sparks and emoji fly in an arc from the phone to the TV. The TV switches on with a white line and shows the game's title and hero. The customer walks to the couch and picks up a controller; the owner sits beside them; Play together zooms into the TV.
LEVELS, POWER-UPS AND BOSS: every game has three short levels (about 12 to 26 seconds each, a bit harder each time, with a "Level 2!" card between them) and then a boss: a big version of the enemy with a crown and hearts, moving at the top and throwing small copies; a star appears near the player, and touching or tapping it sends a zap to the boss. A gift box appears once per level and gives a 7-second power-up (star power, super speed, magnet, double points; in the puzzle a peek at the cards). A mixed-in second kind of play runs on top of the main game in screen space with its own counter: friends in bubbles to save, treats falling to catch, enemies flying across to dodge, or X marks to dig.
ART: draw the main heroes and enemies in code (body shapes, big eyes with a white shine, pink cheeks, a dark outline), cache each at 128 px and use them wherever the emoji would be drawn; enemies look silly, never scary.
MINI-GAME ENGINE: one small engine with shared pieces (hero, world colours and items, obstacles, power, goal, music, level, score, pop-up points, sparkles, a cheering customer line) and nine game types: Racing (top-down track, three rival racers, boost button, finish place), Flying (side-scrolling, hold to fly up, portal at the end), Jumping (generated platforms, jump on enemies, flag at the end), Treasure hunt (top-down map, dig under red X marks, arrow to the nearest), Exploring (fog that clears as you walk, five landmarks), Collecting (catch falling treats in a basket), Dodging (survive things flying in from the edges), Puzzle (memory card pairs) and Rescue (friends in bubbles follow you home). Powers: super speed, shield bubble (three free hits), magnet, super jump (double jump), slow motion, double points. Goals: reach the end, collect treasure, save friends, beat a high score. Each level lasts about 12 to 26 seconds, starts with a title, a one-line how-to and a 3-2-1 countdown, and never ends early on a mistake: a hit says "Oops!" and blinks. Stars: one for playing, one for the main aim, one for the chosen goal (with few hits).
FIVE-MINUTE DAY: a clock counts down 5:00. Minute 1 the lights come on and the first customer arrives; then idea, phone, TV and play; while a game is on, the next customer comes in and waits on a bean bag; under 100 seconds left the next customer is the last one of the day. Walking speeds up while the screen is held, so experienced players move faster. The end card shows games created, happy customers, coins earned, stars collected, customer happiness and a shop rating out of 5, the games made that day, and Play again or Creative mode (no clock, endless customers).
REWARDS: coins and stars per game (more for stars, kept wishes and secret combinations). Lifetime coins unlock new characters, new worlds, gold and rainbow controllers, balloons and a disco ball for the shop, rainbow and golden phone upgrades (faster making), and a second TV that shows the newest game. Ten secret hero-and-world combinations (for example a dragon in the ice cream factory) give a bonus. Save coins, stars, unlocks, secrets and recent game names in localStorage with try/catch.
SOUND: Web Audio only: a cheerful shop tune and five game music styles (happy, adventure, space, calm, party) made note by note from a scale and a chord loop, plus effects for taps, the door chime, talking blips, making, whoosh, TV on, coins, collecting, hits, jumps, boosts, countdown, win, stars and unlocks; a mute button. 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, resume on every tap and when the page is shown again, and say "No sound? Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent."
CONTROLS: in the TV games a touch joystick appears where the thumb lands (in a strip under the game on tall phones) with a big round action button; arrow keys or WASD and Space; the first game controller's stick, D-pad and Cross. In the puzzle, tap the cards. Keys 1 to 3 pick the three customer choices. Big buttons everywhere (at least 56 px), a menu with pause, help, new day, creative mode and title.
FINISH: bright cartoon look, Fredoka for all text, emoji for the game art, no inline styles in the markup (strict security policy), web manifest and icons for the Home Screen, offline after the first open, reduced motion respected, no ads, no purchases, no accounts.
STRESS TEST: play a full day at 320 x 568, 393 x 700, 740 x 360 and 1366 x 800 with touch and keyboard: every customer choice, mixing two ideas, typing an idea, every tab and tile, all nine game types with random input, a game that times out, the last-customer rule and the end card, replay and creative mode; check that the AudioContext runs after the first tap and that audioSession becomes 'playback'; check there is no console error, no security-policy error and no sideways scrolling; search every file for cats. Feed the engine sample sentences (mixed ideas, negations, unknown words, a cat word) and check each plan.
Get the code6 files, exactly as they run on this site · free under the MIT license
These files are exactly what runs at sghadimi.com/games/kidopia (sghadimi.com/kidopia forwards there). 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. There are no images, models or sound files: the shop and the people are drawn in code, the game art is the device's emoji, and the sounds are made in the browser.
kidopia.js (the whole game: shop, people, phone, game engine, nine mini-games, music and sound)1,611 lines
/* Kidopia: The Magical Game Shop.
Original idea: a young player. A child runs a magic video game shop: customers walk in with game ideas,
the owner makes each game on a magic phone, the game flies to the big TV, and everyone plays on the couch.
One script, no libraries, no image or sound files: the shop and the people are drawn on a canvas,
the game art uses the device's emoji, and every sound is made with the Web Audio API.
Rule from the brief: no cats anywhere. */
(function(){'use strict';
/* ================= iPhone sound fix: Web Audio plays even when the phone is on silent ================= */
let AC=null,silentEl=null,master=null,musGain=null,sfxGain=null,noiseBuf=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){}}catch(e){AC=null;return;}
master=AC.createGain();master.gain.value=SAVE.mute?0:0.85;master.connect(AC.destination);
musGain=AC.createGain();musGain.gain.value=0.2;musGain.connect(master);
sfxGain=AC.createGain();sfxGain.gain.value=0.5;sfxGain.connect(master);
noiseBuf=AC.createBuffer(1,Math.floor(AC.sampleRate*0.5),AC.sampleRate);
const d=noiseBuf.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1;
MUS.next=AC.currentTime+0.15;
}
function live(){return AC&&AC.state==='running'&&!SAVE.mute;}
function note(t,f,dur,type,vol,dest,f2){
const o=AC.createOscillator(),g=AC.createGain();
o.type=type||'sine';o.frequency.setValueAtTime(f,t);
if(f2)o.frequency.exponentialRampToValueAtTime(f2,t+dur);
g.gain.setValueAtTime(0.0001,t);g.gain.exponentialRampToValueAtTime(vol,t+0.012);g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
o.connect(g);g.connect(dest||sfxGain);o.start(t);o.stop(t+dur+0.03);
}
function noise(t,dur,vol,f,q,dest,f2){
const s=AC.createBufferSource(),b=AC.createBiquadFilter(),g=AC.createGain();
s.buffer=noiseBuf;b.type='bandpass';b.frequency.setValueAtTime(f,t);if(f2)b.frequency.exponentialRampToValueAtTime(f2,t+dur);b.Q.value=q||1;
g.gain.setValueAtTime(vol,t);g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
s.connect(b);b.connect(g);g.connect(dest||sfxGain);s.start(t);s.stop(t+dur+0.02);
}
const SFX={
tap(){if(!live())return;const t=AC.currentTime;note(t,660,.07,'triangle',.25,0,990);},
pick(){if(!live())return;const t=AC.currentTime;[523,784].forEach((f,i)=>note(t+i*.06,f,.12,'triangle',.25));},
door(){if(!live())return;const t=AC.currentTime;note(t,988,.5,'sine',.3);note(t+.22,784,.7,'sine',.3);},
blip(){if(!live())return;const t=AC.currentTime;for(let i=0;i<3;i++)note(t+i*.07,380+Math.random()*260,.06,'square',.06);},
create(){if(!live())return;const t=AC.currentTime;note(t,180,2,'sawtooth',.08,0,1400);note(t,240,2,'triangle',.12,0,1800);for(let i=0;i<12;i++)note(t+i*.16,1200+Math.random()*1400,.12,'sine',.08);},
whoosh(){if(!live())return;const t=AC.currentTime;noise(t,.9,.35,300,1.2,0,4000);for(let i=0;i<8;i++)note(t+i*.1,1500+i*180,.1,'sine',.06);},
tvon(){if(!live())return;const t=AC.currentTime;note(t,90,.35,'sawtooth',.12,0,1600);noise(t+.1,.25,.15,2500,2);},
coin(){if(!live())return;const t=AC.currentTime;note(t,988,.08,'square',.12);note(t+.07,1319,.25,'square',.12);},
collect(){if(!live())return;const t=AC.currentTime;note(t,660,.12,'triangle',.22,0,1320);},
friend(){if(!live())return;const t=AC.currentTime;[784,988,1175,1568].forEach((f,i)=>note(t+i*.06,f,.15,'triangle',.2));},
hit(){if(!live())return;const t=AC.currentTime;note(t,220,.3,'sawtooth',.18,0,70);noise(t,.18,.2,800,1);},
bonk(){if(!live())return;const t=AC.currentTime;note(t,500,.14,'square',.14,0,160);},
jump(){if(!live())return;const t=AC.currentTime;note(t,330,.16,'square',.1,0,700);},
boost(){if(!live())return;const t=AC.currentTime;noise(t,.5,.25,600,1,0,3000);note(t,200,.5,'sawtooth',.08,0,800);},
beep(hi){if(!live())return;note(AC.currentTime,hi?880:440,hi?.4:.15,'square',.14);},
win(){if(!live())return;const t=AC.currentTime;[523,659,784,1047,784,1047].forEach((f,i)=>note(t+i*.11,f,i===5?.6:.16,'triangle',.25));},
star(){if(!live())return;const t=AC.currentTime;[1319,1568,2093].forEach((f,i)=>note(t+i*.09,f,.35,'sine',.18));},
unlock(){if(!live())return;const t=AC.currentTime;[523,659,784,988,1175,1319,1568].forEach((f,i)=>note(t+i*.07,f,.25,'triangle',.18));},
party(){if(!live())return;const t=AC.currentTime;for(let i=0;i<14;i++){noise(t+i*.07,.12,.15,2000+Math.random()*3000,3);note(t+i*.07,600+Math.random()*900,.1,'square',.05);}}
};
/* ---- cheerful music, made note by note ---- */
const STY={
shop:{bpm:112,root:60,sc:[0,2,4,5,7,9,11],minor:0,lead:'triangle',drums:1,prog:[0,4,5,3],rest:.4},
happy:{bpm:126,root:62,sc:[0,2,4,5,7,9,11],minor:0,lead:'square',drums:1,prog:[0,3,4,0],rest:.3},
adventure:{bpm:138,root:57,sc:[0,2,3,5,7,8,10],minor:1,lead:'square',drums:1,prog:[0,5,3,4],rest:.25},
space:{bpm:94,root:55,sc:[0,2,4,7,9],minor:0,lead:'sine',drums:0,prog:[0,3,5,4],rest:.45},
calm:{bpm:84,root:65,sc:[0,2,4,7,9],minor:0,lead:'sine',drums:0,prog:[0,3,0,4],rest:.55},
party:{bpm:142,root:60,sc:[0,2,4,7,9],minor:0,lead:'square',drums:2,prog:[0,4,5,3],rest:.2}
};
const MAJ=[0,2,4,5,7,9,11],MIN=[0,2,3,5,7,8,10];
const MUS={style:'shop',next:0,step:0,pat:[]};
function mf(m){return 440*Math.pow(2,(m-69)/12);}
function setMusic(id){
if(!STY[id])id='shop';
if(MUS.style===id&&MUS.pat.length)return;
MUS.style=id;MUS.step=0;const s=STY[id];let d=4;MUS.pat=[];
for(let i=0;i<32;i++){
if(Math.random()<s.rest&&i%8!==0){MUS.pat.push(null);continue;}
d+=Math.floor(Math.random()*5)-2;if(d<0)d=1;if(d>9)d=8;MUS.pat.push(d);
}
if(AC)MUS.next=Math.max(MUS.next,AC.currentTime+0.05);
}
function musicTick(){
if(!AC||AC.state!=='running')return;
if(MUS.next<AC.currentTime)MUS.next=AC.currentTime+0.05;
const s=STY[MUS.style],sd=60/s.bpm/2,cs=s.minor?MIN:MAJ;
while(MUS.next<AC.currentTime+0.25){
const t=MUS.next,i=MUS.step,bar=Math.floor(i/8)%4,st=i%8,deg=s.prog[bar];
if(!SAVE.mute){
const cr=s.root+cs[deg%7]+(deg>=7?12:0);
if(st===0||st===4)note(t,mf(cr-24),sd*1.8,'triangle',.32,musGain);
if(st===0)[0,2,4].forEach(k=>{const dd=deg+k;note(t,mf(s.root+cs[dd%7]+12*Math.floor(dd/7)),sd*7,'sine',.05,musGain);});
const p=MUS.pat[i%32];
if(p!=null){const L=s.sc.length;note(t,mf(s.root+12+s.sc[p%L]+12*Math.floor(p/L)),sd*.9,s.lead,s.lead==='square'?.045:.09,musGain);}
if(s.drums){
if(st===0||st===4)note(t,150,.14,'sine',.45,musGain,40);
if(st===2||st===6)noise(t,.12,.18,1800,.8,musGain);
if(s.drums===2||st%2===1)noise(t,.04,.06,7000,1,musGain);
}
}
MUS.next+=sd;MUS.step++;
}
}
/* ================= small helpers ================= */
const rnd=(a,b)=>a+Math.random()*(b-a);
const ri=(a,b)=>Math.floor(rnd(a,b+1));
const pick=a=>a[Math.floor(Math.random()*a.length)];
const clamp=(v,a,b)=>v<a?a:v>b?b:v;
const lerp=(a,b,t)=>a+(b-a)*t;
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 esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const an=w=>/^[aeiou]/i.test(w)?'an':'a';
const FONT='Fredoka,"Trebuchet MS",sans-serif';
const EMOF='"Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif';
/* ================= what can go into a game ================= */
const HEROES=[
{id:'unicorn',n:'Unicorn',e:'🦄'},{id:'dragon',n:'Dragon',e:'🐉'},{id:'mermaid',n:'Mermaid',e:'🧜♀️'},
{id:'astronaut',n:'Astronaut',e:'🧑🚀'},{id:'princess',n:'Princess',e:'👸'},{id:'superhero',n:'Superhero',e:'🦸'},
{id:'robot',n:'Robot',e:'🤖'},{id:'puppy',n:'Puppy',e:'🐶'},{id:'bunny',n:'Bunny',e:'🐰'},
{id:'penguin',n:'Penguin',e:'🐧'},{id:'parrot',n:'Pirate Parrot',e:'🦜'},{id:'dino',n:'Dino',e:'🦕'},
{id:'bear',n:'Bear',e:'🐻'},
{id:'panda',n:'Panda',e:'🐼',u:1},{id:'octopus',n:'Octopus',e:'🐙',u:1},{id:'owl',n:'Owl',e:'🦉',u:1},{id:'frog',n:'Frog',e:'🐸',u:1}
];
const WORLDS=[
{id:'rainbow',n:'Rainbow Land',s:'Rainbow',e:'🌈',sky:['#7fd8ff','#ffd6f5'],gr:'#8be08b',gr2:'#ff9ad5',deco:['🌈','☁️','🌸'],items:['⭐','💎','🍓'],haz:'⛈️',marks:['🎠','🏰','🎡','🌻','🎪'],mus:'happy'},
{id:'candy',n:'Candy Kingdom',s:'Candy',e:'🍭',sky:['#ffb3e6','#fff0b3'],gr:'#ff8fc8',gr2:'#fff4fb',deco:['🍭','🍬'],items:['🍬','🍭','🍫'],haz:'🌶️',marks:['🍰','🍭','🎂','🍪','🍩'],mus:'party'},
{id:'ocean',n:'Under the Sea',s:'Ocean',e:'🐠',sky:['#1ec8e8','#0a4f9e'],gr:'#f2d98c',gr2:'#e0bf62',deco:['🐡','🐠','🐟'],items:['🐚','💎','🪙'],haz:'🦀',marks:['🐙','🐳','🐢','🦭','🐬'],mus:'calm'},
{id:'space',n:'Outer Space',s:'Space',e:'🚀',sky:['#0b0630','#3a1a7a'],gr:'#5b4b9a',gr2:'#8a7bd0',deco:['✨','🪐','🌙'],items:['⭐','💫','🌟'],haz:'☄️',marks:['🪐','🛸','🌙','🛰️','🌍'],mus:'space'},
{id:'icecream',n:'Ice Cream Factory',s:'Ice Cream',e:'🍦',sky:['#bff0ff','#ffe4f2'],gr:'#ffe9c7',gr2:'#ffc2e0',deco:['🍦','🍨'],items:['🍦','🍨','🍧'],haz:'🔥',marks:['🍦','🏭','🍨','🍧','🍒'],mus:'happy'},
{id:'sky',n:'Dragon Sky',s:'Sky',e:'☁️',sky:['#ff9f5a','#ffe1a8'],gr:'#7dc46b',gr2:'#5aa84a',deco:['☁️','🏔️'],items:['💎','⭐','🪙'],haz:'🌩️',marks:['🏔️','🏯','🗻','🌋','🏕️'],mus:'adventure'},
{id:'castle',n:'Princess Castle',s:'Castle',e:'🏰',sky:['#c9a7ff','#ffe1f0'],gr:'#9ad48a',gr2:'#f7c6ff',deco:['🏰','🌷'],items:['👑','💎','🗝️'],haz:'🦇',marks:['🏰','👑','⛲','🌷','🎠'],mus:'calm'},
{id:'city',n:'Superhero City',s:'City',e:'🏙️',sky:['#3fa8ff','#b8e6ff'],gr:'#9aa3b5',gr2:'#c5ccda',deco:['🏢','🚁'],items:['⭐','🪙','💡'],haz:'🚧',marks:['🗽','🚒','🏥','🎡','🏟️'],mus:'adventure'},
{id:'donut',n:'Donut World',s:'Donut',e:'🍩',sky:['#ffd6a5','#ffadad'],gr:'#c98a5a',gr2:'#ff8fc8',deco:['🍩','🍪'],items:['🍩','🍪','🥨'],haz:'🐝',marks:['🍩','🥐','🍪','🧇','🥞'],mus:'party'},
{id:'pirate',n:'Pirate Island',s:'Pirate',e:'🏝️',sky:['#5ad1ff','#c8f4ff'],gr:'#f2d98c',gr2:'#4fc3e8',deco:['🌴','⛵'],items:['🪙','💰','💎'],haz:'🦀',marks:['⛵','🌴','⚓','🏝️','🗿'],mus:'adventure'},
{id:'robot',n:'Robot Factory',s:'Robot',e:'⚙️',sky:['#2b3a55','#6f86b0'],gr:'#7d8aa8',gr2:'#a8b4cc',deco:['⚙️','💡'],items:['🔩','⚙️','🔋'],haz:'⚡',marks:['🤖','🛸','🔭','🏭','📡'],mus:'space'},
{id:'jungle',n:'Jungle Park',s:'Jungle',e:'🌴',sky:['#7fe0a0','#e8ffcc'],gr:'#5aa84a',gr2:'#3f8a3a',deco:['🌴','🌺'],items:['🍌','🍓','🍉'],haz:'🪨',marks:['🐘','🦒','🦜','🐵','🦛'],mus:'adventure'},
{id:'volcano',n:'Volcano Island',s:'Volcano',e:'🌋',sky:['#ff7b54','#ffd23f'],gr:'#6b3a2a',gr2:'#a0522d',deco:['🌋','🔥'],items:['💎','⭐','🪙'],haz:'🔥',marks:['🌋','🦖','💎','🪨','🏕️'],mus:'adventure',u:1},
{id:'snow',n:'Snow Land',s:'Snow',e:'❄️',sky:['#a8e0ff','#ffffff'],gr:'#f0f8ff',gr2:'#cfe8ff',deco:['❄️','⛄'],items:['❄️','🧊','⭐'],haz:'🌨️',marks:['⛄','🏔️','🐧','🎿','🛷'],mus:'calm',u:1}
];
const MODES=[
{id:'race',n:'Racing',e:'🏎️',w:'racing',noun:'Race'},
{id:'fly',n:'Flying',e:'✈️',w:'flying',noun:'Flight'},
{id:'platform',n:'Jumping',e:'🦘',w:'jumping',noun:'Jump'},
{id:'treasure',n:'Treasure hunt',e:'🗺️',w:'treasure hunt',noun:'Treasure Hunt'},
{id:'explore',n:'Exploring',e:'🔭',w:'exploring',noun:'Quest'},
{id:'collect',n:'Collecting',e:'🧺',w:'collecting',noun:'Catch'},
{id:'dodge',n:'Dodging',e:'💨',w:'dodging',noun:'Dash'},
{id:'puzzle',n:'Puzzle',e:'🧩',w:'puzzle',noun:'Puzzle'},
{id:'rescue',n:'Rescue',e:'🛟',w:'rescue',noun:'Rescue'}
];
const POWERS=[
{id:'speed',n:'Super speed',e:'⚡'},{id:'shield',n:'Shield bubble',e:'🛡️'},{id:'magnet',n:'Magnet',e:'🧲'},
{id:'jump',n:'Super jump',e:'🚀'},{id:'slow',n:'Slow motion',e:'⏳'},{id:'double',n:'Double points',e:'✨'}
];
const GOALS=[
{id:'finish',n:'Reach the end',e:'🏁'},{id:'collect',n:'Collect treasure',e:'💎'},
{id:'friends',n:'Save friends',e:'🐣'},{id:'score',n:'Beat the high score',e:'🏆'}
];
const OBST=[
{id:'world',n:'World surprise',e:'🌍'},{id:'rocks',n:'Rolling rocks',e:'🪨'},{id:'bees',n:'Buzzy bees',e:'🐝'},
{id:'clouds',n:'Storm clouds',e:'⛈️'},{id:'crabs',n:'Grumpy crabs',e:'🦀'},{id:'ghosts',n:'Silly ghosts',e:'👻'},{id:'meteors',n:'Meteors',e:'☄️'}
];
const MUSICS=[
{id:'happy',n:'Happy',e:'🎵'},{id:'adventure',n:'Adventure',e:'🥁'},{id:'space',n:'Space',e:'🌌'},
{id:'calm',n:'Calm',e:'🌙'},{id:'party',n:'Party',e:'🎉'}
];
const LEVELS=[{id:'easy',n:'Easy',e:'🐢'},{id:'medium',n:'Medium',e:'🐇'},{id:'hard',n:'Hard',e:'🚀'}];
const FRIENDS=['🐣','🐥','🐹','🐨','🐼','🐰','🐶','🐧'];
const IDEAS=[
{n:'Unicorn Rainbow Racing',t:'a unicorn racing on a rainbow and grabbing stars',hero:'unicorn',world:'rainbow',mode:'race',c:['#ff7eb3','#7f7fff']},
{n:'Candy Kingdom Adventure',t:'a bunny hopping over chilli peppers in a candy kingdom',hero:'bunny',world:'candy',mode:'platform',c:['#ff4fa3','#ffb86b']},
{n:'Underwater Treasure Hunt',t:'a mermaid hunting for treasure under the sea and avoiding crabs',hero:'mermaid',world:'ocean',mode:'treasure',c:['#1ec8e8','#2b6fd6']},
{n:'Space Explorer',t:'an astronaut exploring outer space at night',hero:'astronaut',world:'space',mode:'explore',c:['#3a1a7a','#7b5cff']},
{n:'Magical Ice Cream Factory',t:'a penguin catching ice cream in an ice cream factory',hero:'penguin',world:'icecream',mode:'collect',c:['#ff9ad5','#6fd6ff']},
{n:'Flying Dragon Adventure',t:'a dragon flying in the clouds and collecting gems',hero:'dragon',world:'sky',mode:'fly',c:['#ff8a3d','#ffcf3f']},
{n:'Princess Castle Adventure',t:'a princess saving lost puppies in a castle',hero:'princess',world:'castle',mode:'rescue',c:['#b36bff','#ff8fd0']},
{n:'Superhero City',t:'a superhero saving lost chicks from storms in a big city',hero:'superhero',world:'city',mode:'rescue',c:['#2b6fd6','#ff4f6d']},
{n:'Donut World',t:'a puppy dodging bees in donut world and eating donuts',hero:'puppy',world:'donut',mode:'dodge',c:['#c98a5a','#ff8fc8']},
{n:'Pirate Island',t:'a pirate parrot hunting for treasure on pirate island',hero:'parrot',world:'pirate',mode:'treasure',c:['#19a7c3','#e0bf62']},
{n:'Robot Adventure',t:'a memory puzzle with a robot in a robot factory',hero:'robot',world:'robot',mode:'puzzle',c:['#4b5d82','#22d3ee']},
{n:'Rainbow Obstacle Course',t:'a dino jumping over an obstacle course on a rainbow',hero:'dino',world:'rainbow',mode:'platform',c:['#19c37d','#ffd23f']}
];
const SECRETS=[
{h:'dragon',w:'icecream',n:'Frosty Dragon Freeze'},{h:'unicorn',w:'space',n:'Galaxy Unicorn'},
{h:'robot',w:'ocean',n:'Submarine Robot'},{h:'parrot',w:'space',n:'Space Pirates'},
{h:'penguin',w:'volcano',n:'Toasty Penguin'},{h:'puppy',w:'donut',n:'Donut Doggo'},
{h:'mermaid',w:'candy',n:'Candy Sea Mermaid'},{h:'superhero',w:'castle',n:'Castle Hero'},
{h:'dino',w:'jungle',n:'Dino Jungle Party'},{h:'octopus',w:'pirate',n:'Eight-Arm Pirate'}
];
const UNLOCKS=[
{c:25,k:'hero',id:'panda',t:'New character: Panda',e:'🐼'},
{c:55,k:'world',id:'volcano',t:'New world: Volcano Island',e:'🌋'},
{c:85,k:'ctrl',id:'gold',t:'Special gold controllers',e:'🎮'},
{c:120,k:'deco',id:'balloons',t:'Shop decoration: balloons',e:'🎈'},
{c:160,k:'phone',id:'rainbow',t:'Phone upgrade: Rainbow phone, faster making',e:'📱'},
{c:200,k:'tv',id:'tv2',t:'A second TV for the shop',e:'📺'},
{c:250,k:'hero',id:'octopus',t:'New character: Octopus',e:'🐙'},
{c:310,k:'world',id:'snow',t:'New world: Snow Land',e:'❄️'},
{c:370,k:'deco',id:'disco',t:'Shop decoration: disco ball',e:'🪩'},
{c:440,k:'hero',id:'owl',t:'New character: Owl',e:'🦉'},
{c:520,k:'phone',id:'gold',t:'Phone upgrade: Golden phone',e:'✨'},
{c:600,k:'ctrl',id:'rainbow',t:'Special rainbow controllers',e:'🌈'},
{c:700,k:'hero',id:'frog',t:'New character: Frog',e:'🐸'}
];
const DEF_POWER={race:'speed',fly:'jump',platform:'jump',treasure:'magnet',explore:'speed',collect:'magnet',dodge:'shield',puzzle:'slow',rescue:'shield'};
const OBST_E={rocks:'🪨',bees:'🐝',clouds:'⛈️',crabs:'🦀',ghosts:'👻',meteors:'☄️'};
const byId=(a,id)=>a.find(x=>x.id===id)||a[0];
/* ================= saved progress (this browser only, no personal data) ================= */
const SKEY='kidopia-v1';
let SAVE={coins:0,stars:0,games:0,unl:[],secrets:[],best:0,mute:false,made:[]};
try{const s=JSON.parse(localStorage.getItem(SKEY)||'null');if(s&&typeof s==='object')Object.assign(SAVE,s);}catch(e){}
function save(){try{localStorage.setItem(SKEY,JSON.stringify(SAVE));}catch(e){}}
const has=(k,id)=>SAVE.unl.indexOf(k+':'+id)>=0;
const okHero=h=>!h.u||has('hero',h.id);
const okWorld=w=>!w.u||has('world',w.id);
/* ================= canvas ================= */
const cv=document.getElementById('cv'),ctx=cv.getContext('2d');
let W=0,H=0,DPR=1;
const TOUCH=('ontouchstart' in window)||navigator.maxTouchPoints>0;
function resize(){
W=window.innerWidth;H=window.innerHeight;
DPR=Math.min(window.devicePixelRatio||1,W*H>900000?1.5:2);
cv.width=Math.round(W*DPR);cv.height=Math.round(H*DPR);
}
window.addEventListener('resize',resize);resize();
const EC={};
function emo(c,e,x,y,size,rot,alpha){
let k=EC[e];
if(!k){
k=document.createElement('canvas');k.width=k.height=128;const g=k.getContext('2d');
if(!(window.KidArt&&KidArt.draw(g,e))){g.font='96px '+EMOF;g.textAlign='center';g.textBaseline='middle';g.fillText(e,64,72);}EC[e]=k;
}
if(rot||alpha!=null){c.save();c.translate(x,y);if(rot)c.rotate(rot);if(alpha!=null)c.globalAlpha*=alpha;c.drawImage(k,-size/2,-size/2,size,size);c.restore();}
else c.drawImage(k,x-size/2,y-size/2,size,size);
}
function rr(c,x,y,w,h,r){r=Math.min(r,w/2,h/2);c.beginPath();c.moveTo(x+r,y);c.arcTo(x+w,y,x+w,y+h,r);c.arcTo(x+w,y+h,x,y+h,r);c.arcTo(x,y+h,x,y,r);c.arcTo(x,y,x+w,y,r);c.closePath();}
function ell(c,x,y,rx,ry){c.beginPath();c.ellipse(x,y,rx,ry,0,0,Math.PI*2);}
function txt(c,s,x,y,size,col,align,stroke){
c.font='700 '+size+'px '+FONT;c.textAlign=align||'center';c.textBaseline='middle';
if(stroke){c.lineWidth=size/5;c.strokeStyle=stroke;c.lineJoin='round';c.strokeText(s,x,y);}
c.fillStyle=col;c.fillText(s,x,y);
}
function wrap(c,s,maxW,size){
c.font='700 '+size+'px '+FONT;const words=String(s).split(' '),lines=[];let cur='';
for(const w of words){const t=cur?cur+' '+w:w;if(c.measureText(t).width>maxW&&cur){lines.push(cur);cur=w;}else cur=t;}
if(cur)lines.push(cur);return lines;
}
/* ================= people ================= */
const NAMES=['Mia','Leo','Zara','Omar','Ava','Kai','Lily','Noah','Sofia','Ravi','Emma','Yuki','Nora','Sam','Ella','Theo','Maya','Ben','Aria','Finn','Lena','Jay','Ivy','Max','Rosa','Ali','Hana','Luca'];
const SKIN=['#ffdbb4','#f1c27d','#e0ac69','#c68642','#8d5524','#ffe0c4','#b97a4a'];
const HAIR=['#2b1a10','#5a3214','#a0522d','#f4c542','#e8743b','#1a1a1a','#7b4fd6','#ff6fb5','#3fa8ff'];
const SHIRT=['#ff4f6d','#3fa8ff','#19c37d','#ffd23f','#ff8a3d','#9b5cff','#ff6fb5','#22d3ee','#ffffff'];
const PANTS=['#2d3a8c','#3b2f2f','#5b6b8a','#7b3fa0','#1f6f5f','#c0392b'];
const PERS=[
{id:'excited',hi:'Hi hi hi! I LOVE video games!',know:'I already know what I want!',dunno:'So many games... I can\'t pick!',wait:'I can\'t wait!',couch:'Let\'s play together!'},
{id:'shy',hi:'Um... hello. Can you make me a game?',know:'I have an idea... is that okay?',dunno:'I don\'t know what I like yet.',wait:'Ooh...',couch:'Will you play with me?'},
{id:'silly',hi:'Knock knock! It\'s me, your best customer!',know:'My idea is SUPER silly!',dunno:'Bloop! My brain is empty!',wait:'Wiggle wiggle!',couch:'Couch power, go!'},
{id:'curious',hi:'Wow! Can you really make any game?',know:'I thought of a game on the way here!',dunno:'What kinds of games can you make?',wait:'How does the magic phone work?',couch:'Look, it\'s on the TV!'},
{id:'dreamy',hi:'I dreamed about a magic game last night...',know:'I remember my dream game!',dunno:'My dream was a bit fuzzy...',wait:'So sparkly!',couch:'Just like my dream!'}
];
let seedN=1;
function mkLook(){
const robot=Math.random()<.12;
return {skin:pick(SKIN),hair:pick(HAIR),hs:ri(0,5),shirt:pick(SHIRT),pants:pick(PANTS),hat:Math.random()<.45?ri(1,5):0,
glasses:Math.random()<.2,robot,metal:pick(['#9fb6d6','#c7a0ff','#7fe0c8','#ffb36b']),print:ri(0,3)};
}
function mkPerson(o){return Object.assign({x:-160,y:800,tx:-160,facing:1,walk:0,moving:false,sit:false,happy:0,talk:0,wave:0,ctrl:false,
seed:(seedN++)*1.7,bubble:null,speed:250,arrive:null,scale:1},o);}
const OWNER=mkPerson({x:720,y:760,tx:720,facing:-1,owner:true,look:{skin:'#f1c27d',hair:'#3b1d0e',hs:3,shirt:'#ffd23f',pants:'#47208f',hat:5,glasses:false,robot:false,print:0}});
function say(p,text,dur){p.bubble={text,t:dur||3.2,age:0};p.talk=Math.min(2.2,.5+text.length*.03);SFX.blip();}
function drawPerson(c,p,T){
const L=p.look,s=p.scale||1,sd=p.seed;
c.save();c.translate(p.x,p.y);c.scale(s*p.facing,s);
const ph=p.walk;
let bob=p.moving?-Math.abs(Math.sin(ph))*7:Math.sin(T*2.2+sd)*1.5;
if(p.happy>0)bob=-Math.abs(Math.sin(T*9+sd))*22;
c.fillStyle='rgba(30,0,60,.18)';ell(c,0,2,46,10);c.fill();
const sitY=p.sit?-62:0;
// legs
c.fillStyle=L.pants;
if(p.sit){
rr(c,-22,-84,70,22,10);c.fill();rr(c,30,-80,20,78,9);c.fill();
rr(c,-6,-84,60,22,10);c.fill();
c.fillStyle='#fff';rr(c,26,-8,34,12,6);c.fill();
} else {
const a=p.moving?Math.sin(ph)*.55:0;
for(const sg of [-1,1]){
c.save();c.translate(sg*11,-72+bob*.4);c.rotate(a*sg);c.fillStyle=L.pants;rr(c,-9,0,18,68,9);c.fill();
c.fillStyle=L.robot?'#556':'#fff';rr(c,-11,58,26,12,6);c.fill();c.restore();
}
}
c.translate(0,bob+sitY);
// body
if(L.robot){c.fillStyle=L.metal;rr(c,-34,-152,68,84,14);c.fill();c.fillStyle='#fff8';rr(c,-18,-136,36,22,6);c.fill();
c.fillStyle=Math.sin(T*6+sd)>0?'#ff4f6d':'#4cf2a0';ell(c,0,-92,6,6);c.fill();}
else{c.fillStyle=L.shirt;rr(c,-31,-150,62,84,24);c.fill();
c.fillStyle='rgba(255,255,255,.35)';
if(L.print===1){ell(c,0,-112,12,12);c.fill();}
else if(L.print===2){c.fillRect(-31,-122,62,10);}
else if(L.print===3){emo(c,'⭐',0,-112,26);}
}
if(p.apron){c.fillStyle='#9b5cff';rr(c,-24,-130,48,64,10);c.fill();txt(c,'K',0,-104,30,'#ffd23f');}
// arms
c.lineCap='round';c.lineWidth=15;c.strokeStyle=L.robot?L.metal:L.shirt;
const armA=p.moving?Math.sin(ph)*.6:0;
const arm=(sg,ang,len)=>{c.save();c.translate(sg*30,-140);c.rotate(ang);c.beginPath();c.moveTo(0,0);c.lineTo(0,len);c.stroke();
c.fillStyle=L.robot?'#ccd':L.skin;ell(c,0,len+4,9,9);c.fill();c.restore();};
if(p.ctrl){arm(-1,-1.0,44);arm(1,-1.25,48);
const cc=has('ctrl','rainbow')?'#ff4fa3':has('ctrl','gold')?'#ffc21a':'#2b2b3a';
c.fillStyle=cc;rr(c,10,-128,52,26,12);c.fill();c.fillStyle='#4cf2a0';ell(c,48,-118,4,4);c.fill();c.fillStyle='#ff4f6d';ell(c,40,-112,4,4);c.fill();}
else if(p.wave>0){arm(-1,.1-armA,50);arm(1,Math.PI*0.85+Math.sin(T*12)*.35,50);}
else if(p.happy>0){arm(-1,Math.PI*0.8,50);arm(1,Math.PI*0.8,50);}
else if(p.holdPhone){arm(-1,-.9,44);arm(1,-1.2,46);
c.fillStyle='#111';rr(c,22,-158,30,50,7);c.fill();const gl=.5+.5*Math.sin(T*8);
c.fillStyle='rgba(255,'+(150+gl*100|0)+',255,1)';rr(c,25,-154,24,42,5);c.fill();}
else{arm(-1,.15+armA,52);arm(1,-.15-armA,52);}
// head
const hy=-196;
if(L.robot){
c.strokeStyle='#889';c.lineWidth=5;c.beginPath();c.moveTo(0,hy-44);c.lineTo(0,hy-66);c.stroke();
c.fillStyle=Math.sin(T*4+sd)>0?'#ffd23f':'#ff4fa3';ell(c,0,hy-70,8,8);c.fill();
c.fillStyle=L.metal;rr(c,-44,hy-44,88,84,20);c.fill();
c.fillStyle='#223';rr(c,-32,hy-24,64,34,12);c.fill();
const bl=((T+sd)%3.5)<.12;c.fillStyle='#4cf2ff';
if(bl){c.fillRect(-22,hy-8,14,4);c.fillRect(8,hy-8,14,4);}else{rr(c,-22,hy-16,14,18,4);c.fill();rr(c,8,hy-16,14,18,4);c.fill();}
c.strokeStyle='#4cf2ff';c.lineWidth=4;c.beginPath();
if(p.talk>0){ell(c,0,hy+24,9,3+Math.abs(Math.sin(T*18))*5);c.stroke();}else{c.arc(0,hy+18,10,.2,Math.PI-.2);c.stroke();}
c.restore();return;
}
c.fillStyle=L.hair;
if(L.hs===1||L.hs===3&&p.owner){rr(c,-48,hy-40,96,p.owner?120:104,40);c.fill();}
c.fillStyle=L.skin;ell(c,0,hy,44,44);c.fill();
ell(c,-43,hy+4,8,10);c.fill();ell(c,43,hy+4,8,10);c.fill();
// hair front
c.fillStyle=L.hair;
c.beginPath();c.arc(0,hy-4,46,Math.PI*1.03,Math.PI*1.97);c.quadraticCurveTo(20,hy-22,-10,hy-20);c.quadraticCurveTo(-34,hy-18,-45,hy-4);c.fill();
if(L.hs===2){for(let i=0;i<7;i++){const a=Math.PI*(1.05+i*.15);ell(c,Math.cos(a)*44,hy+Math.sin(a)*44,15,15);c.fill();}}
if(L.hs===3){ell(c,-52,hy-4,15,15);c.fill();ell(c,52,hy-4,15,15);c.fill();}
if(L.hs===4){ell(c,0,hy-50,20,18);c.fill();}
if(L.hs===5){c.beginPath();for(let i=0;i<5;i++){const x=-36+i*18;c.moveTo(x-10,hy-34);c.lineTo(x,hy-62);c.lineTo(x+10,hy-34);}c.fill();}
// face
const bl=((T+sd)%4)<.13;
for(const ex of [-15,15]){
if(bl){c.strokeStyle='#2a1460';c.lineWidth=3;c.beginPath();c.moveTo(ex-7,hy-4);c.lineTo(ex+7,hy-4);c.stroke();}
else{c.fillStyle='#fff';ell(c,ex,hy-4,9,11);c.fill();c.fillStyle='#2a1460';ell(c,ex+3,hy-2,5,6.5);c.fill();c.fillStyle='#fff';ell(c,ex+5,hy-5,2,2);c.fill();}
}
c.fillStyle='rgba(255,90,120,.35)';ell(c,-26,hy+12,8,5);c.fill();ell(c,26,hy+12,8,5);c.fill();
c.fillStyle='#8a2040';
if(p.talk>0){ell(c,3,hy+20,8,3+Math.abs(Math.sin(T*16))*6);c.fill();}
else if(p.happy>0||p.ctrl){c.beginPath();c.arc(3,hy+14,13,0,Math.PI);c.fill();c.fillStyle='#ff8fa8';ell(c,3,hy+22,6,3);c.fill();}
else{c.strokeStyle='#8a2040';c.lineWidth=3.5;c.beginPath();c.arc(3,hy+12,10,.25,Math.PI-.25);c.stroke();}
if(L.glasses){c.strokeStyle='#2a1460';c.lineWidth=3;ell(c,-15,hy-4,13,12);c.stroke();ell(c,15,hy-4,13,12);c.stroke();c.beginPath();c.moveTo(-2,hy-4);c.lineTo(2,hy-4);c.stroke();}
// hats
if(L.hat===1){c.fillStyle=L.shirt==='#ffffff'?'#ff4f6d':L.shirt;c.beginPath();c.arc(0,hy-18,44,Math.PI,0);c.fill();rr(c,0,hy-24,64,12,6);c.fill();}
if(L.hat===2){c.fillStyle='#3fa8ff';c.beginPath();c.arc(0,hy-14,46,Math.PI,0);c.fill();c.fillStyle='#fff';rr(c,-47,hy-22,94,14,7);c.fill();ell(c,0,hy-62,10,10);c.fill();}
if(L.hat===3){c.fillStyle='#ff4fa3';c.beginPath();c.moveTo(18,hy-40);c.lineTo(46,hy-58);c.lineTo(46,hy-22);c.closePath();c.moveTo(18,hy-40);c.lineTo(-8,hy-60);c.lineTo(-8,hy-22);c.closePath();c.fill();ell(c,18,hy-40,8,8);c.fill();}
if(L.hat===4){c.strokeStyle='#ffd23f';c.lineWidth=8;c.beginPath();c.arc(0,hy,44,Math.PI*1.12,Math.PI*1.88);c.stroke();}
if(L.hat===5){c.fillStyle='#ffc21a';c.beginPath();c.moveTo(-26,hy-36);c.lineTo(-26,hy-62);c.lineTo(-13,hy-48);c.lineTo(0,hy-68);c.lineTo(13,hy-48);c.lineTo(26,hy-62);c.lineTo(26,hy-36);c.closePath();c.fill();c.fillStyle='#ff4fa3';ell(c,0,hy-46,4,4);c.fill();}
c.restore();
}
/* ================= the shop scene ================= */
const SHOP={door:0,lights:0,tvOn:0,tvGame:null,tv2:0};
const BOXES=[];for(let i=0;i<18;i++)BOXES.push({c:pick(['#ff4f6d','#3fa8ff','#19c37d','#ffd23f','#9b5cff','#ff8a3d','#22d3ee']),e:pick(['🦄','🚀','🍩','🐉','🏰','🤖','🏝️','🍦','🍭','🦸','🌈','🐠'])});
const CAM={x:800,sc:1,oy:0,vw:1600,cx:null};
const TV={x:1150,y:190,w:340,h:220};
const SEATS=[1265,1395];const WAITS=[940,1030];
function uiReserve(){
let bottom=0,right=0;
for(const el of ui.children){
if(el.classList.contains('hide'))continue;
const r=el.getBoundingClientRect();if(!r.height)continue;
if(el.classList.contains('sheet')||(el.classList.contains('phone')&&r.width>W*.8))bottom=Math.max(bottom,H-r.top+6);
else if(el.classList.contains('phone'))right=Math.max(right,W-r.left+6);
}
return {bottom,right};
}
function camSetup(focus,dt){
const R=uiReserve(),aw=W-R.right,port=aw/H<1.25,area=Math.max(H*.32,H-R.bottom);
let sc,oy;
if(!port&&R.bottom<H*.2){sc=Math.min(aw/1600,H/900);oy=(H-900*sc)/2;}
else if(port&&R.bottom<=H*.42){sc=(H*.6)/900;oy=H*.03;}
else{sc=Math.min(area/560,aw/700);oy=area-880*sc;}
const k=dt?Math.min(1,dt*4):1;
CAM.sc=dt?lerp(CAM.sc,sc,k):sc;CAM.oy=dt?lerp(CAM.oy,oy,k):oy;CAM.cx=dt&&CAM.cx!=null?lerp(CAM.cx,aw/2,k):aw/2;
const vw=aw/CAM.sc;const tx=vw>=1600?800:clamp(focus,vw/2,1600-vw/2);
CAM.x=dt?lerp(CAM.x,tx,Math.min(1,dt*2.2)):tx;CAM.vw=vw;
}
function w2s(x,y){return [(x-CAM.x)*CAM.sc+CAM.cx,y*CAM.sc+CAM.oy];}
function drawShop(c,T,people){
c.setTransform(DPR*CAM.sc,0,0,DPR*CAM.sc,DPR*(CAM.cx-CAM.x*CAM.sc),DPR*CAM.oy);
const Lt=SHOP.lights;
const x0=CAM.x-CAM.cx/CAM.sc-20,x1=CAM.x+(W-CAM.cx)/CAM.sc+20;
// wall
let g=c.createLinearGradient(0,-400,0,700);g.addColorStop(0,'#3a1580');g.addColorStop(1,Lt>.5?'#8a3fc8':'#4a2080');
c.fillStyle=g;c.fillRect(x0,-600,x1-x0,1300);
c.fillStyle='rgba(255,255,255,.05)';for(let x=Math.floor(x0/80)*80;x<x1;x+=80)c.fillRect(x,-600,40,1200);
c.fillStyle='#6a2fb0';c.fillRect(x0,600,x1-x0,100);c.fillStyle='#ffd23f';c.fillRect(x0,596,x1-x0,8);
// floor
c.fillStyle='#ffcf8a';c.fillRect(x0,700,x1-x0,900);
c.fillStyle='#ffb86b';for(let x=Math.floor(x0/100)*100;x<x1;x+=100)for(let r=0;r<3;r++)if(((x/100)+r)%2===0)c.fillRect(x,700+r*70,100,70);
c.fillStyle='rgba(120,40,0,.12)';c.fillRect(x0,700,x1-x0,10);
// rug under couch
c.fillStyle='#ff4fa3';ell(c,1330,830,250,50);c.fill();c.fillStyle='#ffd23f';ell(c,1330,830,200,36);c.fill();
// string lights
c.strokeStyle='#2a1460';c.lineWidth=3;c.beginPath();
for(let x=Math.floor(x0/60)*60;x<x1+60;x+=60){const y=34+Math.sin(x*.05)*10;if(x===Math.floor(x0/60)*60)c.moveTo(x,y);else c.lineTo(x,y);}c.stroke();
const BC=['#ff4f6d','#ffd23f','#4cf2a0','#3fa8ff','#ff8fd0'];
for(let x=Math.floor(x0/60)*60;x<x1+60;x+=60){
const k=Math.round(x/60),on=Lt>((k%7+7)%7)/7&&((Math.floor(T*2)+k)%5!==0);const y=44+Math.sin(x*.05)*10;
c.fillStyle=on?BC[((k%5)+5)%5]:'#553';ell(c,x,y,8,11);c.fill();
if(on){c.globalAlpha=.25;ell(c,x,y,20,20);c.fill();c.globalAlpha=1;}
}
// big sign
c.save();c.translate(800,128);
c.fillStyle='#2a1460';rr(c,-260,-70,520,140,36);c.fill();
c.strokeStyle=Lt>.3?'#ff4fa3':'#553';c.lineWidth=8;rr(c,-252,-62,504,124,30);c.stroke();
const word='KIDOPIA',cols=['#ff4f6d','#ffd23f','#4cf2a0','#3fa8ff','#ff8fd0','#ff8a3d','#c79bff'];
c.font='700 84px '+FONT;c.textBaseline='middle';c.textAlign='center';
for(let i=0;i<7;i++){
const x=-195+i*65,y=-14+Math.sin(T*3+i*.7)*4;const on=Lt>(i+1)/8;
if(on){c.globalAlpha=.35;c.fillStyle=cols[i];c.fillText(word[i],x,y+3);c.globalAlpha=1;}
c.fillStyle=on?cols[i]:'#4a3a6a';c.fillText(word[i],x,y);
}
txt(c,'The Magical Game Shop',0,42,26,Lt>.9?'#ffd23f':'#6a5a8a');
c.restore();
// door
const dx=80,dw=190,dy=330,dh=370;
c.fillStyle='#ff8a3d';rr(c,dx-18,dy-20,dw+36,dh+20,14);c.fill();
g=c.createLinearGradient(0,dy,0,dy+dh);g.addColorStop(0,'#8fd8ff');g.addColorStop(.7,'#d8f4ff');g.addColorStop(.71,'#b8b8c8');g.addColorStop(1,'#9a9aac');
c.fillStyle=g;c.fillRect(dx,dy,dw,dh);
emo(c,'🌳',dx+40,dy+200,80);emo(c,'☀️',dx+150,dy+60,50);
const op=SHOP.door*88;
c.fillStyle='rgba(180,230,255,.45)';c.strokeStyle='#ddd';c.lineWidth=6;
c.fillRect(dx-op,dy,dw/2,dh);c.strokeRect(dx-op,dy,dw/2,dh);c.fillRect(dx+dw/2+op,dy,dw/2,dh);c.strokeRect(dx+dw/2+op,dy,dw/2,dh);
c.fillStyle='#ff8a3d';c.fillRect(dx-40,dy-20,22,dh+20);c.fillRect(dx+dw+18,dy-20,22,dh+20);
c.fillStyle='#2a1460';rr(c,dx+30,dy-90,130,50,14);c.fill();txt(c,'OPEN',dx+95,dy-64,34,Lt>.2?(Math.sin(T*4)>-.6?'#ff4f6d':'#ff9ab0'):'#553');
c.fillStyle='#19c37d';rr(c,dx-10,dy+dh-6,dw+20,14,6);c.fill();
// shelves
for(let r=0;r<3;r++){
const sy=300+r*110;c.fillStyle='#ffb86b';c.fillRect(310,sy+76,240,12);
for(let i=0;i<6;i++){const b=BOXES[r*6+i];c.fillStyle=b.c;rr(c,318+i*38,sy+(i%2?12:4),32,72-(i%2?8:0),5);c.fill();emo(c,b.e,334+i*38,sy+40,24);}
}
emo(c,'🪴',1095,640,110);
// poster or second TV
if(has('tv','tv2')){
c.fillStyle='#111';rr(c,880,215,200,130,12);c.fill();
const sg=c.createLinearGradient(890,0,1070,0);const hh=(T*60)%360;
sg.addColorStop(0,'hsl('+hh+',90%,60%)');sg.addColorStop(1,'hsl('+((hh+120)%360)+',90%,60%)');
c.fillStyle=sg;c.fillRect(890,225,180,110);
const last=SAVE.made.length?SAVE.made[SAVE.made.length-1]:null;
txt(c,last?'NEW GAME!':'KIDOPIA TV',980,250,20,'#fff',0,'#2a1460');
emo(c,last?last.e:'🎮',980,295,46+Math.sin(T*4)*4);
c.fillStyle='#333';c.fillRect(970,345,20,30);
} else {
c.fillStyle='#fff';rr(c,890,215,180,150,10);c.fill();c.fillStyle='#ff4fa3';rr(c,898,223,164,134,8);c.fill();
txt(c,'GAME',980,250,26,'#fff');txt(c,'IDEAS?',980,280,26,'#ffd23f');emo(c,'💡',980,330,44);
}
if(has('deco','balloons')){
for(const [bx,cc] of [[300,'🎈'],[575,'🎈'],[1545,'🎈']]){emo(c,cc,bx,250+Math.sin(T*1.5+bx)*8,70);emo(c,cc,bx+28,280+Math.sin(T*1.7+bx)*8,60);}
}
if(has('deco','disco')){
c.strokeStyle='#ccc';c.lineWidth=2;c.beginPath();c.moveTo(1050,0);c.lineTo(1050,150);c.stroke();emo(c,'🪩',1050,180,70,T);
c.save();c.globalCompositeOperation='lighter';for(let i=0;i<8;i++){const a=T*.8+i*.8;c.fillStyle=BC[i%5]+'55';ell(c,1050+Math.cos(a)*420,420+Math.sin(a*1.3)*160,14,8);c.fill();}c.restore();
}
// TV
c.fillStyle='#14142a';rr(c,TV.x-16,TV.y-16,TV.w+32,TV.h+32,18);c.fill();
drawTVScreen(c,TV.x,TV.y,TV.w,TV.h,T);
c.fillStyle='#14142a';c.fillRect(TV.x+TV.w/2-12,TV.y+TV.h+16,24,40);rr(c,TV.x+60,TV.y+TV.h+50,TV.w-120,16,8);c.fill();
c.fillStyle=SHOP.tvOn>0?'#4cf2a0':'#ff4f6d';ell(c,TV.x+TV.w-6,TV.y+TV.h+6,4,4);c.fill();
// counter (back part), owner, counter front
const owner=people.find(p=>p.owner);
c.fillStyle='#c2387a';c.fillRect(580,555,290,20);
// couch back
c.fillStyle='#2b8be0';rr(c,1150,600,360,120,34);c.fill();
c.fillStyle='#3fa8ff';for(let i=0;i<3;i++){rr(c,1168+i*110,614,104,90,26);c.fill();}
// waiting bean bags back
for(const wx of WAITS){c.fillStyle=wx===WAITS[0]?'#19c37d':'#ff8a3d';ell(c,wx,770,52,40);c.fill();}
c.fillStyle='#fff';rr(c,955,690,70,10,4);c.fill();c.fillStyle='#ffb86b';c.fillRect(985,700,10,60);
emo(c,'🍿',968,672,36);emo(c,'🧃',1008,674,32);
if(!owner||!owner.behind){c.fillStyle='#ff4fa3';rr(c,570,565,310,200,18);c.fill();c.fillStyle='#ffd23f';c.fillRect(570,600,310,14);for(let i=0;i<5;i++)emo(c,'⭐',612+i*58,680,30);}
// people sorted by depth
const ord=people.slice().sort((a,b)=>(a.owner&&a.behind?-1:0)-(b.owner&&b.behind?-1:0)||a.y-b.y);
for(const p of ord){
if(p===owner&&owner.behind){drawPerson(c,p,T);
c.fillStyle='#ff4fa3';rr(c,570,565,310,200,18);c.fill();c.fillStyle='#ffd23f';c.fillRect(570,600,310,14);
for(let i=0;i<5;i++)emo(c,'⭐',612+i*58,680,30,Math.sin(T+i)*.2);
c.fillStyle='#fff';rr(c,590,520,60,40,10);c.fill();emo(c,'🍬',620,530,34);
continue;}
drawPerson(c,p,T);
}
// couch arms (front)
c.fillStyle='#2070c0';rr(c,1128,660,50,130,22);c.fill();rr(c,1482,660,50,130,22);c.fill();
c.fillStyle='#2b8be0';rr(c,1160,720,340,52,16);c.globalAlpha=.0;c.fill();c.globalAlpha=1;
if(!people.some(p=>p.ctrl)){const cc=has('ctrl','rainbow')?'#ff4fa3':has('ctrl','gold')?'#ffc21a':'#2b2b3a';c.fillStyle=cc;rr(c,1135,646,40,20,9);c.fill();rr(c,1487,646,40,20,9);c.fill();}
// spotlights
if(Lt>.6){c.save();c.globalCompositeOperation='lighter';
for(const [sx,sp] of [[420,.7],[1320,.9]]){const a=Math.sin(T*sp)*.25;c.save();c.translate(sx,0);c.rotate(a);
const sg2=c.createLinearGradient(0,0,0,800);sg2.addColorStop(0,'rgba(255,240,180,.22)');sg2.addColorStop(1,'rgba(255,240,180,0)');
c.fillStyle=sg2;c.beginPath();c.moveTo(-20,0);c.lineTo(20,0);c.lineTo(160,800);c.lineTo(-160,800);c.closePath();c.fill();c.restore();}
c.restore();}
if(Lt<1){c.fillStyle='rgba(10,0,30,'+(0.6*(1-Lt))+')';c.fillRect(x0,-600,x1-x0,1600);}
}
function drawTVScreen(c,x,y,w,h,T){
const on=SHOP.tvOn,gm=SHOP.tvGame;
c.save();c.beginPath();c.rect(x,y,w,h);c.clip();
c.fillStyle='#0b0b1a';c.fillRect(x,y,w,h);
if(on<=0){c.fillStyle='rgba(255,255,255,.06)';c.beginPath();c.moveTo(x+w*.6,y);c.lineTo(x+w*.8,y);c.lineTo(x+w*.4,y+h);c.lineTo(x+w*.2,y+h);c.fill();}
else if(on<1){const lh=Math.max(2,h*Math.max(0,on*2-1));c.fillStyle='#fff';c.fillRect(x+w/2-w*Math.min(1,on*2)/2,y+h/2-lh/2,w*Math.min(1,on*2),lh);}
else if(gm){
const wd=gm.world;const g=c.createLinearGradient(0,y,0,y+h);g.addColorStop(0,wd.sky[0]);g.addColorStop(1,wd.sky[1]);
c.fillStyle=g;c.fillRect(x,y,w,h);c.fillStyle=wd.gr;c.fillRect(x,y+h*.72,w,h*.28);
for(let i=0;i<5;i++)emo(c,wd.items[i%3],x+((i*83+T*40)%w),y+h*.3+Math.sin(T*2+i)*20,26);
emo(c,gm.hero.e,x+w/2,y+h*.58+Math.sin(T*5)*-8,70);
const ls=wrap(c,gm.name,w-30,24);ls.slice(0,2).forEach((l,i)=>txt(c,l,x+w/2,y+24+i*26,24,'#fff',0,'#2a1460'));
if(S.st==='tvon'&&Math.sin(T*5)>0)txt(c,'PRESS PLAY',x+w/2,y+h-18,18,'#ffd23f',0,'#2a1460');
} else {
const hh=(T*40)%360;c.fillStyle='hsl('+hh+',70%,30%)';c.fillRect(x,y,w,h);txt(c,'KIDOPIA',x+w/2,y+h/2,40,'#fff',0,'#2a1460');
}
c.restore();
}
function drawBubble(c,p,T){
const b=p.bubble;if(!b)return;
const size=30,lines=wrap(c,b.text,380,size),bw=Math.min(420,Math.max(...lines.map(l=>c.measureText(l).width))+44),bh=lines.length*36+30;
const hy=p.y-270*(p.scale||1)-(p.sit?62:0);
let bx=clamp(p.x,CAM.x-CAM.vw/2+bw/2+10,CAM.x+CAM.vw/2-bw/2-10),by=hy-bh;
const sc=Math.min(1,b.age*6);
c.save();c.translate(bx,by+bh);c.scale(sc,sc);c.translate(-bx,-(by+bh));
c.fillStyle='#fff';c.strokeStyle='#2a1460';c.lineWidth=5;rr(c,bx-bw/2,by,bw,bh,22);c.fill();c.stroke();
c.beginPath();const tx=clamp(p.x,bx-bw/2+30,bx+bw/2-30);c.moveTo(tx-14,by+bh-3);c.lineTo(tx,by+bh+22);c.lineTo(tx+14,by+bh-3);c.fill();
c.beginPath();c.moveTo(tx-14,by+bh);c.lineTo(tx,by+bh+22);c.lineTo(tx+14,by+bh);c.stroke();
lines.forEach((l,i)=>txt(c,l,bx,by+33+i*36,size,'#2a1460'));
c.restore();
}
function drawStorefront(c,T){
c.setTransform(DPR,0,0,DPR,0,0);
const g=c.createLinearGradient(0,0,0,H);g.addColorStop(0,'#2a1460');g.addColorStop(.6,'#ff7eb3');g.addColorStop(1,'#ffcf8a');
c.fillStyle=g;c.fillRect(0,0,W,H);
for(let i=0;i<30;i++){c.fillStyle='rgba(255,255,255,'+(.4+.4*Math.sin(T*2+i))+')';ell(c,(i*137)%W,(i*71)%(H*.4),1.5,1.5);c.fill();}
const s=Math.min(W/900,H/900)*1.1,cx=W/2,base=H*.7;
c.save();c.translate(cx,base);c.scale(s,s);
c.fillStyle='#7b5cff';rr(c,-380,-460,760,460,30);c.fill();
c.fillStyle='#9b7bff';for(let i=0;i<8;i++)c.fillRect(-380+i*95,-460,48,460);
c.fillStyle='#ff4fa3';c.beginPath();for(let i=0;i<9;i++){c.moveTo(-400+i*90,-470);c.arc(-355+i*90,-470,45,Math.PI,0);}c.fill();
c.fillStyle='#fff';for(let i=0;i<9;i++){c.beginPath();c.arc(-355+i*90,-470,45,Math.PI,Math.PI*1.5);c.lineTo(-355+i*90,-470);c.fill();}
c.fillStyle='#2a1460';rr(c,-300,-600,600,130,40);c.fill();c.strokeStyle='#ffd23f';c.lineWidth=8;rr(c,-292,-592,584,114,34);c.stroke();
const cols=['#ff4f6d','#ffd23f','#4cf2a0','#3fa8ff','#ff8fd0','#ff8a3d','#c79bff'];c.font='700 92px '+FONT;c.textAlign='center';c.textBaseline='middle';
for(let i=0;i<7;i++){c.fillStyle=cols[i];c.fillText('KIDOPIA'[i],-210+i*70,-535+Math.sin(T*3+i*.7)*6);}
for(const wx of [-330,130]){c.fillStyle='#ffe9a8';rr(c,wx,-380,200,220,16);c.fill();c.fillStyle='#ffd23f';c.fillRect(wx,-280,200,6);
emo(c,wx<0?'📺':'🎮',wx+100,-320,70);emo(c,wx<0?'🛋️':'📱',wx+100,-210,70);}
c.fillStyle='#ff8a3d';rr(c,-90,-330,180,330,10);c.fill();c.fillStyle='#bfeaff';c.fillRect(-75,-315,150,315);
c.fillStyle='rgba(255,255,255,.5)';c.fillRect(-75,-315,4,315);c.fillRect(-2,-315,4,315);
c.fillStyle='#9a9aac';c.fillRect(-W/s,0,W*2/s,400);c.fillStyle='#b8b8c8';c.fillRect(-W/s,0,W*2/s,20);
c.restore();
for(let i=0;i<3;i++){const px=((T*60+i*W/3)%(W+200))-100;const p=TITLE_KIDS[i];p.x=px/s;p.y=0;p.moving=true;p.walk=T*9+i;
c.save();c.setTransform(DPR*s*.8,0,0,DPR*s*.8,DPR*0,DPR*(base+30*s));drawPerson(c,Object.assign({},p,{x:px/(s*.8)}),T);c.restore();}
}
const TITLE_KIDS=[0,1,2].map(()=>mkPerson({look:mkLook()}));
/* ================= particles ================= */
let PW=[],PS=[];
function confettiW(x,y,n){for(let i=0;i<n;i++)PW.push({x,y,vx:rnd(-400,400),vy:rnd(-900,-300),g:1400,life:rnd(1.2,2.2),t:0,c:pick(['#ff4f6d','#ffd23f','#4cf2a0','#3fa8ff','#ff8fd0','#fff']),s:rnd(8,16),r:rnd(0,6)});}
function sparkW(x,y,n,col){for(let i=0;i<n;i++){const a=rnd(0,6.28),v=rnd(80,320);PW.push({x,y,vx:Math.cos(a)*v,vy:Math.sin(a)*v,g:0,life:rnd(.4,.9),t:0,c:col||'#ffd23f',s:rnd(6,12),star:1});}}
function stepParts(arr,dt){for(const p of arr){p.t+=dt;p.vy+=(p.g||0)*dt;p.x+=p.vx*dt;p.y+=p.vy*dt;p.r=(p.r||0)+dt*6;}return arr.filter(p=>p.t<p.life);}
function drawParts(c,arr){for(const p of arr){const a=1-p.t/p.life;c.globalAlpha=Math.max(0,a);c.fillStyle=p.c;
if(p.star){ell(c,p.x,p.y,p.s*a,p.s*a);c.fill();}else{c.save();c.translate(p.x,p.y);c.rotate(p.r);c.fillRect(-p.s/2,-p.s/4,p.s,p.s/2);c.restore();}}c.globalAlpha=1;}
/* ================= state ================= */
const S={st:'title',t:0,creative:false,timeLeft:300,paused:false,day:null,cur:null,waiting:null,people:[OWNER],cfg:null,wish:null,lastModes:[],stream:[],zoom:0};
const ui=document.getElementById('ui'),hud=document.getElementById('hud'),toastEl=document.getElementById('toast');
let toastT=null;
function toast(m,ms){toastEl.textContent=m;toastEl.classList.add('on');clearTimeout(toastT);toastT=setTimeout(()=>toastEl.classList.remove('on'),ms||2600);}
function h(tag,cls,html){const e=document.createElement(tag);if(cls)e.className=cls;if(html!=null)e.innerHTML=html;return e;}
function clearUI(){ui.innerHTML='';}
function setSt(st){S.st=st;S.t=0;}
function btn(label,cls,fn){const b=h('button','btn '+(cls||''),label);b.addEventListener('click',()=>{SFX.tap();fn();});return b;}
function updHud(){
if(!S.day)return;
document.getElementById('hCoins').textContent='🪙 '+S.day.coins;
document.getElementById('hStars').textContent='⭐ '+S.day.stars;
const ck=document.getElementById('hClock');
if(S.creative){ck.textContent='∞ Creative';ck.classList.remove('low');}
else{const t=Math.max(0,Math.ceil(S.timeLeft));ck.textContent='⏰ '+Math.floor(t/60)+':'+String(t%60).padStart(2,'0');ck.classList.toggle('low',t<=30);}
}
document.getElementById('bMute').textContent=SAVE.mute?'🔇':'🔊';
document.getElementById('bFree').classList.add('hide');
document.getElementById('bMute').addEventListener('click',toggleMute);
document.getElementById('bMenu').addEventListener('click',()=>{SFX.tap();openMenu();});
function toggleMute(){SAVE.mute=!SAVE.mute;save();if(master)master.gain.value=SAVE.mute?0:.85;
document.querySelectorAll('.muteb').forEach(b=>b.textContent=SAVE.mute?'🔇':'🔊');document.getElementById('bMute').textContent=SAVE.mute?'🔇':'🔊';if(!SAVE.mute)initAudio();}
/* ---------- title ---------- */
function showTitle(){
setSt('title');clearUI();hud.classList.add('hide');setMusic('shop');
const c=h('div','card title-card');
c.appendChild(h('h1','','Kidopia'));
c.appendChild(h('div','by','The Magical Game Shop<br>Game idea by a young player'));
c.appendChild(h('p','lead','Customers bring their game ideas. You make each game on a magic phone. Then everyone plays it on the big TV!'));
const r=h('div','row');
r.appendChild(btn('▶ Open the shop','g',()=>{initAudio();startDay(false);}));
r.appendChild(btn('∞ Creative mode','w',()=>{initAudio();startDay(true);}));
c.appendChild(r);
if(SAVE.games)c.appendChild(h('p','small','Your shop so far: '+SAVE.games+' games made, '+SAVE.coins+' coins, '+SAVE.unl.length+' prizes unlocked.'));
c.appendChild(h('p','small','A day in the shop lasts 5 minutes. 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><a href="../">All games</a> · <a href="../../cases/kidopia/">How it was made</a>'));
ui.appendChild(c);
}
/* ---------- a day in the shop ---------- */
function startDay(creative){
S.creative=creative;S.timeLeft=300;S.day={coins:0,stars:0,games:0,happy:0,sat:[],made:[],unl:[],cust:0};
S.people=[OWNER];S.cur=null;S.waiting=null;S.lastModes=[];PW=[];PS=[];
Object.assign(OWNER,{x:720,y:760,tx:720,facing:-1,behind:true,sit:false,ctrl:false,happy:0,holdPhone:false,bubble:null,arrive:null});
SHOP.door=0;SHOP.lights=0;SHOP.tvOn=0;SHOP.tvGame=null;
clearUI();hud.classList.remove('hide');updHud();setMusic('shop');
setSt('open');CAM.x=420;
}
function spawnCustomer(toWait){
const c=mkPerson({look:mkLook(),name:pick(NAMES),pers:pick(PERS),decided:Math.random()<.55,speed:rnd(240,300)});
if(S.cur&&c.name===S.cur.name)c.name=pick(NAMES);
S.day.cust++;S.people.push(c);
if(toWait){c.tx=WAITS[0];c.arrive=()=>{c.sit=true;c.facing=1;c.y=800;say(c,c.pers.wait,2.5);};}
return c;
}
function walkTo(p,x,cb){p.tx=x;p.arrive=cb||null;}
function callNext(c){
S.cur=c;c.sit=false;c.wave=0;c.happy=0;
if(!S.creative&&S.timeLeft<100){c.final=true;setTimeout(()=>toast('Last customer of the day! 🌟'),300);}
setSt('enter');
walkTo(c,505,()=>{c.facing=1;setSt('talk');showTalk(c);});
}
function showTalk(c){
clearUI();
say(c,c.pers.hi+' '+(c.decided?c.pers.know:c.pers.dunno),4);
const s=h('div','sheet');
s.appendChild(h('h2','',esc(c.name)+' wants a new game!'));
s.appendChild(h('p','sub','What does '+esc(c.name)+' say?'));
const o=h('div','opts');
const mk=(cls,e,t,fn)=>{const b=h('button','opt '+cls,'<span class="e">'+e+'</span><span>'+t+'</span>');b.addEventListener('click',()=>{SFX.pick();fn();});o.appendChild(b);};
mk('o1','💡','I have my own game idea!',()=>ownIdea(c));
mk('o2','🖼️','Show me some game ideas!',()=>showIdeas(c));
mk('o3','🎁','Surprise me!',()=>surprise(c));
s.appendChild(o);ui.appendChild(s);
}
function availHeroes(){return HEROES.filter(h=>okHero(h)&&!h.custom);}
function availWorlds(){return WORLDS.filter(w=>okWorld(w)&&!w.custom);}
function freshMode(){const ms=MODES.filter(m=>S.lastModes.indexOf(m.id)<0);return pick(ms.length?ms:MODES).id;}
/* ---------- the idea engine (idea.js) turns words into a game plan ---------- */
const MIXES=[{id:'none',n:'Nothing',e:'⭕'},{id:'collect',n:'+ Collecting',e:'🧺'},{id:'rescue',n:'+ Rescue friends',e:'🛟'},
{id:'dodge',n:'+ More dodging',e:'💨'},{id:'treasure',n:'+ Big treasure',e:'💰'},{id:'clock',n:'+ Beat the clock',e:'⏱️'}];
function reg(list,o){const f=list.find(x=>x.id===o.id);if(f){Object.assign(f,o);return f;}list.push(o);return o;}
function planFrom(text){
const P=window.KidIdea.read(text,{worldOf:id=>WORLDS.find(w=>w.id===id)});
let hero=null;
if(P.heroE){const known=HEROES.find(x=>x.e===P.heroE&&!x.custom);hero=known&&okHero(known)?known.id:reg(HEROES,{id:'x_'+P.heroWord,n:P.heroN,e:P.heroE,custom:1}).id;}
else hero=pick(availHeroes()).id;
let world=null;
if(P.place){const pl=window.KidIdea.places[P.place];const base=byId(WORLDS,pl?pl.w:P.place);
if(pl&&pl.x)world=reg(WORLDS,Object.assign({},base,pl.x,{id:'x_'+P.place,custom:1,u:0})).id;
else if(!okWorld(base))world=reg(WORLDS,Object.assign({},base,{id:'x_'+base.id,custom:1,u:0})).id;
else world=base.id;}
else world=P.heroSea?'ocean':P.heroFl?'sky':pick(availWorlds()).id;
const w={hero,world,mode:P.mode,plan:P,text};
if(P.mix)w.mix=P.mix;if(P.power)w.power=P.power;if(P.music)w.music=P.music;
if(P.haz)w.obs=reg(OBST,{id:'x_'+P.haz,n:(P.hazN||'Enemie')+'s',e:P.haz,custom:1}).id;
w.items=P.items.slice();w.friendsE=P.friends.slice();
w.mods={night:P.night,weather:P.weather,size:P.size,tint:P.tint,im:P.im,hm:P.hm};
w.level=P.level||'easy';
const hr=byId(HEROES,hero),wd=byId(WORLDS,world);
w.name=window.KidIdea.nameFor(P,hr.n,wd.s,P.mode,P.mix);
return w;
}
function ideaHTML(P){
const roleOf={};P.marks.forEach(m=>{roleOf[m.w]=m.role;});
return P.text.split(/(\s+)/).map(tok=>{
const k=tok.toLowerCase().replace(/[^a-z']/g,'');
let r=roleOf[k];
if(!r){for(const m of P.marks){if(k.length>2&&(k.indexOf(m.w)===0||m.w.indexOf(k)===0)){r=m.role;break;}}}
return r?'<b class="r-'+r+'">'+esc(tok)+'</b>':esc(tok);
}).join('');
}
function showReader(c,w,title){
clearUI();const P=w.plan;
const s=h('div','sheet reader');
s.appendChild(h('h2','',title||'🧠 The magic engine reads the idea'));
s.appendChild(h('div','said','“'+ideaHTML(P)+'”'));
const chips=h('div','chips');
const all=P.notes.slice();
if(w.mix)all.push({w:'',e:'➕',what:'Mixed: '+window.KidIdea.MIX_LABEL[w.mix],role:'mode'});
all.forEach((n,i)=>{const ch=h('span','chip r-'+n.role,'<span class="e">'+n.e+'</span> '+(n.w?'<i>'+esc(n.w)+'</i> → ':'')+esc(n.what));ch.style.animationDelay=(i*0.18)+'s';chips.appendChild(ch);});
if(!all.length)chips.appendChild(h('span','chip','🤔 I will pick the rest!'));
s.appendChild(chips);
P.swaps.forEach(m=>s.appendChild(h('p','sub',esc(m))));
const hr=byId(HEROES,w.hero),wd=byId(WORLDS,w.world),md=byId(MODES,w.mode);
s.appendChild(h('div','wish','<span class="e">'+hr.e+' '+wd.e+' '+md.e+(w.mix?' ➕':'')+'</span> <b>'+esc(w.name)+'</b>'));
const r=h('div','row');r.appendChild(btn('📱 Make it on the phone!','y',()=>openPhone(c,w)));s.appendChild(r);
const ti=h('div','typein');const inp=h('input');inp.type='text';inp.maxLength=120;inp.placeholder='Type any game idea...';inp.setAttribute('aria-label','Type a game idea');inp.autocomplete='off';
const go=btn('✨','p',()=>{
const v=inp.value.trim();if(!v){inp.focus();return;}
const nw=planFrom(v);nw.typed=true;c.wish=nw;say(c,'Yes! I love that idea!',3);SFX.pick();
showReader(c,nw,'🧠 The magic engine reads your idea');
});
inp.addEventListener('keydown',e=>{if(e.key==='Enter')go.click();e.stopPropagation();});
ti.appendChild(inp);ti.appendChild(go);s.appendChild(ti);
ui.appendChild(s);
}
function ownIdea(c){
const text=window.KidIdea.makeRequest({avoid:S.lastModes});
const w=c.wish=planFrom(text);
say(c,(c.decided?'':'Hmm... I\'ve got it! ')+text,6);
showReader(c,w,'🧠 The magic engine reads '+esc(c.name)+'’s idea');
}
function showIdeas(c){
clearUI();say(c,'Ooh, show me! Can I mix two?',3);
const s=h('div','sheet');s.appendChild(h('h2','','Pick one idea, or pick two to mix them!'));
const g=h('div','ideas');const n=(W>H&&H<520)?6:(W<=380?4:6);
const list=shuffle(IDEAS.slice()).slice(0,n);let sel=[];
const go=btn('📱 Make it!','y',()=>{
if(!sel.length)return;
const a=sel[0],b=sel[1];
const text=b?a.t+', mixed with '+b.t.replace(/^an? /,''):a.t;
const w=planFrom(text);if(!b)w.name=a.n;
c.wish=w;say(c,b?'Mix them together!':'That one! '+a.n+'!',3);
showReader(c,w,b?'🧠 The magic engine mixes two ideas':'🧠 The magic engine reads the idea');
});go.disabled=true;
list.forEach(id=>{
const card=h('button','idea','<span class="chk"></span><span class="art">'+byId(HEROES,id.hero).e+byId(WORLDS,id.world).e+'</span><span class="nm">'+esc(id.n)+'</span>');
card.dataset.c0=id.c[0];card.dataset.c1=id.c[1];
card.addEventListener('click',()=>{
SFX.pick();const k=sel.indexOf(id);
if(k>=0)sel.splice(k,1);else{if(sel.length>=2)sel.shift();sel.push(id);}
g.querySelectorAll('.idea').forEach((el,i)=>{const on=sel.indexOf(list[i]);el.classList.toggle('on',on>=0);el.querySelector('.chk').textContent=on>=0?(on===0?'1️⃣':'2️⃣'):'';});
go.disabled=!sel.length;go.innerHTML=sel.length===2?'✨ Mix them!':'📱 Make it!';
});
g.appendChild(card);
});
s.appendChild(g);
g.querySelectorAll('.idea').forEach(el=>{el.style.background='linear-gradient(150deg,'+el.dataset.c0+','+el.dataset.c1+')';});
const r=h('div','row');r.appendChild(btn('🔄 More ideas','w',()=>showIdeas(c)));r.appendChild(go);s.appendChild(r);
ui.appendChild(s);
}
function surprise(c){
let text;
if(Math.random()<.3){const sc=pick(SECRETS.filter(x=>!byId(HEROES,x.h).u||okHero(byId(HEROES,x.h))));
const hh=byId(HEROES,sc.h).n.toLowerCase(),wd=byId(WORLDS,sc.w).n.toLowerCase();text='A '+hh+' in the '+wd+' '+pick(['racing','flying','exploring','collecting treats','dodging storms','saving friends','hunting for treasure']);}
else text=window.KidIdea.makeRequest({avoid:S.lastModes});
const w=planFrom(text);w.surprise=true;c.wish=w;say(c,'Surprise me! I love surprises! 🎁',3);
showReader(c,w,'🎁 The magic engine dreams up a surprise');
}
/* ---------- the magic phone ---------- */
let PH=null;
const ADJ=['Super','Magic','Mega','Sparkly','Turbo','Happy','Cosmic','Wild','Tiny','Giant'];
function autoName(cfg){const hr=byId(HEROES,cfg.hero),wd=byId(WORLDS,cfg.world),md=byId(MODES,cfg.mode);
return (pick(ADJ)+' '+hr.n+' '+(wd.s===hr.n?'':wd.s+' ')+md.noun).replace('Pirate Parrot Pirate','Pirate Parrot').slice(0,34);}
function openPhone(c,w){
clearUI();OWNER.holdPhone=true;say(OWNER,'Let me make it on my magic phone!',2.5);
const cfg={hero:w.hero,world:w.world,mode:w.mode,mix:w.mix||'none',power:w.power||DEF_POWER[w.mode],
goal:w.mix==='collect'||w.mode==='collect'?'collect':w.mix==='rescue'||w.mode==='rescue'?'friends':'finish',
obs:w.obs||'world',music:w.music||byId(WORLDS,w.world).mus,level:w.level||'easy',
items:w.items||[],friendsE:w.friendsE||[],mods:w.mods||{}};
cfg.name=w.name||autoName(cfg);
S.cfg=cfg;S.wish=w;setSt('phone');
PH={tab:'mode',named:!!w.name};
const ph=h('div','phone'+(has('phone','gold')?' gold':has('phone','rainbow')?' rainbow':''));
const scr=h('div','pscr');ph.appendChild(scr);
scr.appendChild(h('div','notch'));
const top=h('div','ptop','<span class="ttl">✨ Magic Game Maker · for '+esc(c.name)+'</span>');
const x=h('button','x','✖');x.setAttribute('aria-label','Close the phone');x.addEventListener('click',()=>{SFX.tap();OWNER.holdPhone=false;showTalk(c);setSt('talk');});
top.appendChild(x);scr.appendChild(top);
const nm=h('div','pname');const inp=h('input');inp.type='text';inp.maxLength=34;inp.value=cfg.name;inp.setAttribute('aria-label','Game name');inp.autocomplete='off';
inp.addEventListener('input',()=>{cfg.name=inp.value;PH.named=true;});inp.addEventListener('keydown',e=>e.stopPropagation());
const dice=h('button','','🎲');dice.setAttribute('aria-label','Make up a new name');dice.addEventListener('click',()=>{SFX.pick();cfg.name=autoName(cfg);inp.value=cfg.name;PH.named=false;});
nm.appendChild(inp);nm.appendChild(dice);scr.appendChild(nm);
const tabs=h('div','tabs');scr.appendChild(tabs);
const match=h('div','match');scr.appendChild(match);
const tiles=h('div','tiles');scr.appendChild(tiles);
const foot=h('div','pfoot');const cb=h('button','create','✨ CREATE GAME ✨');cb.addEventListener('click',()=>{createGame(c);});foot.appendChild(cb);scr.appendChild(foot);
PH.el={ph,scr,tabs,tiles,match,inp};
ui.appendChild(ph);renderPhone();
}
const mine=(list,k)=>()=>list.filter(x=>!x.custom||x.id===S.cfg[k]||(S.wish&&x.id===S.wish[k]));
const TABS=[
{k:'mode',n:'Game type',e:'🎮',list:()=>MODES},{k:'mix',n:'Mix in',e:'➕',list:()=>MIXES},{k:'hero',n:'Hero',e:'🦸',list:mine(HEROES,'hero')},{k:'world',n:'World',e:'🌍',list:mine(WORLDS,'world')},
{k:'power',n:'Power',e:'⚡',list:()=>POWERS},{k:'goal',n:'Goal',e:'🎯',list:()=>GOALS},{k:'obs',n:'Obstacles',e:'🚧',list:mine(OBST,'obs')},
{k:'music',n:'Music',e:'🎵',list:()=>MUSICS},{k:'level',n:'Level',e:'🎚️',list:()=>LEVELS}
];
function matchInfo(){
const w=S.wish,cfg=S.cfg;if(!w||w.surprise)return {n:1,of:1,keys:[]};
const keys=['hero','world','mode'].concat(['mix','power','music','obs'].filter(k=>w[k]));
let n=0;keys.forEach(k=>{if(cfg[k]===w[k])n++;});return {n,of:keys.length,keys};
}
function extrasLine(cfg){
const m=cfg.mods||{},bits=[];
if(cfg.items&&cfg.items.length)bits.push(cfg.items.join('')+' treats');
if(cfg.friendsE&&cfg.friendsE.length)bits.push(cfg.friendsE.join('')+' friends');
if(m.night)bits.push('🌙 night');if(m.weather)bits.push(window.KidIdea.WEA_E[m.weather]+' '+m.weather);
if(m.size>1)bits.push('⬆️ giant hero');if(m.size<1)bits.push('⬇️ tiny hero');if(m.tint)bits.push('🎨 sky');
return bits.length?'<br><span class="e">🧠</span> From the words: '+bits.join(' · '):'';
}
function renderPhone(){
const {tabs,tiles,match,inp}=PH.el,cfg=S.cfg,w=S.wish;
tabs.innerHTML='';
TABS.forEach(t=>{const b=h('button','tab'+(PH.tab===t.k?' on':''),'<span class="e">'+t.e+'</span>'+t.n+(w&&w[t.k]&&!w.surprise?'<span class="dot">❤️</span>':''));
b.addEventListener('click',()=>{SFX.tap();PH.tab=t.k;renderPhone();});tabs.appendChild(b);});
const mi=matchInfo();
match.innerHTML=(w.surprise?'<span class="e">🎁</span> A surprise! Anything you pick will be a happy surprise.':'<span class="e">❤️</span> = what '+esc(S.cur.name)+' wished for. You have '+mi.n+' of '+mi.of+'.')+extrasLine(cfg);
tiles.innerHTML='';
const tab=TABS.find(t=>t.k===PH.tab);
tab.list().forEach(it=>{
const locked=(tab.k==='hero'&&!okHero(it))||(tab.k==='world'&&!okWorld(it));
const b=h('button','tile'+(cfg[tab.k]===it.id?' on':'')+(locked?' lock':'')+(it.custom?' idea':''),'<span class="e">'+(locked?'🔒':it.e)+'</span>'+esc(it.n)+(w&&w[tab.k]===it.id&&!w.surprise?'<span class="heart">❤️</span>':''));
b.addEventListener('click',()=>{
if(locked){const u=UNLOCKS.find(x=>x.id===it.id);toast('Earn '+(u?u.c:'more')+' coins in total to unlock '+it.n+'!');return;}
SFX.pick();cfg[tab.k]=it.id;
if(tab.k==='mix'){if(it.id==='collect')cfg.goal='collect';if(it.id==='rescue')cfg.goal='friends';}
if(!PH.named){cfg.name=autoName(cfg);inp.value=cfg.name;}
renderPhone();
});
tiles.appendChild(b);
});
}
function createGame(c){
const cfg=S.cfg;if(!cfg.name.trim())cfg.name=autoName(cfg);
SFX.create();setSt('creating');
const fast=has('phone','rainbow')||has('phone','gold');const dur=fast?1500:2300;
const hr=byId(HEROES,cfg.hero);
const mk=h('div','making','<div class="big">'+hr.e+'</div><div class="lbl">Drawing the hero...</div><div class="bar"><i></i></div>');
PH.el.scr.appendChild(mk);
const steps=['Drawing the hero...','Building the world...','Adding the music...','Adding magic sparkles...'];
const lbl=mk.querySelector('.lbl'),bar=mk.querySelector('.bar i');const t0=performance.now();
say(c,'Whoa! It\'s working!',2);
const iv=setInterval(()=>{const k=Math.min(1,(performance.now()-t0)/dur);bar.style.width=(k*100)+'%';lbl.textContent=steps[Math.min(3,Math.floor(k*4))];
if(k>=1){clearInterval(iv);transfer(c);}},60);
}
function transfer(c){
const cfg=S.cfg;
const r=PH.el.ph.getBoundingClientRect();const sx=r.left+r.width/2,sy=r.top+r.height*.4;
PH.el.ph.classList.add('fly');setTimeout(clearUI,600);
SFX.whoosh();setSt('transfer');OWNER.holdPhone=true;
const cols=['#ff4f6d','#ffd23f','#4cf2a0','#3fa8ff','#ff8fd0','#fff'];
const hr=byId(HEROES,cfg.hero),wd=byId(WORLDS,cfg.world);
S.stream=[];for(let i=0;i<70;i++)S.stream.push({sx:sx+rnd(-40,40),sy:sy+rnd(-60,60),d:rnd(0,.9),dur:rnd(.9,1.4),c:pick(cols),s:rnd(5,11),wob:rnd(-200,200),e:i%9===0?pick([hr.e,wd.items[0],'⭐']):null});
S.game={cfg,hero:hr,world:wd,name:cfg.name};
say(OWNER,'Zap! Off to the TV!',2);
c.wave=0;walkTo(c,SEATS[0],()=>{c.sit=true;c.facing=1;c.y=800;c.ctrl=true;});
}
function tvOn(){
setSt('tvon');SFX.tvon();SHOP.tvGame=S.game;SHOP.tvOn=.01;
const c=S.cur;OWNER.holdPhone=false;OWNER.behind=false;
walkTo(OWNER,SEATS[1],()=>{OWNER.sit=true;OWNER.facing=-1;OWNER.y=800;OWNER.ctrl=true;});
setTimeout(()=>{if(S.st!=='tvon')return;say(c,c.pers.couch,3);
clearUI();const s=h('div','sheet');s.appendChild(h('h2','','📺 '+esc(S.game.name)+' is on the TV!'));
s.appendChild(h('p','sub',esc(c.name)+' is on the couch with a controller. Join in!'));
const r=h('div','row');r.appendChild(btn('🎮 Play together!','g',startPlay));s.appendChild(r);ui.appendChild(s);},900);
}
function startPlay(){
clearUI();setSt('zoom');S.zoom=0;
if(!S.creative&&S.timeLeft>110&&!S.waiting&&!S.cur.final){S.waiting=spawnCustomer(true);}
}
/* ---------- results and the end of the day ---------- */
function gameDone(res){
const c=S.cur,cfg=S.cfg,day=S.day;
hud.classList.remove('hide');setMusic('shop');
SHOP.tvOn=1;
const mi=matchInfo(),match=mi.of?mi.n/mi.of:1;
const secret=SECRETS.find(x=>x.h===cfg.hero&&x.w===cfg.world);
const sat=Math.round(clamp(100*(.4*match+.6*(res.stars/3))+(secret?8:0),35,100));
let coins=10+res.stars*6+Math.round(match*10)+(secret?15:0)+Math.min(15,Math.floor(res.score/60));
day.coins+=coins;day.stars+=res.stars;day.games++;day.sat.push(sat);if(sat>=60)day.happy++;
const md=byId(MODES,cfg.mode),hr=byId(HEROES,cfg.hero);
day.made.push(hr.e+' '+cfg.name);S.lastModes.push(cfg.mode);if(S.lastModes.length>4)S.lastModes.shift();
SAVE.coins+=coins;SAVE.stars+=res.stars;SAVE.games++;SAVE.made.push({n:cfg.name.slice(0,34),e:hr.e});if(SAVE.made.length>30)SAVE.made.shift();
let newSecret=false;if(secret&&SAVE.secrets.indexOf(secret.n)<0){SAVE.secrets.push(secret.n);newSecret=true;}
const unl=[];UNLOCKS.forEach(u=>{if(SAVE.coins>=u.c&&!has(u.k,u.id)){SAVE.unl.push(u.k+':'+u.id);unl.push(u);day.unl.push(u);}});
save();updHud();
c.ctrl=false;OWNER.ctrl=false;c.sit=false;c.y=800;c.happy=3;OWNER.sit=false;OWNER.y=800;
const happy=sat>=60;
say(c,happy?pick(['Best. Game. Ever!','You\'re a game wizard!','I want to play it again!','That was AMAZING!']):'That was fun! Thank you!',3.5);
confettiW(c.x,560,happy?90:40);SFX.win();
setTimeout(()=>{if(unl.length)SFX.unlock();else SFX.coin();},700);
clearUI();setSt('result');
const cd=h('div','card');
cd.appendChild(h('div','big',happy?'😄':'🙂'));
cd.appendChild(h('h2','',esc(c.name)+(happy?' loved it!':' liked it!')));
cd.appendChild(h('div','stars','⭐'.repeat(res.stars)+'☆'.repeat(3-res.stars)));
cd.appendChild(h('p','lead',res.msg));
const st=h('div','stats');
st.innerHTML='<div class="stat"><b>+'+coins+' 🪙</b><span>coins</span></div><div class="stat"><b>'+sat+'%</b><span>happy</span></div>'+
(S.wish.surprise?'<div class="stat"><b>🎁</b><span>surprise game</span></div>':'<div class="stat"><b>'+'❤️'.repeat(mi.n)+(mi.n?'':'0')+'</b><span>wishes made true</span></div>');
cd.appendChild(st);
if(secret)cd.appendChild(h('div','unl','<span class="e">🤫</span> '+(newSecret?'New secret game found: ':'Secret game: ')+'<b>'+esc(secret.n)+'</b>!'));
unl.forEach(u=>cd.appendChild(h('div','unl','<span class="e">'+u.e+'</span> Unlocked! '+esc(u.t))));
const nx=UNLOCKS.find(u=>!has(u.k,u.id));
if(nx)cd.appendChild(h('p','small','Next prize at '+nx.c+' coins: '+nx.e+' '+esc(nx.t)+' (you have '+SAVE.coins+')'));
const r=h('div','row');
const end=!S.creative&&(c.final||S.timeLeft<=0);
r.appendChild(btn(end?'🎉 Finish the day':'▶ Next customer',end?'p':'g',()=>{clearUI();nextCustomer(end);}));
cd.appendChild(r);ui.appendChild(cd);
}
function nextCustomer(end){
const c=S.cur;c.happy=0;c.wave=1;say(c,'Bye! See you soon!',2);
walkTo(c,-220,()=>{S.people=S.people.filter(p=>p!==c);});
OWNER.behind=false;walkTo(OWNER,720,()=>{OWNER.behind=true;OWNER.facing=-1;OWNER.y=760;});OWNER.y=800;
setTimeout(()=>{SHOP.tvOn=0;SHOP.tvGame=null;},800);
if(end){setTimeout(endDay,900);setSt('leaving');return;}
const w=S.waiting;S.waiting=null;setSt('leaving');
setTimeout(()=>{
if(w){w.sit=false;w.y=800;callNext(w);}
else{const n=spawnCustomer(false);callNext(n);}
},700);
}
function endDay(){
setSt('end');clearUI();const d=S.day;
const avg=d.sat.length?Math.round(d.sat.reduce((a,b)=>a+b,0)/d.sat.length):0;
const rating=avg>=90?5:avg>=78?4:avg>=62?3:avg>=45?2:1;
SAVE.best=Math.max(SAVE.best,rating);save();
SFX.party();setTimeout(SFX.win,500);
confettiW(800,300,160);
OWNER.happy=4;say(OWNER,'What a great day at Kidopia!',4);
const cd=h('div','card');
cd.appendChild(h('h1','','Shop closed!'));
cd.appendChild(h('p','lead','What a magical day at Kidopia!'));
cd.appendChild(h('div','stars','⭐'.repeat(rating)+'☆'.repeat(5-rating)));
cd.appendChild(h('p','small','Shop rating: '+rating+' of 5 stars'));
const st=h('div','stats');
st.innerHTML=[['🎮 '+d.games,'games created'],['😄 '+d.happy,'happy customers'],['🪙 '+d.coins,'coins earned'],['⭐ '+d.stars,'stars collected'],['💖 '+avg+'%','customer happiness'],['🏆 '+rating+'/5','shop rating']]
.map(a=>'<div class="stat"><b>'+a[0]+'</b><span>'+a[1]+'</span></div>').join('');
cd.appendChild(st);
if(d.made.length)cd.appendChild(h('p','made','Games you made today:<br>'+d.made.map(esc).join('<br>')));
if(d.unl.length)cd.appendChild(h('div','unl','New today: '+d.unl.map(u=>'<span class="e">'+u.e+'</span>').join(' ')));
const r=h('div','row');
r.appendChild(btn('🔁 Play again','g',()=>startDay(false)));
r.appendChild(btn('∞ Creative mode','w',()=>startDay(true)));
cd.appendChild(r);
cd.appendChild(h('p','small','<a href="../">All games</a> · <a href="../../cases/kidopia/">How it was made</a>'));
ui.appendChild(cd);
}
function openMenu(){
if(S.st==='title'||S.paused)return;
S.paused=true;const old=Array.from(ui.children);old.forEach(e=>e.classList.add('hide'));
const cd=h('div','card');cd.appendChild(h('h2','','Paused'));
cd.appendChild(h('p','lead','Help customers make their dream games. Tap the choices, make the game on the magic phone, then press Play together and play it on the TV.'));
cd.appendChild(h('p','small','Controls in the TV games: drag on the screen or use the arrow keys to move. The big round button (or Space) is jump, boost or dash. In the puzzle, tap the cards.<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>Progress is saved only on this device. Kidopia asks for no names or personal details.'));
const r=h('div','row');
const close=()=>{cd.remove();old.forEach(e=>e.classList.remove('hide'));S.paused=false;};
r.appendChild(btn('▶ Keep playing','g',close));
r.appendChild(btn('🔁 New day','w',()=>{cd.remove();S.paused=false;if(G)G=null;gamebar.classList.add('hide');startDay(false);}));
r.appendChild(btn('∞ Creative','w',()=>{cd.remove();S.paused=false;if(G)G=null;gamebar.classList.add('hide');startDay(true);}));
r.appendChild(btn('🏠 Title','w',()=>{cd.remove();S.paused=false;if(G)G=null;gamebar.classList.add('hide');showTitle();}));
cd.appendChild(r);ui.appendChild(cd);
}
/* ================= the mini-game engine ================= */
let G=null;
const gamebar=h('div','gamebar hide');
(function(){const m=h('button','ib muteb',SAVE.mute?'🔇':'🔊');m.setAttribute('aria-label','Sound on or off');m.addEventListener('click',toggleMute);
const q=h('button','ib','✖');q.setAttribute('aria-label','Stop this game');q.addEventListener('click',()=>{if(G&&G.phase==='play'){G.phase='end';G.endT=0;G.endMsg='Game over!';}});
const p=h('button','ib','☰');p.setAttribute('aria-label','Menu');p.addEventListener('click',openMenu);
gamebar.appendChild(m);gamebar.appendChild(q);gamebar.appendChild(p);document.body.appendChild(gamebar);})();
const INP={ax:0,ay:0,act:false,actP:false,taps:[],keys:{},joy:null,actId:null,padAct:false};
function newGame(cfg,cust){
const lv={easy:0,medium:1,hard:2}[cfg.level]||0;
const md=cfg.mods||{};let wd=byId(WORLDS,cfg.world);const hr=byId(HEROES,cfg.hero);
if(md.tint)wd=Object.assign({},wd,{sky:md.tint});
const secret=!!SECRETS.find(x=>x.h===cfg.hero&&x.w===cfg.world);
const g={cfg,cust,mode:cfg.mode,lv,dif:[.85,1,1.2][lv],wd,hr,secret,
t:0,dur:[40,36,32][lv],score:0,hits:0,items:0,friends:0,main:false,phase:'intro',introT:0,endT:0,
inv:0,shield:cfg.power==='shield'?3:0,spd:cfg.power==='speed'?1.3:1,mag:cfg.power==='magnet'?150:0,dbl:cfg.power==='double'?2:1,
hz:cfg.power==='slow'?.65:1,jmp:cfg.power==='jump',
hazE:cfg.obs==='world'?wd.haz:byId(OBST,cfg.obs).e,itemE:cfg.items&&cfg.items.length?cfg.items:wd.items,pops:[],fx:[],shake:0,react:null,reactT:0,
W:800,H:540,cam:{x:0,y:0},o:[],p:{x:0,y:0,vx:0,vy:0,face:1}};
const fe=cfg.friendsE||[];g.frE=fe.concat(FRIENDS.filter(x=>fe.indexOf(x)<0));
g.im=md.im||1;g.hm=md.hm||1;g.hs=md.size||1;g.frOn=cfg.goal==='friends'||cfg.mix==='rescue';
if(cfg.mix==='collect')g.im*=1.5;if(cfg.mix==='dodge')g.hm*=1.5;if(cfg.mix==='treasure')g.bigT=true;
if(cfg.mix==='clock'){g.dur-=6;g.spd*=1.12;}
g.stage=1;g.won=0;g.mixN=0;g.L=[];g.base0={spd:g.spd,mag:g.mag,dbl:g.dbl};
g.goalN={collect:[10,12,14][lv],friends:3,score:[300,400,500][lv]}[cfg.goal]||0;
if(cfg.goal==='collect'&&cfg.mode==='collect')g.goalN=[18,22,26][lv];
if(cfg.goal==='collect'&&cfg.mode==='puzzle')g.goalN=0;
return g;
}
function gArea(){
const port=W/H<1;const ctrl=(TOUCH&&port&&G&&G.mode!=='puzzle')?Math.min(230,H*.3):0;
const top=0,aw=W,ah=H-ctrl;
return {x:0,y:top,w:aw,h:ah,ctrl};
}
function gSetup(g){
const A=gArea();g.H=540;g.W=clamp(Math.round(A.w/A.h*540),320,1100);g.sc=Math.min(A.w/g.W,A.h/g.H);
g.ox=A.x+(A.w-g.W*g.sc)/2;g.oy=A.y+(A.h-g.H*g.sc)/2;g.A=A;
}
function pop(g,x,y,t,col){g.pops.push({x,y,t,col:col||'#fff',age:0});}
function gfx(g,x,y,col,n){for(let i=0;i<(n||10);i++){const a=rnd(0,6.28),v=rnd(60,260);g.fx.push({x,y,vx:Math.cos(a)*v,vy:Math.sin(a)*v,life:rnd(.3,.7),t:0,c:col||pick(['#ffd23f','#fff','#ff8fd0','#4cf2ff']),s:rnd(3,7)});}}
function react(g,t){if(g.reactT>0&&Math.random()<.5)return;g.react=t;g.reactT=1.6;}
function gotItem(g,x,y){g.items++;g.score+=10*g.dbl;pop(g,x,y,'+'+10*g.dbl,'#ffd23f');gfx(g,x,y);SFX.collect();if(g.bigT&&Math.random()<.2){g.score+=40*g.dbl;pop(g,x,y-34,'Big treasure! +'+40*g.dbl,'#ffc21a');SFX.star();}if(g.items%5===0)react(g,pick(['Yay!','Wow, so many!','Go go go!','You\'re so good!']));}
function gotFriend(g,x,y){g.friends++;g.score+=50*g.dbl;pop(g,x,y,'Friend saved! +'+50*g.dbl,'#4cf2a0');gfx(g,x,y,'#4cf2a0',18);SFX.friend();react(g,'You saved a friend!');}
function hurt(g,x,y){
if(g.inv>0)return false;
if(g.starT>0){pop(g,x,y,'Star power!','#ffd23f');return false;}
if(g.shield>0){g.shield--;g.inv=1;pop(g,x,y,'Shield!','#4cf2ff');SFX.bonk();return false;}
g.hits++;g.inv=1.3;g.shake=.3;pop(g,x,y,'Oops!','#ff8fa8');SFX.hit();react(g,pick(['Oh no!','Watch out!','Try again!','Ouch, keep going!']));return true;
}
function realFinish(g,msg,main){if(g.phase==='end')return;g.main=main!==false;g.phase='end';g.endT=0;g.endMsg=msg||'You did it!';SFX.win();}
function finishMain(g,msg){stageDone(g,true,msg);}
/* ---- each kind of game ---- */
const MG={};
MG.race={
how:'Steer left and right. Tap the round button to boost!',btn:'⚡',
init(g){g.len=8400*(g.dur/36);g.base=290;g.dist=0;g.boost=0;g.cool=0;g.slow=0;g.p.x=g.W/2;g.p.y=g.H-110;g.rw=Math.min(g.W*.86,560);
const others=shuffle(HEROES.filter(x=>x.id!==g.hr.id&&!x.u)).slice(0,3);
g.riv=others.map((h,i)=>({e:h.e,d:-80-i*70,v:g.base*(.9+i*.03)*g.dif,x:g.W/2+(i-1)*g.rw*.28,fin:0}));
g.place=0;g.fin=0;
for(let d=500;d<g.len-200;d+=rnd(150,260)){
const x=g.W/2+rnd(-.4,.4)*g.rw;
if(Math.random()<Math.min(.7,.32*g.dif*g.hm))g.o.push({k:'haz',d,x,e:g.hazE});
else if(g.frOn&&Math.random()<.06)g.o.push({k:'fr',d,x,e:pick(g.frE)});
else for(let j=0;j<3;j++)g.o.push({k:'it',d:d+j*40,x,e:pick(g.itemE)});
}
},
update(g,dt,I){
const p=g.p;p.x=clamp(p.x+I.ax*430*g.spd*dt,g.W/2-g.rw/2+24,g.W/2+g.rw/2-24);
g.cool-=dt;if(I.actP&&g.cool<=0){g.boost=g.cfg.power==='speed'?1.8:1.2;g.cool=2.6;SFX.boost();}
g.boost-=dt;g.slow-=dt;
const v=g.base*g.dif*(g.boost>0?1.6:1)*(g.slow>0?.55:1)*(g.spd>1?1.08:1);g.dist+=v*dt;
for(const r of g.riv){const gap=r.d-g.dist;const rb=gap>500?.85:gap<-500?1.15:1;r.d+=r.v*rb*dt*(g.hz<1?.92:1);r.x+=Math.sin(g.t*1.3+r.v)*20*dt;if(r.d>=g.len&&!r.fin){r.fin=++g.fin;}}
for(const o of g.o){if(o.gone)continue;let sy=p.y-(o.d-g.dist);
if(g.mag&&o.k!=='haz'&&Math.abs(sy-p.y)<g.mag){o.x+=(p.x-o.x)*Math.min(1,dt*5);}
if(Math.abs(sy-p.y)<36&&Math.abs(o.x-p.x)<40){o.gone=1;
if(o.k==='it'){gotItem(g,o.x,sy);g.boost=Math.max(g.boost,.25);}
else if(o.k==='fr')gotFriend(g,o.x,sy);
else if(hurt(g,o.x,sy))g.slow=1;}}
if(g.dist>=g.len){g.place=g.fin+1;g.score+=[150,100,60,30][g.place-1]*g.dbl;finishMain(g,['1st place! 🥇','2nd place! 🥈','3rd place! 🥉','You finished! 🏁'][g.place-1]);}
},
draw(g,c,T){
const p=g.p,wd=g.wd;c.fillStyle=wd.gr;c.fillRect(0,0,g.W,g.H);
const off=g.dist%120;
for(let y=-120;y<g.H+120;y+=120){for(const sx of [40,g.W-40]){emo(c,wd.deco[(Math.abs(Math.floor((y-off+g.dist)/120))+(sx>100?1:0))%wd.deco.length],sx,y+off,44);}}
const L=g.W/2-g.rw/2;c.fillStyle=wd.gr2;c.fillRect(L,0,g.rw,g.H);
const rc=['#ff4f6d','#ffd23f','#4cf2a0','#3fa8ff'];for(let i=0;i<4;i++){c.fillStyle=rc[i];c.fillRect(L-8-i*6,0,6,g.H);c.fillRect(L+g.rw+2+i*6,0,6,g.H);}
c.fillStyle='rgba(255,255,255,.6)';for(let y=-60;y<g.H+60;y+=60){c.fillRect(g.W/2-g.rw/6-3,y+(g.dist%60),6,30);c.fillRect(g.W/2+g.rw/6-3,y+(g.dist%60),6,30);}
const fy=p.y-(g.len-g.dist);if(fy>-40&&fy<g.H+40){for(let i=0;i<g.rw/20;i++)for(let j=0;j<2;j++){c.fillStyle=(i+j)%2?'#fff':'#222';c.fillRect(L+i*20,fy+j*20-20,20,20);}}
for(const o of g.o){if(o.gone)continue;const sy=p.y-(o.d-g.dist);if(sy<-40||sy>g.H+40)continue;emo(c,o.e,o.x,sy,o.k==='haz'?52:40,o.k==='it'?Math.sin(T*4+o.d)*.2:0);}
for(const r of g.riv){const sy=p.y-(r.d-g.dist);if(sy<-60||sy>g.H+60)continue;kart(c,r.x,sy,r.e,'#9b5cff',T);}
if(g.boost>0)for(let i=0;i<4;i++)emo(c,'✨',p.x+rnd(-14,14),p.y+40+i*16,24,0,.8-i*.18);
if(!(g.inv>0&&Math.floor(T*12)%2))kart(c,p.x,p.y,g.hr.e,'#ff4fa3',T,g.shield>0);
const pr=clamp(g.dist/g.len,0,1);c.fillStyle='rgba(0,0,0,.3)';rr(c,g.W-26,70,12,g.H-160,6);c.fill();c.fillStyle='#ffd23f';rr(c,g.W-26,70+(g.H-160)*(1-pr),12,(g.H-160)*pr,6);c.fill();
let place=1;for(const r of g.riv)if(r.d>g.dist)place++;txt(c,['1st','2nd','3rd','4th'][place-1],g.W-20,g.H-70,22,'#fff','center','#2a1460');
},
goal(g){return '🏁 '+Math.round(clamp(g.dist/g.len,0,1)*100)+'%';}
};
function kart(c,x,y,e,col,T,sh){c.fillStyle='rgba(0,0,0,.25)';ell(c,x,y+26,30,9);c.fill();c.fillStyle=col;rr(c,x-26,y-4,52,32,12);c.fill();c.fillStyle='#222';rr(c,x-30,y-2,10,14,4);c.fill();rr(c,x+20,y-2,10,14,4);c.fill();rr(c,x-30,y+16,10,14,4);c.fill();rr(c,x+20,y+16,10,14,4);c.fill();emo(c,e,x,y-12+Math.sin(T*12)*1.5,46);if(sh){c.strokeStyle='rgba(76,242,255,.8)';c.lineWidth=4;ell(c,x,y,40,40);c.stroke();}}
MG.fly={
how:'Hold the round button (or push up) to fly up. Let go to glide down.',btn:'⬆️',
init(g){g.p.x=g.W*.26;g.p.y=g.H/2;g.p.vy=0;g.scroll=0;g.next=0;g.nextH=1.5;g.portal=null;g.flyT=g.dur-6;},
update(g,dt,I){
const p=g.p,sp=250*g.dif;g.scroll+=sp*dt;
if(Math.abs(I.ay)>.25&&!I.act)p.vy=lerp(p.vy,I.ay*330*g.spd,Math.min(1,dt*8));
else if(I.act)p.vy-=(g.jmp?1500:1200)*dt;
else p.vy+=650*dt;
p.vy=clamp(p.vy,-420,380);p.y+=p.vy*dt;if(p.y<70){p.y=70;p.vy=0;}if(p.y>g.H-50){p.y=g.H-50;p.vy=-200;}
g.next-=dt;if(g.next<=0&&!g.portal){g.next=rnd(.35,.6)/g.im;const by=rnd(110,g.H-90);
if(g.frOn&&Math.random()<.06)g.o.push({k:'fr',x:g.W+40,y:by,e:pick(g.frE),v:sp});
else for(let j=0;j<3;j++)g.o.push({k:'it',x:g.W+40+j*44,y:by+Math.sin(j)*20,e:pick(g.itemE),v:sp});}
g.nextH-=dt;if(g.nextH<=0&&!g.portal){g.nextH=rnd(1.1,1.7)/(g.dif*g.hm);g.o.push({k:'haz',x:g.W+50,y:rnd(90,g.H-70),e:g.hazE,v:sp*rnd(1.1,1.4)*g.hz,w:rnd(0,3)});}
if(g.t>g.flyT&&!g.portal)g.portal={x:g.W+80,y:g.H/2};
if(g.portal){g.portal.x-=sp*dt;if(Math.hypot(g.portal.x-p.x,g.portal.y-p.y)<70||g.portal.x<p.x-20){g.score+=100*g.dbl;finishMain(g,'You flew all the way! 🌀');}}
for(const o of g.o){if(o.gone)continue;o.x-=o.v*dt;if(o.k==='haz')o.y+=Math.sin(g.t*2+o.w)*60*dt;
if(g.mag&&o.k!=='haz'&&Math.hypot(o.x-p.x,o.y-p.y)<g.mag){o.x+=(p.x-o.x)*dt*5;o.y+=(p.y-o.y)*dt*5;}
if(Math.hypot(o.x-p.x,o.y-p.y)<(o.k==='haz'?36:40)){o.gone=1;if(o.k==='it')gotItem(g,o.x,o.y);else if(o.k==='fr')gotFriend(g,o.x,o.y);else hurt(g,o.x,o.y);}
if(o.x<-60)o.gone=1;}
g.o=g.o.filter(o=>!o.gone);
},
draw(g,c,T){const p=g.p;sideBG(g,c,g.scroll,T);
for(const o of g.o)emo(c,o.e,o.x,o.y,o.k==='haz'?56:40,o.k==='it'?Math.sin(T*4+o.x*.02)*.2:0);
if(g.portal){emo(c,'🌀',g.portal.x,g.portal.y,140,T*3);}
for(let i=0;i<3;i++)emo(c,'✨',p.x-30-i*18,p.y+rnd(-6,6),20,0,.7-i*.2);
if(!(g.inv>0&&Math.floor(T*12)%2)){emo(c,g.hr.e,p.x,p.y,64*g.hs,clamp(p.vy/900,-.4,.4));if(g.shield>0){c.strokeStyle='rgba(76,242,255,.8)';c.lineWidth=4;ell(c,p.x,p.y,42,42);c.stroke();}}
},
goal(g){return '🌀 '+Math.round(clamp(g.t/g.flyT,0,1)*100)+'%';}
};
MG.platform={
how:'Move left and right. Tap the round button to jump. Jump on top of enemies!',btn:'⬆️',
init(g){const P=g.plats=[];let x=0,y=430;P.push({x:-200,y,w:700});x=500;
const gapMax=[120,150,175][g.lv],end=900+g.stage*450+g.lv*200;
while(x<end){const gap=rnd(70,gapMax);x+=gap;y=clamp(y+rnd(-100,80),230,460);const w=rnd(170,340);P.push({x,y,w});
for(let j=0;j<3;j++)g.o.push({k:'it',x:x+w/2+(j-1)*40,y:y-60-Math.sin(j/2*Math.PI)*30,e:pick(g.itemE)});
if(w>230&&Math.random()<.55*g.dif*g.hm)g.o.push({k:'haz',x:x+w*.7,y:y-26,e:g.hazE,a:x+20,b:x+w-20,v:rnd(50,90)*g.hz*g.dif});
if(g.frOn&&Math.random()<.13)g.o.push({k:'fr',x:x+w*.3,y:y-110,e:pick(g.frE)});
x+=w;}
P.push({x:x+90,y:400,w:400});g.flag={x:x+300,y:400};g.endX=x+300;
Object.assign(g.p,{x:120,y:380,vx:0,vy:0,ground:false,coy:0,buf:0,jumps:0,safe:{x:120,y:380}});g.cx=0;},
update(g,dt,I){
const p=g.p,run=300*g.spd;p.vx=lerp(p.vx,I.ax*run,Math.min(1,dt*10));if(I.ax)p.face=I.ax>0?1:-1;
if(I.actP||(I.ay<-.6&&!g.upHeld))p.buf=.14;g.upHeld=I.ay<-.6;
p.buf-=dt;p.coy-=dt;
if(p.buf>0&&(p.coy>0||(g.jmp&&p.jumps<2))){p.vy=g.jmp?-800:-700;p.buf=0;p.coy=0;p.jumps++;SFX.jump();}
if(!I.act&&p.vy<-200)p.vy+=1400*dt;
p.vy+=1650*dt;p.vy=Math.min(p.vy,900);
const oy=p.y;p.x+=p.vx*dt;p.y+=p.vy*dt;p.ground=false;
for(const q of g.plats){if(p.x>q.x-14&&p.x<q.x+q.w+14&&oy<=q.y-26+1&&p.y>=q.y-26){p.y=q.y-26;p.vy=0;p.ground=true;p.coy=.1;p.jumps=0;p.safe={x:clamp(p.x,q.x+30,q.x+q.w-30),y:q.y-60};}}
if(p.x<20)p.x=20;
if(p.y>g.H+120){hurt(g,p.x,g.H-40);g.inv=1.3;p.x=p.safe.x;p.y=p.safe.y;p.vy=0;}
for(const o of g.o){if(o.gone)continue;
if(o.k==='haz'){o.x+=o.v*dt;if(o.x<o.a||o.x>o.b)o.v*=-1;}
if(g.mag&&o.k!=='haz'&&Math.hypot(o.x-p.x,o.y-p.y)<g.mag){o.x+=(p.x-o.x)*dt*5;o.y+=(p.y-o.y)*dt*5;}
if(Math.hypot(o.x-p.x,o.y-p.y)<36){
if(o.k==='it'){o.gone=1;gotItem(g,o.x,o.y);}
else if(o.k==='fr'){o.gone=1;gotFriend(g,o.x,o.y);}
else if(p.vy>50&&p.y<o.y-8){o.gone=1;p.vy=-520;g.score+=20*g.dbl;pop(g,o.x,o.y,'Bonk! +'+20*g.dbl);SFX.bonk();gfx(g,o.x,o.y,'#fff',12);}
else hurt(g,o.x,o.y);}}
g.cx=lerp(g.cx,clamp(p.x-g.W*.35,0,g.endX+200-g.W),Math.min(1,dt*6));
if(p.x>=g.flag.x-10){g.score+=100*g.dbl;finishMain(g,'You reached the flag! 🏁');}
},
draw(g,c,T){const p=g.p;sideBG(g,c,g.cx,T);c.save();c.translate(-g.cx,0);
for(const q of g.plats){if(q.x+q.w<g.cx-20||q.x>g.cx+g.W+20)continue;c.fillStyle=g.wd.gr;rr(c,q.x,q.y,q.w,g.H-q.y+40,14);c.fill();c.fillStyle=g.wd.gr2;rr(c,q.x,q.y,q.w,16,8);c.fill();
c.fillStyle='rgba(0,0,0,.08)';for(let i=q.x+20;i<q.x+q.w-10;i+=40)ell(c,i,q.y+50,8,8),c.fill();}
emo(c,'🏁',g.flag.x,g.flag.y-60,90);
for(const o of g.o){if(o.gone||o.x<g.cx-40||o.x>g.cx+g.W+40)continue;emo(c,o.e,o.x,o.y,o.k==='haz'?50:38,o.k==='haz'?Math.sin(T*8)*.1:Math.sin(T*4+o.x)*.2);}
if(!(g.inv>0&&Math.floor(T*12)%2)){c.save();c.translate(p.x,p.y);c.scale(-p.face,1);emo(c,g.hr.e,0,-4-(g.hs-1)*24,58*g.hs,p.ground?Math.sin(T*14)*Math.abs(p.vx)/2000:0);c.restore();
if(g.shield>0){c.strokeStyle='rgba(76,242,255,.8)';c.lineWidth=4;ell(c,p.x,p.y-4,38,38);c.stroke();}}
c.restore();
},
goal(g){return '🏁 '+Math.round(clamp(g.p.x/g.flag.x,0,1)*100)+'%';}
};
function sideBG(g,c,scroll,T){
const wd=g.wd;const gr=c.createLinearGradient(0,0,0,g.H);gr.addColorStop(0,wd.sky[0]);gr.addColorStop(1,wd.sky[1]);c.fillStyle=gr;c.fillRect(0,0,g.W,g.H);
if(wd.id==='space'||wd.id==='robot'){for(let i=0;i<40;i++){c.fillStyle='rgba(255,255,255,'+(.4+.4*Math.sin(T*3+i))+')';const x=((i*97-scroll*.1)%g.W+g.W)%g.W;ell(c,x,(i*53)%g.H,1.6,1.6);c.fill();}}
for(let k=0;k<2;k++){const sp=k?.5:.2,col=k?'rgba(255,255,255,.28)':'rgba(255,255,255,.18)';c.fillStyle=col;c.beginPath();c.moveTo(0,g.H);
for(let x=0;x<=g.W+40;x+=40){const wx=x+scroll*sp;c.lineTo(x,g.H-(k?120:200)-Math.sin(wx*.006+k)*50-Math.sin(wx*.017)*20);}c.lineTo(g.W,g.H);c.fill();}
for(let i=0;i<6;i++){const sp=.35;const x=((i*190-scroll*sp)%(g.W+200)+g.W+200)%(g.W+200)-100;emo(c,wd.deco[i%wd.deco.length],x,80+(i*67)%180,40+(i%3)*14,0,.75);}
}
/* top-down games: treasure, explore, dodge, rescue */
function tdInit(g,o){
const arena=g.mode==='dodge';g.MW=arena?g.W:Math.max(g.W*2.1,1500);g.MH=arena?g.H:1300;
Object.assign(g.p,{x:g.MW/2,y:g.MH/2,dash:0,cool:0,trail:[]});
const free=(r)=>{for(let k=0;k<40;k++){const x=rnd(70,g.MW-70),y=rnd(110,g.MH-70);if(Math.hypot(x-g.p.x,y-g.p.y)>r)return {x,y};}return {x:rnd(70,g.MW-70),y:rnd(110,g.MH-70)};};
g.free=free;
const nItems=Math.round((arena?6:24)*g.im);for(let i=0;i<nItems;i++){const q=free(60);g.o.push({k:'it',x:q.x,y:q.y,e:pick(g.itemE)});}
const nh=arena?0:Math.round([4,5,7][g.lv]*g.hm);for(let i=0;i<nh;i++){const q=free(260);const a=rnd(0,6.28);g.o.push({k:'haz',x:q.x,y:q.y,vx:Math.cos(a),vy:Math.sin(a),v:rnd(70,110)*g.dif*g.hz,e:g.hazE});}
if(g.frOn&&g.mode!=='rescue')for(let i=0;i<3;i++){const q=free(200);g.o.push({k:'fr',x:q.x,y:q.y,e:g.frE[i%g.frE.length]});}
g.deco=[];if(!arena)for(let i=0;i<40;i++)g.deco.push({x:rnd(0,g.MW),y:rnd(0,g.MH),e:pick(g.wd.deco),s:rnd(30,56)});
}
function tdMove(g,dt,I){
const p=g.p;let ax=I.ax,ay=I.ay;const m=Math.hypot(ax,ay);if(m>1){ax/=m;ay/=m;}
p.cool-=dt;if(I.actP&&p.cool<=0){p.dash=.28;p.cool=1;SFX.boost();}
p.dash-=dt;const sp=270*g.spd*(p.dash>0?2.3:1);
p.x=clamp(p.x+ax*sp*dt,30,g.MW-30);p.y=clamp(p.y+ay*sp*dt,80,g.MH-30);if(ax)p.face=ax>0?1:-1;
p.trail.unshift({x:p.x,y:p.y});if(p.trail.length>120)p.trail.pop();
g.cam.x=clamp(p.x-g.W/2,0,g.MW-g.W);g.cam.y=clamp(p.y-g.H/2,0,g.MH-g.H);
for(const o of g.o){if(o.gone)continue;
if(o.k==='haz'){o.x+=o.vx*o.v*dt;o.y+=o.vy*o.v*dt;
if(o.bul){if(o.x<-80||o.x>g.MW+80||o.y<-80||o.y>g.MH+80)o.gone=1;}
else{if(o.x<30||o.x>g.MW-30)o.vx*=-1;if(o.y<90||o.y>g.MH-30)o.vy*=-1;if(Math.random()<dt*.4){const a=rnd(0,6.28);o.vx=Math.cos(a);o.vy=Math.sin(a);}}}
if(g.mag&&(o.k==='it')&&Math.hypot(o.x-p.x,o.y-p.y)<g.mag){o.x+=(p.x-o.x)*dt*5;o.y+=(p.y-o.y)*dt*5;}
if(Math.hypot(o.x-p.x,o.y-p.y)<(o.k==='haz'?34:38)){
if(o.k==='it'){o.gone=1;gotItem(g,o.x,o.y);}
else if(o.k==='fr'){o.gone=1;gotFriend(g,o.x,o.y);}
else if(o.k==='haz'){if(hurt(g,o.x,o.y)){const a=Math.atan2(p.y-o.y,p.x-o.x);p.x=clamp(p.x+Math.cos(a)*60,30,g.MW-30);p.y=clamp(p.y+Math.sin(a)*60,80,g.MH-30);}}}}
}
function tdDraw(g,c,T,extra){
const wd=g.wd,p=g.p;c.save();c.translate(-g.cam.x,-g.cam.y);
c.fillStyle=wd.gr;c.fillRect(0,0,g.MW,g.MH);
c.fillStyle=wd.gr2;c.globalAlpha=.35;const x0=Math.floor(g.cam.x/80)*80,y0=Math.floor(g.cam.y/80)*80;
for(let x=x0;x<g.cam.x+g.W+80;x+=80)for(let y=y0;y<g.cam.y+g.H+80;y+=80)if(((x+y)/80)%2===0){ell(c,x+40,y+40,22,14);c.fill();}
c.globalAlpha=1;
c.strokeStyle='rgba(0,0,0,.2)';c.lineWidth=10;c.strokeRect(5,5,g.MW-10,g.MH-10);
for(const d of g.deco)if(d.x>g.cam.x-60&&d.x<g.cam.x+g.W+60&&d.y>g.cam.y-60&&d.y<g.cam.y+g.H+60)emo(c,d.e,d.x,d.y,d.s,0,.8);
if(extra)extra(c);
for(const o of g.o){if(o.gone)continue;if(o.x<g.cam.x-60||o.x>g.cam.x+g.W+60||o.y<g.cam.y-60||o.y>g.cam.y+g.H+60)continue;
if(o.k==='fr'){c.fillStyle='rgba(180,240,255,.5)';c.strokeStyle='#fff';c.lineWidth=3;ell(c,o.x,o.y,30,30);c.fill();c.stroke();}
emo(c,o.e,o.x,o.y,o.k==='haz'?52:o.k==='fr'?40:36,o.k==='haz'?Math.sin(T*6+o.x)*.15:Math.sin(T*4+o.y)*.2);}
if(g.followers)g.followers.forEach((f,i)=>{const tp=p.trail[Math.min(p.trail.length-1,(i+1)*12)]||p;emo(c,f,tp.x,tp.y,40,Math.sin(T*8+i)*.15);});
if(p.dash>0)for(let i=1;i<5;i++){const tp=p.trail[i*3];if(tp)emo(c,g.hr.e,tp.x,tp.y,56,0,.3-i*.05);}
if(!(g.inv>0&&Math.floor(T*12)%2)){c.save();c.translate(p.x,p.y);c.scale(-(p.face||1),1);emo(c,g.hr.e,0,Math.sin(T*10)*2,60*g.hs);c.restore();
if(g.shield>0){c.strokeStyle='rgba(76,242,255,.8)';c.lineWidth=4;ell(c,p.x,p.y,40,40);c.stroke();}}
c.restore();
}
function arrowTo(g,c,tx,ty,col){const p=g.p;const sx=p.x-g.cam.x,sy=p.y-g.cam.y;const a=Math.atan2(ty-p.y,tx-p.x);const d=Math.hypot(tx-p.x,ty-p.y);if(d<90)return;
c.save();c.translate(sx+Math.cos(a)*62,sy+Math.sin(a)*62);c.rotate(a);c.fillStyle=col||'#ffd23f';c.strokeStyle='#2a1460';c.lineWidth=3;c.beginPath();c.moveTo(16,0);c.lineTo(-8,-12);c.lineTo(-3,0);c.lineTo(-8,12);c.closePath();c.fill();c.stroke();c.restore();}
function chest(c,x,y,open,T){c.fillStyle='#8b4a1c';rr(c,x-26,y-12,52,32,6);c.fill();c.fillStyle='#ffc21a';c.fillRect(x-26,y-2,52,6);
if(open){c.fillStyle='#a0612a';rr(c,x-26,y-34,52,18,6);c.fill();emo(c,'💎',x,y-20,28);}else{c.fillStyle='#a0612a';rr(c,x-28,y-24,56,16,8);c.fill();c.fillStyle='#ffc21a';ell(c,x,y-6,5,5);c.fill();}}
MG.treasure={
how:'Drag or use the arrows to walk. Find the treasure under every red X!',btn:'💨',
init(g){tdInit(g);g.chests=[];for(let i=0;i<[2,3,3][g.stage-1];i++){const q=g.free(300);g.chests.push({x:q.x,y:q.y,open:false});}},
update(g,dt,I){tdMove(g,dt,I);const p=g.p;
for(const ch of g.chests)if(!ch.open&&Math.hypot(ch.x-p.x,ch.y-p.y)<52){ch.open=true;g.score+=100*g.dbl;pop(g,ch.x,ch.y-40,'Treasure! +'+100*g.dbl,'#ffd23f');gfx(g,ch.x,ch.y,'#ffd23f',24);SFX.star();react(g,'Treasure! Woo-hoo!');}
if(g.chests.every(c=>c.open))finishMain(g,'You found all the treasure! 💰');},
draw(g,c,T){tdDraw(g,c,T,cc=>{for(const ch of g.chests){if(ch.open)chest(cc,ch.x,ch.y,true,T);else{cc.strokeStyle='#ff2d55';cc.lineWidth=9;cc.lineCap='round';cc.beginPath();cc.moveTo(ch.x-18,ch.y-18);cc.lineTo(ch.x+18,ch.y+18);cc.moveTo(ch.x+18,ch.y-18);cc.lineTo(ch.x-18,ch.y+18);cc.stroke();if(Math.sin(T*6+ch.x)>.6)emo(cc,'✨',ch.x+16,ch.y-20,22);}}});
const nx=nearest(g,g.chests.filter(c=>!c.open));if(nx)arrowTo(g,c,nx.x,nx.y);},
goal(g){return '💰 '+g.chests.filter(c=>c.open).length+'/'+g.chests.length;}
};
function nearest(g,list){let b=null,bd=1e9;for(const o of list){const d=Math.hypot(o.x-g.p.x,o.y-g.p.y);if(d<bd){bd=d;b=o;}}return b;}
MG.explore={
how:'Walk around to clear the fog. Find all the hidden places!',btn:'💨',
init(g){tdInit(g);g.fogS=64;g.fc=Math.ceil(g.MW/g.fogS);g.fr=Math.ceil(g.MH/g.fogS);g.fog=new Uint8Array(g.fc*g.fr);
g.marks=shuffle(g.wd.marks.slice()).slice(0,g.stage+1).map(e=>{const q=g.free(280);return {x:q.x,y:q.y,e,found:false};});},
update(g,dt,I){tdMove(g,dt,I);const p=g.p,R=170,s=g.fogS;
for(let i=Math.max(0,Math.floor((p.x-R)/s));i<=Math.min(g.fc-1,Math.floor((p.x+R)/s));i++)for(let j=Math.max(0,Math.floor((p.y-R)/s));j<=Math.min(g.fr-1,Math.floor((p.y+R)/s));j++)
if(Math.hypot(i*s+s/2-p.x,j*s+s/2-p.y)<R)g.fog[j*g.fc+i]=1;
for(const m of g.marks)if(!m.found&&Math.hypot(m.x-p.x,m.y-p.y)<80){m.found=true;g.score+=80*g.dbl;pop(g,m.x,m.y-60,'You found it! +'+80*g.dbl,'#4cf2a0');gfx(g,m.x,m.y,'#4cf2a0',24);SFX.star();react(g,'Look what we found!');}
if(g.marks.every(m=>m.found))finishMain(g,'You explored everything! 🔭');},
draw(g,c,T){tdDraw(g,c,T,cc=>{for(const m of g.marks){emo(cc,m.e,m.x,m.y,m.found?96:80,0,m.found?1:.9);if(m.found){cc.strokeStyle='#4cf2a0';cc.lineWidth=5;ell(cc,m.x,m.y,58,58);cc.stroke();}}});
c.save();c.translate(-g.cam.x,-g.cam.y);const s=g.fogS;c.fillStyle=g.wd.id==='space'?'rgba(10,4,40,.93)':'rgba(40,20,90,.88)';
for(let i=Math.floor(g.cam.x/s);i<=Math.min(g.fc-1,Math.floor((g.cam.x+g.W)/s));i++)for(let j=Math.floor(g.cam.y/s);j<=Math.min(g.fr-1,Math.floor((g.cam.y+g.H)/s));j++)if(!g.fog[j*g.fc+i])c.fillRect(i*s-1,j*s-1,s+2,s+2);
c.restore();
const nx=nearest(g,g.marks.filter(m=>!m.found));if(nx&&Math.sin(T*3)>0)arrowTo(g,c,nx.x,nx.y,'#4cf2a0');},
goal(g){return '🔭 '+g.marks.filter(m=>m.found).length+'/'+g.marks.length;}
};
MG.dodge={
how:'Move to dodge everything that flies at you. Grab the stars! The round button dashes.',btn:'💨',
init(g){tdInit(g);g.spawn=1;g.ispawn=1;g.dur=[30,32,32][g.lv];},
update(g,dt,I){tdMove(g,dt,I);const p=g.p;
g.spawn-=dt;if(g.spawn<=0){g.spawn=Math.max(.3,(1.25-g.t*.02)/(g.dif*g.hm));const side=ri(0,3);let x,y;
if(side===0){x=-30;y=rnd(90,g.H);}else if(side===1){x=g.W+30;y=rnd(90,g.H);}else if(side===2){x=rnd(0,g.W);y=60;}else{x=rnd(0,g.W);y=g.H+30;}
const a=Math.atan2(p.y-y+rnd(-80,80),p.x-x+rnd(-80,80));g.o.push({k:'haz',bul:1,x,y,vx:Math.cos(a),vy:Math.sin(a),v:rnd(150,240)*g.dif*g.hz,e:g.hazE});}
g.ispawn-=dt;if(g.ispawn<=0){g.ispawn=1.1/g.im;const q=g.free(80);g.o.push({k:'it',x:q.x,y:q.y,e:pick(g.itemE)});}
g.o=g.o.filter(o=>!o.gone);
if(g.t>=g.dur-.05){g.score+=100*g.dbl;finishMain(g,'You dodged it all! 💨');}},
draw(g,c,T){tdDraw(g,c,T);},
goal(g){return '⏱️ '+Math.max(0,Math.ceil(g.dur-g.t))+'s';}
};
MG.rescue={
how:'Find the friends in bubbles and bring them home to the house!',btn:'💨',
init(g){tdInit(g);g.home={x:g.MW/2,y:g.MH/2};g.p.y+=120;g.followers=[];g.saved=0;g.need=[1,2,2][g.stage-1]+(g.lv>1?1:0);
g.home.e=g.wd.id==='castle'?'🏰':g.wd.id==='ocean'?'🐚':g.wd.id==='space'?'🛸':'🏠';
g.friendsO=[];for(let i=0;i<g.need;i++){const q=g.free(320);g.friendsO.push({x:q.x,y:q.y,e:g.frE[i%g.frE.length],got:false});}},
update(g,dt,I){tdMove(g,dt,I);const p=g.p;
for(const f of g.friendsO)if(!f.got&&Math.hypot(f.x-p.x,f.y-p.y)<46){f.got=true;g.followers.push(f.e);pop(g,f.x,f.y-40,'Follow me!','#4cf2ff');SFX.friend();gfx(g,f.x,f.y,'#bff',16);react(g,'Bring them home!');}
if(g.followers.length&&Math.hypot(g.home.x-p.x,g.home.y-p.y)<90){const n=g.followers.length;g.saved+=n;g.friends+=n;g.score+=100*n*g.dbl;pop(g,g.home.x,g.home.y-70,n+' safe at home! +'+100*n*g.dbl,'#4cf2a0');gfx(g,g.home.x,g.home.y,'#4cf2a0',30);SFX.star();g.followers=[];react(g,'Hooray! They\'re safe!');}
if(g.saved>=g.need)finishMain(g,'Everyone is safe! 🛟');},
draw(g,c,T){tdDraw(g,c,T,cc=>{cc.fillStyle='rgba(255,255,255,.35)';ell(cc,g.home.x,g.home.y+20,90,40);cc.fill();emo(cc,g.home.e,g.home.x,g.home.y,110);
for(const f of g.friendsO)if(!f.got){cc.fillStyle='rgba(180,240,255,.55)';cc.strokeStyle='#fff';cc.lineWidth=3;ell(cc,f.x,f.y+Math.sin(T*3+f.x)*6,32,32);cc.fill();cc.stroke();emo(cc,f.e,f.x,f.y+Math.sin(T*3+f.x)*6,40);}});
if(g.followers.length)arrowTo(g,c,g.home.x,g.home.y,'#4cf2a0');else{const nx=nearest(g,g.friendsO.filter(f=>!f.got));if(nx)arrowTo(g,c,nx.x,nx.y,'#4cf2ff');}},
goal(g){return '🏠 '+g.saved+'/'+g.need+(g.followers.length?' (+'+g.followers.length+')':'');}
};
MG.collect={
how:'Move left and right to catch the treats. Do not catch the obstacles!',btn:'💨',
init(g){g.p.x=g.W/2;g.p.y=g.H-70;g.sp=0;g.hsp=1.2;g.cool=0;g.dash=0;},
update(g,dt,I){const p=g.p;g.cool-=dt;if(I.actP&&g.cool<=0){g.dash=.25;g.cool=1;SFX.boost();}g.dash-=dt;
p.x=clamp(p.x+I.ax*470*g.spd*(g.dash>0?2:1)*dt,40,g.W-40);if(I.ax)p.face=I.ax>0?1:-1;
g.sp-=dt;if(g.sp<=0){g.sp=rnd(.35,.6)/(g.dif*g.im);const fr=g.frOn&&Math.random()<.07;g.o.push({k:fr?'fr':'it',x:rnd(40,g.W-40),y:40,v:rnd(150,230)*g.dif,e:fr?pick(g.frE):pick(g.itemE),r:rnd(-1,1)});}
g.hsp-=dt;if(g.hsp<=0){g.hsp=rnd(1.1,1.7)/(g.dif*g.hm);g.o.push({k:'haz',x:rnd(40,g.W-40),y:40,v:rnd(170,240)*g.dif*g.hz,e:g.hazE,r:0});}
const cr=g.mag?80:52;
for(const o of g.o){if(o.gone)continue;o.y+=o.v*dt;
if(g.mag&&o.k!=='haz'&&o.y>g.H-260)o.x+=(p.x-o.x)*dt*3;
if(o.y>p.y-30&&o.y<p.y+20&&Math.abs(o.x-p.x)<(o.k==='haz'?42:cr)){o.gone=1;if(o.k==='it')gotItem(g,o.x,o.y);else if(o.k==='fr')gotFriend(g,o.x,o.y);else hurt(g,o.x,o.y);}
if(o.y>g.H+40)o.gone=1;}
g.o=g.o.filter(o=>!o.gone);
if(g.t>=g.dur-.05){g.score+=50*g.dbl;finishMain(g,'Time! What a catch! 🧺');}},
draw(g,c,T){const p=g.p;sideBG(g,c,g.t*30,T);c.fillStyle=g.wd.gr;c.fillRect(0,g.H-36,g.W,36);
for(const o of g.o)emo(c,o.e,o.x,o.y,o.k==='haz'?52:42,o.r*g.t);
if(!(g.inv>0&&Math.floor(T*12)%2)){emo(c,'🧺',p.x,p.y+14,64);c.save();c.translate(p.x,p.y-30);c.scale(-(p.face||1),1);emo(c,g.hr.e,0,Math.sin(T*10)*2-(g.hs-1)*24,58*g.hs);c.restore();
if(g.shield>0){c.strokeStyle='rgba(76,242,255,.8)';c.lineWidth=4;ell(c,p.x,p.y-10,50,50);c.stroke();}}},
goal(g){return g.cfg.goal==='collect'?'🧺 '+g.items+'/'+g.goalN:'⏱️ '+Math.max(0,Math.ceil(g.dur-g.t))+'s';}
};
MG.puzzle={
how:'Tap two cards to flip them. Find all the matching pairs!',btn:'',
init(g){const pairs=[3,4,6][g.stage-1]+(g.lv>1?2:g.lv);g.dur=[60,60,65][g.lv]+(g.cfg.power==='slow'?15:0);
let pool=[g.hr.e].concat(g.wd.items,g.wd.marks,g.wd.deco);if(g.frOn)pool=g.frE.slice(0,3).concat(pool);
pool=Array.from(new Set(pool)).slice(0,pairs);while(pool.length<pairs)pool.push(pick(['⭐','🎈','🎁','🍀','🌟','🎵'].filter(x=>pool.indexOf(x)<0)));
g.cards=shuffle(pool.concat(pool).map(e=>({e,up:false,done:false,flip:0})));
g.cols=pairs===6?4:pairs===8?4:5;if(g.W<520)g.cols=pairs===10?4:3;g.rows=Math.ceil(g.cards.length/g.cols);
g.sel=[];g.wait=0;g.cur=0;g.miss=0;g.peek=(g.cfg.power==='magnet'||g.cfg.power==='jump'||g.cfg.power==='speed')?2.2:1.2;g.mv=0;},
layout(g){const top=70,pad=10,aw=g.W-20,ah=g.H-top-12;const cw=Math.min((aw-pad*(g.cols-1))/g.cols,(ah-pad*(g.rows-1))/g.rows*0.8);const ch=cw*1.25;
const gw=g.cols*cw+(g.cols-1)*pad,gh=g.rows*ch+(g.rows-1)*pad;return {x0:(g.W-gw)/2,y0:top+(ah-gh)/2,cw,ch,pad};},
update(g,dt,I){g.peek-=dt;const Lo=this.layout(g);
g.mv-=dt;if(g.mv<=0&&(Math.abs(I.ax)>.5||Math.abs(I.ay)>.5)){g.mv=.18;let cx=g.cur%g.cols,cy=Math.floor(g.cur/g.cols);if(Math.abs(I.ax)>.5)cx=clamp(cx+Math.sign(I.ax),0,g.cols-1);else cy=clamp(cy+Math.sign(I.ay),0,g.rows-1);g.cur=clamp(cy*g.cols+cx,0,g.cards.length-1);}
let tap=-1;if(I.actP)tap=g.cur;
for(const t of I.taps){g.cards.forEach((cd,i)=>{const x=Lo.x0+(i%g.cols)*(Lo.cw+Lo.pad),y=Lo.y0+Math.floor(i/g.cols)*(Lo.ch+Lo.pad);if(t.x>=x&&t.x<=x+Lo.cw&&t.y>=y&&t.y<=y+Lo.ch){tap=i;g.cur=i;}});}
for(const cd of g.cards)cd.flip=lerp(cd.flip,(cd.up||cd.done||g.peek>0)?1:0,Math.min(1,dt*12));
if(g.wait>0){g.wait-=dt;if(g.wait<=0){g.sel.forEach(i=>g.cards[i].up=false);g.sel=[];}return;}
if(tap>=0&&g.peek<=0){const cd=g.cards[tap];if(!cd.up&&!cd.done&&g.sel.length<2){cd.up=true;g.sel.push(tap);SFX.tap();
if(g.sel.length===2){const a=g.cards[g.sel[0]],b=g.cards[g.sel[1]];
if(a.e===b.e){a.done=b.done=true;a.up=b.up=false;g.sel=[];g.score+=30*g.dbl;g.items++;if(g.frE.slice(0,3).indexOf(a.e)>=0)g.friends++;
const i=g.cards.indexOf(a);const x=Lo.x0+(i%g.cols)*(Lo.cw+Lo.pad)+Lo.cw/2,y=Lo.y0+Math.floor(i/g.cols)*(Lo.ch+Lo.pad)+Lo.ch/2;pop(g,x,y,'Match! +'+30*g.dbl,'#4cf2a0');gfx(g,x,y,'#4cf2a0',16);SFX.collect();if(Math.random()<.4)react(g,pick(['A match!','So smart!','You remembered!']));}
else{g.wait=.75;g.miss++;g.hits=Math.floor(g.miss/3);}}}}
if(g.cards.every(c=>c.done)){g.score+=Math.round(Math.max(0,g.dur-g.t)*3)*g.dbl;finishMain(g,'All pairs found! 🧩');}},
draw(g,c,T){sideBG(g,c,g.t*20,T);const Lo=this.layout(g);
g.cards.forEach((cd,i)=>{const x=Lo.x0+(i%g.cols)*(Lo.cw+Lo.pad),y=Lo.y0+Math.floor(i/g.cols)*(Lo.ch+Lo.pad);const f=cd.flip,sx=Math.abs(Math.cos(f*Math.PI));const show=f>.5;
c.save();c.translate(x+Lo.cw/2,y+Lo.ch/2);c.scale(Math.max(.05,sx),1);
c.fillStyle=cd.done?'#d9ffe9':show?'#fff':'#7b5cff';rr(c,-Lo.cw/2,-Lo.ch/2,Lo.cw,Lo.ch,14);c.fill();
c.strokeStyle=i===g.cur&&!TOUCH?'#ffd23f':'#fff';c.lineWidth=i===g.cur&&!TOUCH?6:4;c.stroke();
if(show)emo(c,cd.e,0,0,Lo.cw*.7);else{txt(c,'K',0,2,Lo.cw*.45,'#ffd23f');}
c.restore();});
if(g.peek>0)txt(c,'Look carefully!',g.W/2,Lo.y0-22,24,'#fff','center','#2a1460');},
goal(g){return '🧩 '+g.cards.filter(c=>c.done).length/2+'/'+g.cards.length/2;}
};
/* ---- levels, power-ups, mixed-in games and the boss ---- */
const STAGE_T={race:13,fly:13,platform:18,treasure:18,explore:18,collect:12,dodge:12,puzzle:26,rescue:20};
function stageInit(g){
g.o=[];g.t=0;g.cam={x:0,y:0};g.followers=null;g.L=[];g.gift=null;g.gotGift=0;g.giftT=3;g.layT=1;
g.dur=STAGE_T[g.mode]+(g.cfg.mix==='clock'?-2:0);MG[g.mode].init(g);g.dur=STAGE_T[g.mode]+(g.cfg.mix==='clock'?-2:0);
}
function stageDone(g,won,msg){
if(g.phase!=='play')return;
if(won){g.won++;g.score+=50*g.dbl;}
g.phase='lvl';g.lvlT=0;SFX.star();
if(g.stage<3){g.lvlMsg='Level '+(g.stage+1)+'!';g.lvlSub=won?(msg||'Great job!'):'Time! Keep going!';}
else{g.toBoss=true;g.lvlMsg='Boss time!';g.lvlSub='Grab the stars to zap the boss!';}
react(g,pick(['Next level!','Woo-hoo!','We are so good!']));
}
function heroScr(g){const p=g.p;if(g.boss)return g.bp;
if(g.mode==='puzzle')return null;if(g.mode==='platform')return {x:p.x-g.cx,y:p.y};
if(g.mode==='collect')return {x:p.x,y:p.y-30};
if(g.mode in {treasure:1,explore:1,rescue:1,dodge:1})return {x:p.x-g.cam.x,y:p.y-g.cam.y};
return {x:p.x,y:p.y};}
function touched(g,o,r,I){const h=heroScr(g);if(h&&Math.hypot(o.x-h.x,o.y-h.y)<r)return true;
for(const t of I.taps)if(Math.hypot(o.x-t.x,o.y-t.y)<r+16)return true;return false;}
const GIFTS=[{k:'star',n:'Star power!',e:'⭐'},{k:'speed',n:'Super speed!',e:'⚡'},{k:'magnet',n:'Magnet!',e:'🧲'},{k:'double',n:'Double points!',e:'✨'}];
function powTick(g,dt){g.starT=(g.starT||0)-dt;if(g.pw){g.pw.t-=dt;if(g.pw.t<=0){Object.assign(g,g.base0);g.pw=null;}}
if(g.boss||g.phase!=='play')return;
g.giftT-=dt;if(g.giftT<=0&&!g.gift&&!g.gotGift){g.gift={x:rnd(80,g.W-80),y:rnd(140,g.H-120),t:9};}
const G2=g.gift;if(!G2)return;G2.t-=dt;G2.y+=Math.sin(g.t*3)*20*dt;if(G2.t<=0){g.gift=null;g.gotGift=1;return;}
if(touched(g,G2,48,INP)){g.gift=null;g.gotGift=1;
const k=g.mode==='puzzle'?{k:'peek',n:'Peek at the cards!',e:'👀'}:pick(GIFTS);Object.assign(g,g.base0);
if(k.k==='star')g.starT=7;if(k.k==='speed')g.spd=g.base0.spd*1.4;if(k.k==='magnet')g.mag=170;if(k.k==='double')g.dbl=g.base0.dbl*2;if(k.k==='peek')g.peek=1.6;
g.pw={k:k.k,e:k.e,t:7};pop(g,G2.x,G2.y,k.n,'#ffd23f');gfx(g,G2.x,G2.y,'#ffd23f',24);SFX.unlock();react(g,k.n);}
}
/* the mixed-in game runs on top of the main game, in screen space */
const MIXGOAL={rescue:3,collect:12,dodge:10,treasure:3};
function layerUpdate(g,dt,I){
const mx=g.cfg.mix;if(!MIXGOAL[mx])return;if(mx==='dodge'&&g.mode==='puzzle')return;
g.layT-=dt;
if(g.layT<=0){
if(mx==='rescue'&&!g.L.length){g.layT=3;g.L.push({k:'fr',x:rnd(70,g.W-70),y:rnd(130,g.H-110),e:pick(g.frE),t:9});}
else if(mx==='collect'){g.layT=rnd(.7,1.1);g.L.push({k:'it',x:rnd(50,g.W-50),y:60,v:rnd(110,160),e:pick(g.itemE)});}
else if(mx==='dodge'){g.layT=rnd(1,1.5)/g.dif;const l=Math.random()<.5;g.L.push({k:'hz',x:l?-30:g.W+30,y:rnd(120,g.H-80),vx:(l?1:-1)*rnd(170,240)*g.hz,e:g.hazE});}
else if(mx==='treasure'&&!g.L.length){g.layT=3;g.L.push({k:'x',x:rnd(70,g.W-70),y:rnd(130,g.H-110),t:10});}
else g.layT=.5;
}
for(const o of g.L){
if(o.t!=null){o.t-=dt;if(o.t<=0)o.gone=1;}
if(o.k==='it'){o.y+=o.v*dt;if(o.y>g.H+30)o.gone=1;}
if(o.k==='hz'){o.x+=o.vx*dt;if(o.x<-60||o.x>g.W+60){o.gone=1;g.mixN++;}}
if(o.gone)continue;
if(o.k==='hz'){const h=heroScr(g);if(h&&Math.hypot(o.x-h.x,o.y-h.y)<34){o.gone=1;hurt(g,o.x,o.y);}continue;}
if(touched(g,o,44,I)){o.gone=1;g.mixN++;
if(o.k==='fr')gotFriend(g,o.x,o.y);else if(o.k==='it')gotItem(g,o.x,o.y);
else{g.score+=100*g.dbl;pop(g,o.x,o.y-30,'Treasure! +'+100*g.dbl,'#ffd23f');gfx(g,o.x,o.y,'#ffd23f',20);SFX.star();}}
}
g.L=g.L.filter(o=>!o.gone);
if(!g.mixOk&&g.mixN>=MIXGOAL[mx]){g.mixOk=true;g.score+=100*g.dbl;pop(g,g.W/2,g.H/2,'Mix done! +'+100*g.dbl,'#4cf2a0');SFX.unlock();react(g,'We did both games!');}
}
function layerDraw(g,c,T){
for(const o of g.L){
if(o.k==='fr'){c.fillStyle='rgba(180,240,255,.55)';c.strokeStyle='#fff';c.lineWidth=3;ell(c,o.x,o.y+Math.sin(T*3)*5,32,32);c.fill();c.stroke();emo(c,o.e,o.x,o.y+Math.sin(T*3)*5,42);}
else if(o.k==='x'){c.strokeStyle='#ff2d55';c.lineWidth=9;c.lineCap='round';c.beginPath();c.moveTo(o.x-18,o.y-18);c.lineTo(o.x+18,o.y+18);c.moveTo(o.x+18,o.y-18);c.lineTo(o.x-18,o.y+18);c.stroke();if(Math.sin(T*6)>.4)emo(c,'✨',o.x+18,o.y-20,22);}
else emo(c,o.e,o.x,o.y,o.k==='hz'?50:40,Math.sin(T*4+o.x)*.2);
}
const G2=g.gift;if(G2){c.fillStyle='rgba(255,210,63,.35)';ell(c,G2.x,G2.y,40+Math.sin(T*6)*5,40+Math.sin(T*6)*5);c.fill();emo(c,'🎁',G2.x,G2.y,56,Math.sin(T*5)*.15);}
}
function hudExtra(g,c,T){
if(g.phase==='intro')return;
const lab=g.boss?'👑 Boss':'Level '+g.stage+'/3';txt(c,lab,g.W-16,g.H-18,18,'#fff','right','#2a1460');
let y=72;if(MIXGOAL[g.cfg.mix]&&!(g.cfg.mix==='dodge'&&g.mode==='puzzle')){const ic={rescue:'🐣',collect:'🧺',dodge:'💨',treasure:'❌'}[g.cfg.mix];
txt(c,'➕ '+ic+' '+Math.min(g.mixN,MIXGOAL[g.cfg.mix])+'/'+MIXGOAL[g.cfg.mix]+(g.mixOk?' ✔':''),22,y+26,18,g.mixOk?'#4cf2a0':'#fff','left','#2a1460');y+=26;}
if(g.pw){emo(c,g.pw.e,36,y+30,28);txt(c,Math.ceil(g.pw.t)+'s',56,y+32,16,'#ffd23f','left','#2a1460');}
if(g.starT>0&&!g.boss){const h=heroScr(g);if(h){c.strokeStyle='hsl('+((T*300)%360)+',100%,60%)';c.lineWidth=5;ell(c,h.x,h.y,46,46);c.stroke();}}
}
function bossStart(g){
const hp=3+g.lv;g.o=[];g.L=[];g.gift=null;g.t=0;g.dur=18;
g.boss={x:g.W/2,y:200,hp,max:hp,shot:1.2,hitT:0,e:g.hazE,zaps:[],shots:[],orb:null,orbT:.8};
g.bp={x:g.W/2,y:g.H-110,face:1};react(g,'A big boss! We can do it!');SFX.boost();
}
function bossUpdate(g,dt,I){
const b=g.boss,p=g.bp;let ax=I.ax,ay=I.ay;const m=Math.hypot(ax,ay);if(m>1){ax/=m;ay/=m;}
p.x=clamp(p.x+ax*320*g.spd*dt,30,g.W-30);p.y=clamp(p.y+ay*320*g.spd*dt,300,g.H-40);if(ax)p.face=ax>0?1:-1;
b.x=g.W/2+Math.sin(g.t*.9)*(g.W/2-110);b.y=200+Math.sin(g.t*1.7)*25;b.hitT-=dt;
b.shot-=dt*g.hz;if(b.shot<=0){b.shot=Math.max(.7,1.5-g.lv*.25)/g.dif;const a=Math.atan2(p.y-b.y,p.x-b.x)+rnd(-.25,.25);b.shots.push({x:b.x,y:b.y+40,vx:Math.cos(a)*200*g.dif,vy:Math.sin(a)*200*g.dif});}
for(const s of b.shots){s.x+=s.vx*dt*g.hz;s.y+=s.vy*dt*g.hz;if(Math.hypot(s.x-p.x,s.y-p.y)<32){s.gone=1;hurt(g,s.x,s.y);}if(s.y>g.H+40||s.x<-40||s.x>g.W+40)s.gone=1;}
b.shots=b.shots.filter(s=>!s.gone);
b.orbT-=dt;if(!b.orb&&b.orbT<=0)b.orb={x:rnd(60,g.W-60),y:rnd(320,g.H-60)};
if(b.orb&&touched(g,b.orb,46,I)){b.zaps.push({x:b.orb.x,y:b.orb.y});b.orb=null;b.orbT=.9;SFX.collect();}
for(const z of b.zaps){const a=Math.atan2(b.y-z.y,b.x-z.x);z.x+=Math.cos(a)*700*dt;z.y+=Math.sin(a)*700*dt;
if(Math.hypot(b.x-z.x,b.y-z.y)<50){z.gone=1;b.hp--;b.hitT=.4;g.shake=.25;g.score+=40*g.dbl;pop(g,b.x,b.y-70,'Zap! +'+40*g.dbl,'#4cf2ff');gfx(g,b.x,b.y,'#4cf2ff',24);SFX.bonk();
if(b.hp<=0){g.score+=200*g.dbl;gfx(g,b.x,b.y,'#ffd23f',40);realFinish(g,'You beat the boss! 🏆');return;}}}
b.zaps=b.zaps.filter(z=>!z.gone);
}
function bossDraw(g,c,T){
const b=g.boss,p=g.bp;sideBG(g,c,g.t*60,T);
c.fillStyle='rgba(42,20,96,.18)';c.fillRect(0,0,g.W,g.H);
if(b.orb){c.fillStyle='rgba(255,210,63,.35)';ell(c,b.orb.x,b.orb.y,34+Math.sin(T*8)*6,34+Math.sin(T*8)*6);c.fill();emo(c,'⭐',b.orb.x,b.orb.y,46,T*2);}
for(const s of b.shots)emo(c,b.e,s.x,s.y,36,T*4);
for(const z of b.zaps)emo(c,'✨',z.x,z.y,34);
const sc=b.hitT>0?1.15:1;emo(c,b.e,b.x,b.y,150*sc,Math.sin(T*3)*.08,b.hitT>0&&Math.floor(T*20)%2?.5:1);emo(c,'👑',b.x,b.y-82,54);
for(let i=0;i<b.max;i++)emo(c,i<b.hp?'❤️':'🤍',b.x-(b.max-1)*14+i*28,b.y+92,24);
if(!(g.inv>0&&Math.floor(T*12)%2)){c.save();c.translate(p.x,p.y);c.scale(-p.face,1);emo(c,g.hr.e,0,Math.sin(T*10)*2,64*g.hs);c.restore();
if(g.shield>0){c.strokeStyle='rgba(76,242,255,.8)';c.lineWidth=4;ell(c,p.x,p.y,42,42);c.stroke();}}
if(g.t<3)txt(c,'Grab the ⭐ to zap the boss!',g.W/2,g.H*.6,22,'#fff','center','#2a1460');
}
function gUpdate(g,dt){
g.reactT-=dt;g.inv-=dt;g.shake=Math.max(0,g.shake-dt);
for(const p of g.pops)p.age+=dt;g.pops=g.pops.filter(p=>p.age<1);
for(const f of g.fx){f.t+=dt;f.x+=f.vx*dt;f.y+=f.vy*dt;}g.fx=g.fx.filter(f=>f.t<f.life);
const I=INP;
if(g.phase==='intro'){g.introT+=dt;const k=Math.floor(g.introT);if(k!==g.lastBeep&&g.introT>.8){g.lastBeep=k;SFX.beep(g.introT>3);}if(g.introT>3.6){g.phase='play';react(g,pick(['Let\'s go!','Here we go!','I\'m ready!']));}I.actP=false;I.taps=[];return;}
if(g.phase==='play'){
g.t+=dt;powTick(g,dt);
if(g.boss)bossUpdate(g,dt,I);else{MG[g.mode].update(g,dt,I);if(g.phase==='play')layerUpdate(g,dt,I);}
if(g.phase==='play'&&g.t>=g.dur){if(g.boss)realFinish(g,'The boss ran away! 💨',g.won>=2);else stageDone(g,false);}
} else if(g.phase==='lvl'){g.lvlT+=dt;if(g.lvlT>1.9){g.phase='play';if(g.toBoss)bossStart(g);else{g.stage++;g.dif*=1.12;stageInit(g);gSetup(g);}}
} else if(g.phase==='end'){g.endT+=dt;if(g.endT>2.2&&!g.closing){g.closing=true;closeGame(g);}}
I.actP=false;I.taps=[];
}
function gResult(g){
let goalMet=false;const gl=g.cfg.goal;
if(gl==='finish')goalMet=g.main;else if(gl==='collect')goalMet=g.mode==='puzzle'?g.main:g.items>=g.goalN;
else if(gl==='friends')goalMet=g.friends>=Math.min(3,g.mode==='rescue'?g.need:3);else if(gl==='score')goalMet=g.score>=g.goalN;
let stars=1+(g.main?1:0)+((goalMet&&(gl!=='finish'||g.hits<=2))?1:0);
if(!g.main&&goalMet)stars=Math.max(stars,2);
const msg=(g.main?g.endMsg:'Nice try! ')+(g.mixOk?' You did the mix too!':'')+' Score: '+g.score+'.';
return {stars:clamp(stars,1,3),score:g.score,msg};
}
function closeGame(g){S.zoom=1;setSt('unzoom');S.res=gResult(g);}
function gDraw(g,c,T){
gSetup(g);const A=g.A;
c.setTransform(DPR,0,0,DPR,0,0);c.fillStyle='#14142a';c.fillRect(0,0,W,H);
const sx=g.shake>0?rnd(-6,6):0;
c.setTransform(DPR*g.sc,0,0,DPR*g.sc,DPR*(g.ox+sx),DPR*g.oy);
c.save();c.beginPath();c.rect(0,0,g.W,g.H);c.clip();
if(g.boss)bossDraw(g,c,T);else{MG[g.mode].draw(g,c,T);layerDraw(g,c,T);}
const md=g.cfg.mods||{};
if(md.night){c.fillStyle='rgba(12,8,60,.4)';c.fillRect(0,0,g.W,g.H);}
if(md.weather)drawWeather(g,c,T,md.weather);
c.save();if(g.cam&&(g.mode in {treasure:1,explore:1,dodge:1,rescue:1}))c.translate(-g.cam.x,-g.cam.y);if(g.mode==='platform')c.translate(-g.cx,0);
for(const f of g.fx){c.globalAlpha=1-f.t/f.life;c.fillStyle=f.c;ell(c,f.x,f.y,f.s,f.s);c.fill();}c.globalAlpha=1;
for(const p of g.pops)txt(c,p.t,p.x,p.y-p.age*50,22,p.col,'center','#2a1460');
c.restore();
if(g.secret){c.save();c.globalCompositeOperation='lighter';c.fillStyle='hsla('+((T*80)%360)+',100%,60%,.08)';c.fillRect(0,0,g.W,g.H);c.restore();}
// HUD inside the TV
const hr=g.W-Math.min(g.W*.45,170/g.sc);
c.fillStyle='rgba(20,6,60,.6)';rr(c,8,8,hr-8,48,16);c.fill();
const nm=g.cfg.name.length>22?g.cfg.name.slice(0,21)+'…':g.cfg.name;
txt(c,'⭐ '+g.score,22,32,22,'#ffd23f','left');
txt(c,g.boss?'👑 '+g.boss.hp+' left':MG[g.mode].goal(g),Math.max(150,(hr+110)/2),32,20,'#fff');
const tl=Math.max(0,g.dur-g.t);c.fillStyle='rgba(20,6,60,.5)';c.fillRect(0,0,g.W,6);c.fillStyle=tl<6?'#ff4f6d':'#4cf2a0';c.fillRect(0,0,g.W*tl/g.dur,6);
if(g.cfg.goal!=='finish'&&g.mode!=='puzzle'){const gtxt=g.cfg.goal==='collect'?'💎 '+g.items+'/'+g.goalN:g.frOn?'🐣 '+g.friends+'/3':'🏆 '+g.score+'/'+g.goalN;txt(c,gtxt,22,72,18,'#fff','left','#2a1460');}
if(g.reactT>0&&g.react){const cu=g.cust;const bx=g.W-14,by=g.H-(TOUCH&&W/H>=1?150:24);c.globalAlpha=Math.min(1,g.reactT*2);
c.font='700 18px '+FONT;const tw=c.measureText(cu.name+': '+g.react).width+24;c.fillStyle='#fff';rr(c,bx-tw,by-30,tw,32,14);c.fill();txt(c,cu.name+': '+g.react,bx-tw/2,by-14,18,'#2a1460');c.globalAlpha=1;}
if(g.phase==='intro'){c.fillStyle='rgba(20,6,60,.72)';c.fillRect(0,0,g.W,g.H);
emo(c,g.hr.e,g.W/2,g.H*.26,90,Math.sin(T*4)*.1);
wrap(c,g.cfg.name,g.W-40,34).slice(0,2).forEach((l,i)=>txt(c,l,g.W/2,g.H*.44+i*38,34,'#ffd23f','center','#2a1460'));
wrap(c,MG[g.mode].how,g.W-60,20).forEach((l,i)=>txt(c,l,g.W/2,g.H*.62+i*26,20,'#fff'));
if(!TOUCH)txt(c,'Keys: arrows or WASD to move, Space for the button',g.W/2,g.H*.62+80,16,'#c9b8f0');
const k=g.introT;if(k>.8)txt(c,k<1.8?'3':k<2.6?'2':k<3.3?'1':'GO!',g.W/2,g.H*.86,54,'#4cf2a0','center','#2a1460');}
if(g.phase==='lvl'){c.fillStyle='rgba(20,6,60,.55)';c.fillRect(0,0,g.W,g.H);txt(c,g.lvlMsg,g.W/2,g.H*.42,40,'#ffd23f','center','#2a1460');txt(c,g.lvlSub,g.W/2,g.H*.42+48,22,'#fff','center','#2a1460');}
hudExtra(g,c,T);
if(g.phase==='end'){c.fillStyle='rgba(20,6,60,'+Math.min(.6,g.endT)+')';c.fillRect(0,0,g.W,g.H);txt(c,g.endMsg,g.W/2,g.H/2,40,'#ffd23f','center','#2a1460');txt(c,'⭐ '+g.score,g.W/2,g.H/2+50,30,'#fff','center','#2a1460');}
c.restore();
// TV frame
c.setTransform(DPR,0,0,DPR,0,0);c.strokeStyle='#14142a';c.lineWidth=10;c.strokeRect(g.ox-5,g.oy-5,g.W*g.sc+10,g.H*g.sc+10);
drawControls(c,g,T);
}
function drawWeather(g,c,T,k){
const n=k==='rain'?70:k==='snow'?55:28;
for(let i=0;i<n;i++){
const sx=(i*137.5)%g.W,sp=k==='rain'?520:k==='snow'?50:k==='bubbles'?-60:70;
let y=((i*89)+T*sp*(0.7+(i%5)*.1))%(g.H+40);if(y<0)y+=g.H+40;y-=20;
const x=(sx+Math.sin(T+i)*(k==='snow'||k==='leaves'?24:6)+g.W)%g.W;
if(k==='rain'){c.strokeStyle='rgba(180,210,255,.65)';c.lineWidth=2;c.beginPath();c.moveTo(x,y);c.lineTo(x-4,y+14);c.stroke();}
else if(k==='snow'){c.fillStyle='rgba(255,255,255,.9)';ell(c,x,y,3+(i%3),3+(i%3));c.fill();}
else if(k==='bubbles'){c.strokeStyle='rgba(255,255,255,.7)';c.lineWidth=2;ell(c,x,y,5+(i%4)*3,5+(i%4)*3);c.stroke();}
else if(k==='hearts')emo(c,'💖',x,y,16+(i%3)*4,Math.sin(T*2+i)*.3,.8);
else if(k==='sparkles'){if(Math.sin(T*3+i*1.7)>.2)emo(c,'✨',(i*211)%g.W,(i*97)%g.H,14+(i%3)*6,0,.85);}
else if(k==='leaves')emo(c,'🍂',x,y,20,Math.sin(T*2+i),.85);
else if(k==='confetti'){c.fillStyle=['#ff4f6d','#ffd23f','#4cf2a0','#3fa8ff'][i%4];c.fillRect(x,y,6,10);}
}
}
/* ---- touch controls ---- */
function ctrlGeom(){const A=gArea();const port=W/H<1;
if(A.ctrl){const y=H-A.ctrl/2;return {jx:Math.min(W*.27,130),jy:y,br:Math.min(60,A.ctrl*.3),bx:W-Math.min(W*.22,110),by:y,r:Math.min(70,A.ctrl*.36)};}
return {jx:110,jy:H-110,br:58,bx:W-100,by:H-100,r:66,port};}
function drawControls(c,g,T){
if(!TOUCH||g.mode==='puzzle'||g.phase!=='play')return;const k=ctrlGeom();
c.globalAlpha=.85;const j=INP.joy;const bx=j?j.bx:k.jx,by=j?j.by:k.jy;
c.fillStyle='rgba(255,255,255,.18)';c.strokeStyle='rgba(255,255,255,.6)';c.lineWidth=3;ell(c,bx,by,k.r,k.r);c.fill();c.stroke();
const kx=bx+INP.ax*k.r*.6,ky=by+INP.ay*k.r*.6;c.fillStyle='#fff';ell(c,kx,ky,k.r*.42,k.r*.42);c.fill();
if(!j){txt(c,'◀ ▶',bx,by+k.r+16,14,'#fff');}
const bt=MG[g.mode].btn;if(bt){c.fillStyle=INP.act?'#ffd23f':'rgba(255,79,163,.85)';ell(c,k.bx,k.by,k.br,k.br);c.fill();c.strokeStyle='#fff';c.stroke();emo(c,bt,k.bx,k.by,k.br*.9);}
c.globalAlpha=1;
}
function toGame(x,y){const g=G;return {x:(x-g.ox)/g.sc,y:(y-g.oy)/g.sc};}
cv.addEventListener('pointerdown',e=>{
if(S.st!=='play'||!G)return;e.preventDefault();
if(G.mode==='puzzle'){INP.taps.push(toGame(e.clientX,e.clientY));return;}
INP.taps.push(toGame(e.clientX,e.clientY));
const k=ctrlGeom();
if(MG[G.mode].btn&&Math.hypot(e.clientX-k.bx,e.clientY-k.by)<k.br*1.5){INP.act=true;INP.actP=true;INP.actId=e.pointerId;return;}
if(!INP.joy){const A=gArea();const inCtrl=A.ctrl&&e.clientY>H-A.ctrl;
if(e.clientX<W*.62||inCtrl){INP.joy={id:e.pointerId,bx:inCtrl?k.jx:e.clientX,by:inCtrl?k.jy:e.clientY,r:k.r};joyMove(e);}
else{INP.act=true;INP.actP=true;INP.actId=e.pointerId;}}
});
function joyMove(e){const j=INP.joy;if(!j||e.pointerId!==j.id)return;let dx=(e.clientX-j.bx)/(j.r*.6),dy=(e.clientY-j.by)/(j.r*.6);const m=Math.hypot(dx,dy);if(m>1){dx/=m;dy/=m;}
INP.ax=Math.abs(dx)<.15?0:dx;INP.ay=Math.abs(dy)<.15?0:dy;}
cv.addEventListener('pointermove',e=>{if(INP.joy)joyMove(e);});
const endPtr=e=>{if(INP.joy&&e.pointerId===INP.joy.id){INP.joy=null;INP.ax=0;INP.ay=0;}if(e.pointerId===INP.actId){INP.act=false;INP.actId=null;}};
cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',endPtr);
window.addEventListener('keydown',e=>{
const k=e.key.toLowerCase();INP.keys[k]=true;
if([' ','enter','z','x'].indexOf(k)>=0&&S.st==='play'){if(!INP.kAct)INP.actP=true;INP.kAct=true;e.preventDefault();}
if(k.startsWith('arrow')&&S.st==='play')e.preventDefault();
if(S.st==='talk'&&['1','2','3'].indexOf(k)>=0){const o=ui.querySelectorAll('.opt');if(o[+k-1])o[+k-1].click();}
});
window.addEventListener('keyup',e=>{const k=e.key.toLowerCase();INP.keys[k]=false;if([' ','enter','z','x'].indexOf(k)>=0)INP.kAct=false;});
window.addEventListener('blur',()=>{INP.keys={};INP.kAct=false;});
function readInput(){
const K=INP.keys;let kx=(K['arrowright']||K['d']?1:0)-(K['arrowleft']||K['a']?1:0),ky=(K['arrowdown']||K['s']?1:0)-(K['arrowup']||K['w']?1:0);
let px=0,py=0,pa=false;
try{const pads=navigator.getGamepads?navigator.getGamepads():[];for(const p of pads){if(!p)continue;const ax=p.axes[0]||0,ay=p.axes[1]||0;px=Math.abs(ax)>.25?ax:0;py=Math.abs(ay)>.25?ay:0;
if(p.buttons[14]&&p.buttons[14].pressed)px=-1;if(p.buttons[15]&&p.buttons[15].pressed)px=1;if(p.buttons[12]&&p.buttons[12].pressed)py=-1;if(p.buttons[13]&&p.buttons[13].pressed)py=1;
pa=!!(p.buttons[0]&&p.buttons[0].pressed);break;}}catch(e){}
if(pa&&!INP.padAct)INP.actP=true;INP.padAct=pa;
if(!INP.joy){INP.ax=kx||px;INP.ay=ky||py;}
if(!INP.actId)INP.act=!!INP.kAct||pa;
}
/* ================= main loop ================= */
let last=performance.now(),T=0;
function frame(now){
requestAnimationFrame(frame);
let dt=Math.min(.05,(now-last)/1000);last=now;if(S.paused)dt=0;T+=dt;
musicTick();
if(S.st==='title'){drawStorefront(ctx,T);return;}
if(S.st!=='end'&&S.st!=='title'&&!S.creative&&dt>0){S.timeLeft-=dt;if(Math.floor(S.timeLeft+dt)!==Math.floor(S.timeLeft))updHud();}
if(S.st==='play'&&G){readInput();gUpdate(G,dt);if(S.st==='play'){gDraw(G,ctx,T);}return;}
S.t+=dt;
// people
for(const p of S.people){
if(p.bubble){p.bubble.age+=dt;p.bubble.t-=dt;if(p.bubble.t<=0)p.bubble=null;}
p.talk=Math.max(0,p.talk-dt);if(p.happy>0&&S.st!=='end')p.happy-=dt;if(p.wave>0&&!p.moving)p.wave=Math.max(0,p.wave-dt*.3);
const dx=p.tx-p.x;
if(Math.abs(dx)>3&&!p.sit){p.moving=true;p.facing=dx>0?1:-1;const sp=p.speed*(INP.fast?2.2:1);p.x+=Math.sign(dx)*Math.min(Math.abs(dx),sp*dt);p.walk+=dt*sp/22;}
else if(p.moving){p.moving=false;p.x=p.tx;const cb=p.arrive;p.arrive=null;if(cb)cb();}
}
const nearDoor=S.people.some(p=>Math.abs(p.x-175)<190&&!p.owner);SHOP.door=clamp(SHOP.door+(nearDoor?dt*3:-dt*2),0,1);
if(nearDoor&&SHOP.door<.05&&dt>0)SFX.door();
SHOP.tv2=T;
// states
if(S.st==='open'){SHOP.lights=Math.min(1,S.t/1.4);if(S.t>1.5){toast('Kidopia is open! 🎉');say(OWNER,'Welcome to Kidopia!',2.5);const c=spawnCustomer(false);callNext(c);}}
else SHOP.lights=1;
if(S.st==='transfer'){
if(S.t>1.6)tvOn();
}
if(S.st==='tvon'){SHOP.tvOn=Math.min(1,SHOP.tvOn+dt*1.6);}
let focus=680;
if(S.st==='enter'&&S.cur)focus=Math.max(450,S.cur.x+80);
if(S.st==='transfer')focus=lerp(680,1300,Math.min(1,S.t/1.2));
if(S.st==='tvon'||S.st==='zoom'||S.st==='unzoom')focus=1300;
if(S.st==='result')focus=1200;
if(S.st==='leaving'||S.st==='end')focus=S.cur?Math.max(450,Math.min(S.cur.x,900)):700;
camSetup(focus,dt);
ctx.setTransform(DPR,0,0,DPR,0,0);ctx.fillStyle='#ffcf8a';ctx.fillRect(0,0,W,H);
drawShop(ctx,T,S.people);
for(const p of S.people)drawBubble(ctx,p,T);
PW=stepParts(PW,dt);drawParts(ctx,PW);
ctx.setTransform(DPR,0,0,DPR,0,0);
// stream of magic from the phone to the TV
if(S.st==='transfer'||S.st==='tvon'){
const [tx,ty]=w2s(TV.x+TV.w/2,TV.y+TV.h/2);
for(const s of S.stream){const k=clamp((S.t-s.d)/s.dur,0,1);if(k<=0||k>=1)continue;
const mx=(s.sx+tx)/2+s.wob,my=Math.min(s.sy,ty)-120;
const x=(1-k)*(1-k)*s.sx+2*(1-k)*k*mx+k*k*tx,y=(1-k)*(1-k)*s.sy+2*(1-k)*k*my+k*k*ty;
if(s.e)emo(ctx,s.e,x,y,28);else{ctx.fillStyle=s.c;ctx.globalAlpha=.9;ell(ctx,x,y,s.s,s.s);ctx.fill();ctx.globalAlpha=.3;ell(ctx,x,y,s.s*2.2,s.s*2.2);ctx.fill();ctx.globalAlpha=1;}}
}
if(S.st==='zoom'||S.st==='unzoom'){
if(S.st==='zoom'){S.zoom=Math.min(1,S.zoom+dt*1.6);}else{S.zoom=Math.max(0,S.zoom-dt*2);}
const [ax,ay]=w2s(TV.x,TV.y);const aw=TV.w*CAM.sc,ah=TV.h*CAM.sc;const k=S.zoom*S.zoom*(3-2*S.zoom);
const x=lerp(ax,0,k),y=lerp(ay,0,k),w=lerp(aw,W,k),hh=lerp(ah,H,k);
const wd=S.game.world;const gr=ctx.createLinearGradient(0,y,0,y+hh);gr.addColorStop(0,wd.sky[0]);gr.addColorStop(1,wd.sky[1]);
ctx.fillStyle='#14142a';ctx.fillRect(x-8,y-8,w+16,hh+16);ctx.fillStyle=gr;ctx.fillRect(x,y,w,hh);emo(ctx,S.game.hero.e,x+w/2,y+hh/2,Math.min(w,hh)*.4);
if(S.st==='zoom'&&S.zoom>=1){G=newGame(S.cfg,S.cur);gSetup(G);stageInit(G);gSetup(G);setSt('play');setMusic(S.cfg.music);hud.classList.add('hide');gamebar.classList.remove('hide');INP.ax=INP.ay=0;INP.joy=null;}
if(S.st==='unzoom'&&S.zoom<=0){gamebar.classList.add('hide');G=null;gameDone(S.res);}
}
if(S.st==='unzoom'&&G){/* draw last game frame shrinking */}
}
document.addEventListener('pointerdown',e=>{if(S.st==='enter'||S.st==='leaving'||S.st==='transfer'){if(e.target===cv){INP.fast=true;}}});
document.addEventListener('pointerup',()=>{INP.fast=false;});
document.addEventListener('visibilitychange',()=>{if(document.hidden&&S.st!=='title'&&S.st!=='end'&&!S.paused)openMenu();});
// test hooks for automated checks
window.__k={S,get G(){return G;},MG,planFrom,HEROES,WORLDS,MODES,IDEAS,SAVE:()=>SAVE,AC:()=>AC,iosUnlock,
setTime(t){S.timeLeft=t;},endGame(){if(G){G.phase='end';G.endT=0;G.endMsg='Test end';}},
skip(){if(G)stageDone(G,true,'Test');},
winGame(){if(G){G.main=true;G.items=99;G.friends=9;G.score=999;G.phase='end';G.endT=0;G.endMsg='Test win';}}};
showTitle();requestAnimationFrame(frame);
})();
idea.js (the magic engine: reads an idea and turns it into a game plan)260 lines
/* Kidopia idea engine: reads a game idea in plain words and turns it into a game plan, on the device, with no AI service.
How it works:
1. Words and short phrases are looked up in a picture dictionary (creatures, food, things, dangers, places, verbs, looks).
2. Verbs set what the nouns after them mean: "collect carrots" makes carrots the treats, "dodge sharks" makes sharks
the enemies, "save puppies" makes puppies the friends to rescue. "no" or "without" skips the next thing.
3. The first two kinds of play it hears become the game type and the mixed-in extra (for example racing plus collecting).
4. Looks words change the game: night, rain, snow, bubbles, hearts, sparkles, giant or tiny hero, sky colours.
5. If an idea is outside what the engine can make (sports, cooking, fighting), it picks the closest game it can make.
The result also lists which words did what, so the game can show the child how their idea became the game. */
(function(){'use strict';
/* ---- picture dictionary ----
kind: c creature (can be hero, friend or enemy), v vehicle (hero, racing), f food (treat), o thing (treat),
d danger (enemy), plural forms are found by the word stemmer. "fl" marks things that fly. */
const D={};
function add(kind,list){list.split(',').forEach(it=>{const [w,e,extra]=it.split(':');const n=w.trim();D[n]={k:kind,e,w:n,fl:extra==='fl',sea:extra==='sea'};});}
add('c','pig:🐷,cow:🐮,horse:🐴,pony:🐴,unicorn:🦄:fl,dragon:🐉:fl,dino:🦕,dinosaur:🦕,trex:🦖,dog:🐶,puppy:🐶,doggy:🐶,bunny:🐰,rabbit:🐰,bear:🐻,teddy:🧸,panda:🐼,koala:🐨,penguin:🐧,fox:🦊,monkey:🐵,elephant:🐘,giraffe:🦒,owl:🦉:fl,frog:🐸,duck:🦆:fl,chicken:🐔,chick:🐥,turtle:🐢:sea,fish:🐟:sea,dolphin:🐬:sea,whale:🐳:sea,octopus:🐙:sea,mermaid:🧜♀️:sea,fairy:🧚:fl,wizard:🧙,princess:👸,prince:🤴,king:🤴,queen:👸,superhero:🦸:fl,hero:🦸:fl,ninja:🥷,pirate:🦜,parrot:🦜:fl,astronaut:🧑🚀,alien:👽,robot:🤖,butterfly:🦋:fl,ladybug:🐞:fl,snail:🐌,mouse:🐭,hamster:🐹,hedgehog:🦔,sloth:🦥,deer:🦌,sheep:🐑,goat:🐐,zebra:🦓,hippo:🦛,rhino:🦏,kangaroo:🦘,flamingo:🦩:fl,peacock:🦚,swan:🦢:sea,eagle:🦅:fl,bird:🐦:fl,seal:🦭:sea,otter:🦦:sea,squirrel:🐿️,raccoon:🦝,ant:🐜,snowman:⛄,baby:🐣,girl:👧,boy:👦,kid:🧒,mom:👩,dad:👨,grandma:👵,grandpa:👴,friend:🧒,ghost:👻,elf:🧝,giant:🧌');
add('v','car:🚗,racecar:🏎️,kart:🏎️,truck:🚚,train:🚂,bus:🚌,bike:🚲,bicycle:🚲,tractor:🚜,motorcycle:🏍️,scooter:🛴,skateboard:🛹,rocket:🚀:fl,plane:✈️:fl,airplane:✈️:fl,jet:✈️:fl,helicopter:🚁:fl,ufo:🛸:fl,spaceship:🚀:fl,boat:⛵:sea,ship:🚢:sea,submarine:🚤:sea,balloon:🎈:fl');
add('f','pizza:🍕,pepper:🌶️,chilli:🌶️,chili:🌶️,cake:🎂,cookie:🍪,donut:🍩,doughnut:🍩,candy:🍬,sweet:🍬,lollipop:🍭,chocolate:🍫,icecream:🍦,apple:🍎,banana:🍌,strawberry:🍓,watermelon:🍉,carrot:🥕,cheese:🧀,burger:🍔,hamburger:🍔,fries:🍟,taco:🌮,sushi:🍣,popcorn:🍿,pancake:🥞,waffle:🧇,bread:🍞,egg:🥚,cherry:🍒,grape:🍇,orange:🍊,lemon:🍋,pineapple:🍍,peach:🍑,corn:🌽,honey:🍯,milk:🥛,juice:🧃,pretzel:🥨,croissant:🥐,broccoli:🥦,mushroom:🍄,hotdog:🌭,noodle:🍜,pasta:🍝,muffin:🧁,cupcake:🧁,pie:🥧,sandwich:🥪,fruit:🍓,veggie:🥦,vegetable:🥕,food:🍕,snack:🍿,treat:🍬,acorn:🌰,nut:🥜,peanut:🥜,coconut:🥥,avocado:🥑,potato:🥔,tomato:🍅');
add('o','coin:🪙,gold:🪙,money:💰,treasure:💰,gem:💎,diamond:💎,jewel:💎,crystal:💎,star:⭐,heart:❤️,crown:👑,key:🗝️,ball:⚽,football:🏈,basketball:🏀,soccerball:⚽,present:🎁,gift:🎁,flower:🌸,rose:🌹,leaf:🍃,shell:🐚,book:📚,note:🎵,trophy:🏆,medal:🏅,toy:🧸,kite:🪁,potion:🧪,battery:🔋,bone:🦴,sock:🧦,shoe:👟,hat:🎩,ring:💍,sticker:⭐,card:🃏,letter:💌,cloud:☁️,sun:☀️,moonstone:🌙,feather:🪶,block:🧱,brick:🧱,stone:🪨,pearl:🦪,bubble:🫧,snowflake:❄️,balloons:🎈');
add('d','shark:🦈:sea,crab:🦀:sea,bee:🐝:fl,spider:🕷️,snake:🐍,bat:🦇:fl,monster:👾,zombie:👾,villain:👾,meteor:☄️:fl,asteroid:☄️:fl,rock:🪨,boulder:🪨,fire:🔥,lava:🔥,storm:⛈️,lightning:⚡,tornado:🌪️,cactus:🌵,wave:🌊:sea,iceberg:🧊,mosquito:🦟:fl,scorpion:🦂,wolf:🐺,squid:🦑:sea,jellyfish:🦑:sea,slime:🟢,trap:🪤,thunder:🌩️,witch:🧙,goblin:🧌,troll:🧌,crocodile:🐊,alligator:🐊,bull:🐂,wasp:🐝,fly:🪰');
/* phrases (several words) become one word before reading */
const PHR=[['ice cream','icecream'],['hot dog','hotdog'],['race car','racecar'],['t rex','trex'],['t-rex','trex'],['north pole','northpole'],['outer space','space'],['candy land','candy'],['hide and seek','hideseek'],['super jump','superjump'],['run away','runaway'],['pick up','pickup'],['obstacle course','obstacle'],['under the sea','underwater'],['under water','underwater'],['haunted house','spookyhouse'],['spooky house','spookyhouse'],['toy shop','toyshop'],['toy store','toyshop'],['play as','playas'],['i am','iam'],["i'm",'iam'],['soccer ball','soccerball'],['high score','highscore'],['lots of','lots'],['a lot of','lots'],['tons of','lots'],['loads of','lots'],['super fast','fast'],['really fast','fast'],['space ship','spaceship'],['rain bow','rainbow'],['dodge ball','dodgeball'],['bad guys','villain'],['bad guy','villain']];
/* places: base world plus a custom look when the place is new */
const PL={
rainbow:{w:'rainbow'},sky:{w:'sky'},cloud:{w:'sky'},clouds:{w:'sky'},mountain:{w:'sky'},mountains:{w:'sky'},
candy:{w:'candy'},candyland:{w:'candy'},sweets:{w:'candy'},chocolate:{w:'candy'},
sea:{w:'ocean'},ocean:{w:'ocean'},underwater:{w:'ocean'},reef:{w:'ocean'},
lake:{w:'ocean',x:{n:'Sparkle Lake',s:'Lake',e:'🏞️',sky:['#7fd8ff','#2b8be0'],marks:['🦆','🛶','🏞️','🐸','🦢']}},
river:{w:'ocean',x:{n:'Rushing River',s:'River',e:'🏞️',sky:['#8fe0ff','#3a9be8'],marks:['🦦','🛶','🐟','🌉','🦆']}},
space:{w:'space'},planet:{w:'space'},galaxy:{w:'space'},stars:{w:'space'},
moon:{w:'space',x:{n:'The Moon',s:'Moon',e:'🌙',sky:['#0b0630','#2a2a4a'],gr:'#b8b8c8',gr2:'#d8d8e4',deco:['🌍','✨','🌙'],marks:['🚀','🛰️','🌍','🏳️','🌕']}},
mars:{w:'space',x:{n:'Planet Mars',s:'Mars',e:'🔴',sky:['#3a0a14','#a8452a'],gr:'#c0502a',gr2:'#e07040',deco:['✨','🪐'],marks:['🚀','🛸','🪨','🛰️','🌋']}},
icecream:{w:'icecream'},factory:{w:'robot'},lab:{w:'robot'},robotland:{w:'robot'},
kitchen:{w:'icecream',x:{n:'Giant Kitchen',s:'Kitchen',e:'🍳',sky:['#fff3d6','#ffd6a5'],gr:'#e8c49a',gr2:'#fff',deco:['🍳','🥄'],marks:['🍳','🧁','🥞','🫖','🍰']}},
castle:{w:'castle'},palace:{w:'castle'},kingdom:{w:'castle'},
city:{w:'city'},town:{w:'city'},street:{w:'city'},
school:{w:'city',x:{n:'School Day',s:'School',e:'🏫',sky:['#8fd0ff','#e6f6ff'],gr:'#9ad48a',gr2:'#ffd23f',deco:['🏫','✏️'],marks:['🏫','📚','🖍️','🚌','🎒']}},
donut:{w:'donut'},bakery:{w:'donut'},
pirate:{w:'pirate'},island:{w:'pirate'},
beach:{w:'pirate',x:{n:'Sunny Beach',s:'Beach',e:'🏖️',sky:['#5ad1ff','#fff3c8'],gr:'#f7dc8f',gr2:'#4fc3e8',deco:['🏖️','🌴'],marks:['🏖️','🏰','🐚','⛱️','🦀']}},
jungle:{w:'jungle'},rainforest:{w:'jungle'},zoo:{w:'jungle'},safari:{w:'jungle'},park:{w:'jungle'},
forest:{w:'jungle',x:{n:'Whispering Forest',s:'Forest',e:'🌲',sky:['#a8e6b0','#f0ffe0'],gr:'#4a9a4a',gr2:'#2f7a3a',deco:['🌲','🍄'],marks:['🌲','🦌','🍄','🏕️','🦉']}},
woods:{w:'jungle',x:{n:'Whispering Forest',s:'Forest',e:'🌲',sky:['#a8e6b0','#f0ffe0'],gr:'#4a9a4a',gr2:'#2f7a3a',deco:['🌲','🍄'],marks:['🌲','🦌','🍄','🏕️','🦉']}},
farm:{w:'jungle',x:{n:'Happy Farm',s:'Farm',e:'🚜',sky:['#9be0ff','#fff6d0'],gr:'#9ad46a',gr2:'#c9a06a',deco:['🌻','🌾'],marks:['🚜','🏡','🌽','🐄','🐓']}},
desert:{w:'volcano',x:{n:'Sunny Desert',s:'Desert',e:'🏜️',sky:['#ffb36b','#fff0c4'],gr:'#f0c878',gr2:'#e0a850',deco:['🌵','🏜️'],marks:['🐫','🏜️','🌵','🗿','⛺']}},
volcano:{w:'volcano'},cave:{w:'volcano',x:{n:'Crystal Cave',s:'Cave',e:'💎',sky:['#1a1030','#4a3070'],gr:'#5a4a6a',gr2:'#7a6a9a',deco:['💎','🦇'],marks:['💎','🔦','🦇','🪨','🗝️']}},
snow:{w:'snow'},winter:{w:'snow'},arctic:{w:'snow'},northpole:{w:'snow'},iceland:{w:'snow'},
house:{w:'castle',x:{n:'Cozy House',s:'House',e:'🏡',sky:['#ffe4c4','#fff8ee'],gr:'#e0b080',gr2:'#ff9ad5',deco:['🪴','🖼️'],marks:['🛏️','🧸','🛁','📺','🍪']}},
home:{w:'castle',x:{n:'Cozy House',s:'House',e:'🏡',sky:['#ffe4c4','#fff8ee'],gr:'#e0b080',gr2:'#ff9ad5',deco:['🪴','🖼️'],marks:['🛏️','🧸','🛁','📺','🍪']}},
bedroom:{w:'castle',x:{n:'Bedroom Adventure',s:'Bedroom',e:'🛏️',sky:['#c9d6ff','#fff0f8'],gr:'#c8a0e0',gr2:'#ffd6ec',deco:['🧸','🌙'],marks:['🛏️','🧸','🪀','📚','🚂']}},
spookyhouse:{w:'castle',x:{n:'Silly Spooky House',s:'Spooky',e:'🏚️',sky:['#2a1460','#6a3fa0'],gr:'#4a3a6a',gr2:'#7a5aa0',deco:['🕸️','🎃'],marks:['🏚️','🎃','🕯️','🦉','🍬']}},
toyshop:{w:'candy',x:{n:'Toy Shop',s:'Toy',e:'🧸',sky:['#ffd6ec','#e6f6ff'],gr:'#ffcf8a',gr2:'#ff8fd0',deco:['🧸','🪀'],marks:['🧸','🪁','🚂','🎲','🪀']}},
playground:{w:'rainbow',x:{n:'Playground',s:'Playground',e:'🛝',sky:['#8fd8ff','#fff6d0'],gr:'#8be08b',gr2:'#ffd23f',deco:['🌳','⚽'],marks:['🛝','⚽','🪁','🌳','🏀']}},
stadium:{w:'city',x:{n:'Big Stadium',s:'Stadium',e:'🏟️',sky:['#3fa8ff','#d6efff'],gr:'#4cc15a',gr2:'#ffffff',deco:['🏟️','🎉'],marks:['🏟️','🏆','⚽','🥅','📣']}}
};
/* kinds of play */
const MV={race:'race',racing:'race',drive:'race',driving:'race',kart:'race',zoom:'race',speedway:'race',racetrack:'race',
fly:'fly',flying:'fly',soar:'fly',glide:'fly',wing:'fly',jetpack:'fly',swim:'fly',float:'fly',
jump:'platform',hop:'platform',climb:'platform',run:'platform',parkour:'platform',obstacle:'platform',bounce:'platform',platform:'platform',skip:'platform',
treasure:'treasure',dig:'treasure',hunt:'treasure',map:'treasure',
explore:'explore',adventure:'explore',discover:'explore',travel:'explore',journey:'explore',visit:'explore',quest:'explore',hideseek:'explore',wander:'explore',
collect:'collect',catch:'collect',gather:'collect',grab:'collect',pickup:'collect',eat:'collect',munch:'collect',feed:'collect',cook:'collect',bake:'collect',shop:'collect',buy:'collect',
dodge:'dodge',avoid:'dodge',escape:'dodge',runaway:'dodge',survive:'dodge',hide:'dodge',dodgeball:'dodge',chase:'dodge',
puzzle:'puzzle',memory:'puzzle',match:'puzzle',think:'puzzle',brain:'puzzle',remember:'puzzle',solve:'puzzle',
rescue:'rescue',save:'rescue',help:'rescue',protect:'rescue',free:'rescue',lost:'rescue'};
const CTX={collect:'item',catch:'item',gather:'item',grab:'item',pickup:'item',eat:'item',munch:'item',feed:'item',cook:'item',bake:'item',buy:'item',get:'item',find:'item',win:'item',earn:'item',
dodge:'haz',avoid:'haz',escape:'haz',runaway:'haz',from:'haz',against:'haz',fight:'haz',battle:'haz',beat:'haz',chase:'haz',over:'haz',chased:'haz',enemy:'haz',enemies:'haz',villain:'haz',attack:'haz',defeat:'haz',stop:'haz',zap:'haz',dodgeball:'haz',survive:'haz',hide:'haz',
rescue:'friend',save:'friend',help:'friend',protect:'friend',free:'friend',lost:'friend',
playas:'hero',iam:'hero',am:'hero',be:'hero',starring:'hero'};
const POW={fast:'speed',speedy:'speed',quick:'speed',speed:'speed',zoomy:'speed',shield:'shield',safe:'shield',armor:'shield',invincible:'shield',protected:'shield',
magnet:'magnet',magnetic:'magnet',superjump:'jump',jumpy:'jump',bouncy:'jump',spring:'jump',slow:'slow',slowmo:'slow',freeze:'slow',double:'double',rich:'double',highscore:'double',points:'double'};
const MUSW={party:'party',dance:'party',disco:'party',dancing:'party',calm:'calm',sleepy:'calm',quiet:'calm',relax:'calm',peaceful:'calm',cozy:'calm',
epic:'adventure',brave:'adventure',adventure:'adventure',exciting:'adventure',spooky:'adventure',space:'space',cosmic:'space',happy:'happy',silly:'happy',funny:'happy',cute:'happy'};
const LVW={easy:'easy',simple:'easy',little:'easy',medium:'medium',normal:'medium',hard:'hard',difficult:'hard',crazy:'hard',impossible:'hard',tricky:'hard',extreme:'hard'};
const TINT={pink:['#ff9ad5','#ffe0f0'],purple:['#9b5cff','#e6d6ff'],blue:['#3fa8ff','#d6efff'],green:['#4cd18a','#e0ffe8'],yellow:['#ffd23f','#fff6c8'],
orange:['#ff8a3d','#ffe0c4'],red:['#ff4f6d','#ffd6dc'],gold:['#ffc21a','#fff3b0'],golden:['#ffc21a','#fff3b0'],silver:['#b8c4d6','#f0f4fa']};
const WEA={rain:'rain',rainy:'rain',raining:'rain',snowy:'snow',snowing:'snow',snowflake:'snow',heart:'hearts',love:'hearts',valentine:'hearts',bubble:'bubbles',bubbly:'bubbles',
sparkle:'sparkles',sparkly:'sparkles',glitter:'sparkles',magic:'sparkles',magical:'sparkles',shiny:'sparkles',leaf:'leaves',autumn:'leaves',fall:'leaves',confetti:'confetti'};
const NIGHT={night:1,dark:1,midnight:1,nighttime:1,moonlight:1,evening:1};
const BIG={giant:1.35,huge:1.35,big:1.25,enormous:1.4,mega:1.35,gigantic:1.4},SMALL={tiny:.75,little:.85,small:.8,mini:.75,teeny:.7};
const NEG={no:1,not:1,without:1,never:1,dont:1,"don't":1,nothing:1};
const NEAR=[
[/\b(soccer|football|basketball|sport|tennis|golf|baseball|hockey)(s|es|ing|ed|er|ers)?\b/,{mode:'collect',item:'⚽',music:'party'},'A sports game! You catch the balls.'],
[/\b(cook|chef|recipe|restaurant)(s|es|ing|ed|er|ers)?\b/,{mode:'collect',world:'kitchen'},'A cooking game! Catch the food for the kitchen.'],
[/\b(fight|battle|war|shoot|gun|sword|punch|kill)(s|es|ing|ed|er|ers)?\b/,{mode:'dodge',power:'shield'},'This is a friendly dodging game instead of a fight.'],
[/\b(draw|paint|art|colou?r)(s|es|ing|ed|er|ers)?\b/,{mode:'puzzle',world:'rainbow'},'An art game! A colorful matching puzzle.'],
[/\b(music|sing|piano|song|band|guitar|drum)(s|es|ing|ed|er|ers)?\b/,{mode:'collect',item:'🎵',music:'party'},'A music game! Catch the notes.'],
[/\b(scary|horror|creepy)(s|es|ing|ed|er|ers)?\b/,{mode:'dodge',haz:'👻',world:'spookyhouse'},'A silly-spooky game with friendly ghosts.'],
[/\b(build|block|craft)(s|es|ing|ed|er|ers)?\b/,{mode:'platform',item:'🧱'},'A building game! Jump across the blocks.'],
[/\b(shop|store|money|sell)(s|es|ing|ed|er|ers)?\b/,{mode:'collect',item:'🪙'},'Collect all the coins!'],
[/\b(school|learn|math|read)(s|es|ing|ed|er|ers)?\b/,{mode:'puzzle',world:'school'},'A school game! A memory puzzle.'],
[/\b(sleep|bed|dream)(s|es|ing|ed|er|ers)?\b/,{mode:'explore',world:'bedroom',night:1},'A dream game! Explore the dark bedroom.']
];
const NAME_MODE={race:'Race',fly:'Flight',platform:'Jump',treasure:'Treasure Hunt',explore:'Quest',collect:'Catch',dodge:'Dash',puzzle:'Puzzle',rescue:'Rescue'};
const MODE_LABEL={race:'Racing game',fly:'Flying game',platform:'Jumping game',treasure:'Treasure hunt',explore:'Exploring game',collect:'Collecting game',dodge:'Dodging game',puzzle:'Memory puzzle',rescue:'Rescue game'};
const MODE_E={race:'🏎️',fly:'✈️',platform:'🦘',treasure:'🗺️',explore:'🔭',collect:'🧺',dodge:'💨',puzzle:'🧩',rescue:'🛟'};
const MIX_OF={collect:'collect',rescue:'rescue',dodge:'dodge',treasure:'treasure',race:'clock'};
const MIX_LABEL={collect:'+ collecting',rescue:'+ rescuing friends',dodge:'+ extra dodging',treasure:'+ big treasure',clock:'+ beat the clock'};
const WEA_E={rain:'🌧️',snow:'❄️',hearts:'💖',bubbles:'🫧',sparkles:'✨',leaves:'🍂',confetti:'🎉'};
const POW_N={speed:'Super speed',shield:'Shield bubble',magnet:'Magnet',jump:'Super jump',slow:'Slow motion',double:'Double points'};
const POW_E={speed:'⚡',shield:'🛡️',magnet:'🧲',jump:'🚀',slow:'⏳',double:'✨'};
const cap=s=>s.charAt(0).toUpperCase()+s.slice(1);
function stems(w){
const out=[w];const add=s=>{if(s&&s.length>1&&out.indexOf(s)<0)out.push(s);};
if(w.endsWith('ies'))add(w.slice(0,-3)+'y');
if(w.endsWith('es'))add(w.slice(0,-2));
if(w.endsWith('s'))add(w.slice(0,-1));
if(w.endsWith('ves'))add(w.slice(0,-3)+'f');
if(w.endsWith('ing')){const b=w.slice(0,-3);add(b);add(b+'e');if(b.length>2&&b[b.length-1]===b[b.length-2])add(b.slice(0,-1));}
if(w.endsWith('ed')){const b=w.slice(0,-2);add(b);add(w.slice(0,-1));if(b.length>2&&b[b.length-1]===b[b.length-2])add(b.slice(0,-1));}
if(w.endsWith('er'))add(w.slice(0,-2));
if(w==='mice')add('mouse');if(w==='geese')add('duck');if(w==='children'||w==='kids')add('kid');if(w==='people')add('friend');
return out;
}
function find(table,w){for(const s of stems(w))if(Object.prototype.hasOwnProperty.call(table,s))return {key:s,v:table[s]};return null;}
/* Read an idea. ctx: {heroes:[{id,e,n}], worlds:[{id,...}], okWorld(id)} */
function read(text,ctx){
const raw=String(text||'').slice(0,160);
let t=' '+raw.toLowerCase().replace(/[’']/g,"'").replace(/[,.;:!?]+/g,' | ').replace(/\bmixed with\b|\bthen\b|\bbut\b|\bplus\b/g,' | ').replace(/[^a-z0-9'| -]/g,' ')+' ';
for(const [a,b] of PHR)t=t.split(' '+a+' ').join(' '+b+' ');
const words=t.split(/\s+/).filter(Boolean);
const P={text:raw,heroE:null,heroN:null,heroWord:null,heroFl:false,heroSea:false,vehicle:false,place:null,placeWord:null,modes:[],items:[],haz:null,hazN:null,friends:[],
power:null,music:null,level:null,night:false,weather:null,size:1,tint:null,im:1,hm:1,notes:[],marks:[],swaps:[]};
let ctxRole=null,neg=0,lots=false;
const note=(w,e,what,role)=>{if(!P.notes.some(n=>(n.w===w||n.e===e)&&n.what===what))P.notes.push({w,e,what,role});P.marks.push({w,role});};
for(let i=0;i<words.length;i++){
const w=words[i];
if(w==='|'){ctxRole=null;neg=0;lots=false;continue;}
if(NEG[w]){neg=2;continue;}
if(neg>0)neg--;
if(/^(in|on|at|into|inside|across|through|around)$/.test(w)&&ctxRole!=='hero'){ctxRole=null;continue;}
if(w==='lots'||w==='many'||w==='hundreds'||w==='millions'||w==='loads'){lots=true;continue;}
if(w==='and'||w==='the'||w==='a'||w==='an'||w==='of'||w==='to'||w==='in'||w==='on'||w==='at'||w==='with'||w==='game'||w==='games')continue;
// context verbs and kinds of play
const cv=find(CTX,w);if(cv&&!neg)ctxRole=cv.v;
const mv=find(MV,w);
if(mv&&!neg){if(P.modes.indexOf(mv.v)<0){P.modes.push(mv.v);note(w,MODE_E[mv.v],P.modes.length===1?MODE_LABEL[mv.v]:'Mixed in: '+MODE_LABEL[mv.v].toLowerCase(),'mode');}
if(!(w==='fly'&&words[i-1]&&/^(a|the|some|lots)$/.test(words[i-1])))continue;}
// looks
if(NIGHT[w]&&!neg){P.night=true;note(w,'🌙','Night time','look');continue;}
const we=find(WEA,w);if(we&&!neg&&!D[w]){P.weather=we.v;note(w,WEA_E[we.v],'Weather: '+we.v,'look');continue;}
if(BIG[w]&&!neg){P.size=BIG[w];note(w,'⬆️','Giant hero','look');continue;}
if(SMALL[w]&&!neg){P.size=SMALL[w];note(w,'⬇️','Tiny hero','look');continue;}
if(TINT[w]&&!neg){P.tint=TINT[w];note(w,'🎨',cap(w)+' sky','look');continue;}
const pw=find(POW,w);if(pw&&!neg&&!P.power){P.power=pw.v;note(w,POW_E[pw.v],'Power: '+POW_N[pw.v],'power');continue;}
const lv=find(LVW,w);if(lv&&!neg&&!(w==='little'&&words[i+1]&&D[words[i+1]])){P.level=lv.v;note(w,'🎚️','Level: '+cap(lv.v),'look');continue;}
const mu=find(MUSW,w);if(mu&&!neg&&!PL[w]&&!P.music){P.music=mu.v;note(w,'🎵','Music: '+cap(mu.v),'look');}
// places (a thing after "collect", "dodge" or "save" is a thing, not a place)
const thingFirst=(ctxRole==='item'||ctxRole==='haz'||ctxRole==='friend')&&find(D,w);
const pl=thingFirst?null:find(PL,w);
if(pl&&P.place&&/^(in|on|at|the|into|across|through|around)$/.test(words[i-1]||'')){continue;}
if(pl&&!neg&&!P.place){P.place=pl.key;P.placeWord=w;const base=pl.v.x||(ctx&&ctx.worldOf(pl.v.w));note(w,base?base.e:'🌍','World: '+(base?base.n:cap(w)),'place');if(!D[pl.key]||pl.key==='candy'||pl.key==='chocolate')continue;}
// things
const th=find(D,w);if(!th)continue;
const it=th.v;
if(neg){P.swaps.push('No '+it.w+'s, got it!');continue;}
let role;
if(ctxRole==='haz')role='haz';
else if(ctxRole==='friend')role=(it.k==='c'||it.k==='v')?'friend':(it.k==='d'?'haz':'item');
else if(ctxRole==='item')role=(it.k==='d')?'haz':'item';
else if(ctxRole==='hero')role='hero';
else role=it.k==='d'?'haz':(it.k==='f'||it.k==='o')?'item':(P.heroE?'friend':'hero');
if(role==='hero'&&P.heroE)role=it.k==='d'?'haz':'friend';
if(role==='hero'&&it.k==='d'){role='haz';}
if(role==='hero'){P.heroE=it.e;P.heroN=cap(it.w==='trex'?'T-Rex':it.w);P.heroWord=it.w;P.heroFl=it.fl;P.heroSea=it.sea;P.vehicle=it.k==='v';note(w,it.e,'Hero','hero');if(ctxRole==='hero')ctxRole=null;}
else if(role==='item'){if(P.items.indexOf(it.e)<0&&P.items.length<3)P.items.push(it.e);if(lots)P.im=1.6;note(w,it.e,'Treats to collect','item');}
else if(role==='haz'){if(!P.haz){P.haz=it.e;P.hazN=cap(it.w);}if(lots)P.hm=1.5;note(w,it.e,'Enemies to dodge','haz');}
else if(role==='friend'){if(P.friends.indexOf(it.e)<0&&P.friends.length<3)P.friends.push(it.e);note(w,it.e,'Friends to rescue','friend');}
lots=false;
}
// ideas the engine cannot make become the closest game it can make
const low=raw.toLowerCase();let near=null;
for(const [re,set,msg] of NEAR)if(re.test(low)){near={set,msg};break;}
if(near&&(!P.modes.length||near.set.mode==='dodge')){
const s=near.set;
if(s.mode&&(!P.modes.length||s.mode==='dodge')){P.modes=[s.mode].concat(P.modes.filter(m=>m!==s.mode));}
if(s.item&&!P.items.length)P.items.push(s.item);
if(s.haz&&!P.haz){P.haz=s.haz;P.hazN='Ghost';}
if(s.world&&!P.place)P.place=s.world;
if(s.power&&!P.power)P.power=s.power;if(s.music&&!P.music)P.music=s.music;if(s.night)P.night=true;
P.swaps.push(near.msg);
}
// the kind of play, when no play word was heard
if(!P.modes.length){
let m='platform',why='';
if(P.vehicle&&!P.heroFl&&!P.heroSea){m='race';why=P.heroWord;}
else if(P.heroFl){m='fly';why=P.heroWord;}
else if(P.heroSea&&P.place!=='ocean'){m='fly';why=P.heroWord;}
else if(P.friends.length){m='rescue';why='friends';}
else if(P.place==='pirate'||P.place==='island'||P.place==='beach'||P.place==='cave'){m='treasure';why=P.placeWord;}
else if(P.place==='space'||P.place==='moon'||P.place==='mars'||P.place==='forest'||P.place==='woods'){m='explore';why=P.placeWord;}
else if(P.items.length){m='collect';why='treats';}
else if(P.haz){m='dodge';why='enemies';}
else if(P.place==='ocean'||P.place==='sea'||P.place==='underwater'){m='fly';why=P.placeWord;}
P.modes=[m];P.inferred=true;
P.notes.push({w:why||'idea',e:MODE_E[m],what:'Best fit: '+MODE_LABEL[m].toLowerCase(),role:'mode'});
}
P.mode=P.modes[0];
P.mix=null;
for(const m of P.modes.slice(1))if(MIX_OF[m]&&MIX_OF[m]!==P.mode){P.mix=MIX_OF[m];break;}
if(!P.mix&&P.items.length&&P.mode!=='collect'&&P.mode!=='puzzle')P.mix='collect';
if(!P.mix&&P.friends.length&&P.mode!=='rescue'&&P.mode!=='puzzle')P.mix='rescue';
if(P.mix==='collect'&&P.mode==='collect')P.mix=null;
if(P.mode==='fly'&&P.modes.indexOf('platform')>0&&!P.power)P.power='jump';
P.found=P.notes.length;
if(!P.found&&!P.swaps.length)P.swaps.push('That idea is brand new to me! I made my best guess.');
return P;
}
/* Make up a customer's request, in words, from the same dictionary */
const REQ_HEROES=['pig','unicorn','dragon','puppy','bunny','penguin','robot','astronaut','mermaid','monkey','elephant','fox','frog','owl','turtle','dino','panda','koala','duck','princess','superhero','ninja','car','rocket','hamster','dolphin','giraffe','sloth','snowman','fairy','bear','octopus','kangaroo','chicken'];
const REQ_PLACES=[['on the moon','moon'],['under the sea','underwater'],['in a candy kingdom','candy'],['on a farm','farm'],['in the jungle','jungle'],['at the beach','beach'],['in the desert','desert'],['in a big city','city'],['in a snowy land','snow'],['in outer space','space'],['in a castle','castle'],['in an ice cream factory','icecream'],['on pirate island','pirate'],['in a robot factory','robot'],['in donut world','donut'],['on a rainbow','rainbow'],['in the clouds','sky'],['near a volcano','volcano'],['in a silly spooky house','spookyhouse'],['in a toy shop','toyshop'],['in a crystal cave','cave'],['at school','school'],['in a giant kitchen','kitchen'],['in the forest','forest'],['on Mars','mars']];
const REQ_ITEMS=['pizza','carrot','cookie','donut','star','gem','banana','strawberry','coin','candy','ice cream','cheese','apple','pretzel','shell','acorn','present','heart','balloon','crown','honey','watermelon','popcorn'];
const REQ_HAZ=['shark','bee','crab','meteor','rock','ghost','bat','snake','storm','spider','fire','tornado','cactus','slime','wave'];
const REQ_FR=['puppy','chick','bunny','hamster','duck','baby turtle','koala','penguin','panda'];
const REQ_EXTRA=['at night','in the snow','in the rain','with lots of bubbles','super fast','with a giant hero','with a tiny hero','with sparkles everywhere','with a pink sky','with party music','with calm music','and it is super hard','and it is easy'];
const pl=w=>{if(/(sh|ch|x|s)$/.test(w))return w+'es';if(/[^aeiou]y$/.test(w))return w.slice(0,-1)+'ies';if(w==='fish'||w==='sheep')return w;if(w==='mouse')return 'mice';if(w==='ice cream')return 'ice creams';if(w==='popcorn')return 'popcorn';return w+'s';};
function pickOne(a,r){return a[Math.floor(r()*a.length)];}
function makeRequest(opts){
const r=(opts&&opts.rand)||Math.random,avoid=(opts&&opts.avoid)||[];
const modes=['race','fly','platform','treasure','explore','collect','dodge','puzzle','rescue'].filter(m=>avoid.indexOf(m)<0);
const m=pickOne(modes.length?modes:['collect'],r);
let h=pickOne(REQ_HEROES,r);if(m==='race'&&r()<.5)h=pickOne(['car','racecar','truck','tractor','unicorn','dino'],r);
const [pp]=pickOne(REQ_PLACES,r),I=pickOne(REQ_ITEMS,r),Z=pickOne(REQ_HAZ,r),F=pickOne(REQ_FR,r);
const H=an(h)+' '+h;
const S={
race:`a racing game where ${H} drives ${pp}`+(r()<.6?` and grabs ${pl(I)}`:''),
fly:`${H} that flies ${pp}`+(r()<.6?` and collects ${pl(I)}`:` and dodges ${pl(Z)}`),
platform:`a jumping game with ${H} hopping ${pp}`+(r()<.6?` over ${pl(Z)}`:` and grabbing ${pl(I)}`),
treasure:`${H} hunting for treasure ${pp}`+(r()<.5?` and avoiding ${pl(Z)}`:''),
explore:`${H} exploring ${pp}`+(r()<.5?` and finding ${pl(I)}`:''),
collect:`${H} catching falling ${pl(I)} ${pp}`+(r()<.5?` and dodging ${pl(Z)}`:''),
dodge:`${H} dodging ${pl(Z)} ${pp}`+(r()<.5?` and collecting ${pl(I)}`:''),
puzzle:`a memory puzzle with ${H} ${pp}`,
rescue:`${H} saving lost baby ${pl(F)} ${pp}`+(r()<.4?` and escaping ${pl(Z)}`:'')
}[m];
const extra=r()<.45?' '+pickOne(REQ_EXTRA,r):'';
const start=pickOne(['I want ','Can you make ','My idea is ','Please make ','I dream of '],r);
let s=start+S+extra;
s=s.charAt(0).toUpperCase()+s.slice(1)+'!';
return s;
}
function an(w){return /^[aeiou]/i.test(w)?'an':'a';}
function nameFor(P,heroN,worldS,modeId,mix){
const parts=[];
if(heroN)parts.push(heroN.replace(/^Pirate Parrot$/,'Parrot')+'’s');
if(worldS&&worldS!==heroN)parts.push(worldS);
parts.push(NAME_MODE[modeId]||'Game');
if(mix==='collect'&&modeId!=='collect')parts.push('& Catch');
else if(mix==='rescue')parts.push('& Rescue');
else if(mix==='treasure')parts.push('of Treasure');
return parts.join(' ').slice(0,34);
}
window.KidIdea={read,makeRequest,nameFor,MIX_LABEL,WEA_E,dict:D,places:PL};
})();
art.js (the cartoon heroes and enemies, drawn in code)61 lines
/* Kidopia drawn art: cartoon heroes and enemies drawn in code, so they look the same on every device.
KidArt.draw(ctx, emoji) paints into a 128 x 128 box when the emoji has art and returns true. No cats. */
(function(){'use strict';
const P=Math.PI*2;
function E(c,x,y,rx,ry,col,rot){c.beginPath();c.ellipse(x,y,rx,ry,rot||0,0,P);if(col){c.fillStyle=col;c.fill();}}
function O(c,w){c.lineWidth=w||4;c.strokeStyle='#2a1460';c.stroke();}
function B(c,x,y,rx,ry,col,rot){E(c,x,y,rx,ry,col,rot);O(c);}
function poly(c,pts,col){c.beginPath();c.moveTo(pts[0],pts[1]);for(let i=2;i<pts.length;i+=2)c.lineTo(pts[i],pts[i+1]);c.closePath();c.fillStyle=col;c.fill();O(c,3.5);}
function eyes(c,x,y,gap,s,cheek){for(const d of [-1,1]){E(c,x+d*gap,y,s,s*1.15,'#2a1460');E(c,x+d*gap+s*.35,y-s*.4,s*.38,s*.38,'#fff');}
if(cheek!==false){c.globalAlpha=.55;E(c,x-gap*1.75,y+s*1.6,s*.95,s*.6,'#ff7fae');E(c,x+gap*1.75,y+s*1.6,s*.95,s*.6,'#ff7fae');c.globalAlpha=1;}}
function RR(c,x,y,w,h,r){if(c.roundRect)c.roundRect(x,y,w,h,r);else c.rect(x,y,w,h);}
function smile(c,x,y,w){c.beginPath();c.arc(x,y,w,.15*Math.PI,.85*Math.PI);c.lineWidth=3.5;c.strokeStyle='#2a1460';c.lineCap='round';c.stroke();}
function kid(c,skin,hair,suit,extra){ // a small cartoon child: body, head, hair, then extras
B(c,64,100,24,20,suit);B(c,64,56,30,30,skin);
if(hair){c.beginPath();c.arc(64,52,31,Math.PI*1.02,Math.PI*1.98);c.lineTo(94,58);c.quadraticCurveTo(64,36,34,58);c.closePath();c.fillStyle=hair;c.fill();O(c,3.5);}
eyes(c,64,60,11,4.5);smile(c,64,68,7);if(extra)extra(c);}
const A={
'🦄':c=>{poly(c,[52,26,64,0,72,28],'#ffd23f');B(c,64,84,38,30,'#fff');B(c,64,58,30,28,'#fff');
for(const [x,col] of [[40,'#ff7fae'],[46,'#7fd8ff'],[52,'#b28cff']]){E(c,x,50,7,20,col,-.3);}
poly(c,[44,34,48,18,58,30],'#fff');eyes(c,70,58,10,4.5);smile(c,70,68,6);},
'🐉':c=>{poly(c,[18,70,6,36,40,58],'#7ce07c');poly(c,[110,70,122,36,88,58],'#7ce07c');B(c,64,88,34,30,'#4cc46a');E(c,64,94,18,16,'#c8f7a8');
B(c,64,54,32,28,'#4cc46a');poly(c,[44,32,40,14,54,28],'#ffd23f');poly(c,[84,32,88,14,74,28],'#ffd23f');E(c,64,66,16,10,'#8fe08f');eyes(c,64,50,12,4.5);E(c,58,66,2,2,'#2a1460');E(c,70,66,2,2,'#2a1460');},
'🧜♀️':c=>{poly(c,[50,96,64,124,78,96],'#3fd6c6');poly(c,[64,116,48,126,64,122,80,126],'#3fd6c6');
kid(c,'#ffd8b8','#ff5fa2','#3fd6c6',cc=>{E(cc,30,70,8,22,'#ff5fa2');E(cc,98,70,8,22,'#ff5fa2');E(cc,58,92,8,6,'#b28cff');E(cc,70,92,8,6,'#b28cff');});},
'🧑🚀':c=>{B(c,64,100,26,20,'#f2f4ff');B(c,64,56,36,34,'#f2f4ff');B(c,64,58,26,22,'#7fd8ff');E(c,56,50,6,4,'rgba(255,255,255,.8)');
eyes(c,64,60,9,4,false);smile(c,64,67,5);E(c,64,104,6,6,'#ff4f6d');E(c,100,40,5,5,'#ffd23f');},
'👸':c=>{kid(c,'#ffd8b8','#ffcf4d','#ff8fd0',cc=>{poly(cc,[46,30,46,14,55,24,64,10,73,24,82,14,82,30],'#ffd23f');E(cc,64,20,3,3,'#ff4f6d');});},
'🦸':c=>{poly(c,[40,90,30,126,98,126,88,90],'#ff4f6d');kid(c,'#e8b48a','#3a2a1a','#3fa8ff',cc=>{E(cc,64,58,26,7,'#ff4f6d');eyes(cc,64,59,11,3.5,false);poly(cc,[58,96,64,90,70,96,64,104],'#ffd23f');});},
'🤖':c=>{c.fillStyle='#ffd23f';E(c,64,10,6,6,'#ffd23f');O(c,3);c.beginPath();c.moveTo(64,16);c.lineTo(64,28);O(c,4);
c.beginPath();RR(c,28,28,72,54,14);c.fillStyle='#9fb4d8';c.fill();O(c);c.beginPath();RR(c,38,40,52,28,10);c.fillStyle='#2a3a66';c.fill();
E(c,52,54,7,7,'#4cf2ff');E(c,76,54,7,7,'#4cf2ff');c.beginPath();RR(c,40,84,48,36,10);c.fillStyle='#7d8aa8';c.fill();O(c);E(c,64,100,6,6,'#ff4f6d');},
'🐶':c=>{B(c,64,96,30,24,'#e0a96d');B(c,64,58,34,30,'#f0c08a');B(c,30,58,10,24,'#8a5a2b',.3);B(c,98,58,10,24,'#8a5a2b',-.3);E(c,64,72,16,11,'#fff2dc');eyes(c,64,54,12,4.5);E(c,64,66,5,4,'#2a1460');smile(c,64,70,5);},
'🐰':c=>{B(c,48,22,9,24,'#fff');B(c,80,22,9,24,'#fff');E(c,48,24,4,16,'#ffb3cf');E(c,80,24,4,16,'#ffb3cf');B(c,64,96,28,24,'#fff');B(c,64,62,30,28,'#fff');eyes(c,64,60,11,4.5);E(c,64,70,4,3,'#ff7fae');},
'🐧':c=>{B(c,64,74,34,46,'#2a3a66');E(c,64,82,22,32,'#fff');E(c,64,48,24,18,'#fff');eyes(c,64,48,10,4.5);poly(c,[56,58,72,58,64,68],'#ffa53f');E(c,50,120,9,4,'#ffa53f');E(c,78,120,9,4,'#ffa53f');},
'🦜':c=>{poly(c,[56,100,64,128,72,100],'#3fa8ff');B(c,64,82,28,32,'#ff4f6d');B(c,82,80,10,22,'#ffd23f',-.3);B(c,64,46,26,24,'#ff4f6d');
c.beginPath();c.moveTo(40,48);c.quadraticCurveTo(24,52,34,66);c.lineTo(44,56);c.closePath();c.fillStyle='#ffd23f';c.fill();O(c,3.5);eyes(c,66,42,9,4,false);
poly(c,[44,26,86,26,80,14,50,14],'#2a1460');},
'🦕':c=>{B(c,98,92,22,8,'#7ad1a0',-.4);B(c,64,94,34,24,'#7ad1a0');for(const x of [44,58,72,86])poly(c,[x-6,74,x,62,x+6,74],'#ffd23f');B(c,42,54,22,22,'#7ad1a0');eyes(c,40,50,8,4);smile(c,38,60,5);E(c,50,118,7,5,'#5ab880');E(c,78,118,7,5,'#5ab880');},
'🐻':c=>{B(c,38,32,11,11,'#b07040');B(c,90,32,11,11,'#b07040');B(c,64,96,30,24,'#b07040');B(c,64,60,34,30,'#c88050');E(c,64,72,15,11,'#f0c8a0');eyes(c,64,56,12,4.5);E(c,64,67,5,4,'#2a1460');smile(c,64,72,5);},
'🐼':c=>{B(c,38,32,11,11,'#2a2a3a');B(c,90,32,11,11,'#2a2a3a');B(c,64,96,30,24,'#2a2a3a');B(c,64,60,34,30,'#fff');E(c,52,58,9,11,'#2a2a3a',.4);E(c,76,58,9,11,'#2a2a3a',-.4);
E(c,52,58,3.5,4,'#fff');E(c,76,58,3.5,4,'#fff');E(c,64,70,5,4,'#2a1460');smile(c,64,74,5);},
'🐙':c=>{for(let i=0;i<6;i++){const x=34+i*12;B(c,x,100,6,18,'#b28cff',(i-2.5)*.15);}B(c,64,62,38,38,'#b28cff');eyes(c,64,64,12,5);smile(c,64,74,6);E(c,50,40,6,4,'rgba(255,255,255,.6)');},
'🦉':c=>{poly(c,[36,30,44,14,52,30],'#a0703a');poly(c,[76,30,84,14,92,30],'#a0703a');B(c,64,72,38,46,'#a0703a');E(c,64,88,24,28,'#f0d0a0');
B(c,50,54,14,14,'#fff');B(c,78,54,14,14,'#fff');E(c,50,55,6,7,'#2a1460');E(c,78,55,6,7,'#2a1460');E(c,52,52,2.5,2.5,'#fff');E(c,80,52,2.5,2.5,'#fff');poly(c,[58,66,70,66,64,76],'#ffa53f');},
'🐸':c=>{B(c,64,90,38,28,'#5ccf5c');B(c,64,64,40,26,'#6cdc6c');B(c,44,42,14,14,'#6cdc6c');B(c,84,42,14,14,'#6cdc6c');E(c,44,42,6,7,'#2a1460');E(c,84,42,6,7,'#2a1460');E(c,46,39,2.5,2.5,'#fff');E(c,86,39,2.5,2.5,'#fff');smile(c,64,62,16);},
/* enemies: silly, not scary */
'👻':c=>{c.beginPath();c.moveTo(30,110);c.lineTo(30,56);c.arc(64,56,34,Math.PI,0);c.lineTo(98,110);for(let i=0;i<4;i++){c.quadraticCurveTo(94-i*17,98,89-i*17,110);}c.closePath();c.fillStyle='#fff';c.fill();O(c);eyes(c,64,58,11,5);E(c,64,76,6,8,'#2a1460');},
'🪨':c=>{poly(c,[20,96,30,52,56,32,90,40,108,70,100,100],'#9aa0b0');E(c,48,56,8,5,'#b8bfcc');eyes(c,64,72,11,4.5,false);c.beginPath();c.moveTo(52,58);c.lineTo(62,62);c.moveTo(76,58);c.lineTo(66,62);O(c,3);},
'🐝':c=>{B(c,50,36,14,20,'rgba(220,245,255,.9)',-.4);B(c,78,36,14,20,'rgba(220,245,255,.9)',.4);B(c,64,72,36,28,'#ffd23f');c.save();c.beginPath();c.ellipse(64,72,34,26,0,0,P);c.clip();c.fillStyle='#2a1460';c.fillRect(56,40,10,70);c.fillRect(78,40,10,70);c.restore();
poly(c,[100,72,114,68,100,80],'#2a1460');eyes(c,40,68,6,3.5);},
'⛈️':c=>{poly(c,[60,80,48,108,62,104,54,126,80,94,66,98,74,80],'#ffd23f');E(c,40,62,24,20,'#8a92b8');E(c,64,48,28,26,'#8a92b8');E(c,90,62,24,20,'#8a92b8');E(c,64,70,44,16,'#8a92b8');eyes(c,64,60,10,4,false);c.beginPath();c.moveTo(50,48);c.lineTo(60,53);c.moveTo(78,48);c.lineTo(68,53);O(c,3);},
'🦀':c=>{B(c,24,44,12,10,'#ff6b4a');B(c,104,44,12,10,'#ff6b4a');c.beginPath();c.moveTo(30,56);c.lineTo(44,72);c.moveTo(98,56);c.lineTo(84,72);O(c,5);
for(const d of [-1,1])for(let i=0;i<3;i++){c.beginPath();c.moveTo(64+d*28,90+i*6);c.lineTo(64+d*48,100+i*8);O(c,4);}B(c,64,84,36,24,'#ff6b4a');E(c,52,54,7,9,'#fff');E(c,76,54,7,9,'#fff');O(c,3);E(c,52,56,3.5,4,'#2a1460');E(c,76,56,3.5,4,'#2a1460');smile(c,64,88,8);},
'☄️':c=>{c.globalAlpha=.8;poly(c,[80,40,120,6,96,52],'#ffd23f');poly(c,[86,58,124,40,92,74],'#ff9f3f');c.globalAlpha=1;B(c,58,70,32,30,'#a07a60');E(c,48,60,7,6,'#8a6450');E(c,70,84,6,5,'#8a6450');eyes(c,58,70,9,4,false);},
'🔥':c=>{c.beginPath();c.moveTo(64,10);c.bezierCurveTo(96,44,108,70,96,96);c.quadraticCurveTo(84,120,64,120);c.quadraticCurveTo(36,120,30,96);c.bezierCurveTo(24,72,40,60,46,40);c.quadraticCurveTo(54,60,58,56);c.quadraticCurveTo(54,30,64,10);c.fillStyle='#ff7a2f';c.fill();O(c);
c.beginPath();c.moveTo(64,52);c.bezierCurveTo(84,74,90,96,64,112);c.bezierCurveTo(40,100,46,76,64,52);c.fillStyle='#ffd23f';c.fill();eyes(c,64,90,8,4,false);}
};
A['🌩️']=A['⛈️'];A['🌨️']=A['⛈️'];
window.KidArt={has:e=>!!A[e],draw(c,e){const f=A[e];if(!f)return false;c.save();c.lineJoin='round';f(c);c.restore();return true;}};
})();
index.html38 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover,user-scalable=no">
<title>Kidopia: The Magical Game Shop</title>
<meta name="description" content="A free children's game from a child's idea: run a magical video game shop, make each customer's game on a magic phone and play it together on the big TV.">
<meta name="theme-color" content="#2a1460">
<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="Kidopia">
<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="./kidopia.css">
</head>
<body>
<canvas id="cv" aria-label="The Kidopia game shop"></canvas>
<div id="hud" class="hud hide">
<div class="pill" id="hCoins">🪙 0</div>
<div class="pill" id="hStars">⭐ 0</div>
<div class="pill clock" id="hClock">⏰ 5:00</div>
<div class="sp"></div>
<button class="ib" id="bFree" aria-label="Make my own game">📱</button>
<button class="ib" id="bMute" aria-label="Sound on or off">🔊</button>
<button class="ib" id="bMenu" aria-label="Menu">☰</button>
</div>
<div id="ui"></div>
<div id="toast" class="toast" aria-live="polite"></div>
<noscript>Kidopia needs JavaScript to play.</noscript>
<script src="./art.js"></script>
<script src="./idea.js"></script>
<script src="./kidopia.js"></script>
</body>
</html>
kidopia.css (the phone, cards, buttons and layouts)191 lines
@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')}
/* Kidopia: a bright cartoon toy shop at night. Purple walls, candy neon, gold coins. Fredoka for all text. */
:root{--ink:#2a1460;--ink2:#47208f;--pink:#ff4fa3;--yel:#ffd23f;--cyan:#3ff2ff;--mint:#4cf2a0;--white:#fff;--card:#fffaf2;--shadow:0 8px 0 rgba(30,10,70,.35);--emo:"Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;background:#2a1460;color:#2a1460;font-family:Fredoka,"Trebuchet MS",system-ui,sans-serif;font-weight:600;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
canvas#cv{position:fixed;inset:0;width:100%;height:100%;display:block}
button{font:inherit;cursor:pointer;border:0;color:inherit;touch-action:manipulation}
input{font:inherit}
.hide{display:none!important}
.hud{position:fixed;left:0;right:0;top:0;display:flex;gap:6px;align-items:center;padding:calc(env(safe-area-inset-top) + 8px) calc(env(safe-area-inset-right) + 8px) 0 calc(env(safe-area-inset-left) + 8px);z-index:20;pointer-events:none}
.hud .sp{flex:1}
.pill{pointer-events:auto;background:rgba(20,6,60,.72);color:#fff;border-radius:999px;padding:6px 12px;font-size:16px;border:2px solid rgba(255,255,255,.25);white-space:nowrap}
.pill.clock.low{background:#ff4f6d;animation:pulse 1s infinite}
.ib{pointer-events:auto;width:44px;height:44px;border-radius:14px;background:rgba(20,6,60,.72);border:2px solid rgba(255,255,255,.25);font-size:22px;font-family:var(--emo);display:grid;place-items:center;color:#fff}
.ib:active{transform:scale(.92)}
#ui{position:fixed;inset:0;z-index:30;pointer-events:none}
#ui>*{pointer-events:auto}
/* bottom sheet */
.sheet{position:absolute;left:50%;bottom:calc(env(safe-area-inset-bottom) + 10px);transform:translateX(-50%);width:min(720px,calc(100% - 16px));background:var(--card);border-radius:28px;padding:14px;box-shadow:var(--shadow),0 0 0 4px #fff inset;animation:up .35s cubic-bezier(.2,1.4,.5,1)}
.sheet h2{margin:2px 6px 10px;font-size:22px;line-height:1.15;text-align:center}
.sheet p.sub{margin:-4px 6px 10px;text-align:center;font-size:15px;color:#6a4aa8}
.opts{display:grid;gap:10px}
.opt{display:flex;align-items:center;gap:12px;min-height:64px;padding:10px 16px;border-radius:20px;font-size:20px;text-align:left;color:#fff;box-shadow:0 6px 0 rgba(0,0,0,.22);transition:transform .1s}
.opt:active{transform:translateY(4px);box-shadow:0 2px 0 rgba(0,0,0,.22)}
.opt .e{font-family:var(--emo);font-size:34px;line-height:1}
.o1{background:linear-gradient(135deg,#ff4fa3,#ff7b54)}
.o2{background:linear-gradient(135deg,#7b5cff,#3fa8ff)}
.o3{background:linear-gradient(135deg,#19c37d,#3ff2c0);color:#0b3b2a}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:56px;padding:10px 22px;border-radius:18px;font-size:20px;background:#7b5cff;color:#fff;box-shadow:0 6px 0 #4a2fb8}
.btn:active{transform:translateY(4px);box-shadow:0 2px 0 #4a2fb8}
.btn.y{background:var(--yel);color:#4a2a00;box-shadow:0 6px 0 #c99400}
.btn.g{background:#19c37d;box-shadow:0 6px 0 #0d8a56}
.btn.p{background:var(--pink);box-shadow:0 6px 0 #b8216d}
.btn.w{background:#fff;color:#47208f;box-shadow:0 6px 0 #c9b8f0}
.btn[disabled]{opacity:.45}
.row{display:flex;gap:10px;justify-content:center;flex-wrap:wrap;margin-top:12px}
/* idea cards */
.ideas{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
.idea{position:relative;border-radius:20px;padding:10px 6px 10px;color:#fff;text-align:center;min-height:132px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;box-shadow:0 6px 0 rgba(0,0,0,.22);border:4px solid transparent}
.idea .art{font-family:var(--emo);font-size:40px;line-height:1.05;letter-spacing:-4px}
.idea .nm{font-size:16px;line-height:1.1}
.idea.on{border-color:#fff;outline:4px solid var(--yel);transform:translateY(-3px)}
.idea .chk{position:absolute;top:6px;right:8px;font-family:var(--emo);font-size:20px}
.ideahint{text-align:center;font-size:14px;color:#6a4aa8;margin-top:8px}
.typein{display:flex;gap:8px;margin-top:10px}
.typein input{flex:1;min-width:0;min-height:52px;border-radius:16px;border:3px solid #c9b8f0;padding:6px 14px;font-size:18px;color:#2a1460;background:#fff;-webkit-user-select:text;user-select:text}
.wish{background:#fff;border-radius:18px;padding:10px 14px;font-size:19px;text-align:center;border:3px dashed #ffb3d6;margin-bottom:6px}
.wish .e{font-family:var(--emo)}
/* the magic phone */
.phone{position:absolute;bottom:calc(env(safe-area-inset-bottom) + 6px);left:50%;transform:translateX(-50%);width:min(400px,calc(100% - 12px));height:min(720px,calc(100% - 64px - env(safe-area-inset-top)));background:#111;border-radius:40px;padding:12px;box-shadow:0 0 0 3px #7b5cff,0 0 40px rgba(123,92,255,.8),var(--shadow);display:flex;flex-direction:column;animation:phoneup .45s cubic-bezier(.2,1.3,.5,1)}
.phone.rainbow{box-shadow:0 0 0 4px #ff4fa3,0 0 0 8px #ffd23f,0 0 0 12px #3ff2ff,0 0 50px rgba(255,79,163,.8),var(--shadow)}
.phone.gold{box-shadow:0 0 0 4px #ffd23f,0 0 50px rgba(255,210,63,.9),var(--shadow)}
.pscr{flex:1;min-height:0;border-radius:30px;background:linear-gradient(170deg,#2b1a7a,#7b2fbf 55%,#ff4fa3);display:flex;flex-direction:column;overflow:hidden;color:#fff;position:relative}
.ptop{display:flex;align-items:center;gap:8px;padding:12px 14px 6px}
.ptop .ttl{flex:1;font-size:15px;opacity:.9}
.ptop .x{width:40px;height:40px;border-radius:12px;background:rgba(255,255,255,.18);font-size:18px}
.notch{position:absolute;top:6px;left:50%;transform:translateX(-50%);width:90px;height:8px;border-radius:9px;background:#111}
.pname{display:flex;gap:6px;padding:4px 12px 8px}
.pname input{flex:1;min-width:0;height:48px;border-radius:14px;border:0;padding:4px 12px;font-size:18px;color:#2a1460;-webkit-user-select:text;user-select:text}
.pname button{width:48px;height:48px;border-radius:14px;background:var(--yel);font-family:var(--emo);font-size:24px}
.tabs{display:flex;gap:6px;overflow-x:auto;padding:2px 12px 8px;scrollbar-width:none}
.tabs::-webkit-scrollbar{display:none}
.tab{flex:0 0 auto;min-width:62px;height:62px;border-radius:16px;background:rgba(255,255,255,.14);display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:11px;gap:1px;position:relative}
.tab .e{font-family:var(--emo);font-size:24px}
.tab.on{background:#fff;color:#47208f}
.tab .dot{position:absolute;top:3px;right:5px;font-family:var(--emo);font-size:11px}
.tiles{flex:1;min-height:0;overflow-y:auto;display:grid;grid-template-columns:repeat(3,1fr);gap:8px;padding:4px 12px 10px;align-content:start;touch-action:pan-y}
.tile{position:relative;min-height:84px;border-radius:18px;background:rgba(255,255,255,.16);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;font-size:13px;line-height:1.1;padding:6px 4px;text-align:center;color:#fff;border:3px solid transparent}
.tile .e{font-family:var(--emo);font-size:34px;line-height:1.1}
.tile.on{background:#fff;color:#47208f;border-color:var(--yel)}
.tile.lock{opacity:.4}
.tile .heart{position:absolute;top:3px;right:5px;font-family:var(--emo);font-size:14px}
.tile.new::after{content:"NEW";position:absolute;top:-6px;left:-4px;background:var(--pink);color:#fff;font-size:10px;padding:2px 6px;border-radius:8px}
.pfoot{padding:8px 12px 14px}
.create{width:100%;min-height:66px;border-radius:22px;font-size:24px;letter-spacing:1px;color:#4a2a00;background:linear-gradient(90deg,#ffd23f,#ffef9a,#ffd23f);background-size:200% 100%;box-shadow:0 0 0 3px #fff,0 0 24px #ffd23f,0 0 48px #ff4fa3;animation:glow 1.4s ease-in-out infinite,shine 2.5s linear infinite}
.create:active{transform:scale(.97)}
.match{font-size:13px;text-align:center;padding:0 12px 4px;opacity:.95}
.match .e{font-family:var(--emo)}
.making{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;background:radial-gradient(circle,#ff9ad5,#7b2fbf 60%,#2b1a7a);z-index:3}
.making .big{font-family:var(--emo);font-size:90px;animation:spin 1.2s linear infinite}
.making .lbl{font-size:22px}
.bar{width:70%;height:18px;border-radius:9px;background:rgba(255,255,255,.25);overflow:hidden}
.bar i{display:block;height:100%;width:0;background:linear-gradient(90deg,#3ff2ff,#ffd23f,#ff4fa3);border-radius:9px;transition:width .2s linear}
/* centre cards: title, results, summary, menu */
.card{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(560px,calc(100% - 20px));max-height:calc(100% - 20px);overflow-y:auto;background:var(--card);border-radius:30px;padding:18px;text-align:center;box-shadow:var(--shadow),0 0 0 5px #fff inset;animation:pop .4s cubic-bezier(.2,1.5,.5,1);touch-action:pan-y}
.card h1{margin:0;font-size:clamp(34px,9vw,58px);line-height:1;color:var(--pink);text-shadow:0 4px 0 #ffd23f}
.card h2{margin:4px 0 8px;font-size:24px}
.card .by{font-size:17px;color:#6a4aa8;margin:6px 0 10px}
.card .lead{font-size:17px;margin:6px 0}
.card .small{font-size:13px;color:#6a4aa8;margin-top:12px;line-height:1.35}
.card .stars{font-family:var(--emo);font-size:44px;letter-spacing:4px;margin:4px 0}
.card .big{font-family:var(--emo);font-size:56px;line-height:1.1}
.stats{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:10px 0}
.stat{background:#fff;border-radius:16px;padding:8px;border:3px solid #ece2ff}
.stat b{display:block;font-size:26px;color:#47208f}
.stat span{font-size:13px;color:#6a4aa8}
.unl{background:linear-gradient(135deg,#fff3b0,#ffd6ec);border-radius:18px;padding:10px;margin:8px 0;font-size:17px}
.unl .e{font-family:var(--emo);font-size:30px}
.made{font-size:14px;color:#47208f;margin:6px 0;line-height:1.5}
.title-card{top:auto;bottom:calc(env(safe-area-inset-bottom) + 12px);transform:translateX(-50%);background:rgba(255,250,242,.96)}
.toast{position:fixed;left:50%;top:calc(env(safe-area-inset-top) + 62px);transform:translateX(-50%) translateY(-20px);background:#ffd23f;color:#4a2a00;padding:10px 18px;border-radius:999px;font-size:18px;z-index:50;opacity:0;transition:all .3s;pointer-events:none;box-shadow:0 5px 0 #c99400;max-width:calc(100% - 20px);text-align:center}
.toast.on{opacity:1;transform:translateX(-50%) translateY(0)}
.gamebar{position:absolute;top:calc(env(safe-area-inset-top) + 8px);right:calc(env(safe-area-inset-right) + 8px);display:flex;gap:6px}
@keyframes up{from{transform:translate(-50%,110%)}to{transform:translate(-50%,0)}}
@keyframes phoneup{from{transform:translate(-50%,120%) rotate(8deg)}to{transform:translate(-50%,0)}}
@keyframes pop{from{transform:translate(-50%,-50%) scale(.6);opacity:0}to{transform:translate(-50%,-50%) scale(1);opacity:1}}
.title-card{animation:up .5s cubic-bezier(.2,1.3,.5,1)}
@keyframes glow{50%{box-shadow:0 0 0 3px #fff,0 0 36px #ffd23f,0 0 70px #ff4fa3}}
@keyframes shine{to{background-position:-200% 0}}
@keyframes spin{to{transform:rotate(360deg)}}
@keyframes pulse{50%{transform:scale(1.06)}}
.phone.fly{animation:phonefly .6s ease-in forwards}
@keyframes phonefly{to{transform:translate(-50%,0) scale(.3);opacity:0}}
@media (max-height:520px) and (orientation:landscape){
.phone{left:auto;right:calc(env(safe-area-inset-right) + 8px);transform:none;width:min(560px,62vw);height:calc(100% - 12px);bottom:6px;animation:none;border-radius:28px;padding:8px}
.pscr{border-radius:22px}
.phone.fly{animation:phonefly2 .6s ease-in forwards}
.tiles{grid-template-columns:repeat(4,1fr)}
.tile{min-height:66px}.tile .e{font-size:26px}
.tab{height:50px;min-width:54px}.tab .e{font-size:20px}
.create{min-height:50px;font-size:20px}
.pfoot{padding:4px 10px 8px}
.ptop{padding:6px 12px 2px}
.pname input,.pname button{height:40px}
.sheet{padding:10px;width:min(760px,calc(100% - 16px))}
.sheet h2{font-size:18px;margin-bottom:6px}
.opts{grid-template-columns:repeat(3,1fr)}
.opt{flex-direction:column;text-align:center;font-size:16px;gap:4px;min-height:56px;padding:8px}
.opt .e{font-size:26px}
.ideas{grid-template-columns:repeat(6,1fr);gap:6px}
.idea{min-height:96px}.idea .art{font-size:28px}.idea .nm{font-size:13px}
.card{padding:12px}.card h1{font-size:40px}
.stats{grid-template-columns:repeat(3,1fr)}
.title-card{bottom:8px}
}
@keyframes phonefly2{to{transform:scale(.3);opacity:0}}
@media (max-width:380px){
.ideas{grid-template-columns:repeat(2,1fr)}
.opt{font-size:18px}
.tiles{grid-template-columns:repeat(3,1fr);gap:6px;padding:4px 8px 8px}
.tile{min-height:76px;font-size:12px}
}
@media (prefers-reduced-motion:reduce){*{animation-duration:.01s!important;animation-iteration-count:1!important}}
.card .row{position:sticky;bottom:-18px;background:var(--card);padding:8px 0 10px;margin-bottom:-8px}
@media (max-height:520px) and (orientation:landscape){
.card .row{bottom:-12px}
.card .big{display:none}
.card .stars{font-size:30px;margin:0}
.card h2{margin:0 0 4px;font-size:20px}
.notch,.ptop .ttl,.match{display:none}
.ptop{position:absolute;top:6px;right:8px;padding:0;z-index:2}
.ptop .x{width:38px;height:38px}
.pname{padding:8px 54px 4px 10px}
.tabs{padding:2px 10px 4px}
.tab{height:44px;min-width:50px;font-size:10px}.tab .e{font-size:18px}
.tile{min-height:58px;font-size:11px}.tile .e{font-size:22px}
}
/* idea engine reader */
.sheet{max-height:calc(100% - 70px - env(safe-area-inset-top));overflow-y:auto;touch-action:pan-y}
.said{background:#fff;border-radius:18px;padding:10px 14px;font-size:18px;line-height:1.45;margin-bottom:8px;border:3px solid #ece2ff}
.said b{border-radius:8px;padding:0 4px}
.chips{display:flex;flex-wrap:wrap;gap:6px;justify-content:center;margin:4px 0 8px}
.chip{display:inline-flex;align-items:center;gap:4px;background:#f1eaff;border-radius:999px;padding:5px 11px;font-size:14px;animation:chipin .4s cubic-bezier(.2,1.5,.5,1) both}
.chip .e{font-family:var(--emo);font-size:18px}
.chip i{font-style:normal;opacity:.75}
@keyframes chipin{from{transform:scale(.3);opacity:0}to{transform:scale(1);opacity:1}}
.r-hero{background:#ffe08a}.r-place{background:#b8ecff}.r-mode{background:#ffc2e0}.r-item{background:#c8f7d4}
.r-haz{background:#ffcfc4}.r-friend{background:#d9ccff}.r-look{background:#e8e8ff}.r-power{background:#fff0a8}
.reader .row{position:sticky;bottom:-14px;background:var(--card);padding:6px 0 8px;margin:0;z-index:2}
.tile.idea::before{content:"🧠";position:absolute;top:3px;left:5px;font-family:var(--emo);font-size:12px}
@media (max-height:520px) and (orientation:landscape){
.said{font-size:15px;padding:6px 10px;margin-bottom:4px}
.chip{font-size:12px;padding:3px 8px}.chip .e{font-size:15px}
.reader .wish{font-size:15px;padding:6px}
.reader .row{bottom:-10px;padding:4px 0 6px}
.reader h2{font-size:16px;margin:0 0 4px}
}
manifest.webmanifest (Home Screen icon)17 lines
{
"name": "Kidopia: The Magical Game Shop",
"short_name": "Kidopia",
"description": "Run a magical video game shop: make each customer's game idea on a magic phone, send it to the TV and play it together.",
"id": "./",
"start_url": "./",
"scope": "./",
"display": "fullscreen",
"orientation": "any",
"background_color": "#2a1460",
"theme_color": "#2a1460",
"icons": [
{ "src": "icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
]
}
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.