首页 > 解决方案 > Pygame如何使用相同的键启用和禁用功能?

问题描述

在制作暂停菜单时,我注意到我无法使用相同的键暂停和继续游戏。

假设我想用转义键做到这一点。然后,如果我只是按下它,游戏将暂停几微秒,但会继续,因为pause()功能也用退出键结束。

我还注意到,如果我将用于结束 pause() 函数执行的键更改为与暂停游戏不同的键,一切都会正常工作,但我不希望这样。

那么我应该怎么做才能防止这种情况并能够一键暂停和继续游戏呢?

标签: pygameevent-handlingkey

解决方案


添加一个paused状态。实现依赖于状态的事件处理paused
用来pygame.time.get_ticks()测量时间。计算暂停模式应该结束的时间。设置paused = False时间到:

paused = False
pause_end_time = 0

while running:
    current_time = pygame.time.get_ticks()
    if current_time > pause_end_time:
        paused = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                paused = not paused
                pause_end_time = current_time + 3000 # pause for 3 seconds

        if not paused:
            # game event handling
            if event.type == pygame.KEYDOWN:
                # [...]

    # [...]

推荐阅读