有什么可以影响time.sleep()提前发生的事情吗?

时间:2019-05-17 08:10:12

标签: python pygame

我是初学者,正在学习pygame。我正在按照一个简单游戏的教程进行操作,但我无法弄清楚问题出在哪里。我有一个崩溃函数,并使用time.sleep()。但是睡眠时间更早,使整个代码变得毫无用处。

我正在Mac上工作,但我认为这不应该引起这种情况。

我试图将time.sleep()放到另一个函数中,然后在崩溃函数中使用该函数,但是效果不佳,我不确定time.sleep是否具有某种偏好。

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)
    pygame.display.update()
    time.sleep(2)
    game_loop()  

def crash():
    message_display('You Crashed')

前两个功能应该不是问题,但我只是为了确定而发布了它们。 因此,当游戏中的汽车撞车时,应该写一个大的“ You Crashed”,然后等待2秒钟,然后使用game_loop()函数重新启动游戏。但是它将停止游戏,等待2秒钟,然后写“ You Crashed”并立即重新启动游戏。

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为在用pygame.display.flip()pygame.display.update()更新屏幕表面之后,您必须处理事件(例如,调用pygame.event.get),才能使窗口有机会重新绘制自己。

这可能在Windows上有效,因为那里的窗口管理方式不同,但是仍然是“错误的”。

您必须遵守以下规则:

  • 永远不要致电time.sleep(除非您更了解)
  • 永远不要在主循环之外调用pygame.display.update()pygame.display.flip()(除非您更了解)
  • 从来没有一个以上的游戏循环(除非您更了解)
  • 您的游戏是循环运行的,因此要执行任何基于“时间”的操作(例如:打印2秒钟,在4秒钟内执行此操作,等等),您必须跟踪游戏中的时间状态(可能只是一个变量)
  • 不要从游戏循环中调用游戏循环
  • 基本了解游戏的工作方式,可以进入的状态,在状态之间的移动方式以及每种状态下发生的情况。

一个简单的例子,假设我们要创建一个小赛车游戏,这样我们就可以想到以下状态:

  • 标题屏幕
  • 实际的赛车游戏
  • 游戏在屏幕上

一个简单的实现,只需在主循环中包含一个变量state和一个大的if/else块:

if state == 'TITLE_SCREEN':
    ...render title screen...
    ...if the space bar was pressed set state = 'GAME'
elif state == 'GAME':
    ...render the player, obstacles, etc...
    ...if the player crashed, set state = 'GAMEOVER' and keep track of the current time, e.g. with `timer = pygame.Clock().get_ticks()`
elif state == 'GAMEOVER':
    ...render a game over message...
    ...if the space bar was pressed or `pygame.Clock().get_ticks() - timer > 2000` set state = 'GAME'        

类似问题:
Two display updates at the same time with a pygame.time.wait() function between
pygame.time.wait() makes the window freez
pygame - how to update HP bar slowly without time.sleep()

有关游戏状态的更多信息:
Pygame level/menu states

可能也很有趣:
Threading issue with Pygame