Web Games From Zero · Episode 07

Scenes, Score & UI

Scenes, Score & UI is Episode 07 of Web Games From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 07 · Web Games From Zero

You've spent six episodes making a mechanic feel good — the loop, the input, the collisions, the jump, the juice. But a mechanic isn't a game. A game has a front door and a back door: it starts, it gives you a score, and it ends — and then it lets you go again. That shell is what your player actually experiences before and after the fun part, and it's the difference between "a thing that moves" and "a thing people play twice."

This episode builds that shell: a tiny scene manager (menu → play → game-over → retry), a score and combo system, a HUD, smooth transitions between scenes, and a high score that survives a refresh via localStorage. Play the demo below — or don't, and watch it play itself: lose, see the game-over screen, retry, climb the score. By the end you'll have the plumbing that every one of your future games reuses unchanged.

0 fps
▶ playing demo — press any key or click to take over
scene: —
A scene manager: switch between two placeholder scenes. Each has enter / update / render / exit.

What you're looking at

One canvas, one game loop — but six different configurations of the same scene system, selected by the stage dropdown. In every stage the demo runs in attract mode: a built-in AI presses the same buttons a player would, so the screen is alive the instant it loads. Touch a key or click and you take over; flip attract back on (or sit idle a few seconds) and the demo resumes.

The stage dropdown does double duty here, and that's the lesson: picking a stage is itself a scene change. Stages 1–4 jump you straight into a specific scene so you can study it in isolation; stages 5 and 6 hand control back to the full menu→play→game-over flow with transitions and the HUD turned on. The badge bottom-left always tells you which scene is currently active — watch it flip as the game moves itself from menu to play to game-over and back.

Stage 1 — A scene manager

The whole episode rests on one small abstraction: a scene is an object with four methods — enter, update, render, and exit — and the game holds exactly one current scene at a time. To change scenes you call setScene(next), which runs the old scene's exit() and the new scene's enter(). That's it. This stage strips everything else away: two placeholder scenes, "A" and "B", that do nothing but pulse a color and print their name. The demo flips between them on a timer so you can see the handoff. Master this and the rest is just filling the methods in.

Stage 2 — Title / menu scene

The first real scene a player sees. A big title, a blinking "press to start" prompt, and — crucially — gameplay running behind it. That background isn't a video or a static image; it's the actual play scene driven by the demo AI, dimmed and shoved to the back. This is attract mode in its original arcade sense: the cabinet plays itself to lure you in. Pressing start (Space/click) leaves the menu and enters play.

Stage 3 — Play scene + score

The mechanic: a little ship you steer left/right to catch falling coins (score up) while dodging falling rocks (lose a life). It's deliberately tiny — the point isn't the game, it's that the score ticks. Every coin adds points; the running total lives on the scene object, not at file scope, so a fresh play starts at zero. Catch a streak without missing and you'll notice the points come faster — that's the combo system from Stage 6 sneaking in early.

Stage 4 — Game-over scene + retry

Lose all your lives and the play scene calls setScene(gameOver). The game-over scene shows your final score, the high score, and a "retry" prompt. Hit it and you go back to a completely fresh play scene — full lives, zero score, no leftover coins or rocks from last time. That clean reset is the single most important correctness property in this episode, and the most common thing beginners get wrong (see pitfalls). The demo AI loses on purpose now and then so you can watch the full lose→game-over→retry cycle.

Stage 5 — Transitions

Snapping instantly between scenes feels cheap. A transition is a short overlay that hides the swap: here, a fade-to-black that covers the screen, switches the scene at the darkest moment, then fades back. It's driven by one timer that counts 0→1 and a flag that says "halfway through, do the actual setScene." While a transition is playing, input is locked so you can't trigger a second switch mid-fade. Same scenes as before — now they dissolve into each other.

Stage 6 — HUD + combo + high score

The full package. A polished HUD draws the score, a combo multiplier (×2, ×3… that climbs as you chain catches and decays if you stall), and your remaining lives as little pips. And the score you beat last session is still there: the high score is saved to localStorage every time a run ends and loaded when the page opens, so it survives a refresh. Beat it and the HUD says so. This is the shell that turns the Stage 3 toy into something you'd actually want to top.

How the code works

Four ideas, four code blocks: the scene manager, a concrete scene, the score+combo rules, and the localStorage wrapper. Everything in the demo is built from these.

1. The scene manager

A scene is just an object literal with four optional methods. The manager holds the current one and a setScene that does the exit/enter dance. Notice that enter() receives the new scene's chance to reset its own state — that's where a fresh play scene zeroes its score — and that we guard every call with ?. so a scene can omit any method it doesn't need.

// One current scene at a time. setScene runs exit() then enter().
let current = null;

function setScene(next) {
  current?.exit?.();          // let the old scene tear down / clear input
  current = next;
  current?.enter?.();         // the new scene initializes ITS OWN state here
}

// The loop just forwards to whoever is current — it never knows which scene that is.
function update(dt) { current?.update?.(dt); }
function render(ctx) { current?.render?.(ctx); }

That is the entire abstraction. The loop forwards update/render to current without ever knowing whether it's the menu, the game, or the game-over screen. Adding a pause screen or an options menu later means writing one more object and calling setScene — no changes to the loop at all.

