Creating the Brick Class
Our game is about breaking bricks. The player has to destroy every brick on screen before the ball hits the bottom of the canvas. In this section, we will create a Brick class that extends Block and adds the ability to disappear on impact.
Extending Block with Visibility
Create a new file src/model/brick.js. A brick is a Block with one extra behavior: it can be hit and disappear. We track that with a visibility flag, a boolean property that controls whether the brick is drawn and whether it takes part in collisions.
import Block from "./block.js";
class Brick extends Block {
constructor(x, y, width, height, color) {
super(x, y, width, height, color);
this.visible = true;
}
draw(ctx) {
if (this.visible) {
super.draw(ctx);
}
}
collides(ball) {
if (this.visible && this.intersects(ball)) {
this.visible = false;
ball.collides(this); // causes the ball to bounce off
}
}
}
export default Brick;
The draw method checks this.visible before calling super.draw(ctx). Once a brick is hit, it stops being drawn. The collides method does the same check: if the brick is not visible, it ignores the ball. When a collision does happen, we set this.visible = false and call ball.collides(this), which makes the ball bounce off.
In the next section, we will add several bricks to the canvas in a grid layout.
Checkpoint: Commit your progress.
git add .
git commit -m "brick-13: Create Brick class with visibility toggling"
git push