为什么我的程序挂起了

时间:2017-07-29 05:03:51

标签: python while-loop

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")

我正在尝试制作一个简单的基于遗传算法的Tic-Tac-Toe,我不知道它为什么会崩溃。 我发现它在Automated_Move功能的循环中(如果有帮助)

1 个答案:

答案 0 :(得分:0)

你的主循环永远不会结束。其中没有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()的{​​{1}}循环迟早会进入永久循环。

while

仅当def Automated_Move(board): while True: RandomMove = randint(0,2) if board[RandomMove][RandomMove] == "#": board[RandomMove][RandomMove] = "O" break elif board[RandomMove][RandomMove] != "#": pass 中有'#'个元素(将该元素更改为board后)时,此循环才会中断。经过几次迭代后,O的所有(对角线)元素都将为board,因此循环将永远不会退出。

一种可能的解决方案是将主循环修改为:

'O'