我无与伦比的井字游戏程序失败了

时间:2018-10-17 00:14:50

标签: python algorithm artificial-intelligence tic-tac-toe minimax

我尝试使用minimax算法制作一个不会在井字游戏中丢失的程序。但是,在某些情况下,它会失败。例如,在井字游戏板上还剩下两个点时(在某些情况下),该程序停止播放并询问用户两个连续的输入。而且,在某些情况下,如果计算机明显赢得了胜利,那就不是对移动的正确选择。

这是一项任务,非常感谢您今天提供的任何帮助。

非常感谢!

编辑: 请注意,该代码允许用户覆盖先前的动作。我将尽快解决此问题。 但是,即使我不覆盖以前的机会,也不会得到结果。我已经测试了代码,问题似乎出在minimax函数中,但是我保留了整个代码,以防万一我错了,真正的问题出在其他地方。

编辑2:对不完整的帖子表示抱歉!重现此问题的测试用例如下。在我进入移动位置(位置5)后,程序停止播放并要求我玩所有机会。

Would you like to go first (Y/N)?: n  
. . .  
. . .   
. . .   

x . .   
. . .   
. . .   

Enter your choice (1-9): 5  
x . .   
. o .   
. . .   

x x .   
. o .   
. . .   

Enter your choice (1-9): 7  
x x .   
. o .   
o . .   

x x .   
. o .   
o . .   

Enter your choice (1-9): 

此外,我知道我的代码很混乱而且很业余-但是尽管使用了全局变量,但我应该能够使其工作。如果您可以帮我解决这个问题,我会全部清理干净。再次感谢!

编辑3:另一个测试案例: 您要先(是/否)吗?:y

. . . 
. . . 
. . . 

Enter your choice (1-9): 5
. . . 
. o . 
. . . 

x . . 
. o . 
. . . 

Enter your choice (1-9): 3
x . o 
. o . 
. . . 

x . o 
. o . 
x . . 

Enter your choice (1-9): 2
x o o 
. o . 
x . . 

x o o 
. o . 
x . . 

Enter your choice (1-9): 6
x o o 
. o o 
x . . 

x o o 
. o o 
x . . 

Enter your choice (1-9): 9
You win!

我的代码在Python 3.6中,如下所示:

move = -1
n = 0
def evaluateBoard(board):
    global n
    #Checking for rows
    cnt = 0
    for i in range(n):
        res = 0
        for j in range(n):
           res += board[cnt * n + j] 
        cnt += 1
        if res == n:
            return 1
        elif res == -n:
            return -1

    #Checking for columns
    for i in range(n):
        res = 0
        for j in range(n):
            res += board[i + n * j]
        if res == n:
            return 1
        elif res == -n:
            return -1

    #Checking for diagonals
    res = res2 = 0
    for i in range(n):
        res += board[i * (n + 1)]   
        res2 += board[(i + 1) * (n - 1)]
    if n in [res, res2]:
        return 1
    elif -n in [res, res2]:
        return -1

    return 0

def checkNonTerminal(board):
   for pos in board:
       if pos == 0:
           return 1
   return 0

def getScore(board, depth):
    if evaluateBoard(board) == 1:
        return 10 - depth
    elif evaluateBoard(board) == -1:
        return depth - 10
    else:
        return 0

def minimax(board, turn, depth):
    if evaluateBoard(board) == 0 and checkNonTerminal(board) == 0:
        return getScore(board, depth)
    global move
    moves = list()
    scores = list()

    for square, pos in enumerate(board):
        if pos == 0:
            #print(board)
            new_board = board.copy()
            new_board[square] = turn
            moves.append(square)
            #print("Moves:", moves, "depth:", depth, "turn:", turn, checkNonTerminal(new_board) == 0)
            if evaluateBoard(new_board) in [1, -1] or checkNonTerminal(new_board) == 0:
                return getScore(new_board, depth)
            scores.append(minimax(new_board, turn * -1, depth + 1))
        #print("scores", scores) 

    if turn == 1:
        move = moves[scores.index(max(scores))]
        return max(scores)
    elif turn == -1:
        move = moves[scores.index(min(scores))]
        return min(scores)

def displayBoard(board):
    global n
    for i in range(n):
        for j in range(n):
            if board[n*i+j] == 1:
                print("x", end = " ")
            elif board[n*i+j] == -1:
                print("o", end = " ")
            else:
                print(".", end = " ")
        print()

def main():      
    global n 
    global move
    n = 3
    first_turn = input("Would you like to go first (Y/N)?: ")
    if first_turn in ['Y', 'y']:
        first_turn = -1
        cnt = 1
    else:
        first_turn = 1
        cnt = 2
    board = [0] * 9

    while evaluateBoard(board) == 0 and checkNonTerminal(board) == 1:
        displayBoard(board)
        if cnt % 2 == 0:
            score = minimax(board, 1, 0)
            print(score)
            board[move] = 1
        else:
            choice = eval(input("Enter your choice (1-9): "))
            board[choice - 1] = -1
        cnt += 1

    if evaluateBoard(board) == 1:
        print("You lose!")
    elif evaluateBoard(board) == -1:
        print("You win!")
    else:
        print("It's a draw!")

main()

1 个答案:

答案 0 :(得分:2)

如果您选中的第一招是游戏玩家,那么您将返回而未设置招数。可能是您的获胜逻辑失败以及转弯失败的原因。

多说一些程序员的话:
您的递归终止条件被过早触发,您也需要处理这种情况!

for square, pos in enumerate(board):
    if pos == 0:
        #print(board)
        new_board = board.copy()
        new_board[square] = turn
        moves.append(square)
        #print("Moves:", moves, "depth:", depth, "turn:", turn, checkNonTerminal(new_board) == 0)
        if evaluateBoard(new_board) in [1, -1] or checkNonTerminal(new_board) == 0:
            return getScore(new_board, depth) <----here
        scores.append(minimax(new_board, turn * -1, depth + 1))
    #print("scores", scores) 

太忙而无法检查,但是我相信您也可以在该位置设置move变量-如果您只是弹出递归堆栈,以后它将被覆盖。

PS,这是使用适当的返回变量而不是仅设置全局变量的另一个原因;)