May 24, 2022

Programming a Tetris game in Python



Tetris is perhaps one of the most common games ever. On the first look it looks simple but it is demanding at the same time. To get a better understanding about games in general it is recommended to program the game from scratch.
In contrast to a simple hello world program in python, the game of tetris can be called an intermediate challenge. For a beginner the difficulty is higher than writing down only some lines of code. The reason is, that the Tetris game consists of many modules which can have bugs everywhere. A good way in handling the complexity is to use object oriented programming technique. That means, the program is divided into smaller classes which are created separately.
For the Tetris game the following classes make sense: Game, GUI, Piece, Board and Physics. If each class consists of 50 lines of code, the overall software will need 250 lines of code. A short look into exiting Tetris clones at github will show, that this estimation fits to the reality. How exactly each class is written depends on the individual choices of the programmer. In case of the python language, it makes sense to use the pygame library and creating the Pieces class can be simplified by using patterns which are stored in a list.
The perhaps most difficult part of the game is the collision detection algorithm. The piece should stay within the border and if it hits other pieces it is not allowed that they overlap. From a technical perspective, such a collision detection system can be realized by comparing the content of a piece with the background. If two fields have the same value, a collision is there.