如何在pygame中使用time.sleep?

How to use time.sleep in pygame?

所以我正在尝试显示一张图片,等待 1 秒,然后再显示另一张图片。我正在制作一个匹配游戏,所以在我的代码中我试图说如果两个图像不匹配,我想将图像更改为仅预设的通用图像。所以我的代码看起来像这样:

if True:
    self.content = self.image
    time.sleep(1)
    self.content = Tile.cover

self.content 是显示内容的变量,self.image 是显示的图像,然后 Tile.cover 是覆盖另一个图像的通用图像。然而,每当我这样做时,代码都会跳过第一行,只是将图像设置为 Tile.cover,为什么?

更新于 18/03/2019

在Pygame中,你必须使用pygame.time.wait()而不是python的time.sleep()

耗时毫秒:

pygame.time.wait(1000)

不使用time.sleep的原因是它会阻塞pygame的事件循环,因此pygame将无法处理其他事件。




旧答案

以下是此答案的旧版本,已标记为已接受。它 已过时 并且很可能 不正确

你得到的行为是由于 time.sleep()

的方式

示例:

我希望您在控制台中尝试以下代码:

>>> import time
>>> 
>>> def foo():
        print "before sleep"
        time.sleep(1)
        print "after sleep"
>>> 
>>> # Now call foo()
>>> foo()

你观察到输出过程中发生了什么吗?

>>> # Output on calling foo()
... # Pause for 1 second
... 'before sleep'
... 'after sleep'

这也是您的代码所发生的情况。首先它休眠,然后同时将 self.content 更新为 self.imageTime.cover

修复:

要修复上面示例中的代码,您可以使用sys.stdout.flush()

>>> def foo():
        print "before sleep"
        sys.stdout.flush()
        time.sleep(1)
        sys.stdout.flush()
        print "after sleep"

>>> foo()
... 'before sleep'
... # pause for 1 second
... 'after sleep'

免责声明:

我还没有尝试过 sys.stdout.flush() 和 Pygame 所以我不能说它是否适合你,但你可以试试。

对于这个 SO 问题似乎有一个可行的解决方案:How to wait some time in pygame?