Tetrix Example

The Tetrix example is a Qt version of the classic Tetrix game.


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(QWidget):

# public
    TetrixWindow(QWidget parent = None)
# private
    createLabel = QLabel(QString text)
    board = TetrixBoard()
    nextPieceLabel = QLabel()
    scoreLcd = QLCDNumber()
    levelLcd = QLCDNumber()
    linesLcd = QLCDNumber()
    startButton = QPushButton()
    quitButton = QPushButton()
    pauseButton = QPushButton()

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:

def __init__(self, parent):
    QWidget.__init__(self, parent)
    self.board = 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 = QLCDNumber(5)

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

startButton = QPushButton(tr("Start"))
quitButton = QPushButton(tr("Quit"))
pauseButton = 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 quit() slot.

connect(startButton, QPushButton.clicked, board, TetrixBoard.start)            connect(quitButton , QPushButton.clicked, qApp, QCoreApplication.quit)
    connect(pauseButton, QPushButton.clicked, board, TetrixBoard.pause)
#if __cplusplus >= 201402L
    connect(board, TetrixBoard::scoreChanged,
            scoreLcd, qOverload<int>(QLCDNumber.display))
    connect(board, TetrixBoard::levelChanged,
            levelLcd, qOverload<int>(QLCDNumber.display))
    connect(board, TetrixBoard::linesRemovedChanged,
            linesLcd, qOverload<int>(QLCDNumber.display))
    connect(board, TetrixBoard::scoreChanged,
            scoreLcd, QOverload<int>.of(QLCDNumber.display))
    connect(board, TetrixBoard::levelChanged,
            levelLcd, QOverload<int>.of(QLCDNumber.display))
    connect(board, TetrixBoard::linesRemovedChanged,
            linesLcd, QOverload<int>.of(QLCDNumber.display))

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:

layout = QGridLayout()
layout.addWidget(createLabel(tr("NEXT")), 0, 0)
layout.addWidget(nextPieceLabel, 1, 0)
layout.addWidget(createLabel(tr("LEVEL")), 2, 0)
layout.addWidget(levelLcd, 3, 0)
layout.addWidget(startButton, 4, 0)
layout.addWidget(board, 0, 1, 6, 1)
layout.addWidget(createLabel(tr("SCORE")), 0, 2)
layout.addWidget(scoreLcd, 1, 2)
layout.addWidget(createLabel(tr("LINES REMOVED")), 2, 2)
layout.addWidget(linesLcd, 3, 2)
layout.addWidget(quitButton, 4, 2)
layout.addWidget(pauseButton, 5, 2)
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:

TetrixWindow::createLabel = QLabel(QString text)

    label = QLabel(text)
    label.setAlignment(Qt.AlignHCenter | Qt.AlignBottom)
    return label

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); }
    def setRandomShape():
    def setShape(shape):
    TetrixShape shape() { return pieceShape; }
    int x(int index) { return coords[index][0]; }
    int y(int index) { return coords[index][1]; }
    minX = int()
    maxX = int()
    minY = int()
    maxY = int()
    rotatedLeft = TetrixPiece()
    rotatedRight = TetrixPiece()
# private
    def setX(index, x): coords[index][0] = x
    def setY(index, y): coords[index][1] = y
    pieceShape = TetrixShape()
    coords[4][2] = int()

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:

