超级井字棋的高级极小极大算法仅返回 NONE

问题描述 投票:0回答:1

这是我对超级井字游戏的 minimax 函数的实现:

import math
import random
from copy import deepcopy

def is_terminal_node(board):
    return board.check_winner() != 0 or not board.get_valid_moves()

def opponent_piece(piece):
    if piece == "O":
        return "X"
    else:
        return "O"

def minimax(board, depth, scoring_function, maximizing_player, piece):
    is_terminal = is_terminal_node(board)
    opponent_piece = opponent_piece(piece)

    if depth == 0 or is_terminal:
        if is_terminal:
            if board.check_winner() == piece:
                return (None, math.inf)
            elif board.check_winner() == opponent_piece:
                return (None, -math.inf)
            else:
                return (None, 0)
        else:
            if maximizing_player:
                return (None, scoring_function(board, piece))
            else:
                return (None, -scoring_function(board, opponent_piece))

    if maximizing_player:
        valid_moves = board.get_valid_moves()
        best_score = -math.inf
        best_move = random.choice(valid_moves)

        for move in valid_moves:
            board_copy = deepcopy(board)
            board_copy.make_move(move, piece)
            _, score = minimax(board_copy, depth - 1, scoring_function, False, piece)

            if score > best_score:
                best_score = score
                best_move = move

        return best_move, best_score

    else:
        valid_moves = board.get_valid_moves()
        best_score = math.inf
        best_move = random.choice(valid_moves)

        for move in valid_moves:
            board_copy = deepcopy(board)
            board_copy.make_move(move, piece)
            _, score = minimax(board_copy, depth - 1, scoring_function, True, piece)

            if score < best_score:
                best_score = score
                best_move = move

        return best_move, best_score

问题是当我使用简单的 main 时:

def main():

    board = Board()
    
    print(minimax(board, 1,scoring_function,True,"X"))

我只得到“(None,0)”,并且在更高级的主程序(有两个玩家)中,我看到循环永远不会停止,并且返回的 best_move 始终是“None”。我警告说问题不能来自“scoring_function”。

python artificial-intelligence tic-tac-toe nonetype minimax
1个回答
0
投票

我假设您未显示的其余

Board
功能正常工作。

当您递归调用

minimax
时,
piece
不应该更改为
opponent_piece
吗?

线路:

_, score = minimax(board_copy, depth - 1, scoring_function, False, piece)

更改为:

_, score = minimax(board_copy, depth - 1, scoring_function, False, opponent_piece)
.

例如。

© www.soinside.com 2019 - 2024. All rights reserved.