The move(), rotate(), and isBlock() functions

The second section contains the logic to move or rotate the piece and determine its current location:

void Piece::move(int columnDelta, int rowDelta) {
column_ += columnDelta;
row_ += rowDelta;
}

void Piece::rotate() {
angle_ += 3;
angle_ %= 4;
}

bool Piece::isBlock(int column, int row) const {
static const char *Shapes[][4] = {
// I
{
" * "
" * "
" * "
" * ",
" "
"****"
" "
" ",
" * "
" * "
" * "
" * ",
" "
"****"
" "
" ",
},
// J
{
" * "
" * "
" ** "
" ",
" "
"* "
"*** "
" ",
" ** "
" * "
" * "
" ",
" "
" "
"*** "
" * ",
},
...
};
return Shapes[kind_][angle_][column + row * PieceSize] == '*';
}

int Piece::getColumn() const {
return column_;
}
int Piece::getRow() const {
return row_;
}

The move() function updates the values of the private column_ and row_ variables, which dictates the piece's location on the board. The rotate() function sets the value of the private angle_ variable to either 0, 1, 2, or 3 (which is why %= 4 is used).

Determination for which kind of piece is shown, its location, and rotation is performed in the isBlock() function. I omitted all but the first two elements of the Shapes multi-dimensional array to avoid cluttering up the file, but the remaining five piece kinds are present in the actual code. I will admit that this isn't the most elegant implementation, but it suits our purposes just fine.

The private kind_ and angle_ values are specified as dimensions in the Shapes array to pick the four corresponding char* elements. These four elements represent the four possible orientations of the piece. If the index of column + row * PieceSize in the string is an asterisk, the piece is present in the specified row and column. If you decide to work through one of the Tetris tutorials available on the web (or look at one of the many Tetris repositories on GitHub), you'll find that there are several different ways to calculate whether a cell is populated by a piece. I chose this method because it's easier to visualize the pieces.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset