问题
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
回答1:
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_pressed
function 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 to True
in this vector. (The keycodes are available as constants in pygame.locals, like K_ESC, K_a, K_LEFT, and so on).
Ex:
if pygame.key.get_pressed()[pygame.K_ESCAPE]:
pygame.quit()
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 the else
clause in an if/elif sequence where you check for some state in the event queue.
回答2:
I don't know if it is good style, but what I did was just saving all the events in a variable and passing it to the objects that used their own event queues to detect "their" events.
while running:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
running = False
self.allS.update(events)
and in the update method:
for event in events:
print("Player ", event)
来源:https://stackoverflow.com/questions/8866096/pygame-event-queue