I'm having trouble figuring out how the event loop should be polled in pygame when the application becomes a bit more complex than the basic tutorials.
The game has different phases (or states), and I need to check for different events in different states.
I have a Game
class and a Player
class. I am detecting keypresses for moving the player outside of the event queue, in order to achieve the desired behaviour. This is the simplified version of how the file is organised:
class Game:
def __init__(self):
self.state = self.intro
self.player = Player()
def intro(self):
# Display the intro text, play some animations, music etc
if pygame.key.get_pressed()[pygame.K_SPACE]:
# Go to the next phase
self.state = self.running
def running(self):
# Check player input
if pygame.key.get_pressed()[pygame.K_d]:
self.player.move_right()
if pygame.key.get_pressed()[pygame.K_q]:
self.player.move_left()
if pygame.key.get_pressed()[pygame.K_z]:
self.player.jump()
# check game over
if gameisover: # pseudo-variable
self.state = self.gameover
def gameover(self):
# display gameover screen, wait for player input
def run(self):
self.state()
game = Game()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
game.run()
pygame.display.update()
clock.tick(60)
The code that gets executed each frame (when Game.run()
is called) depends on the phase of the game. This works, but it seems I have to check the event queue at each phase separately (including checking for quit events everywhere), otherwise pygame reports a crash to the OS.
If I check the event queue in a single loop only once, for each event I have to check the state the game is currently in before reacting to the event (suppose that SPACE does different things in different states).
I'm not sure of the best way to organise this in order to avoid checking the queue multiple times, but also avoid state checks and have each state only react to the events it's interested in.