如何使用Python中的while循环模拟玩家之间的转弯

时间:2018-10-15 16:16:54

标签: python while-loop tic-tac-toe

因此,我正在制作一个简单的井字游戏,但在尝试弄清楚如何确保每个玩家的动作交替时遇到困难。我尝试使用两个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()是一个函数,它将玩家的符号作为参数,如果他们进行有效的移动,则返回True;否则,则返回False。

1 个答案:

答案 0 :(得分:2)

尝试将两个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语句