Leave without saving?

Your editor changes will be lost.

Breakout-4 implements the idea of “health” for the user, which is displayed on the screen as hearts.

Important Code

  • Notice that in TitleScreenState.js, when we transition to ServeState, we are passing along paddle, bricks, health, and score through stateMachine.change(). This design is cleaner since it allows us to remove unnecessary values from our files. For example, it makes sense to have a paddle and bricks when we are in ServeState, but not so much when we are in HighScoreState.

  • On that note, take a look at ServeState.js, which serves (😜) a very similar purpose to the ServeState from Pong. The code should look familiar, as all we’re doing here is providing a state in which the user can hit the enter key to transition to the PlayState.

  • In globals.js you’ll notice we’ve added hearts to our images object. This is used in the new UserInterface class for rendering the user’s health on the screen. It simply draws the corresponding number of full hearts followed by empty hearts per the user’s health.

    UserInterface.js
    let healthX = CANVAS_WIDTH - 130;
    const sprites = SpriteManager.generateHeartSprites();
    for (let i = 0; i < this.health; i++) {
    sprites[0].render(healthX, 12);
    healthX = healthX + 11;
    }
    for (let i = 0; i < 3 - this.health; i++) {
    sprites[1].render(healthX, 12);
    healthX = healthX + 11;
    }
  • PlayState.js now also takes care of keeping score, monitoring the user’s health, and transitioning to other States as needed. You should be able to find the health-tracking code in PlayState::update(), which simply decreases health and reverts to ServeState when the ball goes past the paddle beyond the bottom of the screen:

    PlayState.js
    if (this.ball.didFall()) {
    this.health--;
    sounds.hurt.play();
    if (this.health === 0) {
    stateMachine.change('game-over', {
    score: this.score,
    });
    } else {
    stateMachine.change('serve', {
    paddle: this.paddle,
    ball: this.ball,
    bricks: this.bricks,
    health: this.health,
    score: this.score,
    userInterface: this.userInterface,
    });
    }
    }
  • The score tracking can also be found in PlayState::update(), where we simply add 10 points to the score every time a ball/brick collision is detected.

  • GameOverState.js, which is unsurprisingly called when the user loses all health, simply renders a “Game Over” screen with the final score. When a user presses the enter key in this state, they’re taken back to the TitleScreenState.

Powered by WebContainers
Files
Preparing Environment