简体   繁体   中英

Setting variable to True does not exit while False loop

I'm making a tic tac toe game using Python and I'm almost finished but I'm running into a problem with a while loop. Here is a shortened version of the function I use to check if a player has one.

def check_win(board, marker):
    win = False
    if board['A1'] == marker and board['B1'] == marker and board['C1'] == marker:
        print(f'{marker} wins!')
        win = True
    return win

And here it is in my code.

player_win = False
while player_win == False:
    # Player1's turn
    board_dict = get_and_place_marker(board_dict, player1)
    display_board(board_dict)
--> player_win = check_win(board_dict, player1)
    # Player2's turn
    board_dict = get_and_place_marker(board_dict, player2)
    display_board(board_dict)
--> player_win = check_win(board_dict, player2)

In the first instance of check_win(), it does assign player_win to True but it doesn't exit the loop. It goes to Player2's code and then exits when Player2 wins. What am I doing wrong here? Shouldn't the first instant of player_win being assigned True exit the loop?

If player 1 wins, you are still giving player 2 a chance to make a non-winning move, in which case the loop continues. The condition is not implicitly evaluated in the middle of the loop body just because a variable in the condition changes.

Instead of making both players take a turn in each iteration, change the code so that exactly one player takes a turn, alternating between players each time.

from itertools import cycle

for player in cycle([player1, player2]):
    board_dict = get_and_place_marker(board_dict, player)
    if check_win(board_dict, player):
        break

You can then check the value of player to see how actually won after the loop exits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM