// Fluffy Cat Kingdom - boot, game loop, adventure mode, HUD and victory. import './style.css'; import * as THREE from 'three'; import { setQuality, sharedLight, softMaterial } from './render/fur'; import { buildVillage } from './world/village'; import { makeSky } from './render/sky'; import { Input } from './input/input'; import { Player } from './player/player'; import { Cat, CAT_DEFS } from './cats/cats'; import type { CatWorld } from './cats/cats'; import { Particles } from './fx/particles'; import { Princess, makeTrophy } from './game/characters'; import { TinyRex } from './game/trex'; import { Sanctuary } from './game/sanctuary'; import { applyOutfit } from './game/wardrobe'; import { Quests } from './game/quests'; import { Mountain } from './game/mountain'; import { audio } from './audio'; import { angleDiff, clamp, damp, lerp } from './core/util'; import { loadSave, persist } from './save/save'; const isTouch = matchMedia('(pointer: coarse)').matches || 'ontouchstart' in window; setQuality(isTouch); const save = loadSave(); const canvas = document.getElementById('game') as HTMLCanvasElement; const renderer = new THREE.WebGLRenderer({ canvas, antialias: !isTouch, powerPreference: 'high-performance' }); let pixelRatio = Math.min(devicePixelRatio, isTouch ? 1.6 : 2); renderer.setPixelRatio(pixelRatio); renderer.outputColorSpace = THREE.SRGBColorSpace; const scene = new THREE.Scene(); scene.background = new THREE.Color('#ffd9ec'); const camera = new THREE.PerspectiveCamera(55, 1, 0.1, 260); function resize() { renderer.setSize(innerWidth, innerHeight, false); camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); } addEventListener('resize', resize); resize(); const sky = makeSky(); scene.add(sky); sharedLight.uFogColor.value.set('#ffe0f0'); const level = buildVillage(7); scene.add(level.group); const fx = new Particles(); scene.add(fx.mesh); const input = new Input(canvas); const player = new Player(level.world); scene.add(player.root, player.shadowMesh); applyOutfit(player, save.outfit); player.body.pos.copy(level.spawn); /* Player 2: a second catcher in a blue hoodie, played with a second controller (co-op on the same screen). Press any face button on the second controller during play to join. Player 2 catches cats and picks up candy for the team; one camera frames both, and player 2 pops back beside player 1 if they get too far apart. */ const player2 = new Player(level.world, '#2f8cff'); player2.setHood('#2f8cff', '#bfe3ff'); player2.root.traverse(o => { const m = (o as THREE.Mesh).material as THREE.ShaderMaterial | undefined; const u = m && m.uniforms && m.uniforms.uColor; if (u && (u.value as THREE.Color).getHexString() === '7b5cc4') (o as THREE.Mesh).material = softMaterial('#2f6fd6'); }); player2.root.visible = false; player2.shadowMesh.visible = false; scene.add(player2.root, player2.shadowMesh); let p2On = false; function placeP2() { const a = player.yaw + Math.PI / 2; player2.body.pos.copy(player.body.pos).add(new THREE.Vector3(Math.sin(a) * 1.6, 0.6, Math.cos(a) * 1.6)); player2.body.vel.set(0, 0, 0); player2.yaw = player.yaw; } function setP2(on: boolean) { if (on === p2On) return; p2On = on; player2.root.visible = on; player2.shadowMesh.visible = on; if (on) { placeP2(); fx.emit(player2.body.pos.clone().setY(player2.body.pos.y + 1), 30, { color: ['#7cc8ff', '#ffffff', '#b79bff'], speed: 3, up: 3, size: 0.1 }); audio.play('unlock'); toast('πŸ’™ Player 2 joined!'); } else toast('Player 2 left. Press βœ• on the second controller to join again.'); } const sugarbell = new Princess('#ff9cc9', '#ffc4de', '#ffcf7a'); // Princess Mintly waits in the castle yard with a gift const mintly = new Princess('#9fe8cf', '#d4fff0', '#6fd3c8'); mintly.root.position.set(0, 5, -20.5); scene.add(mintly.root); let mintlyGift = false; // helper arrow: points at the nearest cat when none is close const arrow = new THREE.Mesh(new THREE.ConeGeometry(0.28, 0.7, 12), new THREE.MeshBasicMaterial({ color: '#ffcf3f' })); arrow.geometry.rotateX(Math.PI / 2); scene.add(arrow); let cuddleT = 0; let hitStop = 0, camPunch = 0, candyStreak = 0, candyStreakT = 0, boopT = 0; const catName = (c: Cat) => save.names[c.def.id] || c.def.name; const ring = new THREE.Mesh(new THREE.TorusGeometry(0.75, 0.07, 8, 32), new THREE.MeshBasicMaterial({ color: '#ffcf3f' })); ring.rotation.x = -Math.PI / 2; ring.geometry.rotateX(Math.PI / 2); scene.add(ring); for (let i = 0; i < 6; i++) { const h = new THREE.Mesh(new THREE.SphereGeometry(0.09, 8, 6), new THREE.MeshBasicMaterial({ color: '#ff7fb0' })); const a = i / 6 * Math.PI * 2; h.position.set(Math.cos(a) * 0.75, 0.05, Math.sin(a) * 0.75); ring.add(h); } sugarbell.root.position.copy(level.princessSpot); scene.add(sugarbell.root); // candies const candyGeo = (() => { const g = new THREE.SphereGeometry(0.22, 12, 8); return g; })(); const wrapGeo = new THREE.ConeGeometry(0.16, 0.28, 6); const CANDY_COLORS = ['#ff5e9c', '#ffb648', '#7ee0a1', '#6cc6ff', '#c79bff', '#ffe25e']; interface Candy { pos: THREE.Vector3; mesh: THREE.Group; taken: boolean; fly: number } const candies: Candy[] = level.candySpots.map((p, i) => { const g = new THREE.Group(); const col = CANDY_COLORS[i % CANDY_COLORS.length]; const m = new THREE.MeshLambertMaterial({ color: col, emissive: col, emissiveIntensity: 0.35 }); g.add(new THREE.Mesh(candyGeo, m)); for (const sx of [-1, 1]) { const w = new THREE.Mesh(wrapGeo, m); w.rotation.z = sx * Math.PI / 2; w.position.x = sx * 0.3; g.add(w); } g.position.copy(p); scene.add(g); return { pos: p.clone(), mesh: g, taken: false, fly: 0 }; }); // cats const trail: THREE.Vector3[] = []; const cw: CatWorld = { level, playerPos: player.body.pos, playerSpeed: 0, cats: [], fx, difficulty: save.settings.difficulty, bouncers: level.bouncers, trail, paused: false }; const cats = CAT_DEFS.map((d, i) => { const c = new Cat(d, cw, level.catSpots[i]); scene.add(c.rig.root); return c; }); cw.cats = cats; // tutorial cat starts right in front of the player; the statue stands on the plaza pedestal cats[0].body.pos.set(2, 3.5, 1); cats[0].home.set(2, 3, 1); const statueCat = cats.find(c => c.def.special === 'statue')!; statueCat.body.pos.set(4, 3.6, -3); statueCat.home.set(4, 3, -3); // three tiny T-rex eggs by the plaza (they hatch when you walk up, or by themselves after a while) const REX_LOOKS: [string, string, string, string, string][] = [ ['#9be39b', '#fff4c9', '#fff4c9', '#8fd3ff', '#ff7fb0'], ['#b9a6ff', '#ffe6f2', '#ffe6f2', '#ffcf3f', '#7cc8ff'], ['#ffb37a', '#fff1d6', '#e6f7ff', '#ff9cc9', '#8fe39b'], ]; const REX_SPOTS = [new THREE.Vector3(6.5, 0, 6), new THREE.Vector3(-6.5, 0, 3.5), new THREE.Vector3(6, 0, 0)]; const rexes = REX_SPOTS.map((sp, i) => { const l = REX_LOOKS[i]; const r = new TinyRex(level.world, sp, l[0], l[1], l[2], l[3], l[4], i); scene.add(r.root, r.toy); return r; }); const golden = cats.find(c => c.def.special === 'golden')!; const pedestal = new THREE.Mesh(new THREE.CylinderGeometry(0.8, 0.9, 0.6, 16), new THREE.MeshLambertMaterial({ color: '#e6d4ff' })); pedestal.position.set(4, 3.3, -3); scene.add(pedestal); level.bouncers.length; // pedestal is decorative // lighting colours are in sharedLight; a hemisphere light for Lambert materials scene.add(new THREE.HemisphereLight('#dfe9ff', '#ffc9d9', 1.6)); const sun = new THREE.DirectionalLight('#fff3e0', 1.6); sun.position.set(20, 40, 15); scene.add(sun); // ---------------- UI ---------------- const ui = document.getElementById('ui')!; const el = (h: string) => { const d = document.createElement('div'); d.innerHTML = h.trim(); return d.firstElementChild as HTMLElement; }; const hud = el(``); ui.appendChild(hud); const catRow = hud.querySelector('#catrow')!; CAT_DEFS.forEach(d => { const i = document.createElement('i'); i.textContent = '🐱'; i.title = d.name; i.dataset.id = d.id; catRow.appendChild(i); }); const joy = el(``); ui.appendChild(joy); const stick = el(`
`); ui.appendChild(stick); input.stickEl = stick; joy.addEventListener('pointerdown', e => canvas.dispatchEvent(new PointerEvent('pointerdown', e))); const act = el(``); ui.appendChild(act); input.bindButton(act); const hint = el(``); ui.appendChild(hint); const keyHint = el(``); ui.appendChild(keyHint); const candyEl = hud.querySelector('#candy')!; const quests = new Quests(ui, [sugarbell, mintly]); let candyCount = 0; /** Candy counts for this play session and is banked in the save right away (it buys things in the Cat Home). */ function addCandy(n: number) { candyCount += n; candyEl.textContent = String(candyCount); save.candy += n; persist(save); } function toast(t: string) { const n = ui.querySelectorAll('.toast').length; const d = el(`
${t}
`); if (n) d.style.top = `${22 + n * 9}%`; ui.appendChild(d); setTimeout(() => d.remove(), 1700); } const title = el(`

