TExcelTAD
Home › 2D Games with JavaScript & Canvas › Mini Project: Star Catcher

Mini Project: Star Catcher

Let's finish the course with a complete small game, the kind you could put on itch.io tonight: Star Catcher. Stars fall from the night sky and you catch them in a basket. Catch 25 to win; let three get away, or catch a bomb, and it's game over. It's small on purpose. The point is the whole game: title screen, pause, win and lose screens, restart, a HUD, sound, a saved high score and a bit of juice.

We'll build it the way real games are built:

  1. the rules as pure logic, tested in the console without any drawing;
  2. the screen flow as a tiny state machine;
  3. a playable core you can try after ten minutes;
  4. the full game loop with every screen;
  5. polish: particles, screen shake, sound, combos and saving.

What it uses:

Feature Lessons
Fixed-step loop and keyboard input from the play kit The Fixed-Step Loop, Keyboard Input
Mouse and touch steering Mouse & Touch Input
Circle-vs-rectangle collision Collision Detection
Spawning, swap-and-pop removal Shooter 3
Game states and restart Pong 4
Oscillator beeps after a user gesture Breakout 4
Particles and screen shake Particles, Screen Shake
Pause on blur and visibilitychange Pause & visibilitychange
Saving with a fallback Settings & Saving

Step 1: the rules, without graphics

Before drawing a single pixel, write the rules as plain functions: create a game, advance it by dt with some input, and report what happened. Because the random generator is seeded and the step is fixed, every run gives the same result, so we can play hundreds of games in milliseconds and check the balance. Here a simple autopilot plays two games, and an idle "player" who never moves plays a third:

js · try it yourself
function mulberry32(seed) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const W = 480, H = 270, GOAL = 25, MAX_MISSES = 3;

function circleRect(c, r) {
  const nx = Math.max(r.x, Math.min(c.x, r.x + r.w));
  const ny = Math.max(r.y, Math.min(c.y, r.y + r.h));
  return (c.x - nx) ** 2 + (c.y - ny) ** 2 < c.r * c.r;
}

function createGame(seed) {
  return {
    rnd: mulberry32(seed),
    basket: { x: W / 2 - 32, y: H - 28, w: 64, h: 14, speed: 300 },
    drops: [], spawnIn: 0.5, time: 0,
    caught: 0, misses: 0, result: null,      // result: 'won' | 'lost' | null
  };
}

// Advances the game by dt seconds. input = { move: -1 | 0 | 1 }. Returns the events of this step.
function updateGame(g, dt, input) {
  const events = [];
  g.time += dt;
  const b = g.basket;
  b.x = Math.max(0, Math.min(W - b.w, b.x + input.move * b.speed * dt));

  g.spawnIn -= dt;
  if (g.spawnIn <= 0) {
    const bomb = g.caught >= 3 && g.rnd() < 0.2;
    g.drops.push({ kind: bomb ? 'bomb' : 'star', x: 20 + g.rnd() * (W - 40), y: -10, r: bomb ? 9 : 8, vy: 70 + g.caught * 4 });
    g.spawnIn = Math.max(0.45, 1.1 - g.caught * 0.025);
  }

  for (let i = g.drops.length - 1; i >= 0; i--) {
    const d = g.drops[i];
    d.y += d.vy * dt;
    let gone = false;
    if (circleRect(d, b)) {
      gone = true;
      if (d.kind === 'star') { g.caught++; events.push('catch'); }
      else { g.result = 'lost'; events.push('bomb'); }
    } else if (d.y - d.r > H) {
      gone = true;
      if (d.kind === 'star') { g.misses++; events.push('miss'); }
    }
    if (gone) { g.drops[i] = g.drops[g.drops.length - 1]; g.drops.pop(); }   // swap-and-pop
  }
  if (!g.result && g.misses >= MAX_MISSES) g.result = 'lost';
  if (!g.result && g.caught >= GOAL) g.result = 'won';
  return events;
}

