# Tetrix Example

The object of the game is to stack pieces dropped from the top of the playing area so that they fill entire rows at the bottom of the playing area.

When a row is filled, all the blocks on that row are removed, the player earns a number of points, and the pieces above are moved down to occupy that row. If more than one row is filled, the blocks on each row are removed, and the player earns extra points.

The Left cursor key moves the current piece one space to the left, the Right cursor key moves it one space to the right, the Up cursor key rotates the piece counter-clockwise by 90 degrees, and the Down cursor key rotates the piece clockwise by 90 degrees.

To avoid waiting for a piece to fall to the bottom of the board, press D to immediately move the piece down by one row, or press the Space key to drop it as close to the bottom of the board as possible.

This example shows how a simple game can be created using only three classes:

• The TetrixWindow class is used to display the player's score, number of lives, and information about the next piece to appear.
• The TetrixBoard class contains the game logic, handles keyboard input, and displays the pieces on the playing area.
• The TetrixPiece class contains information about each piece.

In this approach, the TetrixBoard class is the most complex class, since it handles the game logic and rendering. One benefit of this is that the TetrixWindow and TetrixPiece classes are very simple and contain only a minimum of code.

## TetrixWindow Class Definition

The TetrixWindow class is used to display the game information and contains the playing area:

class TetrixWindow : public QWidget
{
Q_OBJECT

public:
TetrixWindow();

private:
QLabel *createLabel(const QString &text);

TetrixBoard *board;
QLabel *nextPieceLabel;
QLCDNumber *scoreLcd;
QLCDNumber *levelLcd;
QLCDNumber *linesLcd;
QPushButton *startButton;
QPushButton *quitButton;
QPushButton *pauseButton;
};

We use private member variables for the board, various display widgets, and buttons to allow the user to start a new game, pause the current game, and quit.

Although the window inherits QWidget, the constructor does not provide an argument to allow a parent widget to be specified. This is because the window will always be used as a top-level widget.

## TetrixWindow Class Implementation

The constructor sets up the user interface elements for the game:

TetrixWindow::TetrixWindow()
{
board = new TetrixBoard;

We begin by constructing a TetrixBoard instance for the playing area and a label that shows the next piece to be dropped into the playing area; the label is initially empty.

Three QLCDNumber objects are used to display the score, number of lives, and lines removed. These initially show default values, and will be filled in when a game begins:

scoreLcd = new QLCDNumber(5);
scoreLcd->setSegmentStyle(QLCDNumber::Filled);

Three buttons with shortcuts are constructed so that the user can start a new game, pause the current game, and quit the application:

startButton = new QPushButton(tr("&Start"));
startButton->setFocusPolicy(Qt::NoFocus);
quitButton = new QPushButton(tr("&Quit"));
quitButton->setFocusPolicy(Qt::NoFocus);
pauseButton = new QPushButton(tr("&Pause"));
pauseButton->setFocusPolicy(Qt::NoFocus);

These buttons are configured so that they never receive the keyboard focus; we want the keyboard focus to remain with the TetrixBoard instance so that it receives all the keyboard events. Nonetheless, the buttons will still respond to Alt key shortcuts.

We connect clicked() signals from the Start and Pause buttons to the board, and from the Quit button to the application's QCoreApplication::quit() slot.

connect(startButton, SIGNAL(clicked()), board, SLOT(start()));
connect(quitButton , SIGNAL(clicked()), qApp, SLOT(quit()));
connect(pauseButton, SIGNAL(clicked()), board, SLOT(pause()));
connect(board, SIGNAL(scoreChanged(int)), scoreLcd, SLOT(display(int)));
connect(board, SIGNAL(levelChanged(int)), levelLcd, SLOT(display(int)));
connect(board, SIGNAL(linesRemovedChanged(int)),
linesLcd, SLOT(display(int)));

Signals from the board are also connected to the LCD widgets for the purpose of updating the score, number of lives, and lines removed from the playing area.

We place the label, LCD widgets, and the board into a QGridLayout along with some labels that we create with the createLabel() convenience function:

QGridLayout *layout = new QGridLayout;
setLayout(layout);

setWindowTitle(tr("Tetrix"));
resize(550, 370);
}

