Find a course

Module 5: Input, Collisions and a Full GameLesson 11 of 1114 min

Randomness, Score and Game Over

Spawn enemies at random positions with Math.random, track score and high score, and add start, playing and game-over states to finish a real game.

Step 1 of 11Learn

Random numbers in the right range

A game that plays out the same way every time gets boring fast. Randomness makes enemies appear in different places, makes loot drops surprising and makes each round feel new.

JavaScript's Math.random() returns a decimal number from 0 up to, but not including, 1, such as 0.0371 or 0.8812. You almost never want that number directly, so you scale and shift it:

  • A decimal in a range: min + Math.random() * (max - min). For an x position across a 480-pixel canvas, Math.random() * 480 gives anything from 0 up to just below 480.
  • A whole number: wrap it in Math.floor, which rounds down. Math.floor(Math.random() * 6) gives 0, 1, 2, 3, 4 or 5, each equally likely.
  • A dice roll from 1 to 6: Math.floor(Math.random() * 6) + 1.

The general formula for a random whole number from min to max, both included, is:

Math.floor(Math.random() * (max - min + 1)) + min

The + 1 is the part people forget. Without it, max can never come up, because Math.random() never quite reaches 1.

Watch out for Math.round. It seems natural, but it makes the end values half as likely as the middle ones, because only half a range rounds to each end. Use Math.floor for fair random integers.

Step 2 of 11Diagram

Turning Math.random() into a die roll

Turning Math.random() into a die rollProcess diagram: Math.random() → × 6 → Math.floor(…) → + 1.Math.random()× 6Math.floor(…)+ 1

Tap a shape with to see more.

Math.random()

A decimal from 0 up to, but not including, 1.

× 6

Now from 0 up to just below 6.

Math.floor(…)

Round down: 0, 1, 2, 3, 4 or 5.

+ 1

Shift to 1 through 6, each equally likely.

Step 3 of 11Practice · Choose one

Which expression gives a random whole number from 1 to 10, with each number equally likely?

Step 4 of 11Learn

Spawning and difficulty

Let's build the game you've been assembling all course: Star Catcher. Stars fall from the top of the canvas, the player moves a basket left and right, each star caught is worth a point, and each star missed costs a life.

Spawning uses randomness for the position and a timer for when:

let spawnTimer = 0;

function update() {
  spawnTimer++;
  if (spawnTimer >= spawnEvery) {
    stars.push({ x: Math.random() * (canvas.width - 20), y: -20,
                 width: 20, height: 20, speed: 2 + Math.random() * 2 });
    spawnTimer = 0;
  }
  for (const s of stars) s.y += s.speed;
}

With spawnEvery = 60, a new star appears about once per second at 60 fps, at a random x and with a random speed between 2 and 4.

Difficulty. A good game gets harder as the player improves. Common tricks: lower spawnEvery as the score rises (more stars), raise the speed range, or add a rare "bomb" that must be avoided. For example, spawnEvery = Math.max(20, 60 - score) starts at one star per second and speeds up to three per second, but never faster. Small, steady increases feel fair; sudden jumps feel cruel.

Then, each frame, check every star: if it hits the basket, add a point and remove it; if its y goes past the bottom of the canvas, lose a life and remove it.

Step 5 of 11Practice · Work it out

A game uses spawnEvery = Math.max(20, 60 - score). How many frames apart are stars spawned when the score is 25?

Step 6 of 11Practice · Chart

spawnEvery = Math.max(20, 60 - score)

At which score does the game stop getting faster?

Tap the point that answers the question, then press Check.

spawnEvery = Math.max(20, 60 - score)Line chart with 7 categories: 0 pts: 60; 10 pts: 50; 20 pts: 40; 30 pts: 30; 40 pts: 20; 50 pts: 20; 60 pts: 20.0204060frames0 pts10 pts20 pts30 pts40 pts50 pts60 ptsscore
spawnEvery = Math.max(20, 60 - score)
scoreframes between stars
0 pts60
10 pts50
20 pts40
30 pts30
40 pts20
50 pts20
60 pts20

Step 7 of 11Learn

Game states and high scores

A finished game needs more than the action. It needs a title screen, the playing part and a game over screen. The clean way to organize this is a single variable that holds the current state:

let state = "start";   // "start", "playing" or "over"

function gameLoop() {
  if (state === "start")   drawTitle();
  if (state === "playing") { update(); draw(); }
  if (state === "over")    drawGameOver();
  requestAnimationFrame(gameLoop);
}

Key presses move between states: Enter on the title screen sets state = "playing"; losing the last life sets state = "over"; Enter on the game-over screen calls resetGame() and goes back to playing. The resetGame function puts every piece of state back to its starting value: score 0, lives 3, empty stars array. Forgetting one value, such as the spawn timer or the speed, is a typical bug where round two starts strangely.

High score. Compare the final score to the best so far when the game ends. To remember it after the page is closed, browsers offer localStorage, a small storage area for each site:

if (score > best) {
  best = score;
  localStorage.setItem("best", best);
}

On startup, read it back with Number(localStorage.getItem("best")) || 0. The Number matters, since storage always returns text, and || 0 covers the very first play when nothing is saved yet.

Step 8 of 11Diagram

Three game states

Three game statesProcess diagram: state = "start" → state = "playing" → state = "over".state = "start"state = "playing"state = "over"

Tap a shape with to see more.

state = "start"

Title screen. Enter switches to playing.

state = "playing"

update() and draw() run every frame.

state = "over"

Last life lost. Enter calls resetGame() and goes back to playing.

Step 9 of 11Tap to reveal

Finishing touches that make a game feel complete

  1. Clear instructions

    The title screen should say how to play in one line, such as "Arrow keys to move, catch the stars, Enter to start." Players won't guess your controls.

  2. Feedback for every action

    A flash, a sound or a small pop of particles when catching a star tells players their action counted. Even a color change for a few frames helps a lot.

  3. A fair start

    Give players a second or two before the first star or enemy arrives, so they aren't hit before they understand what's happening.

  4. Pause

    Toggle a paused flag with the P key and skip update while it's true. Players appreciate being able to stop for a moment.

  5. Playtesting

    Watch a friend play without helping. Where they get confused or frustrated shows you exactly what to fix next.

Step 10 of 11Practice · Code challenge

Write nextState(state, key, lives) for a game with states "start", "playing" and "over". Rules: from "start", pressing "Enter" goes to "playing". From "playing", if lives is 0 or less, go to "over". From "over", pressing "Enter" goes to "playing". In every other case, return the current state unchanged.

Runs in a sandbox in your browser.
  • nextState("start", "Enter", 3)
  • nextState("start", "a", 3)
  • nextState("playing", "", 0)
  • nextState("playing", "Enter", 2)
  • nextState("over", "Enter", 0)
  • nextState("over", " ", 0)

Step 11 of 11Practice · Select all that apply

Ana's resetGame function must restart Star Catcher cleanly. Which values should it set back to their starting values? Select all that apply.

Select all that apply.