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")
I'm trying to make a simple Genetic Algorithm Based Tic-Tac-Toe and I have no idea why it is crashing. I figured out it is in the loop of the Automated_Move Function (If that helps)
Your main loop never ends. There is no break
in:
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")
Also your Automated_Move()
's while
loop also sooner or later will get into a forever loop.
def Automated_Move(board):
while True:
RandomMove = randint(0,2)
if board[RandomMove][RandomMove] == "#":
board[RandomMove][RandomMove] = "O"
break
elif board[RandomMove][RandomMove] != "#":
pass
This loop breaks only if there is a '#'
element in board
(after changing that element to O
). After several iterations, all (diagonal) elements of the board
will be 'O'
and so the loop will never exit.
One possible solution is to modify the main loop as:
if any(['#' in r for r in board]):
Automated_Move(board)
else:
break
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.