我是初学者,正在学习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”并立即重新启动游戏。
答案 0 :(得分:1)
之所以发生这种情况,是因为在用pygame.display.flip()
或pygame.display.update()
更新屏幕表面之后,您必须处理事件(例如,调用pygame.event.get
),才能使窗口有机会重新绘制自己。
这可能在Windows上有效,因为那里的窗口管理方式不同,但是仍然是“错误的”。
您必须遵守以下规则:
time.sleep
(除非您更了解)pygame.display.update()
或pygame.display.flip()
(除非您更了解)一个简单的例子,假设我们要创建一个小赛车游戏,这样我们就可以想到以下状态:
一个简单的实现,只需在主循环中包含一个变量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