Finally, we set the grid layout on the widget, give the window a title, and resize it to an appropriate size.

The createLabel() convenience function simply creates a new label on the heap, gives it an appropriate alignment, and returns it to the caller:

QLabel *TetrixWindow::createLabel(const QString &text)
{
QLabel *lbl = new QLabel(text);
lbl->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
return lbl;
}

Since each label will be used in the widget's layout, it will become a child of the TetrixWindow widget and, as a result, it will be deleted when the window is deleted.

## TetrixPiece Class Definition

The TetrixPiece class holds information about a piece in the game's playing area, including its shape, position, and the range of positions it can occupy on the board:

class TetrixPiece
{
public:
TetrixPiece() { setShape(NoShape); }

void setRandomShape();
void setShape(TetrixShape shape);

TetrixShape shape() const { return pieceShape; }
int x(int index) const { return coords[index][0]; }
int y(int index) const { return coords[index][1]; }
int minX() const;
int maxX() const;
int minY() const;
int maxY() const;
TetrixPiece rotatedLeft() const;
TetrixPiece rotatedRight() const;

private:
void setX(int index, int x) { coords[index][0] = x; }
void setY(int index, int y) { coords[index][1] = y; }

TetrixShape pieceShape;
int coords[4][2];
};

Each shape contains four blocks, and these are defined by the coords private member variable. Additionally, each piece has a high-level description that is stored internally in the pieceShape variable.

The constructor is written inline in the definition, and simply ensures that each piece is initially created with no shape. The shape() function simply returns the contents of the pieceShape variable, and the x() and y() functions return the x and y-coordinates of any given block in the shape.

## TetrixPiece Class Implementation

The setRandomShape() function is used to select a random shape for a piece:

void TetrixPiece::setRandomShape()
{
setShape(TetrixShape(qrand() % 7 + 1));
}

For convenience, it simply chooses a random shape from the TetrixShape enum and calls the setShape() function to perform the task of positioning the blocks.

The setShape() function uses a look-up table of pieces to associate each shape with an array of block positions:

void TetrixPiece::setShape(TetrixShape shape)
{
static const int coordsTable[8][4][2] = {
{ { 0, 0 },   { 0, 0 },   { 0, 0 },   { 0, 0 } },
{ { 0, -1 },  { 0, 0 },   { -1, 0 },  { -1, 1 } },
{ { 0, -1 },  { 0, 0 },   { 1, 0 },   { 1, 1 } },
{ { 0, -1 },  { 0, 0 },   { 0, 1 },   { 0, 2 } },
{ { -1, 0 },  { 0, 0 },   { 1, 0 },   { 0, 1 } },
{ { 0, 0 },   { 1, 0 },   { 0, 1 },   { 1, 1 } },
{ { -1, -1 }, { 0, -1 },  { 0, 0 },   { 0, 1 } },
{ { 1, -1 },  { 0, -1 },  { 0, 0 },   { 0, 1 } }
};

for (int i = 0; i < 4 ; i++) {
for (int j = 0; j < 2; ++j)
coords[i][j] = coordsTable[shape][i][j];
}
pieceShape = shape;
}

These positions are read from the table into the piece's own array of positions, and the piece's internal shape information is updated to use the new shape.

The x() and y() functions are implemented inline in the class definition, returning positions defined on a grid that extends horizontally and vertically with coordinates from -2 to 2. Although the predefined coordinates for each piece only vary horizontally from -1 to 1 and vertically from -1 to 2, each piece can be rotated by 90, 180, and 270 degrees.

The minX() and maxX() functions return the minimum and maximum horizontal coordinates occupied by the blocks that make up the piece:

int TetrixPiece::minX() const
{
int min = coords[0][0];
for (int i = 1; i < 4; ++i)
min = qMin(min, coords[i][0]);
return min;
}

