Track the score and win
This is the 7th step out of 11 of the creating a Breakout game using pure JavaScript tutorial. In this article, we'll add a scoring system to our game. Having a score can make the game more interesting—you can try to beat your own high score, or your friend's. We also add a winning condition, which is if you happen to destroy all the bricks.
Adding score text to the game display
Add a new variable right after let lastTimestamp to store the score:
let score = 0;
Add a drawScore() function to draw the current score on the canvas:
function drawScore() {
ctx.font = "18px Arial";
ctx.fillStyle = "#0095dd";
ctx.textBaseline = "top";
ctx.textAlign = "left";
ctx.fillText(`Points: ${score}`, 5, 5);
}
The ctx.fillText() method takes the text to render and the x and y coordinates to draw it at. In our case, the score text will be blue, sized at 18 pixels, and use the Arial font. Setting textBaseline to "top" positions the top of the text at the given y coordinate.
Call drawScore() inside update(), after drawing the bricks:
function update(timestamp) {
// ...
for (const brick of bricks) {
brick.draw();
}
drawScore();
requestAnimationFrame(update);
}
Updating the score when bricks are destroyed
We will increase the number of points every time the ball hits a brick. Add score += 10; to the brick's existing onCollide() method, after removing the brick from the two arrays:
class Brick extends GameObject {
// ...
onCollide() {
bricks.splice(bricks.indexOf(this), 1);
colliders.splice(colliders.indexOf(this), 1);
score += 10;
}
}
That's it for now—reload your index.html and check that the score updates on every brick hit.
How to win?
Add the following new code into your update() function, after the drawScore() call:
if (bricks.length === 0) {
alert("You won the game, congratulations!");
location.reload();
return;
}
If there are no more bricks, then we display the winning message, restarting the game once the alert is dismissed.
Also update the while condition in moveBall() to stop moving the ball as soon as the last brick is destroyed:
function moveBall(dt) {
while (dt > 0 && bricks.length > 0) {
// ... existing movement and collision code ...
}
}
This prevents the ball from falling out of bounds during the remaining time in the frame after the player has already won.
Compare your code
Here's what you should have so far, running live. To view its source code, click the "Play" button.
Next steps
Both losing and winning are implemented, so the core gameplay of our game is finished. Now let's add something extra—we'll give the player three lives instead of one.