Series entry

Programming Tetris Robot in Python3

Block class

Draw small squares on the screen, and the movement and clearance of the blocks. According to the function characteristics of the Tkinter library, select Canvas. Create_Rectangle to draw the square, Canvas. Move the square, and Canvas. Delete to clear the square. The canvas manipulation function uses only the above three.

Design ideas

The functions provided by the Tkinter library are component-based, and instead of drawing a graph, they generate a meta-object. You can get a “handle” to this primitive, then move it around and delete it. Because the Block class is designed to be constructed, positioned, and cleared, it is sufficient to complete our Tetris game.

The constant

HalfblockWidth = blocksideWidth // 2 # TetrisDimension = 4 # TetrisDimension = 4 # BlocksideWidth = 30 # BlocksideWidth CanvasOffset = 4 TetRisColors = (# Tetris square color set to "Red "," Magenta", "DarkMagenta "," Gray ", "DarkGreen "," DarkCyan ", "DarkBlue")

The specific implementation

The constructor

def __init__(self, canvas, x, y, color = "red") -> None: Self. Canvas = Canvas #, Gamecanvas or NextCanvas self. X = X #, Gamecanvas, X BBB 0 0 and X < 11 self. Y = Y #, Y < 21 self.obj = Canvas. Create_Rectangle ((X-1) * \ #), Y < 21 self.obj = Canvas. Create_Rectangle ((X-1) * \ #), Y < 21 self.obj = Canvas. (y - 1) * \ # The game coordinate corresponds to the space coordinate. # y * blocksideWidth + CanvasOffset, # y * blocksideWidth + CanvasOffset, # y * blocksideWidth + CanvasOffset, # y * blocksideWidth + CanvasOffset, \ fill = color, outline = "yellow") # Fill color and border color

Mobile function

def relocate(self, detaX, detaY): Move (self.obj, \ # move to new position detaX * blocksideWidth, DetaY * blocksideWidth) self.x += detaX # store new position coordinates self.y += detaY

Remove function

In Tetris, blocks are combined, and the clearing on the screen is done by the block itself.

def clean(self):
    self.canvas.delete(self.obj)

` `

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