// A simple autopilot: dodge a low bomb, otherwise chase the lowest star.
function autopilot(g) {
  const b = g.basket, centre = b.x + b.w / 2;
  const danger = g.drops.find((d) => d.kind === 'bomb' && d.y > H - 100 && Math.abs(d.x - centre) < b.w / 2 + 14);
  if (danger) return { move: danger.x < centre ? 1 : -1 };
  const stars = g.drops.filter((d) => d.kind === 'star').sort((p, q) => q.y - p.y);
  if (!stars.length) return { move: 0 };
  const dx = stars[0].x - centre;
  return { move: Math.abs(dx) < 6 ? 0 : Math.sign(dx) };
}
const idle = () => ({ move: 0 });

function play(seed, player) {
  const g = createGame(seed);
  const log = [];
  while (!g.result && g.time < 120) {
    for (const e of updateGame(g, 1 / 60, player(g))) log.push(`${e}@${g.time.toFixed(1)}`);
  }
  console.log(`seed ${seed}, ${player.name}: ${g.result} after ${g.time.toFixed(1)} s (caught ${g.caught}, misses ${g.misses})`);
  console.log('  last events:', log.slice(-4).join(' '));
}

play(1, autopilot);
play(2, autopilot);
play(1, idle);
seed 1, autopilot: won after 26.8 s (caught 25, misses 2)
  last events: miss@25.5 catch@25.9 miss@26.6 catch@26.8
seed 2, autopilot: lost after 28.0 s (caught 23, misses 3)
  last events: catch@26.0 miss@26.9 catch@27.1 miss@28.0
seed 1, idle: lost after 7.9 s (caught 1, misses 3)
  last events: miss@4.6 miss@5.7 catch@6.2 miss@7.9

This tells us a lot before any art exists:

  • The game is winnable but not trivial: a perfect-reflex bot wins one seed and loses the other with 23 stars. A human will lose a few times first, which is what we want.
  • Doing nothing loses in about 8 seconds, so the player can't idle.
  • The difficulty ramps up through two numbers: stars fall faster (70 + caught * 4 px/s) and spawn more often (1.1 - caught * 0.025 s, never below 0.45 s). Tuning the game means tuning these, and you can re-run this check after every change.

Tip: Removing items with swap-and-pop (move the last element into the hole, then pop()) is O(1) and creates no new arrays, unlike splice or filter. The order of drops doesn't matter, so it's safe here. Looping backwards keeps the index valid.

Step 2: the screen flow

A complete game is mostly screens: title, playing, paused, won, lost. Writing the allowed moves as a table makes impossible transitions (winning while paused, pausing on the title screen) impossible by construction:

js · try it yourself
// Which screen comes next? state -> event -> new state. Unknown events are ignored.
const TRANSITIONS = {
  title:   { start: 'playing' },
  playing: { pause: 'paused', blur: 'paused', win: 'won', lose: 'lost' },
  paused:  { pause: 'playing', start: 'playing' },
  won:     { start: 'playing' },
  lost:    { start: 'playing' },
};

function next(state, event) {
  return TRANSITIONS[state][event] ?? state;
}

const events = ['pause', 'start', 'blur', 'win', 'start', 'start', 'lose', 'pause', 'start'];
let state = 'title';
for (const e of events) {
  const after = next(state, e);
  console.log(`${state.padEnd(7)} --${e.padEnd(5)}--> ${after}${after === state ? '   (ignored)' : ''}`);
  state = after;
}
title   --pause--> title   (ignored)
title   --start--> playing
playing --blur --> paused
paused  --win  --> paused   (ignored)
paused  --start--> playing
playing --start--> playing   (ignored)
playing --lose --> lost
lost    --pause--> lost   (ignored)
lost    --start--> playing

In the game below the same idea is written as a few if statements in update, which is fine for five states. For a bigger game, keep the table.

