Web Games From Zero · Episode 08
A Complete Game
A Complete Game is Episode 08 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 .
Seven episodes ago we wrote a loop that just clamped a number to a constant timestep. Since then we've added input, sprites, swept collision, a jump that actually feels good, screen shake, enemies, and a score HUD — each in its own sandbox. This is the episode where we glue all of it together into one tight, polished, genuinely fun little game. Not a tech demo. A game you'd drop in a tweet and watch a stranger lose ten minutes to.
Meet Arena Survivor: you're a glowing triangle in a box, mouse
to aim, click to shoot, WASD to dodge. Enemies pour in from the edges in escalating
waves, the screen kicks when you land a hit, you die in a shower of sparks, and a
high score waits in localStorage to taunt you. The demo below is
playing itself right now — a tiny attract-mode AI is dodging and shooting
on the title screen. Press any key or click to rip the controls out of its hands.
Everything you see is one update() stepping every system on the same
fixed clock. Let's assemble it.
What you're looking at
Six stages, one codebase. Each stage doesn't load different code — it flips a few
features booleans on the same game and lets you see what each
layer of the season actually contributes. Stage 1 is just movement in a box.
Stage 6 is the shipped game. Drag the difficulty slider and the spawn rate and
enemy speed scale live. Toggle juice off and watch how flat
"correct but lifeless" feels. Toggle sound on (it's off by default —
audio must never autoplay) and the first click unlocks gesture-gated Web Audio blips.
The whole thing runs on the fixed-timestep loop from Episode 01. The renderer
interpolates, but every bullet, enemy, particle, and screen-shake decay advances by a
constant STEP — so the game plays identically at 30, 60, or 144 Hz.
That single discipline is what lets us stack eight systems without the physics turning
to soup.
Stage 1 — World + player
The floor of any game: an arena with bounds and an avatar that obeys you. The player is a triangle that points where the mouse is, accelerates toward your WASD/arrow input, has a little drag so it glides to a stop, and is clamped to the box. No enemies, no stakes — but it already has to feel responsive, because every other system hangs off this one. In attract mode the demo-AI wanders and aims at where enemies would be, so even the empty arena looks alive.
Stage 2 — Enemies & waves
Now the pressure. A wave manager spawns batches of chasers from the
arena edges; clear a wave and the next is bigger and faster. Each enemy is a tiny
finite-state machine — spawning (fading in, harmless) then
chasing (steering straight at the player). Enemies come from a
pool: we never allocate one mid-game, we just grab a dead slot and
revive it. That's the difference between a smooth 60fps and a garbage-collector hitch
at wave 12.
Stage 3 — Combat & collision
Click to fire pooled bullets toward the cursor. Bullets are small and fast, so we use swept collision (Episode 03): test the segment the bullet traveled this step against each enemy circle, not just its end point, or fast bullets tunnel straight through. Enemies that touch the player deal contact damage on a short cooldown. This stage is where the loop becomes a game: there's now a way to win an exchange and a way to lose one.
Stage 4 — Juice
Everything from Episode 05, applied to the whole game at once. Killing an enemy adds trauma (screen shake), spawns a particle burst, and triggers a few frames of hit-stop — the entire simulation freezes for ~60ms so the impact lands. The player and enemies squash when they take a hit. Same mechanics as Stage 3, but now it feels like something. Toggle the juice checkbox mid-fight to feel exactly how much these cheap tricks buy.
Stage 5 — Score / HUD / game-over
The shell of a real game: a score that ticks up per kill, the current wave, and a
health bar across the top. Run out of health and the game enters a dead
scene — a "GAME OVER" card with your score and a prompt to retry. The critical detail is
that retry fully resets: every pool is cleared, score and wave go back
to zero, the player is re-centered at full health. A half-reset is the most common bug in
a beginner's first game, and it's the thing this stage exists to get right.
Stage 6 — The full game
All of it, wired into a scene machine:
menu → play → dead → (retry) → play. The menu is the attract
demo — the AI plays a real round behind a "ARENA SURVIVOR / click to play" title. Your
best run is saved to localStorage and shown as BEST. Sound is
optional and gesture-gated. This is the shippable artifact: a complete game in a single
HTML file with no dependencies. Everything below is how it's built.
How the code works
The hard part of a "complete game" isn't any one system — it's the wiring. Four blocks carry the whole thing: the state that ties systems together, the attract-mode AI, the spawn + collision resolution, and the scene/score/retry flow.
(a) One state, one update() stepping every system
There's a single G object holding the player, the three pools, the wave
counter, the juice timers, and the current scene. update(STEP) is the spine:
it reads input once, then steps each subsystem in order on the same constant slice. If
hit-stop is active it skips the step entirely (but rendering keeps going), so the freeze
is visible. Note that nothing multiplies by a variable dt — that's the
Episode 01 rule, and it's why the game is deterministic.
// The whole game is one object. No globals scattered around.
const G = {
scene: 'menu', // 'menu' | 'play' | 'dead'
player: makePlayer(),
enemies: pool(120, makeEnemy), // pre-allocated — never grow mid-game
bullets: pool(200, makeBullet),
parts: pool(400, makePart),
wave: 0, waveTimer: 0, toSpawn: 0, alive: 0,
score: 0, best: loadBest(),
trauma: 0, freeze: 0, // juice: shake + hit-stop
};
function update(dt) {
if (G.freeze > 0) { G.freeze -= dt; return; } // hit-stop: skip sim, keep drawing
const inp = readInput(); // human OR demo-AI — same shape
if (G.scene === 'play') {
stepPlayer(G.player, inp, dt);
stepWaves(dt); // (c)
stepEnemies(dt);
stepBullets(dt);
resolveCombat(dt); // (c)
if (G.player.hp <= 0) gameOver(); // (d)
} else {
runAttract(dt); // menu & dead: AI keeps playing behind the card
}
stepParticles(dt);
G.trauma = Math.max(0, G.trauma - dt * 1.6); // shake decays every step
}
(b) The attract-mode AI that genuinely plays
The single most important rule of attract mode: the AI drives the
exact same input path as the human. readInput() returns the same
{move, aim, fire} shape whether it came from the keyboard or from
demoAI(), so there is no "demo code path" that can rot. The policy is
deliberately simple and readable: find the nearest enemy, aim at it, fire, and steer
away from the closest threat so it doesn't just walk into a hug. It doesn't play
well — it plays visibly, which is all attract mode needs.
// Returns the SAME object a human produces — so update() can't tell them apart.
function demoAI() {
const p = G.player;
const near = nearestEnemy(p.x, p.y); // scan the live pool
let mx = 0, my = 0, aimX = p.x + Math.cos(p.ang), aimY = p.y + Math.sin(p.ang);
let fire = false;
if (near) {
aimX = near.x; aimY = near.y; // aim at the nearest enemy
fire = true; // and shoot at it
const d = Math.hypot(near.x - p.x, near.y - p.y);
if (d < 160) { // too close? back away (dodge)
mx = (p.x - near.x) / d; my = (p.y - near.y) / d;
} else { // otherwise drift toward center, strafing
mx = (ARENA.w/2 - p.x) * 0.002 + Math.cos(t*2) * 0.6;
my = (ARENA.h/2 - p.y) * 0.002 + Math.sin(t*2) * 0.6;
}
} else { // no enemies: wander a lazy circle
mx = Math.cos(t * 0.9); my = Math.sin(t * 0.7);
}
return { move: norm(mx, my), aim: { x: aimX, y: aimY }, fire };
}
function readInput() {
if (G.demo) return demoAI(); // attract mode → AI drives
const mx = (keys.has('KeyD')||keys.has('ArrowRight')) - (keys.has('KeyA')||keys.has('ArrowLeft'));
const my = (keys.has('KeyS')||keys.has('ArrowDown')) - (keys.has('KeyW')||keys.has('ArrowUp'));
return { move: norm(mx, my), aim: pointer, fire: pointer.down };
}
(c) Waves, spawning, and collision resolution
The wave manager is a tiny budget machine: when no enemies are left and none are
queued, it starts the next wave by setting toSpawn to a count that grows
with the wave number and difficulty. It dribbles them in over time (a curtain of enemies
all at once is unfair and ugly). Collision resolution does two passes: swept
bullet-vs-enemy (so fast bullets can't tunnel), and a cheap circle-overlap enemy-vs-player
on a damage cooldown. Every kill routes through one killEnemy() that handles
score, juice, and returning the slot to the pool.
function stepWaves(dt) {
if (G.alive === 0 && G.toSpawn === 0) { // wave cleared → next wave
G.wave++;
G.toSpawn = 3 + G.wave * 2; // escalating count
G.spawnGap = Math.max(0.18, 0.7 - G.wave * 0.03);
}
G.waveTimer -= dt;
if (G.toSpawn > 0 && G.waveTimer <= 0) { // dribble enemies in over time
spawnEnemy(); G.toSpawn--; G.waveTimer = G.spawnGap;
}
}
function resolveCombat(dt) {
for (const b of G.bullets.live()) { // SWEPT bullet → enemy
for (const e of G.enemies.live()) {
if (e.state === 'spawning') continue; // fading-in enemies are harmless
if (segCircle(b.px, b.py, b.x, b.y, e.x, e.y, e.r + b.r)) {
e.hp -= 1; squash(e); b.dead = true;
if (e.hp <= 0) killEnemy(e); // score + juice + recycle
break;
}
}
}
const p = G.player; p.hurt = Math.max(0, p.hurt - dt);
for (const e of G.enemies.live()) { // enemy → player (cooldown)
if (e.state === 'spawning') continue;
if (p.hurt <= 0 && dist2(p, e) < (p.r + e.r) ** 2) {
p.hp -= 1; p.hurt = 0.7; squash(p);
if (FX) { addTrauma(0.5); G.freeze = 0.05; burst(p.x, p.y, '#f87171', 14); }
}
}
}
(d) Scenes, score, and a retry that fully resets
The scene machine is three strings and a couple of transitions. The thing worth
staring at is reset(): it is the only way a round begins, and it
rebuilds the world from zero — clears all three pools, resets the player, zeroes
score/wave/juice. Both "click to play" from the menu and "retry" from game-over call the
same reset(), so there is exactly one definition of "a fresh game." High
score is read once at boot and written only when beaten, wrapped in try/catch because
localStorage can throw (private mode, full quota).
function reset() { // the ONE way a round starts — full wipe
G.enemies.clear(); G.bullets.clear(); G.parts.clear();
G.player = makePlayer(); // re-centered, full hp
G.wave = 0; G.toSpawn = 0; G.alive = 0; G.waveTimer = 0;
G.score = 0; G.trauma = 0; G.freeze = 0;
}
function startGame() { G.demo = false; reset(); G.scene = 'play'; }
function gameOver() {
if (G.score > G.best) { G.best = G.score; saveBest(G.best); } // persist high score
if (FX) addTrauma(0.9);
burst(G.player.x, G.player.y, '#38bdf8', 40); // player explodes
G.scene = 'dead';
}
function loadBest() { try { return +localStorage.getItem('arena.best') || 0; } catch { return 0; } }
function saveBest(v) { try { localStorage.setItem('arena.best', v); } catch {} }
Common pitfalls
- Scope creep. A "complete game" tempts you to add a shop, five enemy types, a map. Don't — finish one tight loop first. Arena Survivor is deliberately one verb (shoot) and one threat (touch). You can always grow it after it's fun; you can't make an unfinished sprawl fun.
- Garbage-collector hitches. Allocating a bullet/enemy/particle
object every frame means the GC eventually stops the world for a few ms — a visible
stutter mid-fight. Pool everything: pre-allocate fixed arrays and
revive dead slots. We never call
newin the hot loop. - The attract-AI stands still. A dead title screen sells nothing.
The AI must actually exercise the mechanic — move, dodge, shoot. Route it through the
same
readInput()the human uses so it can never silently break, and give it a real (if dumb) policy. - Retry only half-resets. Forget to clear one pool or zero one
counter and the "new" game inherits last game's bullets, score, or wave. Make
reset()the single source of truth for "a fresh game," and call it from both the menu and game-over. - Audio autoplays. Browsers block (and users hate) sound before a
gesture. Create the
AudioContextlazily on the first click and keep it off by default. Never start audio on load. - Juice with no restraint. Shake on every frame, particles by the thousand, permanent hit-stop — now the game is unreadable. Juice is seasoning: trauma decays, hit-stop is ~3 frames, bursts are a dozen particles. The juice toggle is there so you can A/B it and feel the line.
Exercises
- A second enemy type. Add a
kindfield to the enemy. Make a "darter" that's faster, has 1 hp, and is drawn smaller — or a "tank" that's slow with 3 hp. The pool and FSM already handle it; you're just branching speed/hp/draw and maybe the spawn mix per wave. - A power-up drop. When an enemy dies, occasionally spawn a pickup (reuse a pool). On contact with the player, grant a few seconds of rapid fire, a spread shot, or a heal. This teaches timed buffs and a fourth entity type with almost no new plumbing.
- A boss every 5 waves. On waves divisible by 5, instead of a swarm, spawn one large enemy with a big health bar and a simple attack (a radial bullet burst on a timer — yes, enemies can use the same bullet pool). Beating it should feel like an event: extra score, a bigger shake, a brief slow-mo.
What's next
That's a wrap on Season 1 — The Game Loop. You started with eight
lines that clamped dt, and you just shipped a juicy, self-contained,
actually-fun arena shooter — loop, input, sprites, collision, enemies, waves, juice,
scenes, score, persistence, and an attract mode that plays itself. That is the entire
skeleton of a real game. Every commercial title is this same loop with more art and more
systems bolted on.
Season 2 — Genres & Systems bolts them on. We leave the single arena and build the machinery behind whole genres: a proper shooter with patterns and bullet hell, a tower defense with a build phase and economy, tilemaps for real levels, A* pathfinding so enemies navigate those levels, and procedural generation so the levels build themselves. Same fixed loop, same zero dependencies — much bigger worlds. See you there.