Series entry

Programming Tetris Robot in Python3

Tetris class

Combine Block class to achieve the drawing of Tetris, movement, rotation and other operations. This is the core business of the Tetris game. The first step is to realize the requirement of manual play, and in the future, when the AI plays automatically, this class will be transformed. In all of the logic, pay special attention to the rotate operation, as many of the bugs that were solved later turned out to be caused by an incomplete consideration of the rotate operation.

Design ideas

The Tetris class composes the Block class to draw the screen and decouples it from the Tkinter library. Because of the design of the Tkinter library, our interface uses two canvases to display the game space and the next square respectively, so it is possible for one square to be displayed on different canvases. When a square is placed, take the next square from the NextCanvas and place it at the top of the game space. I didn’t find an easy way to move a symbol across Canvas. My implementation method is to generate a square in the game space again, which is the same as that in NextCanvas. Since the initial shape of each square is fixed, I just made it rotate randomly several times. Therefore, I only need to query the shape and rotation times in Next Tetris to copy it.

The constant

GameRoom = [[0 for I in range(12)] for I in range(22)] # GameRoom Definition 10x20 TetRisahpes = (# GameRoom Definition (1, 1, 1, 1), # There are six shapes of the cube (0, 1, 1, 1, 0, 0, 1), # Other shapes can be obtained by several rotations (1, 1, 1, 0, 0, 1), # I define rotation as clockwise rotation (0, 1, 1, 0, 1, 1), (1, 1, 0, 0, 0, 1, 1), (0, 1, 1, 0, 1, 1), (0, 1, 0, 0, 1, 1), (0, 1, 0, 0, 1, 1) 1)) TetRisColors = (# Bind shape and color of block "red", "magenta", "darkMagenta", "gray", "darkGreen", "darkCyan", "darkBlue")

The specific implementation

The constructor

def __init__(self, canvas, x, y, shape): Self. canvas = canvas # The space drawn by the square self.objs = [] # Self. Color = TetRisColors [shape] self. Data = TetRisColors [# square shape data [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1] curShape = TetRisahpes [Shape % Len (TetRisahpes)] for I, b in enumerate(CurShape): Self.data [1 + I // TetRisDimension][I % TetRisDimension] = 1 self.objs. Append (Block(canvas,)) Self. X + I % self.y + 1 + I // self.color) self.y + 1 + I

Determine if there is a Block at any point in the game space

This function is very important, and is needed to determine if the bounds are out of bounds and if the block can move. The game space is larger than the real space, and the outermost data is initialized to 1 as a sentinel.

def hasBlock(self, x, y):
    if x < 1 or x > 10 or y > 20:
        return True
    if GameRoom[y][x] == 1:
        return True
    else:
        return False

Determine if a square (Tetris) can be placed

Movement, rotation, and whether the game is over all come into play

def canPlace(self, x, y):
    for i in range(TETRISDIMENSION):
        for j in range(TETRISDIMENSION):
            if self.data[i][j] and GameRoom[y + i][x + j]:
                return False
    return True

Remove squares

The cleanup is done by the composed Block class itself.

def clean(self):
    for block in self.objs:
        block.clean()
    self.objs.clear()

Square redraw

This position is used when the Block class is rotated because the relocate is implemented using tkinter.move and takes a relative distance as its argument. So the rotation redraw is a bit of a hassle, and I’ve done it in a relatively simple and crude way.

Def redraw(self): self.clean() # create new Tetris for j in range(tetrisDimension): If self. Data [I][j]: Self.objs. append(Block(self.canvas, self.x + j, self.y + I, self.color))

Content forecast

Move and rotate in the next post. Due to the problems of Tkinter and Timer, after the implementation of AI, I found that the program had a serious memory leak, which made me suffer for a long time. Please keep paying attention to the future, thank you!

The project address

https://gitee.com/zhoutk/ptetris or https://github.com/zhoutk/ptetris

Operation method

1. install python3, git
2. git clone https://gitee.com/zhoutk/ptetris (or download and unzip source code)
3. cd ptetris
4. python3 tetris

This project surpport windows, linux, macOs

on linux, you must install tkinter first, use this command:  
sudo apt install python3-tk

Related projects

C++ version has been implemented, project address:

https://gitee.com/zhoutk/qtetris