Step 3: a playable core

Now the minimum that's fun to touch: a basket that moves, stars that fall, a counter. No screens yet, no losing. Click the frame and catch some stars with the arrow keys (or A/D):

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const basket = { x: W / 2 - 32, y: H - 28, w: 64, h: 14, speed: 300 };
let stars = [], spawnIn = 0.6, caught = 0, misses = 0;

function circleRect(c, r) {
  const nx = Math.max(r.x, Math.min(c.x, r.x + r.w));
  const ny = Math.max(r.y, Math.min(c.y, r.y + r.h));
  return (c.x - nx) ** 2 + (c.y - ny) ** 2 < c.r * c.r;
}

function update(dt) {
  let move = 0;
  if (keys.has('ArrowLeft') || keys.has('KeyA')) move -= 1;
  if (keys.has('ArrowRight') || keys.has('KeyD')) move += 1;
  basket.x = Math.max(0, Math.min(W - basket.w, basket.x + move * basket.speed * dt));

  spawnIn -= dt;
  if (spawnIn <= 0) {
    stars.push({ x: 20 + Math.random() * (W - 40), y: -10, r: 8, vy: 70 + caught * 4 });
    spawnIn = Math.max(0.45, 1.1 - caught * 0.025);   // faster as you score
  }

  for (let i = stars.length - 1; i >= 0; i--) {
    const s = stars[i];
    s.y += s.vy * dt;
    let gone = false;
    if (circleRect(s, basket)) { caught++; gone = true; }
    else if (s.y - s.r > H) { misses++; gone = true; }
    if (gone) { stars[i] = stars[stars.length - 1]; stars.pop(); }   // swap-and-pop
  }
}

function draw() {
  ctx.fillStyle = '#0b1030'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#ffd54f';
  for (const s of stars) { ctx.beginPath(); ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2); ctx.fill(); }
  ctx.fillStyle = '#8d6e63'; ctx.fillRect(Math.round(basket.x), basket.y, basket.w, basket.h);
  ctx.fillStyle = '#fff'; ctx.font = 'bold 14px system-ui, sans-serif'; ctx.textAlign = 'left';
  ctx.fillText(`Caught ${caught}   Missed ${misses}`, 10, 20);
}

run(update, draw, '←/→ or A/D to move the basket');
</script>

Play it for a minute. Is it fun with yellow circles and a brown box? It is, a little, and that's the signal to keep going. If the core isn't fun with rectangles, art won't save it.

Step 4: the full game loop

This version adds everything that turns a toy into a game:

  • bombs (red) from the fourth star on: catching one ends the game;
  • win at 25 stars, lose at 3 misses;
  • a title screen, pause with P or Esc, and win/lose screens that restart with Enter, Space or a click;
  • mouse and touch steering: the basket follows the pointer until you press a key;
  • auto-pause when the frame loses focus or the tab is hidden, so you never die while reading the lesson.
html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const GOAL = 25, MAX_MISSES = 3;
const basket = { x: W / 2 - 32, y: H - 28, w: 64, h: 14, speed: 300 };
let state = 'title', drops = [], spawnIn = 0, caught = 0, misses = 0, message = '';

// Mouse/touch steering, and clicks as "start/resume" (but not the click that focuses the frame).
let pointerX = null, clicked = false;
cv.addEventListener('pointermove', (e) => {
  const r = cv.getBoundingClientRect();
  pointerX = (e.clientX - r.left) * W / r.width;
});
addEventListener('pointerdown', () => { if (active) clicked = true; }, true);
// Auto-pause: the frame lost focus, or the tab was hidden.
cv.addEventListener('blur', () => { if (state === 'playing') state = 'paused'; });
document.addEventListener('visibilitychange', () => { if (document.hidden && state === 'playing') state = 'paused'; });

function startGame() {
  drops = []; spawnIn = 0.6; caught = 0; misses = 0;
  basket.x = W / 2 - basket.w / 2;
  state = 'playing';
}

