public ScoreLookup(Board board) { _board = board; CreatePieceValues(); }
private MoveSequence AlphaBetaRecursive(Board previousBoard, Move move, int depth, MoveSequence alpha, MoveSequence beta, bool isWhite) { if (depth == 0 || (move.PieceCaptured & EnumBoardSquare.King) == EnumBoardSquare.King) { _numberOfLeafEvaluations++; return(new MoveSequence { Value = previousBoard.Score + move.ScoreChange, Move = move, NextMove = null }); } if (isWhite) { Board board = previousBoard.MakeMove(move); var moves = board.GetMovesForPlayer(EnumBoardSquare.White); Array.Sort(moves, (x, y) => y.ScoreChange.CompareTo(x.ScoreChange)); for (int i = 0; i < moves.Length; i++) { if (_boardStates.TryGetValue(board.GetHashCode(), out var info) && info.SearchDepth == depth) { if (alpha.Value < info.Value) { if (info.Value >= beta.Value) { _numberOfBranchesPruned++; return(beta); } else { alpha = new MoveSequence { Move = move, Value = info.Value, NextMove = null }; } } } else { var moveSequence = AlphaBetaRecursive(board, moves[i], depth - 1, alpha, beta, false); if (alpha.Value < moveSequence.Value) { if (moveSequence.Value >= beta.Value) { _numberOfBranchesPruned++; return(beta); } else { alpha = new MoveSequence { Move = move, Value = moveSequence.Value, NextMove = moveSequence }; } } lock (_lock) { if (!_boardStates.ContainsKey(board.GetHashCode())) { _boardStates.Add(board.GetHashCode(), new BoardStateInfo { SearchDepth = depth, Value = moveSequence.Value }); } } } } return(alpha); } else { Board board = previousBoard.MakeMove(move); var moves = board.GetMovesForPlayer(EnumBoardSquare.Black); Array.Sort(moves, (x, y) => x.ScoreChange.CompareTo(y.ScoreChange)); for (int i = 0; i < moves.Length; i++) { if (_boardStates.TryGetValue(board.GetHashCode(), out var info) && info.SearchDepth == depth) { if (info.Value < beta.Value) { if (alpha.Value >= info.Value) { _numberOfBranchesPruned++; return(alpha); } else { beta = new MoveSequence { Move = move, Value = info.Value, NextMove = null }; } } } else { var moveSequence = AlphaBetaRecursive(board, moves[i], depth - 1, alpha, beta, true); if (moveSequence.Value < beta.Value) { if (alpha.Value >= moveSequence.Value) { _numberOfBranchesPruned++; return(alpha); } else { beta = new MoveSequence { Move = move, Value = moveSequence.Value, NextMove = moveSequence }; } } lock (_lock) { if (!_boardStates.ContainsKey(board.GetHashCode())) { _boardStates.Add(board.GetHashCode(), new BoardStateInfo { SearchDepth = moveSequence.Length, Value = moveSequence.Value }); } } } } return(beta); } }