Step 15

Let's try to implement the conditions and handling of "game over" in our game.

We will adjust the ball's behavior to bounce off the three sides of the canvas but not the bottom edge. When the ball hits the bottom edge, we will end the game!

Open the Ball.js file and update the bounce function to return true when the ball is bounced and false when it fell through the bottom edge!

bounce(canvasWidth, canvasHeight) {
  if (this.x < 0 || this.x + this.width > canvasWidth) {
    // bounce off the left/right edges
    this.dx *= -1; // switch direction
  } 

  if (this.y < 0) {
    // bounce off the top edge
    this.dy *= -1; // switch direction
  } else if (this.y + this.height > canvasHeight) {
    // fall through the bottom edge!
    return false;
  }

  return true;
}

Let's update the main.js as follows:

+ let isGameOver = false;
  function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  
    ball.draw(ctx);
    ball.move();
-   ball.bounce(canvas.width, canvas.height);
+   isGameOver = !ball.bounce(canvas.width, canvas.height);

    paddle.draw(ctx);
    paddle.move(canvas.width);

    ball.colides(paddle);

-   window.requestAnimationFrame(draw);
+   if (!isGameOver) {
+     window.requestAnimationFrame(draw);
+   } else {
+     window.alert("Game over!");
+   }
  }

Save your code and observer the changes in the browser.