This Pygame project implements the essential parts of Tetris: seven tetromino shapes, rotation states, grid collision, falling pieces, line removal, scoring, increasing speed, and keyboard controls.
Install Pygame:
1 | python -m pip install pygame |
Board representation
Represent the fixed blocks as a matrix. None means empty; a color tuple means occupied:
1 | GRID_SIZE = 20 |
Tetromino definitions
Each rotation is a list of row and column offsets from a center point:
1 | SHAPES = { |
Collision and movement
1 | def occupied_cells(shape_name, rotation, center): |
To move, calculate the candidate cells first and accept the new center only if conflicts() returns false. Rotation follows the same rule and restores the previous rotation when blocked.
Lock a piece and remove full lines
1 | def lock_piece(cells, color): |
When downward movement is blocked, lock the current cells, clear full lines, update the score, and create the next random piece. The game ends if the new piece already conflicts at its spawn position.
Controls and timing
Handle K_LEFT, K_RIGHT, K_DOWN, and K_UP for movement and rotation. Space can repeatedly move the piece down for a hard drop. In the main loop, use pygame.time.Clock() and a time accumulator rather than a blocking delay so input and rendering remain responsive.
The original project used a custom font.ttf for Chinese labels. Either provide that file beside the script or use pygame.font.Font(None, size) for the default font.