function circleRect(c, r) {
  const nx = Math.max(r.x, Math.min(c.x, r.x + r.w));
  const ny = Math.max(r.y, Math.min(c.y, r.y + r.h));
  return (c.x - nx) ** 2 + (c.y - ny) ** 2 < c.r * c.r;
}

function update(dt) {
  const go = pressed.has('Enter') || pressed.has('Space') || clicked;
  clicked = false;
  if (state === 'title' || state === 'won' || state === 'lost') { if (go) startGame(); return; }
  if (pressed.has('KeyP') || pressed.has('Escape')) { state = state === 'paused' ? 'playing' : 'paused'; return; }
  if (state === 'paused') { if (go) state = 'playing'; return; }

  let move = 0;
  if (keys.has('ArrowLeft') || keys.has('KeyA')) move -= 1;
  if (keys.has('ArrowRight') || keys.has('KeyD')) move += 1;
  if (move) pointerX = null;
  else if (pointerX !== null) {
    const dx = pointerX - (basket.x + basket.w / 2);
    move = Math.abs(dx) < 4 ? 0 : Math.max(-1, Math.min(1, dx / 40));
  }
  basket.x = Math.max(0, Math.min(W - basket.w, basket.x + move * basket.speed * dt));

  spawnIn -= dt;
  if (spawnIn <= 0) {
    const bomb = caught >= 3 && Math.random() < 0.2;
    drops.push({ kind: bomb ? 'bomb' : 'star', x: 20 + Math.random() * (W - 40), y: -10, r: bomb ? 9 : 8, vy: 70 + caught * 4 });
    spawnIn = Math.max(0.45, 1.1 - caught * 0.025);
  }

  for (let i = drops.length - 1; i >= 0; i--) {
    const d = drops[i];
    d.y += d.vy * dt;
    let gone = false;
    if (circleRect(d, basket)) {
      gone = true;
      if (d.kind === 'star') caught++;
      else { state = 'lost'; message = 'You caught a bomb!'; }
    } else if (d.y - d.r > H) {
      gone = true;
      if (d.kind === 'star') misses++;
    }
    if (gone) { drops[i] = drops[drops.length - 1]; drops.pop(); }
  }
  if (state === 'playing' && misses >= MAX_MISSES) { state = 'lost'; message = 'Three stars got away.'; }
  if (state === 'playing' && caught >= GOAL) { state = 'won'; message = `All ${GOAL} stars caught!`; }
}

function screen(title, ...lines) {
  ctx.fillStyle = 'rgba(5,8,20,0.7)'; ctx.fillRect(0, 0, W, H);
  ctx.textAlign = 'center'; ctx.fillStyle = '#ffd54f';
  ctx.font = 'bold 30px system-ui, sans-serif'; ctx.fillText(title, W / 2, 100);
  ctx.fillStyle = '#e8eaf6'; ctx.font = '14px system-ui, sans-serif';
  lines.forEach((l, i) => ctx.fillText(l, W / 2, 135 + i * 22));
}

function draw() {
  ctx.fillStyle = '#0b1030'; ctx.fillRect(0, 0, W, H);
  for (const d of drops) {
    ctx.fillStyle = d.kind === 'star' ? '#ffd54f' : '#ff5252';
    ctx.beginPath(); ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2); ctx.fill();
  }
  ctx.fillStyle = '#8d6e63'; ctx.fillRect(Math.round(basket.x), basket.y, basket.w, basket.h);
  ctx.fillStyle = '#fff'; ctx.font = 'bold 14px system-ui, sans-serif'; ctx.textAlign = 'left';
  ctx.fillText(`★ ${caught}/${GOAL}   Misses ${misses}/${MAX_MISSES}`, 10, 20);

  if (state === 'title') screen('STAR CATCHER', `Catch ${GOAL} yellow stars. Miss ${MAX_MISSES} or catch a red bomb and it's over.`, '←/→, A/D or the mouse to move · P or Esc to pause', 'Press Enter, Space or click to start');
  if (state === 'paused') screen('Paused', 'P, Enter or click to resume');
  if (state === 'won') screen('You win!', message, 'Enter or click to play again');
  if (state === 'lost') screen('Game over', message, `${caught} stars caught`, 'Enter or click to try again');
}

