I’m creating a small game using Python with the module Pygame.
I tried implementing a pretty basic (and I guess a pretty naive) state manager.
However,
I currently have an issue :
once I switch the the “play” state, I can’t switch back to the “menu”.
Is this a flaw in how I designed my state manager?
I have two methods,
- The
state_changemethod takes one argument, the desired state. - The
state_checkmethod takes a state as the only argument and returns it as the current state.
Here are the two methods:
def state_check(self, state):
self.current_state = state
print self.current_state
return self.current_state
def state_change(self, state):
self.state = state
Before the main loop,
The first state is initialized to be “menu”.
Inside the main loop,
state_check is before the if-statements to indicate which state the start with.
def game_loop(self):
running = True
self.test_car = car()
self.state = "menu"
while running:
pygame.display.set_caption("Project G")
self.state_check(self.state)
if self.current_state == "menu":
self.state_check(self.state)
self.screen.blit(self.background, (0,0))
#Blits the current state on the screen for testing purposes.
self.screen.blit(self.menu_text, (700, 580))
self.event_handler()
pygame.display.flip()
if self.current_state == "play":
self.state_check(self.state)
self.screen.blit(self.background, (0,0))
#Blits the current state on the screen.
self.screen.blit(self.play_text, (700, 580))
self.test_car.event_handler()
self.test_car.update(self.test_car.x_speed, self.test_car.y_speed)
pygame.display.flip()
Within the if-statements,
Are the event handler methods, which I’ve currently made to take keyboard inputs to switch between states (By calling the state_change method) and to quit the program.
Using some print methods, I’ve ruled out the possibility of the keys not registering.
#Event handler for the menu
def event_handler(self):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_p:
self.state_change("play")
print "Key Pressed: p"
if event.key == K_q:
print "Key Pressed: q"
pygame.quit()
sys.exit()
#Sample of the Event handler for "play"
def event_handler(self):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_m:
self.state_change("menu")
print "Key Pressed: m"
if event.key == K_q:
print "Key Pressed: q"
pygame.quit()
sys.exit()
I think you’re over-complicating things a little – do you really need check_state and set_state functions, and two variables?
I would do something like this: