toad100
toad100

Reputation: 13

How do I exit a game loop?

If a set of conditions are true, I want to call a function to check if they're true. If the functions confirms they're true, I want to exit my pygame gameloop by making gameExit=True from the function.

However, its not executing my function, even though the conditions have been met.

Context: Tic tac toe game, want to exit gameloop is all the top sqaures have a cross in them.

def is_game_over(current_game,gameExit):
    if current_game[0][0]=="cross" and current_game[0][1]=="cross" and current_game[0][2]=="cross":
        gameDisplay.fill(white)
        pygame.display.flip()
        gameExit=True

while gameExit == False:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            gameExit=True


        if event.type == pygame.MOUSEBUTTONDOWN:

            placement = (place_clicked(pygame.mouse.get_pos(), "none"))  # get the co-ordinates of place they clicked

           *Below is a bunch of if statements, which call the function is_game_over if i want to exit the game loop"

Upvotes: 1

Views: 1155

Answers (1)

Kieren Anderson
Kieren Anderson

Reputation: 528

The gameExit variable within is_game_over is not referencing the same value as the gameExit variable within the while loop. Read up on parameter passing for python to learn more.

You need to return the new value from the function and use it to set the gameExit variable within the while loop.

* gameExit no longer a parameter (return True, False instead)
def is_game_over(current_game):
    if current_game[0][0]=="cross" and current_game[0][1]=="cross" and current_game[0][2]=="cross":
        gameDisplay.fill(white)
        pygame.display.flip()
        return True
    return False

* set gameExit within while loop
gameExit = is_game_over(current_game)

Upvotes: 2

Related Questions