run(update, draw, 'Catch the stars, dodge the bombs');
</script>

Two details worth copying into your own games:

  1. The "start" click is registered on window in the capture phase. That listener runs before the kit's focus handler, so active is still false for the click that focuses the frame: the first click wakes the game up and shows the title screen instead of skipping it.
  2. Pausing changes the game state, not the loop. The loop keeps drawing, so the pause screen is always up to date, and nothing moves because update returns early.

Step 5: polish (the finished game)

The rules are done; now the game should feel good. The final version adds:

Polish How
Particles on catch, miss and bomb burst() pushes short-lived squares with velocity and gravity
Screen shake on a bomb shake timer + a random translate in draw, decaying to zero
Sound oscillator beeps; the AudioContext is created in the first click/key handler; M mutes
Score with combos 10 points per star, +2 for each catch in a row; a miss resets the combo
HUD stars, score, best, combo and three "lives" dots
Saved best score a storage wrapper: localStorage if allowed, a Map in memory if not
A prettier sky gradient, background stars, spinning star shapes, a blinking bomb fuse
html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

// ---------- saving: localStorage if allowed, memory otherwise ----------
const store = (() => {
  const mem = new Map();
  try {
    localStorage.setItem('__probe', '1');
    localStorage.removeItem('__probe');
    return { persistent: true, get: (k) => localStorage.getItem(k), set: (k, v) => localStorage.setItem(k, String(v)) };
  } catch {   // sandboxed frame, privacy mode, storage full...
    return { persistent: false, get: (k) => mem.get(k) ?? null, set: (k, v) => mem.set(k, String(v)) };
  }
})();
let best = Number(store.get('star-catcher-best')) || 0;

// ---------- sound: the AudioContext is created by the first click or key ----------
let audio = null, muted = false;
function unlockAudio() {
  try {
    audio ??= new AudioContext();
    if (audio.state === 'suspended') audio.resume();
  } catch { audio = null; }   // no Web Audio: play silently
}
addEventListener('pointerdown', unlockAudio);
addEventListener('keydown', unlockAudio);
function beep(freq, dur = 0.08, type = 'square', vol = 0.05) {
  if (!audio || muted) return;
  const t = audio.currentTime, osc = audio.createOscillator(), gain = audio.createGain();
  osc.type = type;
  osc.frequency.setValueAtTime(freq, t);
  gain.gain.setValueAtTime(vol, t);
  gain.gain.exponentialRampToValueAtTime(0.0001, t + dur);
  osc.connect(gain).connect(audio.destination);
  osc.start(t);
  osc.stop(t + dur);
}

// ---------- input: keys (from the kit), mouse/touch, clicks ----------
let pointerX = null, clicked = false;
cv.addEventListener('pointermove', (e) => {
  const r = cv.getBoundingClientRect();
  pointerX = (e.clientX - r.left) * W / r.width;
});
// Capture phase: runs before the kit's focus handler, so the click that focuses the frame doesn't count.
addEventListener('pointerdown', () => { if (active) clicked = true; }, true);
cv.addEventListener('blur', () => { if (state === 'playing') state = 'paused'; });
document.addEventListener('visibilitychange', () => { if (document.hidden && state === 'playing') state = 'paused'; });

