Well, I have my chess engine, and while it is searching, I want it to keep track of the best move of the current position and the sequence of the follow-up moves.
Getting the best move for the current position is easy- it’s the goal of the search. But I want the sequence for debugging.
Here’s my code for the engine:
public static Move StartSearch(int depth)
{
bestMove = Move.NullMove;
// Return Null Move
if (depth <= 0)
{
return bestMove;
}
Search(depth, Infinity.negativeInfinity, Infinity.positiveInfinity, 0);
return bestMove;
}
public static int Search(int depth, int alpha, int beta, int plyFromRoot)
{
// Try looking up the current position in the transposition table.
// If the same position has already been searched to at least an equal depth
// to the search we're doing now,we can just use the recorded evaluation.
int ttVal = tt.LookupEvaluation (depth, plyFromRoot, alpha, beta);
if (ttVal != TranspositionTable.lookupFailed)
{
// The Transposition Table cannot store the repetition data, so whenever a position is repeated, the engine ends up in a threefold draw. To prevent that, check if it's threefold once again!
// For simplicity, just check if previous position is already reached
if (board.positionHistory.ContainsKey(board.currentZobristKey))
{
return 0;
}
Move move = tt.GetStoredMove ();
if (plyFromRoot == 0)
{
bestMove = move;
}
return ttVal;
}
if (depth == 0)
{
return QuiescenceSearch(alpha, beta);
}
List<Move> legalMoves = MoveGen.GenerateMoves(board);
MateChecker.MateState mateState = MateChecker.GetPositionState(board, legalMoves);
if (mateState != MateChecker.MateState.None)
{
if (mateState == MateChecker.MateState.Checkmate)
{
return -Evaluation.checkmateEval + plyFromRoot;
}
return 0;
}
MoveOrder.GetOrderedList(legalMoves);
if (plyFromRoot == 0)
{
bestMove = legalMoves[0];
}
int evalType = TranspositionTable.UpperBound;
foreach (Move move in legalMoves)
{
board.MakeMove(move);
int eval = -Search(depth - 1, -beta, -alpha, plyFromRoot + 1);
board.UnmakeMove(move);
if (eval >= beta)
{
tt.StoreEvaluation (depth, plyFromRoot, beta, TranspositionTable.LowerBound, move);
return beta;
}
if (eval > alpha)
{
alpha = eval;
evalType = TranspositionTable.Exact;
if (plyFromRoot == 0)
{
bestMove = move;
}
}
tt.StoreEvaluation (depth, plyFromRoot, alpha, evalType, bestMove);
}
return alpha;
}
I tried making an array for the sequence but could not figure out how to get the best move for each depth.
Please let me know where I should change or add in my code!