Minimax井字游戏(4x4)挂

时间:2019-12-08 19:41:55

标签: c++ algorithm command-line-interface

我正在为一个班级项目创建一个4x4的Tic Tac Toe游戏。我决定不使用双方,也不使用随机移动,而是尝试实现Minimax算法以制造出具有竞争力的计算机。

我遵循了有关geeksforgeeks的指南,该指南显示了该算法的实现。我已将其跟随到T(而不是复制和粘贴)以尝试理解算法,但是只要轮到计算机,它就会运行findBestMove()函数并挂在内部某处。

我想问题出在findBestMove函数或其中调用的minimax函数中。

findBestMove()

Move findBestMove(char board[boardY][boardX])
{
    int bestVal = -1000;
    Move bestMove;
    bestMove.row = -1;
    bestMove.col = -1;

    for (int i = 0; i < boardY; i++) 
    {
        for (int j = 0; j < boardX; j++) {
            if (board[i][j] == ' ')
            {
                board[i][j] = player;

                int moveVal = minimax(board, 0, false);

                board[i][j] = ' ';

                if (moveVal > bestVal)
                {
                    bestMove.row = i;
                    bestMove.col = j;
                    bestVal = moveVal; 
                }
            }
        }
    }
    printf("The value of the best Move is : %d\n\n", bestVal); 
    return bestMove; 
}

很抱歉,如果这段代码太长。

minimax()

int minimax(char board[boardY][boardX], int depth, bool isMax) {
    int score = evaluate(board);

    if (score == 10)
        return score;

    if (score == -10)
        return score; 

    if (isMovesLeft(board) == false)
        return 0;

    if (isMax) 
    {
        int best = -1000;

        for (int i = 0; i < boardY; i++) {
            for (int j = 0; j < boardX; j++) {
                if (board[i][j] == ' ')
                {
                    board[i][j] == player;

                    best = max(best,
                        minimax(board, depth + 1, !isMax));

                    board[i][j] == ' ';

                }
            }
        }
        return best; 
    }
    else                    // If Mini's move
    {
        int best = 1000;

        for (int i = 0; i < boardY; i++) {
            for (int j = 0; j < boardX; j++) {
                if (board[i][j] == ' ') 
                {
                    board[i][j] = opponent;


                    best = min(best, 
                        minimax(board, depth + 1, !isMax));

                    board[i][j] = ' ';
                }
            }
        }
        return best; 
    }
}

运行此功能的驱动程序代码如下:

Move move = findBestMove(board);
MakeMove(move, isPlayersTurn);

1 个答案:

答案 0 :(得分:2)

您在这里有错字:

board[i][j] == player

还有这里

board[i][j] == ' ';

这可能会导致堆栈溢出(或挂起,具体取决于优化),因为minimax会自行调用而不会更新电路板。但是,如果else分支正常工作,则不会发生,因为将进行对手更新。 (由于在每次递归调用中将isMax设置为!isMax。)仍然会使函数变慢很多。