Fluffy Cat
Kingdom

Catch the fluff. Discover the magic.

πŸ•ΉοΈπŸƒπŸΎπŸ€ΈπŸΎπŸ±πŸ’–πŸ₯šπŸ¦–

Grown-ups: joystick or WASD to move, one paw button or Space to jump and catch. No sound? Turn the volume up and tap once (works on silent too).

`); ui.appendChild(title); const diffRow = title.querySelector('#diff')!; ['🐾', '🐾🐾', '🐾🐾🐾'].forEach((lbl, i) => { const b = document.createElement('button'); b.className = 'big alt'; b.textContent = lbl; b.setAttribute('aria-label', ['Little Explorer', 'Royal Adventurer', 'Master Fluff Catcher'][i]); b.classList.toggle('sel', save.settings.difficulty === i); b.onclick = () => { save.settings.difficulty = i; cw.difficulty = i; persist(save); [...diffRow.children].forEach((c, j) => c.classList.toggle('sel', j === i)); audio.play('click'); }; diffRow.appendChild(b); }); let started = false; type Mode = 'title' | 'intro' | 'play' | 'pause' | 'victory' | 'home' | 'mountain'; let round = 1; let mode: Mode = 'title'; let introT = 0, playT = 0, victoryT = 0, idleT = 0; let camYaw = 0, camPitch = 0.42, camDist = 7.5, manualCamT = 0; const camPos = new THREE.Vector3(0, 12, 22), camLook = new THREE.Vector3(); let trophy: THREE.Group | null = null; let caughtCount = 0; title.querySelector('#play')!.addEventListener('click', () => { audio.init(); audio.play('click'); audio.startMusic('village'); title.remove(); hud.hidden = false; if (isTouch) { joy.hidden = false; act.hidden = false; } if (started) { player.body.pos.copy(level.spawn); player.body.vel.set(0, 0, 0); newRound(); return; } started = true; mode = 'intro'; introT = 0; // the candy machine goes POP and cats scatter (the opening beat) audio.play('firework'); fx.emit(new THREE.Vector3(0, 5, 3), 140, { color: CANDY_COLORS, speed: 9, up: 6, size: 0.16, life: 1.6, grav: 6 }); for (const c of cats) if (c.active && c.state === 'wander') { c.body.vel.set((Math.random() - 0.5) * 4, 8, (Math.random() - 0.5) * 4); } }); const pauseScreen = el(``); ui.appendChild(pauseScreen); const setPause = (p: boolean) => { if (mode === 'victory' || mode === 'title' || mode === 'home' || mode === 'mountain') return; mode = p ? 'pause' : 'play'; pauseScreen.hidden = !p; audio.play('click'); }; hud.querySelector('#pause')!.addEventListener('click', () => setPause(true)); let muted = false; const sndBtn = hud.querySelector('#snd') as HTMLButtonElement; sndBtn.addEventListener('click', () => { if (!audio.isRunning()) { audio.kick(); muted = false; } else muted = !muted; audio.setVolumes(muted ? 0 : 0.7, save.settings.music, save.settings.sfx); sndBtn.textContent = muted ? 'πŸ”‡' : 'πŸ”Š'; audio.play('click'); }); pauseScreen.querySelector('#resume')!.addEventListener('click', () => setPause(false)); pauseScreen.querySelector('#ptitle')!.addEventListener('click', () => { pauseScreen.hidden = true; seek.on = false; seekCover.hidden = true; endHunt(true); input.enabled = true; hud.hidden = true; joy.hidden = true; act.hidden = true; quests.hideAll(); mode = 'title'; ui.appendChild(title); audio.play('click'); audio.startMusic('title'); }); pauseScreen.querySelector('#restart')!.addEventListener('click', () => location.reload()); function catchCat(c: Cat) { const idx = cats.filter(k => k.caught).length; c.startParade(idx); caughtCount = idx + 1; audio.play('catch'); audio.meow(c.def.voice, 'happy'); c.rig.pose = 'spin'; c.rig.flash('happy', 1.5); player.hugT = 0.35; player.happyT = 1.2; const p = c.pos.clone().setY(c.pos.y + 0.8); fx.emit(p.setY(p.y + 0.6), 20, { color: ['#ff7fb0', '#ffd1e6', '#ffffff', '#ffe066'], speed: 3.5, up: 3, size: 0.09 }); addCandy(3); fx.emit(p, 10, { color: CANDY_COLORS, speed: 3, up: 5, size: 0.12 }); const i = catRow.querySelector(`[data-id="${c.def.id}"]`); if (i) { i.className = 'got'; i.textContent = c.def.emoji; } toast(`πŸ’– ${catName(c)}!`); quests.notify('catch'); hitStop = 0.07; camPunch = 1; save.caughtEver = Array.from(new Set([...save.caughtEver, c.def.id])); persist(save); sugarbell.cheer = 1.5; if (seek.on) { seek.found++; seek.lastT = seek.t; c.rig.flash('surprised', 0.6); audio.play('giggle'); if (seek.found === seek.cats.length) setTimeout(seekWin, 900); return; } if (caughtCount === CAT_DEFS.length - 1 && !golden.active) { // Golden Fluff arrives on a cloud setTimeout(() => { golden.active = true; golden.rig.root.visible = true; golden.body.pos.set(0, 10, 4); golden.home.set(0, 3, 4); golden.state = 'wander'; audio.play('sparkle'); audio.play('trophy', { volume: 0.5 }); toast('🌟 Golden Fluff!'); fx.emit(new THREE.Vector3(0, 10, 4), 80, { color: ['#ffe066', '#ffffff'], speed: 5, size: 0.15 }); }, 1500); } if (caughtCount === CAT_DEFS.length) setTimeout(startVictory, 900); } /** Keep playing: friends run off for another game of tag, a bit faster each round. */ function newRound() { round++; audio.play('click'); audio.startMusic('village'); if (trophy) { scene.remove(trophy); trophy = null; } cw.difficulty = Math.min(2, save.settings.difficulty + (round - 1) * 0.5); caughtCount = 0; trail.length = 0; input.enabled = true; mode = 'play'; playT = 0; sugarbell.cheer = 0; sugarbell.root.position.copy(level.princessSpot); catRow.querySelectorAll('i').forEach(i => { i.className = ''; i.textContent = '🐱'; (i as HTMLElement).hidden = false; }); seek.on = false; endHunt(true); for (const c of cats) { c.caught = false; c.wakes = 0; c.paradeIndex = -1; c.jumpQueue = []; c.fleeT = 0; c.state = c.def.special === 'sleeper' ? 'sleep' : c.def.special === 'statue' ? 'statue' : 'flee'; if (c.def.special === 'golden') { c.active = false; c.rig.root.visible = false; continue; } c.active = true; c.rig.root.visible = true; c.home.copy(level.catSpots[Math.floor(Math.random() * level.catSpots.length)]); c.body.vel.set((Math.random() - 0.5) * 8, 10, (Math.random() - 0.5) * 8); } statueCat.body.pos.set(4, 3.6, -3); statueCat.home.set(4, 3, -3); for (const cd of candies) { cd.taken = false; cd.mesh.visible = true; cd.mesh.position.copy(cd.pos); } fx.emit(player.body.pos.clone().setY(player.body.pos.y + 1), 50, { color: CANDY_COLORS, speed: 8, up: 5, size: 0.15 }); audio.play('firework'); toast(`Round ${round}! 🐾`); } function startVictory() { mode = 'victory'; victoryT = 0; input.enabled = false; audio.startMusic('victory'); audio.play('trophy'); trophy = makeTrophy(); trophy.position.copy(player.body.pos).add(new THREE.Vector3(0, 12, 0)); scene.add(trophy); sugarbell.root.position.copy(player.body.pos).add(new THREE.Vector3(-1.8, 0, 1)); sugarbell.cheer = 99; cats.forEach((c, i) => { c.state = 'dance'; const a = i / cats.length * Math.PI * 2; c.body.pos.set(player.body.pos.x + Math.cos(a) * 3.2, player.body.pos.y + 0.5, player.body.pos.z + Math.sin(a) * 3.2); }); const won = { date: new Date().toISOString().slice(0, 10), seconds: Math.round(playT), candy: candyCount, difficulty: save.settings.difficulty }; save.trophies.push(won); persist(save); setTimeout(() => { const v = el(`
πŸ†

