Project final - Mini game
Finalize the mini game and run scene, motion and collision flow.
Bring it all together
In the final lesson we complete the game. The scene, player, keyboard motion and collision detection are ready. Now we add a score. When the player touches the target the score goes up by one, the target moves to a random new spot and the score is shown on the page.
To display the score we select the #score element from HTML and update it with textContent. The target's new position is chosen randomly within the canvas bounds using Math.random().
Move the target at random
On collision we move the target to a random point inside the canvas. For x we use Math.random() * (canvas.width - target.width): this gives a number between 0 and the canvas width minus the target width. We do the same for y.
This way the target always stays inside the canvas and the player has to move to catch it again. The score grows by one with score++ on each collision.
Exercise Add the score and move the target
At the top of the file, after the ctx definition, add const scoreLabel = document.querySelector("#score");. After the target definition add let score = 0;. Then at the end of the update function, after the arrow key code, add an if (hits(player, target)) block with score++, scoreLabel.textContent = "Score: " + score, target.x = Math.random() * (canvas.width - target.width) and target.y = Math.random() * (canvas.height - target.height).
Show example solution
const scoreLabel = document.querySelector("#score");
let score = 0;
// add inside update:
if (hits(player, target)) {
score++;
scoreLabel.textContent = "Score: " + score;
target.x = Math.random() * (canvas.width - target.width);
target.y = Math.random() * (canvas.height - target.height);
}
Test yourself
-
What happens first in each frame of the game loop?
- The scene is cleared and redrawn
- The score is reset
- Keys are recorded
- The target is moved
Show answer
The scene is cleared and redrawn — Correct! Each frame starts with clearRect, then objects are drawn.
-
Show the score on the page
scoreLabel.textContent = ____;Show answer
scoreLabel.textContent = "Score: " + score; -
Match the project parts
- Scene
- Drawing surface
- Motion
- Position by keys
- Collision
- Box overlap
- Game loop
- Frame-by-frame refresh