Creating a Brick Grid

The ball bounces off the walls and the paddle, but there is nothing in the game to break yet. In this section, we will create a grid of bricks and add them to the game loop so the ball can collide with them.

Defining the Brick Layout

We need a few constants to describe how the bricks are arranged. Add the following to src/main.js somewhere before the draw function:

const brickRowCount = 3;
const brickColumnCount = 5;
const bricks = [];
const brickWidth = 75;
const brickHeight = 20;
const brickPadding = 10;
const brickOffsetTop = 30;
const brickOffsetLeft = 30;

The padding is the gap between two bricks. The offsets move the whole grid away from the top-left corner of the canvas, so the bricks do not sit right against the edges.

Populating the Grid with Nested Loops

Right below those constants, use a pair of nested for loops to calculate each brick’s position and push a new Brick instance into the array:

for (let c = 0; c < brickColumnCount; c++) {
  for (let r = 0; r < brickRowCount; r++) {
    let brickX = c * (brickWidth + brickPadding) + brickOffsetLeft;
    let brickY = r * (brickHeight + brickPadding) + brickOffsetTop;
    bricks.push(new Brick(brickX, brickY, brickWidth, brickHeight, "#0095DD"));
  }
}

The outer loop goes over the columns and the inner loop goes over the rows. For each cell we compute brickX and brickY by multiplying the column or row index by the brick size plus the padding, then adding the offset. That puts the same amount of space between every pair of bricks.

Importing the Brick Class

Do not forget to import Brick at the top of src/main.js:

import Brick from "./model/brick.js";

Drawing and Colliding

Finally, add the following inside the draw function so each brick renders itself and checks for collisions with the ball:

bricks.forEach((brick) => {
  brick.draw(ctx);
  brick.collides(ball);
});

Save your code and observe the changes in the browser.

Checkpoint: Commit your progress.

git add .
git commit -m "brick-14: Create brick grid and integrate into game loop"
git push