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

zhoutk
2.6k 声望1.2k 粉丝

自由程序员,技术路线c,delphi,c++,c#,java,php,node.js,python,golang,typescript;超喜欢react.js的设计思路,全栈开发成为我的终极目标。开发机器macbook pro,或装ubuntu、fedora的机器,编程用vim...