如何在 Python 中使用 while 循环模拟玩家之间的回合

how to simulate turns between players using while loops in Python

所以我正在制作一个简单的井字游戏,但我很难弄清楚如何确保每个玩家的动作交替进行。我尝试使用两个带有布尔值的 while 循环,该值应该在每个循环执行后更改。我不确定为什么,但这不起作用,只会导致每个 while 循环迭代一次,然后停止。下面是我的代码。谁能告诉我如何解决这个问题,以便他们交替使用,以及是否有更简单的方法来做到这一点?

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

就上下文而言,ask_for_move() 是一个函数,它将玩家的符号作为参数,returns 如果他们做出有效移动则为 True,否则为 False。

尝试像这样将两个 while 循环放在另一个循环中

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

代码是顺序的,所以程序会执行第一个while循环,然后退出,执行第二个while循环,退出,然后因为没有其他代码所以退出整个程序。这将迫使它无限期地重新评估 while 语句