| | | 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 | | { |
| | 7679449 | 10 | | public static int Nodes { get; private set; } = 0; |
| | | 11 | | public static int Search(BoardState boardState, int alpha, int beta, CancellationToken cancellationToken) |
| | | 12 | | { |
| | 3839675 | 13 | | Nodes++; |
| | | 14 | | |
| | 3839675 | 15 | | if (boardState.IsDraw()) |
| | 0 | 16 | | return 0; |
| | | 17 | | |
| | 3839675 | 18 | | int eval = PieceSquareTableEvaluation.Evaluate(boardState); |
| | | 19 | | |
| | 3839675 | 20 | | if (eval >= beta) |
| | 2629862 | 21 | | return beta; |
| | 1209813 | 22 | | if (eval > alpha) |
| | 2429 | 23 | | alpha = eval; |
| | | 24 | | |
| | 1209813 | 25 | | boardState.GenerateMoves(); |
| | 83790330 | 26 | | foreach (Move move in boardState.Moves) |
| | | 27 | | { |
| | 40685352 | 28 | | MoveOrdering.PopulateMoveScore(move, boardState); |
| | | 29 | | } |
| | 1209813 | 30 | | List<Move> moves = boardState.Moves; |
| | | 31 | | |
| | 7693902 | 32 | | for(int i = 0; i < moves.Count; ++i) |
| | | 33 | | { |
| | 3846951 | 34 | | MoveOrdering.SortNextBestMove(moves, i); |
| | 3846951 | 35 | | Move move = moves[i]; |
| | 3846951 | 36 | | if (cancellationToken.IsCancellationRequested) |
| | | 37 | | break; |
| | 3846950 | 38 | | if (!move.IsCapture()) |
| | | 39 | | break; // If sorted, once a quiet move is reached we won't need to visit the remaining nodes |
| | | 40 | | |
| | 3041517 | 41 | | boardState.MakeMove(move); |
| | 3041517 | 42 | | if (boardState.IsInCheck(boardState.SideToMove.Other())) |
| | | 43 | | { |
| | 355266 | 44 | | boardState.UnmakeMove(move); |
| | 355266 | 45 | | continue; |
| | | 46 | | } |
| | 2686251 | 47 | | int score = -Search(boardState, -beta, -alpha, cancellationToken); |
| | 2686251 | 48 | | boardState.UnmakeMove(move); |
| | | 49 | | |
| | 2686251 | 50 | | if (score >= beta) |
| | 404379 | 51 | | return beta; |
| | 2281872 | 52 | | if (score > alpha) |
| | 792 | 53 | | alpha = score; |
| | | 54 | | } |
| | 805434 | 55 | | return alpha; |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | public static void ResetNodes() |
| | | 59 | | { |
| | 57 | 60 | | Nodes = 0; |
| | 57 | 61 | | } |
| | | 62 | | } |
| | | 63 | | } |