2. A scene object (the play scene)

Here's a real scene. The golden rule lives in enter(): every piece of per-run state is (re)initialized here, never at file scope. That's what makes "retry" produce a clean game instead of resuming a corpse. update reads input through readInput() (so the demo AI and the human share one code path), moves the world by the fixed dt, and calls setScene when the lose condition fires.

const playScene = {
  enter() {                      // ← reset EVERYTHING for a fresh run, right here
    this.score = 0;
    this.lives = 3;
    this.combo = 1;
    this.coins = [];
    this.rocks = [];
    this.shipX = W / 2;
  },
  update(dt) {
    const input = readInput();              // demo-AI or human — same shape
    if (input.left)  this.shipX -= 320 * dt;
    if (input.right) this.shipX += 320 * dt;
    spawnAndMove(this, dt);                  // move coins/rocks, test catches
    if (this.lives <= 0) setScene(gameOverScene);
  },
  render(ctx) { drawWorld(ctx, this); drawHUD(ctx, this); },
  exit() { keys.clear(); }              // don't let held keys bleed into the next scene
};

3. Score + combo (the multiplier decays over time)

Score is easy; the combo is what makes it feel good. Each catch adds points scaled by the current multiplier and refreshes a comboTimer. If you don't catch anything before the timer runs out, the multiplier collapses back to ×1. So a clean streak snowballs, and one fumble resets the party. The decay is the whole trick — without it, the multiplier would only ever go up and the number would stop meaning anything.

// On a successful catch:
function onCatch(s) {
  s.score += 10 * s.combo;          // points scale with the multiplier
  s.combo  = Math.min(8, s.combo + 1); // climb, capped so it can't run away
  s.comboTimer = 2.0;             // you have 2s to keep the chain alive
}

// Every update(dt): let the combo decay if the player stalls.
function tickCombo(s, dt) {
  s.comboTimer -= dt;
  if (s.comboTimer <= 0) s.combo = 1;   // chain broken → back to ×1
}

4. High score in localStorage (wrapped in try/catch)

Persistence is one line each way — but localStorage can throw (Safari private mode, disabled storage, a full quota), so both calls go in try/catch. Read returns a sensible default on failure; write silently does nothing. The game keeps working even when storage doesn't, which is exactly what you want — a high score is a nicety, not a load-bearing feature.

const HS_KEY = 'wgz07.highscore';

function loadHigh() {
  try {
    return parseInt(localStorage.getItem(HS_KEY) ?? '0', 10) || 0;
  } catch (e) { return 0; }   // private mode / blocked → just start at 0
}

function saveHigh(score) {
  try {
    localStorage.setItem(HS_KEY, String(score));
  } catch (e) { /* storage unavailable — fail silently, game still runs */ }
}

Call loadHigh() once on boot, and saveHigh() whenever a run ends with a new best. The game-over scene compares finalScore against the loaded high, saves if it's bigger, and shows a "NEW BEST!" banner — the small dopamine hit that makes a refresh-proof number worth chasing.

Common pitfalls

  • State leaks between scenes. If your score, lives, or entity arrays live at file scope and you only set them once, "retry" will resume last game's mess — half-full of old coins, score already high. Reset per-run state inside enter(), not at the top of the file. The enter/exit pair exists precisely so each visit to a scene is a clean slate.
  • Input bleeds across scenes. A key held down during play is still "down" when you hit game-over, so a buffered jump or fire can instantly skip the game-over screen. Have each scene read input itself, and keys.clear() on exit() (or right after a setScene) so nothing carries over.
  • localStorage can throw. In Safari private mode and some locked-down browsers, even reading it raises an exception. An unguarded localStorage.getItem on boot will crash your whole game before first paint. Always wrap both read and write in try/catch and degrade gracefully.
  • Transition timing race. If input isn't locked during a fade, a player (or an over-eager demo AI) can fire a second setScene mid-transition, and you'll swap scenes twice or land somewhere wrong. Gate input on a transitioning flag, and do the actual swap exactly once, at the midpoint.

Exercises

  1. A pause scene. Add a pauseScene that, instead of replacing play, renders on top of it (draw the frozen play scene first, then a dimmed "PAUSED" overlay) and freezes update. Hint: keep a reference to the scene you paused so you can resume exactly where you left off — pausing shouldn't go through enter() or it'll reset the game.
  2. An options scene. Add a small options menu reachable from the title that toggles one real setting — say, coin spawn rate or whether rocks are enabled — and have the play scene read that setting in enter(). Bonus: persist the setting in localStorage next to the high score.
  3. A top-5 high-score table. Instead of a single number, store a sorted array of the five best scores in localStorage (JSON-encoded, still in try/catch). On game-over, insert the new score, sort, slice to five, and render the leaderboard on the game-over scene. Watch out for the JSON parse throwing on corrupt data — default to [].

What's next

Episode 08 — A Complete Game (Season Finale). We take everything from the whole series — the fixed-timestep loop, input, collisions, the jump feel, the juice, and the scene/score/UI shell you just built — and assemble one complete, polished game from menu to victory. The scene manager from this episode is the spine the finale hangs on, so the work you did here pays off immediately. See you at the finish line.