[英]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.我正在使用 Python 制作井字游戏,我快完成了,但我遇到了一个 while 循环问题。 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.在 check_win() 的第一个实例中,它确实将 player_win 分配给 True,但它不会退出循环。 It goes to Player2's code and then exits when Player2 wins.
它转到 Player2 的代码,然后在 Player2 获胜时退出。 What am I doing wrong here?
我在这里做错了什么? Shouldn't the first instant of player_win being assigned True exit the loop?
player_win 被分配为 True 的第一个瞬间不应该退出循环吗?
If player 1 wins, you are still giving player 2 a chance to make a non-winning move, in which case the loop continues.如果玩家 1 获胜,您仍然给玩家 2 一个机会进行非获胜移动,在这种情况下,循环继续。 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.然后,您可以检查
player
的值,以查看循环退出后实际获胜的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.