Step 13
Let's try to implement "game over" in our game.
We will adjust the behavior of the ball so it bounces 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 add this declaration before the class declaration:
const gameOver = new CustomEvent("gameover");
Update the Ball.bounce
method to dispatch the gameOver
event when the ball hits the bottom side of the canvas:
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) {
// dispatch Game Over signal!
document.dispatchEvent(gameOver);
}
}
Open script.js
and add an event listener for the custom "game over" event we have created earlier!
document.addEventListener("gameover", (e) => {
window.alert("Game Over!");
});
We can also stop the animation by clearing the setInterval
function. For that, you need to store the interval ID retuned by the setInterval
function first:
const interval = setInterval(draw, 10);
Then update the event listener for gameover
:
document.addEventListener("gameover", (_e) => {
clearInterval(interval);
window.alert("Game Over!");
});
Save your code again and try it in your browser.