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