int TetrixPiece::maxX() const
{
int max = coords[0][0];
for (int i = 1; i < 4; ++i)
max = qMax(max, coords[i][0]);
return max;
}

Similarly, the minY() and maxY() functions return the minimum and maximum vertical coordinates occupied by the blocks:

int TetrixPiece::minY() const
{
int min = coords[0][1];
for (int i = 1; i < 4; ++i)
min = qMin(min, coords[i][1]);
return min;
}

int TetrixPiece::maxY() const
{
int max = coords[0][1];
for (int i = 1; i < 4; ++i)
max = qMax(max, coords[i][1]);
return max;
}

The rotatedLeft() function returns a new piece with the same shape as an existing piece, but rotated counter-clockwise by 90 degrees:

TetrixPiece TetrixPiece::rotatedLeft() const
{
if (pieceShape == SquareShape)
return *this;

TetrixPiece result;
result.pieceShape = pieceShape;
for (int i = 0; i < 4; ++i) {
result.setX(i, y(i));
result.setY(i, -x(i));
}

Similarly, the rotatedRight() function returns a new piece with the same shape as an existing piece, but rotated clockwise by 90 degrees:

TetrixPiece TetrixPiece::rotatedRight() const
{
if (pieceShape == SquareShape)
return *this;

TetrixPiece result;
result.pieceShape = pieceShape;
for (int i = 0; i < 4; ++i) {
result.setX(i, -y(i));
result.setY(i, x(i));
}

These last two functions enable each piece to create rotated copies of itself.

## TetrixBoard Class Definition

The TetrixBoard class inherits from QFrame and contains the game logic and display features:

class TetrixBoard : public QFrame
{
Q_OBJECT

public:
TetrixBoard(QWidget *parent = 0);

void setNextPieceLabel(QLabel *label);
QSize sizeHint() const Q_DECL_OVERRIDE;
QSize minimumSizeHint() const Q_DECL_OVERRIDE;

public slots:
void start();
void pause();

signals:
void scoreChanged(int score);
void levelChanged(int level);
void linesRemovedChanged(int numLines);

protected:
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE;
void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE;

Apart from the setNextPieceLabel() function and the start() and pause() public slots, we only provide public functions to reimplement QWidget::sizeHint() and QWidget::minimumSizeHint(). The signals are used to communicate changes to the player's information to the TetrixWindow instance.

The rest of the functionality is provided by reimplementations of protected event handlers and private functions:

private:
enum { BoardWidth = 10, BoardHeight = 22 };

TetrixShape &shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }
int timeoutTime() { return 1000 / (1 + level); }
int squareWidth() { return contentsRect().width() / BoardWidth; }
int squareHeight() { return contentsRect().height() / BoardHeight; }
void clearBoard();
void dropDown();
void oneLineDown();
void pieceDropped(int dropHeight);
void removeFullLines();
void newPiece();
void showNextPiece();
bool tryMove(const TetrixPiece &newPiece, int newX, int newY);
void drawSquare(QPainter &painter, int x, int y, TetrixShape shape);

QBasicTimer timer;
QPointer<QLabel> nextPieceLabel;
bool isStarted;
bool isPaused;
bool isWaitingAfterLine;
TetrixPiece curPiece;
TetrixPiece nextPiece;
int curX;
int curY;
int numLinesRemoved;
int numPiecesDropped;
int score;
int level;
TetrixShape board[BoardWidth * BoardHeight];
};

The board is composed of a fixed-size array whose elements correspond to spaces for individual blocks. Each element in the array contains a TetrixShape value corresponding to the type of shape that occupies that element.

Each shape on the board will occupy four elements in the array, and these will all contain the enum value that corresponds to the type of the shape.

We use a QBasicTimer to control the rate at which pieces fall toward the bottom of the playing area. This allows us to provide an implementation of timerEvent() that we can use to update the widget.

## TetrixBoard Class Implementation

In the constructor, we customize the frame style of the widget, ensure that keyboard input will be received by the widget by using Qt::StrongFocus for the focus policy, and initialize the game state:

TetrixBoard::TetrixBoard(QWidget *parent)
: QFrame(parent)
{
setFrameStyle(QFrame::Panel | QFrame::Sunken);
setFocusPolicy(Qt::StrongFocus);
isStarted = false;
isPaused = false;
clearBoard();

nextPiece.setRandomShape();
}

The first (next) piece is also set up with a random shape.

The setNextPieceLabel() function is used to pass in an externally-constructed label to the board, so that it can be shown alongside the playing area:

void TetrixBoard::setNextPieceLabel(QLabel *label)
{
nextPieceLabel = label;
}

We provide a reasonable size hint and minimum size hint for the board, based on the size of the space for each block in the playing area:

QSize TetrixBoard::sizeHint() const
{
return QSize(BoardWidth * 15 + frameWidth() * 2,
BoardHeight * 15 + frameWidth() * 2);
}

QSize TetrixBoard::minimumSizeHint() const
{
return QSize(BoardWidth * 5 + frameWidth() * 2,
BoardHeight * 5 + frameWidth() * 2);
}

By using a minimum size hint, we indicate to the layout in the parent widget that the board should not shrink below a minimum size.

A new game is started when the start() slot is called. This resets the game's state, the player's score and level, and the contents of the board:

void TetrixBoard::start()
{
if (isPaused)
return;

isStarted = true;
isWaitingAfterLine = false;
numLinesRemoved = 0;
numPiecesDropped = 0;
score = 0;
level = 1;
clearBoard();

emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);
emit levelChanged(level);

newPiece();
timer.start(timeoutTime(), this);
}

