UciParser.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include "UciParser.h"
  2. #include <sstream>
  3. #include "ChessGame.h"
  4. using namespace std;
  5. const std::map<std::string, UciParser::CommandHandler> UciParser::commandHandlers = {
  6. {"uci", &UciParser::uci },
  7. {"debug", &UciParser::debug },
  8. {"isready", &UciParser::isready },
  9. {"setoption", &UciParser::setoption },
  10. {"register", &UciParser::doNothing },
  11. {"ucinewgame", &UciParser::ucinewgame },
  12. };
  13. int UciParser::parse(istream& in, ostream& out)
  14. {
  15. while (!in.eof()) {
  16. string line;
  17. getline(in, line);
  18. executeLine(line);
  19. }
  20. return 0;
  21. }
  22. int UciParser::executeLine(const string& line)
  23. {
  24. stringstream s{ line };
  25. string token;
  26. string command;
  27. vector<string> args;
  28. s >> command;
  29. while (s >> token) {
  30. args.push_back(std::move(token));
  31. }
  32. return executeCommand(command, args);
  33. }
  34. int UciParser::executeCommand(const string& command,
  35. const vector<string>& args)
  36. {
  37. try {
  38. CommandHandler ch = commandHandlers.at(command);
  39. (this->*ch)(args);
  40. return 0;
  41. }
  42. catch (out_of_range& oor) {
  43. // no handler for command -> invalid command
  44. return 1;
  45. }
  46. }
  47. void UciParser::sendCommand(const std::string& command,
  48. const std::vector<std::string>& args)
  49. {
  50. cout << command;
  51. std::for_each(args.begin(), args.end(), [] (auto& x) { cout << " " << x; });
  52. }
  53. void UciParser::uci(const std::vector<std::string>& args)
  54. {
  55. sendCommand(UCIOK);
  56. }
  57. void UciParser::debug(const std::vector<std::string>& args)
  58. {
  59. // not yet implemented
  60. }
  61. void UciParser::isready(const std::vector<std::string>& args)
  62. {
  63. sendCommand(READYOK);
  64. }
  65. void UciParser::setoption(const std::vector<std::string>& args)
  66. {
  67. }
  68. void UciParser::ucinewgame(const std::vector<std::string>& args)
  69. {
  70. }
  71. void UciParser::doNothing(const std::vector<std::string>& args)
  72. {
  73. // explicitly do nothing
  74. return;
  75. }