From eaaa0ca24dbc6d06233d5ad7ae0e77b030871f63 Mon Sep 17 00:00:00 2001 From: k Date: Thu, 19 Jun 2025 17:28:00 -0400 Subject: [PATCH] depth search --- src/eval.c | 46 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/src/eval.c b/src/eval.c index 17a87d8..5ac2f32 100644 --- a/src/eval.c +++ b/src/eval.c @@ -1,5 +1,6 @@ #include "types.h" #include "help.h" +#include "moves.h" #include #include #include @@ -10,24 +11,29 @@ #define ROOK_VALUE 500 #define QUEEN_VALUE 900 #define KING_VALUE 20000 +#define INF 9000000 +#define MAX_DEPTH 3 // Adjustable depth int evaluateBoard(game *game); void makeMove(game *g, move* m); +int negamax(game *g, int depth, int alpha, int beta, int color); move *findBest(move* moves, size_t size, game* g){ - int bestScore = -999999; - move *m = moves; + int bestScore = -INF; + move *bestMove = moves; + int color = g->whiteToMove ? 1 : -1; + for (int i = 0; i < size; i++) { game gg = *g; makeMove(&gg, &moves[i]); - int score = evaluateBoard(&gg); + int score = -negamax(&gg, MAX_DEPTH, -INF, INF, -color); if (score > bestScore) { bestScore = score; - m = &moves[i]; + bestMove = &moves[i]; printf("info score cp %d\n", g->whiteToMove ? bestScore : -bestScore); } } - return m; + return bestMove; } int evaluateBoard(game *game) { @@ -53,7 +59,6 @@ int evaluateBoard(game *game) { else if (game->black.king & bit) score -= KING_VALUE; } - score *= game->whiteToMove ? -1 : 1; return score; } @@ -81,3 +86,32 @@ void makeMove(game *g, move* m) { g->whiteToMove = !g->whiteToMove; } + +int negamax(game *g, int depth, int alpha, int beta, int color) { + if (depth == 0) + return color * evaluateBoard(g); + + move moves[1500]; + int cnt = pawnMove(g, moves); + cnt += knightMove(g, moves + cnt); + cnt += rookMove(g, moves + cnt); + cnt += bishopMove(g, moves + cnt); + cnt += kingMove(g, moves + cnt); + cnt += queenMove(g, moves + cnt); + + if (cnt == 0) + return 0; + + int bestValue = -INF; + for (int i = 0; i < cnt; i++) { + game gg = *g; + makeMove(&gg, &moves[i]); + + int value = -negamax(&gg, depth - 1, -beta, -alpha, -color); + + if (value > bestValue) bestValue = value; + if (value > alpha) alpha = value; + if (alpha >= beta) break; + } + return bestValue; +}