search method

SearchResult? search(
  1. int maxDepth, {
  2. void onDepthComplete(
    1. SearchResult
    )?,
  3. Duration? timeBudget,
})

Iterative deepening to maxDepth. With a timeBudget the search returns the best move from the last fully completed depth once time is spent.

Implementation

SearchResult? search(
  int maxDepth, {
  void Function(SearchResult)? onDepthComplete,
  Duration? timeBudget,
}) {
  _stopped = false;
  _nodes = 0;
  _path
    ..clear()
    ..addAll(_gameHistory); // seed repetition detection with the game so far
  _deadlineMs = timeBudget?.inMilliseconds ?? 0;
  _clock
    ..reset()
    ..start();

  SearchResult? best;
  var prevScore = 0;
  for (var depth = 1; depth <= maxDepth; depth++) {
    if (_stopped) break;
    final result = _aspirationSearch(depth, prevScore);
    if (result != null && !_stopped) {
      best = result;
      prevScore = result.score;
      onDepthComplete?.call(result);
      // A forced mate is found — no point searching deeper.
      if (result.score.abs() >= _mate - _maxPly) break;
    }
    if (_timeUp) break;
  }
  _clock.stop();
  return best;
}