Pong 4: Game States & Restart
Our Pong plays well, but it starts the moment you click and never ends. Real games have a flow: a title screen, the match, a pause screen, a game-over screen, and a way back to the start. In this final Pong step we organise that flow with a state machine, the single most useful structure in game code.
What is a state machine?
The game is always in exactly one state, and each state decides what update and draw do and which events move the game to another state:
| State | Update does | Draw shows | Leaves when |
|---|---|---|---|
title |
nothing | logo + "press Enter" | Enter/Space → playing |
playing |
the whole game | court | P/Esc → paused; a player reaches 5 → over |
paused |
nothing | court + "Paused" | P/Esc → playing |
over |
nothing | court + winner | Enter/Space → playing (new match) |
The alternative, a pile of booleans like isStarted, isPaused, isGameOver, lets impossible combinations exist ("paused and game over?"). One state variable makes them impossible.
The transitions as data
You can write the whole flow as a table and test it without any graphics:
const TRANSITIONS = {
title: { start: 'playing' },
playing: { pause: 'paused', win: 'over' },
paused: { pause: 'playing' },
over: { start: 'playing' },
};
function next(state, event) {
return TRANSITIONS[state][event] ?? state; // unknown events are ignored
}
let state = 'title';
for (const event of ['pause', 'start', 'pause', 'win', 'pause', 'win', 'start']) {
const after = next(state, event);
console.log(`${state.padEnd(7)} --${event}--> ${after}`);
state = after;
}title --pause--> title
title --start--> playing
playing --pause--> paused
paused --win--> paused
paused --pause--> playing
playing --win--> over
over --start--> playing
Look at line 1 and line 4: pressing pause on the title screen, or a "win" arriving while paused, does nothing. The table refuses transitions that make no sense, which removes a whole class of bugs.
Starting a match = resetting state
"Restart" is the place where leftover state hides. Put everything a match needs in one function and call it for every new match:
function startMatch() {
score.left = score.right = 0;
left.y = right.y = H / 2 - PADDLE_H / 2;
serve(Math.random() < 0.5 ? -1 : 1);
state = 'playing';
}If the second match behaves differently from the first, something isn't reset here.
The complete Pong
Click, then press Enter. W/S to move, P or Esc to pause, 2 for two players. First to 5 wins:
<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 ----
// ---- Pong, step 4: title, pause, game over and restart ----
const PADDLE_W = 8, PADDLE_H = 50, PADDLE_SPEED = 260;
const BALL_SPEED = 220, SPEEDUP = 1.06, MAX_SPEED = 520, MAX_ANGLE = Math.PI / 3;
const AI_SPEED = 190, AI_DEAD_ZONE = 6, WIN_SCORE = 5;
const left = { x: 16, y: H / 2 - PADDLE_H / 2 };
const right = { x: W - 16 - PADDLE_W, y: H / 2 - PADDLE_H / 2 };
const ball = { x: W / 2 - 4, y: H / 2 - 4, size: 8, vx: 0, vy: 0 };
const score = { left: 0, right: 0 };
let serveTimer = 0, serveDir = 1, twoPlayers = false;
let state = 'title'; // 'title' | 'playing' | 'paused' | 'over'
function serve(dir) {
ball.x = W / 2 - ball.size / 2;
ball.y = H / 2 - ball.size / 2;
ball.vx = ball.vy = 0;
serveDir = dir;
serveTimer = 1;
}
function startMatch() {
score.left = score.right = 0;
left.y = right.y = H / 2 - PADDLE_H / 2;
serve(Math.random() < 0.5 ? -1 : 1);
state = 'playing';
}
function movePaddle(p, up, down, dt) {
if (keys.has(up)) p.y -= PADDLE_SPEED * dt;
if (keys.has(down)) p.y += PADDLE_SPEED * dt;
p.y = Math.max(0, Math.min(H - PADDLE_H, p.y));
}
function computerPaddle(p, dt) {
const target = ball.vx > 0 ? ball.y + ball.size / 2 : H / 2;
const diff = target - (p.y + PADDLE_H / 2);
if (Math.abs(diff) > AI_DEAD_ZONE) p.y += Math.sign(diff) * Math.min(AI_SPEED * dt, Math.abs(diff));
p.y = Math.max(0, Math.min(H - PADDLE_H, p.y));
}
function hits(b, p) {
return b.x < p.x + PADDLE_W && b.x + b.size > p.x &&
b.y < p.y + PADDLE_H && b.y + b.size > p.y;
}
function bounceOff(p, dir) {
const offset = (ball.y + ball.size / 2 - (p.y + PADDLE_H / 2)) / (PADDLE_H / 2);
const angle = Math.max(-1, Math.min(1, offset)) * MAX_ANGLE;
const speed = Math.min(Math.hypot(ball.vx, ball.vy) * SPEEDUP, MAX_SPEED);
ball.vx = dir * speed * Math.cos(angle);
ball.vy = speed * Math.sin(angle);
}
function point(winner) {
score[winner]++;
if (score[winner] >= WIN_SCORE) { state = 'over'; ball.vx = ball.vy = 0; return; }
serve(winner === 'left' ? 1 : -1); // serve toward the player who lost the point
}
function play(dt) {
movePaddle(left, 'KeyW', 'KeyS', dt);
if (twoPlayers) movePaddle(right, 'ArrowUp', 'ArrowDown', dt);
else computerPaddle(right, dt);
if (serveTimer > 0) {
serveTimer -= dt;
if (serveTimer <= 0) {
const angle = (Math.random() - 0.5) * 0.8;
ball.vx = serveDir * BALL_SPEED * Math.cos(angle);
ball.vy = BALL_SPEED * Math.sin(angle);
}
return;
}
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }
if (ball.y + ball.size > H) { ball.y = H - ball.size; ball.vy = -Math.abs(ball.vy); }
if (ball.vx < 0 && hits(ball, left)) { ball.x = left.x + PADDLE_W; bounceOff(left, 1); }
if (ball.vx > 0 && hits(ball, right)) { ball.x = right.x - ball.size; bounceOff(right, -1); }
if (ball.x + ball.size < 0) point('right');
if (ball.x > W) point('left');
}
function update(dt) {
const confirm = pressed.has('Enter') || pressed.has('Space');
const pause = pressed.has('KeyP') || pressed.has('Escape');
if (pressed.has('Digit2')) twoPlayers = !twoPlayers;
switch (state) {
case 'title':
case 'over':
if (confirm) startMatch();
break;
case 'playing':
if (pause) state = 'paused';
else play(dt);
break;
case 'paused':
if (pause) state = 'playing';
break;
}
}
function drawCourt() {
ctx.fillStyle = '#0e1018';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#2a2f45';
for (let y = 4; y < H; y += 16) ctx.fillRect(W / 2 - 1, y, 2, 8);
ctx.fillStyle = '#5c6380';
ctx.font = 'bold 36px ui-monospace, monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.fillText(score.left, W / 2 - 50, 12);
ctx.fillText(score.right, W / 2 + 50, 12);
ctx.fillStyle = '#e8eaf6';
ctx.fillRect(Math.round(left.x), Math.round(left.y), PADDLE_W, PADDLE_H);
ctx.fillRect(Math.round(right.x), Math.round(right.y), PADDLE_W, PADDLE_H);
if (state !== 'playing' || serveTimer <= 0 || Math.floor(serveTimer * 6) % 2 === 0) {
ctx.fillStyle = '#ffb74d';
ctx.fillRect(Math.round(ball.x), Math.round(ball.y), ball.size, ball.size);
}
}
function draw() {
drawCourt();
const mode = twoPlayers ? '2 players' : 'vs computer';
if (state === 'title') banner('PONG', `Enter to start · ${mode} (press 2 to change)`);
if (state === 'paused') banner('Paused', 'P or Esc to continue');
if (state === 'over') {
const winner = score.left > score.right ? 'Left player' : (twoPlayers ? 'Right player' : 'Computer');
banner(`${winner} wins ${Math.max(score.left, score.right)}–${Math.min(score.left, score.right)}`, 'Enter for a rematch');
}
}
run(update, draw, 'Then Enter to start · W/S · P pause · 2 players');
</script>How the pieces fit
updatereads the input once at the top (confirm,pause) and then hands control to the current state with aswitch. Each case only does what that state allows.- The old
updatewas renamedplay(dt): it's now just one state's behaviour. drawalways draws the court and then layers the state's overlay on top, using the kit'sbanner(). The paused screen still shows the frozen game behind it, so players remember where the ball was.point()checks the win condition in one place. Scoring and winning are game rules; keeping them together makes them easy to change ("win by two", "first to 11").
Note: The kit already pauses when the frame loses focus (click outside the game). That's a safety net for the lesson page; a real game also wants its own pause key and, as you'll see in Pause & visibilitychange, should pause when the browser tab is hidden.
Ideas to extend Pong
- Add a difficulty choice on the title screen (keys 1–3 set
AI_SPEED). - Make the computer aim: predict where the ball will cross its x position, including wall bounces.
- Shrink the paddles a little after each point.
- Add sound effects; you'll learn how in Breakout 4.
Test yourself
Why is a single state variable better than flags like isPaused and isGameOver?
- It uses less memory
- It makes impossible combinations (paused and game over at once) impossible to represent
- Booleans are slow in JavaScript
- Switch statements require it
In the transition table, what happens when the event win arrives in the paused state?
- The game ends
- Nothing: the state stays
paused - The game restarts
- An error is thrown
Where should a "new match" reset every score, position and timer?
- Spread over the draw function
- In one
startMatch()function called for every match - In the play kit
- Nowhere; reload the page