我正在为一个类项目创建一个4x4TicTac脚趾游戏。我决定尝试实现Minimax算法来制造一台有竞争力的计算机,而不是双方都玩,或者随机移动。
我遵循了一个关于极客健忘的指南,它展示了算法的一个实现。我跟随它到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);发布于 2019-12-08 20:08:34
你在这里有个错误:
board[i][j] == player同时也在这里
board[i][j] == ' ';这可能导致堆栈溢出(或挂起,取决于优化),因为minimax将在不更新板的情况下调用自己。但是,如果else分支工作正常,则不会发生这种情况,因为对手将进行更新。(因为每次递归调用都将isMax设置为!isMax。)它仍然会使这个功能慢得多。
https://stackoverflow.com/questions/59239233
复制相似问题