Pygame:如何显示图像,直到按下一个键

时间:2019-05-23 21:06:59

标签: python oop pygame game-development

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

我已经尝试过使用类似的方法,但是我不确定在while循环中放什么(我希望它等到有按键时):

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

如果我将time.sleep()放入while循环中,则整个程序似乎死机了,没有图像发白。

这是我将图片加载到Pygame:

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

在这里我称之为呼叫/确定玩家是否输了(程序似乎跳过了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()函数。

我将不胜感激。

2 个答案:

答案 0 :(得分:2)

我想到的最简单的解决方案是编写一个小的独立函数,该函数会延迟代码的执行。像这样:

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()

答案 1 :(得分:1)

向游戏添加状态,该状态指示游戏是否正在运行,爆炸发生或是否必须启动新游戏。定义状态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

在主循环中为游戏的每种状态实施一个单独的大小写。使用此解决方案,不需要任何“睡眠”:

例如

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()