Skip to content

Commit

Permalink
🐛 Prevent illegal moves when low in time (#657)
Browse files Browse the repository at this point in the history
Prevent illegal moves when low in time by simply returning the first legal move found before the search
  • Loading branch information
eduherminio committed Feb 13, 2024
1 parent cd20262 commit 56fb596
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/Lynx/Search/IDDFS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,13 @@ public SearchResult IDDFS(int? maxDepth, int? decisionTime)
int depth = 1;
bool isCancelled = false;
bool isMateDetected = false;
Move firstLegalMove = default;

try
{
_stopWatch.Start();

if (OnlyOneLegalMove(out var onlyOneLegalMoveSearchResult))
if (OnlyOneLegalMove(ref firstLegalMove, out var onlyOneLegalMoveSearchResult))
{
_engineWriter.TryWrite(InfoCommand.SearchResultInfo(onlyOneLegalMoveSearchResult));

Expand Down Expand Up @@ -166,7 +167,7 @@ public SearchResult IDDFS(int? maxDepth, int? decisionTime)
_stopWatch.Stop();
}

var finalSearchResult = GenerateFinalSearchResult(lastSearchResult, bestEvaluation, alpha, beta, depth, isCancelled);
var finalSearchResult = GenerateFinalSearchResult(lastSearchResult, bestEvaluation, alpha, beta, depth, firstLegalMove, isCancelled);

if (isMateDetected && finalSearchResult.Mate + Game.HalfMovesWithoutCaptureOrPawnMove < 96)
{
Expand Down Expand Up @@ -211,10 +212,9 @@ private bool StopSearchCondition(int depth, int? maxDepth, bool isMateDetected,
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool OnlyOneLegalMove([NotNullWhen(true)] out SearchResult? result)
private bool OnlyOneLegalMove(ref Move firstLegalMove, [NotNullWhen(true)] out SearchResult? result)
{
bool onlyOneLegalMove = false;
Move firstLegalMove = default;

Span<Move> moves = stackalloc Move[Constants.MaxNumberOfPossibleMovesInAPosition];
foreach (var move in MoveGenerator.GenerateAllMoves(Game.CurrentPosition, moves))
Expand Down Expand Up @@ -296,12 +296,13 @@ private bool OnlyOneLegalMove([NotNullWhen(true)] out SearchResult? result)

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private SearchResult GenerateFinalSearchResult(SearchResult? lastSearchResult,
int bestEvaluation, int alpha, int beta, int depth, bool isCancelled)
int bestEvaluation, int alpha, int beta, int depth, Move firstLegalMove, bool isCancelled)
{
SearchResult finalSearchResult;
if (lastSearchResult is null)
{
finalSearchResult = new(default, bestEvaluation, depth, [], alpha, beta);
_logger.Warn("Search cancelled at depth 1, choosing first found legal move as best one");
finalSearchResult = new(firstLegalMove, 0, 0, [firstLegalMove], alpha, beta);
}
else
{
Expand Down

0 comments on commit 56fb596

Please sign in to comment.