// The rules: pure and deterministic. The same seed and the same inputs give the same game. // The preset game: move a lantern along the bottom and catch the sparks before they fall. export const W = 960; export const H = 540; export const DT = 1 / 60; export const LANTERN = { y: H - 40, halfWidth: 46, speed: 760 }; /** A small seeded random number generator (mulberry32). */ export function rng(seed) { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } export function createGame(seed = 1, opts = {}) { return { seed, random: rng(seed), time: 0, state: "title", x: W / 2, sparks: [], nextSpark: 1, caught: 0, lives: opts.lives ?? 3, }; } export function start(game) { game.state = "play"; game.sparks = []; game.caught = 0; game.nextSpark = 0.8; return game; } /** Advances the game by dt seconds. `input.target` moves the lantern toward an x; `input.move` (-1, 0, 1) moves it by hand. */ export function step(game, input = {}, dt = DT) { game.time += dt; const most = LANTERN.speed * dt; if (typeof input.target === "number") game.x += Math.max(-most, Math.min(most, input.target - game.x)); else if (input.move) game.x += Math.sign(input.move) * most; game.x = Math.max(LANTERN.halfWidth, Math.min(W - LANTERN.halfWidth, game.x)); if (game.state !== "play") return game; game.nextSpark -= dt; if (game.nextSpark <= 0) { game.sparks.push({ x: 40 + game.random() * (W - 80), y: -10, vy: 120 + Math.min(200, game.caught * 3) }); game.nextSpark = Math.max(0.45, 1.2 - game.caught * 0.012) * (0.7 + game.random() * 0.6); } const kept = []; for (const s of game.sparks) { s.y += s.vy * dt; if (s.y >= LANTERN.y && s.y < LANTERN.y + 16 && Math.abs(s.x - game.x) < LANTERN.halfWidth) game.caught++; else if (s.y > H + 10) game.lives--; else kept.push(s); } game.sparks = kept; if (game.lives <= 0) { game.lives = 0; game.state = "over"; } return game; } /** Runs the game for `seconds`, asking `control(game)` for input every step. */ export function simulate(game, seconds, control = () => ({})) { for (let i = 0; i < Math.round(seconds / DT); i++) step(game, control(game)); return game; }