You did it!

All ${CAT_DEFS.length} cats are your friends. 🍬 ${candyCount} candies. ⏱ ${Math.floor(playT / 60)}:${String(Math.round(playT % 60)).padStart(2, '0')}

Trophies won on this device: ${save.trophies.length} πŸ† The cats want to play again, a little faster each round!

`); ui.appendChild(v); v.querySelector('#again')!.addEventListener('click', () => { v.remove(); newRound(); }); v.querySelector('#gohome')!.addEventListener('click', () => { v.remove(); goHome(); }); v.querySelector('#gomtn')!.addEventListener('click', () => { v.remove(); goMountain(); }); }, 6500); } // ---------------- Hide and Seek ---------------- // Five cats hide in safe spots around the village. Purrs get louder as she gets closer. // After 20 s without a find, the helper arrow points the way. Cannot fail, no clock. const seek = { on: false, t: 0, lastT: 0, found: 0, cats: [] as Cat[], purrT: 0, countT: 0 }; const seekCover = el(``); ui.appendChild(seekCover); function shuffle(a: T[]): T[] { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } function seekSpots(): THREE.Vector3[] { const s: THREE.Vector3[] = []; const W = level.world; // a hiding spot needs open ground around it (no wall within a block), so a hider can never end up on a roof const open = (x: number, z: number, y: number) => { for (const ox of [-1.1, 0, 1.1]) for (const oz of [-1.1, 0, 1.1]) { if (W.solidAt(x + ox, y + 0.5, z + oz) || Math.abs(W.topAt(x + ox, z + oz) - y) > 1.1) return false; } return true; }; const add = (x: number, z: number) => { const y = W.topAt(x, z); if (y > 0 && Math.hypot(x, z - 6) > 9 && open(x, z, y)) s.push(new THREE.Vector3(x, y + 0.3, z)); }; for (const [hx, hz] of [[-14, 10], [14, 12], [-18, -4], [17, -6], [6, 22]]) { add(hx + 4.6, hz + 1); add(hx - 4.6, hz - 1); add(hx, hz + 4.6); } for (const h of level.hideSpots) { add(h.x + 1.8, h.z + 1.8); add(h.x - 1.8, h.z - 1.2); } for (const t of level.trees) add(t.pos.x + 0.7, t.pos.z + 0.7); for (const [x, z] of [[-5, -24], [5, -24], [-5, -19.5], [5, -19.5], [1.5, 20.5]]) add(x, z); return s; } function startSeek() { audio.init(); audio.play('click'); audio.startMusic('garden'); quests.hideAll(); title.remove(); document.querySelectorAll('.screen.seekend').forEach(e => e.remove()); hud.hidden = false; if (isTouch) { joy.hidden = false; act.hidden = false; } started = true; mode = 'play'; input.enabled = false; playT = 0; caughtCount = 0; trail.length = 0; if (trophy) { scene.remove(trophy); trophy = null; } player.body.pos.copy(level.spawn); player.body.vel.set(0, 0, 0); const pool = shuffle(cats.filter(c => c.def.special !== 'golden')).slice(0, 5); const spots = shuffle(seekSpots()); for (const c of cats) { c.caught = false; c.paradeIndex = -1; c.jumpQueue = []; c.active = false; c.rig.root.visible = false; } pool.forEach((c, i) => { const sp = spots[i % spots.length]; c.active = true; c.rig.root.visible = true; c.state = 'seek'; c.body.pos.copy(sp); c.body.vel.set(0, 0, 0); c.home.copy(sp); c.meowT = 4 + i; }); catRow.querySelectorAll('i').forEach(i => { const on = pool.some(c => c.def.id === (i as HTMLElement).dataset.id); (i as HTMLElement).hidden = !on; i.className = ''; i.textContent = '🐱'; }); Object.assign(seek, { on: true, t: 0, lastT: 0, found: 0, cats: pool, purrT: 2, countT: 3 }); seekCover.hidden = false; (seekCover.querySelector('#seekn') as HTMLElement).textContent = '3'; } function seekUpdate(dt: number) { if (!seek.on) return; if (seek.countT > 0) { const before = Math.ceil(seek.countT); seek.countT -= dt; const now = Math.ceil(seek.countT); if (now !== before) { audio.play('click'); (seekCover.querySelector('#seekn') as HTMLElement).textContent = now > 0 ? String(now) : '🐾'; } if (seek.countT <= 0) { seekCover.hidden = true; input.enabled = true; toast('πŸ™ˆ Ready or not!'); audio.play('whoosh'); } return; } seek.t += dt; seek.purrT -= dt; // hiders stay put (never climb anything) for (const c of seek.cats) if (!c.caught && c.state === 'seek' && (Math.abs(c.pos.y - c.home.y) > 0.8 || Math.hypot(c.pos.x - c.home.x, c.pos.z - c.home.z) > 0.6)) { c.body.pos.copy(c.home); c.body.vel.set(0, 0, 0); } // stuck for a while? the nearest hider gets curious and peeks out close to her if (seek.t - seek.lastT > 30) { let pc: Cat | null = null, pd = 1e9; for (const c of seek.cats) if (!c.caught) { const d = c.pos.distanceTo(player.body.pos); if (d < pd) { pd = d; pc = c; } } const pp = player.body.pos; if (pc && pd > 5) for (let k = 0; k < 12; k++) { const a = Math.atan2(-Math.cos(camYaw), -Math.sin(camYaw)) + (k % 2 ? 1 : -1) * Math.ceil(k / 2) * 0.5, x = pp.x + Math.cos(a) * 4.5, z = pp.z + Math.sin(a) * 4.5, y = level.world.topAt(x, z); if (y > 0 && Math.abs(y - pp.y) < 1.2 && !level.world.solidAt(x, y + 0.5, z)) { pc.body.pos.set(x, y + 0.3, z); pc.body.vel.set(0, 0, 0); pc.home.copy(pc.body.pos); fx.emit(tmpV.set(x, y + 1, z), 24, { color: ['#ffe066', '#ffffff', '#ff7fb0'], speed: 3, up: 2, size: 0.12 }); audio.play('giggle'); pc.rig.flash('smug', 1.2); break; } } seek.lastT = seek.t - 12; // peek again later if she still needs help } // hot and cold: the nearest hidden cat purrs louder as she gets closer let nd = 1e9; for (const c of seek.cats) if (!c.caught) nd = Math.min(nd, c.pos.distanceTo(player.body.pos)); if (seek.purrT <= 0 && nd < 1e8) { seek.purrT = nd < 6 ? 0.9 : 1.8; audio.play('purr', { volume: clamp(1.1 - nd / 18, 0.12, 1) }); } } function seekWin() { mode = 'victory'; input.enabled = false; seek.on = false; audio.startMusic('victory'); audio.play('trophy'); cats.forEach((c, i) => { if (!c.active) return; c.state = 'dance'; const a = i / cats.length * Math.PI * 2; c.body.pos.set(player.body.pos.x + Math.cos(a) * 3, player.body.pos.y + 0.5, player.body.pos.z + Math.sin(a) * 3); }); for (let k = 0; k < 4; k++) setTimeout(() => { fx.emit(player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 12, 8, (Math.random() - 0.5) * 12)), 50, { color: CANDY_COLORS, speed: 6, size: 0.13, life: 1.3, grav: 2 }); audio.play('firework', { volume: 0.6 }); }, k * 500); addCandy(10); setTimeout(() => { const v = el(`
πŸ™ˆ

