nerd0711
nerd0711

Reputation: 59

What happens in this code?

I have been trying to learn python. But don't quite understand the part where event syntax comes into play. Please explain what kind of value etc it takes and how can we compare it with integral values such as 0.

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

Upvotes: 1

Views: 172

Answers (1)

spirulence
spirulence

Reputation: 721

I think I have over-answered your question. pygame.event.get() returns a list object which has zero or more events in it. len() returns the number of items in that list - comparing it with 0 tells you something about the emptiness or otherwise of the list.

def checkForKeyPress():

    #if I retrieve at least one quit event since I last checked
    if len(pygame.event.get(QUIT)) > 0: 
        #quit the game
        terminate()

    #retrieve all the key release events since we last checked
    keyUpEvents = pygame.event.get(KEYUP) 

    #if there are no key release events
    if len(keyUpEvents) == 0: 
        #there was no key press, don't return anything
        #and skip the rest of the method
        return None 

    #if the user pressed the escape key
    if keyUpEvents[0].key == K_ESCAPE:
        #quit the game
        terminate()

    #if we haven't returned or quit already
    #return the first key released since we last checked
    return keyUpEvents[0].key

There are a few deeply troubling things about this code.

  1. This method doesn't have a single, clear purpose. It is in charge of quitting the game AND returning a key release.
  2. It's named improperly, as it's not really checking for presses (KEYDOWN) but releases (KEYUP).
  3. If you jam the keys quickly enough, some key events will get skipped. Only the first event is returned, but all of them are cleared from the queue.
  4. If this is the only checking done on the event queue, eventually the queue will take up all the available memory (given enough time and keystrokes).

I'm sure I could come up with a few more problems if I spent some more time analyzing it and also looking at where it came from. Please use this as a counter-example when processing events in your own game. There are much better and simpler examples of how to do this kind of event checking out there.

Upvotes: 3

Related Questions