// ---------- game state ----------
const GOAL = 25, MAX_MISSES = 3;
const basket = { x: W / 2 - 32, y: H - 28, w: 64, h: 14, speed: 300 };
let state = 'title', drops = [], particles = [], spawnIn = 0, caught = 0, misses = 0, points = 0, combo = 0;
let shake = 0, message = '', newBest = false;
const sky = Array.from({ length: 50 }, () => ({ x: Math.random() * W, y: Math.random() * H, s: Math.random() * 1.5 + 0.5 }));

function startGame() {
  drops = []; particles = []; spawnIn = 0.6;
  caught = 0; misses = 0; points = 0; combo = 0; newBest = false;
  basket.x = W / 2 - basket.w / 2;
  state = 'playing';
  beep(520, 0.1, 'triangle');
}

function endGame(won, why) {
  state = won ? 'won' : 'lost';
  message = why;
  if (points > best) { best = points; newBest = true; store.set('star-catcher-best', best); }
  if (won) [523, 659, 784, 1046].forEach((f, i) => setTimeout(() => beep(f, 0.15, 'triangle'), i * 120));
  else beep(110, 0.5, 'sawtooth', 0.07);
}

function burst(x, y, color, n, speed) {
  for (let i = 0; i < n; i++) {
    const a = Math.random() * Math.PI * 2, v = speed * (0.3 + Math.random() * 0.7);
    particles.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life: 0.6 + Math.random() * 0.4, color });
  }
}

function circleRect(c, r) {
  const nx = Math.max(r.x, Math.min(c.x, r.x + r.w));
  const ny = Math.max(r.y, Math.min(c.y, r.y + r.h));
  return (c.x - nx) ** 2 + (c.y - ny) ** 2 < c.r * c.r;
}

function update(dt) {
  for (const p of particles) { p.x += p.vx * dt; p.y += p.vy * dt; p.vy += 300 * dt; p.life -= dt; }
  particles = particles.filter((p) => p.life > 0);
  shake = Math.max(0, shake - dt);
  if (pressed.has('KeyM')) muted = !muted;

  const go = pressed.has('Enter') || pressed.has('Space') || clicked;
  clicked = false;
  if (state === 'title' || state === 'won' || state === 'lost') { if (go) startGame(); return; }
  if (pressed.has('KeyP') || pressed.has('Escape')) { state = state === 'paused' ? 'playing' : 'paused'; return; }
  if (state === 'paused') { if (go) state = 'playing'; return; }

  // Move the basket: keys win over the mouse until the mouse moves again.
  let move = 0;
  if (keys.has('ArrowLeft') || keys.has('KeyA')) move -= 1;
  if (keys.has('ArrowRight') || keys.has('KeyD')) move += 1;
  if (move) pointerX = null;
  else if (pointerX !== null) {
    const dx = pointerX - (basket.x + basket.w / 2);
    move = Math.abs(dx) < 4 ? 0 : Math.max(-1, Math.min(1, dx / 40));
  }
  basket.x = Math.max(0, Math.min(W - basket.w, basket.x + move * basket.speed * dt));

  spawnIn -= dt;
  if (spawnIn <= 0) {
    const bomb = caught >= 3 && Math.random() < 0.2;
    drops.push({ kind: bomb ? 'bomb' : 'star', x: 20 + Math.random() * (W - 40), y: -10, r: bomb ? 9 : 8, vy: 70 + caught * 4, spin: 0 });
    spawnIn = Math.max(0.45, 1.1 - caught * 0.025);
  }

  for (let i = drops.length - 1; i >= 0; i--) {
    const d = drops[i];
    d.y += d.vy * dt;
    d.spin += dt * 3;
    let gone = false;
    if (circleRect(d, basket)) {
      gone = true;
      if (d.kind === 'star') {
        caught++; combo++; points += 10 + 2 * (combo - 1);
        burst(d.x, d.y, '#ffd54f', 12, 120);
        beep(660 + combo * 40, 0.07);
      } else {
        burst(d.x, d.y, '#ff7043', 40, 220);
        shake = 0.4;
        endGame(false, 'You caught a bomb!');
      }
    } else if (d.y - d.r > H) {
      gone = true;
      if (d.kind === 'star') {
        misses++; combo = 0;
        burst(d.x, H - 2, '#90caf9', 8, 80);
        beep(180, 0.15, 'triangle');
      }
    }
    if (gone) { drops[i] = drops[drops.length - 1]; drops.pop(); }
  }
  if (state === 'playing' && misses >= MAX_MISSES) endGame(false, 'Three stars got away.');
  if (state === 'playing' && caught >= GOAL) endGame(true, `All ${GOAL} stars caught!`);
}

