| | | 1 | | using Rudim.Board; |
| | | 2 | | using Rudim.Common; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Threading; |
| | | 5 | | |
| | | 6 | | namespace Rudim.Search |
| | | 7 | | { |
| | | 8 | | static class Quiescence |
| | | 9 | | { |
| | 8606598 | 10 | | public static int Nodes { get; private set; } = 0; |
| | | 11 | | public static int Search(BoardState boardState, int alpha, int beta, CancellationToken cancellationToken) |
| | | 12 | | { |
| | 4303252 | 13 | | Nodes++; |
| | | 14 | | |
| | 4303252 | 15 | | if (boardState.IsDraw()) |
| | 0 | 16 | | return 0; |
| | | 17 | | |
| | 4303252 | 18 | | int eval = PieceSquareTableEvaluation.Evaluate(boardState); |
| | | 19 | | |
| | 4303252 | 20 | | if (eval >= beta) |
| | 2924077 | 21 | | return beta; |
| | 1379175 | 22 | | if (eval > alpha) |
| | 2413 | 23 | | alpha = eval; |
| | | 24 | | |
| | 1379175 | 25 | | boardState.GenerateMoves(); |
| | 97855084 | 26 | | foreach (Move move in boardState.Moves) |
| | | 27 | | { |
| | 47548367 | 28 | | MoveOrdering.PopulateMoveScore(move, boardState); |
| | | 29 | | } |
| | 1379175 | 30 | | List<Move> moves = boardState.Moves; |
| | | 31 | | |
| | 8847654 | 32 | | for(int i = 0; i < moves.Count; ++i) |
| | | 33 | | { |
| | 4423827 | 34 | | MoveOrdering.SortNextBestMove(moves, i); |
| | 4423827 | 35 | | Move move = moves[i]; |
| | 4423827 | 36 | | if (cancellationToken.IsCancellationRequested) |
| | | 37 | | break; |
| | 4423826 | 38 | | if (!move.IsCapture()) |
| | | 39 | | break; // If sorted, once a quiet move is reached we won't need to visit the remaining nodes |
| | | 40 | | |
| | 3526075 | 41 | | boardState.MakeMove(move); |
| | 3526075 | 42 | | if (boardState.IsInCheck(boardState.SideToMove.Other())) |
| | | 43 | | { |
| | 462880 | 44 | | boardState.UnmakeMove(move); |
| | 462880 | 45 | | continue; |
| | | 46 | | } |
| | 3063195 | 47 | | int score = -Search(boardState, -beta, -alpha, cancellationToken); |
| | 3063195 | 48 | | boardState.UnmakeMove(move); |
| | | 49 | | |
| | 3063195 | 50 | | if (score >= beta) |
| | 481423 | 51 | | return beta; |
| | 2581772 | 52 | | if (score > alpha) |
| | 776 | 53 | | alpha = score; |
| | | 54 | | } |
| | 897752 | 55 | | return alpha; |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | public static void ResetNodes() |
| | | 59 | | { |
| | 52 | 60 | | Nodes = 0; |
| | 52 | 61 | | } |
| | | 62 | | } |
| | | 63 | | } |