The Board

In this lesson, we will discuss how classes encapsulate data and functions when we start coding the game.

We'll cover the following

Now that we have created a container for our game, it’s time to start coding the logic. First, we need the board to be able to draw the falling pieces and keep track of the game state.

The board and pieces are good candidates for a class. We can create a new Board when starting a new game and a new Piece every time a new piece enters the game.

Board class

Let’s start by creating a board.js file where we add a class Board. When we create a new instance of board, we connect it with the canvas context. So, let’s add it to the constructor:

class Board { 
  constructor(ctx) {
    this.ctx = ctx;    
  } 
}

By sending the canvas context to the board class, we can access it when needed. The this keyword allows us to set and access the properties inside a class.

An important difference between function declarations and class declarations is that the function declarations are hoisted and class declarations are not. Therefore, we need to declare the class before we can initialize objects with the new keyword:

let board = new Board(ctx);

Cells

In Tetris, the board consists of cells, which are either occupied or empty. Therefore, we can represent a cell with either Boolean values or by using numbers. The latter approach is better because we can represent an empty cell with 0 and the colors with numbers 1–7.

Next, we need to represent the game board’s rows and coloumns. We can use an array of numbers to represent a row and an array of rows to represent the board. In other words, we will use a two-dimensional (2D) array, or what we call a matrix.

Let’s add a method that returns an empty board with all cells set to zero. We can use the fill() array method that changes all array elements with a static value.

Get hands-on with 1400+ tech skills courses.