def setRandomShape(self):

    setShape(TetrixShape(QRandomGenerator.global().bounded(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:

def setShape(self, shape):

    staticexpr 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 i in range(0, 4 ):
        for j in range(0, 2):
            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:

def minX(self):

    min = coords[0][0]
    for i in range(1, 4):
        min = qMin(min, coords[i][0])
    return min

def maxX(self):        max = coords[0][0]
for i in range(1, 4):
    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:

def minY(self):

    min = coords[0][1]
    for i in range(1, 4):
        min = qMin(min, coords[i][1])
    return min

def maxY(self):        max = coords[0][1]
for i in range(1, 4):
    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:

def rotatedLeft(self):

    if (pieceShape == SquareShape)
        return self
    result = TetrixPiece()
    result.pieceShape = pieceShape
    for i in range(0, 4):
        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:

def rotatedRight(self):

    if (pieceShape == SquareShape)
        return self
    result = TetrixPiece()
    result.pieceShape = pieceShape
    for i in range(0, 4):
        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(QFrame):

# public
    TetrixBoard(QWidget parent = None)
    def setNextPieceLabel(label):
    sizeHint = QSize()
    minimumSizeHint = QSize()
slots: = public()
    def start():
    def pause():
    def scoreChanged(score):
    def levelChanged(level):
    def linesRemovedChanged(numLines):
    def paintEvent(event):
    def keyPressEvent(event):
    def timerEvent(event):

Apart from the setNextPieceLabel() function and the start() and pause() public slots, we only provide public functions to reimplement sizeHint() and 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; }
    def clearBoard():
    def dropDown():
    def oneLineDown():
    def pieceDropped(dropHeight):
    def removeFullLines():
    def newPiece():
    def showNextPiece():
    tryMove = bool(TetrixPiece newPiece, int newX, int newY)
    def drawSquare(painter, x, y, shape):
    timer = QBasicTimer()
nextPieceLabel = QPointer()
    isStarted = bool()
    isPaused = bool()
    isWaitingAfterLine = bool()
    curPiece = TetrixPiece()
    nextPiece = TetrixPiece()
    curX = int()
    curY = int()
    numLinesRemoved = int()
    numPiecesDropped = int()
    score = int()
    level = int()
    board[BoardWidth = TetrixShape()

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 StrongFocus for the focus policy, and initialize the game state:

def __init__(self, parent):
    QFrame.__init__(self, parent)
    self.isStarted = False
    self.isPaused = False

    setFrameStyle(QFrame.Panel | QFrame.Sunken)

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:

def setNextPieceLabel(self, 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:

def sizeHint(self):

    return QSize(BoardWidth * 15 + frameWidth() * 2,
                 * = BoardHeight() * 2)

def minimumSizeHint(self):        return QSize(BoardWidth * 5 + frameWidth() * 2,
             * = BoardHeight() * 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:

def start(self):

    if (isPaused)
    isStarted = True
    isWaitingAfterLine = False
    numLinesRemoved = 0
    numPiecesDropped = 0
    score = 0
    level = 1
    timer.start(timeoutTime(), self)

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:

def pause(self):

    if (not isStarted)
    isPaused = not isPaused
    if (isPaused) {
        timer.start(timeoutTime(), self)


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:

def paintEvent(self, event):

    painter = QPainter(self)
    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.

boardTop = rect.bottom() - BoardHeightsquareHeight()
for i in range(0, BoardHeight):
    for j in range(0, BoardWidth):
        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 i in range(0, 4):
        x = curX + curPiece.x(i)
        y = curY - curPiece.y(i)
        drawSquare(painter, rect.left() + x * squareWidth(),
                   boardTop + (BoardHeight - y - 1) * squareHeight(),

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

def keyPressEvent(self, event):

    if (not isStarted or isPaused or curPiece.shape() == NoShape) {

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()) {
Qt.Key_Left: = case()
    tryMove(curPiece, curX - 1, curY)
Qt.Key_Right: = case()
    tryMove(curPiece, curX + 1, curY)
Qt.Key_Down: = case()
    tryMove(curPiece.rotatedRight(), curX, curY)
Qt.Key_Up: = case()
    tryMove(curPiece.rotatedLeft(), curX, curY)
Qt.Key_Space: = case()
Qt.Key_D: = case()

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:

def timerEvent(self, event):

    if (event.timerId() == timer.timerId()) {
        if (isWaitingAfterLine) {
            isWaitingAfterLine = False
            timer.start(timeoutTime(), self)


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:

def clearBoard(self):

    for i in range(0, BoardHeight * BoardWidth):
        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:

def dropDown(self):

    dropHeight = 0
    newY = curY
    while (newY > 0) {
        if (not tryMove(curPiece, curX, newY - 1))
        newY = newY - 1
        dropHeight = dropHeight + 1


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:

def oneLineDown(self):

    if (not tryMove(curPiece, curX, curY - 1))

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:

def pieceDropped(self, dropHeight):

    for i in range(0, 4):
        x = curX + curPiece.x(i)
        y = curY - curPiece.y(i)
        shapeAt(x, y) = curPiece.shape()

    numPiecesDropped = numPiecesDropped + 1
    if (numPiecesDropped % 25 == 0) {
        level = level + 1
        timer.start(timeoutTime(), self)

    score += dropHeight + 7
    if (not isWaitingAfterLine)

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.

def removeFullLines(self):

    numFullLines = 0
    for i in range(-1, BoardHeight - 1, -1):
        lineIsFull = True()
        for j in range(0, BoardWidth):
            if (shapeAt(j, i) == NoShape) {
                lineIsFull = False

        if (lineIsFull) {        numFullLines = numFullLines + 1
for k in range(i, BoardHeight - 1):
    for j in range(0, BoardWidth):
        shapeAt(j, k) = shapeAt(j, k + 1)        for j in range(0, BoardWidth):
    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
    timer.start(500, self)
    isWaitingAfterLine = True

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:

def newPiece(self):

    curPiece = nextPiece
    curX = BoardWidth / 2 + 1
    curY = BoardHeight - 1 + curPiece.minY()
    if (not tryMove(curPiece, curX, curY)) {
        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:

def showNextPiece(self):

    if (not nextPieceLabel)
    dx = nextPiece.maxX() - nextPiece.minX() + 1
    dy = nextPiece.maxY() - nextPiece.minY() + 1
    pixmap = QPixmap(dx * squareWidth(), dy * squareHeight())
    painter = QPainter(pixmap)
    painter.fillRect(pixmap.rect(), nextPieceLabel.palette().window())
    for i in range(0, 4):
        x = nextPiece.x(i) - nextPiece.minX()
        y = nextPiece.y(i) - nextPiece.minY()
        drawSquare(painter, x * squareWidth(), y * squareHeight(),


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:

def tryMove(self, TetrixPiece newPiece, int newX, int newY):

    for i in range(0, 4):
        x = newX + newPiece.x(i)
        y = newY - newPiece.y(i)
        if (x < 0 or x >= BoardWidth or y < 0 or 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
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:

def drawSquare(self, painter, x, y, shape):

    staticexpr QRgb colorTable[8] = {
        0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
        0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00

    color = colorTable[int(shape)]
    painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2,
    painter.drawLine(x, y + squareHeight() - 1, x, y)
    painter.drawLine(x, y, x + squareWidth() - 1, y)
    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.

Example project @ code.qt.io