-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrax.cc
More file actions
1692 lines (1414 loc) · 46.2 KB
/
trax.cc
File metadata and controls
1692 lines (1414 loc) · 46.2 KB
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2016 Tetsui Ohkubo.
#include "./trax.h"
#include <gflags/gflags.h>
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <mutex> // NOLINT
#include <set>
#include <sstream>
#include <string>
#include <thread> // NOLINT
#include <utility>
#include "./timer.h"
DEFINE_bool(enable_pretty_dump, true,
"Position::Dump() will return pretty colored boards.");
DEFINE_bool(enable_strict_timer, true,
"Exit immediately if the searcher violates time constraint.");
DEFINE_bool(trax8x8, false, "Run as 8x8 Trax.");
DEFINE_string(player_id, "PE",
"Contest issued player ID.");
DEFINE_int32(thinking_time_ms, 1000,
"Thinking time in milliseconds.");
uint32_t Random() {
static uint32_t x = 123456789;
static uint32_t y = 362436069;
static uint32_t z = 521288629;
static uint32_t w = 88675123;
static std::mutex mutex;
uint32_t t;
std::lock_guard<std::mutex> lock(mutex);
t = x ^ (x << 11);
x = y; y = z; z = w;
return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
}
using NeighborKey = uint32_t;
// Encode neighboring pieces into key.
NeighborKey EncodeNeighborKey(int right, int top, int left, int bottom) {
return static_cast<NeighborKey>(
right + (top << 3) + (left << 6) + (bottom << 9));
}
// Table of possible piece kinds for the certain neighboring piece combination.
// Using this gives significant performance improvement on
// Position::GetPossiblePieces().
PieceSet g_possible_pieces_table[1 << 12];
// Should be called before Position::GetPossiblePieces().
void GeneratePossiblePiecesTable() {
std::fill(g_possible_pieces_table,
g_possible_pieces_table +
sizeof(g_possible_pieces_table) /
sizeof(g_possible_pieces_table[0]),
PieceSet());
for (int i_right = 0; i_right < NUM_PIECES; ++i_right) {
for (int j_top = 0; j_top < NUM_PIECES; ++j_top) {
for (int k_left = 0; k_left < NUM_PIECES; ++k_left) {
for (int l_bottom = 0; l_bottom < NUM_PIECES; ++l_bottom) {
PieceSet pieces;
if (i_right == PIECE_EMPTY &&
j_top == PIECE_EMPTY &&
k_left == PIECE_EMPTY &&
l_bottom == PIECE_EMPTY) {
// If all the neighboring pieces are empty then empty piece is
// the only legal piece.
pieces.set(PIECE_EMPTY);
} else {
const char *neighbors[4] = {
kPieceColors[i_right],
kPieceColors[j_top],
kPieceColors[k_left],
kPieceColors[l_bottom]
};
// Exclude empty piece for this loop.
for (int m_candidate = 1; m_candidate< NUM_PIECES; ++m_candidate) {
const char *candidate = kPieceColors[m_candidate];
bool valid = true;
for (int n = 0; n < 4; ++n) {
// If the neighboring cell isn't empty,
// and the color of the shared edges are different,
// then the candidate is invalid piece placement.
if (neighbors[n][0] != '_' &&
candidate[n] != neighbors[n][(n + 2) & 3]) {
valid = false;
break;
}
}
if (valid) {
pieces.set(m_candidate);
}
}
// If it is possible to place at least one kind of non-empty pieces
// then it would also legal to remain empty.
// Otherwise, the placement is illegal at all.
if (pieces.count() > 0) {
pieces.set(PIECE_EMPTY);
}
}
if (pieces.count() > 0) {
g_possible_pieces_table[
EncodeNeighborKey(i_right, j_top, k_left, l_bottom)] = pieces;
}
}
}
}
}
}
// Table of track directions that come into pieces.
// Although using this makes code simpler, the performance improvement on
// Position::TraceVictoryLineOrLoop() is slighter.
int g_track_direction_table[NUM_PIECES][4];
// Should be called before Position::TraceVictoryLineOrLoop().
void GenerateTrackDirectionTable() {
// Skip empty piece.
for (int i = 1; i < NUM_PIECES; ++i) {
// Loop for direction that the track come from.
for (int j = 0; j < 4; ++j) {
// Find the direction that the track goes to.
for (int k = 0; k < 4; ++k) {
// Two edges have the same color.
if (j != k && kPieceColors[i][j] == kPieceColors[i][k]) {
g_track_direction_table[i][j] = k;
}
}
}
}
}
bool g_forced_play_table[1 << 12];
// Should be called before Position::FillForcedPieces().
void GenerateForcedPlayTable() {
std::fill(g_forced_play_table,
g_forced_play_table +
sizeof(g_forced_play_table) /
sizeof(g_forced_play_table[0]),
false);
for (int i_right = 0; i_right < NUM_PIECES; ++i_right) {
for (int j_top = 0; j_top < NUM_PIECES; ++j_top) {
for (int k_left = 0; k_left < NUM_PIECES; ++k_left) {
for (int l_bottom = 0; l_bottom < NUM_PIECES; ++l_bottom) {
NeighborKey key = EncodeNeighborKey(
i_right, j_top, k_left, l_bottom);
PieceSet pieces = g_possible_pieces_table[key];
// No possible piece including empty one for the location.
// The position is invalid.
if (pieces.count() == 0) {
continue;
}
// Exclude empty piece.
pieces.reset(PIECE_EMPTY);
if (pieces.count() != 1) {
// If more than one piece kind is possible, forced play
// does not happen.
continue;
}
int red_count = 0;
int white_count = 0;
int neighbors[4] = {i_right, j_top, k_left, l_bottom};
for (int m = 0; m < 4; ++m) {
const int neighbor = neighbors[m];
if (neighbor == PIECE_EMPTY) {
continue;
}
if (kPieceColors[neighbor][(m + 2) & 3] == 'R') {
++red_count;
} else if (kPieceColors[neighbor][(m + 2) & 3] == 'W') {
++white_count;
}
}
if (red_count >= 2 || white_count >= 2) {
g_forced_play_table[key] = true;
}
}
}
}
}
}
Move::Move(const std::string& trax_notation,
const Position& previous_position)
: x(0), y(0), piece(PIECE_EMPTY) {
if (!Parse(trax_notation, previous_position)) {
std::cerr
<< "cannot parse trax notation \"" << trax_notation << "\"" << std::endl;
exit(EXIT_FAILURE);
}
}
bool Move::Parse(const std::string& trax_notation,
const Position& previous_position) {
auto it = trax_notation.begin();
if (it == trax_notation.end()) {
return false;
}
if (*it == '@') {
x = -1;
++it;
} else {
// This way of encoding is called Bijective base-26.
// http://stackoverflow.com/a/1004651/6583019
// Specified in: http://fpt.massey.ac.nz/design_competition_rules.asp
x = 0;
while (it != trax_notation.end() && 'A' <= *it && *it <= 'Z') {
x *= static_cast<int>('Z' - 'A') + 1;
x += static_cast<int>(*it - 'A') + 1;
++it;
}
--x;
}
if (it == trax_notation.end()) {
return false;
}
y = 0;
while (it != trax_notation.end() && '0' <= *it && *it <= '9') {
y *= 10;
y += *it - '0';
++it;
}
--y;
if (it == trax_notation.end()) {
return false;
}
// If this is the first move, then the color is limited.
if (previous_position.max_x() == 0 && previous_position.max_y() == 0) {
if (*it == '/') {
piece = PIECE_RWWR;
} else if (*it == '+') {
piece = PIECE_RWRW;
} else {
return false;
}
} else {
if (previous_position.at(x, y) != PIECE_EMPTY) {
// Trying to place on already placed coordinate.
return false;
}
PieceSet candidates = previous_position.GetPossiblePieces(x, y);
// Exclude EMPTY piece for added piece candidates.
candidates.reset(PIECE_EMPTY);
piece = PIECE_EMPTY;
for (int i = 0; i < NUM_PIECES; ++i) {
if (kPieceNotations[i] == *it && candidates.test(i)) {
piece = static_cast<Piece>(i);
break;
}
}
if (piece == PIECE_EMPTY) {
return false;
}
}
++it;
if (it != trax_notation.end()) {
return false;
}
return true;
}
std::string Move::notation() const {
std::stringstream trax_notation;
if (x == -1) {
trax_notation << '@';
} else {
// This way of encoding is called Bijective base-26.
// https://github.com/alexfeseto/hexavigesimal
// Specified in: http://fpt.massey.ac.nz/design_competition_rules.asp
std::string columns;
int num = x + 1;
while (num > 0) {
--num;
columns += static_cast<char>(num % ('Z' - 'A' + 1) + 'A');
num /= 'Z' - 'A' + 1;
}
std::reverse(columns.begin(), columns.end());
trax_notation << columns;
}
trax_notation << y + 1;
trax_notation << kPieceNotations[piece];
return trax_notation.str();
}
std::vector<Move> Position::GenerateMoves() const {
std::vector<Move> moves;
moves.reserve(32);
if (finished()) {
// This is a finished game.
return moves;
}
// If this is the first step then they are only valid moves.
if (max_x_ == 0 && max_y_ == 0) {
moves.emplace_back("@0/", *this);
moves.emplace_back("@0+", *this);
return moves;
}
// TODO(tetsui): This is very naive implementation but maybe we can
// progressively update the possible move list.
// (such as using UnionFind tree?)
for (int i_x = -1; i_x <= max_x_; ++i_x) {
for (int j_y = -1; j_y <= max_y_; ++j_y) {
if (at(i_x, j_y) != PIECE_EMPTY) {
continue;
}
if (FLAGS_trax8x8 &&
((max_x_ >= 8 && (i_x == -1 || i_x == max_x_)) ||
(max_y_ >= 8 && (j_y == -1 || j_y == max_y_)))) {
// Invalid move for 8x8 Trax.
continue;
}
PieceSet pieces = GetPossiblePieces(i_x, j_y);
// Exclude EMPTY piece for added piece candidates.
pieces.reset(PIECE_EMPTY);
for (int k = 0; k < NUM_PIECES; ++k) {
if (pieces.test(k)) {
moves.emplace_back(i_x, j_y, static_cast<Piece>(k));
}
}
}
}
return moves;
}
bool Position::DoMove(Move move, Position *next_position) const {
assert(next_position != nullptr);
assert(next_position != this);
assert(move.piece != PIECE_EMPTY);
if (FLAGS_trax8x8 &&
((max_x_ >= 8 && (move.x == -1 || move.x == max_x_)) ||
(max_y_ >= 8 && (move.y == -1 || move.y == max_y_)))) {
// Invalid move for 8x8 Trax.
return false;
}
if (finished()) {
// Every move after the game finished is illegal.
return false;
}
// Be aware of the memory leak!
delete[] next_position->board_;
next_position->board_ = nullptr;
// Flip the side to move.
next_position->red_to_move_ = !red_to_move_;
// Extend the field width and height if it is required by the move.
next_position->max_x_ = max_x_;
next_position->max_y_ = max_y_;
int offset_x = 0, offset_y = 0;
if (move.x < 0) {
++offset_x;
++next_position->max_x_;
} else if (move.x >= max_x_) {
++next_position->max_x_;
}
if (move.y < 0) {
++offset_y;
++next_position->max_y_;
} else if (move.y >= max_y_) {
++next_position->max_y_;
}
// Sentinels with its depth 2 is used here.
next_position->board_ = new Piece[next_position->board_size()];
if (max_x_ == next_position->max_x_ && max_y_ == next_position->max_y_) {
// Hope it will be vectorized :)
std::copy(board_, board_ + board_size(), next_position->board_);
} else {
// Fill the board with empty pieces.
std::fill(next_position->board_,
next_position->board_ + next_position->board_size(),
PIECE_EMPTY);
// Copy the board (if exists).
if (board_ != nullptr) {
for (int i_x = 0; i_x < max_x_; ++i_x) {
for (int j_y = 0; j_y < max_y_; ++j_y) {
next_position->at(i_x + offset_x, j_y + offset_y) = at(i_x, j_y);
}
}
}
}
// Don't forget to add the new piece!
next_position->at(move.x + offset_x, move.y + offset_y) = move.piece;
// The move is illegal when forced play is applied.
if (!next_position->FillForcedPieces(move.x + offset_x,
move.y + offset_y)) {
return false;
}
return true;
}
PieceSet Position::GetPossiblePieces(int x, int y) const {
assert(at(x, y) == PIECE_EMPTY);
NeighborKey key = EncodeNeighborKey(
at(x + kDx[0], y + kDy[0]),
at(x + kDx[1], y + kDy[1]),
at(x + kDx[2], y + kDy[2]),
at(x + kDx[3], y + kDy[3]));
return g_possible_pieces_table[key];
}
void Position::EnumerateLines(std::vector<Line> *lines) const {
lines->clear();
if (finished()) {
return;
}
// Clockwisely traced external facing edges.
std::map<std::pair<int, int>, int> indexed_edges;
int total_index;
// Set of <endpoint_a, endpoint_b, is_red> to keep traced lines unique.
std::set<std::tuple<std::pair<int, int>, std::pair<int, int>, bool>> traced;
// Iterate over cells with external facing edge.
for (int i_x = 0; i_x < max_x_; ++i_x) {
for (int j_y = 0; j_y < max_y_; ++j_y) {
if (at(i_x, j_y) == PIECE_EMPTY) {
continue;
}
bool is_edge = false;
for (int k = 0; k < 4; ++k) {
const int nx = i_x + kDx[k];
const int ny = j_y + kDy[k];
if (at(nx, ny) == PIECE_EMPTY) {
// The cell at <i_x, j_y> has external facing edge.
is_edge = true;
// Generate indexed_edges if not yet generated.
if (indexed_edges.empty()) {
TraceAndIndexEdges(nx, ny, &indexed_edges, &total_index);
}
break;
}
}
// Nothing to do if the cell does not have external facing edge.
if (!is_edge) {
continue;
}
// Trace line from the cell for each color.
for (int k_red = 0; k_red < 2; ++k_red) {
bool is_red = static_cast<bool>(k_red);
std::pair<int, int> endpoint_a, endpoint_b;
// Trace the line.
TraceLineToEndpoints(i_x, j_y, is_red, &endpoint_a, &endpoint_b);
if (endpoint_a > endpoint_b) {
std::swap(endpoint_a, endpoint_b);
}
// Skip to add to list if already added.
if (traced.count(make_tuple(endpoint_a, endpoint_b, is_red))) {
continue;
}
traced.insert(make_tuple(endpoint_a, endpoint_b, is_red));
if (!indexed_edges.count(endpoint_a) ||
!indexed_edges.count(endpoint_b)) {
// It is possible that the board has empty region inside.
// We ignore these cases for now.
continue;
}
Line line(endpoint_a, endpoint_b, is_red, *this,
indexed_edges, total_index);
// Add to the list.
lines->push_back(line);
}
}
}
#if 0
// Map endpoints with clockwise index to the line index by the colors.
std::map<int, int> endpoints_by_color[2];
for (int i = 0; i < lines->size(); ++i) {
Line& line = (*lines)[i];
const bool is_red = line.is_red;
endpoints_by_color[is_red][line.endpoint_index_a] = i;
endpoints_by_color[is_red][line.endpoint_index_b] = i;
}
// Fill Line.is_inner by referencing neighboring endpoints.
for (int i = 0; i < lines->size(); ++i) {
Line& line = (*lines)[i];
const bool is_red = line.is_red;
// Just tracing from endpoint_a is sufficient.
auto it = endpoints_by_color[is_red].find(line.endpoint_index_a);
assert(it != endpoints_by_color[is_red].end());
auto previous_it = it;
if (previous_it == endpoints_by_color[is_red].begin()) {
previous_it = endpoints_by_color[is_red].end();
}
--previous_it;
auto next_it = it;
++next_it;
if (next_it == endpoints_by_color[is_red].end()) {
next_it = endpoints_by_color[is_red].begin();
}
// If more than one of its neighboring points is the line's,
// it's not inner line.
if (previous_it->second == i || next_it->second == i) {
line.is_inner = false;
} else {
line.is_inner = true;
}
}
// Fill loop_distances for lines with is_inner == true.
for (Line& line : *lines) {
if (!line.is_inner) {
continue;
}
const bool is_red = line.is_red;
auto it_a = endpoints_by_color[is_red].find(line.endpoint_index_a);
auto it_b = endpoints_by_color[is_red].find(line.endpoint_index_b);
assert(it_a != endpoints_by_color[is_red].end());
assert(it_b != endpoints_by_color[is_red].end());
// Calculate loop distances.
// It moves to opposite directions for different endpoints so that
// they form possible loops.
// One inner line can form two loops so we first try
// clockwise-anticlockwise for endpoint_a, endpoint_b, then flip to
// anticlockwise-clockwise for endpoint_a, endpoint_b.
for (int i = 0; i < 2; ++i) {
int loop_distance = 0;
auto it = it_a;
while (true) {
auto forward_it = it;
++forward_it;
if (forward_it == endpoints_by_color[is_red].end()) {
forward_it = endpoints_by_color[is_red].begin();
}
if (it->second != forward_it->second) {
loop_distance += abs(forward_it->first - it->first);
}
assert(forward_it->second < lines->size());
it = forward_it;
if ((*lines)[it->second].is_inner) {
break;
}
}
// If reached endpoint is same as endpoint_b, you don't have to trace
// again. Otherwise, it would be double counted.
if (it != it_b) {
it = it_b;
while (true) {
auto backward_it = it;
if (it == endpoints_by_color[is_red].begin()) {
backward_it = endpoints_by_color[is_red].end();
}
--backward_it;
if (it->second != backward_it->second) {
loop_distance += abs(it->first - backward_it->first);
}
assert(backward_it->second < lines->size());
it = backward_it;
if ((*lines)[it->second].is_inner) {
break;
}
}
}
line.loop_distances[i] = loop_distance;
swap(it_a, it_b);
}
}
#endif
}
void Position::Dump() const {
if (board_ != nullptr) {
if (FLAGS_enable_pretty_dump) {
{
std::vector<std::string> line(3, " ");
for (int i_x = -1; i_x <= max_x_; ++i_x) {
line[0] += " ";
line[1] += " ";
line[2] += " ";
if (i_x == -1) {
line[2] += "@";
} else {
if (i_x + 'A' > 'Z') {
line[2] += " ";
} else {
line[2] += i_x + 'A';
}
}
line[2] += " ";
}
for (int i = 0; i < 3; ++i) {
std::cerr << line[i] << std::endl;
}
}
for (int i_y = -1; i_y <= max_y_; ++i_y) {
std::vector<std::string> line(3);
line[0] += " ";
std::stringstream num;
num << std::setw(3) << std::right << i_y + 1;
line[1] += num.str();
line[2] += " ";
for (int j_x = -1; j_x <= max_x_; ++j_x) {
Piece piece = at(j_x, i_y);
assert(
at(j_x, i_y) <
sizeof(kPieceNotations) / sizeof(kPieceNotations[0]));
for (int k = 0; k < 3; ++k) {
line[k] += kLargePieceNotations[piece][k];
}
}
for (int k = 0; k < 3; ++k) {
std::cerr << line[k] << std::endl;
}
}
} else {
for (int i_y = -1; i_y <= max_y_; ++i_y) {
for (int j_x = -1; j_x <= max_x_; ++j_x) {
assert(
at(j_x, i_y) <
sizeof(kPieceNotations) / sizeof(kPieceNotations[0]));
std::cerr << kPieceNotations[at(j_x, i_y)];
}
std::cerr << std::endl;
}
}
}
std::cerr << "red_to_move = " << (red_to_move_ ? "true" : "false");
if (finished()) {
std::cerr << ", finished = true, winner = ";
if (winner() > 0) {
std::cerr << "red";
} else if (winner() < 0) {
std::cerr << "white";
} else {
std::cerr << "draw";
}
std::cerr << ", winning_reason = ";
switch (winning_reason()) {
case WINNING_REASON_UNKNOWN:
std::cerr << "UNKNOWN";
break;
case WINNING_REASON_LOOP:
std::cerr << "LOOP";
break;
case WINNING_REASON_LINE:
std::cerr << "LINE";
break;
case WINNING_REASON_FULL:
std::cerr << "FULL";
break;
case WINNING_REASON_RESIGN:
std::cerr << "RESIGN";
break;
}
std::cerr << std::endl;
} else {
std::cerr << ", finished = false";
}
std::cerr << std::endl;
}
bool Position::FillForcedPieces(int move_x, int move_y) {
// Winner flags can be filled by performing checking from some checkpoints,
// but we have to do them after all the forced plays are done,
// due to some corner cases.
//
// Example: the left side and the right side is connected by victory line,
// but suddenly forced play filled the rightmost cells.
//
// Thus, we have to enumerate all of them first.
std::pair<int8_t, int8_t> winner_flag_checkpoints[64];
int num_checkpoints = 0;
winner_flag_checkpoints[num_checkpoints].first = move_x;
winner_flag_checkpoints[num_checkpoints].second = move_y;
++num_checkpoints;
std::pair<int8_t, int8_t> possible_queue[64];
int queue_begin = 0;
int queue_end = 0;
// Add neighboring cells to the queue as forced play candidates.
for (int j = 0; j < 4; ++j) {
const int nx = move_x + kDx[j];
const int ny = move_y + kDy[j];
// Forced plays should not happen outside the current board region.
// Therefore checking inside [0, max_x) [0, max_y) is enough.
if (nx < 0 || ny < 0 || nx >= max_x_ || ny >= max_y_) {
continue;
}
if (at(nx, ny) == PIECE_EMPTY) {
assert(
queue_end + 1 < sizeof(possible_queue) / sizeof(possible_queue[0]));
possible_queue[queue_end].first = nx;
possible_queue[queue_end].second = ny;
++queue_end;
}
}
// Loop while chain of forced plays is happening.
// while (!possible_queue.empty()) {
while (queue_begin < queue_end) {
const int x = possible_queue[queue_begin].first;
const int y = possible_queue[queue_begin].second;
++queue_begin;
// A place may be filled after the coordinate is pushed to the queue,
// before the coordinate is popped.
if (at(x, y) != PIECE_EMPTY) {
continue;
}
const PieceSet pieces = GetPossiblePieces(x, y);
// No possible piece including empty one for the location.
// The whole position is invalid.
if (pieces.count() == 0) {
return false;
}
// This is forced play.
const bool is_forced_play = g_forced_play_table[
EncodeNeighborKey(
at(x + kDx[0], y + kDy[0]),
at(x + kDx[1], y + kDy[1]),
at(x + kDx[2], y + kDy[2]),
at(x + kDx[3], y + kDy[3]))];
if (!is_forced_play) {
continue;
}
assert(pieces.count() == 2);
for (int i = 1; i < NUM_PIECES; ++i) {
if (pieces.test(i)) {
assert(at(x, y) == PIECE_EMPTY);
// Place the forced piece.
at(x, y) = static_cast<Piece>(i);
break;
}
}
// Add the coordinate to winner flag checkpoints, because
// it may constitute new loop or victory line.
assert(
num_checkpoints + 1 <
sizeof(winner_flag_checkpoints) / sizeof(winner_flag_checkpoints[0]));
winner_flag_checkpoints[num_checkpoints].first = x;
winner_flag_checkpoints[num_checkpoints].second = y;
++num_checkpoints;
// Add neighboring cells to the queue as new forced play candidates.
for (int j = 0; j < 4; ++j) {
const int nx = x + kDx[j];
const int ny = y + kDy[j];
// Forced plays should not happen outside the current board region.
// Therefore checking inside [0, max_x) [0, max_y) is enough.
if (nx < 0 || ny < 0 || nx >= max_x_ || ny >= max_y_) {
continue;
}
if (at(nx, ny) == PIECE_EMPTY) {
assert(
queue_end + 1 <
sizeof(possible_queue) / sizeof(possible_queue[0]));
possible_queue[queue_end].first = nx;
possible_queue[queue_end].second = ny;
++queue_end;
}
}
}
// Fill winner flags based on the position state.
for (int i = 0; i < num_checkpoints; ++i) {
FillWinnerFlags(winner_flag_checkpoints[i].first,
winner_flag_checkpoints[i].second);
}
if (red_winner_ && white_winner_) {
// This is a win for the player who made the last move.
// See http://www.traxgame.com/about_faq.php for detail.
if (red_to_move_) {
red_winner_ = false;
} else {
white_winner_ = false;
}
}
if (FLAGS_trax8x8 && !finished() && max_x_ >= 8 && max_y_ >= 8) {
// For 8x8 Trax, if region is filled without any victory lines or loops,
// the game is considered draw.
bool all_filled = true;
for (int i_x = 0; i_x < max_x_; ++i_x) {
for (int j_y = 0; j_y < max_y_; ++j_y) {
if (at(i_x, j_y) == PIECE_EMPTY) {
all_filled = false;
break;
}
}
if (all_filled) {
break;
}
}
if (all_filled) {
red_winner_ = true;
white_winner_ = true;
red_winning_reason_ = WINNING_REASON_FULL;
white_winning_reason_ = WINNING_REASON_FULL;
}
}
return true;
}
void Position::FillWinnerFlags(int x, int y) {
assert(at(x, y) != PIECE_EMPTY);
WinningReason reason;
if (!red_winner_ &&
(reason = TraceVictoryLineOrLoop(x, y, /* red_line = */ true)) !=
WINNING_REASON_UNKNOWN) {
red_winner_ = true;
red_winning_reason_ = reason;
}
if (!white_winner_ &&
(reason = TraceVictoryLineOrLoop(x, y, /* red_line = */ false)) !=
WINNING_REASON_UNKNOWN) {
white_winner_ = true;
white_winning_reason_ = reason;
}
}
WinningReason Position::TraceVictoryLineOrLoop(int start_x, int start_y,
bool red_line) {
assert(at(start_x, start_y) != PIECE_EMPTY);
assert(0 <= start_x && start_x < max_x_ && 0 <= start_y && start_y < max_y_);
const char traced_color = red_line ? 'R' : 'W';
// Omit edge hit detection for most of the boards.
if (max_x_ < 8 && max_y_ < 8) {
// Traces line to two directions with the edges of the given color.
for (int i = 0; i < 4; ++i) {
if (kPieceColors[at(start_x, start_y)][i] != traced_color) {
// continue if the i-th edge color of the starting piece is
// not trace_color.
continue;
}
int x = start_x + kDx[i];
int y = start_y + kDy[i];
int previous_direction = (i + 2) & 3;
assert(-2 <= x && x < max_x_ + 2 && -2 <= y && y < max_y_ + 2);
// Trace the line until it hits an empty cell.
while (at(x, y) != PIECE_EMPTY) {
if (x == start_x && y == start_y) {
// This is loop.
return WINNING_REASON_LOOP;
}
assert(0 <= x && x < max_x_ && 0 <= y && y < max_y_);
// Continue tracing the line.
const int next_direction =
g_track_direction_table[at(x, y)][previous_direction];
x += kDx[next_direction];
y += kDy[next_direction];
previous_direction = (next_direction + 2) & 3;
}
}
return WINNING_REASON_UNKNOWN;
}
// See also: definition of kDx[] and kDy[]
// x y x y
const int edges[4] = {max_x_ - 1, 0, 0, max_y_ - 1};
// hits becomes true if the line *hits* the edge of the board,
// which is necessary for checking victory line.
bool hits[4] = {false};
// Traces line to two directions with the edges of the given color.
for (int i = 0; i < 4; ++i) {
if (kPieceColors[at(start_x, start_y)][i] != traced_color) {
// continue if the i-th edge color of the starting piece is
// not trace_color.
continue;
}
{
const int xy[2] = {start_x, start_y};
if (edges[i] == xy[i & 1]) {
// You hit the edge at the beggining.
hits[i] = true;
}
}