We also emit signals to inform other components of these changes before creating a new piece that is ready to be dropped into the playing area. We start the timer that determines how often the piece drops down one row on the board.

The pause() slot is used to temporarily stop the current game by stopping the internal timer:

void TetrixBoard::pause()
{
if (!isStarted)
return;

isPaused = !isPaused;
if (isPaused) {
timer.stop();
} else {
timer.start(timeoutTime(), this);
}
update();
}

We perform checks to ensure that the game can only be paused if it is already running and not already paused.

The paintEvent() function is straightforward to implement. We begin by calling the base class's implementation of paintEvent() before constructing a QPainter for use on the board:

void TetrixBoard::paintEvent(QPaintEvent *event)
{
QFrame::paintEvent(event);

QPainter painter(this);
QRect rect = contentsRect();

Since the board is a subclass of QFrame, we obtain a QRect that covers the area inside the frame decoration before drawing our own content.

If the game is paused, we want to hide the existing state of the board and show some text. We achieve this by painting text onto the widget and returning early from the function. The rest of the painting is performed after this point.

The position of the top of the board is found by subtracting the total height of each space on the board from the bottom of the frame's internal rectangle. For each space on the board that is occupied by a piece, we call the drawSquare() function to draw a block at that position.

int boardTop = rect.bottom() - BoardHeight*squareHeight();

for (int i = 0; i < BoardHeight; ++i) {
for (int j = 0; j < BoardWidth; ++j) {
TetrixShape shape = shapeAt(j, BoardHeight - i - 1);
if (shape != NoShape)
drawSquare(painter, rect.left() + j * squareWidth(),
boardTop + i * squareHeight(), shape);
}
}

Spaces that are not occupied by blocks are left blank.

Unlike the existing pieces on the board, the current piece is drawn block-by-block at its current position:

if (curPiece.shape() != NoShape) {
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY - curPiece.y(i);
drawSquare(painter, rect.left() + x * squareWidth(),
boardTop + (BoardHeight - y - 1) * squareHeight(),
curPiece.shape());
}
}
}

The keyPressEvent() handler is called whenever the player presses a key while the TetrixBoard widget has the keyboard focus.