Found you!

🐱 ${seek.cats.length} / ${seek.cats.length} · 🍬 +10

`); ui.appendChild(v); v.addEventListener('click', e => { const a = (e.target as HTMLElement).closest('[data-s]')?.getAttribute('data-s'); if (a === 'again') { v.remove(); startSeek(); } if (a === 'title') { v.remove(); hud.hidden = true; joy.hidden = true; act.hidden = true; mode = 'title'; ui.appendChild(title); audio.startMusic('title'); } }); }, 3000); } // ---------------- Candy Hunt ---------------- // Candy rains on the island for a while. She grabs all she can; the cats grab some too (giggling). // The run always ends with a party and every candy she got goes into her jar. const HUNT_TIME = 75; interface Drop { mesh: THREE.Mesh; vel: THREE.Vector3; alive: boolean; landed: boolean; age: number } const hunt = { on: false, t: 0, got: 0, catsGot: 0, spawnT: 0, catT: 0, drops: [] as Drop[] }; const huntBar = el(``); ui.appendChild(huntBar); const dropGeo = new THREE.OctahedronGeometry(0.3, 0); for (let i = 0; i < 70; i++) { const m = new THREE.Mesh(dropGeo, softMaterial(CANDY_COLORS[i % CANDY_COLORS.length], 1, 0.25)); m.visible = false; scene.add(m); hunt.drops.push({ mesh: m, vel: new THREE.Vector3(), alive: false, landed: false, age: 0 }); } function startHunt() { audio.init(); audio.play('click'); audio.startMusic('garden'); quests.hideAll(); title.remove(); document.querySelectorAll('.screen.seekend').forEach(e => e.remove()); hud.hidden = false; huntBar.hidden = false; if (isTouch) { joy.hidden = false; act.hidden = false; } started = true; seek.on = false; mode = 'play'; input.enabled = true; playT = 0; caughtCount = 0; trail.length = 0; if (trophy) { scene.remove(trophy); trophy = null; } player.body.pos.copy(level.spawn); player.body.vel.set(0, 0, 0); for (const c of cats) { c.caught = false; c.paradeIndex = -1; c.jumpQueue = []; const g = c.def.special === 'golden'; c.active = !g; c.rig.root.visible = !g; if (!g) { c.state = 'wander'; c.body.pos.copy(c.home).y += 1; } } catRow.querySelectorAll('i').forEach(i => { (i as HTMLElement).hidden = false; i.className = ''; i.textContent = '🐱'; }); for (const d of hunt.drops) { d.alive = false; d.mesh.visible = false; } Object.assign(hunt, { on: true, t: 0, got: 0, catsGot: 0, spawnT: 0, catT: 0 }); toast('🍭 Candy rain!'); audio.play('firework'); } function endHunt(silent = false) { if (!hunt.on) return; hunt.on = false; huntBar.hidden = true; for (const d of hunt.drops) { d.alive = false; d.mesh.visible = false; } if (silent) return; mode = 'victory'; input.enabled = false; audio.startMusic('victory'); audio.play('trophy'); cats.forEach((c, i) => { if (!c.active) return; c.state = 'dance'; const a = i / cats.length * Math.PI * 2; c.body.pos.set(player.body.pos.x + Math.cos(a) * 3.2, player.body.pos.y + 0.5, player.body.pos.z + Math.sin(a) * 3.2); }); for (let k = 0; k < 4; k++) setTimeout(() => { fx.emit(player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 12, 8, (Math.random() - 0.5) * 12)), 50, { color: CANDY_COLORS, speed: 6, size: 0.13, life: 1.3, grav: 2 }); audio.play('firework', { volume: 0.6 }); }, k * 500); setTimeout(() => { const v = el(`
🍭

