Track the score and win
This is the 8th step out of 12 of the creating a Breakout game using Phaser 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.
We will use a separate property for storing the score and Phaser's text() method to print it out onto the screen.
New properties
Add two new properties right after the previously defined ones:
class ExampleScene extends Phaser.Scene {
// ... previous property definitions ...
scoreText;
score = 0;
// ... rest of the class ...
}
Adding score text to the game display
Now add this line at the end of the create() method:
this.scoreText = this.add.text(5, 5, "Points: 0", {
font: "18px Arial",
color: "#0095dd",
});
The text() method can take four parameters:
- The x and y coordinates to draw the text at.
- The actual text that will be rendered.
- The font style to render the text with.
The last parameter looks very similar to CSS styling. In our case, the score text will be blue, sized at 18 pixels, and use the Arial font.
Updating the score when bricks are destroyed
We will increase the number of points every time the ball hits a brick and update the scoreText to display the current score. This can be done using the setText() method—add the two new lines seen below to the hitBrick() method:
class ExampleScene extends Phaser.Scene {
// ...
hitBrick(ball, brick) {
brick.destroy();
this.score += 10;
this.scoreText.setText(`Points: ${this.score}`);
}
}
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() method:
class ExampleScene extends Phaser.Scene {
// ...
update() {
// ...
if (this.bricks.countActive() === 0) {
alert("You won the game, congratulations!");
location.reload();
}
}
// ...
}
We count the number of bricks that are still active, using the countActive() method on this.bricks. If there are no more active bricks, then we display the winning message, restarting the game once the alert is dismissed.
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.