C++ 极小极大函数

标签 c++ algorithm minimax

我已经在 Google 和 Stackoverflow 上搜索了这个问题,但我仍然不明白 minimax 函数是如何工作的。

我发现维基百科条目有该函数的伪代码版本:

function integer minimax(node, depth)
    if node is a terminal node or depth <= 0:
        return the heuristic value of node
    α = -∞
    for child in node:                       # evaluation is identical for both players 
        α = max(α, -minimax(child, depth-1))
    return α

我在 Google 上找到的其他几个 minimax 函数基本上都是一样的;我正在尝试用 C++ 实现这一点,这是我到目前为止所想到的:

double miniMax(Board eval, int iterations)
{
    //I evaluate the board from both players' point of view and subtract the difference
    if(iterations == 0)
        return boardEval(eval, playerNumber) - boardEval(eval, opponentSide());

    /*Here, playerTurn tells the findPossibleMoves function whose turn it is;
    I mean, how do you generate a list of possible moves if you don't even know
    whose turn it's supposed to be? But the problem is, I don't see where I can
    get playerTurn from, as there are only 2 parameters in all the examples of
    minimax I've seen*/
    vector<int> moves = eval.findPossibleMoves(playerTurn);

    //I'm assuming -∞ in the wikipedia article means a very low number?
    int result = -999999999;

    //Now I run this loop to evaluate each possible move
    /*Also, the Lua example in the wiki article has
      alpha = node.player==1 and math.max(alpha,score) or math.min(alpha,score)
      Is alpha a boolean there?!*/
    for(int i = 0; i * 2 < moves.size(); i++)
    {
        //I make a copy of the board...
        Board temp = eval;

        /*and make the next possible move... once again playerTurn crops up, and I
        don't know where I can get that variable from*/
        temp.putPiece(moves[i * 2], moves[i * 2 + 1], playerTurn);

        /*So do I create a function max that returns the bigger of two doubles?*/
        result = max(result, -miniMax(temp, iterations - 1));
    }

    return result;
    /*So now I've returned the maximum score from all possible moves within a certain
    # of moves; so how do I know which move to make? I have the score; how do I know
    which sequence of moves that score belongs to?*/
}

如您所见,我对这个极小极大函数感到非常困惑。请至少给我一些提示来帮助我解决这个问题。

谢谢! :)

最佳答案

来自维基百科的样本正在使用 Alpha/Beta 修剪进行 NegaMax

直接命名可能会对您有所帮助:

  • 基础是 MiniMax,字面上的实现将涉及 2 个轮流(相互递归)的方法,每侧 1 个。

  • 懒惰的程序员将其转变为 NegaMax,这是一种策略性放置 - 运算符的方法。

  • Alpha/Beta 修剪正在跟踪最佳移动窗口(多个深度)以检测死分支。

您的playerTurn用于确定轮到谁了。在 NegaMax 中,您可以从深度(迭代)为奇数或偶数得出这一点。但使用 2 个参数(myColor、otherColor)并在每个级别切换它们会更容易。

关于C++ 极小极大函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3630669/

相关文章:

java - 区间和的时间复杂度

订购 2 件商品组合的算法

artificial-intelligence - Minimax/Alpha beta 修剪移动排序?

c minimax 使用 posix 线程

c++ - 名称的策略查找有关功能的完全特化?

c++ - 是否可以为基于对话框的窗口而不是框架窗口创建 MDI 窗口?

c++ - 无法推断可变参数模板的模板类型

c++ - int 和 long 有什么区别?

algorithm - 淘汰赛所需轮次

algorithm - Minimax 算法未按预期工作