pygame:如何显示图像直到按下键



我正在尝试在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')

这是我称之为/确定播放器是否丢失的地方(程序似乎都在屏幕上跳过。字样,因为我什至根本看不到图像(:

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((函数。

我感谢任何帮助。

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

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

在游戏中添加一个状态,该状态表明游戏是否正在运行,exploion发生或必须启动NE游戏。定义状态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()

相关内容

  • 没有找到相关文章

最新更新