private static int AlphaBeta(ChessBoard examineBoard, byte depth, int alpha, int beta) { if (examineBoard == null || examineBoard.pieces == null) { return(0); } ++nodesSearched; if (examineBoard.FiftyMove >= 50 || examineBoard.RepeatedMove >= 3) { return(0); } if (depth == 0) { //Evaluate Score Evaluation.EvaluateBoardScore(examineBoard); //Invert Score to support Negamax return(SideToMoveScore(examineBoard.Score, examineBoard.WhoseMove)); } List <Position> positions = EvaluateMoves(examineBoard, depth); int length = positions.Count; if (examineBoard.whiteInCheck || examineBoard.blackInCheck || length == 0) { if (SearchForMate(examineBoard.WhoseMove, examineBoard, ref examineBoard.blackInMate, ref examineBoard.whiteInMate, ref examineBoard.staleMate)) { if (examineBoard.blackInMate) { if (examineBoard.WhoseMove == ChessPieceColor.Black) { return(-Constants.GameOverValue - depth); } else { return(Constants.GameOverValue + depth); } } if (examineBoard.whiteInMate) { if (examineBoard.WhoseMove == ChessPieceColor.Black) { return(Constants.GameOverValue + depth); } else { return(-Constants.GameOverValue - depth); } } //If Not Mate then StaleMate return(0); } } // Sort by score, this increases te chance we can prune moves early on positions.Sort(Sort); for (int i = 0; i < length; ++i) { Position move = positions[i]; //Make a copy ChessBoard board = new ChessBoard(examineBoard); //Move Piece ChessEngine.MoveContent(board, move.SrcPosition, move.DstPosition, ChessPieceType.Queen); //We Generate Valid Moves for Board PieceValidMoves.GenerateValidMoves(board); if (board.blackInCheck && examineBoard.WhoseMove == ChessPieceColor.Black) { //Invalid Move continue; } if (board.whiteInCheck && examineBoard.WhoseMove == ChessPieceColor.White) { //Invalid Move continue; } int value = -AlphaBeta(board, (byte)(depth - 1), -beta, -alpha); if (value >= beta) { // Beta cut-off return(beta); } if (value > alpha) { alpha = value; } } return(alpha); }