function drawStar(x, y, r, spin) {
  ctx.beginPath();
  for (let i = 0; i < 10; i++) {
    const a = spin + i * Math.PI / 5, rad = i % 2 ? r * 0.45 : r;
    ctx.lineTo(x + Math.cos(a) * rad, y + Math.sin(a) * rad);
  }
  ctx.closePath();
  ctx.fill();
}

function screen(title, ...lines) {
  ctx.fillStyle = 'rgba(5,8,20,0.7)'; ctx.fillRect(0, 0, W, H);
  ctx.textAlign = 'center'; ctx.fillStyle = '#ffd54f';
  ctx.font = 'bold 30px system-ui, sans-serif'; ctx.fillText(title, W / 2, 100);
  ctx.fillStyle = '#e8eaf6'; ctx.font = '14px system-ui, sans-serif';
  lines.forEach((l, i) => {
    ctx.font = i === 3 ? '11px system-ui, sans-serif' : '14px system-ui, sans-serif';   // 4th line: small print
    ctx.fillText(l, W / 2, 135 + i * 22);
  });
}

function draw() {
  ctx.save();
  if (shake > 0) ctx.translate((Math.random() - 0.5) * 12 * shake, (Math.random() - 0.5) * 12 * shake);
  const g = ctx.createLinearGradient(0, 0, 0, H);
  g.addColorStop(0, '#0b1030'); g.addColorStop(1, '#2a1f4f');
  ctx.fillStyle = g; ctx.fillRect(-10, -10, W + 20, H + 20);
  ctx.fillStyle = 'rgba(255,255,255,0.5)';
  for (const s of sky) ctx.fillRect(s.x, s.y, s.s, s.s);

  for (const d of drops) {
    if (d.kind === 'star') { ctx.fillStyle = '#ffd54f'; drawStar(d.x, d.y, d.r, d.spin); }
    else {
      ctx.fillStyle = '#263238'; ctx.beginPath(); ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2); ctx.fill();
      ctx.fillStyle = Math.sin(d.spin * 4) > 0 ? '#ff5252' : '#ffab40'; ctx.fillRect(d.x - 2, d.y - d.r - 5, 4, 5);
    }
  }
  ctx.fillStyle = '#8d6e63'; ctx.fillRect(Math.round(basket.x), basket.y, basket.w, basket.h);
  ctx.fillStyle = '#a1887f'; ctx.fillRect(Math.round(basket.x) - 3, basket.y, basket.w + 6, 4);
  for (const p of particles) {
    ctx.globalAlpha = Math.min(1, p.life * 2);
    ctx.fillStyle = p.color; ctx.fillRect(p.x - 2, p.y - 2, 4, 4);
  }
  ctx.globalAlpha = 1;
  ctx.restore();

  // HUD
  ctx.textAlign = 'left'; ctx.font = 'bold 14px system-ui, sans-serif'; ctx.fillStyle = '#fff';
  ctx.fillText(`★ ${caught}/${GOAL}`, 10, 20);
  ctx.fillText(`Score ${points}`, 90, 20);
  ctx.fillStyle = '#9aa3b5'; ctx.fillText(`Best ${best}${muted ? '  · muted' : ''}`, 190, 20);
  ctx.textAlign = 'right';
  for (let i = 0; i < MAX_MISSES; i++) {
    ctx.fillStyle = i < MAX_MISSES - misses ? '#90caf9' : '#37474f';
    ctx.beginPath(); ctx.arc(W - 14 - i * 18, 15, 6, 0, Math.PI * 2); ctx.fill();
  }
  if (combo >= 3 && state === 'playing') { ctx.fillStyle = '#ffd54f'; ctx.fillText(`combo ×${combo}`, W - 70, 20); }

  const saveNote = store.persistent ? '' : 'Storage is blocked in this frame: the best score lasts until you reload.';
  if (state === 'title') screen('STAR CATCHER', `Catch ${GOAL} stars. Miss ${MAX_MISSES} or catch a bomb and it's over.`, '←/→, A/D or the mouse to move · P pause · M mute', 'Press Enter, Space or click to start');
  if (state === 'paused') screen('Paused', 'P, Enter or click to resume');
  if (state === 'won') screen('You win!', message, `Score ${points} · Best ${best}${newBest ? ' · new best!' : ''}`, 'Enter or click to play again', saveNote);
  if (state === 'lost') screen('Game over', message, `Score ${points} · Best ${best}${newBest ? ' · new best!' : ''}`, 'Enter or click to try again', saveNote);
}

