I am setting up a basic chess AI using negamax and alpha beta pruning. If I remove alpha beta pruning, then it works as expected. After adding in pruning, it plays worse moves (but much faster). Sometimes it plays as expected until it abruptly blunders mate in 1. I am not sure why sometimes the best moves are getting pruned. Could anybody identify the issue?
public Move Think(Board board, Timer timer)
{
int bestEval = int.MinValue;
Move[] moves = board.GetLegalMoves();
Move bestMove = moves[0];
foreach (Move move in moves)
{
board.MakeMove(move);
int eval = -NegaMax(board, MAX_DEPTH, -100000, 100000);
board.UndoMove(move);
if (eval > bestEval)
{
bestEval = eval;
bestMove = move;
}
}
return bestMove;
}
//Evaluates a move based on the resulting board position
private int NegaMax(Board board, int depth, int alpha, int beta)
{
if (board.IsDraw())
return 0;
if (depth == 0)
return EvaluatePosition(board);
Move[] moves = board.GetLegalMoves();
int bestEval = int.MinValue;
foreach (Move move in moves)
{
board.MakeMove(move);
bestEval = Math.Max(bestEval, -NegaMax(board, depth - 1, -beta, -alpha));
board.UndoMove(move); //Must restore the board to its original position before testing the next move
alpha = Math.Max(alpha, bestEval);
if (alpha >= beta)
break;
}
return bestEval;
}
One thing I tried was using int.MinValue and int.MaxValue as the original alpha and beta parameters when I call it in the think() functions. However, this leads to even more unexpected behavior. I would expect it to play the same, but it plays very different moves although they are about just as bad as before.