Reputation: 59
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
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.
KEYDOWN
) but releases (KEYUP
).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