Series entry
"Python3 Programming Actual Tetris Robot"
block class
Draw small squares on the screen, and move and clear the squares. According to the function characteristics of the tkinter library, select canvas.create_rectangle to draw the block, canvas.move to move the block, and canvas.delete to clear the block. The canvas operation function only uses the above three.
Design ideas
The function provided by the tkinter library is component-based, instead of drawing a graph, it generates a primitive object. You can get the "handle" of this primitive, then move it and delete it. Because the block class is designed to construct, locate and clear three methods, it is enough to complete our Tetris game.
Correlation constant
TETRISDIMENSION = 4 # Tetris方块维度
BLOCKSIDEWIDTH = 30 # 最小方块边长设定
HALFBLOCKWIDTH = BLOCKSIDEWIDTH // 2 # 最小方块边长一半
CANVASOFFSET = 4 # 绘制偏移量,与游戏边框的距离
TETRISCOLORS = ( # Tetris方块的颜色设定
"red",
"magenta",
"darkMagenta",
"gray",
"darkGreen",
"darkCyan",
"darkBlue"
)
Implementation
Constructor
def __init__(self, canvas, x, y, color = "red") -> None:
self.canvas = canvas # 所在画布,gameCanvas or nextCanvas
self.x = x # 横会标位置,游戏空间位置,x > 0 and x < 11
self.y = y # 纵会标位置,游戏空间位置,y > 0 and y < 21
self.obj = canvas.create_rectangle((x - 1) * \ # 绘制小正方形,并存储,供清除用
BLOCKSIDEWIDTH + CANVASOFFSET, (y - 1) * \ # 游戏坐标与空间坐标对应,起始点
BLOCKSIDEWIDTH + CANVASOFFSET, \
x * BLOCKSIDEWIDTH + CANVASOFFSET, \ # 结束点
y * BLOCKSIDEWIDTH + CANVASOFFSET, \
fill = color, outline = "yellow") # 填充颜色与边框颜色
Move function
def relocate(self, detaX, detaY): # 参数为移动距离差
self.canvas.move(self.obj, \ # 移动到新位置
detaX * BLOCKSIDEWIDTH, \
detaY * BLOCKSIDEWIDTH)
self.x += detaX # 存储新的位置坐标
self.y += detaY
Clear function
Tetris combines blocks, and the clearing on the screen is done by the block itself.
def clean(self):
self.canvas.delete(self.obj)
``
project address
https://gitee.com/zhoutk/ptetris
或
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 items
C++ version has been implemented, project address:
https://gitee.com/zhoutk/qtetris
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。