Candy party!

🍬 ${hunt.got}

`); ui.appendChild(v); v.addEventListener('click', e => { const a = (e.target as HTMLElement).closest('[data-s]')?.getAttribute('data-s'); if (a === 'again') { v.remove(); startHunt(); } if (a === 'title') { v.remove(); hud.hidden = true; joy.hidden = true; act.hidden = true; mode = 'title'; ui.appendChild(title); audio.startMusic('title'); } }); }, 3000); } function huntUpdate(dt: number) { if (!hunt.on) return; hunt.t += dt; hunt.spawnT -= dt; hunt.catT -= dt; (huntBar.firstElementChild as HTMLElement).style.width = `${Math.max(0, 100 - hunt.t / HUNT_TIME * 100).toFixed(1)}%`; const pp = player.body.pos; // more candy falls near her, some further away so she explores if (hunt.spawnT <= 0 && hunt.t < HUNT_TIME - 2) { hunt.spawnT = 0.28; const d = hunt.drops.find(k => !k.alive); if (d) { let x = 0, z = 0; for (let tries = 0; tries < 8; tries++) { const nearHer = Math.random() < 0.55; const a = Math.random() * Math.PI * 2, r = nearHer ? 2 + Math.random() * 7 : Math.random() * 24; x = (nearHer ? pp.x : 0) + Math.cos(a) * r; z = (nearHer ? pp.z : 0) + Math.sin(a) * r; if (level.world.topAt(x, z) > 0 && Math.hypot(x, z) < 26) break; } d.alive = true; d.landed = false; d.age = 0; d.mesh.visible = true; d.mesh.position.set(x, level.world.topAt(x, z) + 14, z); d.vel.set(0, -4, 0); } } for (const d of hunt.drops) { if (!d.alive) continue; d.age += dt; const m = d.mesh; if (!d.landed) { d.vel.y -= 14 * dt; m.position.addScaledVector(d.vel, dt); const g = level.world.topAt(m.position.x, m.position.z) + 0.35; if (m.position.y <= g) { m.position.y = g; d.landed = true; } } else m.position.y += Math.sin(t * 5 + m.position.x) * 0.004; m.rotation.y += dt * 3; if (Math.hypot(m.position.x - pp.x, m.position.z - pp.z) < 1.3 && Math.abs(m.position.y - pp.y - 0.6) < 1.8) { d.alive = false; m.visible = false; hunt.got++; addCandy(1); quests.notify('candy'); candyStreak = candyStreakT > 0 ? Math.min(candyStreak + 1, 10) : 0; candyStreakT = 1; audio.play('candy', { pitch: 1 + candyStreak * 0.07 }); fx.emit(m.position, 6, { color: CANDY_COLORS, speed: 2, size: 0.07 }); continue; } if (d.age > 22) { d.alive = false; m.visible = false; } } // cats run for candy too if (hunt.catT <= 0) { hunt.catT = 0.8; for (const c of cats) { if (!c.active || c.state !== 'wander' && c.state !== 'idle') continue; let best: Drop | null = null, bd = 9; for (const d of hunt.drops) if (d.alive && d.landed) { const q = d.mesh.position.distanceTo(c.pos); if (q < bd) { bd = q; best = d; } } if (best) { c.target.set(best.mesh.position.x, 0, best.mesh.position.z); c.state = 'wander'; c.timer = 2; } } } for (const c of cats) { if (!c.active) continue; for (const d of hunt.drops) if (d.alive && d.landed && d.mesh.position.distanceTo(c.pos) < 0.9) { d.alive = false; d.mesh.visible = false; hunt.catsGot++; c.rig.flash('happy', 1); if (c.pos.distanceTo(pp) < 12) audio.play('giggle', { volume: 0.35 }); fx.emit(d.mesh.position, 5, { color: CANDY_COLORS, speed: 1.5, size: 0.06 }); } } if (hunt.t >= HUNT_TIME) endHunt(); } // ---------------- Royal Cat Sanctuary ---------------- const home = new Sanctuary(save, ui, el, toast); function goHome() { audio.init(); audio.play('click'); quests.hideAll(); title.remove(); pauseScreen.hidden = true; hud.hidden = true; hint.hidden = true; keyHint.hidden = true; arrow.visible = false; if (isTouch) { joy.hidden = false; act.hidden = false; } input.enabled = true; mode = 'home'; home.enter(); } home.onExit = () => { applyOutfit(player, save.outfit); mode = 'title'; hud.hidden = true; joy.hidden = true; act.hidden = true; ui.appendChild(title); audio.startMusic('title'); }; title.querySelector('#home')!.addEventListener('click', goHome); title.querySelector('#seek')!.addEventListener('click', startSeek); title.querySelector('#hunt')!.addEventListener('click', startHunt); // ---------------- Chocolate Mountain ---------------- const mountain = new Mountain(save, ui, el, toast); function goMountain() { audio.init(); audio.play('click'); quests.hideAll(); title.remove(); pauseScreen.hidden = true; hud.hidden = true; hint.hidden = true; keyHint.hidden = true; arrow.visible = false; if (isTouch) { joy.hidden = false; act.hidden = false; } input.enabled = true; mode = 'mountain'; mountain.enter(); } mountain.onExit = () => { mode = 'title'; hud.hidden = true; joy.hidden = true; act.hidden = true; ui.appendChild(title); audio.startMusic('title'); }; title.querySelector('#mtn')!.addEventListener('click', goMountain); // Trees never block the view: hide any candy tree between the camera and the player (or right next to the camera). const treeM = new THREE.Matrix4(), zeroM = new THREE.Matrix4().makeScale(0, 0, 0); function hideTrees() { const ax = camera.position.x, az = camera.position.z, bx = camLook.x, bz = camLook.z; const vx = bx - ax, vz = bz - az, vl = vx * vx + vz * vz || 1; let dirty = false; for (const tr of level.trees) { const px = tr.pos.x - ax, pz = tr.pos.z - az; const u = Math.max(0, Math.min(1, (px * vx + pz * vz) / vl)); const d = Math.hypot(px - vx * u, pz - vz * u); const hide = mode !== 'title' && (d < 2.4 && u < 0.98 || Math.hypot(px, pz) < 2.6); if (hide !== tr.hidden) { tr.hidden = hide; tr.crown.visible = !hide; dirty = true; level.trunks.setMatrixAt(tr.idx, hide ? zeroM : treeM.makeTranslation(tr.pos.x, tr.pos.y + 1.2, tr.pos.z)); } } if (dirty) level.trunks.instanceMatrix.needsUpdate = true; for (const cup of level.cups) { const px = cup.position.x - ax, pz = cup.position.z - az, u = (px * vx + pz * vz) / vl; cup.visible = !(mode !== 'title' && ((u > -0.1 && u < 0.95 && Math.hypot(px - vx * u, pz - vz * u) < 2.6) || Math.hypot(px, pz) < 3)); } } // --------------- loop ---------------- const clock = new THREE.Clock(); let t = 0, frameAvg = 16, adaptT = 0, audioT = 0; const tmpV = new THREE.Vector3(), tmpV2 = new THREE.Vector3(); function frame() { requestAnimationFrame(frame); const realDt = Math.min(clock.getDelta(), 0.5); let dt = Math.min(realDt, 1 / 20); if (hitStop > 0) { hitStop -= dt; dt *= 0.08; } t += dt; sharedLight.uTime.value = t; const inp = input.update(); if (inp.pausePressed) setPause(mode !== 'pause'); if (mode === 'mountain') { mountain.update(dt, inp, camera); renderer.render(mountain.scene, camera); audioT += dt; if (audioT > 1) { audioT = 0; audio.watchdog(); } (window as unknown as { __fck: unknown }).__fck = { mode, candy: save.candy, fps: Math.round(1000 / frameAvg), mountain: mountain.debug() }; frameAvg = lerp(frameAvg, realDt * 1000, 0.05); return; } if (mode === 'home') { home.update(dt, inp, camera); renderer.render(home.scene, camera); audioT += dt; if (audioT > 1) { audioT = 0; audio.watchdog(); } (window as unknown as { __fck: unknown }).__fck = { mode, candy: save.candy, homeCats: home.cats.map(c => ({ id: c.def.id, state: c.state, x: c.pos.x, y: c.pos.y, z: c.pos.z })), player: home.player.body.pos }; return; } if (mode === 'pause') { (window as unknown as { __fck: { mode: string } }).__fck.mode = 'pause'; renderer.render(scene, camera); return; } if (mode === 'intro') { introT += dt; if (introT > 0.6) { mode = 'play'; } } const playing = mode === 'play'; if (playing) playT += dt; const inp2 = input.p2; if (!inp2 && p2On) setP2(false); if (inp2 && !p2On && (playing || mode === 'intro') && inp2.actionPressed) setP2(true); const two = p2On && !!inp2; // catch check: nearest catchable cat in generous range const range = 3.6 - cw.difficulty * 0.5; let near: Cat | null = null, nd = 1e9; for (const c of cats) { if (!c.catchable || hunt.on) continue; const d = Math.hypot(c.pos.x - player.body.pos.x, c.pos.z - player.body.pos.z); const dy = Math.abs(c.pos.y - player.body.pos.y); if (d < range && dy < (seek.on ? 4 : 2.4) && d < nd) { nd = d; near = c; } } act.classList.toggle('catch', !!near); ring.visible = !!near && playing; if (near) { ring.position.set(near.pos.x, near.pos.y + 0.08, near.pos.z); ring.rotation.z = t * 2; ring.scale.setScalar(near.rig.scale * (1 + Math.sin(t * 10) * 0.08)); } // touch-catch: run into a resting cat to make friends, no button needed if (playing && near && near.resting && nd < 1.3 && cw.difficulty < 1.5) { catchCat(near); near = null; } let allowJump = true; if (playing && near && inp.actionPressed) { allowJump = false; player.pounceT = 0.12; player.pounceDir.set(near.pos.x - player.body.pos.x, 0, near.pos.z - player.body.pos.z).normalize(); audio.play('pounce'); catchCat(near); } const speed = player.update(dt, playing ? inp : { ...inp, moveX: 0, moveY: 0, action: false, actionPressed: false }, camYaw, level.bouncers, allowJump && playing); if (two && inp2) { let near2: Cat | null = null, nd2 = 1e9; for (const c of cats) { if (!c.catchable || hunt.on) continue; const d = Math.hypot(c.pos.x - player2.body.pos.x, c.pos.z - player2.body.pos.z); if (d < range && Math.abs(c.pos.y - player2.body.pos.y) < (seek.on ? 4 : 2.4) && d < nd2) { nd2 = d; near2 = c; } } if (playing && near2 && near2.resting && nd2 < 1.3 && cw.difficulty < 1.5) { catchCat(near2); near2 = null; } let allowJump2 = true; if (playing && near2 && inp2.actionPressed) { allowJump2 = false; player2.pounceT = 0.12; player2.pounceDir.set(near2.pos.x - player2.body.pos.x, 0, near2.pos.z - player2.body.pos.z).normalize(); audio.play('pounce'); catchCat(near2); player2.happyT = 1.2; } player2.update(dt, playing ? inp2 : { ...inp2, moveX: 0, moveY: 0, action: false, actionPressed: false }, camYaw, level.bouncers, allowJump2 && playing); if (player2.justJumped) audio.play('jump', { volume: 0.7 }); if (player2.body.bounced) audio.play('boing'); // fell off, or too far from player 1: pop back beside them if (player2.body.pos.y < -6 || player2.body.pos.distanceTo(player.body.pos) > 22) { placeP2(); fx.emit(player2.body.pos.clone().setY(player2.body.pos.y + 0.6), 20, { color: ['#7cc8ff', '#ffffff'], speed: 2, up: 1, size: 0.12 }); } } cw.playerSpeed = speed; if (player.justJumped) { audio.play('jump'); cats.filter(c => c.state === 'parade').forEach(c => c.jumpQueue.push(0.1 + c.paradeIndex * 0.12)); } if (player.justLanded) { audio.play('land', { volume: 0.5 }); fx.emit(tmpV.copy(player.body.pos).setY(player.body.pos.y + 0.1), 8, { color: '#ffffff', speed: 2, up: 0.5, size: 0.1, grav: 1 }); } if (player.body.bounced) { audio.play('boing'); quests.notify('bounce'); } if (player.justJumped && playing) quests.notify('jump'); // fell off the island: a fluffy white cloud catches her and boings her home if (player.body.pos.y < -6) { player.body.pos.copy(player.body.lastSafe).y += 5; player.body.vel.set(0, 9, 0); audio.play('boing'); audio.play('giggle', { volume: 0.5 }); fx.emit(tmpV.copy(player.body.pos).setY(player.body.pos.y - 0.5), 40, { color: ['#ffffff', '#f3ecff'], speed: 3, up: 1, size: 0.2, life: 1.2, grav: 1 }); toast('☁️ Wheee!'); } // trail for the parade const last = trail[0]; if (!last || last.distanceTo(player.body.pos) > 0.25) { trail.unshift(player.body.pos.clone()); if (trail.length > 80) trail.pop(); } // idle hints for small hands idleT = inp.moved || !playing ? 0 : idleT + dt; candyStreakT -= dt; camPunch = Math.max(0, camPunch - dt * 3); // stand still for a while and a friend sneaks up to boop your nose if (idleT === 0) boopT = 0; if (idleT > 8 && boopT === 0) { boopT = 1; const f = cats.find(c => c.caught); if (f) { f.rig.flash('happy', 1.5); audio.meow(f.def.voice, 'happy'); audio.play('pop', { volume: 0.4 }); player.happyT = 1.2; fx.emit(tmpV.copy(player.body.pos).setY(player.body.pos.y + 1.3), 8, { color: ['#ff7fb0', '#ff4d88'], speed: 0.8, up: 1.4, grav: 0, life: 1.4, size: 0.13 }); toast(`πŸ‘ƒ Boop! ${catName(f)}`); } } hint.hidden = !(playing && isTouch && playT < 8 && !inp.moved); keyHint.hidden = !(playing && !isTouch && playT < 12); for (const c of cats) c.update(dt); seekUpdate(dt); huntUpdate(dt); // tiny T-rexes: hatch, follow a cat, then play with their toys for (const r of rexes) { const ev = r.update(dt, player.body.pos, cats, playing, player.justJumped && playing); if (ev === 'hatch') { quests.notify('hatch'); audio.play('eggCrack'); audio.play('sparkle'); fx.emit(tmpV.copy(r.body.pos).setY(r.body.pos.y + 0.5), 40, { color: ['#fff4c9', '#c9f2b0', '#ffd1e6', '#ffffff'], speed: 3, up: 3, size: 0.1 }); toast('πŸ¦– A tiny T-rex hatched!'); } else if (ev === 'rawr') audio.play('rawr', { volume: 0.7 }); else if (ev === 'sneeze') { audio.play('sneeze', { volume: 0.4, pitch: 1.8 }); fx.emit(tmpV.copy(r.body.pos).setY(r.body.pos.y + 0.8), 24, { color: ['#ff7a9c', '#ffb36b', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'], speed: 2.5, up: 1, size: 0.09, life: 1 }); } else if (ev === 'ballhit' && r.lastHit) { const c = r.lastHit as Cat; if (!c.caught) { c.body.vel.y = 8; c.rig.flash('surprised', 0.8); } audio.play('boing', { volume: 0.5, pitch: 1.3 }); audio.play('giggle', { volume: 0.4 }); } else if (ev === 'wobble') audio.play('eggWobble', { volume: 0.6 }); } for (const c of cats) { const on = c === near; c.highlight = lerp(c.highlight, on ? 1 : 0, damp(10, dt)); c.rig.root.scale.setScalar(c.rig.scale * (1 + c.highlight * 0.08 * (1 + Math.sin(t * 12)))); } // candies for (const cd of candies) { if (cd.taken) continue; cd.mesh.rotation.y += dt * 2; cd.mesh.position.y = cd.pos.y + Math.sin(t * 2.5 + cd.pos.x) * 0.15; const d = cd.mesh.position.distanceTo(tmpV.copy(player.body.pos).setY(player.body.pos.y + 0.7)); if (d < 2.2) cd.mesh.position.lerp(tmpV, damp(8, dt)); const d2 = two ? cd.mesh.position.distanceTo(tmpV2.copy(player2.body.pos).setY(player2.body.pos.y + 0.7)) : 1e9; if (d2 < 2.2 && d >= 2.2) cd.mesh.position.lerp(tmpV2, damp(8, dt)); if (d < 0.9 || d2 < 0.9) { cd.taken = true; cd.mesh.visible = false; addCandy(1); quests.notify('candy'); candyStreak = candyStreakT > 0 ? Math.min(candyStreak + 1, 10) : 0; candyStreakT = 1; audio.play('candy', { pitch: 1 + candyStreak * 0.07 }); fx.emit(cd.mesh.position, 10, { color: CANDY_COLORS, speed: 2, size: 0.08 }); } } // princess picture wishes { const pp = player.body.pos; const res = quests.update(dt, camera, pp, { friends: cats.filter(c => c.caught && c.pos.distanceTo(pp) < 7).length, nearCupcake: level.hideSpots.some(h => Math.hypot(h.x - pp.x, h.z - pp.z) < 3.2), nearRex: rexes.some(r => r.state !== 'egg' && r.state !== 'crack' && r.body.pos.distanceTo(pp) < 3), }, playing && !seek.on && !hunt.on); if (res) { res.who.cheer = 2.5; addCandy(res.reward); audio.play('unlock'); audio.play('candy', { pitch: 1.5 }); fx.emit(tmpV.copy(res.who.root.position).setY(res.who.root.position.y + 2.2), 50, { color: CANDY_COLORS, speed: 4, up: 3, size: 0.12 }); toast(`${res.gift} +${res.reward} 🍬`); player.happyT = 1.5; } } sugarbell.update(dt, player.body.pos); mintly.update(dt, player.body.pos); if (!mintlyGift && playing && player.body.pos.distanceTo(mintly.root.position) < 2.8) { mintlyGift = true; mintly.cheer = 3; const crown = new THREE.Group(); const band = new THREE.Mesh(new THREE.TorusGeometry(0.2, 0.05, 6, 20), new THREE.MeshLambertMaterial({ color: '#ffd34d', emissive: '#ffb300', emissiveIntensity: 0.4 })); band.rotation.x = Math.PI / 2; crown.add(band); ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'].forEach((c, i) => { const g = new THREE.Mesh(new THREE.OctahedronGeometry(0.07), new THREE.MeshLambertMaterial({ color: c, emissive: c, emissiveIntensity: 0.5 })); const a = i / 5 * Math.PI * 2; g.position.set(Math.cos(a) * 0.2, 0.08, Math.sin(a) * 0.2); crown.add(g); }); player.crownSlot.add(crown); player.happyT = 1.5; addCandy(10); audio.play('trophy', { volume: 0.6 }); toast('πŸ‘‘ A rainbow crown!'); fx.emit(player.body.pos.clone().setY(player.body.pos.y + 1.8), 60, { color: ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'], speed: 4, size: 0.12 }); } // arrow to the nearest free cat let best: Cat | null = null, bd = 1e9; for (const c of cats) { if (!c.catchable || hunt.on) continue; const d = c.pos.distanceTo(player.body.pos); if (d < bd) { bd = d; best = c; } } arrow.visible = playing && !!best && (seek.on ? seek.t - seek.lastT > 20 : bd > 11); if (best && arrow.visible) { arrow.position.set(player.body.pos.x, player.body.pos.y + 2.4 + Math.sin(t * 4) * 0.1, player.body.pos.z); arrow.lookAt(best.pos.x, player.body.pos.y + 2.4, best.pos.z); } // stand still with your friends for a cuddle: purrs and hearts const friends = cats.filter(c => c.caught && c.pos.distanceTo(player.body.pos) < 2.4); cuddleT = speed < 0.4 && friends.length && playing ? cuddleT + dt : 0; if (cuddleT > 1.6) { cuddleT = -2.5; const f = friends[Math.floor(Math.random() * friends.length)]; audio.play('purr', { volume: 0.6 }); f.rig.flash('happy', 1.5); fx.emit(f.pos.clone().setY(f.pos.y + 1), 6, { color: ['#ff7fb0', '#ff4d88'], speed: 0.8, up: 1.4, grav: 0, life: 1.4, size: 0.13 }); } for (const a of level.animated) a(t, dt); fx.update(dt); // victory choreography if (mode === 'victory' && trophy) { victoryT += dt; const tgt = tmpV.copy(player.body.pos).add(new THREE.Vector3(0, 2.6, 0)); trophy.position.lerp(tgt, damp(1.5, dt)); trophy.rotation.y += dt * 1.5; trophy.scale.setScalar(1 + Math.sin(t * 3) * 0.05); if (Math.random() < dt * 2) { const p = player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 18, 8 + Math.random() * 6, (Math.random() - 0.5) * 18)); fx.emit(p, 45, { color: CANDY_COLORS, speed: 7, up: 0, size: 0.14, life: 1.4, grav: 2 }); audio.play('firework', { volume: 0.6 }); } if (Math.random() < dt * 8) fx.emit(player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 10, 8, (Math.random() - 0.5) * 10)), 2, { color: CANDY_COLORS, speed: 0.5, up: -1, grav: 1, life: 3, size: 0.1 }); player.happyT = 1; } // camera: follows behind the player, drag to orbit, auto-recentre after a pause if (Math.abs(inp.camX) + Math.abs(inp.camY) > 0) { manualCamT = 2; camYaw -= inp.camX * 0.006; camPitch = clamp(camPitch + inp.camY * 0.004, 0.12, 1.1); } manualCamT -= dt; if (manualCamT <= 0 && speed > 1 && playing) camYaw += angleDiff(camYaw, player.yaw + Math.PI) * damp(1.2, dt) * clamp(Math.abs(inp.moveX) + 0.25, 0, 1); if (mode === 'title') { camYaw += dt * 0.12; } let dist = mode === 'title' ? 16 : mode === 'victory' ? 9 : camDist - camPunch * 1.4; const pitch = mode === 'title' ? 0.45 : camPitch; const spread = two && mode !== 'title' ? Math.hypot(player.body.pos.x - player2.body.pos.x, player.body.pos.z - player2.body.pos.z) : 0; const focus = mode === 'title' ? new THREE.Vector3(0, 3, 2) : two ? player.body.pos.clone().lerp(player2.body.pos, 0.5) : player.body.pos; if (spread) dist += Math.min(10, spread * 0.55); const want = new THREE.Vector3(focus.x + Math.sin(camYaw) * Math.cos(pitch) * dist, focus.y + 1.2 + Math.sin(pitch) * dist, focus.z + Math.cos(camYaw) * Math.cos(pitch) * dist); // keep the camera out of hills and walls: slide it in towards the player until the view is clear if (mode !== 'title') { const fx0 = focus.x, fy0 = focus.y + 1.2, fz0 = focus.z; const clearK = (w: THREE.Vector3) => { let k = 1; for (const oy of [-0.6, 0]) for (let i = 1; i <= 16; i++) { const f = i / 16; if (level.world.solidAt(fx0 + (w.x - fx0) * f, fy0 + oy + (w.y - fy0) * f, fz0 + (w.z - fz0) * f)) { k = Math.min(k, (i - 1.5) / 16); break; } } return k; }; let k = clearK(want); // first try looking down from higher up (keeps her full size on screen), then move in as a last resort for (const pp of [pitch + 0.35, pitch + 0.7, 1.15]) { if (k >= 1) break; const w2 = tmpV.set(focus.x + Math.sin(camYaw) * Math.cos(pp) * dist, focus.y + 1.2 + Math.sin(pp) * dist, focus.z + Math.cos(camYaw) * Math.cos(pp) * dist); const k2 = clearK(w2); if (k2 > k) { want.copy(w2); k = k2; } } k = Math.max(0.5, k); if (k < 1) want.set(fx0 + (want.x - fx0) * k, fy0 + (want.y - fy0) * k, fz0 + (want.z - fz0) * k); } const ground = level.world.topAt(want.x, want.z); if (want.y < ground + 1.2) want.y = ground + 1.2; camPos.lerp(want, damp(mode === 'victory' ? 2 : 8, dt)); camLook.lerp(tmpV.copy(focus).setY(focus.y + 1), damp(12, dt)); camera.position.copy(camPos); camera.lookAt(camLook); if (mode === 'victory') camYaw += dt * 0.4; hideTrees(); // friends that wander between the camera and the player step out of the picture { const ax = camera.position.x, az = camera.position.z, vx = player.body.pos.x - ax, vz = player.body.pos.z - az, vl = vx * vx + vz * vz || 1; for (const c of cats) { if (!c.caught) continue; const px = c.pos.x - ax, pz = c.pos.z - az, u = (px * vx + pz * vz) / vl; c.rig.root.visible = !(mode === 'play' && ((u > -0.2 && u < 0.85 && Math.hypot(px - vx * u, pz - vz * u) < 1.6) || c.pos.distanceTo(camera.position) < 3)); } for (const r of rexes) { const px = r.body.pos.x - ax, pz = r.body.pos.z - az, u = (px * vx + pz * vz) / vl; r.root.visible = !(mode === 'play' && r.state !== 'egg' && ((u > -0.2 && u < 0.85 && Math.hypot(px - vx * u, pz - vz * u) < 1.4) || r.body.pos.distanceTo(camera.position) < 2.6)); } } renderer.render(scene, camera); // adaptive resolution keeps mobile smooth frameAvg = lerp(frameAvg, realDt * 1000, 0.05); adaptT += dt; audioT += dt; if (audioT > 1) { audioT = 0; audio.watchdog(); } if (adaptT > 2) { adaptT = 0; const old = pixelRatio; if (frameAvg > 24 && pixelRatio > 0.8) pixelRatio = Math.max(0.8, pixelRatio - 0.2); else if (frameAvg < 15 && pixelRatio < Math.min(devicePixelRatio, 2)) pixelRatio = Math.min(Math.min(devicePixelRatio, 2), pixelRatio + 0.1); if (old !== pixelRatio) { renderer.setPixelRatio(pixelRatio); resize(); } } (window as unknown as { __fck: unknown }).__fck = { mode, caught: caughtCount, candy: candyCount, fps: Math.round(1000 / frameAvg), pr: pixelRatio, player: player.body.pos, p2: p2On ? player2.body.pos : null, cats: cats.map(c => ({ id: c.id, state: c.state, x: c.pos.x, y: c.pos.y, z: c.pos.z, caught: c.caught, active: c.active })) }; } frame(); // Test hook for automated QA: move the player next to a cat (no effect on normal play). (window as unknown as { __fckTest: unknown }).__fckTest = { rexes() { return rexes.map(r => ({ state: r.state, x: r.body.pos.x, y: r.body.pos.y, z: r.body.pos.z })); }, trees() { return { total: level.trees.length, hidden: level.trees.filter(k => k.hidden).length }; }, home() { goHome(); return save.caughtEver.length; }, homeNear() { const c = home.cats[0]; if (!c) return null; home.player.body.pos.set(c.pos.x + 1, c.pos.y + 0.3, c.pos.z); return c.def.id; }, give(n: number) { save.candy += n; persist(save); return save.candy; }, wish(e: 'candy' | 'bounce' | 'jump' | 'catch', n: number) { for (let i = 0; i < n; i++) quests.notify(e); return true; }, toPrincess(k: number) { const r = (k ? mintly : sugarbell).root.position; player.body.pos.set(r.x + 1.5, r.y + 0.5, r.z + 1.5); player.body.vel.set(0, 0, 0); return true; }, slide(ds: number) { return mountain.skip(ds); }, seek() { startSeek(); return seek.cats.map(c => c.def.id); }, seekSpots() { return seekSpots().length; }, seekStuck() { seek.lastT = seek.t - 31; }, seekCats() { return seek.cats.map(c => ({ id: c.def.id, caught: c.caught, x: +c.pos.x.toFixed(1), y: +c.pos.y.toFixed(1), z: +c.pos.z.toFixed(1), home: +c.home.y.toFixed(1), d: +c.pos.distanceTo(player.body.pos).toFixed(1) })); }, seekNext() { const c = seek.cats.find(k => !k.caught); if (!c) return null; player.body.pos.set(c.pos.x + 1, c.pos.y + 0.2, c.pos.z); player.body.vel.set(0, 0, 0); return c.id; }, hunt() { startHunt(); return true; }, huntState() { return { on: hunt.on, t: Math.round(hunt.t), got: hunt.got, cats: hunt.catsGot, drops: hunt.drops.filter(d => d.alive).length }; }, huntSkip(t: number) { hunt.t += t; return hunt.t; }, hatch() { rexes.forEach(r => r.hatchNow()); return rexes.length; }, nextCat() { const c = cats.find(k => k.catchable); if (!c) return null; player.body.pos.set(c.pos.x + 1, c.pos.y + 0.2, c.pos.z); player.body.vel.set(0, 0, 0); return c.id; }, };