gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:15:13 24 4
gpt4 key购买 nike

所以我正在制作一个简单的井字游戏,但我很难弄清楚如何确保每个玩家的 Action 交替进行。我尝试使用两个带有 bool 值的 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。

最佳答案

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

关于python - 如何在 Python 中使用 while 循环模拟玩家之间的回合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52820861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com