from random import *
IQ = []
row1 = ["#", "#", "#"]
row2 = ["#", "#", "#"]
row3 = ["#", "#", "#"]
board = [row1, row2, row3]
def Display_Board():
print(row1[0],"|", row1[1], "|", row1[2])
print("----------")
print(row2[0],"|", row2[1], "|", row2[2])
print("----------")
print(row3[0],"|", row3[1], "|", row3[2])
def Automated_Move(board):
while True:
RandomMove = randint(0,2)
if board[RandomMove][RandomMove] == "#":
board[RandomMove][RandomMove] = "O"
break
elif board[RandomMove][RandomMove] != "#":
pass
while True:
#print(IQ)
Display_Board()
Row = int(input("Row: ")) - 1
Col = int(input("Col: ")) - 1
if board[Row][Col] != "X" and board[Row][Col] != "O":
board[Row][Col] = "X"
IQ.append(Row)
IQ.append(Col)
elif board[Row][Col] == "X" or board[Row][Col] == "O":
print("This is already Taken")
pass
Automated_Move(board)
print("\n")
我正在尝试制作一个简单的基于遗传算法的井字游戏,但我不知道它为什么会崩溃。我发现它在 Automated_Move 函数的循环中(如果有帮助)
你的主循环永远不会结束。没有break
在:
while True:
#print(IQ)
Display_Board()
Row = int(input("Row: ")) - 1
Col = int(input("Col: ")) - 1
if board[Row][Col] != "X" and board[Row][Col] != "O":
board[Row][Col] = "X"
IQ.append(Row)
IQ.append(Col)
elif board[Row][Col] == "X" or board[Row][Col] == "O":
print("This is already Taken")
pass
Automated_Move(board)
print("\n")
此外,您的Automated_Move()
'swhile
循环也迟早会进入永远循环。
def Automated_Move(board):
while True:
RandomMove = randint(0,2)
if board[RandomMove][RandomMove] == "#":
board[RandomMove][RandomMove] = "O"
break
elif board[RandomMove][RandomMove] != "#":
pass
仅当有'#'
元素 in board
(将该元素更改为 之后O
)时,此循环才会中断。经过几次迭代, 的所有(对角线)元素都board
将是'O'
,因此循环将永远不会退出。
一种可能的解决方案是将主循环修改为:
if any(['#' in r for r in board]):
Automated_Move(board)
else:
break
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句