简体   繁体   English

Pygame window 没有正确关闭 clock.tick 在循环中

[英]Pygame window does not close properly when clock.tick in the loop

I'm working on a project and when I add the clock.tick to my main game loop, my pygame window doesnt close.我正在做一个项目,当我将 clock.tick 添加到我的主游戏循环时,我的 pygame window 没有关闭。


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

When I click the X, the screen freezes until I let go, but unless I click the X in a very specific time frame( I usually need to click it 20 times to close) it doesnt work.当我点击 X 时,屏幕冻结,直到我让 go,但除非我在非常特定的时间范围内点击 X(我通常需要点击它 20 次才能关闭)它不起作用。

This is likely because of the way you are handling the QUIT event in your event loop.这可能是因为您在事件循环中处理 QUIT 事件的方式。 The pygame.event.get() function returns all of the events that have occurred since the last time it was called, so if there is a delay in your loop, the QUIT event may not be handled until multiple events have accumulated. pygame.event.get() function 返回自上次调用以来发生的所有事件,因此如果循环中存在延迟,则可能不会处理 QUIT 事件,直到累积了多个事件。 To fix this, you should move the QUIT event handling code to the top of your event loop so that it is handled as soon as the event occurs.要解决此问题,您应该将 QUIT 事件处理代码移动到事件循环的顶部,以便在事件发生时立即处理它。 Also you could try to add pygame.display.update() after the event handling to make sure it is updated.您也可以尝试在事件处理后添加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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM