【问题标题】:Pygame window does not close properly when clock.tick in the loop当循环中的 clock.tick 时,Pygame 窗口无法正常关闭
【发布时间】:2023-01-25 23:34:14
【问题描述】:

我正在做一个项目,当我将 clock.tick 添加到我的主游戏循环时,我的 pygame 窗口没有关闭。


def game_loop():
    """The main game loop that runs as the game runs. Returns when the pygame window is closed."""
    global running
    global timer
    while running:
        while timer > screen.fixed_fps:
            fixed_update()
            timer -= screen.fixed_fps
        update()
        for event in pygame.event.get():  
            if event.type == pygame.QUIT:
                running = False
                return
        screen.clock.tick(screen.fps)
        timer += delta_time()
    pygame.quit()
    return

当我点击 X 时,屏幕会冻结,直到我松手,但除非我在非常特定的时间范围内点击 X(我通常需要点击它 20 次才能关闭)它不起作用。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    这可能是因为您在事件循环中处理 QUIT 事件的方式。 pygame.event.get() 函数返回自上次调用它以来发生的所有事件,因此如果您的循环中存在延迟,则可能不会处理 QUIT 事件,直到累积了多个事件。要解决此问题,您应该将 QUIT 事件处理代码移动到事件循环的顶部,以便在事件发生时立即处理它。您也可以尝试在事件处理后添加 pygame.display.update() 以确保它已更新。

        while running:
            for event in pygame.event.get():  
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                    return
            while timer > screen.fixed_fps:
                fixed_update()
                timer -= screen.fixed_fps
            update()
            screen.clock.tick(screen.fps)
            timer += delta_time()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多