python - 如何在pygame中使用time.sleep?

标签 python time pygame

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

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

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

最佳答案

更新于 2019 年 3 月 18 日

在 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'

免责声明:

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

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

关于python - 如何在pygame中使用time.sleep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932722/

相关文章:

python - 如何避免在类似蠕虫的游戏中每帧复制水平面?

python - 大型数据集上的ElasticSearch聚合

swift - 获取当前时间作为字符串 swift 3.0

python - 关闭 Pygame 窗口

python - fps - 如何将计数除以时间函数以确定 fps

c - 如何从 struct tm 中生成人类可读的字符串?

python - pygame 中的碰撞检测无法正常工作

python - 得到两个列表之间的区别?

python - 使用 python 和 PIL 模块导入 PPM 图像

python - 如何在 macOS 上使用 speech_recognition 模块修复 "OSError: [Errno -9986] Internal PortAudio error"?