Skip to content Skip to sidebar Skip to footer

Pygame Event Queue

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 loo

Solution 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.

Solution 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()
        foreventin events:
            ifevent.type == pygame.QUIT:
                running = False

        self.allS.update(events)

and in the update method:

foreventin events:
    print("Player ", event)

Solution 3:

As far as I can tell there is no one 'right' way to do this, but one option is to save all the events into a variable. Then you can access them as many times as you want.

Post a Comment for "Pygame Event Queue"