aboutsummaryrefslogtreecommitdiff
path: root/src/base_tab/gamebase/PGNGameBase.cpp
blob: 69dcc4fb37c2c29f5645d7ac6b03a9b53b0ed222 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "PGNGameBase.hpp"
#include <wx/stdpaths.h>

PGNGameBase::PGNGameBase(std::string pgn_file) : pgn(new pgnp::PGN()) {
  file = pgn_file;
  pgn->FromFile(pgn_file);
}

bool PGNGameBase::NextGame() {
  bool game_found = false;
  try {
    pgn->ParseNextGame();
    game_found = true;
  } catch (...) {
    game_found = false;
  }
  return (game_found);
}

std::string PGNGameBase::GetTag(std::string tag) {
  if (pgn->HasTag(tag)) {
    return (pgn->GetTagValue(tag));
  }
  return ("");
}

Game *PGNGameBase::GetCurrentGame() {
  pgnp::HalfMove *pgnp_moves = new pgnp::HalfMove();
  pgn->GetMoves(pgnp_moves);
  std::string fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
  if (pgn->HasTag("FEN")) {
    fen = pgn->GetTagValue("FEN");
  }
  HalfMove *m = new HalfMove(pgnp_moves, fen);
  Game *g = new Game(m, fen);
  for (std::string &s : pgn->GetTagList()) {
    g->SetTag(s, pgn->GetTagValue(s));
  }
  g->SetResult(pgn->GetResult());
  return (g);
}

void PGNGameBase::Reset() {
  delete pgn;
  pgn = new pgnp::PGN();
  pgn->FromFile(file);
}

Game *PGNGameBase::GetGame(std::uint32_t id) {
  Reset();
  std::uint32_t curid = 0;
  while (NextGame()) {
    if (id == curid) {
      return (GetCurrentGame());
    }
    curid++;
  }
  return (NULL);
}

void PGNGameBase::Save(std::vector<std::uint32_t> to_ignore,
                       std::vector<GameBase *> new_games_bases,
                       std::vector<Game *> new_games) {
  wxStandardPaths stdPaths = wxStandardPaths::Get();
  wxString tmp = stdPaths.GetTempDir() + "/save_pgn_tmp.pgn";
  wxFile new_pgn(tmp, wxFile::write);

  Reset();
  std::uint32_t id = 0;
  while (NextGame()) {
    if (std::find(to_ignore.begin(), to_ignore.end(), id) == to_ignore.end()) {
      Game *g = GetCurrentGame();
      new_pgn.Write(g->GetPGN());
      new_pgn.Write("\n\n");
      delete g;
    }
    id++;
  }

  // Now add new games
  // new_games->Reset();
  // while (new_games->NextGame()) {
  //   Game *g = new_games->GetCurrentGame();
  //   new_pgn.Write(g->GetPGN());
  //   delete g;
  // }

  new_pgn.Close();
  wxCopyFile(tmp, file);
  wxRemoveFile(tmp);
}