Manage a game's states and the moves between them. Loading, title / menu, settings, playing, pause, level complete, victory, defeat, restart. Covers state machines and scene stacks, what pause really freezes, clean restarts, input not leaking between screens, transitions, persistent vs per-run data, and versioned save / load. Use for "add a pause menu", "game over screen", "restart is buggy", "...
Download skill (.zip) Files on GitHubGame state management
Map the states first
Write the state diagram before coding, and put it in the design doc:
loading → title ⇄ settings
title → play ⇄ pause → title
play → levelComplete → play (next level)
play → gameover {victory | defeat} → play (retry) | title
For each state, decide: what updates, what draws, what input does, how you leave it.
Pick the mechanism
| Situation | Use |
|---|---|
| Screens replace each other (title → play → results) | State machine / switch() |
| Screens layer on top (pause, inventory, dialogue, settings over play) | Scene stack / push() + pop(): the top one updates, all draw |
| Phases inside play (countdown → playing → dying → respawn) | A small phase field on the play scene |
| Engine game (Phaser) | Engine scenes: scene.start (replace), scene.launch + scene.pause (overlay) |
The game-scaffolding template has a working stack (src/core/scenes.js). Code is in references/state-code.md.
Rules that prevent most bugs
- Each state owns its setup and teardown.
enter()creates everything it needs, andexit()removes listeners, timers and sounds it started. Restarting =switch("play")again, which gives a fresh state, not “reset 14 variables”. - Per-run vs persistent data. Per-run (score, lives, enemies, level timer) lives in the play state. Persistent (best score,
unlocked levels, settings, achievements) lives in
save. Never mix them, or a restart keeps old lives. - Pause freezes game time, not the UI. While paused: no updates to the world, game timers stop (advance timers with
dt, neversetTimeout), music ducks or pauses, and particles stop. Menus still animate. - Auto-pause on
visibilitychange(tab hidden) and onblurin an iframe. Never auto-resume into danger: resume with a short countdown or a tap. - No input leaking. The tap or key that changes a state must not also act in the next one. Use edge-triggered
input (
wasPressed), clear it at the end of each step, and add a short input delay (~0.3–0.6 s) on results screens. - Transitions are states too. A fade or level intro is either its own state or a phase that ignores gameplay input.
- One source of truth.
scenes.current(orstate.phase) says where you are. Don’t use separateisPaused,isGameOverorinMenuflags. - Victory and defeat are separate results with separate feedback: different text, colors and sounds, with stats and the next action (retry, next level, title). Show the best score after updating it.
Saving and loading
const SAVE_VERSION = 2;
const DEFAULT = { v: SAVE_VERSION, best: 0, unlocked: 1, settings: { volume: 0.8, muted: false } };
function load() {
let s = save.get("data", null);
if (!s || typeof s !== "object") return structuredClone(DEFAULT);
if (s.v === 1) s = { ...s, v: 2, settings: { volume: s.volume ?? 0.8, muted: false } }; // migrate old saves
return { ...structuredClone(DEFAULT), ...s, settings: { ...DEFAULT.settings, ...s.settings } };
}
- Version every save and migrate. Never crash on old or corrupt data, fall back to defaults.
- Save at safe moments (level end, settings change, on
visibilitychangehidden), not every frame. - Mid-level “continue” only if the game needs it: save the minimum to rebuild the state (level, position, inventory), not live objects.
- Multiplayer or shared data in Bash: use the playing-together skill, not
localStorage.
Checklist for any state change
- Title → play → pause → resume → lose → retry → win → next / title all work by keyboard and touch
- Restart gives exactly the same starting conditions (lives, score, positions, timers, music)
- Nothing moves or counts down while paused. Hiding the tab pauses
- No double actions from one tap across a state change
- Best score and unlocks survive a reload. Per-run data doesn’t
- No duplicate listeners or sounds after 5 restarts (check the console and listen)