I am making a chess engine in C++ and with this algorithm, I get expected play with max depth set to 1. Beyond that however, it ignores pieces that are in danger and seems to even willingly put itself in danger.
Here is my code:
int negamax(int depth, int alpha, int beta)
{
int max = -INFINITY;
MoveList legalMoves;
MoveGeneration::generateCaptureMoves(&legalMoves);
MoveGeneration::generateQuietMoves(&legalMoves);
// No legal moves
if(legalMoves.count == 0)
{
if(Position::isCheck())
{
// Checkmate
if(Position::activeColor == WHITE)
return VAL_VICTORY;
else
return -VAL_VICTORY;
}
else
{
// Stalemate
return 0;
}
}
// Go through legal moves
for(int i = 0; i < legalMoves.count; i++)
{
// Get move score
Position::doMove(legalMoves[i]);
int score;
if(depth == 0)
score = quiescence(MAX_QUIESCENCE_DEPTH, alpha, beta);
else
score = -negamax(depth - 1, alpha, beta);
Position::undoMove();
// Pruning
if(Position::activeColor == WHITE && score > beta) break;
if(Position::activeColor == BLACK && score < alpha) break;
if(Position::activeColor == WHITE && score > alpha) alpha = score;
if(Position::activeColor == BLACK && score < beta) beta = score;
// Best so far?
if(score > max)
{
max = score;
if(depth == MAX_DEPTH)
bestMove = legalMoves[i];
}
}
return max;
}