run(update, draw, 'Catch the stars, dodge the bombs');
</script>

About saving: in these lesson frames (sandboxed iframes without allow-same-origin) touching localStorage throws a SecurityError. The wrapper probes storage once inside try/catch and falls back to memory, so the game works everywhere and tells the player when the best score can't be kept. Copy the file into a normal .html page and the best score survives reloads.

Note: All sound is generated with oscillators and all graphics are drawn with canvas calls, so the game is one self-contained file: no images, no audio files, no libraries. It works offline and can't break because a CDN is down.

Ship it

To share the game, copy the final block into a file star-catcher.html, open it in a browser, and play it start to finish twice. Then:

  1. Upload it to itch.io as an HTML game (zip the file as index.html) and set the embed size to 960×540.
  2. Write a short README: controls, the goal, and one design choice you made.
  3. Watch a friend play it without explaining anything. Note every moment they are confused.

What you practised

Skill Where in Star Catcher
Testing rules without graphics Step 1's seeded simulation and autopilot
State machines title → playing ⇄ paused → won/lost → playing
Fixed-step updates, edge-triggered keys update(dt) and pressed from the play kit
Collision circleRect between drops and the basket
Difficulty curves fall speed and spawn interval driven by caught
Juice particles, shake, combo sounds
Robust platform code focus, capture-phase clicks, auto-pause, audio unlock, storage fallback

Ideas to extend it

  1. Power-ups: a green drop that widens the basket for five seconds (a timer, like a cooldown).
  2. Levels: after 25 stars, go to "Level 2" with faster drops instead of ending (store level settings in an array).
  3. Lives instead of misses: show hearts and flash the basket when one is lost (tweening).
  4. Settings screen: volume slider and key rebinding, saved with the same storage wrapper.
  5. Touch buttons: two big on-screen arrows for phones without a mouse.
  6. Daily challenge: seed the random generator with the date so everyone gets the same stars today, as Step 1 does with fixed seeds.

Test yourself

Why does Step 1 use a seeded random generator and a fixed step?

  1. Seeded random numbers are faster
  2. So every simulated game is reproducible and balance checks give the same answer each run
  3. Because Math.random doesn't work in Node
  4. To make the game harder

Why is the 'start' click listener registered on window with capture: true?

  1. Capture listeners are faster
  2. It runs before the kit's focus handler, so the click that focuses the frame doesn't also start the game
  3. Canvas elements can't receive clicks
  4. It is required for touch screens

What does the game do when localStorage throws a SecurityError in the sandboxed lesson frame?

  1. It crashes with an error
  2. It stops saving and hides the score
  3. It keeps the best score in a Map in memory and tells the player it won't survive a reload
  4. It retries every frame