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:
| Variable | What it holds | Starts at |
|---|---|---|
score | Hits so far | 0 |
timeLeft | Seconds remaining | 10 |
playing | Is a round running right now? | false |
timer | The ID of the running countdown, so it can be stopped | null |
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
- Finish
moveTargetso it sets the target'sstyle.leftandstyle.topto random positions. Remember the'px'on the end. - In the click handler: add 1 to
score, show it inscoreText, and callmoveTarget(). - Press Run and try it.
- 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)runsfnonce, aftermsmilliseconds.setInterval(fn, ms)runsfnagain and again, everymsmilliseconds, 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.
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:
- 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. - Start a round. In the Start button's handler, reset
scoreto 0 andtimeLefttoGAME_SECONDS, show both, setplayingtotrue, move the target, and start the countdown withtimer = setInterval(tick, 1000). - Count down. In
tick, take 1 offtimeLeft, show it, and callendGame()when it reaches 0.
Press Run, then Start. What's your best score?
- 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) returnexits 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.
Recap
- A game is state (score, time, playing) plus rules that change it and code that draws it on screen.
position: absoluteinside aposition: relativeparent lets you place things withleftandtop.setIntervalrepeats a function on a timer;clearIntervalstops it. Always stop old timers before starting new ones.- A simple flag like
playingis how you make rules like "only count clicks during a round".
Finished this lesson?
Mark it complete to track your progress on this device.