void TetrixBoard::keyPressEvent(QKeyEvent *event)
{
if (!isStarted || isPaused || curPiece.shape() == NoShape) {
QFrame::keyPressEvent(event);
return;
}

If there is no current game, the game is running but paused, or if there is no current shape to control, we simply pass on the event to the base class.

We check whether the event is about any of the keys that the player uses to control the current piece and, if so, we call the relevant function to handle the input:

switch (event->key()) {
case Qt::Key_Left:
tryMove(curPiece, curX - 1, curY);
break;
case Qt::Key_Right:
tryMove(curPiece, curX + 1, curY);
break;
case Qt::Key_Down:
tryMove(curPiece.rotatedRight(), curX, curY);
break;
case Qt::Key_Up:
tryMove(curPiece.rotatedLeft(), curX, curY);
break;
case Qt::Key_Space:
dropDown();
break;
case Qt::Key_D:
oneLineDown();
break;
default:
QFrame::keyPressEvent(event);
}

In the case where the player presses a key that we are not interested in, we again pass on the event to the base class's implementation of keyPressEvent().

The timerEvent() handler is called every time the class's QBasicTimer instance times out. We need to check that the event we receive corresponds to our timer. If it does, we can update the board:

void TetrixBoard::timerEvent(QTimerEvent *event)
{
if (event->timerId() == timer.timerId()) {
if (isWaitingAfterLine) {
isWaitingAfterLine = false;
newPiece();
timer.start(timeoutTime(), this);
} else {
oneLineDown();
}
} else {
QFrame::timerEvent(event);
}
}

If a row (or line) has just been filled, we create a new piece and reset the timer; otherwise we move the current piece down by one row. We let the base class handle other timer events that we receive.

The clearBoard() function simply fills the board with the TetrixShape::NoShape value:

void TetrixBoard::clearBoard()
{
for (int i = 0; i < BoardHeight * BoardWidth; ++i)
board[i] = NoShape;
}

The dropDown() function moves the current piece down as far as possible on the board, either until it is touching the bottom of the playing area or it is stacked on top of another piece:

void TetrixBoard::dropDown()
{
int dropHeight = 0;
int newY = curY;
while (newY > 0) {
if (!tryMove(curPiece, curX, newY - 1))
break;
--newY;
++dropHeight;
}
pieceDropped(dropHeight);
}

The number of rows the piece has dropped is recorded and passed to the pieceDropped() function so that the player's score can be updated.

The oneLineDown() function is used to move the current piece down by one row (line), either when the user presses the D key or when the piece is scheduled to move:

void TetrixBoard::oneLineDown()
{
if (!tryMove(curPiece, curX, curY - 1))
pieceDropped(0);
}

If the piece cannot drop down by one line, we call the pieceDropped() function with zero as the argument to indicate that it cannot fall any further, and that the player should receive no extra points for the fall.

The pieceDropped() function itself is responsible for awarding points to the player for positioning the current piece, checking for full rows on the board and, if no lines have been removed, creating a new piece to replace the current one:

void TetrixBoard::pieceDropped(int dropHeight)
{
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY - curPiece.y(i);
shapeAt(x, y) = curPiece.shape();
}

++numPiecesDropped;
if (numPiecesDropped % 25 == 0) {
++level;
timer.start(timeoutTime(), this);
emit levelChanged(level);
}

score += dropHeight + 7;
emit scoreChanged(score);
removeFullLines();

if (!isWaitingAfterLine)
newPiece();
}

We call removeFullLines() each time a piece has been dropped. This scans the board from bottom to top, looking for blank spaces on each row.

