markdown
struct SearchInfo {
int score;
int depth;
int nodes;
int selDepth;
uint64_t hash;
int timeMs;
};
SearchInfo aspirationSearch(BitboardBoard& board, int maxDepth) {
SearchInfo info = {};
int prevScore = 0;
int alpha, beta;
for (int depth = 1; depth <= maxDepth; depth++) {
if (depth <= 4) {
// Full window search for first few depths
alpha = -INF;
beta = INF;
} else {
// Aspiration window: ±50 centipawns around previous score
int delta = 50;
alpha = prevScore - delta;
beta = prevScore + delta;
while (true) {
int score = alphaBeta(board, depth, alpha, beta, true);
if (score <= alpha) {
// Fail low: widen window downward
alpha = std::max(alpha - delta * 4, -INF);
} else if (score >= beta) {
// Fail high: widen window upward
beta = std::min(beta + delta * 4, INF);
} else {
// Exact score within window
prevScore = score;
break;
}
delta *= 4;
}
}
int score = alphaBeta(board, depth, alpha, beta, true);
prevScore = score;
info.score = score;
info.depth = depth;
// Soft time management
if (depth >= 6) {
double elapsed = getElapsedMs();
double projected = elapsed * (std::pow((double)35, depth) /
std::pow((double)35, depth - 1));
if (projected > timeLimit * 0.6) break;
}
}
return info;
}
int alphaBeta(BitboardBoard& board, int depth, int alpha, int beta, bool isRoot) {
if (depth <= 0) return quiesce(board, alpha, beta);
TTEntry* ttEntry = tt.probe(board.getHash());
if (ttEntry && ttEntry->depth >= depth && !isRoot) {
if (ttEntry->flag == TT_EXACT) return ttEntry->score;
if (ttEntry->flag == TT_ALPHA && ttEntry->score <= alpha) return alpha;
if (ttEntry->flag == TT_BETA && ttEntry->score >= beta) return beta;
}
Move moves[256];
int numMoves = generateLegalMoves(board, moves);
sortMoves(moves, numMoves);
int bestScore = -INF;
Move bestMove = moves[0];
for (int i = 0; i < numMoves; i++) {
board.makeMove(moves[i]);
int score = -alphaBeta(board, depth - 1, -beta, -alpha, false);
board.unmakeMove(moves[i]);
if (score > bestScore) {
bestScore = score;
bestMove = moves[i];
}
if (score > alpha) alpha = score;
if (score >= beta) {
if (!isCapture(moves[i])) {
historyHeuristic[board.sideToMove][moves[i].from][moves[i].to] += depth * depth;
}
break;
}
}
// Store in TT
int flag = bestScore <= alpha ? TT_ALPHA : bestScore >= beta ? TT_BETA : TT_EXACT;
tt.store(board.getHash(), depth, bestScore, flag, bestMove.encode());
return bestScore;
}