-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathSGFTree.cpp
489 lines (412 loc) · 13.5 KB
/
SGFTree.cpp
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#include <iostream>
#include <fstream>
#include <cctype>
#include <sstream>
#include <stdexcept>
#include <memory>
#include <ctime>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include "SGFTree.h"
#include "KoState.h"
#include "SGFParser.h"
#include "Utils.h"
using namespace Utils;
void SGFTree::init_state(void) {
m_initialized = true;
// Initialize with defaults.
// The SGF might be missing boardsize or komi
// which means we'll never initialize properly.
m_state.init_game(19, 7.5f);
}
KoState * SGFTree::get_state(void) {
assert(m_initialized);
return &m_state;
}
SGFTree * SGFTree::get_child(unsigned int count) {
if (count < m_children.size()) {
assert(m_initialized);
return &(m_children[count]);
} else {
return nullptr;
}
}
// This follows the entire line, and doesn't really need the intermediate
// states, just the moves. As a consequence, states that contain more than
// just moves won't have any effect.
GameState SGFTree::follow_mainline_state(unsigned int movenum) {
SGFTree * link = this;
// This initializes a starting state from a KoState and
// sets up the game history.
GameState result(get_state());
int tomove = result.get_to_move();
for (unsigned int i = 0; i <= movenum && link != nullptr; i++) {
// root position has no associated move
if (i != 0) {
int move = link->get_move(tomove);
if (move != SGFTree::EOT) {
result.play_move(move);
tomove = !tomove;
}
}
link = link->get_child(0);
}
return result;
}
KoState * SGFTree::get_state_from_mainline(unsigned int movenum) {
SGFTree * link = this;
SGFTree * last = this;
for (unsigned int i = 0; i <= movenum && link != NULL; i++) {
link = link->get_child(0);
if (link == NULL) {
return last->get_state();
} else {
last = link;
}
}
return link->get_state();
}
// the number of states is one more than the number of moves
int SGFTree::count_mainline_moves(void) {
SGFTree * link = this;
int count = -1;
while (link != NULL) {
link = link->get_child(0);
count++;
}
return count;
}
void SGFTree::load_from_string(std::string gamebuff) {
std::istringstream pstream(gamebuff);
// loads properties with moves
SGFParser::parse(pstream, this);
// Set up the root state to defaults
init_state();
// populates the states from the moves
// split this up in root node, achor (handicap), other nodes
populate_states();
}
// load a single game from a file
void SGFTree::load_from_file(std::string filename, int index) {
std::string gamebuff = SGFParser::chop_from_file(filename, index);
//myprintf("Parsing: %s\n", gamebuff.c_str());
load_from_string(gamebuff);
}
void SGFTree::populate_states(void) {
PropertyMap::iterator it;
bool valid_size = false;
bool has_handicap = false;
// first check for go game setup in properties
it = m_properties.find("GM");
if (it != m_properties.end()) {
if (it->second != "1") {
throw std::runtime_error("SGF Game is not a Go game");
} else {
if (!m_properties.count("SZ")) {
// No size, but SGF spec defines default size for Go
m_properties.insert(std::make_pair("SZ", "19"));
valid_size = true;
}
}
}
// board size
it = m_properties.find("SZ");
if (it != m_properties.end()) {
std::string size = it->second;
std::istringstream strm(size);
int bsize;
strm >> bsize;
if (bsize <= FastBoard::MAXBOARDSIZE) {
// Assume 7.5 komi if not specified
m_state.init_game(bsize, 7.5f);
valid_size = true;
} else {
throw std::runtime_error("Board size not supported.");
}
}
// komi
it = m_properties.find("KM");
if (it != m_properties.end()) {
std::string foo = it->second;
std::istringstream strm(foo);
float komi;
strm >> komi;
int handicap = m_state.get_handicap();
// last ditch effort: if no GM or SZ, assume 19x19 Go here
int bsize = 19;
if (valid_size) {
bsize = m_state.board.get_boardsize();
}
m_state.init_game(bsize, komi);
m_state.set_handicap(handicap);
}
// handicap
it = m_properties.find("HA");
if (it != m_properties.end()) {
std::string size = it->second;
std::istringstream strm(size);
float handicap;
strm >> handicap;
has_handicap = (handicap > 0.0f);
m_state.set_handicap((int)handicap);
}
// result
it = m_properties.find("RE");
if (it != m_properties.end()) {
std::string result = it->second;
if (boost::algorithm::find_first(result, "Time")) {
// std::cerr << "Skipping: " << result << std::endl;
m_winner = FastBoard::EMPTY;
} else {
if (boost::algorithm::starts_with(result, "W+")) {
m_winner = FastBoard::WHITE;
} else if (boost::algorithm::starts_with(result, "B+")) {
m_winner = FastBoard::BLACK;
} else {
m_winner = FastBoard::INVAL;
// std::cerr << "Could not parse game result: " << result << std::endl;
}
}
} else {
m_winner = FastBoard::EMPTY;
}
// Verify Aya results consistency
// We don't really expect to find GN with W+R/B+R in real games,
// and even if we don't this shouldn't hurt.
it = m_properties.find("GN");
if (it != m_properties.end()) {
std::string result = it->second;
if (boost::algorithm::starts_with(result, "W+R")) {
if (m_winner == FastBoard::BLACK) {
m_winner = FastBoard::INVAL;
}
} else if (boost::algorithm::starts_with(result, "B+R")) {
if (m_winner == FastBoard::WHITE) {
m_winner = FastBoard::INVAL;
}
}
}
// handicap stones
auto prop_pair_ab = m_properties.equal_range("AB");
// Do we have a handicap specified but no handicap stones placed in
// the same node? Then the SGF file is corrupt. Let's see if we can find
// them in the next node, which is a common bug in some Go apps.
if (has_handicap && prop_pair_ab.first == prop_pair_ab.second) {
if (!m_children.empty()) {
auto& successor = m_children[0];
prop_pair_ab = successor.m_properties.equal_range("AB");
}
}
// Loop through the stone list and apply
for (auto it = prop_pair_ab.first; it != prop_pair_ab.second; ++it) {
auto move = it->second;
int vtx = string_to_vertex(move);
apply_move(FastBoard::BLACK, vtx);
}
// XXX: count handicap stones
const auto& prop_pair_aw = m_properties.equal_range("AW");
for (auto it = prop_pair_aw.first; it != prop_pair_aw.second; ++it) {
auto move = it->second;
int vtx = string_to_vertex(move);
apply_move(FastBoard::WHITE, vtx);
}
it = m_properties.find("PL");
if (it != m_properties.end()) {
std::string who = it->second;
if (who == "W") {
m_state.set_to_move(FastBoard::WHITE);
} else if (who == "B") {
m_state.set_to_move(FastBoard::BLACK);
}
}
// now for all children play out the moves
for (auto& child_state : m_children) {
// propagate state
child_state.copy_state(*this);
// XXX: maybe move this to the recursive call
// get move for side to move
int move = child_state.get_move(m_state.get_to_move());
if (move != EOT) {
child_state.apply_move(move);
}
child_state.populate_states();
}
}
void SGFTree::copy_state(const SGFTree& tree) {
m_initialized = tree.m_initialized;
m_state = tree.m_state;
}
void SGFTree::apply_move(int color, int move) {
if (move != FastBoard::PASS && move != FastBoard::RESIGN) {
int curr_sq = m_state.board.get_square(move);
if (curr_sq == !color || curr_sq == FastBoard::INVAL) {
throw std::runtime_error("Illegal move");
}
// Playing on an occupied square is legal in SGF setup,
// but we can't really handle it. So just ignore and hope that works.
if (curr_sq == color) {
return;
}
assert(curr_sq == FastBoard::EMPTY);
}
m_state.play_move(color, move);
}
void SGFTree::apply_move(int move) {
int color = m_state.get_to_move();
apply_move(color, move);
}
void SGFTree::add_property(std::string property, std::string value) {
m_properties.emplace(property, value);
}
SGFTree * SGFTree::add_child() {
// first allocation is better small
if (m_children.size() == 0) {
m_children.reserve(1);
}
m_children.emplace_back();
return &(m_children.back());
}
int SGFTree::string_to_vertex(const std::string& movestring) const {
if (movestring.size() == 0) {
return FastBoard::PASS;
}
if (m_state.board.get_boardsize() <= 19) {
if (movestring == "tt") {
return FastBoard::PASS;
}
}
int bsize = m_state.board.get_boardsize();
char c1 = movestring[0];
char c2 = movestring[1];
int cc1;
int cc2;
if (c1 >= 'A' && c1 <= 'Z') {
cc1 = 26 + c1 - 'A';
} else {
cc1 = c1 - 'a';
}
if (c2 >= 'A' && c2 <= 'Z') {
cc2 = bsize - 26 - (c2 - 'A') - 1;
} else {
cc2 = bsize - (c2 - 'a') - 1;
}
// catch illegal SGF
if (cc1 < 0 || cc1 >= bsize
|| cc2 < 0 || cc2 >= bsize) {
throw std::runtime_error("Illegal SGF move");
}
int vtx = m_state.board.get_vertex(cc1, cc2);
return vtx;
}
int SGFTree::get_move(int tomove) {
std::string movestring;
if (tomove == FastBoard::BLACK) {
movestring = "B";
} else {
movestring = "W";
}
PropertyMap::iterator it;
it = m_properties.find(movestring);
if (it != m_properties.end()) {
std::string movestring = it->second;
return string_to_vertex(movestring);
}
return SGFTree::EOT;
}
FastBoard::square_t SGFTree::get_winner() {
return m_winner;
}
std::vector<int> SGFTree::get_mainline() {
std::vector<int> moves;
SGFTree * link = this;
int tomove = link->m_state.get_to_move();
link = link->get_child(0);
while (link != NULL) {
int move = link->get_move(tomove);
if (move != SGFTree::EOT) {
moves.push_back(move);
}
tomove = !tomove;
link = link->get_child(0);
}
return moves;
}
std::string SGFTree::state_to_string(GameState * pstate, int compcolor) {
std::unique_ptr<GameState> state(new GameState);
// make a working copy
*state = *pstate;
std::string header;
std::string moves;
float komi = state->get_komi();
int size = state->board.get_boardsize();
time_t now;
time(&now);
char timestr[sizeof "2017-10-16"];
strftime(timestr, sizeof timestr, "%F", localtime(&now));
header.append("(;GM[1]FF[4]RU[Chinese]");
header.append("DT[" + std::string(timestr) + "]");
header.append("SZ[" + std::to_string(size) + "]");
header.append("KM[" + str(boost::format("%.1f") % komi) + "]");
if (compcolor == FastBoard::WHITE) {
header.append("PW[Leela " + std::string(PROGRAM_VERSION) + "]");
header.append("PB[Human]");
} else {
header.append("PB[Leela " + std::string(PROGRAM_VERSION) + "]");
header.append("PW[Human]");
}
state->rewind();
// check handicap here (anchor point)
int handicap = 0;
std::string handicapstr;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int vertex = state->board.get_vertex(i, j);
int square = state->board.get_square(vertex);
if (square == FastBoard::BLACK) {
handicap++;
handicapstr.append("[" + state->board.move_to_text_sgf(vertex) + "]");
}
}
}
if (handicap > 0) {
header.append("HA[" + std::to_string(handicap) + "]");
moves.append("AB" + handicapstr);
}
moves.append("\n");
int counter = 0;
while (state->forward_move()) {
int move = state->get_last_move();
if (move == FastBoard::RESIGN) {
break;
}
std::string movestr = state->board.move_to_text_sgf(move);
if (state->get_to_move() == FastBoard::BLACK) {
moves.append(";W[" + movestr + "]");
} else {
moves.append(";B[" + movestr + "]");
}
if (++counter % 10 == 0) {
moves.append("\n");
}
}
if (state->get_last_move() != FastBoard::RESIGN) {
float score = state->final_score();
if (score > 0.0f) {
header.append("RE[B+" + str(boost::format("%.1f") % score) + "]");
} else {
header.append("RE[W+" + str(boost::format("%.1f") % -score) + "]");
}
} else {
// Last move was resign, so side to move won
if (state->get_to_move() == FastBoard::BLACK) {
header.append("RE[B+Resign]");
} else {
header.append("RE[W+Resign]");
}
}
std::string result(header);
result.append("\n");
result.append(moves);
result.append(")\n");
return result;
}