Disservin / chess-library

C++ chess library
https://disservin.github.io/chess-library/
MIT License
63 stars 20 forks source link

Side variation support in PgnReader #99

Open trevor-vincent opened 2 months ago

trevor-vincent commented 2 months ago

Hi! it would be nice if we could parse side variations, e.g.

#include <iostream>
#include <sstream>
#include <memory>
#include "chess.hpp"

using namespace chess;

class MyVisitor : public pgn::Visitor {
private:
  size_t ply = 0;

public:
  void header(std::string_view key, std::string_view value) {}

  void move(std::string_view move, std::string_view comment) {
    std::cout << ply << ". " << move;
    if (!comment.empty()) {
      std::cout << " {" << comment << "}";
    }
    std::cout << std::endl;
    ++ply;
  }
  void startPgn() {}
  void startMoves() {}
  void endPgn() {}
};

int main(int argc, char const *argv[]) {
  std::string pgn = R"(
[Event "Random Game"]
[Site "Chess Library"]
[Date "2024.05.13"]
[Round "-"]
[White "White"]
[Black "Black"]
[Result "*"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 (3... Nf6 4. O-O Nxe4) 4. Ba4 Nf6 5. O-O Be7 (5... Nxe4 6. Re1 Nc5 7. Bxc6 bxc6) 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Bb7 (9... Na5 10. Bc2 c5) 10. d4 Re8 11. Nbd2 Bf8 12. Bc2 exd4 13. cxd4 Nb4 (13... g6 14. a3 Bg7) 14. Bb1 c5 15. d5 a5 16. a3 Na6 (16... Na6 17. a4 b4) 17. b3 Nc7 18. Bb2 Nd7 19. Nf1 Nb6 (19... c4 20. Qd4 f6) 20. Ng3 Qd7 21. Nf5 f6 22. N3h4 Qf7 23. Qg4 Kh8 (23... g6 24. Nxd6 Bxd6) 24. Re3 a4 25. Rg3 axb3 26. Ng6+ hxg6 27. Qh4+ Kg8 28. Nh6+ gxh6 29. Qh5 Kh7 30. Qxg6+ Kh8 *
)";

  std::istringstream pgn_stream(pgn);
  auto vis = std::make_unique<MyVisitor>();
  pgn::StreamParser parser(pgn_stream);
  parser.readGames(*vis);

  return 0;
}