I would like to know if there is a way of using poll() or get() without removing the events from the queue.
In my game, I check input at different places (not only in the main loop) and sometimes I need to check the same event at different places but when i check it once it removes it from the queue. I tried using peek() but the problem is that I can’t get the key corresponding to the event done.
while 1:
event = pygame.event.poll()
if event.type == KEYDOWN:
return event.key
else:
pass
#works but removes event from the queue
This can get the key corresponding to the event but with peek() it can’t:
pygame.event.peek(pygame.KEYDOWN).key
#dosent work
However I can’t use the first method because removes the event from the queue so I can’t check key events elsewhere in the program.
I don’t understand well how the queue works so maybe I’m just mistaking but I tried the first one at different location and only the first time i checked the event it worked.
My goal is to check events in different classes in my game.
Thanks for your help
I think a better design would be to check events in a single place – even if in a factored out function or method outside the mainloop code, and keep all the relevnt event data in other objetcts (as attributes) or variables.
For example, you can keep a reference to a Python set with all current pressed keys, current mouse position and button state, and pass these variables around to functions and methods.
Otherwise, if your need is to check only for keys pressed and mouse state (and pointer posistion) you may bypass events entirely (only keeping the calls to pygame.event.pump() on the mainloop). The
pygame.key.get_pressedfunction is my favorite way of reading the keyboard – it returns a sequence with as many positions as there are key codes, and each pressed key has its correspondent position set toTruein this vector. (The keycodes are available as constants in pygame.locals, like K_ESC, K_a, K_LEFT, and so on).Ex:
The mouse module (documented in http://www.pygame.org/docs/ref/mouse.html) allows you to get the mouse state without consuming events as well.
And finally, if you really want to get events, the possibility I see is to repost events to the Queue if they are not consumed, with a call to
pygame.event.post– this call could be placed, for example at theelseclause in an if/elif sequence where you check for some state in the event queue.