Search code examples
pythonwhile-looptic-tac-toe

how to simulate turns between players using while loops in Python


So I am making a simple tic tac toe game and I am having difficulty trying to figure out how to make sure that each player's moves alternate. I tried using two while loops with a boolean value which is supposed to change once each loop is executed. I'm not sure why but this doesn't work, only resulting in one iteration of each while loop and then it stopping. Below is my code. Can anyone help tell me how to fix this so they alternate and if there is a simpler way to do this?

moves = 0
first_player_move = True

while first_player_move is True:
    print("It's the first player's move")
    if ask_for_move("O") is True:
        if 3 <= moves <= 5:
            if check_if_won("O") is True:
                print("The first player won. Congrats! Game over")
                return
            elif moves ==5:
                print("The game ended in a tie.")
                return
            else:
                first_player_move = False
        else:
            moves +=1
            first_player_move = False

    elif ask_for_move("O") is False:
        continue


while first_player_move is False:
    print("It's the second player's move")
    if ask_for_move("X") is True:
        if check_if_won("X") is True:
            print("The second player won. Congrats! Game over")
            return
        else:
            first_player_move = True

    elif ask_for_move("X") is False:
        continue

For context, ask_for_move() is a function that takes in the player's symbol as the argument and returns True if they make a valid move and False if they don't.


Solution

  • Try putting both while loops in another loop like this

    while True:
       while first_player_move is True:
           # Your stuff here
       while first_player_move is False:
           # More of your stuff
    

    Code is sequential, so the program will execute the first while loop, then exit, execute the second while loop, exit, and then since there is no other code it is exiting the whole program. This will force it so reevaluate the while statements indefinitely