ChessEngine.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ChessEngine.h"
  7. #include "MCTSTree.h"
  8. #include <AK/Random.h>
  9. #include <LibCore/ElapsedTimer.h>
  10. using namespace Chess::UCI;
  11. void ChessEngine::handle_uci()
  12. {
  13. send_command(IdCommand(IdCommand::Type::Name, "ChessEngine"sv));
  14. send_command(IdCommand(IdCommand::Type::Author, "the SerenityOS developers"sv));
  15. send_command(UCIOkCommand());
  16. }
  17. void ChessEngine::handle_position(PositionCommand const& command)
  18. {
  19. // FIXME: Implement fen board position.
  20. VERIFY(!command.fen().has_value());
  21. m_board = Chess::Board();
  22. for (auto& move : command.moves()) {
  23. VERIFY(m_board.apply_move(move));
  24. }
  25. }
  26. void ChessEngine::handle_go(GoCommand const& command)
  27. {
  28. // FIXME: A better algorithm than naive mcts.
  29. // FIXME: Add different ways to terminate search.
  30. VERIFY(command.movetime.has_value());
  31. srand(get_random<u32>());
  32. auto elapsed_time = Core::ElapsedTimer::start_new();
  33. auto mcts = [this]() -> MCTSTree {
  34. if (!m_last_tree.has_value())
  35. return { m_board };
  36. auto x = m_last_tree.value().child_with_move(m_board.last_move().value());
  37. if (x.has_value())
  38. return move(x.value());
  39. return { m_board };
  40. }();
  41. int rounds = 0;
  42. while (elapsed_time.elapsed() <= command.movetime.value()) {
  43. mcts.do_round();
  44. ++rounds;
  45. }
  46. dbgln("MCTS finished {} rounds.", rounds);
  47. dbgln("MCTS evaluation {}", mcts.expected_value());
  48. auto& best_node = mcts.best_node();
  49. auto const& best_move = best_node.last_move();
  50. dbgln("MCTS best move {}", best_move.to_long_algebraic());
  51. send_command(BestMoveCommand(best_move));
  52. m_last_tree = move(best_node);
  53. }