在Python中为井字游戏实现Minimax算法

时间:2018-11-29 02:30:55

标签: python minimax

我正在为Tic Tac Toe机器人创建一个简单的minimax算法。我在这里已经阅读了其他一些答案,但是我仍然不确定自己在做什么错,我对递归函数还是很陌生的。我想我了解算法的工作原理,但是我不确定。

def minimax(board, player, originalPlayer):
    global ai, human
    if gameOver(board):
        if hasWon(board, originalPlayer):
            return 1, None
        if hasWon(board, opposite(originalPlayer)):
            return -1, None
        if len(getEmptyIndexes(board)) is 0:
            return 0, None

    possibleMoves = getEmptyIndexes(board)
    if player == originalPlayer:
        bestScore = float('-inf')
    else:
        bestScore = float('inf')

    for moveIndex in possibleMoves:
        clone = copy(board)
        clone = makeMove(clone, moveIndex, player)
        score, index = minimax(clone, opposite(player), originalPlayer)

        if player == originalPlayer:
            if score > bestScore:
                bestScore = score
                bestMove = index
        else:
            if score < bestScore:
                bestScore = score
                bestMove = index

    return bestScore, bestMove

下面是我的游戏循环,我只是将其用于调试。我一直得到的错误是,当我期望有一个无的板子索引时,minimax函数返回元组(0,无)。

ai = 'X'
human = 'O'
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

while True:
    print('Board:')
    printBoard(board)
    choice = int(input('Your choice: '))
    board[choice] = human
    print('AI Moves')
    score, index = minimax(board, ai, ai)
    board[index] = ai

感谢您的帮助!

编辑: getEmptyIndexes返回板上空白的索引;例如:

getEmptyIndexes([' ', 'X', ' ', 'X', ' ', 'O', ' ', 'O', ' ']) = [0, 2, 4, 6, 8]

修改2: 我想我实际上只是解决了它,我写的是“ bestMove = index”而不是“ bestMove = moveIndex”,我几乎是在使用旧叶节点的旧移动索引,而不是新叶节点。

0 个答案:

没有答案
相关问题