search method

int search(
  1. Tensor rootState,
  2. List<int> legalActions, {
  3. int numSimulations = 50,
})

Main entry point for playing: Runs simulations and returns the best move.

Implementation

int search(
  Tensor rootState,
  List<int> legalActions, {
  int numSimulations = 50,
}) {
  MCTSNode root = MCTSNode(rootState);

  // Initial expansion of the root with legal move filtering
  final prediction = model.predict(rootState);
  root.priors = filterPriors(prediction['policy']!.data, legalActions);

  for (int i = 0; i < numSimulations; i++) {
    runSimulation(root);
  }

  if (root.visitCounts.isEmpty) {
    return legalActions.isNotEmpty ? legalActions.first : 0;
  }

  // Return the action with the highest visit count
  return root.visitCounts.entries
      .reduce((a, b) => a.value > b.value ? a : b)
      .key;
}