Animation · project 35 of 37
T-Rex Kingdom.
A block-world 3D game for little ones, for one or two players: a baby T-rex walks, drives, races and flies from Rexy's Island through magic gates into twelve lands to find Mama Rex's eggs.
BeforeA six-year-old who loves dinosaurs, and games full of ads, timers and "Game over" screens she cannot finish alone.
AfterHer own block-world T-rex world for one or two players: an island with magic gates to twelve lands, ten eggs and a parade of babies in each, a grumpy volcano to tickle, cars, races, a plane and a big jet, a bathtub to dive in, cousins and their rooms, a rain land with shooting stars, and tag with a friend.
What it is worthA 3 to 6 minute win on her own, on the iPad, the phone or the computer. Instead of ads, accounts, fail screens and "can you help me, Dad?"
How to use it
- Pick a mode (🌼 Easy has no danger; 🔥 Adventure and ⚡ Turbo can be lost) and press PLAY with the sound on. It plays even when an iPhone or iPad is on silent.
- On Rexy's Island, swipe anywhere on the open screen to walk (arrow keys or WASD on a computer, the left stick on a game controller). The yellow arrow points to a land without a star. Walk through its gate, or tap GET IN at the car or the plane to drive or fly there.
- In a land, follow the light beams and the arrow to each egg and walk into it. Tap JUMP to jump and hold it to ROAR; FIRE makes animals and toys do tricks; RUN goes fast. Walk into the pond to dive with bubbles. Bump an animal or toy to push it (RUN pushes it right out of the land), or jump on it to squish it flat like a pancake. Or tap 💥 GET IN at the purple blaster and hold FIRE to blast holes in the land.
- After 10 eggs, fire at Grumbo the volcano's three pink spots (in Easy a roar near a spot works too). Then follow the gold light home to Mama Rex for the trophy, and go back to the island to see the land's new star.
- Tap 🏠 at the top (or press Esc, or Options on a game controller) to go back to the island; on the island it opens the start card. Grown-ups can jump straight to any land from the start card's fold.
- Two players: on the start card pick 🦖🦕 2 players. On a phone or iPad, player 1 (green) uses the right half of the screen and the green buttons, and player 2 (blue) uses the left half and the blue buttons. On a computer player 2 uses the arrow keys, Enter (jump), / (fire), . (get in) and right Shift (run); with controllers, one pad is player 2, or two pads are players 1 and 2. Bump into the other dino to tag them, or both hold FIRE close together for a light-saber duel.
- Full screen: tap ⛶ at the top right (or the Create button on a controller). On a TV browser, the remote's arrow keys walk, red fires, green jumps, yellow runs, blue gets in and Back goes home.
Where it helps most
- A first 3D game a child of four to seven can win alone, with an Easy mode that has no danger and harder modes for when she wants a challenge.
- A way to bring a child's own toys into a game safely: film them, measure them against one toy, and rebuild them as original block models, with no photo, name or voice used.
- A starting point for a three.js kids' game with iPhone-safe Web Audio, multi-touch and game controller support.
The idea
A young player who loves dinosaurs asked for a game. I wanted one a child can win alone, with no ads, no account and no reading needed. The requests grew: running, fire from the mouth, danger, volcanoes that erupt, different places to go, and the eggs and the mom. So Easy mode stays a no-danger path, and Adventure and Turbo add the danger. Then real bath toys came in: we filmed them on the tub edge, and they became Toy Land, each toy at its true size next to the others. I also used it to test a fast way of working: a playable link first, then short numbered versions, each checked by an independent QA agent, with an idea agent that borrows good mechanics from other games without copying any game. Later came vehicles, flying, diving with bubbles, a blue house full of cousins with a dog, and then all the places connected instead of picked from a list, like the hub worlds in platform games. So the maps became lands around one island.
The build
Claude built it in three.js r128 in numbered versions (v2 to v15) in one project, as one page plus one script. Rexy's Island is a 66 by 66 grid of blocks with nine gates in a ring 25 blocks from the centre; its ground is in patches that take the colours of the land each gate leads to, with a small landmark and a stone path at every gate. Walking through a gate fades the screen and builds the new land, and Rexy steps out of the matching gate on the other side. Each land is a 44 by 44 grid of blocks with gentle hills where no step is higher than one block. Each map has its own ground colours, water, weather and scenery, all from boxes in original art: palms and sand castles, cacti and pyramids, snowmen and ice, bamboo, autumn trees, pines and snowy peaks. Toy Land has a rainbow play-mat floor, letter blocks, balls, stacking rings and a giant rubber duck that squeaks when bumped. Its 19 toys (T-rex, little green dino, horse, zebra, little boar, orca, cow, stripy dino, shark, long-neck dino, buffalo, tiger, giraffe, elephant, leopard, polar bear, rat, toy soldier and a tiny cow) were measured from a short phone video against the toy horse, built as generic block animals with no brand shapes or logos, and scaled together so their sizes match the real toys; they walk around and do a trick and say hi when Rexy comes near. Every land has a pond (a bathtub in Toy Land) where Rexy can dive with bubbles and swim up, with no drowning, and a car and a plane to ride; leaving the plane high up opens a parachute. The Blue House land has nine cousin dinos with play names who hide behind bushes and dance when found, and a block dog called Azizam who fetches a red ball. Rexy can push the animals and toys: a bump sends one flying a short way, a run sends it out of the land, and it comes back with a poof a few seconds later. Jumping on one squishes it flat like a pancake, Rexy bounces, and it pops back up; nobody gets hurt or sad, and Mama Rex, the princess, the cousins and the dog are never pushed. Each land and the island also has a toy blaster station: Rexy sits on a purple turntable with three coloured barrels, turns with the joystick and holds FIRE to shoot paint balls that knock holes up to two blocks deep in the ground, pop trees and scenery and bump animals away. The volcanoes, the nest, Mama Rex, the princess, the gates and the Blue House are never destroyed, and a new game rebuilds the land. Phones that can vibrate, iPhones on iOS 18 and game controllers buzz on blasts, squishes, pushes and bumps. Gameplay borrows genre mechanics, not any game's look: a hub island with gates to each land, power-up gift boxes (star, magnet, giant, feather), a golden egg hidden high on each map, no enemies (grumpy beetles were tried and removed), a three-spot boss (Grumbo the volcano, who throws lava rocks with a red ring warning where they land), aim help for fire, a baby pile-up when Rexy stops after a run, and a hiccup puff now and then. Eggs glow under tall light beams and a yellow arrow points the way. All music and sounds are made live with Web Audio: scheduled 0.6 s ahead, about 14 sounds at once, a compressor. On iPhone and iPad the sound plays even on silent: the first tap asks iOS for playback audio (older iPhones loop a tiny silent MP3), and every tap or return wakes the sound. Touch: a floating joystick anywhere on the open screen, a second finger taps to jump, and JUMP, FIRE and RUN buttons; computer keys and a PS5, Xbox or Switch Pro controller also work. Stars per map, golden eggs, best time and trophies are kept only on the device. Limits: tested in desktop and phone emulation in a headless browser and by hand on the family's devices; the toy sizes are estimates from one video. Version 15 (2026-11-29) added a full second player: the game keeps one set of state per player (position, ride, power, fire and jump timing) and runs the same step for each, so player 2 can do everything player 1 can, including driving and flying. On a touch screen the left half is player 2's joystick with blue buttons at the bottom left, and the right half is player 1's with green buttons, each labelled with a dino face; keys and one or two controllers also work. A tag game (the tagged dino blinks for 3 seconds and a star shows who is IT) and cartoon light-saber duels with no damage give the two something to do together. The camera looks at the midpoint and pulls back as the players spread out or fly high, and rises above hills and fades signs, trees and parked vehicles that would block the view. v15 also added three lands (Inside the Blue House with nine cousin rooms, a Race Track with three-lap races against two computer cars, and Rain Land with a 70-second rain, rainbow and night cycle), a big jet the babies ride, more cars, and eggs hidden in crates and hollow trees. For older TV browsers it has layout fallbacks, starts with lighter graphics on a TV, lowers quality by itself when frames are slow, and shows a clear message where a browser has no WebGL (the PS5 browser has none, so the game cannot run there).
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: T-Rex Kingdom
You are a children's game designer and creative coder. Build "T-Rex Kingdom": an original block-world 3D web game for a six-year-old, in three.js r128 from a local file, as one HTML page, one CSS file and one script (no inline scripts or styles; it must run under a strict Content-Security-Policy). It runs on iPhone, iPad and computer, with touch, keys and a game controller. Original design only: borrow genre mechanics, never a game's characters, names, art or levels.
World: one connected world, not a list of maps. PLAY goes to Rexy's Island, a 66 x 66 block hub where Mama Rex lives. Nine gates stand in a ring 25 blocks out, one per land, in an order where neighbours match: Toy Land, Blue House, Meadow, Forest, Jungle, Beach, Desert, Mountain, Snow. Each gate is a stone arch with a spinning portal disc in the land's sky colour, a sign with the land's icon, name and a star once won, a small landmark and a stone path from the centre. The island ground takes the colour of the nearest land. Animals from every land wander the island. No eggs, candy or lava on the island; a yellow arrow points to the nearest land without a star. Walking through a gate fades to white, builds the land and starts it; Rexy steps out of the matching gate. Each land has three gates near the start: back to the island, and to the previous and next land. 🏠 in a land goes back to the island; on the island it opens the start card.
Story: Rexy, a friendly green baby T-rex, finds Mama Rex's 10 lost eggs in each land. Each egg hatches a small baby dino in the egg's colour, wearing one of 5 little hats, that follows Rexy in a line. After the 10th egg Grumbo, the sneezing volcano, wakes up grumpy (eyes open, brows down) and shows 3 glowing pink spots on his front and sides. Fire at the spots to tickle him; he giggles, then laughs so hard he sneezes a candy fountain and smiles. Then a gold light marks the nest; reaching Mama Rex and Princess Pinky wins a golden trophy, and the win card offers BACK TO THE ISLAND.
Modes: Easy (no danger: lava only bumps Rexy; a roar near a spot also tickles Grumbo), Adventure (3 hearts, lava hurts, eruptions every 12 s) and Turbo (faster everything, eruptions every 8 s). No enemies chase Rexy. +1 heart per 10 candies. Losing shows a cartoon nap: Rexy tips over, blue Z's float up, then "Oh no!" with "AGAIN! ↻" and a button to play Easy.
Lands (a 44 x 44 block grid, gentle hills, no step higher than 1 block, auto step-up): Toy Land, meadow, beach (sand slopes into a sea), desert (dunes), snow (snowfall), jungle (fog), forest (autumn) mountain (tall, snowy peaks) and Blue House (a blue block house with a garden, nine cousin dinos with play names such as Pip and Noodle who hide behind bushes, peek and giggle, are found by walking close, roaring or fire, then dance in the yard; a block dog named Azizam who follows Rexy and fetches a red ball that Rexy kicks or fires at). Every land has a pond to dive in (a white bathtub with foam and rubber ducks in Toy Land; the toy orca and shark swim there): slow sinking, JUMP swims up, bubbles, a blue tint, fish, no drowning. Every land has a car (2.3x speed) and a plane (hold JUMP to climb, let go to glide, a ceiling, a parachute when Rexy gets out high up); a GET IN / GET OUT button appears near them. Each has its own colours and box scenery, two erupting volcanoes with red ring warnings, a bouncy mushroom or two, gift boxes, a golden egg hidden high, and funny animals that do tricks (hop, spin, dance, dash, slide, flip) when Rexy comes near or roars.
Toy Land: a rainbow play-mat floor, letter blocks, balls, stacking rings and a giant rubber duck that squeaks and wobbles when bumped or roared at. 19 toys walk around as block models, with sizes relative to a toy horse (1 unit long, then x2 in the game): T-rex 1.15, little green dino 0.35, horse 1, zebra 0.8, little boar 0.4, orca 1.1, cow 0.85, stripy dino 1.6, shark 1.6, long-neck dino 1.2, buffalo 0.8, tiger 0.8, giraffe 1.1 (1.6 tall), elephant 1.1, leopard 0.6, polar bear 0.7, rat 0.55 with tail, toy soldier 0.35 tall (no weapon), tiny cow 0.35; the duck about 2.6. Generic animals only, no brand shapes or logos. Near Rexy each toy does a trick and the hint says "The toy giraffe says hi, Rexy!".
Controls: touch: a floating joystick wherever the first finger lands on open screen; a second finger taps to jump; JUMP (tap = jump, hold 0.45 s = roar, a ring fills), FIRE (fire from the mouth, aim help toward the nearest visible Grumbo spot; a fireball that reaches an animal or toy makes it do a trick within 13 blocks and 0.55 rad, arcing up to the target) and RUN (toggle). Computer: arrows or WASD, Space, F, Shift, R. Gamepad API: left stick or D-pad, X jumps (hold = roar), square or circle fires, R1/R2 runs, triangle roars, options starts; D-pad left and right pick the mode on the start card. V key or triangle gets in or out of a vehicle. Up always walks away from the camera. A 🏠 home button at the top right (also Esc or H, and the controller's Options button during play) goes back to the island, then to the start card.
Push and squish (cartoon only): walking into an animal or toy sends it flying with a boop (speed 8); running or giant sends it out of the land (speed 21 to 24) with a bonk, and it comes back after 8 s with a poof at a free spot. Falling onto one from above squishes it flat (scale y 0.16, wider) for 2.2 s, bounces Rexy (vy 11), then it pops back up with confetti. Not for swimming toys, Mama Rex, the princess, the cousins or the dog.
Blaster station (cartoon toy, not a real gun): a purple turntable with three coloured barrels in every land and on the island, a vehicle with speed 0. The joystick turns it; holding FIRE shoots paint balls every 0.11 s (speed 24, up 4.5, gravity 16). A ball that lands lowers the ground in a 1.7-block circle by 1 (2 at the centre) and the terrain mesh is rebuilt at most every 0.3 s; it pops scenery and knocks animals away. Never destroy volcanoes, the nest, Mama Rex, the princess, gates or the Blue House; a new game rebuilds the land. Haptics: navigator.vibrate where it exists, else a hidden iOS 18 switch input clicked for a tick, and gamepad vibrationActuator dual-rumble, throttled; on shots, blasts, squish, push and hurt.
Fun every minute: power-ups (star: invincible rainbow; magnet: pulls eggs and candies; giant: big stomping Rexy; feather: double jump), a hiccup puff when running, babies copy each roar, a baby pile-up on Rexy's back when he stops after a run, candies everywhere.
Sound: Web Audio only, made live (no files): a bouncy music loop scheduled 0.6 s ahead, plus step, jump, land, egg, hatch, roar, fire, pop, ouch, bonk, boom, rumble, giggle, grumble, snore, squeak, honk, gift, power, gold, win and lose. Limit to about 14 voices, add a compressor and a sound on/off button. iPhone: create and resume the AudioContext on the first tap, set navigator.audioSession.type = 'playback', loop a same-origin audio/silence.mp3 when audioSession is missing, resume on every tap, on pageshow, focus and visibilitychange. A gamepad press cannot start sound, so show "Tap the screen once to turn on the sound." Show: "No sound? Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent."
Finish: a simple start card (three mode buttons, PLAY, and grown-ups folds with land tiles that jump straight to a land and the controls) that fits at 320x568 and on a phone on its side; a win card with the trophy, time, candies, maps won, golden eggs, best time and trophies (localStorage, wrapped in try/catch), BACK TO THE ISLAND and play again. No ads, no tracking, no accounts, never the child's real name, voice or photo.
Two players (v15): a 1 player / 2 players switch on the start card. Keep per-player state (player, model, ride, power and timers) and swap it in and out so one step function runs for each player; vehicles know their driver and a passenger. Touch: the left half of the screen is player 2's floating joystick, with blue JUMP, FIRE, RUN and GET IN buttons at the bottom left mirroring player 1's green set at the bottom right, each with a 'Player 1'/'Player 2' label and a dino face; true multi-touch on one iPad. Keys: arrows, Enter, /, . and right Shift for player 2. One pad = player 2; two pads = players 1 and 2. Tag: a bump tags, the tagged dino blinks for 3 s, a star marks who is IT, a counter pill counts tags. Toy light-saber duels: cartoon clashes and sparks, no damage. Camera: aim at the midpoint, pull back with the spread and with flying height, rise over hills on the line of sight, hide trees and parked vehicles between camera and players, fade big signs near the camera.
More lands (v15): Inside the Blue House (a 3 x 3 grid of rooms, one per cousin, with bed, toy chest, toys, sign; the house's door is a portal), Race Track (an oval; drive a car into the yellow ring to start 3 laps against two computer cars named Vroomy and Zoom), Rain Land (70 s cycle: rain with puddles and frogs, a rainbow, then night with stars, planets and shooting stars, darker sky when flying high). A big jet the babies ride, more cars in colours, and 3 eggs hidden in crates or hollow trees that open with a fireball.
Old devices: CSS fallbacks for max(), env() and inset, a PointerEvent shim, try WebGL normally then low-power, show a clear message if there is no WebGL, start light on TVs (no antialias, pixel ratio 1, no shadows) and lower quality when frames are slow; TV remote colour keys; a full-screen button.
Stress test: Playwright at 320x568, 393x700, 740x360 and 1366x800 under the site CSP: no console errors or CSP violations, no sideways scroll; win every land in every mode; walk through gates both ways; hide and seek and fetch; car, plane and dive; the Grumbo fight with real fireballs; lose and retry; multi-touch joystick plus buttons; a simulated gamepad; every power-up; the golden egg; the 19 toys all spawn. Then test on a real iPhone on silent and with a real controller.
Get the code4 files, exactly as they run on this site · free under the MIT license
These four files are exactly what runs at sghadimi.com/games/trex. The page also needs three.js r128 (loaded from the site's own copy between boot.js and trex.js) and a one-second silent MP3 at audio/silence.mp3 for older iPhones. No images, fonts or voice files are used: every shape and every sound is made by the code.
trex.js (the whole game: Rexy's Island, 12 lands and their gates, two players, Rexy, eggs, babies, toys, cousins and their rooms, the dog, cars, plane, jet, races, swimming, rain and night sky, Grumbo, power-ups, tag and duels, sound, controls)1,473 lines
'use strict';
if(!window.THREE){window.__no3d=true;__bootMsg('The 3D engine did not load. Check the internet connection and reload.');}
/* ================= AUDIO (iPhone-safe, scheduled ahead, voice-limited) ================= */
let AC=null,silentEl=null,master=null,musicGain=null,sfxGain=null,muted=false,voices=0;
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();});
// Home Screen app (iOS standalone): wake sound when the app comes back, block pinch and double-tap zoom.
addEventListener('pageshow',wake);addEventListener('focus',wake);
['gesturestart','gesturechange','gestureend','dblclick'].forEach(ev=>document.addEventListener(ev,e=>e.preventDefault(),{passive:false}));
document.addEventListener('touchmove',e=>{if(e.touches.length>1)e.preventDefault();},{passive:false});
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=muted?0:0.9;
const comp=AC.createDynamicsCompressor();master.connect(comp);comp.connect(AC.destination);
musicGain=AC.createGain();musicGain.gain.value=0.22;musicGain.connect(master);
sfxGain=AC.createGain();sfxGain.gain.value=0.8;sfxGain.connect(master);
startMusic();
}
window.__audio=()=>AC;
function tone(f,t0,dur,type,vol,dest,f2){
if(!AC||voices>14)return;voices++;
const o=AC.createOscillator(),g=AC.createGain();o.type=type||'sine';o.frequency.setValueAtTime(f,t0);
if(f2)o.frequency.exponentialRampToValueAtTime(f2,t0+dur);
g.gain.setValueAtTime(0.0001,t0);g.gain.exponentialRampToValueAtTime(vol||0.3,t0+0.015);g.gain.exponentialRampToValueAtTime(0.0001,t0+dur);
o.connect(g);g.connect(dest||sfxGain);o.start(t0);o.stop(t0+dur+0.05);o.onended=()=>{voices--;};
}
let noiseBuf=null;
function noise(t0,dur,vol,freq,q){
if(!AC||voices>14)return;voices++;
if(!noiseBuf){noiseBuf=AC.createBuffer(1,AC.sampleRate,AC.sampleRate);const d=noiseBuf.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1;}
const s=AC.createBufferSource();s.buffer=noiseBuf;const f=AC.createBiquadFilter();f.type='bandpass';f.frequency.value=freq||800;f.Q.value=q||1;
const g=AC.createGain();g.gain.setValueAtTime(vol,t0);g.gain.exponentialRampToValueAtTime(0.0001,t0+dur);
s.connect(f);f.connect(g);g.connect(sfxGain);s.start(t0);s.stop(t0+dur+0.05);s.onended=()=>{voices--;};
}
const SFX={
bark(){if(!AC)return;const t=AC.currentTime;tone(540,t,0.09,'square',0.16,null,300);noise(t,0.08,0.18,900,1);tone(580,t+0.17,0.09,'square',0.14,null,320);noise(t+0.17,0.08,0.16,900,1);},
pew(){if(!AC)return;const t=AC.currentTime;tone(900,t,0.09,'square',0.06,null,300);},
peek(){if(!AC)return;const t=AC.currentTime;[880,1100,880].forEach((f,i)=>tone(f,t+i*0.09,0.08,'triangle',0.08));},
step(){if(!AC)return;const t=AC.currentTime;tone(90,t,0.12,'sine',0.25,null,50);},
jump(){if(!AC)return;const t=AC.currentTime;tone(260,t,0.25,'square',0.12,null,620);},
land(){if(!AC)return;const t=AC.currentTime;tone(120,t,0.15,'sine',0.35,null,45);noise(t,0.12,0.15,300);},
egg(){if(!AC)return;const t=AC.currentTime;[784,988,1175,1568].forEach((f,i)=>tone(f,t+i*0.07,0.25,'triangle',0.2));},
hatch(){if(!AC)return;const t=AC.currentTime;noise(t,0.08,0.4,2500,2);tone(600,t+0.08,0.18,'square',0.1,null,1200);tone(1200,t+0.22,0.15,'square',0.08,null,900);},
roar(){if(!AC)return;const t=AC.currentTime;tone(160,t,0.9,'sawtooth',0.25,null,70);tone(240,t,0.8,'sawtooth',0.12,null,110);noise(t,0.9,0.35,500,0.7);},
win(){if(!AC)return;const t=AC.currentTime;[523,659,784,1047,784,1047,1319].forEach((f,i)=>tone(f,t+i*0.13,0.35,'triangle',0.25));},
candy(n){if(!AC)return;const t=AC.currentTime;const f=660*Math.pow(2,((n%8))/12);tone(f,t,0.12,'triangle',0.18);tone(f*1.5,t+0.06,0.14,'triangle',0.12);},
boing(){if(!AC)return;const t=AC.currentTime;tone(180,t,0.45,'sine',0.35,null,720);tone(360,t,0.3,'triangle',0.1,null,1100);},
ahh(){if(!AC)return;const t=AC.currentTime;tone(300,t,0.5,'triangle',0.15,null,420);tone(320,t+0.6,0.6,'triangle',0.18,null,520);},
choo(){if(!AC)return;const t=AC.currentTime;noise(t,0.5,0.6,1800,0.8);tone(500,t,0.3,'square',0.12,null,150);},
babyRoar(i){if(!AC)return;const t=AC.currentTime;tone(520+i*45,t,0.28,'square',0.07,null,330);},
fire(){if(!AC)return;const t=AC.currentTime;noise(t,0.25,0.3,1100,0.8);tone(420,t,0.2,'sawtooth',0.1,null,120);},
pop(){if(!AC)return;const t=AC.currentTime;tone(900,t,0.14,'square',0.14,null,200);noise(t,0.1,0.3,3000,1);},
ouch(){if(!AC)return;const t=AC.currentTime;tone(700,t,0.25,'triangle',0.25,null,250);tone(520,t+0.12,0.25,'triangle',0.2,null,200);},
bonk(){if(!AC)return;const t=AC.currentTime;tone(240,t,0.15,'square',0.12,null,120);},
lose(){if(!AC)return;const t=AC.currentTime;[392,370,349,311].forEach((f,i)=>tone(f,t+i*0.32,0.4,'triangle',0.22,null,f*0.96));},
rumble(){if(!AC)return;const t=AC.currentTime;noise(t,1.8,0.3,90,0.7);tone(55,t,1.8,'sine',0.3,null,40);},
boom(){if(!AC)return;const t=AC.currentTime;noise(t,0.9,0.6,200,0.6);tone(90,t,0.8,'sine',0.5,null,30);},
grr(){if(!AC)return;const t=AC.currentTime;tone(150,t,0.3,'sawtooth',0.08,null,100);},
heart(){if(!AC)return;const t=AC.currentTime;[660,880,1320].forEach((f,i)=>tone(f,t+i*0.08,0.18,'sine',0.2));},
squeak(){if(!AC)return;const t=AC.currentTime;tone(1200,t,0.12,'sine',0.18,null,1800);tone(1500,t+0.1,0.1,'sine',0.14,null,900);},
honk(){if(!AC)return;const t=AC.currentTime;tone(320,t,0.18,'square',0.1,null,260);tone(300,t+0.2,0.18,'square',0.1,null,240);},
click(){if(!AC)return;const t=AC.currentTime;for(let i=0;i<4;i++)noise(t+i*0.08,0.04,0.3,4000,4);},
gift(){if(!AC)return;const t=AC.currentTime;noise(t,0.15,0.3,2500,1);[659,784,988,1319,1568].forEach((f,i)=>tone(f,t+0.1+i*0.07,0.22,'triangle',0.18));},
power(){if(!AC)return;const t=AC.currentTime;tone(300,t,0.6,'square',0.08,null,1200);tone(450,t+0.05,0.6,'triangle',0.1,null,1600);},
stomp(){if(!AC)return;const t=AC.currentTime;tone(70,t,0.25,'sine',0.4,null,40);noise(t,0.15,0.2,200,1);},
hic(){if(!AC)return;const t=AC.currentTime;tone(700,t,0.08,'square',0.12,null,1100);},
gold(){if(!AC)return;const t=AC.currentTime;[1047,1319,1568,2093,1568,2093,2637].forEach((f,i)=>tone(f,t+i*0.08,0.3,'sine',0.16));},
mama(i){if(!AC)return;const t=AC.currentTime;const f=900+i*30;tone(f,t,0.14,'sine',0.14,null,f*1.3);tone(f*0.8,t+0.16,0.2,'sine',0.14,null,f*0.7);},
giggle(){if(!AC)return;const t=AC.currentTime;[0,1,2,3,4,5].forEach(i=>tone(520+(i%2)*160+i*30,t+i*0.09,0.09,'triangle',0.2,null,700+i*40));},
grumble(){if(!AC)return;const t=AC.currentTime;tone(80,t,0.9,'sawtooth',0.18,null,55);tone(95,t+0.3,0.7,'sawtooth',0.12,null,60);},
snore(){if(!AC)return;const t=AC.currentTime;noise(t,0.5,0.15,500,1);tone(110,t,0.5,'sine',0.12,null,90);},
vroom(){if(!AC)return;const t=AC.currentTime;tone(70,t,0.7,'sawtooth',0.14,null,160);tone(110,t+0.1,0.5,'square',0.06,null,220);},
prop(){if(!AC)return;const t=AC.currentTime;for(let i=0;i<8;i++)noise(t+i*0.07,0.05,0.18,600,2);tone(140,t,0.6,'sawtooth',0.08,null,260);},
splash(){if(!AC)return;const t=AC.currentTime;noise(t,0.45,0.4,1200,0.7);tone(300,t,0.2,'sine',0.12,null,120);},
blub(){if(!AC)return;const t=AC.currentTime;tone(500+Math.random()*300,t,0.08,'sine',0.1,null,900);},
hello(){if(!AC)return;const t=AC.currentTime;[880,1109,1319].forEach((f,i)=>tone(f,t+i*0.09,0.2,'sine',0.18));}
};
// music: simple bouncy loop, scheduled 0.6 s ahead
let musicNext=0,musicStep=0;
const MEL=[67,0,71,74,72,0,69,67,64,0,67,69,67,0,0,0, 67,0,71,74,76,0,74,72,71,0,69,71,67,0,0,0];
const BASS=[43,43,47,47,45,45,38,38];
function midi(n){return 440*Math.pow(2,(n-69)/12);}
function startMusic(){musicNext=AC.currentTime+0.1;musicStep=0;setInterval(schedMusic,100);}
function schedMusic(){
if(!AC||AC.state!=='running')return;
const spb=0.18;
if(musicNext<AC.currentTime-0.5)musicNext=AC.currentTime+0.05;
while(musicNext<AC.currentTime+0.6){
const n=MEL[musicStep%MEL.length];if(n)tone(midi(n),musicNext,0.16,'triangle',0.18,musicGain);
if(musicStep%4===0)tone(midi(BASS[(musicStep/4|0)%BASS.length]),musicNext,0.3,'sine',0.35,musicGain);
musicNext+=spb;musicStep++;
}
}
const sndBtn=document.getElementById('snd');
sndBtn.addEventListener('click',()=>{muted=!muted;sndBtn.textContent=muted?'🔇':'🔊';if(master)master.gain.value=muted?0:0.9;});
/* ================= WORLD ================= */
const canvas=document.getElementById('c');
const renderer=(()=>{const tries=window.__tv?[{antialias:false,powerPreference:'low-power'},{antialias:false,precision:'mediump'}]:[{antialias:true},{antialias:false,powerPreference:'low-power',precision:'mediump'},{antialias:false,precision:'lowp',depth:true,stencil:false,alpha:false}];
for(const o of tries){try{const r=new THREE.WebGLRenderer(Object.assign({canvas,failIfMajorPerformanceCaveat:false},o));if(r.getContext())return r;}catch(e){}}
if(window.THREE){window.__no3d=true;__bootMsg('This browser cannot draw 3D (WebGL is off or missing), so the game cannot run here. Please play on a tablet, phone or computer. Tip: an iPad on AirPlay to the TV works, and a PS5 controller can pair with the iPad by Bluetooth.');}
throw new Error(window.THREE?'no WebGL':'3D engine did not load');})();
renderer.setPixelRatio(window.__tv?1:Math.min(devicePixelRatio||1,2));
renderer.shadowMap.enabled=!window.__tv;renderer.shadowMap.type=THREE.PCFSoftShadowMap;
const scene=new THREE.Scene();scene.background=new THREE.Color(0x9fe0ff);scene.fog=new THREE.Fog(0x9fe0ff,30,70);
const camera=new THREE.PerspectiveCamera(55,1,0.1,200);
const hemi=new THREE.HemisphereLight(0xffffff,0x6a8f4a,0.75);scene.add(hemi);
const sun=new THREE.DirectionalLight(0xfff2d6,0.85);sun.position.set(15,30,10);sun.castShadow=true;
sun.shadow.mapSize.set(1024,1024);Object.assign(sun.shadow.camera,{left:-25,right:25,top:25,bottom:-25,near:1,far:80});scene.add(sun);scene.add(sun.target);
let N=44,HALF=N/2; // the island is bigger: buildMap sets N from MP.size
function hash(x,z){const s=Math.sin(x*127.1+z*311.7)*43758.5453;return s-Math.floor(s);}
/* ================= MAPS ================= */
// Each map is its own level: ground colours, hills, water, scenery and beetle colour.
const MAPS={
meadow:{name:'Meadow',icon:'🌼',sky:0x9fe0ff,hemi:0x6a8f4a,top:[0.27,0.62,0.5],jit:0.3,side:[0.08,0.45,0.38],water:0x4fc3f7,waterY:0.6,amp:1,max:3,bug:0x7b4fd0,decor:'meadow'},
beach:{name:'Beach',icon:'🏖️',sky:0x8fdcff,hemi:0xc9b37a,top:[0.12,0.6,0.74],jit:0.04,side:[0.11,0.5,0.62],water:0x29b6f6,waterY:1.35,amp:0.7,max:3,sea:true,bug:0xff6e40,decor:'beach'},
desert:{name:'Desert',icon:'🏜️',sky:0xffe2a8,hemi:0xc9a05a,top:[0.1,0.65,0.64],jit:0.03,side:[0.08,0.55,0.52],water:0,waterY:-5,amp:1.1,max:4,dune:true,bug:0x8d6e63,decor:'desert'},
snow:{name:'Snow',icon:'❄️',sky:0xdcefff,hemi:0x9fb8d0,top:[0.58,0.35,0.93],jit:0.02,side:[0.6,0.18,0.72],water:0xa8dcff,waterY:0.6,amp:1,max:3,bug:0x1e88e5,decor:'snow',snowfall:true},
jungle:{name:'Jungle',icon:'🌴',sky:0xa6e8c8,hemi:0x3e6b3a,top:[0.33,0.58,0.32],jit:0.05,side:[0.07,0.4,0.28],water:0x26a69a,waterY:0.6,amp:1.1,max:3,bug:0xd81b60,decor:'jungle',fogNear:22,fogFar:60},
forest:{name:'Forest',icon:'🍂',sky:0xffdcb8,hemi:0x7a6a3a,top:[0.22,0.42,0.4],jit:0.05,side:[0.07,0.42,0.33],water:0x4fc3f7,waterY:0.6,amp:1,max:3,bug:0x5d4037,decor:'forest'},
toys:{name:'Toy Land',icon:'🧸',sky:0xbfe6ff,hemi:0x9a8fb0,top:[0.6,0.55,0.64],jit:2.2,side:[0.62,0.3,0.6],water:0x7fd3ff,waterY:0.6,amp:0.7,max:2,bug:0x7b4fd0,decor:'toys'},
hub:{name:"Rexy's Island",icon:'🏝️',sky:0x9fe0ff,hemi:0x6a8f4a,top:[0.3,0.55,0.55],jit:0.2,side:[0.08,0.45,0.38],water:0x4fc3f7,waterY:0.6,amp:0.6,max:2,bug:0,decor:'hub',hub:true,size:66,fogNear:42,fogFar:100},
house:{name:'Blue House',icon:'🏡',sky:0xa9e4ff,hemi:0x6a8f4a,top:[0.3,0.6,0.52],jit:0.25,side:[0.08,0.45,0.38],water:0x4fc3f7,waterY:0.6,amp:0.8,max:3,bug:0x7b4fd0,decor:'house'},
inside:{name:'Inside the Blue House',icon:'🛏️',sky:0xd8efff,hemi:0x9a8fb0,top:[0.1,0.45,0.62],jit:0.02,side:[0.1,0.3,0.85],water:0x7fd3ff,waterY:-5,amp:0,max:4,bug:0,decor:'inside',inside:true,noSmooth:true,fogNear:45,fogFar:100,
vehs:[['car',-6,4],['car',-15.5,-4,0x2f80ed],['plane',6,1],['blaster',-15.5,4]],pond:[15.5,15.5,3.4],mush:[[-15.5,8.5],[15.5,-5],[-5,15.5],[5,-15.5],[15.5,8]],gates:[[-5,-5.5],[0,-6.2],[5,-5.5]]},
rain:{name:'Rain Land',icon:'🌧️',sky:0x9fb4c8,hemi:0x55705f,top:[0.36,0.5,0.42],jit:0.05,side:[0.08,0.38,0.32],water:0x5c8fd6,waterY:0.6,amp:1.1,max:3,bug:0,decor:'rain',rain:true,fogNear:26,fogFar:72},
race:{name:'Race Track',icon:'🏁',sky:0xa8e0ff,hemi:0x6a8f4a,top:[0.28,0.6,0.5],jit:0.2,side:[0.08,0.45,0.38],water:0x4fc3f7,waterY:0.6,amp:0.6,max:2,bug:0,decor:'race',race:true,
vehs:[['car',-3,-12.2,0xff3d3d,Math.PI/2],['car',-3,-14.4,0x2f80ed,Math.PI/2],['car',-6.5,-12.2,0xffd24d,Math.PI/2],['car',-6.5,-14.4,0x5ccf6b,Math.PI/2],['plane',-5,-0.5],['blaster',10,6],['jet',8.5,-1.5]],
pond:[-9,3.5,3],mush:[[-3,6],[-11,-5],[10,-6],[12,2.5]],gates:[[-5,-5.5],[0,-6.2],[5,-5.5]]},
mountain:{name:'Mountain',icon:'⛰️',sky:0xb5d8ff,hemi:0x667788,top:[0.27,0.25,0.48],jit:0.04,side:[0.6,0.06,0.48],water:0x4fc3f7,waterY:0.6,amp:2.7,max:7,lift:1,snowcap:4,bug:0x455a64,decor:'mountain'}
};
const MAP_ORDER=['toys','house','inside','race','meadow','forest','jungle','beach','desert','mountain','snow','rain']; // the order of the gates round the island: each land sits next to a land like it
let GATES=[],gateCd=0,traveling=false;
function gatesFor(id){const NL=MAP_ORDER.length;if(MAPS[id].hub)return MAP_ORDER.map((to,k)=>{const a=k/NL*Math.PI*2,R=25;const x=Math.sin(a)*R,z=Math.cos(a)*R;return {to,x,z,ry:Math.atan2(-x,-z)};});
const k=MAP_ORDER.indexOf(id),n=MAP_ORDER.length,P=MAPS[id].gates||[[-11.5,-9.5],[-6.5,-11],[-1.5,-10.5]];
const out=[{to:MAP_ORDER[(k+n-1)%n],x:P[0][0],z:P[0][1],ry:0},{to:'hub',x:P[1][0],z:P[1][1],ry:0},{to:MAP_ORDER[(k+1)%n],x:P[2][0],z:P[2][1],ry:0}];
// the Blue House door is a portal: walk in to go inside the house
if(id==='house'){const d=Math.hypot(YARD.x-HOUSE.x,YARD.z-HOUSE.z),ux=(YARD.x-HOUSE.x)/d,uz=(YARD.z-HOUSE.z)/d;out.unshift({to:'inside',x:HOUSE.x+ux*3.5,z:HOUSE.z+uz*3.5,ry:Math.atan2(ux,uz),door:true});out.splice(out.findIndex((G,i)=>i>0&&G.to==='inside'),1);}
return out;}
function sectorOf(x,z){const n=MAP_ORDER.length,a=(Math.atan2(x,z)+Math.PI*2)%(Math.PI*2);return Math.round(a/(Math.PI*2/n))%n;}
let mapId='hub';
let MP=MAPS[mapId],builtMap=null,world=null,water=null,volcano=new THREE.Group();
const NEST={x:3.5,z:6.5};let VSPOTS=[[-16,-16],[16.5,-15.5],[-15.5,16.5]];
let H=[];
function heightCell(ix,iz){
const x=ix-HALF+0.5,z=iz-HALF+0.5,d=Math.hypot(x,z);
let n=Math.sin(ix*0.25)*0.9+Math.cos(iz*0.21)*0.9+Math.sin((ix+iz)*0.13)*0.7;
if(MP.dune)n+=Math.sin(ix*0.45+iz*0.12)*0.8;
let h=Math.floor(1.2+n*MP.amp+(MP.lift||0));
if(MP.sea)h=Math.min(h,Math.floor((12-x)/2.5)); // beach: the sand slopes into the sea on one side
if(MP.inside){let w=insideWall(x,z)?4:1;if(d<3||Math.hypot(x-NEST.x,z-NEST.z)<2.6||GATES.some(g=>Math.hypot(x-g.x,z-g.z)<2.4))w=1;return w;}
if(MP.race){const e=trackE(x,z);if(e>0.8&&e<1.2)h=1;}
if(d<5||Math.hypot(x-NEST.x,z-NEST.z)<4.5)h=1; // flat start and flat nest
if(Math.hypot(x-POND.x,z-POND.z)<POND.r+2)h=0;
if(MP.decor==='house'&&Math.hypot(x-HOUSE.x,z-HOUSE.z)<7.5)h=1;
if(GATES.some(g=>Math.hypot(x-g.x,z-g.z)<3))h=1; // flat ground at each gate // flat garden round the blue house // flat ground round the pond
return Math.max(0,Math.min(MP.max,h));
}
const POND={x:8.5,z:-10.5,r:4.2,floor:-2,surf:0.85};
// Inside the Blue House: 9 rooms in a 3 x 3 grid with doors between them, one room for each cousin
function insideWall(x,z){const ax=Math.abs(x),az=Math.abs(z);if(ax>20.2||az>20.2)return true;const door=c=>[-15.5,0,15.5].some(d=>Math.abs(c-d)<1.6);
if(Math.abs(ax-10.5)<0.6&&!door(z))return true;if(Math.abs(az-10.5)<0.6&&!door(x))return true;return false;}
function nearWall(x,z,m){if(!MP.inside)return false;m=m||1.3;for(const a of[-m,0,m])for(const b of[-m,0,m])if(insideWall(x+a,z+b))return true;return false;}
function roomOf(x,z){const c=v=>v<-10.5?0:v>10.5?2:1;return c(z)*3+c(x);}
const ROOMC=[-15.5,0,15.5];
// Race Track: an oval road round the middle of the land
const TRA=17,TRB=13;function trackE(x,z){return Math.hypot(x/TRA,z/TRB);}
const HOUSE={x:-9,z:9},YARD={x:-5,z:5};
function inPondCell(i,j){return Math.hypot(i-HALF+0.5-POND.x,j-HALF+0.5-POND.z)<POND.r;}
function inPond(x,z){return inPondCell(Math.floor(x+HALF),Math.floor(z+HALF));}
function groundAt(x,z){const i=Math.floor(x+HALF),j=Math.floor(z+HALF);if(i<0||j<0||i>=N||j>=N||!H[i])return 1;if(inPondCell(i,j))return POND.floor;return H[i][j]+1;}
const trees=[],mush=[],VOLC=[],flakes=[];
const GEO={},MATS={};const WHITE=new THREE.Color(0xffffff);
function geo(w,h,d){const k=w+','+h+','+d;return GEO[k]||(GEO[k]=new THREE.BoxGeometry(w,h,d));}
function mat(c,em){const k=c+'/'+(em||0);return MATS[k]||(MATS[k]=new THREE.MeshLambertMaterial({color:c,emissive:em||0}));}
function bx(g,w,h,d,c,x,y,z,ry,rx,rz,em){const m=new THREE.Mesh(geo(w,h,d),mat(c,em));m.position.set(x,y,z);if(ry)m.rotation.y=ry;if(rx)m.rotation.x=rx;if(rz)m.rotation.z=rz;m.castShadow=true;g.add(m);return m;}
function addObs(g,x,z,r){g.position.set(x,groundAt(x,z),z);world.add(g);trees.push({x,z,r,g,shake:0});}
function addDeco(g,x,z){g.position.set(x,groundAt(x,z),z);world.add(g);}
function spots(n,minD,maxD,seed,clear){const out=[];for(let t=0;t<n*6&&out.length<n;t++){const a=hash(t,seed)*Math.PI*2,d=minD+hash(t,seed+1)*(maxD-minD);
const x=Math.floor(Math.cos(a)*d)+0.5,z=Math.floor(Math.sin(a)*d)+0.5;if(Math.hypot(x-POND.x,z-POND.z)<POND.r+2)continue;if(GATES.some(g=>Math.hypot(g.x-x,g.z-z)<3.6))continue;if(MP.decor==='house'&&(Math.hypot(x-HOUSE.x,z-HOUSE.z)<6.5||Math.hypot(x-YARD.x,z-YARD.z)<3.5))continue;if((MP.vehs||VEHS).some(v=>Math.hypot(v[1]-x,v[2]-z)<(v[0]==='jet'?5:3)))continue;if(nearWall(x,z))continue;if(MP.race&&Math.abs(trackE(x,z)-1)<0.26)continue;
if(Math.abs(x)>HALF-2||Math.abs(z)>HALF-2)continue;if(Math.hypot(x-NEST.x,z-NEST.z)<5.5||Math.hypot(x,z)<5)continue;
if(VSPOTS.some(([vx,vz])=>Math.hypot(vx-x,vz-z)<5.5))continue;if(trees.some(o=>Math.hypot(o.x-x,o.z-z)<o.r+(clear||1.4)))continue;out.push([x,z]);}return out;}
function sprinkle(n,colors,size,seed){n=Math.round(n*0.6);const im=new THREE.InstancedMesh(geo(size*1.3,0.05,size*1.3),new THREE.MeshLambertMaterial({color:0xffffff}),n);const m4=new THREE.Matrix4(),c=new THREE.Color();
for(let f=0;f<n;f++){const x=(hash(f,seed)-0.5)*(N-4),z=(hash(f,seed+2)-0.5)*(N-4);m4.makeTranslation(x,groundAt(x,z)+0.03,z);im.setMatrixAt(f,m4);c.setHex(colors[f%colors.length]);im.setColorAt(f,c);}world.add(im);}
// ---- scenery pieces (original block art) ----
function giantFlower(c){const g=new THREE.Group();bx(g,0.25,2.4,0.25,0x43a047,0,1.2,0);bx(g,0.9,0.12,0.4,0x66bb6a,0.4,0.8,0,0,0,0.5);
for(let k=0;k<6;k++){const a=k/6*Math.PI*2;bx(g,0.6,0.6,0.18,c,Math.cos(a)*0.6,2.6+Math.sin(a)*0.6,0);}bx(g,0.6,0.6,0.3,0xffe14d,0,2.6,0.02);return g;}
function bush(c){const g=new THREE.Group();bx(g,1.6,0.9,1.4,c,0,0.45,0);bx(g,1.0,0.6,1.0,c,0.3,1.0,0.1);bx(g,0.25,0.25,0.25,0xff5c8a,0.5,0.95,0.6);return g;}
function palm(){const g=new THREE.Group();let x=0;for(let i=0;i<6;i++){x+=0.13;bx(g,0.45,0.7,0.45,i%2?0xa1887f:0x8d6e63,x,0.35+i*0.66,0);}
const top=new THREE.Group();top.position.set(x,4.2,0);g.add(top);
for(let k=0;k<7;k++){const p=new THREE.Group();p.rotation.y=k/7*Math.PI*2;top.add(p);bx(p,2.3,0.12,0.6,k%2?0x43a047:0x2e7d32,1.05,-0.3,0,0,0,-0.4);}
for(let k=0;k<3;k++)bx(g,0.3,0.3,0.3,0x6d4c41,x+Math.cos(k*2)*0.3,3.95,Math.sin(k*2)*0.3);return g;}
function umbrella(c){const g=new THREE.Group();bx(g,0.12,2.4,0.12,0xffffff,0,1.2,0);const cone=new THREE.Mesh(new THREE.ConeGeometry(1.5,0.6,8),mat(c));cone.position.y=2.5;g.add(cone);bx(g,1.8,0.1,0.9,0xffffff,1.2,0.05,0.4);return g;}
function sandCastle(){const g=new THREE.Group(),c=0xf1d39a;bx(g,1.8,0.8,1.8,c,0,0.4,0);for(const[a,b]of[[-0.8,-0.8],[0.8,-0.8],[-0.8,0.8],[0.8,0.8]])bx(g,0.5,1.4,0.5,c,a,0.7,b);bx(g,0.6,0.9,0.6,c,0,1.2,0);bx(g,0.05,0.6,0.05,0x5d4037,0,1.9,0);bx(g,0.4,0.25,0.04,0xff5252,0.2,2.05,0);return g;}
function cactus(){const g=new THREE.Group(),c=0x2e9d4a;bx(g,0.75,2.8,0.75,c,0,1.4,0);bx(g,0.6,0.45,0.45,c,0.6,1.3,0);bx(g,0.45,1.0,0.45,c,0.85,1.75,0);bx(g,0.6,0.45,0.45,c,-0.6,1.8,0);bx(g,0.45,0.8,0.45,c,-0.85,2.1,0);bx(g,0.35,0.25,0.35,0xff80ab,0,2.95,0);return g;}
function rock(c){const g=new THREE.Group();bx(g,1.5,0.9,1.3,c,0,0.45,0,0.3);bx(g,0.9,0.7,0.9,c,0.3,1.0,-0.1,0.8);return g;}
function stepPyramid(){const g=new THREE.Group();for(let l=0;l<4;l++){const w=4-l*0.95;bx(g,w,0.8,w,l%2?0xe6c27a:0xd9b263,0,0.4+l*0.8,0);}return g;}
function pine(snowy,s){s=s||1;const g=new THREE.Group();bx(g,0.5*s,1.0*s,0.5*s,0x6d4c41,0,0.5*s,0);
for(let l=0;l<3;l++){const w=(2.4-l*0.7)*s;bx(g,w,0.75*s,w,0x2e7d32,0,(1.3+l*0.8)*s,0);if(snowy)bx(g,w*0.9,0.16*s,w*0.9,0xffffff,0,(1.72+l*0.8)*s,0);}
bx(g,0.4*s,0.5*s,0.4*s,snowy?0xffffff:0x2e7d32,0,3.75*s,0);return g;}
function snowman(){const g=new THREE.Group(),w=0xffffff;bx(g,1.2,1.0,1.2,w,0,0.5,0);bx(g,0.9,0.8,0.9,w,0,1.4,0);bx(g,0.65,0.6,0.65,w,0,2.1,0);bx(g,0.95,0.18,0.95,0xe53935,0,1.86,0);
bx(g,0.12,0.12,0.5,0xff9800,0,2.1,0.5);bx(g,0.1,0.1,0.05,0x111111,-0.15,2.25,0.33);bx(g,0.1,0.1,0.05,0x111111,0.15,2.25,0.33);bx(g,0.7,0.12,0.7,0x222222,0,2.45,0);bx(g,0.45,0.35,0.45,0x222222,0,2.65,0);return g;}
function iceCrystal(){const g=new THREE.Group();bx(g,0.5,2.0,0.5,0x9be7ff,0,1.0,0,0.4,0,0.15,0x1a4a66);bx(g,0.4,1.4,0.4,0xb3f0ff,0.4,0.7,0.2,0.2,0,-0.4,0x1a4a66);return g;}
function bigLeaves(){const g=new THREE.Group();for(let k=0;k<5;k++){const p=new THREE.Group();p.rotation.y=k/5*Math.PI*2+0.3;g.add(p);bx(p,1.0,0.1,2.6,k%2?0x2e7d32:0x43a047,0,1.0,1.1,0,-0.55);}bx(g,0.3,1.2,0.3,0x33691e,0,0.6,0);return g;}
function bamboo(){const g=new THREE.Group();for(let k=0;k<4;k++){const a=k*1.7,x=Math.cos(a)*0.4,z=Math.sin(a)*0.4,h=3.5+k*0.4;bx(g,0.26,h,0.26,0x9ccc65,x,h/2,z);for(let j=1;j<4;j++)bx(g,0.3,0.08,0.3,0x689f38,x,j*h/4,z);bx(g,0.5,0.06,0.2,0x7cb342,x+0.25,h-0.3,z,0,0,0.4);}return g;}
function bigFlowerFlat(){const g=new THREE.Group();for(let k=0;k<5;k++){const a=k/5*Math.PI*2;bx(g,0.8,0.15,0.8,0xe53935,Math.cos(a)*0.6,0.1,Math.sin(a)*0.6,a);}bx(g,0.6,0.25,0.6,0xffe082,0,0.15,0);return g;}
function autumnTree(c){const g=new THREE.Group();bx(g,0.6,2.2,0.6,0x6d4c41,0,1.1,0);bx(g,2.4,1.4,2.4,c,0,2.9,0);bx(g,3.0,0.9,1.6,c,0,2.85,0);bx(g,1.6,0.9,3.0,c,0,2.85,0);bx(g,1.6,0.7,1.6,c,0,3.9,0);return g;}
function log(){const g=new THREE.Group();bx(g,2.6,0.6,0.6,0x795548,0,0.3,0);bx(g,0.05,0.5,0.5,0xd7b98a,1.31,0.3,0);bx(g,0.4,0.3,0.4,0xff7043,0.6,0.75,0);return g;}
function abcBlocks(i){const g=new THREE.Group(),C=[0xff5c5c,0x4fa3ff,0xffd24d,0x5ccf6b,0xb57bff];const n=2+i%2;
for(let k=0;k<n;k++){const c=C[(i+k)%5];const b=bx(g,0.9,0.9,0.9,c,(k%2)*0.2,0.45+k*0.9,0,k*0.4);bx(g,0.5,0.5,0.92,0xffffff,(k%2)*0.2,0.45+k*0.9,0,k*0.4);}return g;}
function ball(c){const g=new THREE.Group();const m=new THREE.Mesh(new THREE.SphereGeometry(0.7,14,10),mat(c));m.position.y=0.7;m.castShadow=true;g.add(m);const s=new THREE.Mesh(new THREE.TorusGeometry(0.7,0.08,6,20),mat(0xffffff));s.position.y=0.7;g.add(s);return g;}
function stackRings(){const g=new THREE.Group(),C=[0xb39ddb,0x90caf9,0xa5d6a7,0xfff59d,0xffcc80,0xf48fb1];
for(let k=0;k<6;k++){const w=1.6-k*0.18;const m=new THREE.Mesh(new THREE.CylinderGeometry(w/2,w/2,0.36,16),mat(C[k]));m.position.y=0.18+k*0.36;m.castShadow=true;g.add(m);}return g;}
let toyDuck=null,DECOR_HUB=null;
let pondFx=[],fish=[],bubbles=[];
function buildPond(){const P=POND,toy=MP.decor==='toys'||!!MP.inside,depth=P.surf-P.floor;pondFx=[];fish=[];if(!P.r)return;
const wall=new THREE.Mesh(new THREE.CylinderGeometry(P.r,P.r,1-P.floor,28,1,true),new THREE.MeshLambertMaterial({color:toy?0xffffff:0x8d7b68,side:THREE.DoubleSide}));wall.position.set(P.x,(1+P.floor)/2,P.z);world.add(wall);
const fl=new THREE.Mesh(new THREE.CylinderGeometry(P.r,P.r,0.2,28),new THREE.MeshLambertMaterial({color:toy?0xbfefff:0xe6d3a3}));fl.position.set(P.x,P.floor-0.1,P.z);world.add(fl);
const w=new THREE.Mesh(new THREE.CylinderGeometry(P.r-0.02,P.r-0.02,depth,28),new THREE.MeshLambertMaterial({color:toy?0x7fd8ff:0x3fa9f5,transparent:true,opacity:0.42,depthWrite:false}));w.position.set(P.x,P.floor+depth/2,P.z);world.add(w);
const top=new THREE.Mesh(new THREE.CircleGeometry(P.r-0.02,28),new THREE.MeshLambertMaterial({color:toy?0xaee9ff:0x6cc4ff,transparent:true,opacity:0.5,depthWrite:false,side:THREE.DoubleSide}));top.rotation.x=-Math.PI/2;top.position.set(P.x,P.surf,P.z);world.add(top);pondFx.push(top);
if(toy){const rim=new THREE.Mesh(new THREE.TorusGeometry(P.r+0.15,0.32,8,32),mat(0xffffff));rim.rotation.x=Math.PI/2;rim.position.set(P.x,1.1,P.z);world.add(rim);
for(let k=0;k<4;k++){const f=new THREE.Mesh(new THREE.SphereGeometry(0.35+0.2*(k%2),8,6),mat(0xffffff));const a=k*1.6;f.position.set(P.x+Math.cos(a)*(P.r-0.8),P.surf+0.1,P.z+Math.sin(a)*(P.r-0.8));world.add(f);}
for(let k=0;k<3;k++){const d=new THREE.Group();bx(d,0.5,0.35,0.6,0xffe633,0,0.15,0);bx(d,0.35,0.35,0.35,0xffe633,0,0.45,0.18);bx(d,0.2,0.1,0.2,0xff8a1a,0,0.42,0.42);world.add(d);fish.push({g:d,a:k*2.1,r:P.r-1.6,y:P.surf-0.05,sp:0.35,duck:true});}}
else{for(let k=0;k<5;k++){const sw=new THREE.Group();const h=1.2+k%3*0.5;bx(sw,0.15,h,0.15,0x2e9d4a,0,h/2,0);bx(sw,0.35,0.1,0.12,0x43c060,0.12,h*0.6,0);const a=k*1.25;sw.position.set(P.x+Math.cos(a)*(P.r-0.7),P.floor,P.z+Math.sin(a)*(P.r-0.7));world.add(sw);}}
const FC=[0xff8a1a,0xffd24d,0xff5c8a,0x40c4ff];for(let k=0;k<4;k++){const g=new THREE.Group();bx(g,0.25,0.3,0.5,FC[k],0,0,0);bx(g,0.05,0.3,0.25,FC[k],0,0,-0.35);bx(g,0.06,0.06,0.02,0x111111,0.1,0.05,0.2);world.add(g);fish.push({g,a:k*1.6,r:1.2+k*0.6,y:P.floor+0.8+k*0.35,sp:0.6+k*0.15});}}
function bubble(x,y,z,n){for(let i=0;i<n;i++){if(bubbles.length>60)break;const m=new THREE.Mesh(bubGeo,bubMat);m.position.set(x+(Math.random()-0.5)*0.4,y+(Math.random()-0.5)*0.3,z+(Math.random()-0.5)*0.4);const s=0.6+Math.random()*0.9;m.scale.setScalar(s);scene.add(m);bubbles.push({m,ph:Math.random()*6,sp:1.2+Math.random()*1.2});}}
const bubGeo=new THREE.SphereGeometry(0.12,8,6),bubMat=new THREE.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:0.7});
/* ---- vehicles: walk up, tap GET IN, tap GET OUT ---- */
const VEHS=[['car',-4,-3.5],['car',-1,-6.5,0x2f80ed],['plane',4.5,-4],['blaster',-9.5,1.5],['jet',11,2]];let vehicles=[],ride=null,rideHint=false;
function carModel(c){c=c||0xff3d3d;const g=new THREE.Group();bx(g,1.9,0.6,3.0,c,0,0.75,0);bx(g,1.9,0.5,0.9,c,0,1.25,-1.0);bx(g,1.7,0.5,0.08,0x9be7ff,0,1.3,0.6,0,-0.4);
for(const[a,b]of[[-1,1],[1,1],[-1,-1],[1,-1]])bx(g,0.35,0.7,0.7,0x222222,a*0.98,0.35,b*0.95);bx(g,0.35,0.2,0.08,0xfff59d,-0.6,0.8,1.52);bx(g,0.35,0.2,0.08,0xfff59d,0.6,0.8,1.52);bx(g,0.5,0.1,0.5,0x333333,0,1.1,0.25);return g;}
function planeModel(){const g=new THREE.Group(),Y=0xffc61a;bx(g,1.1,1.0,3.6,Y,0,1.3,0);bx(g,0.8,0.8,0.5,Y,0,1.3,2.0);bx(g,6.2,0.14,1.1,0x40a4ff,0,1.35,0.3);bx(g,2.4,0.12,0.7,0x40a4ff,0,1.5,-1.6);bx(g,0.12,0.9,0.8,0x40a4ff,0,2.0,-1.6);
for(const a of[-1,1]){bx(g,0.12,0.6,0.12,0x555555,a*0.6,0.5,0.6);bx(g,0.25,0.4,0.4,0x222222,a*0.6,0.2,0.6);}bx(g,0.12,0.3,0.12,0x555555,0,0.6,-1.5);
const pr=new THREE.Group();pr.position.set(0,1.3,2.3);g.add(pr);bx(pr,0.2,2.0,0.08,0x5d4037,0,0,0);bx(pr,0.25,0.25,0.25,0xff3d3d,0,0,0.05);g.userData.prop=pr;return g;}
// the big jet: an original block airliner. The pilot sits on top, a friend can hop on, and the babies ride in a row behind.
function jetModel(){const g=new THREE.Group(),W=0xffffff,B=0x2f80ed,R=0xff5c8a,GL=0x9be7ff;
bx(g,1.6,1.4,7,W,0,1.75,0);bx(g,1.64,0.3,7.04,B,0,1.3,0);bx(g,1.3,1.1,0.9,W,0,1.7,3.9);bx(g,0.9,0.7,0.4,B,0,1.6,4.4);bx(g,1.1,0.5,0.5,GL,0,2.2,3.3);
for(let k=0;k<6;k++)for(const sd of[-1,1])bx(g,0.06,0.32,0.36,GL,sd*0.82,1.95,2.1-k*0.9);
bx(g,9.6,0.18,1.7,B,0,1.5,0.3);for(const sd of[-1,1]){bx(g,0.22,0.5,1.0,R,sd*4.75,1.75,0.1);bx(g,0.7,0.7,1.5,0xcfd8dc,sd*2.5,1.1,0.7);bx(g,0.45,0.45,0.1,0x37474f,sd*2.5,1.1,1.46);}
bx(g,3.4,0.15,1.1,B,0,2.1,-3.1);bx(g,0.16,1.7,1.3,R,0,3.1,-3.0);bx(g,0.18,0.3,0.3,0xffffff,0,3.3,-2.9);
for(const[a,b]of[[-0.7,1.8],[0.7,1.8],[0,-2.6]]){bx(g,0.12,0.6,0.12,0x555555,a,0.65,b);bx(g,0.3,0.4,0.4,0x222222,a,0.2,b);}
const props=[];for(const sd of[-1,1]){const pr=new THREE.Group();pr.position.set(sd*2.5,1.1,1.55);g.add(pr);bx(pr,0.16,1.5,0.06,0x5d4037,0,0,0);bx(pr,0.2,0.2,0.2,R,0,0,0.05);props.push(pr);}g.userData.props=props;return g;}
function buildVehicles(){vehicles=(MP.hub?[['car',-6.5,1.5],['car',-6.5,-2,0x2f80ed],['car',-4,-5,0xffd24d],['plane',7.5,0.5],['blaster',0,-7.5],['jet',9,-9]]:MP.vehs||VEHS).map(([kind,x,z,col,f0])=>{const g=kind==='car'?carModel(col):kind==='blaster'?blasterModel():kind==='jet'?jetModel():planeModel();world.add(g);const v={kind,g,hx:x,hz:z,x,z,y:groundAt(x,z),face:f0||0,hface:f0||0,vy:0};g.position.set(x,v.y,z);g.rotation.y=v.face;return v;});ride=null;}
function resetVehicles(){ride=null;vehicles.forEach(v=>{v.driver=null;v.passenger=null;v.x=v.hx;v.z=v.hz;v.y=groundAt(v.x,v.z);v.face=v.hface||0;v.vy=0;v.g.position.set(v.x,v.y,v.z);v.g.rotation.set(0,0,0);});rideBtn.hidden=true;}
function nearVeh(){let best=null,bd=3.0;for(const v of vehicles){if(v.driver&&v.driver!==player&&!(v.kind==='jet'&&!v.passenger))continue;const d=Math.hypot(v.x-player.x,v.z-player.z)-(v.kind==='jet'?1.4:0);if(d<bd&&Math.abs(v.y-player.y)<2.5){bd=d;best=v;}}return best;}
function toggleRide(){if(!playing)return;if(ride){const v=ride;ride=null;
if(player.pass){player.pass=false;if(v.passenger===player)v.passenger=null;}
else{v.driver=null;if(v.passenger){v.driver=v.passenger;v.driver.pass=false;v.passenger=null;}else{v.x=player.x;v.z=player.z;v.y=player.y;v.face=player.face;v.vy=0;}}
const a=player.face+Math.PI/2,o=v.kind==='jet'?3.4:2.2;let [nx,nz]=collide(player.x+Math.sin(a)*o,player.z+Math.cos(a)*o,0.5);player.x=nx;player.z=nz;player.vy=2;player.onGround=false;if((v.kind==='plane'||v.kind==='jet')&&player.y>groundAt(nx,nz)+2){chute=true;say('Wheee! 🪂',1500);}SFX.jump();return;}
const v=nearVeh();if(!v)return;
if(v.driver&&v.driver!==player){v.passenger=player;player.pass=true;ride=v;chute=false;SFX.prop();say('🛫 You hopped on the jet! FIRE works up here too.',2800);return;}
v.driver=player;ride=v;player.x=v.x;player.z=v.z;player.y=Math.max(player.y,v.y);player.face=v.face;chute=false;
if(v.kind==='car'){SFX.vroom();say('🚗 Vroom! Drive with the joystick. JUMP = hop.',2500);}else if(v.kind==='blaster'){SFX.power();haptic(60,0.8);say('💥 Blaster! Turn with the joystick. Hold FIRE to blast the land!',3000);}
else if(v.kind==='jet'){SFX.prop();SFX.vroom();say('🛫 The big jet! Hold JUMP to fly up high. The babies ride with you!'+(twoP?' Player 2 can hop on too.':''),3500);}else{SFX.prop();say('✈️ Hold JUMP to fly up. Let go to glide down.',3000);}}
/* ---- blaster station: a toy blaster on a turntable. Rexy sits in it, turns with the joystick and holds FIRE: bouncy paint balls knock holes in the land and pop trees and scenery ---- */
function blasterModel(){const g=new THREE.Group();const base=new THREE.Mesh(new THREE.CylinderGeometry(1.5,1.7,0.5,16),mat(0x7e57c2));base.position.y=0.25;base.castShadow=true;g.add(base);
const ring=new THREE.Mesh(new THREE.TorusGeometry(1.5,0.12,6,20),mat(0xffd24d));ring.rotation.x=Math.PI/2;ring.position.y=0.5;g.add(ring);
bx(g,1.2,0.5,1.0,0xff5c8a,0,0.75,-0.4);bx(g,0.25,0.9,0.25,0x555555,0,0.9,0.4);
const C=[0x40c4ff,0xffd24d,0x5ccf6b];for(let k=0;k<3;k++){const t=new THREE.Mesh(new THREE.CylinderGeometry(0.22,0.28,1.8,10),mat(C[k]));t.rotation.x=Math.PI/2;t.position.set((k-1)*0.45,1.45,1.1);t.castShadow=true;g.add(t);
const tip=new THREE.Mesh(new THREE.TorusGeometry(0.24,0.07,6,12),mat(0xffffff));tip.position.set((k-1)*0.45,1.45,2.0);g.add(tip);}
bx(g,1.6,0.6,0.7,0xff9800,0,1.45,0.4);bx(g,0.3,0.3,0.3,0xff3d3d,0,1.85,0.5);return g;}
let blasts=[],blastN=0;const blastGeo=new THREE.SphereGeometry(0.28,10,8);
const BLC=[0xff5c8a,0x40c4ff,0xffd24d,0x5ccf6b,0xb57bff,0xff9a3d].map(c=>new THREE.MeshBasicMaterial({color:c}));
function blast(){if(!ride||ride.kind!=='blaster')return;fireCd=0.11;blastN++;const k=(blastN%3)-1,f=player.face,cx=Math.cos(f),cz=-Math.sin(f);
const x=player.x+Math.sin(f)*2.2+cx*k*0.45,z=player.z+Math.cos(f)*2.2+cz*k*0.45,y=player.y+1.45;const m=new THREE.Mesh(blastGeo,BLC[blastN%BLC.length]);m.position.set(x,y,z);scene.add(m);
blasts.push({m,x,y,z,vx:Math.sin(f)*24,vz:Math.cos(f)*24,vy:4.5,life:2.5});SFX.pew();haptic(15,0.25);}
function crater(x,z){const R=1.7;let hit=false;for(let i=Math.floor(x+HALF-R);i<=Math.ceil(x+HALF+R);i++)for(let j=Math.floor(z+HALF-R);j<=Math.ceil(z+HALF+R);j++){if(i<1||j<1||i>=N-1||j>=N-1||inPondCell(i,j))continue;
const cx=i-HALF+0.5,cz=j-HALF+0.5,d=Math.hypot(cx-x,cz-z);if(d>R)continue;if(Math.hypot(cx-NEST.x,cz-NEST.z)<4.2||GATES.some(G=>Math.hypot(cx-G.x,cz-G.z)<2.6)||Math.hypot(cx-player.x,cz-player.z)<1.6)continue;
const dn=d<0.9?2:1;if(H[i][j]>0){H[i][j]=Math.max(0,H[i][j]-dn);hit=true;}}
if(hit){mapDamaged=true;for(const m of mush){if(m.g.visible&&Math.hypot(m.x-x,m.z-z)<2){m.g.visible=false;m.x=9999;}}}}
function popThing(t){const i=trees.indexOf(t);if(i<0||t.keep)return;trees.splice(i,1);const p=t.g.position;burst(p.x,p.y+1.5,p.z,0x5ccf6b,14,6);burst(p.x,p.y+1,p.z,0xffe14d,10,5);t.g.visible=false;mapDamaged=true;SFX.pop();}
function updateBlasts(dt){blkT-=dt;if(mapDamaged&&blocksMesh&&blkT<=0&&blocksDirty){blocksDirty=false;blkT=0.3;buildBlocks();}
for(let n=blasts.length-1;n>=0;n--){const b=blasts[n];b.life-=dt;b.vy-=16*dt;b.x+=b.vx*dt;b.z+=b.vz*dt;b.y+=b.vy*dt;b.m.position.set(b.x,b.y,b.z);let hit=b.life<=0||Math.abs(b.x)>HALF||Math.abs(b.z)>HALF;
if(!hit)for(const t of trees){if(Math.hypot(t.x-b.x,t.z-b.z)<t.r+0.3&&b.y<groundAt(t.x,t.z)+5){if(t.egg)openBox(t);else if(!t.keep)popThing(t);else t.shake=0.6;hit=true;break;}}
if(!hit)for(const a of animals){if(!(a.gone>0)&&!a.fly&&!a.swim&&Math.hypot(a.x-b.x,a.z-b.z)<1.3&&b.y<groundAt(a.x,a.z)+2.2){const d=Math.hypot(b.vx,b.vz)||1;a.fly=true;a.fy=groundAt(a.x,a.z)+(a.y||0);a.vy=10;a.fvx=b.vx/d*16;a.fvz=b.vz/d*16;a.cd2=1.5;a.t=0;SFX.honk();hit=true;break;}}
if(!hit&&b.y<=groundAt(b.x,b.z)){crater(b.x,b.z);blocksDirty=true;hit=true;}
if(hit){burst(b.x,b.y+0.2,b.z,b.m.material.color.getHex(),12,6);burst(b.x,b.y+0.2,b.z,0xc8b08a,6,4);SFX.bonk();haptic(35,0.7);scene.remove(b.m);blasts.splice(n,1);}}}
let blocksDirty=false;
/* ---- haptics: phones that can vibrate, iPhone (iOS 18+) through a hidden switch, and the game controller's rumble ---- */
let hapT=0;const hapEl=(()=>{try{const l=document.createElement('label');l.id='hap';l.setAttribute('aria-hidden','true');const i=document.createElement('input');i.type='checkbox';i.setAttribute('switch','');i.tabIndex=-1;l.appendChild(i);document.body.appendChild(l);return l;}catch(e){return null;}})();
function haptic(ms,str){const now=performance.now();if(now<hapT)return;hapT=now+Math.max(45,ms);
try{if(navigator.vibrate)navigator.vibrate(ms);else if(hapEl)hapEl.click();}catch(e){}
try{for(const gp of(navigator.getGamepads?navigator.getGamepads():[])){const va=gp&&gp.vibrationActuator;if(va&&va.playEffect){const pr=va.playEffect('dual-rumble',{duration:ms,strongMagnitude:Math.min(1,str||0.6),weakMagnitude:Math.min(1,(str||0.6)+0.2)});if(pr&&pr.catch)pr.catch(()=>{});}}}catch(e){}}
let chute=false,uw=false,wasUw=false,bubT=0;
function giantDuck(){const g=new THREE.Group(),Y=0xffe633;bx(g,3.2,2.2,4.0,Y,0,1.3,0);bx(g,2.6,0.8,3.2,Y,0,2.6,-0.2);bx(g,1.2,1.0,1.0,Y,0,2.9,-2.0,0,-0.5);
bx(g,2.3,2.2,2.2,Y,0,4.0,1.0);bx(g,1.4,0.5,1.2,0xff8a1a,0,3.7,2.6);bx(g,1.2,0.25,1.0,0xf26b00,0,3.38,2.5);
for(const sd of[-1,1]){bx(g,0.12,0.7,0.6,0xffffff,sd*1.16,4.3,1.5);bx(g,0.14,0.36,0.3,0x111111,sd*1.18,4.3,1.6);bx(g,0.4,1.4,2.2,0xf5d800,sd*1.7,1.6,-0.2);}return g;}
/* ---- Blue House map: 9 cousin dinos play hide and seek, Azizam the dog plays fetch ---- */
const COUSINS=[['Pip',0xff8a65,0.42],['Bop',0x7e57c2,0.38],['Zuzu',0xffca28,0.46],['Dot',0x26c6da,0.36],['Mo',0xec407a,0.44],['Tiki',0x9ccc65,0.4],['Bean',0x8d6e63,0.37],['Wiggles',0x42a5f5,0.45],['Noodle',0xffa726,0.39]];
let cousins=[],dog=null,fball=null,partyT=0,foundN=0,fetchN=0;
function nameTag(t,c){const cv=document.createElement('canvas');cv.width=256;cv.height=64;const x=cv.getContext('2d');x.fillStyle='rgba(255,255,255,0.92)';x.fillRect(16,6,224,52);x.strokeStyle=c;x.lineWidth=5;x.strokeRect(16,6,224,52);
x.font='bold 38px Arial Rounded MT Bold, Arial, sans-serif';x.textAlign='center';x.textBaseline='middle';x.fillStyle=c;x.fillText(t,128,34);
const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:new THREE.CanvasTexture(cv),transparent:true,depthTest:false}));sp.scale.set(1.8,0.45,1);sp.renderOrder=5;return sp;}
function blueHouse(){const g=new THREE.Group(),B=0x3d8bff,W=0xffffff,G=0x9be7ff;
bx(g,7.05,0.25,5.05,0x2f6fd6,0,0.12,0);bx(g,7,3.2,5,B,0,1.6,0);
for(let l=0;l<4;l++)bx(g,7.6-l*0.25,0.5,5.6-l*1.3,l%2?0xff6b6b:0xe53935,0,3.45+l*0.5,0);
bx(g,0.8,1.7,0.8,0xb0bec5,2.2,4.5,-1);bx(g,0.95,0.2,0.95,0x90a4ae,2.2,5.4,-1);
bx(g,1.3,2.1,0.1,W,0,1.05,2.52);bx(g,1.05,1.85,0.12,0xffd24d,0,0.95,2.55);bx(g,0.14,0.14,0.06,0x5d4037,0.35,1.0,2.63);
for(const sx of[-2.3,2.3]){bx(g,1.3,1.1,0.1,W,sx,1.9,2.52);bx(g,1.1,0.9,0.12,G,sx,1.9,2.55);bx(g,0.08,0.9,0.14,W,sx,1.9,2.58);bx(g,1.4,0.15,0.3,0xff80ab,sx,1.3,2.65);}
for(const sx of[-3.52,3.52])for(const sz of[-1.2,1.2]){bx(g,0.1,1.1,1.1,W,sx,1.9,sz);bx(g,0.12,0.9,0.9,G,sx,1.9,sz);}
bx(g,1.9,0.25,1.2,0xbcaaa4,0,0.12,3.1);
const heart=[[0,0],[-1,1],[1,1],[-1,2],[1,2],[0,1]];heart.forEach(([a,b])=>bx(g,0.2,0.2,0.06,0xff4f8a,a*0.2,2.6+b*0.2-0.2,2.56));
return g;}
function dogHouse(){const g=new THREE.Group();bx(g,1.6,1.2,1.8,0xff7043,0,0.6,0);bx(g,1.9,0.3,2.0,0x5d4037,0,1.35,0);bx(g,1.3,0.3,2.0,0x5d4037,0,1.6,0);bx(g,0.6,0.8,0.06,0x3e2723,0,0.45,0.91);
const tag=nameTag('Azizam','#c2185b');tag.position.set(0,2.2,0.6);tag.scale.set(1.6,0.4,1);g.add(tag);bx(g,0.5,0.15,0.3,0x90caf9,0.9,0.08,1.2);bx(g,0.3,0.1,0.15,0xffe0b2,0.9,0.2,1.2);return g;}
function dogModel(){const g=new THREE.Group(),body=new THREE.Group();g.add(body);const C=0xe8c48a,D=0x8d5a34,L=0xf5e1c0;
bx(body,0.6,0.5,1.0,C,0,0.62,0);bx(body,0.4,0.3,0.6,L,0,0.45,0.05);const legs=[];
for(const[a,b]of[[-1,1],[1,1],[-1,-1],[1,-1]]){const l=new THREE.Group();l.position.set(a*0.2,0.45,b*0.35);bx(l,0.16,0.42,0.16,b>0?C:D,0,-0.22,0);bx(l,0.18,0.08,0.22,L,0,-0.42,0.03);body.add(l);legs.push(l);}
const head=new THREE.Group();head.position.set(0,0.95,0.55);body.add(head);
bx(head,0.55,0.5,0.5,C,0,0,0);bx(head,0.32,0.24,0.3,L,0,-0.1,0.35);bx(head,0.13,0.1,0.07,0x222222,0,-0.02,0.5);bx(head,0.13,0.05,0.12,0xff6b8a,0,-0.24,0.42);
for(const sd of[-1,1]){bx(head,0.09,0.11,0.04,0x111111,sd*0.14,0.1,0.26);bx(head,0.05,0.05,0.04,0xffffff,sd*0.14+0.02,0.13,0.27);bx(head,0.13,0.38,0.24,D,sd*0.33,-0.02,-0.02,0,0,sd*0.15);}
bx(body,0.62,0.1,0.16,0x3d8bff,0,0.8,0.42);bx(body,0.12,0.12,0.05,0xffd24d,0,0.7,0.52);
const tail=new THREE.Group();tail.position.set(0,0.8,-0.5);body.add(tail);bx(tail,0.1,0.1,0.45,C,0,0.12,-0.18,0,-0.7);
const tag=nameTag('Azizam','#c2185b');tag.position.set(0,1.75,0);g.add(tag);
g.traverse(o=>{if(o.isMesh)o.castShadow=true;});return {g,body,head,tail,legs};}
function buildFamily(){const H0=blueHouse(),ry=Math.atan2(YARD.x-HOUSE.x,YARD.z-HOUSE.z);H0.rotation.y=ry;addObs(H0,HOUSE.x,HOUSE.z,2.6);trees[trees.length-1].keep=true;
const ax=Math.cos(ry),az=-Math.sin(ry);for(const k of[-1.9,1.9])trees.push({x:HOUSE.x+ax*k,z:HOUSE.z+az*k,r:2.6,g:new THREE.Group(),shake:0,keep:true});
const DH=dogHouse();DH.rotation.y=ry;addObs(DH,HOUSE.x+ax*5+Math.sin(ry)*1.5,HOUSE.z+az*5+Math.cos(ry)*1.5,1.2);trees[trees.length-1].keep=true;
for(let k=-3;k<=3;k++){const f=new THREE.Group();bx(f,0.9,0.12,0.08,0xffffff,0,0.55,0);bx(f,0.9,0.12,0.08,0xffffff,0,0.25,0);bx(f,0.12,0.8,0.1,0xffffff,0,0.4,0);
f.rotation.y=ry+Math.PI/2;addDeco(f,HOUSE.x-Math.sin(ry)*3.6+ax*k*0.95,HOUSE.z-Math.cos(ry)*3.6+az*k*0.95);}
const spotsC=spots(9,8,20,61,1.9);cousins=COUSINS.map(([name,c,sc],i)=>{const sp=spotsC[i]||[YARD.x+i,YARD.z-3];const bu=bush(i%2?0x5cc96b:0x4caf50);addObs(bu,sp[0],sp[1],0.9);
const d=Math.hypot(sp[0],sp[1])||1,hx=sp[0]+sp[0]/d*1.15,hz=sp[1]+sp[1]/d*1.15;
const r=makeRex(sc,c,0xfff3e0);addHat(r,i);world.add(r.R);const tag=nameTag(name,'#'+c.toString(16).padStart(6,'0'));tag.position.set(0,4.3,0);tag.scale.set(1.7/sc,0.42/sc,1);tag.visible=false;r.R.add(tag);
return {i,name,r,tag,hx,hz,x:hx,z:hz,y:0,face:0,found:false,walkT:0,slot:i};});
const dm=dogModel();world.add(dm.g);dog=Object.assign(dm,{m0y:1,x:YARD.x+1,z:YARD.z,face:0,st:'follow',t:0,walkT:0,stuck:0});
const bm=new THREE.Mesh(new THREE.SphereGeometry(0.4,12,8),mat(0xff3d3d));bm.castShadow=true;const bs=new THREE.Mesh(new THREE.TorusGeometry(0.4,0.06,6,16),mat(0xffffff));bm.add(bs);world.add(bm);
fball={m:bm,x:YARD.x-1,z:YARD.z,y:groundAt(YARD.x-1,YARD.z)+0.4,vx:0,vy:0,vz:0,held:false,cd:0};
spots(8,7,20,71).forEach(([x,z],i)=>{const g=autumnTree(i%3?0x43a047:0x66bb6a);for(let k=0;k<4;k++)bx(g,0.25,0.25,0.25,0xff3d3d,Math.cos(k*1.6)*1.25,2.6+(k%2)*0.5,Math.sin(k*1.6)*1.25);addObs(g,x,z,0.8);});
spots(10,6,20,81).forEach(([x,z],i)=>addObs(giantFlower([0xff5c8a,0xb57bff,0xff9a3d,0x4fc3ff][i%4]),x,z,0.5));
sprinkle(130,[0xff5c8a,0xffe14d,0xffffff,0x4fa3ff],0.25,37);resetFamily();}
function resetFamily(){if(!dog)return;foundN=0;fetchN=0;partyT=0;cousins.forEach(c=>{c.found=false;c.x=c.hx;c.z=c.hz;c.y=0;c.tag.visible=false;c.r.R.rotation.set(0,0,0);c.face=Math.atan2(-c.hx,-c.hz);});
dog.x=YARD.x+1;dog.z=YARD.z;dog.st='follow';dog.t=0;fball.x=YARD.x-1;fball.z=YARD.z;fball.y=groundAt(fball.x,fball.z)+0.4;fball.vx=fball.vy=fball.vz=0;fball.held=false;fball.cd=0;}
function findCousin(c){if(c.found)return;c.found=true;foundN++;c.tag.visible=true;c.y=0.1;c.vy=7;SFX.peek();setTimeout(()=>SFX.giggle(),180);burst(c.x,groundAt(c.x,c.z)+1,c.z,0xffe14d,14,5);
const left=9-foundN;if(left)say(`You found cousin ${c.name}! 🙈 ${left} more cousin${left>1?'s are':' is'} hiding.`,2600);
else{say('You found all 9 cousins! Dance party at the Blue House! 💃🕺🎉',4500);partyT=7;SFX.gold();for(let k=0;k<5;k++)setTimeout(()=>burst(YARD.x+(Math.random()-0.5)*5,3.5,YARD.z+(Math.random()-0.5)*5,EGG_COLORS[k%EGG_COLORS.length],18,7),k*250);}}
function kickBall(vx,vz,up){const d=Math.hypot(vx,vz)||1;fball.vx=vx/d*9;fball.vz=vz/d*9;fball.vy=up||6;fball.held=false;fball.cd=1;SFX.boing();
if(dog.st!=='bring'){dog.st='chase';dog.t=0;if(playing)say(fetchN?'Go, Azizam, go! 🐶':'Kick! Azizam, fetch the ball! 🐶',1600);}}
function familyRoar(){if(!dog)return;cousins.forEach(c=>{if(!c.found&&Math.hypot(c.x-player.x,c.z-player.z)<5)findCousin(c);});
if(Math.hypot(dog.x-player.x,dog.z-player.z)<10&&dog.st!=='chase'&&dog.st!=='bring'){dog.st='happy';dog.t=1.4;setTimeout(()=>SFX.bark(),250);}
if(foundN&&Math.hypot(YARD.x-player.x,YARD.z-player.z)<11&&partyT<=0){partyT=4;say('Roar! The cousins dance! 💃',1600);}}
function walkTo(o,tx,tz,sp,dt,r){const dx=tx-o.x,dz=tz-o.z,d=Math.hypot(dx,dz);if(d<0.05)return d;const st=Math.min(d,sp*dt);let nx=o.x+dx/d*st,nz=o.z+dz/d*st;
const c=collide(nx,nz,r||0.4);o.x=c[0];o.z=c[1];o.face=Math.atan2(dx,dz);o.walkT+=dt*sp*3;return d;}
function updateFamily(dt,T){if(!dog)return;fball.cd-=dt;if(partyT>0)partyT-=dt;
// ball
if(!fball.held){fball.vy-=20*dt;fball.x+=fball.vx*dt;fball.z+=fball.vz*dt;fball.y+=fball.vy*dt;const lim=HALF-2;
if(Math.abs(fball.x)>lim){fball.x=Math.sign(fball.x)*lim;fball.vx*=-0.5;}if(Math.abs(fball.z)>lim){fball.z=Math.sign(fball.z)*lim;fball.vz*=-0.5;}
const c=collide(fball.x,fball.z,0.4);if(Math.abs(c[0]-fball.x)+Math.abs(c[1]-fball.z)>0.001){fball.vx*=-0.5;fball.vz*=-0.5;fball.x=c[0];fball.z=c[1];}
const gy=(inPond(fball.x,fball.z)?POND.surf-0.15:groundAt(fball.x,fball.z))+0.4;
if(fball.y<gy){fball.y=gy;if(fball.vy<-3)fball.vy=-fball.vy*0.45;else fball.vy=0;fball.vx*=1-Math.min(1,3*dt);fball.vz*=1-Math.min(1,3*dt);}
fball.m.rotation.x+=fball.vz*dt*2;fball.m.rotation.z-=fball.vx*dt*2;
if(playing&&fball.cd<=0&&!ride&&Math.hypot(player.x-fball.x,player.z-fball.z)<1.4&&Math.abs(player.y+0.4-fball.y)<2){kickBall(Math.sin(player.face),Math.cos(player.face),runOn||power?7:6);}}
fball.m.position.set(fball.x,fball.y,fball.z);
// Azizam
const pd=Math.hypot(player.x-dog.x,player.z-dog.z);let mv=0,sp=0;dog.t+=dt;
if(dog.st==='follow'){const a=player.face+2.3,tx=player.x+Math.sin(a)*2.4,tz=player.z+Math.cos(a)*2.4;if(Math.hypot(tx-dog.x,tz-dog.z)>1.2){sp=pd>8?9:5;walkTo(dog,tx,tz,sp,dt);mv=1;}else dog.face=Math.atan2(player.x-dog.x,player.z-dog.z);
if(pd>26){dog.x=player.x-2;dog.z=player.z-2;}}
else if(dog.st==='chase'){sp=8;const d=walkTo(dog,fball.x,fball.z,sp,dt);mv=1;if(d<0.9&&fball.y<groundAt(fball.x,fball.z)+1.6){fball.held=true;dog.st='bring';dog.t=0;SFX.squeak();}}
else if(dog.st==='bring'){sp=7.5;const d=walkTo(dog,player.x,player.z,sp,dt);mv=1;
fball.x=dog.x+Math.sin(dog.face)*0.95;fball.z=dog.z+Math.cos(dog.face)*0.95;fball.y=dog.m0y+0.9;
if(d<2.1){fball.held=false;fball.vx=fball.vz=0;fball.vy=0;fball.x=player.x+Math.sin(player.face)*1.9;fball.z=player.z+Math.cos(player.face)*1.9;const cc=collide(fball.x,fball.z,0.4);fball.x=cc[0];fball.z=cc[1];fball.cd=0.9;
fetchN++;dog.st='happy';dog.t=1.6;SFX.bark();say(fetchN===1?'Azizam brought the ball back! Good dog! 🐶 Kick it again!':`Good dog, Azizam! ${fetchN} fetches! 🐶`,2400);}}
else if(dog.st==='happy'){dog.t-=dt*2;dog.body.rotation.y=(1.6-dog.t)*Math.PI*2.5;if(dog.t<=0){dog.st='follow';dog.body.rotation.y=0;}}
if((dog.st==='chase'||dog.st==='bring')&&dog.t>9){burst(dog.x,dog.m0y+1,dog.z,0xffffff,10,4);const tg=dog.st==='chase'?fball:player;dog.x=tg.x-1;dog.z=tg.z-1;dog.t=0;}
if(dog.st!=='happy')dog.t+=0;
const dg=inPond(dog.x,dog.z)?POND.surf-0.55:groundAt(dog.x,dog.z);dog.m0y=dg;dog.walkT+=mv?dt*sp*2.2:0;
const hop=dog.st==='happy'?Math.abs(Math.sin(dog.t*7))*0.8:partyT>0?Math.abs(Math.sin(T*8))*0.5:mv?Math.abs(Math.sin(dog.walkT))*0.08:0;
dog.g.position.set(dog.x,dg+hop,dog.z);dog.g.rotation.y=dog.face;dog.legs.forEach((l,k)=>l.rotation.x=mv?Math.sin(dog.walkT+(k%2?Math.PI:0)+(k>1?Math.PI:0))*0.7:0);
dog.tail.rotation.y=Math.sin(T*(dog.st==='follow'&&!mv?8:18))*0.6;dog.head.rotation.x=dog.st==='bring'?0.2:Math.sin(T*2)*0.05;
if(playing&&pd<2&&dog.st==='follow'&&Math.random()<dt*0.15)SFX.bark();
// cousins
for(const c of cousins){const R=c.r.R;
if(!c.found){const g=groundAt(c.x,c.z),pk=Math.sin(T*1.1+c.i*0.9)>0.55;R.position.set(c.x,g-(pk?0.15:0.75),c.z);R.rotation.y=Math.atan2(-c.x,-c.z);c.r.headPivot.rotation.x=pk?-0.15:0.2;
const d=Math.hypot(player.x-c.x,player.z-c.z);if(playing&&d<2.6&&Math.abs(player.y-g)<3)findCousin(c);else if(playing&&pk&&d<7&&Math.random()<dt*0.12)SFX.peek();continue;}
let tx,tz,mvC=0;if(partyT>0){const a=c.i/9*Math.PI*2+T*1.2;tx=YARD.x+Math.cos(a)*3.2;tz=YARD.z+Math.sin(a)*3.2;}else{const a=c.slot/9*Math.PI*2;tx=YARD.x+Math.cos(a)*3.6;tz=YARD.z+Math.sin(a)*3.6;}
const d=walkTo(c,tx,tz,partyT>0?6:4.5,dt,0.3);mvC=d>0.15;if(!mvC)c.face=Math.atan2(YARD.x-c.x,YARD.z-c.z);
c.vy=(c.vy||0)-20*dt;c.y+=c.vy*dt;if(c.y<0){c.y=0;c.vy=partyT>0?4+((c.i*7)%3):0;}
R.position.set(c.x,groundAt(c.x,c.z)+c.y,c.z);R.rotation.y=c.face+(partyT>0?Math.sin(T*6+c.i)*0.8:0);
const s=mvC?Math.sin(c.walkT)*0.7:0;c.r.legs[0].rotation.x=s;c.r.legs[1].rotation.x=-s;c.r.tail.rotation.y=Math.sin(T*6+c.i)*0.5;c.r.arms.forEach((a,k)=>a.rotation.x=partyT>0?-2.4+Math.sin(T*10+k*3)*0.5:0);c.r.headPivot.rotation.x=Math.sin(T*3+c.i)*0.08;}}
/* ---- one connected world: Rexy's Island in the middle, a gate to each land; each land has gates back to the island and to the lands next door ---- */
function signTag(txt,col){const cv=document.createElement('canvas');cv.width=512;cv.height=128;const x=cv.getContext('2d');x.fillStyle='rgba(255,255,255,0.95)';x.fillRect(10,10,492,108);x.strokeStyle=col;x.lineWidth=10;x.strokeRect(10,10,492,108);
let fs=58;x.font=`bold ${fs}px Arial Rounded MT Bold, Arial, sans-serif`;while(x.measureText(txt).width>468&&fs>22){fs-=3;x.font=`bold ${fs}px Arial Rounded MT Bold, Arial, sans-serif`;}x.textAlign='center';x.textBaseline='middle';x.fillStyle=col;x.fillText(txt,256,68);
const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:new THREE.CanvasTexture(cv),transparent:true}));sp.scale.set(4,1,1);bigSigns.push(sp);return sp;}
const bigSigns=[],_sv=new THREE.Vector3();
function fadeSigns(){for(let i=bigSigns.length-1;i>=0;i--){const s=bigSigns[i];s.getWorldPosition(_sv);const d=camera.position.distanceTo(_sv);s.material.opacity=Math.max(0,Math.min(1,(d-7)/5));}}
function gateModel(to){const L=MAPS[to],g=new THREE.Group(),c=new THREE.Color(L.sky).multiplyScalar(0.75).getHex(),stone=to==='hub'?0x26a69a:0xffffff;
for(const sd of[-1,1]){bx(g,0.8,3.4,0.8,stone,sd*1.6,1.7,0);bx(g,1.0,0.3,1.0,c,sd*1.6,3.5,0);bx(g,1.0,0.3,1.0,c,sd*1.6,0.15,0);}
bx(g,4.2,0.6,1.0,c,0,3.9,0);bx(g,1.2,0.5,1.0,stone,0,4.45,0);
const disc=new THREE.Mesh(new THREE.CircleGeometry(1.25,24),new THREE.MeshBasicMaterial({color:L.sky,transparent:true,opacity:0.75,side:THREE.DoubleSide}));disc.position.y=1.9;g.add(disc);
const ring=new THREE.Mesh(new THREE.TorusGeometry(1.3,0.12,6,24),new THREE.MeshBasicMaterial({color:0xffffff}));ring.position.y=1.9;g.add(ring);
const won=mapStars()[to];const tag=signTag(`${L.icon} ${to==='hub'?'Island':L.name}${won?' ⭐':''}`,'#'+new THREE.Color(c).multiplyScalar(0.7).getHexString());tag.position.y=5.4;g.add(tag);
const sw=new THREE.Group();sw.position.y=1.9;g.add(sw);for(let k=0;k<6;k++){const m=new THREE.Mesh(geo(0.22,0.22,0.22),new THREE.MeshBasicMaterial({color:k%2?0xffffff:0xfff59d}));const a=k/6*Math.PI*2;m.position.set(Math.cos(a)*0.8,Math.sin(a)*0.8,0.05);sw.add(m);}
g.userData={disc,sw};return g;}
let gateObjs=[];
function buildGates(){gateObjs=GATES.map(G=>{const g=gateModel(G.to);g.rotation.y=G.ry;g.position.set(G.x,groundAt(G.x,G.z),G.z);world.add(g);
const ax=Math.cos(G.ry),az=-Math.sin(G.ry);for(const sd of[-1,1])trees.push({x:G.x+ax*sd*1.6,z:G.z+az*sd*1.6,r:0.6,g:new THREE.Group(),shake:0,keep:true});return {G,g};});}
const LANDMARK={toys:()=>ball(0xff5c5c),house:()=>{const h=blueHouse();h.scale.setScalar(0.32);return h;},meadow:()=>giantFlower(0xff5c8a),forest:()=>autumnTree(0xff8f00),jungle:()=>palm(),beach:()=>sandCastle(),desert:()=>cactus(),mountain:()=>rock(0x9e9e9e),snow:()=>snowman(),inside:()=>bedModel(0x7e57c2),rain:()=>umbrella(0x40c4ff),race:()=>{const c=carModel(0xff3d3d);c.scale.setScalar(0.8);return c;}};
DECOR_HUB=function(){GATES.forEach((G,k)=>{const a=k/MAP_ORDER.length*Math.PI*2,tx=Math.cos(a),tz=-Math.sin(a);
const lm=LANDMARK[G.to]();lm.rotation.y=G.ry;if(G.to!=='house')lm.scale.multiplyScalar(1.4);else lm.scale.setScalar(0.5);addObs(lm,G.x+tx*3.8,G.z+tz*3.8,G.to==='house'?2:1.2);
if(G.to==='mountain'){const p=pine(true,0.8);addObs(p,G.x-tx*3.4,G.z-tz*3.4,0.7);}
const pc=new THREE.Color(MAPS[G.to].sky).getHex();for(let r=4.5;r<22.6;r+=1.5){const st=new THREE.Group();bx(st,1.1,0.12,1.1,r%3<1.5?0xffffff:pc,0,0.06,0,a);addDeco(st,Math.sin(a)*r,Math.cos(a)*r);}});
spots(22,8,29,91,2).forEach(([x,z])=>{const to=MAP_ORDER[sectorOf(x,z)];const m=to==='house'?bush(0x5cc96b):LANDMARK[to]();m.rotation.y=hash(x,z)*6;addObs(m,x,z,1.0);}); // each corner of the island looks like the land next to it
sprinkle(220,[0xff5c8a,0xffe14d,0xffffff,0x4fa3ff],0.25,43);};
function updateGates(dt,T){gateCd-=dt;for(const o of gateObjs){o.g.userData.sw.rotation.z+=dt*2.5;o.g.userData.disc.material.opacity=0.6+Math.sin(T*3)*0.15;
if(playing&&!traveling&&gateCd<=0&&Math.hypot(player.x-o.G.x,player.z-o.G.z)<1.3&&player.y<groundAt(o.G.x,o.G.z)+5)travel(o.G.to,mapId);}}
function travel(to,from){if(traveling)return;traveling=true;SFX.power();fadeEl.style.opacity=1;
setTimeout(()=>{playing=false;ride=null;buildMap(to);startGame();const back=GATES.find(G=>G.to===from);
if(back){player.x=back.x+Math.sin(back.ry)*4.6;player.z=back.z+Math.cos(back.ry)*4.6;player.y=groundAt(player.x,player.z);player.face=back.ry;camYaw=back.ry+Math.PI;placeP2();}
gateCd=1.5;babies.forEach(b=>{b.x=player.x;b.z=player.z;});setTimeout(()=>{fadeEl.style.opacity=0;traveling=false;},120);},420);}
function startIsland(){if(builtMap!=='hub')buildMap('hub');startGame();}
function goLand(id){if(builtMap!==id)buildMap(id);startGame();}
function bedModel(c){const g=new THREE.Group();bx(g,2.2,0.5,3.2,c,0,0.45,0);bx(g,2.0,0.3,3.0,0xffffff,0,0.85,0);bx(g,2.05,0.18,1.9,new THREE.Color(c).lerp(WHITE,0.4).getHex(),0,1.05,-0.5);
bx(g,1.2,0.3,0.6,0xfffde7,0,1.1,1.0);bx(g,2.2,1.4,0.25,c,0,1.0,1.6);bx(g,0.5,0.5,0.1,0xffe14d,0,1.4,1.74);for(const[a,b]of[[-1,-1],[1,-1],[-1,1],[1,1]])bx(g,0.25,0.3,0.25,0x6d4c41,a*0.95,0.1,b*1.45);return g;}
function toyChest(c){const g=new THREE.Group();bx(g,1.8,1.0,1.1,c,0,0.5,0);bx(g,1.9,0.25,1.2,new THREE.Color(c).multiplyScalar(0.75).getHex(),0,1.1,0);bx(g,0.3,0.3,0.1,0xffe14d,0,0.8,0.58);
bx(g,0.5,0.5,0.5,0xff5c5c,-0.4,1.4,0,0.4);bx(g,0.4,0.4,0.4,0x4fa3ff,0.45,1.35,0.1,0.8);return g;}
let roomKids=[];
function buildRooms(){roomKids=[];
for(let k=0;k<9;k++){const [name,c,sc]=COUSINS[k],cx=ROOMC[k%3],cz=ROOMC[(k/3)|0],center=k===4;
const rug=new THREE.Group();bx(rug,center?6:5,0.06,center?4:4.5,new THREE.Color(c).lerp(WHITE,0.25).getHex(),0,0.03,0);bx(rug,center?5:4,0.07,center?3:3.5,0xffffff,0,0.035,0);addDeco(rug,cx+(center?-6:0),cz+(center?4:0));
let sign=null;if(!center){sign=signTag(`${name}'s room`,'#'+new THREE.Color(c).multiplyScalar(0.75).getHexString());sign.position.set(cx,7,cz);sign.scale.set(4.4,1.1,1);world.add(sign);}
if(!center){const free=(x,z,r)=>!VSPOTS.some(([vx,vz])=>Math.hypot(vx-x,vz-z)<r+3.8)&&Math.hypot(x-POND.x,z-POND.z)>POND.r+r+0.5&&!trees.some(t=>Math.hypot(t.x-x,t.z-z)<t.r+r+0.3)&&!nearWall(x,z,r);
const ox=Math.sign(cx)||1,oz=Math.sign(cz)||1;const cands=[[cx+ox*5.5,cz-oz*3.5],[cx-ox*5.5,cz+oz*5.5],[cx+ox*5.5,cz+oz*5.5],[cx-ox*5.5,cz-oz*5.5],[cx,cz+oz*6]];
let placed=0;for(const [x,z] of cands){if(placed>=3)break;if(!free(x,z,1.6))continue;const m=placed===0?bedModel(c):placed===1?toyChest(c):[abcBlocks(k),stackRings(),ball(c)][k%3];m.rotation.y=placed===0?Math.atan2(-ox*0,-oz)+ (cz?0:Math.PI/2):hash(k,placed)*6;addObs(m,x,z,placed===0?1.6:1.0);placed++;}}
const r=makeRex(sc,c,0xfff3e0);addHat(r,k);world.add(r.R);const tag=nameTag(name,'#'+c.toString(16).padStart(6,'0'));tag.position.set(0,4.3,0);tag.scale.set(1.7/sc,0.42/sc,1);r.R.add(tag);
const hx=cx+(center?-6:1.5),hz=cz+(center?4:1.5);roomKids.push({k,name,c,r,sign,x:hx,z:hz,y:0,vy:0,face:0,walkT:0,tx:hx,tz:hz,t:0,cx,cz,greet:false,dance:0});}
// windows and pictures on the outer walls, a lamp in each corner
for(let k=0;k<12;k++){const a=k/12*Math.PI*2,x=Math.cos(a)*20.3,z=Math.sin(a)*20.3;if(Math.abs(Math.abs(x)-10.5)<2||Math.abs(Math.abs(z)-10.5)<2)continue;const w=new THREE.Group();const side=Math.abs(x)>Math.abs(z);
bx(w,side?0.15:2.2,1.6,side?2.2:0.15,0xffffff,0,3.2,0);bx(w,side?0.18:1.8,1.2,side?1.8:0.18,0x9be7ff,0,3.2,0);w.position.set(side?Math.sign(x)*20.2:x,1,side?z:Math.sign(z)*20.2);world.add(w);}
sprinkle(60,[0xff5c8a,0xffe14d,0x4fa3ff,0x5ccf6b],0.22,53);}
function roomRoar(){roomKids.forEach(c=>{if(Math.hypot(c.x-player.x,c.z-player.z)<12){c.dance=3.5;c.vy=6;}});}
function updateRooms(dt,T){if(!roomKids.length)return;const pr=playing?roomOf(player.x,player.z):-1;
for(const c of roomKids){const R=c.r.R;c.t-=dt;if(c.dance>0)c.dance-=dt;if(c.sign)c.sign.visible=pr!==c.k&&Math.hypot(camera.position.x-c.cx,camera.position.z-c.cz)>7;
if(pr===c.k&&!c.greet){c.greet=true;c.vy=7;SFX.peek();setTimeout(()=>SFX.giggle(),200);say(`🛏️ ${c.name}'s room! ${c.name} says hi, Rexy! 👋 ROAR to make ${c.name} dance!`,3000);}
if(c.t<=0){c.t=2+Math.random()*3;const near=Math.hypot(player.x-c.x,player.z-c.z)<6;if(near&&pr===c.k){const a=player.face+Math.PI+(Math.random()-0.5);c.tx=player.x+Math.sin(a)*2;c.tz=player.z+Math.cos(a)*2;}else{c.tx=c.cx+(Math.random()-0.5)*(c.k===4?8:6);c.tz=c.cz+(Math.random()-0.5)*(c.k===4?8:6);}
if(c.k===4){c.tx=Math.min(-2,c.tx);c.tz=Math.max(1.5,c.tz);}if(nearWall(c.tx,c.tz,0.8)){c.tx=c.cx;c.tz=c.cz;}}
const d=c.dance>0?0:walkTo(c,c.tx,c.tz,3,dt,0.3),mv=d>0.2;
c.vy-=20*dt;c.y+=c.vy*dt;if(c.y<0){c.y=0;c.vy=c.dance>0?4+(c.k%3):(mv&&Math.random()<0.01?4:0);}
R.position.set(c.x,groundAt(c.x,c.z)+c.y,c.z);R.rotation.y=c.face+(c.dance>0?T*6:0);const s=mv?Math.sin(c.walkT)*0.7:0;c.r.legs[0].rotation.x=s;c.r.legs[1].rotation.x=-s;
c.r.arms.forEach((a,k)=>a.rotation.x=c.dance>0?-2.4+Math.sin(T*10+k*3)*0.5:0);c.r.tail.rotation.y=Math.sin(T*6+c.k)*0.5;c.r.headPivot.rotation.x=Math.sin(T*3+c.k)*0.08;}}
/* ---- Rain Land: rain, then a rainbow, then night with stars, planets and shooting stars ---- */
function puddle(){const g=new THREE.Group();const m=new THREE.Mesh(new THREE.CircleGeometry(1.2,16),new THREE.MeshLambertMaterial({color:0x7fb2e5,transparent:true,opacity:0.8}));m.rotation.x=-Math.PI/2;m.position.y=0.04;m.scale.set(1,1.4,1);g.add(m);return g;}
function toadstool(c){const g=new THREE.Group();bx(g,0.5,1.6,0.5,0xfff8e1,0,0.8,0);bx(g,2.2,0.6,2.2,c,0,1.8,0);bx(g,1.4,0.4,1.4,c,0,2.25,0);for(const[a,b]of[[-0.6,0.5],[0.5,-0.4],[0.2,0.7]])bx(g,0.3,0.1,0.3,0xffffff,a,2.47,b);return g;}
/* ---- Race Track: drive a car to the start line and the race begins. 3 laps against 2 toy race cars. ---- */
function raceArch(){const g=new THREE.Group();for(const sd of[-1,1]){bx(g,0.6,4.6,0.6,0xffffff,0,2.3,sd*3.3);bx(g,0.7,0.4,0.7,0xff3d3d,0,4.6,sd*3.3);}
for(let k=0;k<12;k++)bx(g,0.3,0.5,0.55,k%2?0x111111:0xffffff,0,4.4+(k%2?0.25:0),-3.0+k*0.55);const t=signTag('🏁 START','#d32f2f');t.position.set(0,5.6,0);g.add(t);return g;}
let race=null;
function buildRace(){const A=raceArch();addDeco(A,0,-13);trees.push({x:0,z:-16.3,r:0.5,g:new THREE.Group(),shake:0,keep:true},{x:0,z:-9.7,r:0.5,g:new THREE.Group(),shake:0,keep:true});
const pad=new THREE.Mesh(new THREE.RingGeometry(1.4,1.8,32),new THREE.MeshBasicMaterial({color:0xffe14d,transparent:true,opacity:0.7,side:THREE.DoubleSide}));pad.rotation.x=-Math.PI/2;pad.position.set(-3,1.05,-13.3);world.add(pad);
for(let k=0;k<28;k++){const a=k/28*Math.PI*2,x=Math.cos(a)*TRA*0.76,z=Math.sin(a)*TRB*0.76;if(Math.hypot(x,z+13)<4)continue;const g=new THREE.Group();bx(g,0.5,0.7,0.5,k%2?0xff7043:0xffffff,0,0.35,0);bx(g,0.6,0.1,0.6,0xff7043,0,0.05,0);addDeco(g,x,z);}
for(let k=0;k<24;k++){const a=k/24*Math.PI*2,x=Math.cos(a)*TRA*1.27,z=Math.sin(a)*TRB*1.27;if(Math.abs(x)>20||Math.abs(z)>20)continue;const g=new THREE.Group();bx(g,0.9,0.4,0.9,0x222222,0,0.2,0);bx(g,0.9,0.4,0.9,0x333333,0,0.6,0);bx(g,0.5,0.1,0.5,0xff3d3d,0,0.82,0);addObs(g,x,z,0.5);}
const bots=[[0xb57bff,0.92],[0xff9a3d,1.08]].map(([c,lane],i)=>{const g=carModel(c);world.add(g);const n=nameTag(i?'Zoom':'Vroomy','#'+c.toString(16).padStart(6,'0'));n.position.set(0,2.6,0);g.add(n);return {g,lane,th:0,prog:0,sp:0,lap:0};});
race={pad,bots,st:'idle',t:0,racers:[],place:[]};resetRace();
spots(10,6,20,111,1.5).forEach(([x,z],i)=>addObs(i%2?bush(0x5cc96b):giantFlower([0xff5c8a,0xffe14d][i%2]),x,z,0.8));sprinkle(90,[0xffffff,0xffe14d,0xff5c8a],0.22,57);}
function botPos(b){const a=TRA*b.lane,c=TRB*b.lane;return [Math.cos(b.th)*a,Math.sin(b.th)*c];}
function resetRace(){if(!race)return;race.st='idle';race.t=0;race.place=[];race.bots.forEach((b,i)=>{b.th=-Math.PI/2-0.42-i*0.1;b.prog=0;b.lap=0;b.done=false;const [x,z]=botPos(b);b.g.position.set(x,groundAt(x,z),z);b.g.rotation.y=Math.PI/2;});}
function racerTheta(x,z){return Math.atan2(z/TRB,x/TRA);}
function startRace(){race.st='count';race.t=3.2;race.racers=[];forP(()=>{if(ride&&ride.kind==='car'&&!player.pass)race.racers.push({p:player,name:player.p2?'Player 2':'Rexy',th:racerTheta(player.x,player.z),prog:0,lap:0,done:false});});
resetRace();race.st='count';race.t=3.2;SFX.honk();say('🏁 Race! 3 laps round the track. Ready...',1200);}
function updateRace(dt,T){if(!race||!playing)return;race.pad.material.opacity=0.5+Math.sin(T*5)*0.3;
if(race.st==='idle'){let go=false;forP(()=>{if(ride&&ride.kind==='car'&&!player.pass&&Math.hypot(player.x+3,player.z+13.3)<2.6)go=true;});if(go)startRace();
else if(!race.told&&Math.hypot(player.x,player.z+13)<9){race.told=true;say('🏁 Drive a car to the yellow ring at the start to race!',3000);}return;}
if(race.st==='count'){const n0=Math.ceil(race.t);race.t-=dt;const n1=Math.ceil(race.t);if(n1!==n0&&n1>0){say(`🏁 ${n1}...`,900);SFX.bonk();}if(race.t<=0){race.st='go';race.t=0;say('🏁 GO! GO! GO!',1200);SFX.power();race.racers.forEach(r=>{r.th=racerTheta(r.p.x,r.p.z);});}return;}
if(race.st==='go'){race.t+=dt;const all=[...race.racers];
race.bots.forEach((b,i)=>{if(b.done)return;const sp=(M.spd>1?13.5:11.2)*(1+0.04*Math.sin(T*0.7+i*2))+i*0.4;const a=TRA*b.lane,c=TRB*b.lane;const dl=Math.hypot(a*Math.sin(b.th),c*Math.cos(b.th))||1;const d=sp*dt/dl;b.th+=d;b.prog+=d;
const [x,z]=botPos(b);b.g.position.set(x,groundAt(x,z)+Math.abs(Math.sin(T*12+i))*0.05,z);b.g.rotation.y=Math.atan2(-a*Math.sin(b.th),c*Math.cos(b.th));if(b.prog>=Math.PI*6){b.done=true;race.place.push(i?'Zoom':'Vroomy');}});
for(const r of all){if(r.done)continue;const th=racerTheta(r.p.x,r.p.z);let d=th-r.th;while(d>Math.PI)d-=Math.PI*2;while(d<-Math.PI)d+=Math.PI*2;r.th=th;if(Math.abs(trackE(r.p.x,r.p.z)-1)<0.6)r.prog+=d;
const lap=Math.min(3,Math.floor(Math.max(0,r.prog)/(Math.PI*2))+1);if(lap>r.lap){r.lap=lap;if(lap>1){say(`🏁 ${r.name}: lap ${lap} of 3!`,1400);SFX.hello();}}
if(r.prog>=Math.PI*6){r.done=true;race.place.push(r.name);const pos=race.place.length;burst(r.p.x,r.p.y+2,r.p.z,0xffd24d,30,8);SFX[pos===1?'win':'gift']();say(pos===1?`🏆 ${r.name} WINS THE RACE! 🏁`:`🏁 ${r.name} finished! Place ${pos}!`,3500);if(pos===1)for(let k=0;k<6;k++)makeCandy(r.p.x+(Math.random()-0.5)*3,r.p.z+(Math.random()-0.5)*3);}}
if(all.length&&all.every(r=>r.done)||!all.length&&race.bots.every(b=>b.done)||race.t>150){race.st='done';race.t=4;}
if(all.length&&!all.some(r=>r.done)&&race.bots.every(b=>b.done)){race.st='done';race.t=4;say('🏁 The toy cars won this time. Try again! Drive to the yellow ring.',3500);}return;}
if(race.st==='done'){race.t-=dt;if(race.t<=0)resetRace();}}
const DECOR={
hub(){DECOR_HUB();},
inside(){buildRooms();},
race(){buildRace();},
rain(){spots(8,6,20,7).forEach(([x,z],i)=>addObs(toadstool([0xff4f6d,0x40c4ff,0xffd24d,0xb57bff][i%4]),x,z,1.0));
spots(5,6,18,17).forEach(([x,z],i)=>addObs(umbrella([0xff5252,0xffeb3b,0x40c4ff,0xff80ab,0x7ee36b][i]),x,z,0.4));
spots(10,6,20,27).forEach(([x,z])=>addDeco(puddle(),x,z));spots(8,7,20,37).forEach(([x,z],i)=>addObs(bush(i%2?0x4caf50:0x2e7d32),x,z,0.9));
spots(6,7,20,47).forEach(([x,z],i)=>addObs(giantFlower([0x40c4ff,0xb57bff,0xff5c8a][i%3]),x,z,0.5));sprinkle(110,[0x9be7ff,0xffffff,0xb57bff],0.24,61);},
house(){buildFamily();},
toys(){const D=giantDuck();D.rotation.y=Math.PI*0.75;addObs(D,12.5,9.5,3.0);toyDuck={x:12.5,z:9.5,g:D,cd:0,sq:0};
spots(9,7,20,7).forEach(([x,z],i)=>{const g=abcBlocks(i);g.rotation.y=hash(i,3)*6;addObs(g,x,z,0.8);});
spots(5,7,20,17).forEach(([x,z],i)=>addObs(stackRings(),x,z,0.9));
spots(7,7,20,27).forEach(([x,z],i)=>addObs(ball([0xff5c5c,0x4fa3ff,0xffd24d,0x5ccf6b][i%4]),x,z,0.8));
sprinkle(120,[0xff5c8a,0xffe14d,0x4fa3ff,0x5ccf6b],0.25,13);},
meadow(){spots(14,7,20,7).forEach(([x,z],i)=>{const g=giantFlower([0xff5c8a,0xb57bff,0xff9a3d,0x4fc3ff][i%4]);g.rotation.y=hash(i,3)*6;addObs(g,x,z,0.5);});
spots(10,7,20,17).forEach(([x,z],i)=>addObs(bush(i%2?0x5cc96b:0x7bd96a),x,z,0.9));sprinkle(140,[0xff5c8a,0xffe14d,0xffffff,0xb57bff],0.25,11);},
beach(){spots(16,6,20,7).forEach(([x,z],i)=>{const g=palm();g.rotation.y=hash(i,5)*6;addObs(g,x,z,0.6);});
spots(4,6,16,21).forEach(([x,z],i)=>addObs(umbrella([0xff5252,0xffeb3b,0x40c4ff,0xff80ab][i]),x,z,0.4));spots(4,6,18,31).forEach(([x,z])=>addObs(sandCastle(),x,z,1.2));
sprinkle(90,[0xffffff,0xffc1d6,0xffe0b2],0.22,13);},
desert(){spots(18,6,20,7).forEach(([x,z],i)=>{const g=cactus();g.rotation.y=hash(i,4)*6;addObs(g,x,z,0.6);});
spots(8,7,20,17).forEach(([x,z])=>addObs(rock(0xa1887f),x,z,1.0));spots(2,10,18,27).forEach(([x,z])=>addObs(stepPyramid(),x,z,2.3));sprinkle(70,[0xbcaaa4,0x8d6e63,0xffccbc],0.22,15);},
snow(){spots(16,7,20,7).forEach(([x,z])=>addObs(pine(true),x,z,0.8));spots(6,6,18,17).forEach(([x,z],i)=>{const g=snowman();g.rotation.y=Math.atan2(-x,-z);addObs(g,x,z,0.7);});
spots(6,7,20,27).forEach(([x,z])=>addObs(iceCrystal(),x,z,0.6));sprinkle(80,[0xffffff,0xe3f2fd],0.25,19);
const fm=mat(0xffffff);for(let i=0;i<90;i++){const m=new THREE.Mesh(geo(0.13,0.13,0.13),fm);m.position.set((Math.random()-0.5)*40,Math.random()*14,(Math.random()-0.5)*40);world.add(m);flakes.push(m);}},
jungle(){spots(16,6,20,7).forEach(([x,z])=>addObs(bigLeaves(),x,z,0.8));spots(9,7,20,17).forEach(([x,z])=>addObs(bamboo(),x,z,0.8));
spots(8,6,20,27).forEach(([x,z])=>addDeco(bigFlowerFlat(),x,z));sprinkle(120,[0xff4081,0xffeb3b,0x7c4dff,0x1de9b6],0.25,23);},
forest(){spots(18,7,20,7).forEach(([x,z],i)=>addObs(autumnTree([0xff8f00,0xe53935,0xfdd835,0xff7043][i%4]),x,z,0.8));
spots(5,6,18,17).forEach(([x,z],i)=>{const g=log();g.rotation.y=hash(i,9)*3;addObs(g,x,z,1.1);});sprinkle(160,[0xff8f00,0xe53935,0xfdd835,0x8d6e63],0.24,29);},
mountain(){spots(14,6,20,7).forEach(([x,z])=>addObs(rock(0x9e9e9e),x,z,1.0));spots(8,8,20,17).forEach(([x,z])=>addObs(pine(true,0.8),x,z,0.7));
spots(5,8,20,27).forEach(([x,z])=>addObs(iceCrystal(),x,z,0.6));sprinkle(80,[0xbdbdbd,0xffffff,0x8bc34a],0.24,31);}
};
function sneezeVolcano(x,z){const g=new THREE.Group();for(let l=0;l<5;l++){const s=7-l*1.3;bx(g,s,1.2,s,l===4?0xff7043:0x8d6e63,0,l*1.2+0.6,0);}g.position.set(x,groundAt(x,z),z);world.add(g);return g;}
// lava volcanoes: they rumble, then erupt lava bombs (a red ring shows where each lands)
function makeVolcano(x,z){
const g=new THREE.Group();
for(let l=0;l<5;l++){const s=6.5-l*1.2;bx(g,s,1.2,s,l===4?0xff3d00:0x4e342e,0,l*1.2+0.6,0,0,0,0,l===4?0x992200:0);}
for(let k=0;k<4;k++){const a=k*Math.PI/2;bx(g,0.5,3.2,0.12,0xff6d00,Math.sin(a)*2.0,3.4,Math.cos(a)*2.0,a,0.35*Math.cos(a),-0.35*Math.sin(a),0xff6d00);}
g.position.set(x,groundAt(x,z),z);world.add(g);
const v={x,z,g,t:0,warn:false};VOLC.push(v);return v;
}
let boss=null,blocksMesh=null,mapDamaged=false,blkT=0;
function buildBlocks(){if(blocksMesh){world.remove(blocksMesh);blocksMesh.material.dispose();blocksMesh.dispose&&blocksMesh.dispose();}
let count=0;for(let i=0;i<N;i++)for(let j=0;j<N;j++)count+=H[i][j]+1;
const blocks=new THREE.InstancedMesh(geo(1,1,1),new THREE.MeshLambertMaterial({color:0xffffff}),count);blocks.receiveShadow=true;
const m4=new THREE.Matrix4(),col=new THREE.Color();let k=0;
for(let i=0;i<N;i++)for(let j=0;j<N;j++)for(let y=0;y<=H[i][j];y++){if(inPondCell(i,j))continue;
m4.makeTranslation(i-HALF+0.5,y+0.5,j-HALF+0.5);blocks.setMatrixAt(k,m4);
const top=y===H[i][j],r=hash(i,j)*0.12;
const bxp=i-HALF+0.5,bzp=j-HALF+0.5;
if(MP.inside){if(H[i][j]>=3)col.setHex(top?0xff9ec4:y===1?0xbcaaa4:0xfff3e0);else col.setHex(COUSINS[roomOf(bxp,bzp)][1]).lerp(WHITE,(i+j)%2?0.55:0.68);}
else if(top&&MP.race&&Math.abs(trackE(bxp,bzp)-1)<0.2){const e=trackE(bxp,bzp);if(Math.abs(bxp)<1.1&&bzp<0)col.setHex((i+j)%2?0x111111:0xffffff);else if(Math.abs(e-1)>0.16)col.setHex((Math.floor(Math.atan2(bzp,bxp)*8))%2?0xff3d3d:0xffffff);else col.setHSL(0,0,0.32+r);}
else if(top&&MP.snowcap&&y>=MP.snowcap)col.setHSL(0.58,0.3,0.9+r*0.5);
else if(top&&MP.sea&&y===0)col.setHSL(0.11,0.5,0.66+r);
else if(top&&MP.hub&&Math.hypot(i-HALF+0.5,j-HALF+0.5)>6){const L=MAPS[MAP_ORDER[sectorOf(i-HALF+0.5,j-HALF+0.5)]];col.setHSL(L.top[0]+r*L.jit,L.top[1],L.top[2]+r*0.8);}
else if(top)col.setHSL(MP.top[0]+r*MP.jit,MP.top[1],MP.top[2]+r*0.8);else col.setHSL(MP.side[0],MP.side[1],MP.side[2]+r);
blocks.setColorAt(k,col);k++;}
blocks.count=k;world.add(blocks);blocksMesh=blocks;}
function buildMap(id){toyDuck=null;cousins=[];dog=null;fball=null;roomKids=[];race=null;
mapId=id;MP=MAPS[id];builtMap=id;N=MP.size||44;HALF=N/2;{const k=HALF/22;VSPOTS=[[-16*k,-16*k],[16.5*k,-15.5*k],[-15.5*k,16.5*k]];}{const pd=MP.pond||[8.5,-10.5,4.2];POND.x=pd[0];POND.z=pd[1];POND.r=MP.hub?0:pd[2];}GATES=gatesFor(id);
if(world){scene.remove(world);world.traverse(o=>{if(o.isInstancedMesh){o.material.dispose();o.dispose&&o.dispose();}});}
world=new THREE.Group();scene.add(world);bigSigns.length=0;trees.length=0;mush.length=0;VOLC.length=0;flakes.length=0;
scene.background.setHex(MP.sky);scene.fog.color.setHex(MP.sky);scene.fog.near=MP.fogNear||30;scene.fog.far=MP.fogFar||70;hemi.groundColor.setHex(MP.hemi);
H=[];for(let i=0;i<N;i++){H[i]=[];for(let j=0;j<N;j++)H[i][j]=heightCell(i,j);}
for(let pass=0;pass<(MP.noSmooth?0:MP.max>3?10:4);pass++)for(let i=0;i<N;i++)for(let j=0;j<N;j++) // neighbours differ by at most 1 block
for(const[a,b]of[[1,0],[-1,0],[0,1],[0,-1]]){const ni=i+a,nj=j+b;if(ni<0||nj<0||ni>=N||nj>=N)continue;if(H[i][j]>H[ni][nj]+1)H[i][j]=H[ni][nj]+1;}
blocksMesh=null;mapDamaged=false;buildBlocks();buildPond();buildVehicles();
water=null;if(MP.waterY>-1){water=new THREE.Mesh(new THREE.PlaneGeometry(300,300),new THREE.MeshLambertMaterial({color:MP.water,transparent:!!MP.sea,opacity:MP.sea?0.78:1}));water.rotation.x=-Math.PI/2;water.position.y=MP.waterY;world.add(water);}
volcano=sneezeVolcano(VSPOTS[0][0],VSPOTS[0][1]);makeGrumbo(volcano);trees.push({x:VSPOTS[0][0],z:VSPOTS[0][1],r:3.6,g:volcano,shake:0});
makeVolcano(VSPOTS[1][0],VSPOTS[1][1]);makeVolcano(VSPOTS[2][0],VSPOTS[2][1]);VOLC.forEach(v=>trees.push({x:v.x,z:v.z,r:3.3,g:v.g,shake:0}));
// home: nest, Mama Rex and Princess Pinky
const ny=groundAt(NEST.x,NEST.z);nest.position.set(NEST.x,ny,NEST.z);
mama.R.position.set(NEST.x,ny,NEST.z+2.6);mama.R.rotation.y=Math.atan2(-NEST.x,-(NEST.z+2.6));
princess.R.position.set(PRP.x,ny,PRP.z);princess.R.rotation.y=Math.atan2(-PRP.x,-PRP.z);
prPad.position.set(NEST.x,ny+0.04,NEST.z);prBeam.position.set(NEST.x,ny+8,NEST.z);
trees.push({x:NEST.x,z:NEST.z+2.6,r:1.2,g:mama.R,shake:0},{x:PRP.x,z:PRP.z,r:0.8,g:princess.R,shake:0});trees.forEach(t=>t.keep=true); // volcanoes, Mama and the princess cannot be blasted
DECOR[MP.decor]();buildGates();
spawnAnimals();
(MP.mush||[[6.5,-5.5],[-7.5,6.5],[10.5,9.5],[-11.5,-2.5],[2.5,13.5],[13.5,-9.5],[-4.5,-10.5]]).forEach(([x,z])=>addMush(x,z));
document.querySelectorAll('.maps .mapb').forEach(b=>b.classList.toggle('on',b.dataset.map===id));
}
/* ---- funny animals: each map has its own, and each does a trick when Rexy says hello ---- */
const TOYS=['trex','minidino','horse','zebra','boar','orca','cow','stripedino','shark','longneck','buffalo','tiger','giraffe','elephant','leopard','polarbear','rat','soldier','minicow'];
const TOYNAME={trex:'T-rex',minidino:'little green dino',horse:'horse',zebra:'zebra',boar:'little boar',orca:'orca',cow:'cow',stripedino:'stripy dino',shark:'shark',longneck:'long-neck dino',buffalo:'buffalo',tiger:'tiger',giraffe:'giraffe',elephant:'elephant',leopard:'leopard',polarbear:'polar bear',rat:'rat',soldier:'toy soldier',minicow:'tiny cow'};
const TOY_S=2.0;
function beast(b,o){const {L,W,B,LG,c}=o,lc=o.lc||c,y=LG+B/2;bx(b,W,B,L,c,0,y,0);
const lw=Math.max(0.05,W*0.28);for(const[a,z]of[[-1,1],[1,1],[-1,-1],[1,-1]])bx(b,lw,LG+0.02,lw,lc,a*W*0.32,LG/2,z*L*0.36);
const hs=o.hs||W*0.8,hy=y+B*0.3+(o.hy||0),hz=L/2+hs*0.35+(o.hz||0);bx(b,hs*0.9,hs*0.85,o.hl||hs,o.hc||c,0,hy,hz);
bx(b,hs*0.18,hs*0.18,0.03,0x111111,-hs*0.28,hy+hs*0.15,hz+(o.hl||hs)/2);bx(b,hs*0.18,hs*0.18,0.03,0x111111,hs*0.28,hy+hs*0.15,hz+(o.hl||hs)/2);
if(o.tail!==false)bx(b,0.04,0.04,o.tail||L*0.3,o.tc||c,0,y+B*0.2,-L/2-(o.tail||L*0.3)/2,0,0.5);return {y,hy,hz,hs};}
function toyModel(kind,body){const q=(w,h,d,c,x,y,z,ry,rx,rz)=>bx(body,w,h,d,c,x,y,z,ry,rx,rz);let trick='hop',snd='squeak';
if(kind==='horse'){const r=beast(body,{L:1,W:0.3,B:0.3,LG:0.42,c:0x7b4a2b,hs:0.16,hl:0.34,hy:0.28,hz:0.02});q(0.14,0.36,0.16,0x7b4a2b,0,0.85,0.43,0,0.5);q(0.05,0.3,0.2,0x3b2414,0,0.95,0.38,0,0.5);trick='hop';snd='honk';}
if(kind==='zebra'){beast(body,{L:0.8,W:0.26,B:0.26,LG:0.34,c:0xf2f2f2,hs:0.14,hl:0.28,hy:0.22,tc:0x222222});q(0.12,0.3,0.13,0xf2f2f2,0,0.7,0.35,0,0.5);for(let k=0;k<6;k++)q(0.27,0.27,0.035,0x1a1a1a,0,0.47,-0.32+k*0.13);q(0.05,0.26,0.16,0x1a1a1a,0,0.78,0.31,0,0.5);trick='dash';}
if(kind==='cow'||kind==='minicow'){beast(body,{L:0.85,W:0.34,B:0.32,LG:0.3,c:0xf7f7f7,hs:0.2,hl:0.24,hy:0.05,tc:0x222222});q(0.35,0.2,0.25,0x151515,0,0.5,0.1);q(0.35,0.16,0.18,0x151515,0,0.42,-0.25);q(0.12,0.08,0.14,0xffb3c6,0,0.26,-0.12);q(0.2,0.05,0.04,0xe0d6c0,0,0.66,0.53);if(kind==='minicow')body.scale.setScalar(0.41);trick='spin';snd='honk';}
if(kind==='boar'){beast(body,{L:0.4,W:0.2,B:0.18,LG:0.08,c:0x8a4b2e,hs:0.15,hy:-0.04,tail:0.08});q(0.08,0.07,0.06,0x5a2e1a,0,0.16,0.33);trick='dash';}
if(kind==='buffalo'){beast(body,{L:0.8,W:0.34,B:0.34,LG:0.28,c:0x6b3a22,hs:0.22,hy:-0.06});q(0.3,0.16,0.3,0x5a2e1a,0,0.68,0.18);q(0.4,0.05,0.05,0xe8dcc0,0,0.64,0.5);trick='hop';snd='honk';}
if(kind==='tiger'){beast(body,{L:0.8,W:0.22,B:0.2,LG:0.24,c:0xe89a2c,hs:0.18,tail:0.4});for(let k=0;k<6;k++)q(0.23,0.21,0.03,0x2a1a0a,0,0.35,-0.3+k*0.12);q(0.12,0.1,0.05,0xffffff,0,0.42,0.53);trick='flip';}
if(kind==='leopard'){beast(body,{L:0.6,W:0.17,B:0.16,LG:0.2,c:0xe0a646,hs:0.14,tail:0.32});for(let k=0;k<8;k++)q(0.05,0.05,0.05,0x2a1a0a,(k%2?0.087:-0.087),0.3+(k%3)*0.03,-0.24+k*0.07);q(0.05,0.05,0.05,0x2a1a0a,0,0.37,0);trick='dash';}
if(kind==='polarbear'){beast(body,{L:0.7,W:0.3,B:0.3,LG:0.2,c:0xf3e6b8,hs:0.22,hy:-0.02,tail:0.05});q(0.07,0.07,0.04,0xf3e6b8,-0.08,0.54,0.38);q(0.07,0.07,0.04,0xf3e6b8,0.08,0.54,0.38);q(0.07,0.05,0.04,0x222222,0,0.38,0.54);trick='spin';}
if(kind==='elephant'){const r=beast(body,{L:1.0,W:0.5,B:0.48,LG:0.4,c:0x80858b,hs:0.34,hl:0.3,hy:0.02,tail:0.2});
for(const sd of[-1,1])q(0.04,0.36,0.3,0x8b9096,sd*0.2,r.hy,r.hz-0.1,sd*0.5);q(0.11,0.4,0.11,0x80858b,0,r.hy-0.3,r.hz+0.16);q(0.08,0.2,0.08,0x80858b,0,r.hy-0.52,r.hz+0.2,0,0.4);
for(const sd of[-1,1])q(0.04,0.04,0.28,0xf5f0e0,sd*0.1,r.hy-0.2,r.hz+0.22,0,0.5);trick='hop';snd='honk';}
if(kind==='giraffe'){beast(body,{L:0.7,W:0.22,B:0.26,LG:0.55,c:0xdcb15c,hs:0.13,hl:0.24,hy:0.62,hz:-0.05,tail:0.25});q(0.1,0.7,0.11,0xdcb15c,0,1.15,0.33,0,0.35);
for(let k=0;k<7;k++)q(0.07,0.07,0.07,0x8a5a2a,(k%2?0.1:-0.1),0.72+(k%3)*0.07,-0.27+k*0.09);for(let k=0;k<3;k++)q(0.11,0.06,0.06,0x8a5a2a,0,0.95+k*0.18,0.28+k*0.06);q(0.03,0.08,0.03,0x5a3a1a,-0.04,1.62,0.42);q(0.03,0.08,0.03,0x5a3a1a,0.04,1.62,0.42);trick='spin';}
if(kind==='rat'){beast(body,{L:0.28,W:0.13,B:0.11,LG:0.04,c:0x6d4c32,hs:0.1,hl:0.13,hy:-0.04,tail:0.3,tc:0x8a6a4a});q(0.05,0.05,0.02,0xffb3c6,-0.04,0.17,0.17);q(0.05,0.05,0.02,0xffb3c6,0.04,0.17,0.17);trick='dash';}
if(kind==='orca'){q(0.3,0.3,0.95,0x111111,0,0.2,0);q(0.22,0.12,0.7,0xffffff,0,0.07,0.08);q(0.06,0.08,0.18,0xffffff,-0.16,0.26,0.32);q(0.06,0.08,0.18,0xffffff,0.16,0.26,0.32);q(0.22,0.22,0.2,0x111111,0,0.2,0.55);
q(0.05,0.3,0.18,0x111111,0,0.48,-0.02,0,-0.3);q(0.45,0.04,0.16,0x111111,0,0.2,-0.55);q(0.3,0.04,0.14,0x111111,0,0.08,0.18);trick='flip';snd='honk';}
if(kind==='shark'){q(0.3,0.3,1.0,0x7d8590,0,0.22,0);q(0.22,0.22,0.35,0x7d8590,0,0.22,0.65);q(0.12,0.12,0.18,0x7d8590,0,0.22,0.9);q(0.24,0.08,0.9,0xf1f1f1,0,0.08,0.2);
q(0.05,0.32,0.22,0x6b737d,0,0.5,0.05,0,-0.35);q(0.05,0.36,0.18,0x222222,0,0.32,-0.62,0,-0.5);q(0.5,0.04,0.16,0x6b737d,0,0.12,0.3,0,0,0);q(0.12,0.06,0.03,0x111111,-0.08,0.27,0.78);q(0.12,0.06,0.03,0x111111,0.08,0.27,0.78);trick='spin';}
if(kind==='trex'||kind==='minidino'){const c=kind==='trex'?0x5a3a28:0x5bd94a;q(0.36,0.38,0.55,c,0,0.62,0,0,-0.25);for(const sd of[-1,1]){q(0.12,0.45,0.14,c,sd*0.12,0.25,-0.05);q(0.14,0.05,0.2,c,sd*0.12,0.03,0.02);q(0.05,0.15,0.05,c,sd*0.16,0.62,0.28,0,0.6);}
q(0.3,0.26,0.4,c,0,0.95,0.4);q(0.26,0.08,0.34,c,0,0.78,0.42,0,0.25);q(0.22,0.04,0.04,0xffffff,0,0.86,0.58);q(0.06,0.06,0.03,kind==='trex'?0x7dff6a:0x111111,-0.15,1.0,0.45);q(0.06,0.06,0.03,kind==='trex'?0x7dff6a:0x111111,0.15,1.0,0.45);
q(0.2,0.2,0.4,c,0,0.55,-0.42,0,0.35);q(0.12,0.12,0.35,c,0,0.38,-0.75,0,0.25);if(kind==='minidino')body.scale.setScalar(0.32);trick=kind==='trex'?'hop':'dash';snd=kind==='trex'?'honk':'squeak';}
if(kind==='stripedino'){const c=0x5d4030,s2=0x9de07a;beast(body,{L:0.85,W:0.36,B:0.32,LG:0.2,c,lc:s2,hs:0.18,hy:-0.12,hz:0.18,tail:0.6});q(0.14,0.14,0.22,c,0,0.38,0.5);for(let k=0;k<6;k++)q(0.38,0.06,0.07,s2,0,0.53,-0.3+k*0.12);q(0.1,0.04,0.3,s2,0,0.4,-0.65,0,0.5);trick='hop';snd='honk';}
if(kind==='longneck'){beast(body,{L:0.6,W:0.36,B:0.36,LG:0.32,c:0x6b4a32,hs:0.13,hl:0.2,hy:0.6,hz:0.0,tail:0.45});q(0.12,0.75,0.12,0x2a2420,0,0.95,0.35,0,0.45);trick='spin';snd='honk';}
if(kind==='soldier'){const c=0x5d7a3d;q(0.06,0.14,0.06,c,-0.04,0.07,0);q(0.06,0.14,0.06,c,0.04,0.07,0);q(0.15,0.14,0.08,c,0,0.21,0);q(0.09,0.09,0.09,c,0,0.33,0);q(0.12,0.04,0.12,c,0,0.38,0);q(0.04,0.13,0.04,c,-0.1,0.23,0);q(0.04,0.13,0.04,c,0.1,0.31,0.02,0,0,-1.0);trick='flip';}
body.scale.multiplyScalar(TOY_S);return {trick,snd};}
const ANIMALS={inside:['horse','zebra','cow','tiger','giraffe','elephant','polarbear','longneck'],rain:['frog','duck','frog','bunny'],race:['bunny','duck'],hub:['bunny','duck','crab','lizard','penguin','monkey','squirrel','goat'],toys:TOYS,house:['bunny','squirrel'],meadow:['bunny','duck'],beach:['crab'],desert:['lizard'],snow:['penguin'],jungle:['monkey'],forest:['squirrel','bunny'],mountain:['goat']};
let animals=[],squishN=0,pushN=0;
function makeAnimal(kind){const g=new THREE.Group(),body=new THREE.Group();g.add(body);let trick='hop',snd='squeak';if(TOYNAME[kind]){const t=toyModel(kind,body);return {g,body,kind,trick:t.trick,snd:t.snd,toy:true};}
if(kind==='bunny'){bx(body,0.6,0.5,0.8,0xffffff,0,0.35,0);bx(body,0.45,0.45,0.45,0xffffff,0,0.7,0.4);bx(body,0.12,0.5,0.08,0xffffff,-0.12,1.1,0.35);bx(body,0.12,0.5,0.08,0xffffff,0.12,1.1,0.35);bx(body,0.08,0.3,0.04,0xffb3c6,-0.12,1.1,0.4);bx(body,0.08,0.3,0.04,0xffb3c6,0.12,1.1,0.4);bx(body,0.1,0.08,0.04,0xff80ab,0,0.72,0.64);bx(body,0.25,0.25,0.2,0xffffff,0,0.45,-0.45);trick='hop';}
if(kind==='duck'){bx(body,0.6,0.5,0.8,0xffe14d,0,0.35,0);bx(body,0.4,0.4,0.4,0xffe14d,0,0.75,0.3);bx(body,0.3,0.1,0.25,0xff9800,0,0.7,0.6);trick='spin';snd='honk';}
if(kind==='crab'){bx(body,0.9,0.35,0.6,0xff5722,0,0.35,0);for(const sd of[-1,1]){bx(body,0.08,0.3,0.08,0xff5722,sd*0.2,0.65,0.15);bx(body,0.14,0.14,0.14,0xffffff,sd*0.2,0.82,0.15);bx(body,0.35,0.25,0.3,0xff7043,sd*0.6,0.55,0.3);for(let k=0;k<3;k++)bx(body,0.35,0.06,0.06,0xd84315,sd*0.55,0.2,-0.2+k*0.18,0,0,sd*0.4);}trick='dance';snd='click';}
if(kind==='lizard'){bx(body,0.4,0.25,1.0,0x7cb342,0,0.15,0);bx(body,0.3,0.22,0.35,0x8bc34a,0,0.2,0.62);bx(body,0.15,0.12,0.8,0x7cb342,0,0.12,-0.85);bx(body,0.08,0.1,0.04,0x000000,-0.1,0.28,0.78);bx(body,0.08,0.1,0.04,0x000000,0.1,0.28,0.78);trick='dash';}
if(kind==='penguin'){bx(body,0.6,0.8,0.5,0x263238,0,0.45,0);bx(body,0.45,0.6,0.1,0xffffff,0,0.42,0.25);bx(body,0.18,0.1,0.2,0xff9800,0,0.62,0.33);bx(body,0.2,0.06,0.3,0xff9800,-0.15,0.03,0.1);bx(body,0.2,0.06,0.3,0xff9800,0.15,0.03,0.1);bx(body,0.06,0.06,0.04,0xffffff,-0.1,0.72,0.26);bx(body,0.06,0.06,0.04,0xffffff,0.1,0.72,0.26);trick='slide';snd='honk';}
if(kind==='monkey'){bx(body,0.5,0.6,0.4,0x795548,0,0.45,0);bx(body,0.45,0.42,0.4,0x795548,0,0.95,0.05);bx(body,0.3,0.25,0.06,0xffcc80,0,0.9,0.26);bx(body,0.14,0.18,0.06,0xffcc80,-0.28,0.98,0.05);bx(body,0.14,0.18,0.06,0xffcc80,0.28,0.98,0.05);bx(body,0.08,0.08,0.8,0x6d4c41,0,0.4,-0.5,0,0.7);trick='flip';}
if(kind==='squirrel'){bx(body,0.4,0.45,0.55,0xef6c00,0,0.3,0);bx(body,0.35,0.35,0.35,0xef6c00,0,0.62,0.25);bx(body,0.45,0.8,0.3,0xff9800,0,0.65,-0.35);bx(body,0.06,0.06,0.04,0x000000,-0.08,0.68,0.43);bx(body,0.06,0.06,0.04,0x000000,0.08,0.68,0.43);trick='spin';}
if(kind==='frog'){bx(body,0.7,0.4,0.8,0x66bb6a,0,0.3,0);bx(body,0.6,0.35,0.4,0x81c784,0,0.55,0.25);for(const sd of[-1,1]){bx(body,0.22,0.22,0.2,0xffffff,sd*0.2,0.78,0.3);bx(body,0.1,0.1,0.05,0x111111,sd*0.2,0.78,0.41);bx(body,0.25,0.2,0.45,0x4caf50,sd*0.42,0.15,-0.15);}bx(body,0.4,0.05,0.04,0xc2185b,0,0.45,0.46);trick='hop';snd='boing';}
if(kind==='goat'){bx(body,0.6,0.55,1.0,0xf5f5f5,0,0.75,0);for(const[a,b]of[[-0.2,0.35],[0.2,0.35],[-0.2,-0.35],[0.2,-0.35]])bx(body,0.14,0.5,0.14,0xbdbdbd,a,0.25,b);bx(body,0.4,0.4,0.45,0xf5f5f5,0,1.15,0.55);bx(body,0.08,0.3,0.08,0x8d6e63,-0.12,1.45,0.5,0,-0.4);bx(body,0.08,0.3,0.08,0x8d6e63,0.12,1.45,0.5,0,-0.4);bx(body,0.12,0.2,0.08,0xe0e0e0,0,0.88,0.8);trick='hop';snd='honk';}
return {g,body,kind,trick,snd};}
function spawnAnimals(){animals.forEach(a=>scene.remove(a.g));animals=[];const kinds=ANIMALS[mapId]||['bunny'];
(mapId==='toys'?spots(kinds.length,6,21,41,1.6):spots(8,6,19,41,1.2)).forEach(([x,z],i)=>{const a=makeAnimal(kinds[i%kinds.length]);a.x=x+0.3;a.z=z+0.3;a.face=hash(i,5)*6;a.turn=0;a.t=0;a.cd=0;a.y=0;a.vy=0;if(mapId==='toys'&&(a.kind==='orca'||a.kind==='shark')){a.swim=true;a.ang=a.kind==='orca'?0:Math.PI;}scene.add(a.g);animals.push(a);});}
function animalTrick(a,big){if(a.gone>0||a.fly||a.sq>0)return;if(a.toy&&!big&&playing&&phase==='eggs')say(`The toy ${TOYNAME[a.kind]} says hi, Rexy! 👋`,1400);a.t=big?1.2:1;a.cd=2.5;a.vy=a.trick==='hop'?(big?9:7):a.trick==='flip'?8:a.trick==='spin'?5:2;SFX[a.snd]();burst(a.x,groundAt(a.x,a.z)+1.2,a.z,0xffe14d,5,3);
if(a.trick==='dash'||a.trick==='slide'){a.face=Math.atan2(a.x-player.x,a.z-player.z);}}
const puffs=[];for(let p=0;p<8;p++){const m=new THREE.Mesh(new THREE.BoxGeometry(0.9,0.9,0.9),new THREE.MeshLambertMaterial({color:0xffffff,transparent:true,opacity:0.8}));scene.add(m);puffs.push({m,t:p/8});}
// clouds
const clouds=[];for(let c=0;c<9;c++){const g=new THREE.Group();for(let b=0;b<3;b++){const m=new THREE.Mesh(new THREE.BoxGeometry(3,1.2,2),new THREE.MeshLambertMaterial({color:0xffffff}));m.position.set(b*1.8-1.8,(b%2)*0.5,0);g.add(m);}g.position.set((hash(c,1)-0.5)*70,14+hash(c,2)*6,(hash(c,5)-0.5)*70);scene.add(g);clouds.push(g);}
/* ================= BOUNCY MUSHROOMS ================= */
function addMush(x,z){
if(trees.some(t=>Math.hypot(t.x-x,t.z-z)<t.r+1.3))return;
const g=new THREE.Group();
bx(g,0.7,0.9,0.7,0xfff3e0,0,0.45,0);bx(g,2.1,0.5,2.1,0xff4f6d,0,1.1,0);bx(g,1.4,0.3,1.4,0xff4f6d,0,1.45,0);bx(g,0.12,0.12,0.05,0x222222,-0.15,0.6,0.36);bx(g,0.12,0.12,0.05,0x222222,0.15,0.6,0.36);
for(const[a,b]of[[-0.5,-0.4],[0.5,0.3],[-0.2,0.6],[0.6,-0.6]])bx(g,0.35,0.08,0.35,0xffffff,a,1.62,b);
g.position.set(x,groundAt(x,z),z);world.add(g);mush.push({x,z,g,sq:0,cd:0});
}
/* ================= T-REX (Rexy) ================= */
function makeRex(scale,bodyC,bellyC){
const R=new THREE.Group(),M=c=>new THREE.MeshLambertMaterial({color:c});
const body=new THREE.Mesh(new THREE.BoxGeometry(1.2,1.1,1.6),M(bodyC));body.position.set(0,1.35,0);R.add(body);
const belly=new THREE.Mesh(new THREE.BoxGeometry(0.9,0.8,0.1),M(bellyC));belly.position.set(0,1.25,0.81);R.add(belly);
const headPivot=new THREE.Group();headPivot.position.set(0,1.9,0.55);R.add(headPivot);
const head=new THREE.Mesh(new THREE.BoxGeometry(1.0,0.75,1.1),M(bodyC));head.position.set(0,0.35,0.45);headPivot.add(head);
const jaw=new THREE.Group();jaw.position.set(0,0.05,0.0);headPivot.add(jaw);
const jawM=new THREE.Mesh(new THREE.BoxGeometry(0.9,0.25,1.0),M(bellyC));jawM.position.set(0,-0.05,0.45);jaw.add(jawM);
const mouth=new THREE.Mesh(new THREE.BoxGeometry(0.85,0.05,0.95),M(0xd84343));mouth.position.set(0,0.09,0.46);jaw.add(mouth);
for(const s of[-1,1]){
const eye=new THREE.Mesh(new THREE.BoxGeometry(0.22,0.26,0.1),M(0xffffff));eye.position.set(s*0.28,0.55,1.0);headPivot.add(eye);
const pup=new THREE.Mesh(new THREE.BoxGeometry(0.12,0.16,0.05),M(0x1b1b1b));pup.position.set(s*0.28,0.53,1.06);headPivot.add(pup);
const tooth=new THREE.Mesh(new THREE.BoxGeometry(0.1,0.12,0.08),M(0xffffff));tooth.position.set(s*0.3,0.1,0.95);headPivot.add(tooth);
const cheek=new THREE.Mesh(new THREE.BoxGeometry(0.16,0.1,0.05),M(0xff9eb5));cheek.position.set(s*0.4,0.32,1.0);headPivot.add(cheek);
}
const arms=[];for(const s of[-1,1]){const a=new THREE.Mesh(new THREE.BoxGeometry(0.18,0.4,0.18),M(bodyC));a.geometry.translate(0,-0.18,0);a.position.set(s*0.5,1.6,0.75);R.add(a);arms.push(a);}
const legs=[];for(const s of[-1,1]){const l=new THREE.Group();l.position.set(s*0.38,0.95,0);const lm=new THREE.Mesh(new THREE.BoxGeometry(0.42,0.95,0.55),M(bodyC));lm.position.y=-0.45;l.add(lm);const foot=new THREE.Mesh(new THREE.BoxGeometry(0.46,0.18,0.75),M(bellyC));foot.position.set(0,-0.88,0.12);l.add(foot);R.add(l);legs.push(l);}
const tail=new THREE.Group();tail.position.set(0,1.4,-0.8);R.add(tail);
const t1=new THREE.Mesh(new THREE.BoxGeometry(0.8,0.7,1.0),M(bodyC));t1.position.z=-0.45;tail.add(t1);
const t2=new THREE.Mesh(new THREE.BoxGeometry(0.5,0.45,0.9),M(bodyC));t2.position.set(0,-0.1,-1.2);tail.add(t2);
// back spikes
for(let s=0;s<4;s++){const sp=new THREE.Mesh(new THREE.BoxGeometry(0.12,0.28,0.28),M(0xffb74d));sp.position.set(0,1.98-s*0.08,0.3-s*0.45);sp.rotation.x=0.7;R.add(sp);}
R.traverse(o=>{if(o.isMesh)o.castShadow=true;});
R.scale.setScalar(scale);
return {R,headPivot,jaw,legs,arms,tail};
}
let rex=makeRex(0.8,0x4caf50,0xc5e1a5);scene.add(rex.R);
let rexMats=[],rexCols=[];rex.R.traverse(o=>{if(o.isMesh&&!rexMats.includes(o.material)){rexMats.push(o.material);rexCols.push(o.material.color.getHex());}});
// Princess Pinky: friendly princess dino who gives the trophy
const PR=NEST,PRP={x:6.6,z:5.6};
const princess=makeRex(0.9,0xff8fc8,0xffe3f1);
{const gold=new THREE.MeshLambertMaterial({color:0xffd24d,emissive:0x664400});
const base=new THREE.Mesh(new THREE.BoxGeometry(0.8,0.18,0.8),gold);base.position.set(0,0.82,0.4);princess.headPivot.add(base);
for(const[a,b]of[[-0.3,-0.3],[0.3,-0.3],[-0.3,0.3],[0.3,0.3],[0,0]]){const sp=new THREE.Mesh(new THREE.BoxGeometry(0.16,0.3,0.16),gold);sp.position.set(a,1.0,0.4+b);princess.headPivot.add(sp);}
const gem=new THREE.Mesh(new THREE.BoxGeometry(0.16,0.16,0.06),new THREE.MeshLambertMaterial({color:0x40c4ff,emissive:0x003355}));gem.position.set(0,0.85,0.83);princess.headPivot.add(gem);}
scene.add(princess.R);
const prPad=new THREE.Mesh(new THREE.RingGeometry(1.2,2.2,40),new THREE.MeshBasicMaterial({color:0xff8fc8,transparent:true,opacity:0.6,side:THREE.DoubleSide}));prPad.rotation.x=-Math.PI/2;prPad.position.set(PR.x,groundAt(PR.x,PR.z)+0.04,PR.z);scene.add(prPad);
const prBeam=new THREE.Mesh(new THREE.CylinderGeometry(0.35,0.35,16,10),new THREE.MeshBasicMaterial({color:0xffd24d,transparent:true,opacity:0.45}));prBeam.position.set(PR.x,groundAt(PR.x,PR.z)+8,PR.z);prBeam.visible=false;scene.add(prBeam);
// Mama Rex: a big T-rex with a bow, waiting at the nest
const mama=makeRex(1.45,0xff9f43,0xffe0b2);
{const pink=mat(0xff5c8a);const b1=new THREE.Mesh(geo(0.35,0.3,0.2),pink);b1.position.set(-0.22,0.85,0.2);mama.headPivot.add(b1);const b2=b1.clone();b2.position.x=0.22;mama.headPivot.add(b2);
const k=new THREE.Mesh(geo(0.16,0.16,0.22),pink);k.position.set(0,0.85,0.2);mama.headPivot.add(k);
for(const sd of[-1,1]){const l=new THREE.Mesh(geo(0.06,0.12,0.04),mat(0x222222));l.position.set(sd*0.38,0.73,1.02);l.rotation.z=sd*0.4;mama.headPivot.add(l);}}
scene.add(mama.R);
const nest=new THREE.Group();{for(let k=0;k<14;k++){const a=k/14*Math.PI*2;const m=new THREE.Mesh(geo(0.75,0.45,0.35),mat(k%2?0x8d6e63:0xa1887f));m.position.set(Math.cos(a)*1.4,0.22,Math.sin(a)*1.4);m.rotation.y=-a;nest.add(m);}
const f=new THREE.Mesh(geo(2.4,0.12,2.4),mat(0xd7b46a));f.position.y=0.06;nest.add(f);}
scene.add(nest);
buildMap(mapId);
// guide arrow over Rexy's head
const arrow=new THREE.Group();{const c=new THREE.Mesh(new THREE.ConeGeometry(0.32,0.9,4),new THREE.MeshBasicMaterial({color:0xffe14d}));c.rotation.x=Math.PI/2;arrow.add(c);}scene.add(arrow);
// trophy (shown at the end)
const trophy=new THREE.Group();{const gold=new THREE.MeshLambertMaterial({color:0xffd24d,emissive:0x775500});
const b=new THREE.Mesh(new THREE.BoxGeometry(0.7,0.2,0.7),gold);trophy.add(b);
const st=new THREE.Mesh(new THREE.BoxGeometry(0.2,0.4,0.2),gold);st.position.y=0.3;trophy.add(st);
const cup=new THREE.Mesh(new THREE.CylinderGeometry(0.5,0.25,0.6,8),gold);cup.position.y=0.8;trophy.add(cup);
for(const s of[-1,1]){const h=new THREE.Mesh(new THREE.BoxGeometry(0.15,0.4,0.15),gold);h.position.set(s*0.58,0.85,0);trophy.add(h);}}
trophy.visible=false;scene.add(trophy);
// candies
const CANDY_C=[0xff4f8b,0x4fc3ff,0xffe14d,0x7ee36b,0xb57bff,0xff9a3d];
const candyBall=new THREE.SphereGeometry(0.24,10,8),candyEnd=new THREE.ConeGeometry(0.16,0.26,6);
const candyMats=CANDY_C.map(c=>new THREE.MeshLambertMaterial({color:c,emissive:c,emissiveIntensity:0.2}));
let candies=[],candyN=0;
function makeCandy(x,z,y,fly){
const g=new THREE.Group(),m=candyMats[(Math.random()*candyMats.length)|0];
const b=new THREE.Mesh(candyBall,m);b.scale.set(1.3,1,1);g.add(b);
for(const s of[-1,1]){const e=new THREE.Mesh(candyEnd,m);e.rotation.z=s*Math.PI/2;e.position.x=-s*0.42;g.add(e);}
g.scale.setScalar(1.25);scene.add(g);
const c={g,x,z,y:y==null?groundAt(x,z)+0.5:y,vx:0,vy:0,vz:0,fly:!!fly,alive:true,pull:0,ph:Math.random()*6};candies.push(c);return c;
}
function spawnCandies(){
candies.forEach(c=>scene.remove(c.g));candies=[];let tries=0,n=0;
while(n<30&&tries<600){tries++;const x=(Math.random()-0.5)*(N-6),z=(Math.random()-0.5)*(N-6);
if(trees.some(t=>Math.hypot(t.x-x,t.z-z)<t.r+0.8))continue;if(Math.hypot(x-POND.x,z-POND.z)<POND.r+1)continue;if(nearWall(x,z,1))continue;if(mush.some(m=>Math.hypot(m.x-x,m.z-z)<1.6))continue;
makeCandy(x,z);n++;}
}
let airT=0,loseT=0,zzT=0,pileT=0,pileCd=0,runT=0;
let phase='eggs',sneezeT=18,sneezeWarn=false,talkCd=0;
/* ---- surprise gift boxes with power-ups ---- */
const POWERS={star:{icon:'⭐',name:'Super Star! Nothing can hurt Rexy.',t:9},magnet:{icon:'🧲',name:'Magnet! Eggs and candies come to Rexy.',t:12},
giant:{icon:'🦖',name:'Giant Rexy! Stomp, stomp!',t:10},feather:{icon:'🪶',name:'Feather! Jump again in the air.',t:14}};
let gifts=[],power=null,powerT=0,airJump=false,rexScale=0.8;
const powerEl=document.getElementById('power');
function spawnGifts(){gifts.forEach(g=>scene.remove(g.g));gifts=[];for(let i=0;i<6;i++)placeGift();}
function placeGift(){for(let t=0;t<80;t++){const x=(Math.random()-0.5)*(N-8),z=(Math.random()-0.5)*(N-8);
if(Math.hypot(x,z)<6||nearWall(x,z)||Math.hypot(x-POND.x,z-POND.z)<POND.r+1||Math.hypot(x-NEST.x,z-NEST.z)<5||trees.some(o=>Math.hypot(o.x-x,o.z-z)<o.r+1)||mush.some(m=>Math.hypot(m.x-x,m.z-z)<2)||gifts.some(g=>Math.hypot(g.x-x,g.z-z)<6))continue;
const g=new THREE.Group(),c=[0xff5c8a,0x40c4ff,0xb57bff,0x7ee36b][gifts.length%4];bx(g,0.9,0.9,0.9,c,0,0,0);bx(g,0.95,0.95,0.2,0xffe14d,0,0,0);bx(g,0.2,0.95,0.95,0xffe14d,0,0,0);bx(g,0.3,0.25,0.3,0xffe14d,-0.15,0.55,0,0,0,0.5);bx(g,0.3,0.25,0.3,0xffe14d,0.15,0.55,0,0,0,-0.5);
scene.add(g);gifts.push({g,x,z,alive:true});return;}}
function givePower(k){if(power)endPower();power=k;powerT=POWERS[k].t;airJump=false;SFX.power();say(`${POWERS[k].icon} ${POWERS[k].name}`,2500);
if(k==='star')rexMats.forEach(m=>m.emissive.setHex(0x333300));}
function endPower(){if(power==='star')rexMats.forEach((m,i)=>{m.color.setHex(rexCols[i]);m.emissive.setHex(0);});power=null;if(cur===1)powerEl.hidden=true;}
function defeatBug(b){b.alive=false;b.g.visible=false;b.respawn=mode==='turbo'?10:16;burst(b.x,groundAt(b.x,b.z)+0.6,b.z,0x7b4fd0,16,6);burst(b.x,groundAt(b.x,b.z)+0.6,b.z,0xffe14d,8,5);SFX.pop();makeCandy(b.x,b.z);}
/* ---- one hidden golden egg per map ---- */
let goldEgg=null;
function goldFound(){try{return JSON.parse(localStorage.getItem('trexGold')||'{}');}catch(e){return {};}}
function spawnGold(){if(goldEgg){scene.remove(goldEgg.g);goldEgg=null;}
let best=null;for(let t=0;t<300;t++){const x=(Math.random()-0.5)*(N-5),z=(Math.random()-0.5)*(N-5);if(Math.hypot(x,z)<14)continue;
if(trees.some(o=>Math.hypot(o.x-x,o.z-z)<o.r+0.8)||eggs.some(e=>Math.hypot(e.x-x,e.z-z)<4)||nearWall(x,z,1.5))continue;const h=groundAt(x,z)+Math.random()*0.5;if(!best||h>best.h)best={x,z,h};}
if(!best)return;const g=new THREE.Group();const m=new THREE.Mesh(new THREE.SphereGeometry(0.42,14,10),new THREE.MeshLambertMaterial({color:0xffd24d,emissive:0x886600}));m.scale.set(1,1.3,1);g.add(m);
scene.add(g);goldEgg={g,x:best.x,z:best.z,alive:true};}
/* ---- modes ---- */
const MODES={easy:{dmg:false,spd:1,bugs:0,bugSpd:2.4,erupt:22,bombs:4,txt:'Easy: no danger. Lava only bumps Rexy.'},
adv:{dmg:true,spd:1,bugs:0,bugSpd:3.3,erupt:12,bombs:6,txt:'Adventure: 3 hearts. Lava takes a heart. 10 candies = 1 more heart.'},
turbo:{dmg:true,spd:1.45,bugs:0,bugSpd:4.6,erupt:8,bombs:8,txt:'Turbo: everything is fast! More lava.'}};
let mode='easy';try{const m=localStorage.getItem('trexMode');if(MODES[m])mode=m;}catch(e){}
let M=MODES[mode];
function setMode(m){mode=m;M=MODES[m];try{localStorage.setItem('trexMode',m);}catch(e){}
document.querySelectorAll('.modes .mode[data-m]').forEach(b=>b.classList.toggle('on',b.dataset.m===m));document.getElementById('modeTxt').textContent=M.txt;}
document.querySelectorAll('.modes .mode[data-m]').forEach(b=>b.addEventListener('click',()=>setMode(b.dataset.m)));
let hearts=3,inv=0,runOn=false,fireHeld=false,fireCd=0,roarCd=0;
const heartsEl=document.getElementById('hearts');
/* ---- grumpy beetles ---- */
let bugs=[];
function makeBug(){
const g=new THREE.Group(),Mt=c=>new THREE.MeshLambertMaterial({color:c});
const body=new THREE.Mesh(new THREE.BoxGeometry(1.0,0.6,1.2),Mt(MP.bug));body.position.y=0.5;g.add(body);
const stripe=new THREE.Mesh(new THREE.BoxGeometry(0.12,0.62,1.22),Mt(0x3d2470));stripe.position.y=0.5;g.add(stripe);
const head=new THREE.Mesh(new THREE.BoxGeometry(0.7,0.5,0.4),Mt(0x4a2a8a));head.position.set(0,0.5,0.75);g.add(head);
for(const sd of[-1,1]){
const e=new THREE.Mesh(new THREE.BoxGeometry(0.2,0.2,0.06),Mt(0xffffff));e.position.set(sd*0.18,0.6,0.96);g.add(e);
const pu=new THREE.Mesh(new THREE.BoxGeometry(0.1,0.1,0.04),Mt(0xd32f2f));pu.position.set(sd*0.18,0.58,1.0);g.add(pu);
const br=new THREE.Mesh(new THREE.BoxGeometry(0.26,0.06,0.06),Mt(0x111111));br.position.set(sd*0.18,0.74,0.98);br.rotation.z=sd*0.45;g.add(br);
const an=new THREE.Mesh(new THREE.BoxGeometry(0.05,0.35,0.05),Mt(0x222222));an.position.set(sd*0.2,0.9,0.85);an.rotation.z=sd*0.4;g.add(an);
}
const legs=[];for(let k=0;k<6;k++){const l=new THREE.Mesh(new THREE.BoxGeometry(0.5,0.08,0.1),Mt(0x222222));l.position.set((k%2?1:-1)*0.6,0.25,-0.35+(k>>1)*0.35);g.add(l);legs.push(l);}
g.traverse(o=>{if(o.isMesh)o.castShadow=true;});scene.add(g);return {g,legs};
}
function bugSpot(){for(let i=0;i<60;i++){const a=Math.random()*Math.PI*2,d=8+Math.random()*12,x=Math.cos(a)*d,z=Math.sin(a)*d;
if(Math.abs(x)>HALF-3||Math.abs(z)>HALF-3)continue;if(Math.hypot(x-player.x,z-player.z)<11)continue;if(Math.hypot(x-PR.x,z-PR.z)<5)continue;
if(trees.some(t=>Math.hypot(t.x-x,t.z-z)<t.r+1))continue;return[x,z];}return[12,12];}
function spawnBugs(n){bugs.forEach(b=>scene.remove(b.g));bugs=[];for(let i=0;i<n;i++){const m=makeBug(),[x,z]=bugSpot();bugs.push({g:m.g,legs:m.legs,x,z,face:Math.random()*6,turnT:0,stun:0,alive:true,respawn:0,chase:false,grrCd:0,walk:0});}}
/* ---- fire from the mouth ---- */
let fireballs=[];const fbGeo=new THREE.BoxGeometry(0.5,0.5,0.5),fbMat=new THREE.MeshBasicMaterial({color:0xff7b00}),fbCore=new THREE.MeshBasicMaterial({color:0xffe14d});
function shoot(){
if(!playing||fireCd>0)return;if(ride&&ride.kind==='blaster'){blast();return;}if(saberSwing())return;fireCd=0.22;player.fireT=0.25;
let ang=player.face,best=0.6,ty=null;const cand=bugs.filter(b=>b.alive&&b.stun<=0).map(b=>[b.x,b.z,groundAt(b.x,b.z)+0.6,0]);eggBoxes.forEach(t=>cand.push([t.x,t.z,groundAt(t.x,t.z)+(t.tree?1.5:0.8),0.15]));if(phase==='boss'){const c=boss.g.position;boss.spots.forEach(s=>{if(s.alive&&(s.x-c.x)*(player.x-s.x)+(s.z-c.z)*(player.z-s.z)>0)cand.push([s.x,s.z,s.y,0.2]);});}
let td=1;for(const [x,z,y,bonus] of cand){const d=Math.hypot(x-player.x,z-player.z);if(d>13||d<0.5)continue;let da=Math.atan2(x-player.x,z-player.z)-player.face;while(da>Math.PI)da-=Math.PI*2;while(da<-Math.PI)da+=Math.PI*2;if(Math.abs(da)>0.55)continue;const sc=Math.abs(da)+d*0.01-bonus;if(sc<best){best=sc;ang=player.face+da;ty=y;td=d;}}
const fx=Math.sin(ang),fz=Math.cos(ang);
const g=new THREE.Group();const o=new THREE.Mesh(fbGeo,fbMat);g.add(o);const c=new THREE.Mesh(new THREE.BoxGeometry(0.28,0.28,0.28),fbCore);g.add(c);
g.position.set(player.x+fx*1.3,player.y+1.55,player.z+fz*1.3);scene.add(g);
const vy=ty===null?0:Math.max(-10,Math.min(10,(ty-(player.y+1.55))/Math.max(0.12,(td-1.3)/18)));fireballs.push({g,vx:fx*18,vz:fz*18,vy,life:0.85});SFX.fire();
if(fireballs.length>8){scene.remove(fireballs[0].g);fireballs.shift();}
}
/* ---- lava bombs ---- */
let bombs=[],pools=[];const bombGeo=new THREE.BoxGeometry(0.8,0.8,0.8),bombMat=new THREE.MeshBasicMaterial({color:0xff3d00});
const ringGeo=new THREE.RingGeometry(1.1,1.5,28),poolGeo=new THREE.CylinderGeometry(1.4,1.4,0.12,16),poolMat=new THREE.MeshBasicMaterial({color:0xff5722,transparent:true,opacity:0.85});
function erupt(v){
const top=v.g.position.y+6.2;burst(v.x,top,v.z,0xff5722,22,8);burst(v.x,top,v.z,0x444444,12,5);SFX.boom();
v.g.scale.set(1.12,0.9,1.12);setTimeout(()=>v.g.scale.set(1,1,1),200);
const near=Math.hypot(player.x-v.x,player.z-v.z)<20&&playing;
for(let i=0;i<M.bombs;i++){
let tx,tz;if(i===0&&near){tx=player.x+(Math.random()-0.5)*3;tz=player.z+(Math.random()-0.5)*3;}
else{const a=Math.random()*Math.PI*2,d=4+Math.random()*10;tx=v.x+Math.cos(a)*d;tz=v.z+Math.sin(a)*d;}
const lim=HALF-2;tx=Math.max(-lim,Math.min(lim,tx));tz=Math.max(-lim,Math.min(lim,tz));
const T=1.7,gy=groundAt(tx,tz)+0.4;const m=new THREE.Mesh(bombGeo,bombMat);m.position.set(v.x,top,v.z);scene.add(m);
const ring=new THREE.Mesh(ringGeo,new THREE.MeshBasicMaterial({color:0xff1744,transparent:true,opacity:0.8,side:THREE.DoubleSide}));ring.rotation.x=-Math.PI/2;ring.position.set(tx,gy-0.33,tz);scene.add(ring);
bombs.push({m,ring,x:v.x,y:top,z:v.z,vx:(tx-v.x)/T,vz:(tz-v.z)/T,vy:(gy-top+0.5*18*T*T)/T,tx,tz,gy});
}
if(candies.length<70)for(let i=0;i<2;i++){const a=Math.random()*Math.PI*2,sp=3+Math.random()*4;const c=makeCandy(v.x,v.z,top,true);c.vx=Math.sin(a)*sp;c.vz=Math.cos(a)*sp;c.vy=11;}
if(near)say('The volcano is erupting! Run from the red rings! 🌋',2500);
}
function hurt(fx,fz,why){haptic(90,1);
const dx=player.x-fx,dz=player.z-fz,d=Math.hypot(dx,dz)||1;
if(inv>0||power==='star'||power==='giant')return;player.kx=dx/d*10;player.kz=dz/d*10;player.vy=7;player.onGround=false;inv=1.6;
if(!M.dmg){SFX.bonk();return;}
hearts--;setHUD();SFX.ouch();burst(player.x,player.y+1.5,player.z,0xff5c8a,10,5);
if(hearts<=0)loseGame(why);else say(`Ouch! ${hearts} heart${hearts>1?'s':''} left. ❤️`,1800);
}
function loseGame(why){
playing=false;phase='lost';SFX.lose();say('',1);
document.getElementById('losetxt').textContent=`Too hot! You found ${saved} egg${saved===1?'':'s'}. Try again!`;
loseT=0;setTimeout(()=>{if(phase==='lost')document.getElementById('lose').hidden=false;},1700);
}
let player={x:0,z:0,y:2,vy:0,face:0,speed:0,onGround:true,walkT:0,roarT:0,stepT:0,pass:false};const P1O=player;
// target ring under player shows reach
let reachRing=new THREE.Mesh(new THREE.RingGeometry(1.85,2.05,40),new THREE.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:0.55,side:THREE.DoubleSide}));reachRing.rotation.x=-Math.PI/2;scene.add(reachRing);
let roarWave=new THREE.Mesh(new THREE.RingGeometry(0.9,1.2,48),new THREE.MeshBasicMaterial({color:0xffe14d,transparent:true,opacity:0,side:THREE.DoubleSide}));roarWave.rotation.x=-Math.PI/2;scene.add(roarWave);
/* ---- player 2: a blue dino with its own controls (a game controller, or the arrow keys). It can do all that Rexy can do. ---- */
let twoP=false;try{twoP=localStorage.getItem('trexTwo')==='1';}catch(e){}
let cur=1; // 1 while Rexy (player 1) runs, 2 while player 2 runs
const rex2=makeRex(0.8,0x42a5f5,0xbbdefb);scene.add(rex2.R);
const rex2Mats=[],rex2Cols=[];rex2.R.traverse(o=>{if(o.isMesh&&!rex2Mats.includes(o.material)){rex2Mats.push(o.material);rex2Cols.push(o.material.color.getHex());}});
const tagP1=nameTag('P1','#2e7d32'),tagP2=nameTag('P2','#1565c0');[[rex,tagP1],[rex2,tagP2]].forEach(([r,t])=>{t.position.set(0,4.1,0);t.scale.set(2.6,0.65,1);r.R.add(t);});
const reach2=new THREE.Mesh(reachRing.geometry,new THREE.MeshBasicMaterial({color:0x90caf9,transparent:true,opacity:0.55,side:THREE.DoubleSide}));reach2.rotation.x=-Math.PI/2;scene.add(reach2);
const roar2=new THREE.Mesh(roarWave.geometry,new THREE.MeshBasicMaterial({color:0x90caf9,transparent:true,opacity:0,side:THREE.DoubleSide}));roar2.rotation.x=-Math.PI/2;scene.add(roar2);
function newP2(){return {player:{x:2,z:0,y:2,vy:0,face:0,speed:0,onGround:true,walkT:0,roarT:0,stepT:0,kx:0,kz:0,fireT:0,pass:false,p2:true},rex:rex2,rexMats:rex2Mats,rexCols:rex2Cols,ride:null,chute:false,uw:false,wasUw:false,bubT:0,inv:0,fireCd:0,roarCd:0,airT:0,airJump:false,rexScale:0.8,power:null,powerT:0,jumpHeld:false,jumpPressT:0,jumpQueued:false,roarFired:false,fireHeld:false,runOn:false,roarWave:roar2,reachRing:reach2};}
let S2=newP2();
function getS(){return {player,rex,rexMats,rexCols,ride,chute,uw,wasUw,bubT,inv,fireCd,roarCd,airT,airJump,rexScale,power,powerT,jumpHeld,jumpPressT,jumpQueued,roarFired,fireHeld,runOn,roarWave,reachRing};}
function setS(o){({player,rex,rexMats,rexCols,ride,chute,uw,wasUw,bubT,inv,fireCd,roarCd,airT,airJump,rexScale,power,powerT,jumpHeld,jumpPressT,jumpQueued,roarFired,fireHeld,runOn,roarWave,reachRing}=o);}
function asP2(fn){if(!twoP||cur!==1)return;const s1=getS();setS(S2);cur=2;try{fn();}finally{S2=getS();setS(s1);cur=1;}}
function forP(fn){fn();asP2(fn);}
function showP2(){const tc=document.getElementById('p2ctl');if(tc){tc.hidden=!twoP;document.getElementById('lab1').hidden=!twoP;document.getElementById('lab2').hidden=!twoP;document.body.classList.toggle('two',twoP);}rex2.R.visible=twoP;reach2.visible=twoP;tagP1.visible=twoP;tagP2.visible=twoP;}
function freeP2(){const v=S2.ride;if(v){if(v.driver===S2.player){v.driver=v.passenger||null;if(v.driver)v.driver.pass=false;v.passenger=null;}if(v.passenger===S2.player)v.passenger=null;}S2.ride=null;S2.player.pass=false;}
function placeP2(){if(!twoP)return;freeP2();const p=S2.player,a=player.face-Math.PI/2;let [x,z]=collide(player.x+Math.sin(a)*1.8,player.z+Math.cos(a)*1.8,0.5);p.x=x;p.z=z;p.y=groundAt(x,z);p.vy=0;p.kx=0;p.kz=0;p.face=player.face;p.onGround=true;S2.chute=false;S2.uw=false;S2.wasUw=false;}
function resetP2(){asP2(()=>endPower());freeP2();const keep=S2.player;S2=Object.assign(newP2(),{player:keep});Object.assign(keep,{vy:0,kx:0,kz:0,fireT:0,roarT:0,pass:false});rex2.R.rotation.z=0;placeP2();showP2();}
showP2();
/* ---- two-player games: TAG (always on with 2 players) and a toy foam saber duel. No hearts are ever lost. ---- */
const REX1=rex; // Rexy's model (rex is swapped while player 2 runs)
SFX.swoosh=function(){if(!AC)return;const t=AC.currentTime;noise(t,0.22,0.35,900,1.2);tone(300,t,0.2,'sine',0.08,null,900);};
SFX.tagged=function(){if(!AC)return;const t=AC.currentTime;[659,880,1047,1319].forEach((f,i)=>tone(f,t+i*0.07,0.18,'triangle',0.18));};
function starTex(){const c=document.createElement('canvas');c.width=c.height=128;const x=c.getContext('2d');x.beginPath();for(let i=0;i<10;i++){const r=i%2?26:58,a=-Math.PI/2+i*Math.PI/5;x.lineTo(64+Math.cos(a)*r,66+Math.sin(a)*r);}x.closePath();
x.lineWidth=10;x.strokeStyle='#fff';x.stroke();x.fillStyle='#ffd400';x.fill();x.fillStyle='#5a3b00';x.fillRect(48,58,8,12);x.fillRect(72,58,8,12);return new THREE.CanvasTexture(c);}
// tag: it = which player is IT, blink = seconds the new IT blinks (no tag back), apart = they moved apart since the last tag
const tag={it:2,n:0,blink:0,apart:true,shown:'',star:new THREE.Sprite(new THREE.SpriteMaterial({map:starTex(),transparent:true,depthTest:false}))};
tag.star.scale.setScalar(1.3);tag.star.renderOrder=6;tag.star.visible=false;scene.add(tag.star);
const tagPill=document.createElement('div');tagPill.id='tagpill';tagPill.className='pill';tagPill.hidden=true;document.body.appendChild(tagPill);
// toy sabers: a soft foam blade with a glow, green for Rexy, blue for player 2. They sit in the right hand.
function makeSaber(c){const piv=new THREE.Group();piv.position.set(0,-0.36,0.08);piv.rotation.x=-1.0;
bx(piv,0.16,0.16,0.42,0xeeeeee,0,0,0.1);bx(piv,0.24,0.24,0.08,0x9e9e9e,0,0,0.32);
const blade=new THREE.Mesh(geo(0.22,0.22,1.7),new THREE.MeshBasicMaterial({color:c}));blade.position.z=1.2;piv.add(blade);
const glow=new THREE.Mesh(geo(0.42,0.42,1.85),new THREE.MeshBasicMaterial({color:c,transparent:true,opacity:0.3,depthWrite:false}));glow.position.z=1.2;piv.add(glow);
const tip=new THREE.Mesh(new THREE.SphereGeometry(0.2,10,8),new THREE.MeshBasicMaterial({color:0xffffff}));tip.position.z=2.08;piv.add(tip);piv.userData.c=c;return piv;}
const sabers=[makeSaber(0x39ff6a),makeSaber(0x3fa9ff)];REX1.arms[0].add(sabers[0]);rex2.arms[0].add(sabers[1]);
let saberHits=0;const arcs=[];
// FIRE near the other dino: swing the saber at it instead of a fireball. Returns true when it swung.
function saberSwing(){if(!twoP||ride)return false;const o=cur===1?S2.player:P1O,oRide=vehicles.some(v=>v.driver===o||v.passenger===o);
const dx=o.x-player.x,dz=o.z-player.z,d=Math.hypot(dx,dz);if(d>3.2||Math.abs(o.y-player.y)>2.5||oRide)return false;
fireCd=0.45;player.swingT=0.35;player.face=Math.atan2(dx,dz);SFX.swoosh();
const sc=cur===1?0x39ff6a:0x3fa9ff,arc=new THREE.Mesh(new THREE.RingGeometry(1.1,1.9,20,1,-1.1,2.2),new THREE.MeshBasicMaterial({color:sc,transparent:true,opacity:0.75,side:THREE.DoubleSide,depthWrite:false}));
arc.rotation.set(-Math.PI/2,0,player.face-Math.PI/2);arc.position.set(player.x,player.y+1.5,player.z);scene.add(arc);arcs.push({m:arc,t:0.3});
if((o.bonkCd||0)<=0){o.bonkCd=0.6;o.spinT=0.8;const k=d||1;o.kx=dx/k*7;o.kz=dz/k*7;if(!o.pass){o.vy=5;o.onGround=false;}saberHits++;
burst(o.x,o.y+1.6,o.z,0xffe14d,12,5);burst(o.x,o.y+1.6,o.z,0xffffff,8,4);burst(o.x,o.y+1.6,o.z,sc,6,4);setTimeout(()=>SFX.boing(),90);haptic(40,0.5);say(['Bonk! 💫','Bonk! ✨ Boing!','Bonk! 🌟 Got you!'][saberHits%3],1100);}
return true;}
// each frame after both dinos moved: tag, blinking, the IT star, saber poses, spins
function updateDuel(dt,T){const on=twoP&&playing;tag.star.visible=on;sabers.forEach(s=>s.visible=twoP);
for(let i=arcs.length-1;i>=0;i--){const a=arcs[i];a.t-=dt;a.m.material.opacity=Math.max(0,a.t/0.3)*0.75;a.m.scale.setScalar(1+(0.3-a.t)*1.5);if(a.t<=0){scene.remove(a.m);a.m.geometry.dispose();a.m.material.dispose();arcs.splice(i,1);}}
[[P1O,REX1,sabers[0]],[S2.player,rex2,sabers[1]]].forEach(([p,r,s])=>{p.bonkCd=(p.bonkCd||0)-dt;
if(p.swingT>0){p.swingT-=dt;const k=1-Math.max(0,p.swingT)/0.35;r.arms[0].rotation.x=-1.3;s.rotation.set(-0.1,1.5-k*3,0);}else s.rotation.set(-1.0,0,0);
if(p.spinT>0){p.spinT-=dt;r.R.rotation.y+=(1-Math.max(0,p.spinT)/0.8)*Math.PI*2;}});
tagPill.hidden=!on;if(!on){tag.blink=0;return;}
const A=P1O,B=S2.player,d=Math.hypot(A.x-B.x,A.z-B.z),same=ride&&ride===S2.ride;tag.blink-=dt;if(d>2.6)tag.apart=true;
if(tag.blink<=0&&tag.apart&&!traveling&&!same&&d<1.7&&Math.abs(A.y-B.y)<1.8){tag.it=tag.it===1?2:1;tag.n++;tag.blink=3;tag.apart=false;const q=tag.it===1?A:B;
SFX.tagged();haptic(50,0.6);burst(q.x,q.y+2,q.z,0xffe14d,16,6);burst(q.x,q.y+2,q.z,tag.it===1?0x5ccf6b:0x42a5f5,10,5);say(`🏃 Tag! Player ${tag.it} is IT! Catch Player ${3-tag.it}!`,1800);}
const ip=tag.it===1?A:B,ir=tag.it===1?REX1:rex2;if(tag.blink>0)ir.R.visible=Math.floor(T*10)%2===0;
tag.star.position.set(ip.x,ir.R.position.y+4.9*ir.R.scale.y+Math.abs(Math.sin(T*5))*0.5,ip.z);tag.star.material.rotation=Math.sin(T*3)*0.3;
const txt=`🏃 Tag! P${tag.it} is IT · ${tag.n}`;if(tag.shown!==txt){tag.shown=txt;tagPill.textContent=txt;tagPill.classList.toggle('p2',tag.it===2);}
p2Extras(dt);}
// player 2 extras: its power-up timer on its label, and animals say hi when it walks up (like they do for Rexy)
const p2pw=document.createElement('span');p2pw.style.marginLeft='4px';document.getElementById('lab2').appendChild(p2pw);
function p2Extras(dt){const P=S2.player,t=S2.power?`${POWERS[S2.power].icon} ${Math.ceil(Math.max(0,S2.powerT))}`:'';if(p2pw.textContent!==t)p2pw.textContent=t;
for(const a of animals){if(a.cd<=0&&!(a.t>0)&&!(a.gone>0)&&!a.fly&&!(a.sq>0)&&!a.swim&&Math.hypot(P.x-a.x,P.z-a.z)<2.2)animalTrick(a,false);}}
// while playing, Enter is player 2's jump: it must not also press a focused button (sound, home)
addEventListener('keydown',e=>{if(playing&&(e.code==='Enter'||e.code==='NumpadEnter'))e.preventDefault();});
/* ================= EGGS + BABIES ================= */
const EGG_COLORS=[0xff8a80,0x80d8ff,0xffe57f,0xb9f6ca,0xea80fc,0xffab40,0x84ffff,0xff80ab,0xccff90,0xb388ff];
const eggGeo=new THREE.SphereGeometry(0.45,16,12);
let eggs=[],babies=[];
function spawnEggs(){
eggs.forEach(e=>scene.remove(e.g));babies.forEach(b=>scene.remove(b.r.R));eggs=[];babies=[];
const spots=[];let tries=0;
while(spots.length<10&&tries<500){tries++;
const a=hash(tries,21)*Math.PI*2+gameSeed,d=5+hash(tries,22+gameSeed)*13;const x=Math.cos(a)*d,z=Math.sin(a)*d;
if(Math.abs(x)>HALF-3||Math.abs(z)>HALF-3)continue;
if(trees.some(t=>Math.hypot(t.x-x,t.z-z)<t.r+1))continue;
if(Math.hypot(x+16,z+16)<5)continue;if(Math.hypot(x-POND.x,z-POND.z)<POND.r+1.5)continue;
if(VOLC.some(v=>Math.hypot(v.x-x,v.z-z)<5.5))continue;
if(mush.some(m=>Math.hypot(m.x-x,m.z-z)<2.5))continue;
if(Math.hypot(x-PR.x,z-PR.z)<5||Math.hypot(x,z)<4)continue;
if(spots.some(s=>Math.hypot(s.x-x,s.z-z)<4))continue;if(nearWall(x,z,1.5))continue;spots.push({x,z});
}
spots.forEach((s,i)=>{
const g=new THREE.Group();const e=new THREE.Mesh(eggGeo,new THREE.MeshLambertMaterial({color:EGG_COLORS[i],emissive:EGG_COLORS[i],emissiveIntensity:0.25}));e.scale.set(1,1.3,1);e.castShadow=true;g.add(e);
for(let d=0;d<3;d++){const dot=new THREE.Mesh(new THREE.BoxGeometry(0.14,0.14,0.05),new THREE.MeshLambertMaterial({color:0xffffff}));dot.position.set(Math.cos(d*2.1)*0.3,0.1+d*0.18-0.2,Math.sin(d*2.1)*0.3+0.12);g.add(dot);}
const ring=new THREE.Mesh(new THREE.RingGeometry(0.7,0.95,32),new THREE.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:0.7,side:THREE.DoubleSide}));ring.rotation.x=-Math.PI/2;ring.position.y=-0.55;g.add(ring);
// tall light beam so eggs are seen from far away
const beam=new THREE.Mesh(new THREE.CylinderGeometry(0.12,0.12,8,8),new THREE.MeshBasicMaterial({color:EGG_COLORS[i],transparent:true,opacity:0.35}));beam.position.y=4;g.add(beam);
g.position.set(s.x,groundAt(s.x,s.z)+0.65,s.z);scene.add(g);
eggs.push({g,x:s.x,z:s.z,c:EGG_COLORS[i],alive:true,ring,beam,phase:i});
});
hideEggs();
}
// 3 eggs in each land hide inside a mystery crate or a hollow tree. A fireball or a blaster ball opens it.
let eggBoxes=[];
function crateModel(){const g=new THREE.Group(),W=0xc68642,D=0x8d5524,Y=0xffe14d;bx(g,1.6,1.6,1.6,W,0,0.8,0);
for(const[a,b]of[[-1,-1],[1,-1],[-1,1],[1,1]]){bx(g,0.18,1.66,0.18,D,a*0.75,0.8,b*0.75);bx(g,1.66,0.18,0.18,D,0,0.08+(b>0?1.5:0),a*0.75);bx(g,0.18,0.18,1.66,D,a*0.75,0.08+(b>0?1.5:0),0);}
for(const sd of[-1,1]){const q=new THREE.Group();q.position.set(0,0.85,sd*0.82);q.rotation.y=sd>0?0:Math.PI;g.add(q);[[0,0.38],[0.18,0.3],[0.2,0.14],[0.08,0.02],[0,-0.1],[0,-0.34]].forEach(([x,y])=>bx(q,0.16,0.14,0.06,Y,x,y,0));}
return g;}
function eggTreeModel(c){const g=new THREE.Group();bx(g,0.9,2.4,0.9,0x6d4c41,0,1.2,0);bx(g,0.5,0.6,0.1,0x3e2723,0,1.4,0.46);
const e=new THREE.Mesh(eggGeo,mat(c));e.scale.set(0.45,0.55,0.45);e.position.set(0,1.42,0.5);g.add(e);
bx(g,3.0,1.8,3.0,0x43a047,0,3.2,0);bx(g,2.0,0.9,2.0,0x66bb6a,0,4.4,0);bx(g,0.4,0.4,0.4,0xff5c8a,1.2,3.6,1.3);bx(g,0.4,0.4,0.4,0xffe14d,-1.3,2.9,1.1);return g;}
function hideEggs(){eggBoxes.forEach(t=>{scene.remove(t.g);const k=trees.indexOf(t);if(k>=0)trees.splice(k,1);});eggBoxes=[];
if(MP.hub||!eggs.length)return;
[1,4,7].forEach((k,n)=>{const e=eggs[k];if(!e)return;e.hidden=true;e.g.children.forEach(ch=>{if(ch!==e.beam)ch.visible=false;});
const tree=n===1,g=tree?eggTreeModel(e.c):crateModel();g.position.set(e.x,groundAt(e.x,e.z),e.z);g.rotation.y=Math.atan2(-e.x,-e.z);scene.add(g);
const t={x:e.x,z:e.z,r:tree?0.7:0.95,h:tree?4.8:1.8,g,shake:0,egg:e,tree};trees.push(t);eggBoxes.push(t);});}
function openBox(t){const i=trees.indexOf(t);if(i>=0)trees.splice(i,1);const k=eggBoxes.indexOf(t);if(k>=0)eggBoxes.splice(k,1);scene.remove(t.g);
const e=t.egg,gy=groundAt(t.x,t.z);e.hidden=false;e.g.children.forEach(ch=>ch.visible=true);e.pop=1;
burst(t.x,gy+1.2,t.z,t.tree?0x43a047:0xc68642,22,7);burst(t.x,gy+1.5,t.z,0xffe14d,14,6);burst(t.x,gy+1.2,t.z,e.c,10,5);SFX.pop();SFX.gift();haptic(50,0.7);
say(t.tree?'🌳 Pop! An egg fell out of the tree! 🥚':'📦 Crash! An egg was in the box! 🥚',2200);}
function eggBoxHint(){if(!playing)return;for(const t of eggBoxes){const d=Math.hypot(player.x-t.x,player.z-t.z);if(d<6&&!t.told){t.told=true;say(t.tree?'🌳 An egg is stuck in this tree! Shoot it with FIRE 🔥':'📦 An egg is inside this box! Shoot it with FIRE 🔥',2600);}}}
let gameSeed=0;
/* ================= PARTICLES ================= */
const parts=[];const pGeo=new THREE.BoxGeometry(0.18,0.18,0.18);
const zTex=(()=>{const c=document.createElement('canvas');c.width=c.height=64;const x=c.getContext('2d');x.font='900 52px sans-serif';x.textAlign='center';x.textBaseline='middle';x.lineWidth=8;x.strokeStyle='#fff';x.strokeText('Z',32,34);x.fillStyle='#4f7bff';x.fillText('Z',32,34);return new THREE.CanvasTexture(c);})();
const zzs=[];function zzz(x,y,z){const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:zTex,transparent:true}));sp.position.set(x,y,z);sp.scale.setScalar(0.6);scene.add(sp);zzs.push({sp,t:0,ph:Math.random()*6});SFX.snore&&zzs.length%2&&SFX.snore();}
/* ---- Grumbo, the grumpy volcano boss: tickle 3 glowing spots with fire ---- */
function makeGrumbo(v){
v.rotation.y=Math.PI/4; // front looks at the middle of the map
const face=new THREE.Group();v.add(face);
const white=0xffffff,dark=0x3b2a22;
const eyes=[],lids=[];
[-0.95,0.95].forEach(x=>{const e=new THREE.Group();face.add(e);e.position.set(x,3.15,2.24);
bx(e,0.9,0.7,0.08,white,0,0,0);const pu=bx(e,0.36,0.36,0.1,0x111111,0,-0.08,0.03);eyes.push(pu);
const lid=bx(e,0.96,0.76,0.14,0x8d6e63,0,0,0.05);lids.push(lid);});
const brows=[bx(face,0.9,0.18,0.12,dark,-0.95,3.6,2.27),bx(face,0.9,0.18,0.12,dark,0.95,3.6,2.27)];
brows[0].rotation.z=-0.35;brows[1].rotation.z=0.35;
const grump=bx(face,1.4,0.2,0.12,dark,0,2.62,2.27);
const happy=new THREE.Group();face.add(happy);bx(happy,1.2,0.22,0.12,dark,0,2.55,2.27);bx(happy,0.25,0.22,0.12,dark,-0.7,2.72,2.27);bx(happy,0.25,0.22,0.12,dark,0.7,2.72,2.27);happy.visible=false;
const cheeks=[bx(face,0.4,0.25,0.1,0xff8aa8,-1.6,2.75,2.25),bx(face,0.4,0.25,0.1,0xff8aa8,1.6,2.75,2.25)];cheeks.forEach(c=>c.visible=false);
const spots=[];v.updateMatrixWorld(true);
[[0,1.8,2.9,0],[-2.9,1.8,0,1],[2.9,1.8,0,2]].forEach(([x,y,z,k])=>{
const m=new THREE.Mesh(geo(1.1,1.1,0.25),new THREE.MeshBasicMaterial({color:0xff4fa3}));m.position.set(x,y,z);if(k)m.rotation.y=Math.PI/2;v.add(m);
const glow=new THREE.Mesh(geo(1.5,1.5,0.12),new THREE.MeshBasicMaterial({color:0xffe14d,transparent:true,opacity:0.6}));glow.position.copy(m.position);glow.rotation.y=m.rotation.y;v.add(glow);
v.updateMatrixWorld(true);const w=m.getWorldPosition(new THREE.Vector3());
spots.push({m,glow,x:w.x,y:w.y,z:w.z,alive:true});});
boss={g:v,face,eyes,lids,brows,grump,happy,cheeks,spots,hits:0,awake:false,lobT:3,wig:0};resetBoss();
}
function resetBoss(){if(!boss)return;boss.hits=0;boss.awake=false;boss.lobT=3;boss.wig=0;boss.lids.forEach(l=>l.visible=true);boss.brows.forEach(b=>b.visible=false);boss.grump.visible=true;boss.happy.visible=false;boss.cheeks.forEach(c=>c.visible=false);boss.spots.forEach(s=>{s.alive=true;s.m.visible=false;s.glow.visible=false;});}
function wakeBoss(){phase='boss';boss.awake=true;boss.lobT=3.5;boss.lids.forEach(l=>l.visible=false);boss.brows.forEach(b=>b.visible=true);boss.spots.forEach(s=>{s.m.visible=true;s.glow.visible=true;});SFX.rumble();setTimeout(()=>SFX.grumble(),300);
say(`Mama Rex: Oh no! Grumbo the volcano woke up grumpy! Tickle his 3 pink spots with FIRE${M.dmg?'':' or a ROAR'}! 🌋🔥`,0);}
function tickle(s){if(!s.alive||phase!=='boss')return;s.alive=false;s.m.visible=false;s.glow.visible=false;boss.hits++;boss.wig=1;SFX.giggle();
burst(s.x,s.y,s.z,0xff4fa3,18,6);burst(s.x,s.y,s.z,0xffe14d,10,5);
const left=3-boss.hits;if(left>0){say(`Grumbo: Hee hee hee! That tickles! ${left} more spot${left>1?'s':''}! 🤭`,2600);return;}
boss.awake=false;boss.brows.forEach(b=>b.visible=false);boss.grump.visible=false;boss.happy.visible=true;boss.cheeks.forEach(c=>c.visible=true);
setTimeout(()=>{SFX.choo();const vg=boss.g.position;burst(vg.x,vg.y+6.5,vg.z,0xffffff,30,9);
for(let i=0;i<24;i++){const a=Math.PI/4+(Math.random()-0.5)*2.4,sp=3+Math.random()*7;const c=makeCandy(vg.x,vg.z,vg.y+6.5,true);c.vx=Math.sin(a)*sp;c.vz=Math.cos(a)*sp;c.vy=11+Math.random()*6;}},700);
phase='princess';prBeam.visible=true;SFX.win();
say('Grumbo laughed so much he sneezed a CANDY FOUNTAIN! 🍬 Now bring the babies home to Mama Rex. Follow the gold light! 🏠',0);}
function lob(){const vg=boss.g.position,top=vg.y+6.2;const T=1.6;
const tx=player.x+player.kx*0+(Math.random()-0.5)*2.5,tz=player.z+(Math.random()-0.5)*2.5,gy=groundAt(tx,tz)+0.4;
const m=new THREE.Mesh(bombGeo,bombMat);m.position.set(vg.x,top,vg.z);scene.add(m);
const ring=new THREE.Mesh(ringGeo,new THREE.MeshBasicMaterial({color:0xff1744,transparent:true,opacity:0.8,side:THREE.DoubleSide}));ring.rotation.x=-Math.PI/2;ring.position.set(tx,gy-0.33,tz);scene.add(ring);
bombs.push({m,ring,x:vg.x,y:top,z:vg.z,vx:(tx-vg.x)/T,vz:(tz-vg.z)/T,vy:(gy-top+0.5*18*T*T)/T,tx,tz,gy});SFX.boom();boss.wig=0.5;burst(vg.x,top,vg.z,0xff5722,8,4);}
function burst(x,y,z,c,n,spd){for(let i=0;i<n;i++){const m=new THREE.Mesh(pGeo,new THREE.MeshBasicMaterial({color:c}));m.position.set(x,y,z);scene.add(m);parts.push({m,vx:(Math.random()-0.5)*spd,vy:Math.random()*spd*0.8+2,vz:(Math.random()-0.5)*spd,life:1});}}
/* ================= INPUT ================= */
const keys={};let joy={x:0,y:0},jumpHeld=false,jumpPressT=0,jumpQueued=false,roarFired=false;
addEventListener('keydown',e=>{keys[e.code]=true;if(e.code==='Space'&&!e.repeat){pressJump();}if((e.code==='KeyF'||e.code==='KeyE'||(!twoP&&e.code==='Enter'))&&!e.repeat){fireHeld=true;shoot();}if(e.code==='KeyR'&&!e.repeat&&playing&&roarCd<=0){roarCd=0.8;doRoar();}if(['Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Slash','Period'].includes(e.code))e.preventDefault();});
addEventListener('keyup',e=>{keys[e.code]=false;if(e.code==='Space')releaseJump();if(e.code==='KeyF'||e.code==='KeyE'||(!twoP&&e.code==='Enter'))fireHeld=false;});
addEventListener('blur',()=>{for(const k in keys)keys[k]=false;if(jumpHeld)releaseJump();fireHeld=false;});
const jumpBtn=document.getElementById('jump'),ringEl=document.getElementById('ring');
function pressJump(){if(!playing)return;jumpHeld=true;jumpPressT=performance.now();jumpQueued=true;roarFired=false;if(cur===1)jumpBtn.classList.add('down');}
function releaseJump(){jumpHeld=false;if(cur===1){jumpBtn.classList.remove('down');ringEl.style.opacity=0;}}
jumpBtn.addEventListener('pointerdown',e=>{e.preventDefault();try{jumpBtn.setPointerCapture(e.pointerId);}catch(_){}pressJump();});
jumpBtn.addEventListener('pointerup',releaseJump);jumpBtn.addEventListener('pointercancel',releaseJump);
const fadeEl=document.getElementById('fade'),fireBtn=document.getElementById('fire'),runBtn=document.getElementById('run'),rideBtn=document.getElementById('ride'),uwTint=document.getElementById('uwtint');
rideBtn.addEventListener('pointerdown',e=>{e.preventDefault();e.stopPropagation();toggleRide();});
addEventListener('keydown',e=>{if(e.code==='KeyV'&&!e.repeat)toggleRide();});
fireBtn.addEventListener('pointerdown',e=>{e.preventDefault();try{fireBtn.setPointerCapture(e.pointerId);}catch(_){}fireHeld=true;fireBtn.classList.add('down');shoot();});
const fireUp=()=>{fireHeld=false;fireBtn.classList.remove('down');};fireBtn.addEventListener('pointerup',fireUp);fireBtn.addEventListener('pointercancel',fireUp);
runBtn.addEventListener('pointerdown',e=>{e.preventDefault();runOn=!runOn;runBtn.classList.toggle('on',runOn);runBtn.textContent=runOn?'FAST!':'RUN';});
// Touch anywhere that is not a button: the first finger is a floating joystick (swipe to walk),
// a second finger tap on open screen jumps (hold = roar). Buttons keep their own fingers, so all work together.
const kb=document.getElementById('knobBase'),knob=document.getElementById('knob');let stickId=null,sx=0,sy=0,tapJumpId=null;
const kb2=document.getElementById('knobBase2'),knob2=document.getElementById('knob2');let stick2Id=null,sx2=0,sy2=0;const joy2={x:0,y:0},t2={jump:false,fire:false,run:false,ride:false};
function freeSpot(e){return !e.target.closest('button,.screen,#hud,a');}
document.addEventListener('pointerdown',e=>{
if(!playing||!freeSpot(e))return;
if(twoP&&e.clientX<innerWidth/2){if(stick2Id===null){stick2Id=e.pointerId;sx2=e.clientX;sy2=e.clientY;kb2.style.display='block';kb2.style.left=sx2+'px';kb2.style.top=sy2+'px';moveStick(e);}return;}
if(stickId===null){stickId=e.pointerId;sx=e.clientX;sy=e.clientY;kb.style.display='block';kb.style.left=sx+'px';kb.style.top=sy+'px';moveStick(e);}
else if(tapJumpId===null&&e.pointerType!=='mouse'){tapJumpId=e.pointerId;pressJump();}
});
function moveStick(e){const max=55;if(e.pointerId===stick2Id){let dx=e.clientX-sx2,dy=e.clientY-sy2;const d=Math.hypot(dx,dy);if(d>max){dx*=max/d;dy*=max/d;}knob2.style.transform=`translate(${dx}px,${dy}px)`;joy2.x=dx/max;joy2.y=dy/max;return;}
if(e.pointerId!==stickId)return;let dx=e.clientX-sx,dy=e.clientY-sy;const d=Math.hypot(dx,dy);if(d>max){dx*=max/d;dy*=max/d;}knob.style.transform=`translate(${dx}px,${dy}px)`;joy.x=dx/max;joy.y=dy/max;}
document.addEventListener('pointermove',moveStick);
function endStick(e){if(e.pointerId===stick2Id){stick2Id=null;joy2.x=joy2.y=0;kb2.style.display='none';knob2.style.transform='';return;}if(e.pointerId===tapJumpId){tapJumpId=null;releaseJump();return;}if(e.pointerId!==stickId)return;stickId=null;joy.x=joy.y=0;kb.style.display='none';knob.style.transform='';}
// player 2 buttons (left side)
const jump2B=document.getElementById('jump2'),fire2B=document.getElementById('fire2'),run2B=document.getElementById('run2'),ride2B=document.getElementById('ride2');
function hold2(b,k){b.addEventListener('pointerdown',e=>{e.preventDefault();e.stopPropagation();try{b.setPointerCapture(e.pointerId);}catch(_){}t2[k]=true;b.classList.add('down');});const up=()=>{t2[k]=false;b.classList.remove('down');};b.addEventListener('pointerup',up);b.addEventListener('pointercancel',up);}
hold2(jump2B,'jump');hold2(fire2B,'fire');
run2B.addEventListener('pointerdown',e=>{e.preventDefault();e.stopPropagation();t2.run=!t2.run;run2B.classList.toggle('on',t2.run);run2B.textContent=t2.run?'FAST!':'RUN';});
ride2B.addEventListener('pointerdown',e=>{e.preventDefault();e.stopPropagation();t2.ride=true;});
document.addEventListener('pointerup',endStick);document.addEventListener('pointercancel',endStick);
/* ================= GAME FLOW ================= */
let playing=false,saved=0,startTime=0,camYaw=0;
const eggsEl=document.getElementById('eggs'),hint=document.getElementById('hint');
const candyEl=document.getElementById('candy');
function setHUD(){eggsEl.textContent=MP.hub?`⭐ ${Object.keys(mapStars()).length} / ${MAP_ORDER.length}`:`🥚 ${saved} / 10`;candyEl.textContent=`🍬 ${candyN}`;heartsEl.hidden=!M.dmg;heartsEl.textContent=hearts>0?`❤️ ${hearts}`:'💔';}
function startGame(){
initAudio();resetRace();wx.t=0;wx.ph='';if(mapDamaged)buildMap(mapId);blasts.forEach(b=>scene.remove(b.m));blasts=[];
document.getElementById('start').hidden=true;document.getElementById('win').hidden=true;document.getElementById('lose').hidden=true;
hearts=3;inv=0;rexScale=0.8;airT=0;player.kx=0;player.kz=0;player.fireT=0;fireballs.forEach(f=>scene.remove(f.g));fireballs=[];bombs.forEach(b=>{scene.remove(b.m);scene.remove(b.ring);});bombs=[];pools.forEach(p=>scene.remove(p.m));pools=[];
VOLC.forEach((v,i)=>{v.t=M.erupt*0.8+i*5;v.warn=false;});
setTimeout(()=>{if(!AC||AC.state!=='running')say('Tap the screen once to turn on the sound. 🔊',5000);},900);
player.x=0;player.z=0;player.y=groundAt(0,0);player.vy=0;player.face=0;saved=0;candyN=0;phase='eggs';sneezeT=18;sneezeWarn=false;talkCd=4;resetBoss();zzs.forEach(z=>scene.remove(z.sp));zzs.length=0;pileT=0;pileCd=0;runT=0;rex.R.rotation.z=0;trophy.visible=false;prBeam.visible=false;if(MP.hub){candies.forEach(c=>scene.remove(c.g));candies=[];}else{spawnCandies();for(let k=0;k<7;k++){const a=k/7*Math.PI*2;makeCandy(POND.x+Math.cos(a)*2.2,POND.z+Math.sin(a)*2.2);}}resetVehicles();resetFamily();chute=false;rideHint=false;player.pass=false;resetP2();setHUD();
gameSeed=(gameSeed+1.7)%6.28;spawnEggs();spawnBugs(M.bugs);spawnGifts();spawnGold();if(MP.hub){eggs.forEach(e=>scene.remove(e.g));eggs=[];if(goldEgg){scene.remove(goldEgg.g);goldEgg=null;}phase='hub';}endPower();setTimeout(()=>{if(playing&&goldEgg&&phase==='eggs')say('Mama Rex: Psst! A golden egg is hidden on this map. Look up high! ✨',4000);},25000);playing=true;startTime=performance.now();
if(MP.hub){const n=Object.keys(mapStars()).length;say(n>=MAP_ORDER.length?`🏝️ You saved all ${MAP_ORDER.length} lands! 👑 Mama Rex is so proud of you!`:`🏝️ Rexy's Island! Mama Rex: My eggs rolled into all the lands. Walk through a gate to go there! (${n} of ${MAP_ORDER.length} ⭐)`,6000);SFX.hello();setHUD();return;}
say(MP.rain?'🌧️ Rain Land! It is raining. When the rain stops, look up! 🌠 Mama Rex: Please find my 10 eggs!':MP.inside?'🛏️ Inside the Blue House! 9 cousins have 9 rooms. Go and visit them! Mama Rex: Please find my 10 eggs!':MP.race?'🏁 Race Track! Drive a car to the yellow ring at the start to race. Mama Rex: Please find my 10 eggs!':`${MP.icon} ${MP.name}! Mama Rex: Please find my 10 eggs! Follow the light beams. 🥚`,6000);SFX.hello();
setTimeout(()=>{if(playing&&phase==='eggs'&&MP.decor!=='house')say('🏝️ The gates near the start go back to the island and to the lands next door.',4000);},13000);
if(dog)setTimeout(()=>{if(playing&&phase==='eggs')say('🏡 Welcome to the Blue House! 9 cousins are hiding. Can you find them? 🙈 Kick the red ball for Azizam! 🐶',6000);},6500);
}
document.getElementById('go').addEventListener('click',startIsland);
/* ---- full screen: button, F key, controller Create button ---- */
const fsBtn=document.getElementById('fs'),fsRoot=document.documentElement;
const fsOn=()=>!!(document.fullscreenElement||document.webkitFullscreenElement);
const fsCan=!!(fsRoot.requestFullscreen||fsRoot.webkitRequestFullscreen)&&(document.fullscreenEnabled!==false||document.webkitFullscreenEnabled);
function toggleFull(){try{if(fsOn()){(document.exitFullscreen||document.webkitExitFullscreen).call(document);}else{const p=(fsRoot.requestFullscreen||fsRoot.webkitRequestFullscreen).call(fsRoot);if(p&&p.catch)p.catch(()=>{});}}catch(e){}setTimeout(resize,300);}
fsBtn.hidden=!fsCan;fsBtn.addEventListener('click',e=>{e.stopPropagation();toggleFull();});
['fullscreenchange','webkitfullscreenchange'].forEach(ev=>document.addEventListener(ev,()=>{fsBtn.textContent=fsOn()?'🗗':'⛶';setTimeout(resize,100);}));
{let fsPad=false;setInterval(()=>{let d=false;try{for(const gp of(navigator.getGamepads?navigator.getGamepads():[]))if(gp&&gp.buttons&&gp.buttons[8]&&gp.buttons[8].pressed)d=true;}catch(e){}if(d&&!fsPad&&fsCan)toggleFull();fsPad=d;},120);}
function setTwo(on){twoP=!!on;try{localStorage.setItem('trexTwo',twoP?'1':'0');}catch(e){}document.getElementById('p1b').classList.toggle('on',!twoP);document.getElementById('p2b').classList.toggle('on',twoP);
if(!twoP)freeP2();else if(playing)placeP2();showP2();}
document.getElementById('p1b').addEventListener('click',()=>setTwo(false));document.getElementById('p2b').addEventListener('click',()=>setTwo(true));setTwo(twoP);
function goHome(){if(document.getElementById('start').hidden===false||traveling)return;if(!MP.hub&&phase!=='lost'){travel('hub',mapId);return;}playing=false;ride=null;player.pass=false;freeP2();S2.jumpHeld=false;rideBtn.hidden=true;uwTint.style.opacity=0;phase='home';endPower();say('',1);jumpHeld=false;fireHeld=false;runOn=false;runBtn.classList.remove('on');runBtn.textContent='RUN';
stickId=null;tapJumpId=null;joy.x=joy.y=0;kb.style.display='none';stick2Id=null;joy2.x=joy2.y=0;kb2.style.display='none';Object.assign(t2,{jump:false,fire:false,run:false,ride:false});run2B.classList.remove('on');run2B.textContent='RUN';arrow.visible=false;prBeam.visible=false;
document.getElementById('win').hidden=true;document.getElementById('lose').hidden=true;document.getElementById('start').hidden=false;drawMaps();}
document.getElementById('home').addEventListener('click',e=>{e.stopPropagation();goHome();});
addEventListener('keydown',e=>{if((e.code==='Escape'||e.code==='KeyH'||e.keyCode===461||e.keyCode===10009)&&!e.repeat){if(e.keyCode===461||e.keyCode===10009)e.preventDefault();goHome();}});
/* TV remote colour keys: red = fire, green = jump (hold = roar), yellow = run, blue = get in / out */
addEventListener('keydown',e=>{const k=e.keyCode;if(k<403||k>406)return;e.preventDefault();if(e.repeat)return;if(k===403){fireHeld=true;shoot();}if(k===404)pressJump();if(k===405){runOn=!runOn;runBtn.classList.toggle('on',runOn);runBtn.textContent=runOn?'FAST!':'RUN';}if(k===406)toggleRide();});
addEventListener('keyup',e=>{const k=e.keyCode;if(k===403)fireHeld=false;if(k===404)releaseJump();});
document.getElementById('again').addEventListener('click',startGame);
document.getElementById('retry').addEventListener('click',startGame);
document.getElementById('toeasy').addEventListener('click',()=>{setMode('easy');startGame();});
setMode(mode);
const mapsEl=document.querySelector('.maps');
function mapStars(){try{return JSON.parse(localStorage.getItem('trexMapsWon')||'{}');}catch(e){return {};}}
function drawMaps(){const st=mapStars();mapsEl.innerHTML='';MAP_ORDER.forEach(id=>{const b=document.createElement('button');b.className='mapb'+(id===mapId?' on':'');b.dataset.map=id;const gd=goldFound();b.innerHTML=`<span class="mi">${MAPS[id].icon}</span><span>${MAPS[id].name}${st[id]?' ⭐':''}${gd[id]?' ✨':''}</span>`;b.addEventListener('click',()=>{setMap(id);startGame();});mapsEl.appendChild(b);});}
function setMap(id){if(playing)return;if(builtMap!==id)buildMap(id);drawMaps();}
function nextMap(){travel('hub',mapId);}
document.getElementById('next').addEventListener('click',nextMap);
drawMaps();
function addHat(b,i){const h=new THREE.Group(),k=i%5;
if(k===0){bx(h,0.5,0.15,0.5,0xffd24d,0,0.85,0.4);bx(h,0.12,0.25,0.12,0xffd24d,-0.15,1.0,0.4);bx(h,0.12,0.25,0.12,0xffd24d,0.15,1.0,0.4);}
if(k===1){const c=new THREE.Mesh(new THREE.ConeGeometry(0.28,0.6,6),mat(0xff5c8a));c.position.set(0,1.05,0.4);h.add(c);bx(h,0.15,0.15,0.15,0xffe14d,0,1.38,0.4);}
if(k===2){bx(h,0.6,0.14,0.1,0x111111,0,0.55,1.04);}
if(k===3){bx(h,0.3,0.25,0.15,0x40c4ff,-0.2,0.85,0.3);bx(h,0.3,0.25,0.15,0x40c4ff,0.2,0.85,0.3);bx(h,0.15,0.15,0.18,0x40c4ff,0,0.85,0.3);}
if(k===4){bx(h,0.55,0.08,0.55,0x7b4fd0,0,0.78,0.4);bx(h,0.35,0.35,0.35,0x7b4fd0,0,0.98,0.4);bx(h,0.37,0.08,0.37,0xff5c8a,0,0.85,0.4);}
b.headPivot.add(h);}
function rescue(e){
if(e.hidden){const t=eggBoxes.find(t=>t.egg===e);if(t)openBox(t);}
e.alive=false;scene.remove(e.g);saved++;setHUD();SFX.egg();setTimeout(()=>SFX.hatch(),250);
burst(e.x,e.g.position.y,e.z,e.c,22,6);burst(e.x,e.g.position.y,e.z,0xffffff,10,4);
const b=makeRex(0.32,e.c,0xffffff);b.R.position.copy(e.g.position);b.R.position.y-=0.65;scene.add(b.R);addHat(b,saved);setTimeout(()=>SFX.mama(saved),550);
babies.push({r:b,x:e.x,z:e.z,y:b.R.position.y,vy:4,face:0,walkT:Math.random()*6,hop:0,roarT:0});
const left=10-saved;
if(left)say(`A baby dino hatched! ${left} more egg${left>1?'s':''} to find.`,2500);
else wakeBoss();
}
function say(t,ms){hint.style.opacity=1;hint.textContent=t;clearTimeout(say.t);if(ms)say.t=setTimeout(()=>hint.style.opacity=0,ms);}
function winGame(){
phase='won';prBeam.visible=false;hint.style.opacity=0;
playing=false;SFX.win();trophy.visible=true;babies.forEach(b=>b.vy=7);
for(let i=0;i<6;i++)setTimeout(()=>burst(player.x+(Math.random()-0.5)*4,player.y+3,player.z+(Math.random()-0.5)*4,EGG_COLORS[i],20,8),i*200);
const s=Math.round((performance.now()-startTime)/1000);
document.getElementById('wintime').textContent=`Time: ${Math.floor(s/60)} min ${s%60} s · 🍬 ${candyN} cand${candyN===1?'y':'ies'}`;
let best=null,wins=0;try{best=+localStorage.getItem('trexBest')||null;wins=(+localStorage.getItem('trexWins')||0)+1;if(!best||s<best)best=s;localStorage.setItem('trexBest',best);localStorage.setItem('trexWins',wins);}catch(e){}
{const st=mapStars();st[mapId]=1;try{localStorage.setItem('trexMapsWon',JSON.stringify(st));}catch(e){}const n=Object.keys(st).length;
document.getElementById('winmap').textContent=`${MP.icon} ${MP.name} done! ⭐ ${n} of ${MAP_ORDER.length} maps · ✨ ${Object.keys(goldFound()).length} golden eggs`;drawMaps();}
document.getElementById('winbest').textContent=best?`Best time: ${Math.floor(best/60)} min ${best%60} s · Trophies: 🏆 ${wins}`:'';
setTimeout(()=>{if(phase==='won')document.getElementById('win').hidden=false;},1400);
}
function doRoar(){
player.roarT=1;SFX.roar();roarWave.material.opacity=0.9;roarWave.scale.setScalar(1);
trees.forEach(t=>{if(Math.hypot(t.x-player.x,t.z-player.z)<7)t.shake=1;});
eggs.forEach(e=>{if(e.alive&&!e.hidden&&Math.hypot(e.x-player.x,e.z-player.z)<9){e.pull=1.2;e.pt=player;}});
babies.forEach((b,i)=>{b.vy=5;setTimeout(()=>{b.roarT=0.6;SFX.babyRoar(i);},300+i*130);});
candies.forEach(c=>{if(c.alive&&!c.fly&&Math.hypot(c.x-player.x,c.z-player.z)<9){c.pull=1.2;c.pt=player;}});
bugs.forEach(b=>{if(b.alive&&Math.hypot(b.x-player.x,b.z-player.z)<8){b.stun=3;b.chase=false;}});
if(phase==='boss'&&!M.dmg){const s=boss.spots.filter(s=>s.alive).sort((a,b)=>Math.hypot(a.x-player.x,a.z-player.z)-Math.hypot(b.x-player.x,b.z-player.z))[0];if(s&&Math.hypot(s.x-player.x,s.z-player.z)<8)setTimeout(()=>tickle(s),250);}
animals.forEach((a,i)=>{if(Math.hypot(a.x-player.x,a.z-player.z)<10)setTimeout(()=>animalTrick(a,true),200+i*90);});
familyRoar();roomRoar();
}
/* ================= LOOP ================= */
function viewSize(){const de=document.documentElement;let w=Math.max(innerWidth,de.clientWidth||0),h=Math.max(innerHeight,de.clientHeight||0);
// Home Screen app on iPad or iPhone: the page can report a height a little too small, which leaves a strip at the bottom. Use the full screen size.
let sa=false;try{sa=navigator.standalone||matchMedia('(display-mode: standalone)').matches||matchMedia('(display-mode: fullscreen)').matches;}catch(e){}
if((sa||(navigator.maxTouchPoints>1&&matchMedia('(pointer:coarse)').matches))&&screen&&screen.width){const land=w>h,sw=land?Math.max(screen.width,screen.height):Math.min(screen.width,screen.height),sh=land?Math.min(screen.width,screen.height):Math.max(screen.width,screen.height);if(Math.abs(sw-w)<40){w=Math.max(w,sw);h=Math.max(h,sh);}}
return [Math.round(w),Math.round(h)];}
let viewW=0,viewH=0;
function resize(){const [w,h]=viewSize();viewW=w;viewH=h;canvas.style.width=w+'px';canvas.style.height=h+'px';renderer.setSize(w,h,false);camera.aspect=w/h;baseFov=w<h?68:55;camera.fov=baseFov;camera.updateProjectionMatrix();}
let baseFov=55;
addEventListener('resize',resize);resize();
addEventListener('orientationchange',()=>{[60,300,800].forEach(t=>setTimeout(resize,t));});if(window.visualViewport)visualViewport.addEventListener('resize',resize);
setInterval(()=>{const [w,h]=viewSize();if(w!==viewW||h!==viewH)resize();},1000);
let last=performance.now(),pad={},padFire=false,padRun=false;
addEventListener('gamepadconnected',()=>say(twoP?'Game controller ready for Player 2 (blue dino)! ✕ jump, ▢ fire, △ get in, R2 run.':'Game controller ready! ✕ jump, ▢ fire, R2 run. Press ✕ to play. (2 players: pick 🦖🦕 on the start card.)',4500));
function collide(px,pz,r){ // push out of trees and world edge
for(const t of trees){const dx=px-t.x,dz=pz-t.z,d=Math.hypot(dx,dz),m=t.r+r;if(d<m&&d>0.0001){px=t.x+dx/d*m;pz=t.z+dz/d*m;}}
const lim=HALF-1;px=Math.max(-lim,Math.min(lim,px));pz=Math.max(-lim,Math.min(lim,pz));return[px,pz];
}
// game controllers: one player = every controller. Two players: with two controllers the first is Rexy (P1) and the second is P2; with one controller it is P2, and P1 uses the touch screen or the keys.
let pad2={};
function readPads(){const mk=()=>({ix:0,iz:0,j:false,f:false,r:false,run:false,any:false,l:false,rt:false,opt:false}),A=mk(),B=mk();let list=[];
try{list=[...(navigator.getGamepads?navigator.getGamepads():[])].filter(g=>g&&g.buttons);}catch(e){}
list.forEach((gp,k)=>{const o=!twoP?A:(list.length>=2&&k===0?A:B);const ax=gp.axes[0]||0,ay=gp.axes[1]||0;if(Math.hypot(ax,ay)>0.2){o.ix+=ax;o.iz+=ay;}
const Bt=i=>!!(gp.buttons[i]&&(gp.buttons[i].pressed||gp.buttons[i].value>0.5));
if(Bt(14)){o.ix-=1;o.l=true;}if(Bt(15)){o.ix+=1;o.rt=true;}if(Bt(12))o.iz-=1;if(Bt(13))o.iz+=1;
if(Bt(0))o.j=true;if(Bt(1)||Bt(2))o.f=true;if(Bt(3))o.r=true;if(Bt(4)||Bt(5)||Bt(6)||Bt(7)||Bt(10))o.run=true;if(Bt(0)||Bt(1)||Bt(2)||Bt(3)||Bt(9))o.any=true;if(Bt(9))o.opt=true;});
return [A,B];}
// one player's moves for one frame: walk, run, jump, roar, fire, ride, swim, fly. The game runs it for Rexy, then for player 2.
function stepPlayer(dt,T,ix,iz,mag,running,fireHold,jumpHold){
const me=cur===1,passenger=!!(ride&&player.pass),flyer=!!(ride&&(ride.kind==='plane'||ride.kind==='jet'));if(passenger){mag=0;jumpQueued=false;}
fireCd-=dt;roarCd-=dt;inv-=dt;if(playing&&fireHold&&fireCd<=0)shoot();
if(!passenger&&(player.kx||player.kz)){const [nx,nz]=collide(player.x+player.kx*dt,player.z+player.kz*dt,0.5);player.x=nx;player.z=nz;const k=Math.max(0,1-dt*5);player.kx*=k;player.kz*=k;if(Math.abs(player.kx)+Math.abs(player.kz)<0.2){player.kx=0;player.kz=0;}}
if(playing&&!passenger){
if(mag>0){
const a=Math.atan2(-ix,-iz)+camYaw;const mx=Math.sin(a),mz=Math.cos(a);
const tf=Math.atan2(mx,mz);let df=tf-player.face;while(df>Math.PI)df-=Math.PI*2;while(df<-Math.PI)df+=Math.PI*2;player.face+=df*Math.min(1,dt*12);
const sp=6.5*mag*M.spd*(ride?(ride.kind==='car'?2.3:ride.kind==='blaster'?0:ride.kind==='jet'?3.3:2.8):uw?0.75:(running?1.75:1));let nx=player.x+mx*sp*dt,nz=player.z+mz*sp*dt;
// auto step-up: any 1-block step is climbed; a taller wall stops you (also in the air)
const g=groundAt(nx,nz);if(g-player.y>1.05&&!uw&&!flyer){nx=player.x;nz=player.z;}
const high=flyer&&player.y>groundAt(player.x,player.z)+2.5;if(high){const lim=HALF-1;nx=Math.max(-lim,Math.min(lim,nx));nz=Math.max(-lim,Math.min(lim,nz));}else [nx,nz]=collide(nx,nz,ride?(ride.kind==='jet'?1.6:1.0):0.5);
if(groundAt(nx,nz)-player.y>1.05&&!flyer&&!uw){nx=player.x;nz=player.z;}
player.x=nx;player.z=nz;player.walkT+=dt*sp*1.6;
player.stepT-=dt;if(player.stepT<=0&&player.onGround&&!ride&&!uw){player.stepT=running?0.2:0.32;SFX.step();if(running)burst(player.x,player.y+0.1,player.z,0xd7c49e,3,2);}
}
// jump / roar (same button: tap = jump, hold = roar)
if(jumpQueued&&flyer){jumpQueued=false;}
if(jumpQueued){const can=player.onGround||airT<0.1||uw;if(can||(power==='feather'&&!airJump)||performance.now()-jumpPressT>150)jumpQueued=false;if(can){airT=1;player.vy=uw?5.5:power==='giant'?10:8.5;player.onGround=false;airJump=false;if(uw){bubble(player.x,player.y+1.4,player.z,6);SFX.blub();}else SFX.jump();}else if(power==='feather'&&!airJump){airJump=true;player.vy=9.5;SFX.jump();burst(player.x,player.y+0.5,player.z,0xffffff,10,4);}}
if(jumpHeld&&!roarFired&&!flyer){const held=(performance.now()-jumpPressT)/1000;if(me){ringEl.style.opacity=Math.min(1,held/0.45);ringEl.style.transform=`rotate(${held*800}deg)`;}if(held>0.45){roarFired=true;if(me)ringEl.style.opacity=0;doRoar();}}
}
// gravity
const g=groundAt(player.x,player.z);
if(passenger){const P=ride.driver;if(P){const f=P.face;player.x=P.x+Math.sin(f)*1.7;player.z=P.z+Math.cos(f)*1.7;player.y=P.y;player.vy=P.vy;player.face=f;}player.onGround=true;uw=false;}
else{
uw=inPond(player.x,player.z)&&player.y<POND.surf-0.15;
if(flyer){const top=ride.kind==='jet'?34:19;const want=jumpHold?(ride.kind==='jet'?8:6):(player.y>g+0.05?-2.2:0);player.vy+=(want-player.vy)*Math.min(1,dt*4);if(player.y>g+top)player.vy=Math.min(0,player.vy);}
else if(uw){player.vy-=6*dt;player.vy=Math.max(-2.5,player.vy);player.vy*=1-dt*0.8;}
else{player.vy-=22*dt;if(chute)player.vy=Math.max(-3,player.vy);}
player.y+=player.vy*dt;
if(uw!==wasUw){if(playing)SFX.splash();burst(player.x,POND.surf+0.1,player.z,0xffffff,12,4);wasUw=uw;}
if(uw){bubT-=dt;if(bubT<=0){bubT=0.45;bubble(player.x+Math.sin(player.face)*0.6,player.y+1.4,player.z+Math.cos(player.face)*0.6,2);if(Math.random()<0.3)SFX.blub();}}
if(player.y<=g){if(!player.onGround&&player.vy<-4){SFX.land();burst(player.x,g+0.1,player.z,0xc8b08a,6,3);}player.y=g;player.vy=0;player.onGround=true;chute=false;}
else if(player.y>g+0.05)player.onGround=false;
}
if(me)uwTint.style.opacity=uw&&player.y+1.4<POND.surf?1:0;
if(player.onGround)airT=0;else airT+=dt;
// rex pose
rex.R.position.set(player.x,player.y,player.z);rex.R.rotation.y=player.face;
if(ride){rex.R.position.y+=ride.kind==='car'?0.55:ride.kind==='blaster'?0.35:ride.kind==='jet'?2.4:1.75;rex.legs[0].rotation.x=-1.2;rex.legs[1].rotation.x=-1.2;}
if(me||twoP){const rb=me?rideBtn:ride2B;const nv=playing&&!ride?nearVeh():null;rb.hidden=!(playing&&(ride||nv));if(!rb.hidden){const k=(ride||nv).kind;rb.textContent=ride?'⬇️ GET OUT':(k==='car'?'🚗 GET IN':k==='blaster'?'💥 GET IN':k==='jet'?(nv.driver?'🛫 HOP ON':'🛫 GET IN'):'✈️ GET IN');}
if(me&&nv&&!rideHint){rideHint=true;say(nv.kind==='car'?'🚗 A car! Tap GET IN to drive.':nv.kind==='blaster'?'💥 A blaster! Tap GET IN.':nv.kind==='jet'?'🛫 A big jet! Tap GET IN to fly high.':'✈️ A plane! Tap GET IN to fly.',2500);}}
if(phase==='lost'){if(me)loseT+=dt;rex.R.rotation.z+=(1.45-rex.R.rotation.z)*Math.min(1,dt*5);if(me){zzT-=dt;if(zzT<=0){zzT=0.55;zzz(player.x,player.y+1.4,player.z);}}}else rex.R.rotation.z=0;rex.R.visible=!(inv>0&&playing&&Math.floor(T*14)%2)&&(me||twoP);
const sw=mag>0&&player.onGround?Math.sin(player.walkT)*0.7:0;
rex.legs[0].rotation.x=sw;rex.legs[1].rotation.x=-sw;rex.arms[0].rotation.x=-sw*0.6;rex.arms[1].rotation.x=sw*0.6;
if(ride){rex.legs[0].rotation.x=-1.2;rex.legs[1].rotation.x=-1.2;}
rex.tail.rotation.y=Math.sin(T*3+player.walkT*0.5)*0.35;rex.R.position.y+=Math.abs(sw)*0.08;
if(player.roarT>0){player.roarT-=dt*1.1;const r=Math.sin(Math.min(1,player.roarT)*Math.PI);rex.headPivot.rotation.x=-r*0.5;rex.jaw.rotation.x=r*0.8;rex.R.scale.setScalar(rexScale*(1+r*0.12));}
else{rex.headPivot.rotation.x=Math.sin(T*2)*0.05;rex.jaw.rotation.x=0.05+Math.max(0,Math.sin(T*1.3))*0.05;rex.R.scale.setScalar(rexScale);}
if(!player.onGround&&!ride){rex.legs[0].rotation.x=0.5;rex.legs[1].rotation.x=-0.3;}
if(player.fireT>0){player.fireT-=dt;rex.jaw.rotation.x=0.7;}
reachRing.visible=!ride&&(me||twoP);reachRing.position.set(player.x,g+0.03,player.z);reachRing.material.opacity=0.35+Math.sin(T*4)*0.15;
if(roarWave.material.opacity>0){roarWave.scale.multiplyScalar(1+dt*6);roarWave.material.opacity=Math.max(0,roarWave.material.opacity-dt*1.2);roarWave.position.set(player.x,g+0.1,player.z);}
// power-ups (each player has its own)
if(power){powerT-=dt;if(me){powerEl.hidden=false;powerEl.textContent=`${POWERS[power].icon} ${Math.ceil(Math.max(0,powerT))}`;}
if(power==='star'){rexMats.forEach((m,i)=>m.color.setHSL((T*1.5+i*0.1)%1,0.8,0.6));if(Math.random()<0.5)burst(player.x,player.y+1.2,player.z,0xffffff,1,2);}
if(power==='magnet'){eggs.forEach(e=>{if(e.alive&&!e.hidden&&Math.hypot(e.x-player.x,e.z-player.z)<13){e.pull=0.15;e.pt=player;}});candies.forEach(c=>{if(c.alive&&!c.fly&&Math.hypot(c.x-player.x,c.z-player.z)<13){c.pull=0.15;c.pt=player;}});}
if(power==='giant'&&player.stepT>0.28&&player.onGround&&mag>0)SFX.stomp();
if(powerT<=0||!playing)endPower();}
rexScale+=((power==='giant'?1.6:0.8)-rexScale)*Math.min(1,dt*4);
}
// what one player touches: eggs, mushrooms, candies, animals, gifts, the golden egg, lava pools. Player 2 can also use the gates, find cousins, kick the ball and win at the nest.
function interact(dt,T,mag,running){if(!playing)return;const me=cur===1;
for(const e of eggs){if(!e.alive||e.hidden)continue;const gy=groundAt(e.x,e.z);if(Math.hypot(player.x-e.x,player.z-e.z)<(power==='giant'?3.2:2.0)&&Math.abs(player.y-gy)<3.5)rescue(e);}
for(const m of mush){const mg=groundAt(m.x,m.z);if(m.cd<=0&&!player.pass&&Math.hypot(player.x-m.x,player.z-m.z)<1.3&&player.y<mg+1.8&&player.vy<=0.5){player.vy=14;player.onGround=false;m.sq=1;m.cd=0.5;SFX.boing();burst(m.x,mg+1,m.z,0xffffff,6,3);}}
for(const c of candies){if(c.alive&&!c.fly&&Math.hypot(player.x-c.x,player.z-c.z)<2.0&&Math.abs(player.y-c.y)<3.5){c.alive=false;scene.remove(c.g);candyN++;SFX.candy(candyN);if(M.dmg&&candyN%10===0&&hearts<5){hearts++;SFX.heart();say('10 candies! +1 heart ❤️',1800);}burst(c.x,c.y,c.z,0xffffff,5,3);setHUD();}}
// push and squish (cartoon only): a bump sends it flying, a run sends it out of the land; it comes back with a poof. A jump on top makes a pancake that pops back up.
if(!ride)for(const a of animals){if(a.gone>0||a.fly||a.sq>0||a.swim||(a.cd2||0)>0)continue;const ag=groundAt(a.x,a.z),d=Math.hypot(player.x-a.x,player.z-a.z),hr=(power==='giant'?2:1)*(a.toy?1.1:0.95)+0.25;
if(d<hr&&player.vy<0&&player.y>ag+0.3&&player.y<ag+2.6){a.sq=2.2;a.cd2=2.6;player.vy=11;haptic(30,0.6);player.onGround=false;SFX.boing();SFX.squeak();burst(a.x,ag+0.4,a.z,0xff5c8a,12,4);squishN++;if(squishN<4||Math.random()<0.3)say('Squish! Pancake! 🥞',1000);continue;}
if(d<hr*0.9&&mag>0&&Math.abs(player.y-ag)<1.3){const ux=(a.x-player.x)/(d||1),uz=(a.z-player.z)/(d||1),sp=power==='giant'?24:running?21:8;
haptic(25,0.5);a.fly=true;a.fy=ag+(a.y||0);a.vy=running||power==='giant'?11:7;a.fvx=ux*sp;a.fvz=uz*sp;a.cd2=1.5;a.t=0;SFX.honk();SFX.jump();burst(a.x,ag+0.6,a.z,0xffffff,8,4);pushN++;if(pushN<4||Math.random()<0.3)say(running?'Bonk! Out of the land! 💨':'Boop! 💨',900);}}
for(const g of gifts){if(!g.alive)continue;if(Math.hypot(player.x-g.x,player.z-g.z)<(power==='giant'?2.6:1.6)&&Math.abs(player.y-groundAt(g.x,g.z))<3){g.alive=false;scene.remove(g.g);SFX.gift();burst(g.x,groundAt(g.x,g.z)+1,g.z,0xff5c8a,14,6);burst(g.x,groundAt(g.x,g.z)+1,g.z,0x40c4ff,14,6);
const ks=Object.keys(POWERS);givePower(ks[(Math.random()*ks.length)|0]);setTimeout(()=>{if(playing){gifts=gifts.filter(x=>x.alive);placeGift();}},20000);}}
if(goldEgg&&goldEgg.alive){const gy=groundAt(goldEgg.x,goldEgg.z);if(Math.hypot(player.x-goldEgg.x,player.z-goldEgg.z)<2.2&&Math.abs(player.y-gy)<3.5){goldEgg.alive=false;scene.remove(goldEgg.g);SFX.gold();burst(goldEgg.x,gy+1,goldEgg.z,0xffd24d,30,8);
const b=makeRex(0.36,0xffd24d,0xfff3b0);b.R.traverse(o=>{if(o.isMesh)o.material.emissive&&o.material.emissive.setHex(0x443300);});addHat(b,0);b.R.position.set(goldEgg.x,gy,goldEgg.z);scene.add(b.R);babies.push({r:b,x:goldEgg.x,z:goldEgg.z,y:gy,vy:6,face:0,walkT:0,hop:0,roarT:0,gold:true});
const st=goldFound();st[mapId]=1;try{localStorage.setItem('trexGold',JSON.stringify(st));}catch(e){}say('✨ You found the GOLDEN EGG! A golden baby joins you! ✨',3500);drawMaps();}}
// hiccup: now and then, a tiny surprise puff while running
if(mag>0&&running&&Math.random()<dt*0.08){SFX.hic();const fx=Math.sin(player.face),fz=Math.cos(player.face);const r=Math.random();burst(player.x+fx*1.2,player.y+1.6,player.z+fz*1.2,r<0.5?0xff7b00:r<0.8?0x9be7ff:0xffe14d,8,3);say(r<0.5?'Hic! 🔥':r<0.8?'Hic! 🫧':'Hic! 🐤',1000);}
for(const p of pools){if(p.life>0.5&&player.onGround&&Math.hypot(player.x-p.x,player.z-p.z)<1.3){hurt(p.x,p.z,'lava');break;}}
if(!me){
if(!traveling&&gateCd<=0)for(const o of gateObjs){if(Math.hypot(player.x-o.G.x,player.z-o.G.z)<1.3&&player.y<groundAt(o.G.x,o.G.z)+5){travel(o.G.to,mapId);break;}}
for(const c of cousins){if(!c.found&&Math.hypot(player.x-c.x,player.z-c.z)<2.6&&Math.abs(player.y-groundAt(c.x,c.z))<3)findCousin(c);}
if(fball&&!fball.held&&fball.cd<=0&&!ride&&Math.hypot(player.x-fball.x,player.z-fball.z)<1.4&&Math.abs(player.y+0.4-fball.y)<2)kickBall(Math.sin(player.face),Math.cos(player.face),6);
if(phase==='princess'&&Math.hypot(player.x-PR.x,player.z-PR.z)<2.8)winGame();}
}
let camTX=0,camTZ=0,camTY=0,camSpread=0;const camV=new THREE.Vector3();
function updateCamera(dt,mag,running){
let tx=player.x,ty=player.y,tz=player.z,spread=0,up=0;
if(twoP){const q=S2.player;tx=(player.x+q.x)/2;tz=(player.z+q.z)/2;ty=Math.min(player.y,q.y)+Math.abs(player.y-q.y)*0.5;spread=Math.hypot(player.x-q.x,player.z-q.z);up=Math.abs(player.y-q.y);}
// flying high: move back so the land below stays in view
const hi=Math.max(0,ty-groundAt(tx,tz)-3);camSpread+=((spread+up*0.9+hi*0.45)-camSpread)*Math.min(1,dt*3);
camTX=tx;camTZ=tz;camTY=ty;
const sc=(rexScale/0.8)**0.6,cd=(camera.aspect<1?11:9.5)*sc+camSpread*0.62;let ch=6.5*sc+camSpread*0.42;
const cx=tx-Math.sin(camYaw)*cd,cz=tz-Math.cos(camYaw)*cd,ey=ty+1.2;
// terrain clearance: raise the camera until the line to the dinos clears every block
let need=ch;for(let s=1;s<=14;s++){const k=s/14,px=tx+(cx-tx)*k,pz=tz+(cz-tz)*k,gy=groundAt(px,pz)+0.8;const req=(gy-ey)/k+ey-ty;if(req>need)need=req;}
need=Math.min(need,ch+14);
{const want=baseFov+(running&&mag>0&&playing?9:0);if(Math.abs(camera.fov-want)>0.05){camera.fov+=(want-camera.fov)*Math.min(1,dt*4);camera.updateProjectionMatrix();}}
camera.position.lerp(camV.set(cx,ty+need,cz),Math.min(1,dt*5));camera.lookAt(tx,ey,tz);
// hide scenery that stands between the camera and the dinos, near the camera
const C=camera.position,sx=tx-C.x,sz=tz-C.z,L2=sx*sx+sz*sz||1;
for(const t of trees){if(!t.g||t.g===mama.R||t.g===princess.R)continue;const k=((t.x-C.x)*sx+(t.z-C.z)*sz)/L2;let hide=false;
if(k>-0.15&&k<0.8){const px=C.x+sx*k,pz=C.z+sz*k,d=Math.hypot(t.x-px,t.z-pz);if(d<t.r+0.9){const ly=C.y+(ey-C.y)*Math.max(0,k);hide=ly<groundAt(t.x,t.z)+(t.h||4.6);}}
if(hide&&!t.camHid&&t.g.visible){t.camHid=true;t.g.visible=false;}else if(!hide&&t.camHid){t.camHid=false;t.g.visible=true;}}
for(const v of vehicles){if(v.driver){v.g.visible=true;continue;}const k=((v.x-C.x)*sx+(v.z-C.z)*sz)/L2;let hide=false;if(k>-0.15&&k<0.75){const px=C.x+sx*k,pz=C.z+sz*k;if(Math.hypot(v.x-px,v.z-pz)<(v.kind==='jet'?3:1.9)){const ly=C.y+(ey-C.y)*Math.max(0,k);hide=ly<v.y+(v.kind==='jet'?4:2.6);}}v.g.visible=!hide;}
}
// sky: Rain Land has rain, then a rainbow, then night. At night, or when a plane flies very high in any land, stars and planets show and shooting stars fly.
let wx={t:0,ph:''},rainK=0,nightK=0,rainSndT=0,shootT=2,shootN=0;const shooters=[];
const SKYC=new THREE.Color(),RAINC=new THREE.Color(0x7d8a99),NIGHTC=new THREE.Color(0x0d1b4a),SPACEC=new THREE.Color(0x050a24),CLOUDW=new THREE.Color(0xffffff),CLOUDG=new THREE.Color(0x8a96a3);
const starPts=(()=>{const n=600,p=new Float32Array(n*3);for(let i=0;i<n;i++){const u=Math.random()*Math.PI*2,v=0.08+Math.random()*0.92,r=150;const c=Math.sqrt(1-v*v);p[i*3]=Math.cos(u)*c*r;p[i*3+1]=v*r;p[i*3+2]=Math.sin(u)*c*r;}
const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(p,3));const m=new THREE.Points(g,new THREE.PointsMaterial({color:0xffffff,size:2.4,sizeAttenuation:false,transparent:true,opacity:0,fog:false,depthWrite:false}));m.visible=false;m.renderOrder=-2;scene.add(m);return m;})();
const planets=(()=>{const G=new THREE.Group(),B=(c)=>new THREE.MeshBasicMaterial({color:c,transparent:true,opacity:0,fog:false,depthWrite:false});
const add=(r,c,dir,extra)=>{const p=new THREE.Group();const s=new THREE.Mesh(new THREE.SphereGeometry(r,24,16),B(c));p.add(s);if(extra)extra(p,r);p.position.copy(new THREE.Vector3(...dir).normalize().multiplyScalar(125));G.add(p);return p;};
add(9,0xffb74d,[0.6,0.45,0.65],(p,r)=>{const ring=new THREE.Mesh(new THREE.RingGeometry(r*1.3,r*1.9,40),B(0xffe0b2));ring.material.side=THREE.DoubleSide;ring.rotation.x=1.2;ring.rotation.y=0.3;p.add(ring);});
add(4.5,0xef5350,[-0.7,0.5,0.4]);add(6.5,0x64b5f6,[-0.3,0.35,-0.9],(p,r)=>{for(const y of[-0.4,0.2,0.6]){const b=new THREE.Mesh(new THREE.TorusGeometry(r*Math.cos(Math.asin(y))*1.01,0.35,6,32),B(0xe3f2fd));b.rotation.x=Math.PI/2;b.position.y=y*r;p.add(b);}});
add(7,0xeeeeee,[0.2,0.7,-0.5],(p,r)=>{for(let k=0;k<5;k++){const c=new THREE.Mesh(new THREE.SphereGeometry(r*0.2,10,8),B(0xbdbdbd));const a=k*1.3,b=k*0.7;c.position.set(Math.cos(a)*Math.cos(b)*r*0.93,Math.sin(b)*r*0.93,Math.sin(a)*Math.cos(b)*r*0.93);p.add(c);}});
add(3,0x9ccc65,[0.9,0.25,-0.2]);G.visible=false;G.renderOrder=-1;scene.add(G);G.mats=[];G.traverse(o=>{if(o.material)G.mats.push(o.material);});return G;})();
const rainLines=(()=>{const n=420,p=new Float32Array(n*6);const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(p,3));const m=new THREE.LineSegments(g,new THREE.LineBasicMaterial({color:0xd6ecff,transparent:true,opacity:0.65}));m.visible=false;m.frustumCulled=false;scene.add(m);m.n=n;m.init=false;return m;})();
const rainbow=(()=>{const G=new THREE.Group(),C=[0xff3d3d,0xff9800,0xffeb3b,0x4caf50,0x2196f3,0x3f51b5,0x9c27b0];C.forEach((c,i)=>{const t=new THREE.Mesh(new THREE.TorusGeometry(34-i*1.1,0.55,6,48,Math.PI),new THREE.MeshBasicMaterial({color:c,transparent:true,opacity:0,fog:false}));G.add(t);});G.position.set(0,-2,-40);G.visible=false;scene.add(G);return G;})();
function shootingStar(){const C=camera.position,g=new THREE.Group(),m=new THREE.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:1,fog:false});
const head=new THREE.Mesh(new THREE.BoxGeometry(0.9,0.9,0.9),m);g.add(head);const tail=new THREE.Mesh(new THREE.BoxGeometry(0.35,0.35,9),new THREE.MeshBasicMaterial({color:0xfff59d,transparent:true,opacity:0.8,fog:false}));tail.position.z=-4.8;g.add(tail);
const a=Math.random()*Math.PI*2,vx=Math.cos(a+1.6),vz=Math.sin(a+1.6);g.position.set(C.x+Math.cos(a)*55,C.y+38+Math.random()*25,C.z+Math.sin(a)*55);g.lookAt(g.position.x+vx,g.position.y-0.35,g.position.z+vz);scene.add(g);shooters.push({g,vx:vx*60,vy:-21,vz:vz*60,life:1.3,m,tail});
shootN++;if(shootN===1||Math.random()<0.25)say(['🌠 A shooting star! Make a wish!','🌠 Whoosh! Another shooting star!','🌠 Look up! A shooting star!'][Math.min(2,shootN-1)],2200);SFX.gold();}
function updateSky(dt,T){
let wantRain=0,wantNight=0;
if(MP.rain){if(playing)wx.t+=dt;const c=wx.t%70;const ph=c<22?'rain':c<28?'clear':c<64?'night':'dawn';wantRain=ph==='rain'?1:0;wantNight=ph==='night'?1:0;
if(ph!==wx.ph&&playing){if(ph==='clear')say('🌦️ The rain stopped! Look, a rainbow! 🌈',3000);if(ph==='night')say('🌙 Night time! Look up: stars and planets! 🪐 Fly the jet up high to see them!',4500);if(ph==='rain'&&wx.ph)say('🌧️ Here comes the rain again! Splash in the puddles!',2500);}wx.ph=ph;}
rainK+=(wantRain-rainK)*Math.min(1,dt*1.2);nightK+=(wantNight-nightK)*Math.min(1,dt*0.9);
const alt=Math.max(0,Math.min(1,(camTY-groundAt(camTX,camTZ)-10)/14)),spaceK=ride&&(ride.kind==='jet'||ride.kind==='plane')?alt:alt*0.5,starK=Math.max(nightK,spaceK);
SKYC.setHex(MP.sky).lerp(RAINC,rainK*0.8).lerp(NIGHTC,nightK).lerp(SPACEC,spaceK*0.85);scene.background.copy(SKYC);scene.fog.color.copy(SKYC);
hemi.intensity=0.75-0.3*Math.max(nightK,spaceK*0.6)-0.15*rainK;sun.intensity=0.85-0.45*nightK-0.3*rainK;
clouds.forEach(c=>c.children.forEach(m=>m.material.color.copy(CLOUDW).lerp(CLOUDG,rainK).lerp(NIGHTC,nightK*0.7)));
const C=camera.position;starPts.visible=starK>0.02;starPts.position.copy(C);starPts.material.opacity=starK;
planets.visible=starK>0.02;if(planets.visible){planets.position.copy(C);planets.mats.forEach(m=>m.opacity=starK);planets.rotation.y=T*0.01;planets.scale.setScalar(1+spaceK*0.5);}
rainbow.visible=MP.rain&&wx.ph==='clear';if(rainbow.visible){const k=Math.min(1,Math.sin(Math.min(1,((wx.t%70)-22)/6)*Math.PI)*1.6);rainbow.children.forEach(m=>m.material.opacity=Math.max(0,k)*0.85);}
// rain drops round the camera
rainLines.visible=rainK>0.03;if(rainLines.visible){const p=rainLines.geometry.attributes.position.array,n=rainLines.n,cx=camTX,cz=camTZ,cy=camTY;
for(let i=0;i<n;i++){let x=p[i*6],y=p[i*6+1],z=p[i*6+2];y-=26*dt;if(!rainLines.init||y<groundAt(x,z)||Math.abs(x-cx)>22||Math.abs(z-cz)>22){x=cx+(Math.random()-0.5)*40;z=cz+(Math.random()-0.5)*40;y=cy+(rainLines.init?14+Math.random()*6:Math.random()*20);}
p[i*6]=x;p[i*6+1]=y;p[i*6+2]=z;p[i*6+3]=x+0.05;p[i*6+4]=y+0.9;p[i*6+5]=z;}rainLines.init=true;rainLines.geometry.attributes.position.needsUpdate=true;rainLines.material.opacity=0.65*rainK;
rainSndT-=dt;if(AC&&rainSndT<=0&&rainK>0.4){rainSndT=0.22;noise(AC.currentTime,0.3,0.035*rainK,2600+Math.random()*1500,0.6);}}
// shooting stars
if(starK>0.6&&playing){shootT-=dt;if(shootT<=0){shootT=1.2+Math.random()*2.2;shootingStar();}}
for(let i=shooters.length-1;i>=0;i--){const s=shooters[i];s.life-=dt;s.g.position.x+=s.vx*dt;s.g.position.y+=s.vy*dt;s.g.position.z+=s.vz*dt;s.m.opacity=Math.max(0,Math.min(1,s.life*1.5));s.tail.material.opacity=s.m.opacity*0.8;if(s.life<=0){scene.remove(s.g);shooters.splice(i,1);}}
}
let slowT=0,slowN=0,lowQ=0;
function lowerQuality(){lowQ++;if(lowQ===1){renderer.shadowMap.enabled=false;sun.castShadow=false;renderer.setPixelRatio(1);}else if(lowQ===2){renderer.setPixelRatio(0.75);scene.fog.far=Math.min(scene.fog.far,55);camera.far=90;camera.updateProjectionMatrix();}resize();}
function frame(now){
const dt=Math.min(0.05,(now-last)/1000);{const raw=(now-last)/1000;if(playing&&lowQ<2&&raw>0&&raw<1){slowT+=raw;if(raw>0.045)slowN+=raw;if(slowT>4){if(slowN/slowT>0.5)lowerQuality();slowT=0;slowN=0;}}}last=now;const T=now/1000;
// input to move vector (camera-relative). Two players: WASD is Rexy, the arrows are player 2.
let ix=joy.x,iz=joy.y;
if(keys.KeyA||(!twoP&&keys.ArrowLeft))ix-=1;if(keys.KeyD||(!twoP&&keys.ArrowRight))ix+=1;if(keys.KeyW||(!twoP&&keys.ArrowUp))iz-=1;if(keys.KeyS||(!twoP&&keys.ArrowDown))iz+=1;
// game controller (PS5 DualSense, Xbox, Switch Pro): ✕ jump (hold = roar), ▢ or ○ fire, △ roar or get in, R1 R2 L2 L3 run, D-pad left/right picks the mode on the start card, up/down picks 1 or 2 players
const [pa,pb]=readPads();ix+=pa.ix;iz+=pa.iz;
const pJ=pa.j,pF=pa.f,pR=pa.r,pRun=pa.run,pAny=pa.any||pb.any,pL=pa.l||pb.l,pRt=pa.rt||pb.rt,pOpt=pa.opt||pb.opt;
const menu=!playing&&(!document.getElementById('start').hidden||!document.getElementById('win').hidden||!document.getElementById('lose').hidden);
if(pOpt&&!pad.opt&&playing){goHome();}
else if(pAny&&!pad.any&&menu){wake();if(!document.getElementById('win').hidden)nextMap();else if(!document.getElementById('start').hidden)startIsland();else startGame();}
else if(playing){if(pAny&&!pad.any)wake();if(pJ&&!pad.j)pressJump();if(pR&&!pad.r){if(ride||nearVeh())toggleRide();else if(roarCd<=0){roarCd=0.8;doRoar();}}if(pF&&!pad.f)shoot();}
const ud=(pa.iz+pb.iz)<-0.5?-1:(pa.iz+pb.iz)>0.5?1:0;
if(!document.getElementById('start').hidden){const order=['easy','adv','turbo'];if(pL&&!pad.l)setMode(order[(order.indexOf(mode)+2)%3]);if(pRt&&!pad.rt)setMode(order[(order.indexOf(mode)+1)%3]);if(ud&&ud!==pad.ud)setTwo(ud>0);}
if(!pJ&&pad.j&&jumpHeld)releaseJump();
padFire=pF;padRun=pRun;pad={opt:pOpt,any:pAny,j:pJ,f:pF,r:pR,l:pL,rt:pRt,ud};
if(menu){ix=0;iz=0;}
let mag=Math.min(1,Math.hypot(ix,iz));if(mag<0.12)mag=0;
const running=runOn||keys.ShiftLeft||(!twoP&&keys.ShiftRight)||padRun;
stepPlayer(dt,T,ix,iz,mag,running,fireHeld||padFire,!!(jumpHeld||keys.Space||pad.j));
interact(dt,T,mag,running);
// player 2: a game controller, or the arrow keys + Enter (jump, hold = roar), / (fire), . (get in or out), right Shift (run)
if(twoP){let jx=pb.ix+joy2.x,jz=pb.iz+joy2.y;if(keys.ArrowLeft)jx-=1;if(keys.ArrowRight)jx+=1;if(keys.ArrowUp)jz-=1;if(keys.ArrowDown)jz+=1;if(menu){jx=0;jz=0;}
const j2=pb.j||t2.jump||!!(keys.Enter||keys.NumpadEnter),f2=pb.f||t2.fire||!!(keys.Slash||keys.NumpadDecimal),r2=pb.r,rd2=!!keys.Period||t2.ride,run2=pb.run||t2.run||!!keys.ShiftRight;t2.ride=false;
let m2=Math.min(1,Math.hypot(jx,jz));if(m2<0.12)m2=0;
asP2(()=>{if(playing){if(j2&&!pad2.j)pressJump();if(r2&&!pad2.r){if(ride||nearVeh())toggleRide();else if(roarCd<=0){roarCd=0.8;doRoar();}}if(f2&&!pad2.f)shoot();if(rd2&&!pad2.rd)toggleRide();}
if(!j2&&pad2.j&&jumpHeld)releaseJump();
stepPlayer(dt,T,jx,jz,m2,run2,f2,j2);interact(dt,T,m2,run2);});
pad2={j:j2,f:f2,r:r2,rd:rd2};
// too far apart: player 2 pops back next to Rexy
if(playing&&!traveling&&Math.hypot(S2.player.x-player.x,S2.player.z-player.z)>26){placeP2();burst(S2.player.x,S2.player.y+1,S2.player.z,0x90caf9,16,5);SFX.pop();say('✨ Player 2 jumps back next to Rexy!',1600);}}
updateDuel(dt,T); // tag + toy saber duel (two players)
// vehicles follow their driver; empty ones fall to the ground
for(const v of vehicles){const P=v.driver;if(P){v.x=P.x;v.z=P.z;v.y=P.y;v.face=P.face;}else if(v.y>groundAt(v.x,v.z)+0.01){v.vy-=18*dt;v.y=Math.max(groundAt(v.x,v.z),v.y+v.vy*dt);}else{v.y=groundAt(v.x,v.z);v.vy=0;}
v.g.position.set(v.x,v.y,v.z);v.g.rotation.y=v.face;if(v.g.userData.prop)v.g.userData.prop.rotation.z+=dt*(P?30:2);if(v.g.userData.props)v.g.userData.props.forEach(p=>p.rotation.z+=dt*(P?34:2));
if(P&&(v.kind==='plane'||v.kind==='jet'))v.g.rotation.x=-Math.max(-0.3,Math.min(0.3,P.vy*0.05));else v.g.rotation.x=0;}
// eggs
for(const e of eggs){if(!e.alive)continue;
if(e.pull>0){e.pull-=dt;const P=e.pt||player,dx=P.x-e.x,dz=P.z-e.z,d=Math.hypot(dx,dz);if(d>0.1){e.x+=dx/d*Math.min(d,dt*9);e.z+=dz/d*Math.min(d,dt*9);}}
const gy=groundAt(e.x,e.z);if(e.hidden){e.g.position.set(e.x,gy+0.65,e.z);continue;}if(e.pop>0)e.pop=Math.max(0,e.pop-dt*1.5);e.g.position.set(e.x,gy+0.65+Math.abs(Math.sin(T*3+e.phase))*0.3+Math.sin(e.pop*Math.PI)*2.2,e.z);
e.g.children[0].rotation.z=Math.sin(T*6+e.phase)*0.15;e.ring.scale.setScalar(1+Math.sin(T*4+e.phase)*0.1);
}
// baby pile-up: stop fast after a run and the babies jump on Rexy's back
pileCd-=dt;if(playing&&mag>0&&running)runT+=dt;else if(mag>0)runT=0;
if(playing&&mag===0&&runT>1.2&&pileCd<=0&&babies.length>=2){pileT=2.6;pileCd=14;babies.slice(0,5).forEach((b,i)=>setTimeout(()=>SFX.mama(i+3),i*120));say('Baby pile-up! 🦖🦖🦖',1500);}
if(mag===0)runT=0;
if(pileT>0){pileT-=dt;if(pileT<=0)babies.slice(0,5).forEach(b=>{b.vy=6;});}
// babies follow in a line
const jv=ride&&ride.kind==='jet'?ride:null;
babies.forEach((b,i)=>{
if(jv&&i<10&&phase!=='won'){const f=jv.face,row=Math.floor(i/2),lx=(i%2?1:-1)*0.45,lz=-0.9-row*0.55;b.x=jv.x+Math.sin(f)*lz+Math.cos(f)*lx;b.z=jv.z+Math.cos(f)*lz-Math.sin(f)*lx;b.y=jv.y+2.45;b.vy=0;b.face=f;
b.r.R.position.set(b.x,b.y,b.z);b.r.R.rotation.y=f;b.r.R.rotation.z=Math.sin(T*5+i)*0.12;b.r.legs[0].rotation.x=-1.2;b.r.legs[1].rotation.x=-1.2;b.r.headPivot.rotation.x=Math.sin(T*4+i)*0.15;return;}
if(pileT>0&&i<5&&phase!=='won'){const sc=rexScale/0.8,w=Math.sin(T*9+i)*0.12*(i+1);b.x=player.x-Math.sin(player.face)*0.3*sc+Math.cos(player.face)*w;b.z=player.z-Math.cos(player.face)*0.3*sc-Math.sin(player.face)*w;b.y=player.y+(1.55+i*0.62)*sc;b.vy=0;b.face=player.face;
b.r.R.position.set(b.x,b.y,b.z);b.r.R.rotation.y=b.face;b.r.R.rotation.z=w*0.6;b.r.legs[0].rotation.x=0.6;b.r.legs[1].rotation.x=-0.6;return;}
b.r.R.rotation.z=0;
let lead=i===0?{x:player.x,z:player.z}:babies[i-1],want=i===0?1.6:1.0;if(phase==='won'){const a=i/Math.max(1,babies.length)*Math.PI*2;lead={x:NEST.x+Math.cos(a)*0.75,z:NEST.z+Math.sin(a)*0.75};want=0.05;}const dx=lead.x-b.x,dz=lead.z-b.z,d=Math.hypot(dx,dz);
let moving=false;if(d>want){const s=Math.min(d-want,dt*7.5*M.spd*(running?1.8:1));b.x+=dx/d*s;b.z+=dz/d*s;b.face=Math.atan2(dx,dz);moving=true;}
[b.x,b.z]=collide(b.x,b.z,0.25);
const gy=groundAt(b.x,b.z);b.vy-=22*dt;b.y+=b.vy*dt;if(b.y<gy){b.y=gy;b.vy=moving&&Math.random()<0.02?4:0;}
b.walkT+=dt*(moving?14:2);b.r.R.position.set(b.x,b.y,b.z);b.r.R.rotation.y=b.face;
const s=moving?Math.sin(b.walkT)*0.7:0;b.r.legs[0].rotation.x=s;b.r.legs[1].rotation.x=-s;b.r.tail.rotation.y=Math.sin(T*6+i)*0.5;
b.roarT-=dt;b.r.headPivot.rotation.x=b.roarT>0?-0.4:Math.sin(T*3+i)*0.08;b.r.jaw.rotation.x=b.roarT>0?0.7:0.05;
});
// bouncy mushrooms
for(const m of mush){m.cd-=dt;const mg=groundAt(m.x,m.z);
for(const b of babies){if(Math.hypot(b.x-m.x,b.z-m.z)<1.1&&b.vy<=0&&b.y<mg+0.6){b.vy=10;m.sq=Math.max(m.sq,0.6);}}
if(m.sq>0){m.sq-=dt*2.5;const q=Math.sin(m.sq*Math.PI*3)*0.3*m.sq;m.g.scale.set(1+q,1-q,1+q);}else m.g.scale.set(1,1,1);}
// candies
for(const c of candies){if(!c.alive)continue;
if(c.fly){c.vy-=18*dt;c.x+=c.vx*dt;c.z+=c.vz*dt;c.y+=c.vy*dt;const lim=HALF-2;c.x=Math.max(-lim,Math.min(lim,c.x));c.z=Math.max(-lim,Math.min(lim,c.z));const gy=groundAt(c.x,c.z)+0.5;if(c.y<=gy&&c.vy<0){c.y=gy;c.fly=false;}}
else{if(c.pull>0){c.pull-=dt;const P=c.pt||player,dx=P.x-c.x,dz=P.z-c.z,d=Math.hypot(dx,dz);if(d>0.1){c.x+=dx/d*Math.min(d,dt*10);c.z+=dz/d*Math.min(d,dt*10);}}
c.y=groundAt(c.x,c.z)+0.5+Math.sin(T*3+c.ph)*0.12;}
c.g.position.set(c.x,c.y,c.z);c.g.rotation.y+=dt*2;
}
if(candies.length>80||candies.some(c=>!c.alive))candies=candies.filter(c=>c.alive);
updateFamily(dt,T);updateGates(dt,T);updateBlasts(dt);eggBoxHint();updateRooms(dt,T);updateRace(dt,T);
// funny animals
for(const a of animals){a.cd-=dt;const ag=groundAt(a.x,a.z);const d=Math.hypot(player.x-a.x,player.z-a.z);
// push and squish (cartoon only): a bump sends it flying, a run sends it out of the land; it comes back with a poof. A jump on top makes a pancake that pops back up.
a.cd2=(a.cd2||0)-dt;
if(a.gone>0){a.gone-=dt;a.g.visible=false;if(a.gone<=0){const sp=spots(1,6,19,(Math.random()*997)|0,1.2)[0]||[2,-6];a.x=sp[0]+0.3;a.z=sp[1]+0.3;a.y=0;a.vy=6;a.g.visible=true;a.g.scale.set(1,1,1);burst(a.x,groundAt(a.x,a.z)+1,a.z,0xffffff,16,5);SFX.pop();}continue;}
if(a.fly){a.vy-=20*dt;a.x+=a.fvx*dt;a.z+=a.fvz*dt;a.fy+=a.vy*dt;a.body.rotation.x+=dt*11;a.body.rotation.z+=dt*6;
if(Math.abs(a.x)>HALF+1||Math.abs(a.z)>HALF+1){a.fly=false;a.gone=8;a.body.rotation.set(0,0,0);burst(a.x,a.fy,a.z,0xffe14d,10,5);continue;}
const gg=groundAt(a.x,a.z);if(a.fy<=gg&&a.vy<0){a.fly=false;a.y=0;a.vy=5;a.body.rotation.set(0,0,0);burst(a.x,gg+0.4,a.z,0xffffff,8,3);SFX.boing();a.g.position.set(a.x,gg,a.z);}else a.g.position.set(a.x,a.fy,a.z);continue;}
if(a.sq>0){a.sq-=dt;const k=a.sq>0.4?0.16:0.16+(0.4-a.sq)/0.4*0.84;a.g.scale.set(1+(1-k)*0.7,k,1+(1-k)*0.7);
if(a.sq<=0){a.g.scale.set(1,1,1);a.y=0;a.vy=9;burst(a.x,ag+0.8,a.z,0xffe14d,12,4);SFX.pop();}a.g.position.set(a.x,ag,a.z);continue;}
if(a.t>0){a.t-=dt;const k=1-a.t;
if(a.trick==='flip')a.body.rotation.x=-k*Math.PI*2;if(a.trick==='spin')a.body.rotation.y=k*Math.PI*4;
if(a.trick==='dance'){a.body.rotation.z=Math.sin(T*18)*0.4;a.x+=Math.sin(T*9)*dt*2;}
if(a.trick==='dash'||a.trick==='slide'){const sp=a.trick==='dash'?9:6;a.x+=Math.sin(a.face)*sp*dt;a.z+=Math.cos(a.face)*sp*dt;if(a.trick==='slide')a.body.rotation.x=Math.PI/2*0.85;if(Math.random()<0.4)burst(a.x,ag+0.1,a.z,0xffffff,1,1);}
if(a.t<=0){a.body.rotation.set(0,0,0);}}
else{a.turn-=dt;if(a.turn<=0){a.turn=1.5+Math.random()*2.5;a.face+=(Math.random()-0.5)*2.4;a.walk=Math.random()<0.6;}
if(a.walk){a.x+=Math.sin(a.face)*1.2*dt;a.z+=Math.cos(a.face)*1.2*dt;}
if(playing&&d<2.2&&a.cd<=0)animalTrick(a,false);}
if(a.swim){a.ang+=dt*0.5;a.x=POND.x+Math.cos(a.ang)*(POND.r-1.8);a.z=POND.z+Math.sin(a.ang)*(POND.r-1.8);a.face=-a.ang;a.g.position.set(a.x,POND.floor+0.9+Math.sin(T*2+a.ang)*0.3,a.z);a.g.rotation.y=a.face;if(Math.random()<dt*0.8)bubble(a.x,POND.floor+1.6,a.z,1);continue;}
const c=collide(a.x,a.z,0.4);if(Math.abs(c[0]-a.x)+Math.abs(c[1]-a.z)>0.001||groundAt(c[0],c[1])-ag>1.05)a.face+=1.5;if(groundAt(c[0],c[1])-ag<=1.05){a.x=c[0];a.z=c[1];}
a.vy-=20*dt;a.y+=a.vy*dt;if(a.y<0){a.y=0;a.vy=(a.walk&&a.kind==='bunny')?3:0;}
a.g.position.set(a.x,ag+a.y,a.z);a.g.rotation.y=a.face;}
// gift boxes and power-ups
for(const g of gifts){if(!g.alive)continue;g.g.position.set(g.x,groundAt(g.x,g.z)+0.9+Math.sin(T*3+g.x)*0.15,g.z);g.g.rotation.y+=dt*1.5;}
if(goldEgg&&goldEgg.alive){const gy=groundAt(goldEgg.x,goldEgg.z);goldEgg.g.position.set(goldEgg.x,gy+0.7+Math.sin(T*3)*0.15,goldEgg.z);goldEgg.g.rotation.y+=dt*2;if(Math.random()<0.2)burst(goldEgg.x,gy+1,goldEgg.z,0xfff176,1,2);}
// grumpy beetles
for(const b of bugs){
if(!b.alive){b.respawn-=dt;if(b.respawn<=0&&playing){const [x,z]=bugSpot();b.x=x;b.z=z;b.alive=true;b.g.visible=true;b.stun=0;burst(x,groundAt(x,z)+0.5,z,0x7b4fd0,8,3);}continue;}
const d=Math.hypot(player.x-b.x,player.z-b.z);b.grrCd-=dt;
if(b.stun>0){b.stun-=dt;b.g.rotation.z=Math.PI;b.legs.forEach((l,k)=>l.rotation.x=Math.sin(T*30+k)*0.6);b.g.position.set(b.x,groundAt(b.x,b.z)+1.0,b.z);continue;}
b.g.rotation.z=0;
let sp=1.4;
if(playing&&phase!=='won'&&d<9&&inv<=0){if(!b.chase&&b.grrCd<=0){SFX.grr();b.grrCd=4;}b.chase=true;b.face=Math.atan2(player.x-b.x,player.z-b.z);sp=M.bugSpd;}
else{b.chase=false;b.turnT-=dt;if(b.turnT<=0){b.turnT=2+Math.random()*2;b.face+=(Math.random()-0.5)*2.5;}}
let nx=b.x+Math.sin(b.face)*sp*dt,nz=b.z+Math.cos(b.face)*sp*dt;
if(Math.hypot(nx-PR.x,nz-PR.z)<3.2){nx=b.x;nz=b.z;b.face+=Math.PI*0.7;}
if(Math.abs(groundAt(nx,nz)-groundAt(b.x,b.z))>1.1){nx=b.x;nz=b.z;b.face+=1.5;}
const c=collide(nx,nz,0.55);if(Math.abs(c[0]-nx)+Math.abs(c[1]-nz)>0.001&&!b.chase)b.face+=1.2;b.x=c[0];b.z=c[1];
b.walk+=dt*sp*4;b.legs.forEach((l,k)=>l.rotation.x=Math.sin(b.walk+k*1.3)*0.5);
b.g.position.set(b.x,groundAt(b.x,b.z)+Math.abs(Math.sin(b.walk))*0.08,b.z);b.g.rotation.y=b.face;
if(playing&&d<(power==='giant'?2.2:1.25)&&Math.abs(player.y-groundAt(b.x,b.z))<(power==='giant'?2.5:1.3)){if(power==='star'||power==='giant'){defeatBug(b);if(power==='giant')SFX.stomp();}else hurt(b.x,b.z,'bug');}
}
// fireballs
for(let i=fireballs.length-1;i>=0;i--){const f=fireballs[i];f.life-=dt;f.g.position.x+=f.vx*dt;f.g.position.z+=f.vz*dt;f.g.position.y+=f.vy*dt;f.g.rotation.x+=dt*12;f.g.rotation.y+=dt*9;
const fx=f.g.position.x,fz=f.g.position.z;let hit=f.life<=0||Math.abs(fx)>HALF||Math.abs(fz)>HALF;
if(Math.random()<0.5)burst(fx,f.g.position.y,fz,Math.random()<0.5?0xff7b00:0xffe14d,1,1);
for(const b of bugs){if(b.alive&&Math.hypot(b.x-fx,b.z-fz)<1.2){b.alive=false;b.g.visible=false;b.respawn=mode==='turbo'?10:16;burst(b.x,groundAt(b.x,b.z)+0.6,b.z,0x7b4fd0,16,6);burst(b.x,groundAt(b.x,b.z)+0.6,b.z,0xffe14d,8,5);SFX.pop();makeCandy(b.x,b.z);hit=true;break;}}
if(!hit)for(const a of animals){if(!(a.gone>0)&&!a.fly&&Math.hypot(a.x-fx,a.z-fz)<1.3&&a.t<=0){animalTrick(a,true);hit=true;break;}}
if(!hit)for(const c of cousins){if(!c.found&&Math.hypot(c.x-fx,c.z-fz)<1.5){findCousin(c);hit=true;break;}}
if(!hit)for(const c of roomKids){if(Math.hypot(c.x-fx,c.z-fz)<1.4){c.vy=8;c.dance=1.5;SFX.giggle();hit=true;break;}}
if(!hit&&fball&&!fball.held&&Math.hypot(fball.x-fx,fball.z-fz)<1.3&&Math.abs(fball.y-f.g.position.y)<2){kickBall(f.vx,f.vz,5);hit=true;}
if(!hit&&phase==='boss')for(const s of boss.spots){if(s.alive&&Math.hypot(s.x-fx,s.z-fz)<1.9){tickle(s);hit=true;break;}}
if(!hit)for(const t of trees){if(Math.hypot(t.x-fx,t.z-fz)<t.r+(t.egg?0.5:0)){if(t.egg)openBox(t);else t.shake=0.6;hit=true;break;}}
if(!hit&&f.g.position.y<groundAt(fx,fz)+0.3)hit=true;
if(hit){burst(fx,f.g.position.y,fz,0xff7b00,6,3);scene.remove(f.g);fireballs.splice(i,1);}}
// lava volcanoes
for(const v of VOLC){if(!playing||MP.hub){v.g.position.x=v.x;v.g.position.z=v.z;continue;}v.t-=dt;
if(v.t<2.2&&!v.warn){v.warn=true;if(Math.hypot(player.x-v.x,player.z-v.z)<26)SFX.rumble();}
if(v.warn){v.g.position.x=v.x+(Math.random()-0.5)*0.15;v.g.position.z=v.z+(Math.random()-0.5)*0.15;if(Math.random()<0.15)burst(v.x,v.g.position.y+6.2,v.z,0x555555,1,2);}
if(v.t<=0){v.warn=false;v.g.position.x=v.x;v.g.position.z=v.z;v.t=M.erupt+Math.random()*5;erupt(v);}}
for(let i=bombs.length-1;i>=0;i--){const b=bombs[i];b.vy-=18*dt;b.x+=b.vx*dt;b.z+=b.vz*dt;b.y+=b.vy*dt;b.m.position.set(b.x,b.y,b.z);b.m.rotation.x+=dt*6;
b.ring.material.opacity=0.5+Math.sin(T*18)*0.35;
if(Math.random()<0.4)burst(b.x,b.y,b.z,0xff9100,1,1);
if(b.vy<0&&b.y<=b.gy){scene.remove(b.m);scene.remove(b.ring);bombs.splice(i,1);burst(b.tx,b.gy,b.tz,0xff3d00,14,6);
const pm=new THREE.Mesh(poolGeo,poolMat);pm.position.set(b.tx,b.gy-0.33,b.tz);scene.add(pm);pools.push({m:pm,x:b.tx,z:b.tz,life:3});
forP(()=>{if(playing&&Math.hypot(player.x-b.tx,player.z-b.tz)<1.7&&player.y<b.gy+1.5)hurt(b.tx,b.tz,'lava');});}}
for(let i=pools.length-1;i>=0;i--){const p=pools[i];p.life-=dt;p.m.scale.setScalar(Math.max(0.05,Math.min(1,p.life)));
if(p.life<=0){scene.remove(p.m);pools.splice(i,1);}}
// Grumbo the boss
if(boss){const B=boss;if(B.wig>0){B.wig=Math.max(0,B.wig-dt*2);const sq=Math.sin(T*30)*0.06*B.wig;B.g.scale.set(1+sq,1-sq,1+sq);}
B.spots.forEach((s,i)=>{if(s.alive&&s.glow.visible){const k=1+Math.sin(T*6+i)*0.15;s.glow.scale.set(k,k,1);s.glow.material.opacity=0.45+Math.sin(T*6+i)*0.25;}});
if(phase==='eggs'&&Math.random()<dt*0.25&&Math.hypot(player.x-B.g.position.x,player.z-B.g.position.z)<16)zzz(B.g.position.x+2,B.g.position.y+5,B.g.position.z+2);
if(B.awake){B.eyes.forEach(p=>{p.position.x=Math.max(-0.2,Math.min(0.2,(player.x-B.g.position.x-(player.z-B.g.position.z))*0.01));});
if(playing&&phase==='boss'){B.lobT-=dt;if(B.lobT<=0){B.lobT=mode==='turbo'?1.6:mode==='adv'?2.5:3.4;if(Math.hypot(player.x-B.g.position.x,player.z-B.g.position.z)<22)lob();}}}}
for(let i=zzs.length-1;i>=0;i--){const z=zzs[i];z.t+=dt;z.sp.position.y+=dt*1.2;z.sp.position.x+=Math.sin(T*3+z.ph)*dt*0.6;z.sp.scale.setScalar(0.5+z.t*0.5);z.sp.material.opacity=Math.max(0,1-z.t/1.8);if(z.t>1.8){scene.remove(z.sp);z.sp.material.dispose();zzs.splice(i,1);}}
// sneezing volcano
if(playing&&phase==='eggs'){sneezeT-=dt;const vg=volcano.position;
if(sneezeT<1.6&&!sneezeWarn){sneezeWarn=true;SFX.ahh();}
if(sneezeWarn){const k=1+Math.max(0,1.6-sneezeT)*0.08;volcano.scale.set(1/k,k,1/k);}
if(sneezeT<=0){sneezeWarn=false;sneezeT=14+Math.random()*6;volcano.scale.set(1.25,0.8,1.25);setTimeout(()=>volcano.scale.set(1,1,1),180);SFX.choo();
burst(vg.x,vg.y+6.5,vg.z,0xffffff,18,7);
if(candies.length<70)for(let i=0;i<8;i++){const a=Math.atan2(16,16)+(Math.random()-0.5)*1.6,sp=4+Math.random()*5;const c=makeCandy(vg.x,vg.z,vg.y+6.5,true);c.vx=Math.sin(a)*sp;c.vz=Math.cos(a)*sp;c.vy=10+Math.random()*4;}
if(Math.hypot(player.x-vg.x,player.z-vg.z)<26)say('AH-CHOO! The volcano sneezed candies! 🍬',2500);}}
// princess
{const d=Math.hypot(player.x-PR.x,player.z-PR.z);talkCd-=dt;
const wave=phase!=='eggs'||d<5;princess.arms[1].rotation.x=wave?-1.6+Math.sin(T*8)*0.5:0;princess.arms[0].rotation.x=phase==='won'?-1.6+Math.sin(T*8+1)*0.5:0;
princess.tail.rotation.y=Math.sin(T*2.5)*0.3;princess.headPivot.rotation.x=Math.sin(T*1.7)*0.06;
const pg=groundAt(PR.x,PR.z);princess.R.position.y=pg+(phase==='won'?Math.abs(Math.sin(T*5))*0.8:0);
mama.R.position.y=pg+(phase==='won'?Math.abs(Math.sin(T*4+1))*0.6:0);mama.tail.rotation.y=Math.sin(T*2)*0.3;mama.headPivot.rotation.x=Math.sin(T*1.4)*0.08;
const mw=phase!=='eggs'||d<7;mama.arms[0].rotation.x=mw?-1.5+Math.sin(T*7)*0.5:0;mama.arms[1].rotation.x=mw?-1.5+Math.sin(T*7+1.5)*0.5:0;
if(d<12)mama.R.rotation.y=Math.atan2(player.x-mama.R.position.x,player.z-mama.R.position.z);
if(phase!=='eggs'||d<6)princess.R.rotation.y=Math.atan2(player.x-PR.x,player.z-PR.z);
if(phase==='hub'&&d<3.6&&talkCd<=0){talkCd=9;SFX.hello();say('Mama Rex: Hello, Rexy! Each gate goes to a land. Find my eggs there! 🥚',3000);}
if(phase==='eggs'&&d<3.6&&talkCd<=0){talkCd=9;SFX.hello();say(`Mama Rex: Thank you, Rexy! ${10-saved} more egg${10-saved>1?'s':''} to find.`,3000);}
if(phase==='princess'&&playing&&d<2.8)winGame();
prPad.material.opacity=0.45+Math.sin(T*4)*0.15;}
// guide arrow to nearest egg or the princess
{let tx=null,tz=null;if(phase==='princess'){tx=PR.x;tz=PR.z;}else if(phase==='boss'){let bd=1e9;for(const s of boss.spots){if(!s.alive)continue;const d=Math.hypot(s.x-player.x,s.z-player.z);if(d<bd){bd=d;tx=s.x;tz=s.z;}}}else if(phase==='hub'){let bd=1e9;const st=mapStars();for(const G of GATES){if(st[G.to])continue;const d=Math.hypot(G.x-player.x,G.z-player.z);if(d<bd){bd=d;tx=G.x;tz=G.z;}}}else if(phase==='eggs'){let bd=1e9;for(const e of eggs){if(!e.alive)continue;const d=Math.hypot(e.x-player.x,e.z-player.z);if(d<bd){bd=d;tx=e.x;tz=e.z;}}}
if(tx!==null&&playing){const dx=tx-player.x,dz=tz-player.z,d=Math.hypot(dx,dz);arrow.visible=d>5;arrow.position.set(player.x+dx/d*1.4,player.y+3.2+Math.sin(T*5)*0.15,player.z+dz/d*1.4);arrow.rotation.y=Math.atan2(dx,dz);}else arrow.visible=false;}
if(trophy.visible){trophy.position.set(player.x,player.y+3.4+Math.sin(T*3)*0.2,player.z);trophy.rotation.y+=dt*2;}
if(toyDuck){toyDuck.cd-=dt;const d=Math.hypot(player.x-toyDuck.x,player.z-toyDuck.z);if(playing&&d<3.9&&toyDuck.cd<=0){toyDuck.cd=1.2;toyDuck.sq=1;SFX.squeak();SFX.honk();burst(toyDuck.x,groundAt(toyDuck.x,toyDuck.z)+5,toyDuck.z,0xffe633,8,4);}
const tr=trees.find(t=>t.g===toyDuck.g);if(tr&&tr.shake>0.5&&toyDuck.sq<=0){toyDuck.sq=1;SFX.squeak();}
if(toyDuck.sq>0){toyDuck.sq-=dt*1.6;const q=Math.sin(toyDuck.sq*Math.PI*4)*0.12*toyDuck.sq;toyDuck.g.scale.set(1+q,1-q,1+q);}else toyDuck.g.scale.set(1,1,1);}
// trees shake
trees.forEach(t=>{if(t.shake>0){t.shake-=dt*1.5;t.g.rotation.z=Math.sin(T*40)*0.08*t.shake;}else t.g.rotation.z=0;});
// volcano puffs
puffs.forEach(p=>{p.t+=dt*0.25;if(p.t>1)p.t-=1;const v=volcano.position;p.m.position.set(v.x+Math.sin(p.t*9)*0.6,v.y+6.2+p.t*6,v.z+p.t*1.5);p.m.scale.setScalar(0.6+p.t*1.8);p.m.material.opacity=0.8*(1-p.t);});
if(flakes.length)for(const f of flakes){f.position.y-=dt*2.2;f.position.x+=Math.sin(T+f.position.z)*dt*0.4;if(f.position.y<groundAt(f.position.x,f.position.z)){f.position.set(player.x+(Math.random()-0.5)*40,player.y+10+Math.random()*6,player.z+(Math.random()-0.5)*40);}}
if(water&&MP.sea)water.position.y=MP.waterY+Math.sin(T*1.2)*0.08;
clouds.forEach((c,i)=>{c.position.x+=dt*(0.4+i*0.05);if(c.position.x>40)c.position.x=-40;});
for(let i=bubbles.length-1;i>=0;i--){const b=bubbles[i];b.m.position.y+=b.sp*dt;b.m.position.x+=Math.sin(T*4+b.ph)*dt*0.3;if(b.m.position.y>POND.surf+0.05||!inPond(b.m.position.x,b.m.position.z)&&b.m.position.y>3){scene.remove(b.m);bubbles.splice(i,1);}}
for(const f of fish){f.a+=dt*f.sp;f.g.position.set(POND.x+Math.cos(f.a)*f.r,f.y+(f.duck?Math.sin(T*2+f.a)*0.05:Math.sin(T*3+f.a)*0.1),POND.z+Math.sin(f.a)*f.r);f.g.rotation.y=-f.a;if(!f.duck&&Math.random()<dt*0.4)bubble(f.g.position.x,f.g.position.y,f.g.position.z,1);}
babies.forEach(b=>{if(inPond(b.x,b.z)&&b.y<POND.surf-0.3&&Math.random()<dt*1.2)bubble(b.x,b.y+0.6,b.z,1);});
// particles
for(let i=parts.length-1;i>=0;i--){const p=parts[i];p.vy-=14*dt;p.m.position.x+=p.vx*dt;p.m.position.y+=p.vy*dt;p.m.position.z+=p.vz*dt;p.life-=dt*0.9;p.m.scale.setScalar(Math.max(0.01,p.life));p.m.rotation.x+=dt*5;if(p.life<=0){scene.remove(p.m);p.m.material.dispose();parts.splice(i,1);}}
// camera: behind and above. With 2 players it looks at the middle and moves back to show both. It moves back when a plane flies high,
// rises over hills and walls so they never block the view, and hides a tree or a toy that comes between the camera and the dinos.
if(mag>0&&playing){let dy=player.face-camYaw;while(dy>Math.PI)dy-=Math.PI*2;while(dy<-Math.PI)dy+=Math.PI*2;if(Math.abs(dy)<2.2)camYaw+=dy*dt*0.6;}
updateCamera(dt,mag,running);
sun.position.set(camTX+15,30,camTZ+10);sun.target.position.set(camTX,0,camTZ);
updateSky(dt,T);
fadeSigns();renderer.render(scene,camera);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
window.__game={player,get eggs(){return eggs},get saved(){return saved},get phase(){return phase},get candies(){return candies},get candyN(){return candyN},PR,mush,get bugs(){return bugs},get hearts(){return hearts},get mode(){return mode},setMode,VOLC,erupt,get fireballs(){return fireballs},shoot,get mapId(){return mapId},setMap,buildMap,MAP_ORDER,get gifts(){return gifts},givePower,get power(){return power},get goldEgg(){return goldEgg},get animals(){return animals},startGame,rescueAll(){eggs.filter(e=>e.alive).forEach(rescue)},get boss(){return boss},tickle,beatBoss(){if(phase==='boss')boss.spots.forEach(tickle)},get pileT(){return pileT},get vehicles(){return vehicles},toggleRide,get ride(){return ride},POND,get uw(){return uw},get mapDamaged(){return mapDamaged},get blasts(){return blasts},get GATES(){return GATES},travel,goLand,startIsland,get traveling(){return traveling},get cousins(){return cousins},get dog(){return dog},get fball(){return fball},HOUSE,YARD,kickBall,findCousin,get partyT(){return partyT},get fetchN(){return fetchN},set camYaw(v){camYaw=v}};
Object.defineProperties(window.__game,{S2:{get:()=>S2},twoP:{get:()=>twoP},cur:{get:()=>cur},camera:{get:()=>camera},player1:{get:()=>P1O},trees:{get:()=>trees}});Object.defineProperties(window.__game,{camYaw:{get:()=>camYaw,set:v=>{camYaw=v;}},eggBoxes:{get:()=>eggBoxes},race:{get:()=>race},roomKids:{get:()=>roomKids},wx:{get:()=>wx},babies:{get:()=>babies},gateObjs:{get:()=>gateObjs}});Object.assign(window.__game,{openBox,startRace,shootingStar,insideWall,groundAt});Object.assign(window.__game,{setTwo,asP2,placeP2,stepPlayer,nearVeh});
Object.defineProperties(window.__game,{pools:{get:()=>pools},rexMats:{get:()=>rexMats},rex2Mats:{get:()=>rex2Mats},t2:{get:()=>t2},saberHits:{get:()=>saberHits}});Object.assign(window.__game,{hurt,tag,sabers,rex:REX1}); // test hooks for the two-player checks
boot.js (older-browser helpers and the no-3D message)13 lines
if(!String.prototype.padStart)String.prototype.padStart=function(n,c){var s=String(this);c=c||' ';while(s.length<n)s=c+s;return s.slice(-Math.max(n,String(this).length));};
if(!Element.prototype.closest)Element.prototype.closest=function(q){var e=this;while(e&&e.nodeType===1){if(e.matches?e.matches(q):e.webkitMatchesSelector(q))return e;e=e.parentElement;}return null;};
window.__tv=/Web0S|webOS|SmartTV|SMART-TV|Tizen|NetCast|HbbTV|PlayStation|AFT|BRAVIA/i.test(navigator.userAgent);
if(!window.PointerEvent){(function(){var map={pointerdown:['mousedown','touchstart'],pointermove:['mousemove','touchmove'],pointerup:['mouseup','touchend'],pointercancel:['touchcancel']};
var add=EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener=function(type,fn,opt){var self=this;if(!map[type])return add.call(this,type,fn,opt);
map[type].forEach(function(t){add.call(self,t,function(e){if(e.changedTouches){for(var k=0;k<e.changedTouches.length;k++){var tc=e.changedTouches[k];fn.call(self,{type:type,pointerId:tc.identifier+2,pointerType:'touch',clientX:tc.clientX,clientY:tc.clientY,target:t==='touchstart'?e.target:(document.elementFromPoint(tc.clientX,tc.clientY)||e.target),preventDefault:function(){e.preventDefault();},stopPropagation:function(){e.stopPropagation();}});}}
else fn.call(self,{type:type,pointerId:1,pointerType:'mouse',clientX:e.clientX,clientY:e.clientY,target:e.target,button:e.button,preventDefault:function(){e.preventDefault();},stopPropagation:function(){e.stopPropagation();}});},t.indexOf('touch')===0?{passive:false}:opt);});};
if(!Element.prototype.setPointerCapture)Element.prototype.setPointerCapture=function(){};})();}
window.__bootErr=[];
function __bootMsg(t){try{var c=document.querySelector('#start .card');if(!c)return;var p=document.getElementById('bootmsg');if(!p){p=document.createElement('p');p.id='bootmsg';p.style.cssText='background:#fff3e0;border:3px solid #ff9800;border-radius:14px;padding:10px;font-size:15px;line-height:1.35;color:#5d4037';c.insertBefore(p,c.children[2]||null);}p.textContent=t;var g=document.getElementById('go');if(g&&window.__no3d)g.style.display='none';}catch(e){}}
window.addEventListener('error',function(e){var m=(e&&e.message)||'error';window.__bootErr.push(m);if(!window.__game&&!window.__no3d)__bootMsg('The game could not start in this browser. ('+m+')');});
index.html60 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title>T-Rex Kingdom: a free 3D game for young children</title>
<meta name="description" content="A block-world 3D game for young kids: a baby T-rex walks, drives and flies through magic gates into twelve lands to find Mama Rex's eggs and bring them home.">
<meta name="theme-color" content="#9fe0ff">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="T-Rex">
<meta name="mobile-web-app-capable" content="yes">
<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="stylesheet" href="./trex.css">
</head>
<body>
<canvas id="c"></canvas>
<div id="hud"><div class="pill" id="eggs">🥚 0 / 10</div><div class="pill" id="candy">🍬 0</div><div class="pill" id="hearts" hidden>❤️ 3</div><div class="pill" id="power" hidden></div><button id="home" aria-label="Home: back to the maps">🏠</button><button id="fs" aria-label="Full screen" hidden>⛶</button><button id="snd" aria-label="Sound on or off">🔊</button></div>
<div id="knobBase"><div id="knob"></div></div>
<div id="knobBase2"><div id="knob2"></div></div><div class="plab" id="lab1" hidden><span class="dino">🦖</span> Player 1</div><div class="plab p2" id="lab2" hidden><span class="dino">🦕</span> Player 2</div>
<div id="p2ctl" hidden><button id="ride2" hidden aria-label="Player 2: get in or out">🚗 GET IN</button><button id="run2" aria-label="Player 2: run">RUN</button><button id="fire2" aria-label="Player 2: fire">🔥<br>FIRE</button><button id="jump2" aria-label="Player 2: jump, hold to roar">JUMP<br><span class="sub">hold = ROAR</span></button></div>
<div id="uwtint"></div><div id="fade"></div><button id="ride" hidden aria-label="Get in or out">🚗 GET IN</button><button id="run" aria-label="Run fast on or off">RUN</button><button id="fire" aria-label="Fire">🔥<br>FIRE</button><button id="jump" aria-label="Jump. Hold to roar">JUMP<br><span class="sub">hold = ROAR</span><div class="ring" id="ring"></div></button>
<div id="hint">Find the lost eggs! 🥚</div>
<div class="screen" id="start"><div class="card">
<h1 class="nowrap">🦖 T‑Rex Kingdom</h1><p class="small" id="ver">v15 · <a href="/games/">All games</a> · <a href="/cases/trex-kingdom/">How it was made</a></p>
<p class="story">🦖🦕 New: 2 players! 🛫 A big jet, 🏁 races, 🌧️ Rain Land with shooting stars, and 🛏️ the rooms inside the Blue House.</p>
<div class="modes" role="group" aria-label="Game mode"><button class="mode on" data-m="easy">🌼 Easy</button><button class="mode" data-m="adv">🔥 Adventure</button><button class="mode" data-m="turbo">⚡ Turbo</button></div>
<p class="small" id="modeTxt"></p>
<div class="modes players" role="group" aria-label="Players"><button class="mode" id="p1b">🦖 1 player</button><button class="mode" id="p2b">🦖🦕 2 players</button></div>
<button class="big" id="go">PLAY</button>
<p class="small">No sound? Turn the volume up with the side buttons and tap the screen once. It plays even when an iPhone is on silent.</p>
<details class="small"><summary>Grown-ups: jump straight to a land</summary><div class="maps" role="group" aria-label="Map"></div></details>
<details class="small"><summary>Grown-ups: controls</summary><p class="small">Touch: swipe to walk. JUMP jumps, hold it to ROAR. FIRE tickles Grumbo and makes animals and toys do tricks. Walk to the car or the plane and tap GET IN (V key, △ on a controller). In the plane, hold JUMP to fly up. Walk into the pond to swim under water; tap JUMP to swim up. Bump an animal or toy to push it (RUN pushes it out of the land; it comes back), or jump on it to squish it flat like a pancake. Walk to the purple blaster and tap 💥 GET IN: turn with the joystick and hold FIRE to blast holes in the land. Phones that can vibrate, iPhones with iOS 18 and game controllers buzz. Blue House: walk near the bushes to find the 9 hiding cousins, and walk into the red ball (or fire at it) so Azizam the dog can fetch it. RUN goes fast. 2 players: tap 🦖🦕 2 players. Player 1 (green) uses the right side of the screen, Player 2 (blue) uses the left side, each with a joystick and buttons. A game controller can be Player 2. The big jet 🛫 flies high, the babies ride on it and a friend can HOP ON. Some eggs hide in a box 📦 or a tree 🌳: shoot it with FIRE. The Blue House door goes inside to 9 cousin rooms. Race Track: drive a car to the yellow ring to race 3 laps. Rain Land: after the rain, a rainbow, then stars, planets and shooting stars.<br>Computer: arrows or WASD walk, Space jumps (hold = roar), F fires, Shift runs, R roars, V gets in. Player 2 on the keys: arrows walk, Enter jumps (hold = roar), / fires, . gets in, right Shift runs.<br>🏠 or Esc goes back to the island. On the island it opens this card. Each land has 3 gates near the start: back to the island and to the two lands next door. Game controller: left stick walks, ✕ jumps (hold = roar), ▢ or ○ fires, R1 or R2 runs, △ roars. D-pad picks map and mode.</p></details>
</div></div>
<div class="screen" id="lose" hidden><div class="card">
<div id="sad">😴</div>
<h1>Oh no!</h1>
<p>Rexy got too many bumps and needs a nap.</p>
<p id="losetxt"></p>
<button class="big" id="retry">AGAIN! ↻</button>
<p><button class="mode" id="toeasy">🌼 Play Easy mode</button></p>
</div></div>
<div class="screen" id="win" hidden><div class="card">
<div id="trophy">🏆</div>
<h1>You did it!</h1>
<p id="winstory">The babies are home with Mama Rex! Princess Pinky gives Rexy the golden trophy.</p>
<p id="winmap"></p>
<p id="wintime"></p>
<p id="winbest" class="small"></p>
<button class="big" id="next">🏝️ BACK TO THE ISLAND</button>
<p><button class="mode" id="again">↻ Play this map again</button></p>
</div></div>
<script src="./boot.js"></script>
<script src="../../animations/vendor/three-r128.min.js"></script>
<script src="./trex.js"></script>
</body>
</html>
trex.css (layout, two sets of buttons, screens)78 lines
:root{--sky:#9fe0ff;--ink:#21313a;--btn:#ff8a3d;--btn2:#ffd24d;--panel:rgba(255,255,255,.92);--good:#3cb371;color-scheme:light}
html,body{height:100%;margin:0;overflow:hidden;background:var(--sky);touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
body{font-family:"Baloo 2","Trebuchet MS",system-ui,sans-serif;color:var(--ink)}
canvas#c{position:fixed;left:0;top:0;width:100vw;height:100vh;display:block}
#hud{position:fixed;top:10px;top:calc(env(safe-area-inset-top,0px) + 10px);left:12px;left:max(12px,env(safe-area-inset-left,0px));right:12px;right:max(12px,env(safe-area-inset-right,0px));display:flex;justify-content:space-between;align-items:center;pointer-events:none;gap:8px}
.pill{background:var(--panel);border-radius:999px;padding:6px 14px;font-size:22px;font-weight:800;box-shadow:0 3px 0 rgba(0,0,0,.15);display:flex;gap:6px;align-items:center}
#home{pointer-events:auto;border:0;font-size:26px;width:60px;height:60px;border-radius:50%;background:var(--panel);box-shadow:0 3px 0 rgba(0,0,0,.15);margin-left:auto;flex:none}
#fs{pointer-events:auto;border:0;font-size:26px;width:60px;height:60px;border-radius:50%;background:var(--panel);box-shadow:0 3px 0 rgba(0,0,0,.15);flex:none}
#snd{pointer-events:auto;border:0;font-size:26px;width:60px;height:60px;border-radius:50%;background:var(--panel);box-shadow:0 3px 0 rgba(0,0,0,.15)}
#jump{position:fixed;right:calc(20px + 4px);right:calc(max(20px,env(safe-area-inset-right,0px)) + 4px);bottom:28px;bottom:calc(env(safe-area-inset-bottom,0px) + 28px);width:120px;height:120px;border-radius:50%;border:6px solid #fff;background:radial-gradient(circle at 35% 30%,var(--btn2),var(--btn));color:#fff;font-weight:900;font-size:22px;line-height:1.05;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 6px 0 rgba(0,0,0,.2);touch-action:none}
#fire{position:fixed;right:calc(20px + 136px);right:calc(max(20px,env(safe-area-inset-right,0px)) + 136px);bottom:30px;bottom:calc(env(safe-area-inset-bottom,0px) + 30px);width:96px;height:96px;border-radius:50%;border:5px solid #fff;background:radial-gradient(circle at 35% 30%,#ffb199,#ff3d2e);color:#fff;font-weight:900;font-size:18px;line-height:1.05;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 6px 0 rgba(0,0,0,.2);touch-action:none}
#run{position:fixed;right:calc(20px + 16px);right:calc(max(20px,env(safe-area-inset-right,0px)) + 16px);bottom:166px;bottom:calc(env(safe-area-inset-bottom,0px) + 166px);width:112px;height:64px;border-radius:22px;border:5px solid #fff;background:linear-gradient(#8be37b,#2eaa4f);color:#fff;font-weight:900;font-size:18px;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 5px 0 rgba(0,0,0,.2);touch-action:none}
#ride{position:fixed;right:calc(20px + 10px);right:calc(max(20px,env(safe-area-inset-right,0px)) + 10px);bottom:244px;bottom:calc(env(safe-area-inset-bottom,0px) + 244px);width:124px;height:60px;border-radius:20px;border:5px solid #fff;background:linear-gradient(#7fd3ff,#2f80ed);color:#fff;font-weight:900;font-size:17px;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 5px 0 rgba(0,0,0,.2);touch-action:none}
#jump2{position:fixed;left:calc(20px + 4px);left:calc(max(20px,env(safe-area-inset-left,0px)) + 4px);bottom:28px;bottom:calc(env(safe-area-inset-bottom,0px) + 28px);width:120px;height:120px;border-radius:50%;border:6px solid #fff;background:radial-gradient(circle at 35% 30%,#9fd8ff,#2f80ed);color:#fff;font-weight:900;font-size:22px;line-height:1.05;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 6px 0 rgba(0,0,0,.2);touch-action:none}
#fire2{position:fixed;left:calc(20px + 136px);left:calc(max(20px,env(safe-area-inset-left,0px)) + 136px);bottom:30px;bottom:calc(env(safe-area-inset-bottom,0px) + 30px);width:96px;height:96px;border-radius:50%;border:5px solid #fff;background:radial-gradient(circle at 35% 30%,#ffb199,#ff3d2e);color:#fff;font-weight:900;font-size:18px;line-height:1.05;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 6px 0 rgba(0,0,0,.2);touch-action:none}
#run2{position:fixed;left:calc(20px + 16px);left:calc(max(20px,env(safe-area-inset-left,0px)) + 16px);bottom:166px;bottom:calc(env(safe-area-inset-bottom,0px) + 166px);width:112px;height:64px;border-radius:22px;border:5px solid #fff;background:linear-gradient(#90caf9,#1e6fd9);color:#fff;font-weight:900;font-size:18px;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 5px 0 rgba(0,0,0,.2);touch-action:none}
#run2.on{background:linear-gradient(#ffe14d,#ff8a3d)}#jump2.down,#fire2.down{transform:translateY(4px) scale(.96)}
#ride2{position:fixed;left:calc(20px + 10px);left:calc(max(20px,env(safe-area-inset-left,0px)) + 10px);bottom:244px;bottom:calc(env(safe-area-inset-bottom,0px) + 244px);width:124px;height:60px;border-radius:20px;border:5px solid #fff;background:linear-gradient(#b3e5fc,#0d47a1);color:#fff;font-weight:900;font-size:17px;font-family:inherit;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 5px 0 rgba(0,0,0,.2);touch-action:none}
.plab{position:fixed;bottom:314px;bottom:calc(env(safe-area-inset-bottom,0px) + 314px);right:calc(20px + 8px);right:calc(max(20px,env(safe-area-inset-right,0px)) + 8px);background:linear-gradient(#a5e88f,#2eaa4f);color:#fff;border:4px solid #fff;border-radius:18px;padding:4px 12px 4px 6px;font-weight:900;font-size:18px;text-shadow:0 2px 0 rgba(0,0,0,.25);box-shadow:0 4px 0 rgba(0,0,0,.18);pointer-events:none;display:flex;align-items:center;gap:6px}
.plab .dino{font-size:30px;line-height:1;display:inline-block;animation:dwig 1.2s ease-in-out infinite alternate}.plab.p2{right:auto;left:calc(20px + 8px);left:calc(max(20px,env(safe-area-inset-left,0px)) + 8px);background:linear-gradient(#90caf9,#1e6fd9)}.plab.p2 .dino{transform:scaleX(-1)}
@keyframes dwig{to{transform:rotate(-12deg) translateY(-3px)}}.plab.p2 .dino{animation-name:dwig2}@keyframes dwig2{from{transform:scaleX(-1)}to{transform:scaleX(-1) rotate(-12deg) translateY(-3px)}}
body.two #jump{background:radial-gradient(circle at 35% 30%,#c5f5a5,#2eaa4f)}
#knobBase2{position:fixed;width:130px;height:130px;margin:-65px 0 0 -65px;border-radius:50%;background:rgba(144,202,249,.35);border:4px solid rgba(255,255,255,.8);pointer-events:none;display:none}
#knob2{position:absolute;left:50%;top:50%;width:60px;height:60px;margin:-30px 0 0 -30px;border-radius:50%;background:#bbdefb;box-shadow:0 3px 0 rgba(0,0,0,.2)}
@media (max-height:500px){.plab{bottom:256px;bottom:calc(env(safe-area-inset-bottom,0px) + 256px);font-size:14px}#ride2{bottom:200px;bottom:calc(env(safe-area-inset-bottom,0px) + 200px);height:50px;width:110px;font-size:15px}}
@media (max-width:700px){body.two #jump,#jump2{width:96px;height:96px;font-size:18px}body.two #fire,#fire2{width:78px;height:78px;font-size:15px}#fire2{left:calc(14px + 106px);left:calc(max(14px,env(safe-area-inset-left,0px)) + 106px)}body.two #fire{right:calc(14px + 106px);right:calc(max(14px,env(safe-area-inset-right,0px)) + 106px)}}
@media (max-width:430px){body.two #jump,#jump2{width:74px;height:74px;font-size:14px;border-width:4px}body.two #fire,#fire2{width:58px;height:58px;font-size:12px;border-width:4px}#fire2{left:calc(14px + 82px);left:calc(max(14px,env(safe-area-inset-left,0px)) + 82px)}body.two #fire{right:calc(14px + 82px);right:calc(max(14px,env(safe-area-inset-right,0px)) + 82px)}
body.two #run,#run2{width:84px;height:50px;font-size:15px;bottom:116px;bottom:calc(env(safe-area-inset-bottom,0px) + 116px)}body.two #ride,#ride2{width:96px;height:48px;font-size:13px;bottom:176px;bottom:calc(env(safe-area-inset-bottom,0px) + 176px)}.plab{bottom:232px;bottom:calc(env(safe-area-inset-bottom,0px) + 232px);font-size:13px}.plab .dino{font-size:22px}}
@media (prefers-reduced-motion:reduce){.plab .dino{animation:none}}
#hap{position:fixed;left:-60px;top:-60px;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none}
#fade{position:fixed;top:0;right:0;bottom:0;left:0;inset:0;background:#fff;pointer-events:none;opacity:0;transition:opacity .35s;z-index:40}
#uwtint{position:fixed;top:0;right:0;bottom:0;left:0;inset:0;background:radial-gradient(ellipse at center,rgba(64,170,255,.08),rgba(20,90,200,.38));pointer-events:none;opacity:0;transition:opacity .3s}
@media (max-height:500px){#ride{bottom:200px;bottom:calc(env(safe-area-inset-bottom,0px) + 200px);height:50px;width:110px;font-size:15px}}
#run.on{background:linear-gradient(#ffe14d,#ff8a3d)}
#fire.down{transform:translateY(4px) scale(.96)}
.modes{display:flex;gap:8px;justify-content:center;flex-wrap:wrap;margin:6px 0}
.mode{border:3px solid #fff;border-radius:16px;padding:9px 13px;font-weight:800;font-size:17px;font-family:inherit;background:#e3f2f9;color:var(--ink);box-shadow:0 3px 0 rgba(0,0,0,.12)}
.mode.on{background:#ffd24d;box-shadow:0 0 0 3px #ff8a3d}
.maps{display:flex;gap:6px;justify-content:center;flex-wrap:wrap;margin:8px 0}
.mapb{border:3px solid #fff;border-radius:14px;padding:6px 9px;font-weight:800;font-size:15px;font-family:inherit;background:#e3f2f9;color:var(--ink);box-shadow:0 3px 0 rgba(0,0,0,.12)}
.mapb{display:inline-flex;flex-direction:column;align-items:center;min-width:72px;font-size:13px;padding:6px 6px 4px;line-height:1.1}.mapb .mi{font-size:32px;line-height:1.1}
.mode{font-size:19px;padding:10px 14px}.story{font-size:20px;font-weight:800}.nowrap{white-space:nowrap}
@media (max-width:360px){#candy{display:none}#hud .pill{font-size:14px!important;padding:4px 7px!important}}
@media (max-width:480px){#hud .pill{font-size:15px;padding:4px 8px}#snd,#home,#fs{flex:none;width:46px;height:46px;font-size:22px}#hud{gap:4px}}
@media (max-width:480px){#start .card h1{font-size:31px}#start .card{padding:16px 14px}.mapb{min-width:62px;font-size:12px}.mapb .mi{font-size:26px}.mode{font-size:16px;padding:8px 10px}.story{font-size:17px}}
@media (max-height:620px){#ver,.story{display:none}}
@media (max-height:500px){#ver,.story,#winstory,#winbest{display:none}#start .card{max-width:min(680px,calc(100% - 8px))}.maps{flex-wrap:nowrap;margin:4px 0}.mapb{min-width:0;flex:1;font-size:10px;padding:3px 2px}.mapb .mi{font-size:22px}.modes{margin:2px 0}}
.mapb.on{background:#9be88b;box-shadow:0 0 0 3px #2eaa4f}
#sad{font-size:80px;line-height:1}
.pill{white-space:nowrap}
@media (max-width:480px){.pill{font-size:17px;padding:5px 10px}#hud{gap:6px}}
#jump.down{transform:translateY(4px) scale(.96);box-shadow:0 2px 0 rgba(0,0,0,.2)}
#jump .ring{position:absolute;inset:-12px;border-radius:50%;border:6px solid transparent;border-top-color:#fff;opacity:0}
#stick{position:fixed;left:0;bottom:16px;bottom:calc(env(safe-area-inset-bottom,0px) + 16px);width:55%;height:60%;touch-action:none}
#knobBase{position:fixed;width:130px;height:130px;margin:-65px 0 0 -65px;border-radius:50%;background:rgba(255,255,255,.35);border:4px solid rgba(255,255,255,.8);pointer-events:none;display:none}
#knob{position:absolute;left:50%;top:50%;width:60px;height:60px;margin:-30px 0 0 -30px;border-radius:50%;background:#fff;box-shadow:0 3px 0 rgba(0,0,0,.2)}
#hint{position:fixed;left:16px;left:max(16px,env(safe-area-inset-left,0px));bottom:24px;bottom:calc(env(safe-area-inset-bottom,0px) + 24px);font-size:18px;font-weight:700;background:var(--panel);padding:8px 14px;border-radius:14px;pointer-events:none;max-width:min(52%,calc(100% - 190px));transition:opacity .6s}
[hidden]{display:none!important}
.card{max-height:calc(100% - 8px);overflow:auto;-webkit-overflow-scrolling:touch}
@media (max-height:500px){.mode{font-size:14px;padding:6px 10px}#sad{font-size:48px}.card{padding:12px 20px}.card h1{font-size:28px}.card p{font-size:15px;margin:5px 0}.big{padding:10px 32px;font-size:22px}.small{font-size:12px}#trophy{font-size:56px}}
#hint{left:50%;right:auto;transform:translateX(-50%);bottom:auto;top:74px;top:calc(env(safe-area-inset-top,0px) + 74px);max-width:min(560px,calc(100% - 32px));text-align:center}
@media (max-width:380px){#hint{font-size:16px}}
.screen{position:fixed;top:0;right:0;bottom:0;left:0;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(159,224,255,.55);padding:16px}
.card{box-sizing:border-box;background:var(--panel);border-radius:28px;padding:24px 28px;text-align:center;max-width:440px;box-shadow:0 8px 0 rgba(0,0,0,.12)}
.card h1{margin:0 0 4px;font-size:40px;line-height:1;color:#2f8f4e;text-wrap:balance}
.card p{font-size:19px;margin:8px 0}
.big{border:0;border-radius:999px;padding:16px 40px;font-weight:900;font-size:28px;font-family:inherit;color:#fff;background:linear-gradient(var(--btn2),var(--btn));box-shadow:0 6px 0 #c4561a;margin-top:10px}
.big:active{transform:translateY(4px);box-shadow:0 2px 0 #c4561a}
.small{font-size:14px;opacity:.75}
#trophy{font-size:96px;line-height:1;animation:bob 1s ease-in-out infinite alternate}
@keyframes bob{to{transform:translateY(-10px) rotate(6deg)}}
@media (prefers-reduced-motion:reduce){#trophy{animation:none}}
/* two-player games: tag pill under the top bar; narrow phones keep both players' buttons apart */
#tagpill{position:fixed;top:64px;top:calc(env(safe-area-inset-top,0px) + 64px);left:50%;transform:translateX(-50%);font-size:17px;padding:4px 12px;border:3px solid #2eaa4f;pointer-events:none;animation:tagb .5s ease-in-out infinite alternate}#tagpill.p2{border-color:#1e6fd9}
@keyframes tagb{to{transform:translateX(-50%) translateY(-3px)}}body.two #hint{top:108px;top:calc(env(safe-area-inset-top,0px) + 108px)}
@media (max-width:420px){body.two #jump,#jump2{width:88px;height:88px;font-size:16px}body.two #fire,#fire2{width:70px;height:70px;font-size:14px}#fire2{left:calc(12px + 100px);left:calc(max(12px,env(safe-area-inset-left,0px)) + 100px)}body.two #fire{right:calc(12px + 100px);right:calc(max(12px,env(safe-area-inset-right,0px)) + 100px)}}
@media (prefers-reduced-motion:reduce){#tagpill{animation:none}}
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.