Pygame: 如何在按下某个键之前显示图像

Pygame: how to display an image until a key is pressed

我正在尝试在 Pygame 中构建一个游戏,如果玩家移动到红色方块上,则该玩家输了。发生这种情况时,我想显示一张爆炸图片,玩家在其中丢失,直到用户按下键盘上的任意键。当用户按下一个键时,我将调用函数 new_game() 来开始新游戏。问题是我的代码似乎跳过了我 blit 爆炸的那一行,而是立即开始一个新游戏。

我试过使用类似的东西,但我不确定在 while 循环中放什么(我希望它等到有按键):

while event != KEYDOWN:
   # Not sure what to put here

如果我将 time.sleep() 放在 while 循环中,整个程序似乎冻结并且没有图像被 blit。

这是我将图像加载到 Pygame:

explosionpic = pygame.image.load('C:/Users/rohan/Desktop/explosion.png')

如果玩家输了,我会在这里调用 it/determine(程序似乎跳过了 screen.blit 行,因为我根本看不到图像):

if get_color(p1.x + p1_velocity_x, p1.y + p1_velocity_y) == red:  # If player lands on a red box
    screen.blit(explosionpic, (p1.x, p1.y))
    # Bunch of other code goes here, like changing the score, etc.
    new_game()

它应该显示图像,然后当用户按下一个键时,调用 new_game() 函数。

如有任何帮助,我将不胜感激。

向游戏添加一个状态,指示游戏是运行、发生爆炸还是必须开始新的游戏。定义状态 RUNEXPLODENEWGAME。初始化状态game_state:

RUN = 1
EXPLODE = 2
NEWGAME = 3

game_state = RUN

如果发生爆炸,设置状态EXPLODE

if get_color(p1.x + p1_velocity_x, p1.y + p1_velocity_y) == red:  # If player lands on a red box
    game_state = EXPLODE

当一个键被按下后切换到状态NEWGAME:

if game_state == EXPLODE and event.type == pygame.KEYDOWN:
    game_state = NEWGAME

newgame()被执行时,则设置game_state = RUN:

newgame()
game_state = RUN

在主循环中为游戏的每个状态实现一个单独的案例。使用此解决方案不需要任何 "sleep":

例如

ENDGAME = 0
RUN = 1
EXPLODE = 2
NEWGAME = 3

game_state = RUN
while game_state != ENDGAME:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_state = ENDGAME

        if game_state == EXPLODE and event.type == pygame.KEYDOWN:
            game_state = NEWGAME


    if game_state == RUN:
        # [...]

        if get_color(p1.x + p1_velocity_x, p1.y + p1_velocity_y) == red:  # If player lands on a red box
            game_state = EXPLODE

        # [...]

    elif game_state == EXPLODE:
        screen.blit(explosionpic, (p1.x, p1.y))

    elif game_state == NEWGAME:
        newgame()
        game_state = RUN

    pygame.display.flip()

我想到的最简单的解决方案是编写一个小的独立函数来延迟代码的执行。类似于:

def wait_for_key_press():
    wait = True
    while wait:
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                wait = False
                break

此函数将暂停执行,直到 KEYDOWN 信号被事件系统捕获。

因此您的代码将是:

if get_color(p1.x + p1_velocity_x, p1.y + p1_velocity_y) == red:  # If player lands on a red box
    screen.blit(explosionpic, (p1.x, p1.y))
    pygame.display.update() #needed to show the effect of the blit
    # Bunch of other code goes here, like changing the score, etc.
    wait_for_key_press()
    new_game()