Skip to main content
Engineering LibreTexts

7.24: The checkForQuit() Function

  • Page ID
    14600
  • def checkForQuit():
        for event in pygame.event.get(QUIT): # get all the QUIT events
            terminate() # terminate if any QUIT events are present
        for event in pygame.event.get(KEYUP): # get all the KEYUP events
            if event.key == K_ESCAPE:
                terminate() # terminate if the KEYUP event was for the Esc key
            pygame.event.post(event) # put the other KEYUP event objects back
    

    The checkForQuit() function can be called to handle any events that will cause the program to terminate. This happens if there are any QUIT events in the event queue (this is handle by lines 2 [348] and 3 [349]), or if there is a KEYUP event of the Esc key. The player should be able to press the Esc key at any time to quit the program.

    Because the pygame.event.get() call on line 4 [350] pulls out all of the KEYUP events (including events for keys other than the Esc key), if the event is not for the Esc key, we want to put it back into the event queue by calling the pygame.event.post() function.