Win the game

This is the 12th step out of 16 of the Gamedev Phaser tutorial. Implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win.

How to win?

Add the following new code into your update() method:

js
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 alive, using the countAlive() method on this.bricks. If there are no more bricks left alive, 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.