我正在使用Pygame制作一款Snake游戏。一切都很有效,但下面是我游戏的结束。有一个声音效果,我把延迟放在声音播放完毕之前窗口没有关闭。这一切都运行良好,我刚刚在Game Over文本中添加了。出于某种原因,声音播放,游戏暂停,然后然后游戏结束在屏幕上快速闪烁。任何人都可以向我解释为什么这会出现故障吗?
我在Mac 10.6.8上使用Python 2.7。
if w.crashed or w.x<=0 or w.x >= width - 1 or w.y<=0 or w.y >= height -1:
gameover.play()
font = pygame.font.Font(None, 80)
end_game = font.render("Game Over!", True, (255, 0, 0), (0,0,0))
endRect = end_game.get_rect(centerx = width/2, centery = height / 2)
screen.blit(end_game, endRect)
pygame.time.delay(3500)
running = False
答案 0 :(得分:2)
在pygame.display.flip()
来电之后,您是否遗漏了display.update(rectangle=endRect)
或screen.blit()
?
答案 1 :(得分:0)
我认为你的问题出在running
varibale上。如果这结束你的主要while循环*,它结束程序,这将是你的问题。
* main while循环:
while running:
#everything that the program does goes here
大多数游戏都有一个,并且做任何事情都会影响它会破坏循环,因此会结束你程序中的所有内容。由于您在问题中显示的代码将位于该循环内,因此文本和声音将无法播放。
我知道python在找到延迟命令时暂停程序是有意义的,但它实际上并没有暂停程序。它只是暂停 pygame 。该程序将继续运行,将running
分配给false
,您的循环刚刚结束。字体将不会呈现,因为它在循环中,并且由于pygame暂停,声音将无法播放。它永远不会停顿,因为这将是在while循环中调用的事件,现在已关闭。
作为旁注,Pygame保持“冻结”窗口打开的原因是因为屏幕上每个其他图像和字体的变量保持不变,并且没有告知它关闭。
当然,如果running
变量不是我认为的那样,那么整个答案可能会浪费我们的时间。
一个有价值的问题:)
答案 2 :(得分:0)
pygame.display.flip() should be done before `pygame.time.delay(3500)`.
将您的代码更改为此
if w.crashed or w.x<=0 or w.x >= width - 1 or w.y<=0 or w.y >= height -1:
gameover.play()
font = pygame.font.Font(None, 80)
end_game = font.render("Game Over!", True, (255, 0, 0), (0,0,0))
endRect = end_game.get_rect(centerx = width/2, centery = height / 2)
screen.blit(end_game, endRect)
pygame.display.update()
pygame.time.delay(3500)
running = False