Series entry
"Python3 Programming Actual Tetris Robot"
Design ideas
The game pause function is relatively simple. It mainly controls the value of the gameRunningStatus variable and the interface control. When the game is paused, the keyboard response will also stop. In addition, the change of the gameRunningStatus variable cannot be directly operated, and a pause command unit needs to be generated, sent to the queue, and processed by the work task thread.
Implementation
Interface control
The start button will switch between "Start", "Rause" and "Resume".
def btnStartClicked(self):
if self.game.getGameRunningStatus() == 0: # 点击时游戏处于未开始状态
self.btnStartVar.set("Pause")
self.game.start()
elif self.game.getGameRunningStatus() == 1: # 点击时游戏处于游戏中
self.btnStartVar.set("Resume")
self.game.pause()
elif self.game.getGameRunningStatus() == 5: # 点击时游戏处于暂停状态
self.btnStartVar.set("Pause")
self.game.resume()
self.gameCanvas.focus_set() # 设置游戏空间为当前活动控件
At the end of the game, restore the initial state
self.app.setStartButtonText("Start")
Pause operation
def pause(self):
opQueue.put(("pause",5))
Recovery operation
The game is paused, so directly modify the variable value, there is no design command unit.
def resume(self):
self.gameRunningStatus = 1
self.canvas.after(self.gameSpeedInterval * (0 if self.isAutoRunning else 1), self.tickoff)
Each task unit is a two-tuple (convenient for data deconstruction), the first is a string, which is a command; the second is a tuple, which is a data packet (also designed in a convenient way to deconstruct), by each Each command is self-defined.
Worker thread increase pause processing
...
elif cmd == "pause":
self.gameRunningStatus = data
...
Keyboard response transformation
def processKeyboardEvent(self, ke):
if self.game.getGameRunningStatus() == 1 and self.game.isAutoRunning == 0:
if ke.keysym == 'Left':
opQueue.put(('Left',()))
...
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) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。