void TetrixBoard::removeFullLines()
{
int numFullLines = 0;

for (int i = BoardHeight - 1; i >= 0; --i) {
bool lineIsFull = true;

for (int j = 0; j < BoardWidth; ++j) {
if (shapeAt(j, i) == NoShape) {
lineIsFull = false;
break;
}
}

if (lineIsFull) {
++numFullLines;
for (int k = i; k < BoardHeight - 1; ++k) {
for (int j = 0; j < BoardWidth; ++j)
shapeAt(j, k) = shapeAt(j, k + 1);
}
for (int j = 0; j < BoardWidth; ++j)
shapeAt(j, BoardHeight - 1) = NoShape;
}
}

If a row contains no blank spaces, the rows above it are copied down by one row to compress the stack of pieces, the top row on the board is cleared, and the number of full lines found is incremented.

if (numFullLines > 0) {
numLinesRemoved += numFullLines;
score += 10 * numFullLines;
emit linesRemovedChanged(numLinesRemoved);
emit scoreChanged(score);

timer.start(500, this);
isWaitingAfterLine = true;
curPiece.setShape(NoShape);
update();
}
}

If some lines have been removed, the player's score and the total number of lines removed are updated. The linesRemoved() and scoreChanged() signals are emitted to send these new values to other widgets in the window.

Additionally, we set the timer to elapse after half a second, set the isWaitingAfterLine flag to indicate that lines have been removed, unset the piece's shape to ensure that it is not drawn, and update the widget. The next time that the timerEvent() handler is called, a new piece will be created and the game will continue.

The newPiece() function places the next available piece at the top of the board, and creates a new piece with a random shape:

void TetrixBoard::newPiece()
{
curPiece = nextPiece;
nextPiece.setRandomShape();
showNextPiece();
curX = BoardWidth / 2 + 1;
curY = BoardHeight - 1 + curPiece.minY();

if (!tryMove(curPiece, curX, curY)) {
curPiece.setShape(NoShape);
timer.stop();
isStarted = false;
}
}

We place a new piece in the middle of the board at the top. The game is over if the piece can't move, so we unset its shape to prevent it from being drawn, stop the timer, and unset the isStarted flag.

The showNextPiece() function updates the label that shows the next piece to be dropped:

void TetrixBoard::showNextPiece()
{
if (!nextPieceLabel)
return;

int dx = nextPiece.maxX() - nextPiece.minX() + 1;
int dy = nextPiece.maxY() - nextPiece.minY() + 1;

QPixmap pixmap(dx * squareWidth(), dy * squareHeight());
QPainter painter(&pixmap);
painter.fillRect(pixmap.rect(), nextPieceLabel->palette().background());

for (int i = 0; i < 4; ++i) {
int x = nextPiece.x(i) - nextPiece.minX();
int y = nextPiece.y(i) - nextPiece.minY();
drawSquare(painter, x * squareWidth(), y * squareHeight(),
nextPiece.shape());
}
nextPieceLabel->setPixmap(pixmap);
}

We draw the piece's component blocks onto a pixmap that is then set on the label.

The tryMove() function is used to determine whether a piece can be positioned at the specified coordinates:

bool TetrixBoard::tryMove(const TetrixPiece &newPiece, int newX, int newY)
{
for (int i = 0; i < 4; ++i) {
int x = newX + newPiece.x(i);
int y = newY - newPiece.y(i);
if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
return false;
if (shapeAt(x, y) != NoShape)
return false;
}

We examine the spaces on the board that the piece needs to occupy and, if they are already occupied by other pieces, we return false to indicate that the move has failed.

curPiece = newPiece;
curX = newX;
curY = newY;
update();
return true;
}

If the piece could be placed on the board at the desired location, we update the current piece and its position, update the widget, and return true to indicate success.

The drawSquare() function draws the blocks (normally squares) that make up each piece using different colors for pieces with different shapes:

void TetrixBoard::drawSquare(QPainter &painter, int x, int y, TetrixShape shape)
{
static const QRgb colorTable[8] = {
0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00
};

QColor color = colorTable[int(shape)];
painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2,
color);

painter.setPen(color.light());
painter.drawLine(x, y + squareHeight() - 1, x, y);
painter.drawLine(x, y, x + squareWidth() - 1, y);

painter.setPen(color.dark());
painter.drawLine(x + 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + squareHeight() - 1);
painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + 1);
}

We obtain the color to use from a look-up table that relates each shape to an RGB value, and use the painter provided to draw the block at the specified coordinates.

Files: