Changing of game states in pygame crashes it

Viewed 37

so i'm doing the states of my game right now :

import pygame
import sys
screen=pygame.display.set_mode((1200,700))
play_image=pygame.Surface((100,200))
play_image.fill('red')
play_rect=play_image.get_rect(topleft=(200,200))
retry_image=pygame.Surface((100,200))
retry_image.fill('red')
retry_rect=retry_image.get_rect(topleft=(200,200))
game_over=False
menustatus=True
while menustatus:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            pygame.font.quit()
            sys.exit()
    mouse_pos=pygame.mouse.get_pos()
    mousecheck=pygame.mouse.get_pressed()
    if play_rect.collidepoint(mouse_pos) and mousecheck[0]:
        game_over=True
        menustatus=False
    screen.blit(play_image,play_rect)
    pygame.display.update()

while game_over:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            pygame.font.quit()
            sys.exit()
    mouse_pos=pygame.mouse.get_pos()
    mousecheck=pygame.mouse.get_pressed()
    if retry_rect.collidepoint(mouse_pos) and mousecheck[0]:
        menustatus=True
        game_over=False
    screen.blit(retry_image,retry_rect)
    pygame.display.update()

problem is, when i click the red rectangle, which is a placeholder for my play button to head into the gameover screen, it crashes instead of showing me a game over screen

1 Answers

I've written a function state_machine() which decides what is happening and what to do next, but is uses states to 'jump' from one thing to another:

import pygame
import sys
screen=pygame.display.set_mode((1200,700))
play_image=pygame.Surface((100,200))
play_image.fill('red')
play_rect=play_image.get_rect(topleft=(200,200))
retry_image=pygame.Surface((100,200))
retry_image.fill('red')
retry_rect=retry_image.get_rect(topleft=(200,200))

def state_machine(state):
    if state == "menu_status":
        if play_rect.collidepoint(mouse_pos) and mousecheck[0]:  #checks if player clicks a button to play
            state = "game_over"
    elif state == "game_over":
        if retry_rect.collidepoint(mouse_pos) and mousecheck[0]: #checks if player clicks a button to retry
            state = "game_active"
    elif state == "game_active":
        if player.rect.y>screen_height: #checks if player dies
            state = "game_over"
    return state

game_state = "menu_status"

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            pygame.font.quit()
            sys.exit()
    mouse_pos=pygame.mouse.get_pos()
    mousecheck=pygame.mouse.get_pressed()

    game_state = state_machine(game_state)

    screen.blit(play_image,play_rect)
    pygame.display.update()

I've not run this code because I'm not sure I've captured everything from your code.

Related