Variables & objects
player, bug, and score store game state β like Lesson 1 and Lesson 9.
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.
player, bug, and score store game state β like Lesson 1 and Lesson 9.
keydown and button clicks move the player β same idea as Lesson 11.
requestAnimationFrame repeats update + draw ~60 times per second β a loop in action (Lesson 5).
Collision uses if to detect a catch and add points β Lesson 4 logic.
getContext("2d") draws shapes on screen β also used in Chart.js (Lesson 18).
Combine everything into one small app β the goal of Lesson 12.
Lesson 12 βSee the result of real JavaScript code running in your browser.
Loading gameβ¦
Score: 0
Open game.js on this site. These are the main ideas:
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.
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.
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.
if for collision and scoringif (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.
Try these coding tasks after you finish Lessons 1β12:
player.speed from 5 to 10 β what happens?#f7df1e to another hex color.bug.size.console.log(score) inside the collision if to debug in DevTools.