Game Lab: Learn JavaScript by Building a Game

This is not just a game to play β€” it is a practice project. The same ideas from our lessons (variables, objects, loops, events, and if logic) power every web game. Play first, then read the code, then change it yourself.

What you practice here

Variables & objects

player, bug, and score store game state β€” like Lesson 1 and Lesson 9.

Lesson 1 β†’

Events

keydown and button clicks move the player β€” same idea as Lesson 11.

Lesson 11 β†’

Game loop

requestAnimationFrame repeats update + draw ~60 times per second β€” a loop in action (Lesson 5).

Lesson 5 β†’

Conditions

Collision uses if to detect a catch and add points β€” Lesson 4 logic.

Lesson 4 β†’

Canvas drawing

getContext("2d") draws shapes on screen β€” also used in Chart.js (Lesson 18).

Lesson 18 β†’

Mini project

Combine everything into one small app β€” the goal of Lesson 12.

Lesson 12 β†’

Step 1 β€” Play the demo

See the result of real JavaScript code running in your browser.

Loading game…

Score: 0

Step 2 β€” Read the code that makes it work

Open game.js on this site. These are the main ideas:

1. Store data with variables and objects

const player = { x: 40, y: 180, size: 22, speed: 5 };
const bug = { x: 620, y: 150, size: 16 };
let score = 0;

Position, size, and speed are data. Objects group related values β€” like a game character profile.

2. Listen for keyboard and button events

window.addEventListener("keydown", (e) => {
  if (e.key === "ArrowUp") keys.ArrowUp = true;
});

When the user presses a key, JavaScript runs your function. Same pattern as a click counter.

3. Repeat with a game loop

function loop() {
  update();   // move player, check collision
  draw();     // paint canvas
  requestAnimationFrame(loop);
}
loop();

Instead of for, games use a loop that runs every frame. Each frame: update logic, then redraw.

4. Use if for collision and scoring

if (distance < player.size + bug.size) {
  score += 1;
  scoreEl.textContent = String(score);
  respawnBug();
}

When the player touches the bug, the score goes up and the bug moves to a new random place.

Step 3 β€” Change the code yourself

Try these coding tasks after you finish Lessons 1–12:

  • Change player.speed from 5 to 10 β€” what happens?
  • Change the player color #f7df1e to another hex color.
  • Make the bug bigger by increasing bug.size.
  • Add console.log(score) inside the collision if to debug in DevTools.

Open Playground Back to Lessons Read: Click Counter Project