【问题标题】:How to be sure that time.sleep() is called only after the previous command is fully executed? [duplicate]如何确保 time.sleep() 仅在前一个命令完全执行后才被调用? [复制]
【发布时间】:2021-08-09 14:20:09
【问题描述】:

我正在使用 pygame,我想在窗口关闭之前显示“游戏结束”消息。为此,我想像这样使用 time.sleep() 函数:

message('Game Over', red)
pygame.display.update()

time.sleep(3)

但是似乎 time.sleep() 延迟了 pygame.display.update() 的执行,基本上,消息出现在延迟之后而不是之前。如何确保仅在前一个函数完全执行后才调用 time.sleep()?提前谢谢你。

【问题讨论】:

  • pygame.display.update() 仅在代码末尾有效。 time.sleep() 将阻止屏幕更新,直到它完成运行

标签: python pygame delay


【解决方案1】:

一般来说,您希望避免在 pygame 或内部循环中使用 time.sleep()。一种解决方法是使用datetime 模块。

下面的代码将运行 doSomething(),一旦变量 GameOver 为真,等待 3 秒,然后在 3 秒后再次开始运行 doSomething(),同时更新屏幕,以便您可以绘制和运行 doOtherStuff(),同时3 秒过去了。

d = datetime.now()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    if not GameOver:
        d = datetime.now()
        # your main code will go here
        doSomething()
    
    # wait 3 seconds when GameOver is True
    if GameOver and (datetime.now() - d).total_seconds() >= 3:
        GameOver = False
        # you can put anything else you want to run at the end of the 3 seconds here
    
    # do other stuff even while waiting
    doOtherStuff()
    pygame.display.update()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多