如何在 class 中创建一个暂停函数,然后在海龟游戏中使用它?

How can I create a Pause function inside a class and then use it inside turtle game?

我在 python 中使用乌龟图形制作贪吃蛇游戏。游戏运行良好。 然后,我想对其进行改进,并为其添加暂停功能。当我刚刚在游戏代码中编写暂停函数的代码行时,它起作用了,但我的目标是在 class 中创建暂停函数,并能够将其实例用于我的后续项目,而不仅仅是每次都重新编写整个功能。

由于贪吃蛇游戏的代码很长,我决定在一个简单的乌龟动画上尝试暂停功能,以便在我的贪吃蛇游戏中实现之前掌握它的窍门,但是将它写在 class 中是行不通的。工作。 这是我在代码中编写它的时候,它起作用了:

from turtle import Turtle, Screen

tim = Turtle()
screen = Screen()
is_paused = False

def toggle_pause():
    global is_paused
    if is_paused:
        is_paused = False
    else:
        is_paused = True

screen.listen()
screen.onkey(toggle_pause, "p")

while True:
    if not is_paused:
        tim.forward(12)
        tim.left(10)
    else:
        screen.update()

这是我在 class 中编写暂停函数的时候,但没有用。

class Pause:
    def __init__(self, is_paused):
        self.is_paused = is_paused

    def toggle_pause(self):
        if self.is_paused:
            is_paused = False
            return is_paused
        else:
            is_paused = True
            return is_paused
from turtle import Turtle, Screen
from pause import Pause

ps = Pause(False)
tim = Turtle()
screen = Screen()

screen.listen()
screen.onkeypress(ps.toggle_pause, "p")

pause = ps.toggle_pause()
while True:
    if not pause:
        tim.forward(12)
        tim.left(10)
    else:
        screen.update()

你能告诉我我做错了什么吗?谢谢

变量 pause 仅在 while 循环之外更新一次。您应该使用 class 变量 self.is_paused 来测试游戏状态。

您需要做两件事才能使用 class:

让暂停在您的游戏中发挥作用
  1. 更改 Pause class 的定义,以便在通过添加 [=] 调用其 toggle_pause() 方法时更新其 is_paused 属性15=] is_paused 变量名的前缀:

    class Pause:
        def __init__(self, is_paused):
            self.is_paused = is_paused
    
        def toggle_pause(self):
            self.is_paused = not self.is_paused
            return self.is_paused
    
  2. 更改主程序中while循环中检查暂停状态的方式:

    ...
    
    while True:
        if not ps.is_paused:
            tim.forward(12)
            tim.left(10)
        else:
            screen.update()