Reputation: 703
I'm creating a game in pygame that requires waves of enemies being sent out consistently. My wave-sending code works perfectly when used just once by itself, but when I try to repeat it with set_timer(), nothing happens.
Necessary code:
def game():
WAVE_EVENT = USEREVENT + 1
pygame.time.set_timer(WAVE_EVENT, 1000)
and
for event in pygame.event.get():
if pygame.event.get(WAVE_EVENT):
wave1()
print 'Wave1 sent'
Result? Nothing at all. My player just sits there in the middle of the screen looking bored.
How would I make the set_timer event actuall work?
Upvotes: 0
Views: 463
Reputation: 104877
Your event loop code is incorrect. When you call pygame.event.get()
(with no argument), you'll get all events currently in the event queue, including the timer driven WAVE_EVENT
s. Your second call tries to get only the WAVE_EVENT
s, but since they've already been collected by the first call, there won't be any left in the queue.
Generally the way to deal with this is to check the type of each event as you iterate over them:
for event in pygame.event.get(): # gets all events, loops over them
if event.type == WAVE_EVENT:
wave1()
print 'Wave1 sent'
Often you'll also want to check for other event types (such as QUIT
events that are generated when the user tries to close your window). For simple code with a few different event types, you'll probably just use elif
statements, but for complicated stuff you might want to use a dictionary to map event types to handler functions.
An alternative solution would be to separately request each type of event you need to handle, and never request all event types:
if pygame.event.get(WAVE_EVENT):
wave1()
print 'Wave1 sent'
if pygame.event.get(pygame.event.QUIT):
# ...
for key_event in pygame.event.get(pygame.event.KEYDOWN):
# ...
This later form is good for separating out different parts of your code that consume different events, but it may cause problems if you're not requesting all of the event types that are being queued. You'll probably need to be using some of the filtering functions (e.g. pygame.event.set_allowed
) to make sure your event queue doesn't fill up with events you're not checking for.
Upvotes: 1