Lesson 5 路 Websites from scratch

Make a browser game

Build a click-the-target game with a score and a timer.

About 35 minutes

Tab indents. Press Escape, then Tab, to leave the editor.

Time to build something you can hand to a friend and say "beat my score". It's a reaction game: a target jumps around the screen, you click it as many times as you can before the clock runs out. Small, but it has everything a real game has: state (score, time, whether the game is on), input (clicks), a timer, and rules that decide what counts. You'll build it in two rounds.

Thinking like a game developer

Before writing code, list what the game needs to remember. That's its state:

VariableWhat it holdsStarts at
scoreHits so far0
timeLeftSeconds remaining10
playingIs a round running right now?false
timerThe ID of the running countdown, so it can be stoppednull

Every feature is then "when X happens, change the state, then update the screen to match". Click the target? Add 1 to score, show the new score, move the target. A second passes? Take 1 off timeLeft, show it, end the game at zero. Keeping the state in variables and drawing it onto the page is how pretty much every app works, from games to chat apps.

Moving things with position

To put the target anywhere inside the play area, use CSS positioning. The arena gets position: relative, and the target gets position: absolute. Now the target's left and top are measured from the arena's top-left corner:

#arena  { position: relative; height: 240px; }
#target { position: absolute; left: 0; top: 0; }

JavaScript can change those any time through the element's style:

target.style.left = '120px'
target.style.top = '40px'

For a random spot, pick a number between 0 and the arena's width minus the target's width (so it never hangs off the edge). clientWidth is an element's inner width in pixels and offsetWidth is its full width, border included.

const maxX = arena.clientWidth - target.offsetWidth
const x = Math.floor(Math.random() * maxX)

Round 1: a target that runs away

Challenge

Click it, score it, move it

  1. Finish moveTarget so it sets the target's style.left and style.top to random positions. Remember the 'px' on the end.
  2. In the click handler: add 1 to score, show it in scoreText, and call moveTarget().
  3. Press Run and try it.
Console
  1. Nothing logged yet.
  • Clicking the target adds 1 to the score on screen
  • The target jumps to a new spot when you click it
  • The target always stays inside the arena

Timers: setInterval and clearInterval

A game with no time limit is just clicking. JavaScript has two built-in timers:

  • setTimeout(fn, ms) runs fn once, after ms milliseconds.
  • setInterval(fn, ms) runs fn again and again, every ms milliseconds, until you stop it.

Both return an ID. Pass it to clearInterval (or clearTimeout) to stop the timer:

const timer = setInterval(function () {
  console.log('tick')
}, 1000)            // every 1000 ms = every second

clearInterval(timer) // stop ticking

Forgetting to stop an interval is a classic bug: start the game twice and you get two countdowns running at once, so time drains twice as fast. That's why the Start button below clears any old timer first.

Question

Quick check

Your game needs to take one second off the clock every second. Which do you use?
Pick an answer.

Round 2: the full game

Now add the rules. Clicks only count while playing is true. Start resets everything and starts the countdown. When time hits zero, the game ends.

Challenge

Beat the clock

The target code from round 1 is done. Fill in the three TODOs:

  1. Clicks only count while playing. At the top of the target's click handler, stop early if the game isn't running: if (!playing) return.
  2. Start a round. In the Start button's handler, reset score to 0 and timeLeft to GAME_SECONDS, show both, set playing to true, move the target, and start the countdown with timer = setInterval(tick, 1000).
  3. Count down. In tick, take 1 off timeLeft, show it, and call endGame() when it reaches 0.

Press Run, then Start. What's your best score?

Console
  1. Nothing logged yet.
  • Clicks before you press Start don't score
  • Start resets the score and clicks count while you play
  • After Start, the clock counts down once a second
  • When time runs out, the game stops at 0 and clicks stop scoring

How the pieces fit

Look at what you built, because the shape is worth remembering:

  • Guard clauses. if (!playing) return exits the click handler early when a click shouldn't count. Putting the "no" cases at the top keeps the rest of the function simple.
  • One place for each rule. The game only ends in endGame, so the cleanup (stop the timer, show the message) can't be forgotten in one path and done in another.
  • State first, screen second. Every handler changes the variables, then copies them onto the page with textContent. The page never holds the "real" score; your variables do.

That last one is the core idea behind tools like React: describe how the screen should look for a given state, and update the state.

When something goes wrong, console.log is your best friend. Drop console.log('tick', timeLeft) inside tick and watch the console: if the number drops by two each second, two timers are running. If nothing prints, the interval never started.

Question

Quick check

Why does the game need the playing variable at all?
Pick an answer.

Recap

  • A game is state (score, time, playing) plus rules that change it and code that draws it on screen.
  • position: absolute inside a position: relative parent lets you place things with left and top.
  • setInterval repeats a function on a timer; clearInterval stops it. Always stop old timers before starting new ones.
  • A simple flag like playing is how you make rules like "only count clicks during a round".

Finished this lesson?

Mark it complete to track your progress on this device.