Build a Classic Tetris Game with PyQt5: Step‑by‑Step Tutorial
This tutorial walks you through creating a fully functional Tetris clone using Python's PyQt5 library, covering game logic, rendering, user controls, shape management, line clearing, and includes complete source code for all core classes and methods.
01 Tetris
Tetris is one of the most popular games in the world, originally created by Russian programmer Alexey Pajitnov in 1985. It belongs to the falling‑block puzzle genre and uses seven basic shapes—S, Z, T, L, reverse L, line, and square—each composed of four blocks.
The game board is a grid where blocks fall from the top; the player moves and rotates them to fill complete rows, which then disappear and increase the score. The game ends when a new shape cannot be placed because it reaches the top of the screen.
02 Development
We use PyQt5 to create the graphical interface and implement the game logic. The main components are four classes: Tetris, Board, Tetrominoe, and Shape. Tetris creates the window, Board handles the core gameplay, Tetrominoe defines the shape types, and Shape stores the coordinates of a piece.
Key steps before starting:
Use QtCore.QBasicTimer() to create a game loop.
The model continuously falls.
Movement is based on block units, not pixels.
Mathematically, the model is just a sequence of numbers.
The source code below implements all functionality.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
This is a Tetris game clone.
"""
from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication
from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal
from PyQt5.QtGui import QPainter, QColor
import sys, random
class Tetris(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.tboard = Board(self)
self.setCentralWidget(self.tboard)
self.statusbar = self.statusBar()
self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)
self.tboard.start()
self.resize(180, 380)
self.center()
self.setWindowTitle('Tetris')
self.show()
def center(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
class Board(QFrame):
msg2Statusbar = pyqtSignal(str)
BoardWidth = 10
BoardHeight = 22
Speed = 300
def __init__(self, parent):
super().__init__(parent)
self.initBoard()
def initBoard(self):
self.timer = QBasicTimer()
self.isWaitingAfterLine = False
self.curX = 0
self.curY = 0
self.numLinesRemoved = 0
self.board = []
self.setFocusPolicy(Qt.StrongFocus)
self.isStarted = False
self.isPaused = False
self.clearBoard()
# ... (remaining methods omitted for brevity) ...
if __name__ == '__main__':
app = QApplication([])
tetris = Tetris()
sys.exit(app.exec_())The game starts automatically after loading. Press P to pause, Space to drop the piece instantly, and use arrow keys to move or rotate. The speed is fixed; there is no acceleration feature. The score reflects the number of cleared lines.
Key methods explained: shapeAt(x, y) returns the shape at a board position. squareWidth() and squareHeight() compute the pixel size of each block based on the current board dimensions. pause() toggles the game pause state and updates the status bar. paintEvent(event) renders the board and the falling piece using QPainter. keyPressEvent(event) handles user input for moving, rotating, dropping, and accelerating the piece. tryMove(newPiece, newX, newY) attempts to move a piece, checking boundaries and collisions. timerEvent(event) drives the game loop, moving pieces down or creating a new piece after a line is cleared. clearBoard() initializes the board with empty shapes. removeFullLines() detects and removes completed rows, shifting above rows down. newPiece() creates a random new shape and starts it at the top center. rotateLeft() and rotateRight() rotate the current piece.
Supported shapes are defined in the Tetrominoe class (NoShape, ZShape, SShape, LineShape, TShape, SquareShape, LShape, MirroredLShape). The Shape class stores the coordinates for each shape and provides methods for rotation and coordinate access.
Below is a visual representation of the coordinate system used for the shapes:
Running the program displays a simple Tetris window where you can play the game using the described controls.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
