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 toServeState, we are passing along paddle, bricks, health, and score throughstateMachine.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 inServeState, but not so much when we are inHighScoreState. -
On that note, take a look at
ServeState.js, which serves (😜) a very similar purpose to theServeStatefrom 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 thePlayState. -
In
globals.jsyou’ll notice we’ve added hearts to ourimagesobject. This is used in the newUserInterfaceclass 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.jsnow 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 inPlayState::update(), which simply decreases health and reverts toServeStatewhen 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 theTitleScreenState.