简体   繁体   中英

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.


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.

This is likely because of the way you are handling the QUIT event in your event loop. 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. 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. Also you could try to add pygame.display.update() after the event handling to make sure it is updated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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