Skip to main content
Engineering LibreTexts

7.14: The checkForKeyPress() Function

  • Page ID
  • def checkForKeyPress():
        if len(pygame.event.get(QUIT)) > 0:
        keyUpEvents = pygame.event.get(KEYUP)
        if len(keyUpEvents) == 0:
            return None
        if keyUpEvents[0].key == K_ESCAPE:
        return keyUpEvents[0].key

    This function first checks if there are any QUIT events in the event queue. The call to pygame.event.get() on line 2 [117] returns a list of all the QUIT events in the event queue (because we pass QUIT as an argument). If there are not QUIT events in the event queue, then the list that pygame.event.get() returns will be the empty list: [].

    The len() call on line 2 [117] will return 0 if pygame.event.get() returned an empty list. If there are more than zero items in the list returned by pygame.event.get() (and remember, any items in this list will only be QUIT events because we passed QUIT as the argument to pygame.event.get()), then the terminate() function gets called on line 3 [118] and the program terminates.

    After that, the call to pygame.event.get() gets a list of any KEYUP events in the event queue. If the key event is for the Esc key, then the program terminates in that case as well. Otherwise, the first key event object in the list that was returned by pygame.event.get() is returned from this checkForKeyPress() function.