Connect Four - Negamax AI评估功能问题

时间:2015-04-24 02:44:13

标签: c++ artificial-intelligence minimax negamax

我正在尝试为Connect 4实现NegaMax ai。该算法在某些时候运行良好,并且ai可以获胜。但是,有时它完全无法阻挡对手3,或者连续三次没有获胜。

评估函数遍历网格(水平,垂直,对角线向上,对角线向下),并采用每组四个方格。然后,它会在每个集合中进行检查,并根据此进行评估。

我基于此处提供的评估代码的功能:http://blogs.skicelab.com/maurizio/connect-four.html

我的功能如下:

    //All sets of four tiles are evaluated before this
    //and values for the following variables are set.
    if (redFoursInARow != 0)
    {
        redScore = INT_MAX;
    }
    else 
    {
        redScore = (redThreesInARow * threeWeight) + (redTwosInARow * twoWeight);
    }
    int yellowScore = 0;
    if (yellowFoursInARow != 0)
    {
        yellowScore = INT_MAX;
    }
    else
    {
        yellowScore = (yellowThreesInARow * threeWeight) + (yellowTwosInARow * twoWeight);
    }
    int finalScore = yellowScore - redScore;

    return turn ? finalScore : -finalScore; //If this is an ai turn, return finalScore. Else return -finalScore.

我的negamax功能如下:

    inline int NegaMax(char g[6][7], int depth, int &bestMove, int row, int col, bool aiTurn)
{
    {
        char c = CheckForWinner(g);
        if ('E' != c || 0 == depth)
        {
            return EvaluatePosition(g, aiTurn);
        }
    }
    int bestScore = INT_MIN;

    for (int i = 0; i < 7; ++i)
    {
        if (CanMakeMove(g, i)) //If column i is not full...
        {
            {
                //...then make a move in that column.
                //Grid is a 2d char array.
                //'E' = empty tile, 'Y' = yellow, 'R' = red.
                char newPos[6][7];
                memcpy(newPos, g, sizeof(char) * 6 * 7);
                int newRow = GetNextEmptyInCol(g, i);
                if (aiTurn)
                {
                    UpdateGrid(newPos, i, 'Y');
                }
                else 
                {
                    UpdateGrid(newPos, i, 'R');
                }
                int newScore = 0; int newMove = 0;
                newScore = NegaMax(newPos, depth - 1, newMove, newRow, i, !aiTurn);
                newScore = -newScore;
                if (newScore > bestScore)
                {
                    bestMove = i;
                    bestScore = newScore;
                }
            }
        }
    }
    return bestScore;
}

我知道连接四已经解决了,肯定有更好的方法可以解决这个问题,但任何有关修复/改进的帮助或建议都将非常感激。谢谢!

0 个答案:

没有答案