-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.c
1393 lines (1246 loc) · 56.1 KB
/
game.c
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
#include "game.h"
#include "gameconstants.h"
#include "misc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*************** Rule Related Helper Function Declarations ***************/
static inline int8_t layout_at(const int8_t *layout, int8_t row, int8_t col);
static inline bool in_scope(scope_t scope, int8_t row, int8_t col);
static inline bool in_board(int8_t row, int8_t col);
static inline bool is_empty(const int8_t *layout, int8_t row, int8_t col);
static inline bool is_red(int8_t pieceIdx);
static inline bool is_black(int8_t pieceIdx);
static inline bool can_capture(board_t *board, int8_t row, int8_t col);
static inline bool is_opponent_king(board_t *board, int8_t row, int8_t col);
static bool flying_general_possible(const board_t *board);
static bool is_legal_pos(board_t *board);
static uint8_t num_moves(board_t *board, int8_t idx, bool testOnly);
static bool is_valid_move(board_t *board, int8_t idx, int8_t i, int8_t j);
/************* End Rule Related Helper Function Declarations *************/
/************** Move Related Helper Function Declarations ****************/
static void move_piece(board_t *board, int8_t destRow, int8_t destCol,
int8_t srcRow, int8_t srcCol, int8_t replace);
static void move_piece_append(ext_pos_array_t *children, board_t *board,
int8_t destRow, int8_t destCol,
int8_t srcRow, int8_t srcCol);
static void undomove_piece_append(pos_array_t *parents,
const char *tier, board_t *board,
int8_t destRow, int8_t destCol,
int8_t srcRow, int8_t srcCol,
int8_t replace);
static bool add_children(ext_pos_array_t *children, board_t *board, int8_t idx);
static void add_parents(pos_array_t *parents, const char *tier,
board_t *board, int8_t row, int8_t col, int8_t revIdx);
/************ End Move Related Helper Function Declarations **************/
/************** Hash Related Helper Function Declarations ****************/
static uint64_t *hash_to_steps(const char *tier, uint64_t hash);
static uint64_t steps_to_hash(const char *tier, const uint64_t *steps);
static bool steps_to_board(board_t *board, const char *tier, uint64_t *steps);
static uint64_t *board_to_steps(const char *tier, const board_t *board);
static uint64_t combiCount(const uint8_t *counts, uint8_t numPieces);
static uint64_t hash_cruncher(const int8_t *layout, const uint8_t *slots, uint8_t size,
int8_t pieceMin, int8_t pieceMax,
uint8_t *rems, uint8_t numPieces);
static void hash_uncruncher(uint64_t hash, board_t *board, uint8_t *piecesSizes,
uint8_t *slots, uint8_t numSlots,
const int8_t *tokens, uint8_t *rems, uint8_t numTokens);
static void board_to_sa_position(sa_position_t *pos, board_t *board);
/************ End Hash Related Helper Function Declarations **************/
/**************************** Game Utilities *****************************/
/**
* @brief Returns the number of legal child positions of HASH in TIER.
* Returns ILLEGAL_NUM_CHILD_POS if the given HASH is illegal in TIER.
* Returns ILLEGAL_NUM_CHILD_POS_OOM if heap memory runs out during
* this function call. BOARD is guaranteed to be reset to empty state
* after call to this function.
* @param tier: tier of the parent position.
* @param hash: hash of the parent position inside TIER.
* @param board: this global board should be pre-allocated and empty
* initialized by the caller.
*/
uint8_t game_num_child_pos(const char *tier, uint64_t hash, board_t *board) {
uint8_t count = 0, nmoves;
if (!game_unhash(board, tier, hash)) return ILLEGAL_NUM_CHILD_POS_OOM;
if (!board->valid || flying_general_possible(board)) {
clear_board(board);
return ILLEGAL_NUM_CHILD_POS;
}
for (int8_t i = board->blackTurn*BOARD_PIECES_OFFSET;
board->pieces[i].token != BOARD_EMPTY_CELL; ++i) {
nmoves = num_moves(board, i, false);
if (nmoves == ILLEGAL_NUM_MOVES) {
clear_board(board);
return ILLEGAL_NUM_CHILD_POS;
}
count += nmoves;
}
clear_board(board);
return count;
}
ext_pos_array_t game_get_children(const char *tier, uint64_t hash) {
ext_pos_array_t children;
board_t board;
memset(&children, 0, sizeof(children));
game_init_board(&board);
if (!game_unhash(&board, tier, hash)) exit(1);
if (!board.valid || flying_general_possible(&board)) {
children.size = ILLEGAL_POSITION_ARRAY_SIZE;
return children;
}
children.array = (sa_position_t*)safe_malloc(NUM_MOVES_MAX * sizeof(sa_position_t));
for (int8_t i = board.blackTurn*BOARD_PIECES_OFFSET;
board.pieces[i].token != BOARD_EMPTY_CELL; ++i) {
if (!add_children(&children, &board, i)) {
free(children.array); children.array = NULL;
children.size = ILLEGAL_POSITION_ARRAY_SIZE;
return children;
}
}
return children;
}
/**
* @brief Returns a PositionArray that contains all the parent
* positions of position HASH in tier TIER that satisfies the
* TierChange required by CHANGE. A TierChange object specifies
* which type of piece is captured and/or the row number of the
* pawn that moved forward and is generated with child tiers.
* By specifying the tier change, we restrict the tier in which
* the parent position can be in. This function assumes that
* the given TIER and HASH are both valid.
* @param tier: tier of the child position.
* @param hash: hash of the child position.
* @param change: tier change from parent tier (the tier we
* wish to return to) to child tier (the current TIER.)
* @param board: this global board should be pre-allocated and empty
* initialized by the caller.
* @return A PositionArray which contains a pointer to an array of
* parent position hashes and the size of that array. If OOM,
* the size of the array is set to ILLEGAL_POSITION_ARRAY_SIZE_OOM
* and the array pointer is set to NULL. Otherwise, the array is
* malloced and should be freed by the caller of this function.
*/
pos_array_t game_get_parents(const char *tier, uint64_t hash, const char *parentTier,
tier_change_t change, board_t *board) {
pos_array_t parents;
memset(&parents, 0, sizeof(parents));
if (!game_unhash(board, tier, hash)) {
parents.size = ILLEGAL_POSITION_ARRAY_SIZE_OOM;
goto _bailout;
}
/* Return empty parents array if turn does not match tier change. */
if ((!board->blackTurn && (is_black(change.captureIdx) || is_red(change.pawnIdx))) ||
(board->blackTurn && (is_red(change.captureIdx) || is_black(change.pawnIdx)))) {
goto _bailout;
}
bool pbwd = (change.pawnIdx != INVALID_IDX);
bool revBlackP = (change.captureIdx == BLACK_P_IDX);
bool revRedP = (change.captureIdx == RED_P_IDX);
bool revp = revRedP || revBlackP;
bool revOK;
int8_t row, col, token, destRow;
parents.array = (uint64_t*)malloc(NUM_MOVES_MAX * sizeof(uint64_t));
if (!parents.array) {
parents.size = ILLEGAL_POSITION_ARRAY_SIZE_OOM;
goto _bailout;
}
/* Convert row number for black pawns. */
if (change.captureIdx == BLACK_P_IDX) change.captureRow = 9 - change.captureRow;
if (change.pawnIdx == BLACK_P_IDX) change.pawnRow = 9 - change.pawnRow;
for (int8_t i = (!board->blackTurn)*BOARD_PIECES_OFFSET;
board->pieces[i].token != BOARD_EMPTY_CELL; ++i) {
token = board->pieces[i].token;
row = board->pieces[i].row;
col = board->pieces[i].col;
destRow = row - 1 + ((token == BOARD_RED_PAWN) << 1); // row+1 if red, row-1 if black.
revOK = !revp || (row == change.captureRow);
if (!pbwd && validSlotLookup[change.captureIdx + 2][row][col] && revOK) {
/* No backward pawn move:
1. If no reverse capture, validSlotLookup returns true for
blank space and we can always add parents;
2. If reverse capturing non-pawn pieces, add parents if src
slot is valid for the piece put back;
3. If reverse capturing pawns, add parents if slot and row
number are both valid. */
add_parents(&parents, parentTier, board, row, col, change.captureIdx);
} else if (pbwd && (token == change.pawnIdx) && (row == change.pawnRow) &&
validSlotLookup[token + 2][destRow][col] && is_empty(board->layout, destRow, col) &&
validSlotLookup[change.captureIdx + 2][row][col] && revOK) {
/* Move pawn backward: always need to check if token is the pawn to move and
the destination is a valid position where the pawn can reach. Then check
the same conditions as above. */
undomove_piece_append(&parents, parentTier, board, destRow, col,
row, col, change.captureIdx);
}
}
/* Check for illegal positions due to OOM in the array. */
for (uint8_t i = 0; i < parents.size; ++i) {
if (parents.array[i] == ILLEGAL_HASH) {
free(parents.array); parents.array = NULL;
parents.size = ILLEGAL_POSITION_ARRAY_SIZE_OOM;
break;
}
}
_bailout:
clear_board(board);
return parents;
}
inline bool game_is_black_turn(uint64_t hash) {
return (hash & 1);
}
/**
* @brief Returns the hash of BOARD in TIER. Returns ILLEGAL_HASH if fails
* to allocate space for intermediate steps.
*/
uint64_t game_hash(const char *tier, const board_t *board) {
uint64_t *steps = board_to_steps(tier, board);
uint64_t res = steps_to_hash(tier, steps);
free(steps);
return res;
}
// Assumes board->layout is pre-allocated and contains all BOARD_EMPTY_CELL.
/**
* @brief Unhashes TIER and HASH to BOARD, which is assumed to be empty
* and valid. If HASH is invalid for TIER, BOARD->valid is set to false.
* Returns true no OOM error occurs, false otherwise.
* @note A HASH is invalid if some pieces are overlapping.
*/
bool game_unhash(board_t *board, const char *tier, uint64_t hash) {
uint64_t *steps = hash_to_steps(tier, hash);
bool success = steps_to_board(board, tier, steps);
free(steps);
return success;
}
static void take_pieces_off_and_rotate(piece_t *pieces, int8_t *layout) {
for (int8_t i = 0; pieces[i].token != BOARD_EMPTY_CELL; ++i) {
layout[pieces[i].row*BOARD_COLS + pieces[i].col] = BOARD_EMPTY_CELL;
pieces[i].token ^= 1;
pieces[i].row = BOARD_ROWS - 1 - pieces[i].row;
pieces[i].col = BOARD_COLS - 1 - pieces[i].col;
}
}
static void place_pieces(piece_t *pieces, int8_t *layout) {
for (int8_t i = 0; pieces[i].token != BOARD_EMPTY_CELL; ++i) {
layout[pieces[i].row*BOARD_COLS + pieces[i].col] = pieces[i].token;
}
}
uint64_t game_get_noncanonical_hash(const char *canonicalTier, uint64_t canonicalHash,
const char *noncanonicalTier, board_t *board) {
game_unhash(board, canonicalTier, canonicalHash);
/* Take all pieces off the board, swap the color, and rotate by 180 degrees. */
take_pieces_off_and_rotate(board->pieces, board->layout);
take_pieces_off_and_rotate(board->pieces + BOARD_PIECES_OFFSET, board->layout);
piece_t tmp[16];
memcpy(tmp, board->pieces, 16*sizeof(piece_t));
memcpy(board->pieces, board->pieces + BOARD_PIECES_OFFSET, 16*sizeof(piece_t));
memcpy(board->pieces + BOARD_PIECES_OFFSET, tmp, 16*sizeof(piece_t));
/* Place the new set of pieces on the board. */
place_pieces(board->pieces, board->layout);
place_pieces(board->pieces + BOARD_PIECES_OFFSET, board->layout);
board->blackTurn = !board->blackTurn;
uint64_t res = game_hash(noncanonicalTier, board);
clear_board(board);
return res;
}
void game_init_board(board_t *board) {
memset(board->layout, BOARD_EMPTY_CELL, BOARD_SIZE);
for (uint8_t i = 0; i < 2*MAX_PIECES_EACH_SIDE + 2; ++i) {
board->pieces[i].token = BOARD_EMPTY_CELL;
}
}
static void clear_board_helper(piece_t *pieces, int8_t *layout) {
for (int8_t i = 0; pieces[i].token != BOARD_EMPTY_CELL; ++i) {
layout[pieces[i].row*BOARD_COLS + pieces[i].col] = BOARD_EMPTY_CELL;
}
pieces[0].token = BOARD_EMPTY_CELL;
}
void clear_board(board_t *board) {
clear_board_helper(board->pieces, board->layout);
clear_board_helper(board->pieces + BOARD_PIECES_OFFSET, board->layout);
}
/*************************** End Game Utilities ****************************/
/**************** Rule Related Helper Function Definitions *****************/
static inline int8_t layout_at(const int8_t *layout, int8_t row, int8_t col) {
return layout[row*BOARD_COLS + col];
}
static inline bool in_scope(scope_t scope, int8_t row, int8_t col) {
return row >= scope.rowMin && row <= scope.rowMax &&
col >= scope.colMin && col <= scope.colMax;
}
static inline bool in_board(int8_t row, int8_t col) {
return row >= 0 && row < BOARD_ROWS &&
col >= 0 && col < BOARD_COLS;
}
static inline bool is_empty(const int8_t *layout, int8_t row, int8_t col) {
return layout_at(layout, row, col) == BOARD_EMPTY_CELL;
}
static inline bool is_red(int8_t pieceIdx) {
return !(pieceIdx & 1) && pieceIdx != INVALID_IDX;
}
static inline bool is_black(int8_t pieceIdx) {
return (pieceIdx & 1) && pieceIdx != INVALID_IDX;
}
static inline bool can_capture(board_t *board, int8_t row, int8_t col) {
return is_empty(board->layout, row, col) || (board->blackTurn ^ is_black(layout_at(board->layout, row, col)));
}
static inline bool is_opponent_king(board_t *board, int8_t row, int8_t col) {
return (board->blackTurn && layout_at(board->layout, row, col) == BOARD_RED_KING) ||
(!board->blackTurn && layout_at(board->layout, row, col) == BOARD_BLACK_KING);
}
static bool flying_general_possible(const board_t *board) {
if (board->pieces[0].col != board->pieces[BOARD_PIECES_OFFSET].col) return false;
for (int8_t i = board->pieces[BOARD_PIECES_OFFSET].row + 1; i < board->pieces[0].row; ++i) {
if (layout_at(board->layout, i, board->pieces[0].col) != BOARD_EMPTY_CELL) {
return false;
}
}
return true;
}
/**
* @brief Returns true if the position as represented by BOARD
* is a legal one, false otherwise.
*/
static bool is_legal_pos(board_t *board) {
if (flying_general_possible(board)) return false;
uint8_t nmoves;
for (int8_t i = board->blackTurn*BOARD_PIECES_OFFSET;
board->pieces[i].token != BOARD_EMPTY_CELL; ++i) {
nmoves = num_moves(board, i, true);
if (nmoves == ILLEGAL_NUM_MOVES) return false;
}
return true;
}
/**
* @brief Returns the number of legal moves of the piece at (ROW, COL)
* in LAYOUT. Returns ILLEGAL_NUM_MOVES if the given piece can capture
* the opponent king directly.
*/
static uint8_t num_moves(board_t *board, int8_t idx, bool testOnly) {
uint8_t nmoves = 0;
int8_t row = board->pieces[idx].row;
int8_t col = board->pieces[idx].col;
int8_t i, j, encounter;
const int8_t piece = layout_at(board->layout, row, col);
switch (piece) {
case BOARD_RED_KING: case BOARD_BLACK_KING:
/* A king can never capture the opponent's king. */
if (testOnly) return 0;
for (i = 0; i <= 1; ++i) {
j = 1 - i;
nmoves += is_valid_move(board, idx, i, j);
nmoves += is_valid_move(board, idx, -i, -j);
}
break;
case BOARD_RED_ADVISOR: case BOARD_BLACK_ADVISOR:
/* An advisor can never capture the opponent's king. */
if (testOnly) return 0;
for (i = -1; i <= 1; i += 2) for (j = -1; j <= 1; j += 2) {
nmoves += is_valid_move(board, idx, i, j);
}
break;
case BOARD_RED_BISHOP: case BOARD_BLACK_BISHOP:
/* A bishop can never capture the opponent's king. */
if (testOnly) return 0;
for (i = -2; i <= 2; i += 4) for (j = -2; j <= 2; j += 4) {
nmoves += is_valid_move(board, idx, i, j);
}
break;
case BOARD_RED_PAWN: case BOARD_BLACK_PAWN:
/* A pawn may capture the opponent's king. */
/* Horizontal moves. */
for (j = -1; j <= 1; j += 2) {
if (in_board(row, col+j) && is_opponent_king(board, row, col+j)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && is_valid_move(board, idx, 0, j);
}
/* Forward move. */
i = -1 + ((piece == BOARD_BLACK_PAWN) << 1);
if (in_board(row + i, col) && is_opponent_king(board, row+i, col)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && is_valid_move(board, idx, i, 0);
break;
case BOARD_RED_KNIGHT: case BOARD_BLACK_KNIGHT:
/* A knight may capture the opponent's king. */
for (i = -1; i <= 1; i += 2) for (j = -1; j <= 1; j += 2) {
if ((in_board(row + i*2, col+j) &&
is_empty(board->layout, row+i, col) &&
is_opponent_king(board, row + i*2, col+j)) ||
(in_board(row+i, col + j*2) &&
is_empty(board->layout, row, col+j) &&
is_opponent_king(board, row+i, col + j*2))
) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && is_valid_move(board, idx, i*2, j);
nmoves += !testOnly && is_valid_move(board, idx, i, j*2);
}
break;
case BOARD_RED_CANNON: case BOARD_BLACK_CANNON:
/* A cannon may capture the opponent's king. */
// up
for (i = -1, encounter = 0; in_board(row+i, col) && encounter < 2; --i) {
encounter += !is_empty(board->layout, row+i, col);
if (encounter == 2 && is_opponent_king(board, row+i, col)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && !(encounter & 1) && is_valid_move(board, idx, i, 0);
}
// down
for (i = 1, encounter = 0; in_board(row+i, col) && encounter < 2; ++i) {
encounter += !is_empty(board->layout, row+i, col);
if (encounter == 2 && is_opponent_king(board, row+i, col)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && !(encounter & 1) && is_valid_move(board, idx, i, 0);
}
// left
for (j = -1, encounter = 0; in_board(row, col+j) && encounter < 2; --j) {
encounter += !is_empty(board->layout, row, col+j);
if (encounter == 2 && is_opponent_king(board, row, col+j)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && !(encounter & 1) && is_valid_move(board, idx, 0, j);
}
// right
for (j = 1, encounter = 0; in_board(row, col+j) && encounter < 2; ++j) {
encounter += !is_empty(board->layout, row, col+j);
if (encounter == 2 && is_opponent_king(board, row, col+j)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && !(encounter & 1) && is_valid_move(board, idx, 0, j);
}
break;
case BOARD_RED_ROOK: case BOARD_BLACK_ROOK:
// up
for (i = -1, encounter = 0; in_board(row+i, col) && encounter < 1; --i) {
encounter += !is_empty(board->layout, row+i, col);
if (is_opponent_king(board, row+i, col)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && is_valid_move(board, idx, i, 0);
}
// down
for (i = 1, encounter = 0; in_board(row+i, col) && encounter < 1; ++i) {
encounter += !is_empty(board->layout, row+i, col);
if (is_opponent_king(board, row+i, col)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && is_valid_move(board, idx, i, 0);
}
// left
for (j = -1, encounter = 0; in_board(row, col+j) && encounter < 1; --j) {
encounter += !is_empty(board->layout, row, col+j);
if (is_opponent_king(board, row, col+j)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && is_valid_move(board, idx, 0, j);
}
// right
for (j = 1, encounter = 0; in_board(row, col+j) && encounter < 1; ++j) {
encounter += !is_empty(board->layout, row, col+j);
if (is_opponent_king(board, row, col+j)) return ILLEGAL_NUM_MOVES;
nmoves += !testOnly && is_valid_move(board, idx, 0, j);
}
break;
default:
printf("game.c::num_moves: invalid piece on board.layout\n");
exit(1);
}
return nmoves;
}
static bool is_valid_move(board_t *board, int8_t idx, int8_t i, int8_t j) {
int8_t row = board->pieces[idx].row;
int8_t col = board->pieces[idx].col;
const int8_t piece = layout_at(board->layout, row, col);
scope_t scope = scopes[piece + 2];;
bool res = true;
/* "Row-6 pawns" can move forward into a cell that is not in the above scope. */
bool fwdException = (piece == BOARD_RED_PAWN && row == 6 && i == -1 && j == 0) ||
(piece == BOARD_BLACK_PAWN && row == 3 && i == 1 && j == 0);
/* Move is immediately invalid if attempting to move a piece
off borders or to capture a friendly piece. */
res &= (in_scope(scope, row+i, col+j) || fwdException) &&
can_capture(board, row+i, col+j);
/* Special rule for knights and bishops: cannot be blocked. */
res &= (piece != BOARD_RED_BISHOP && piece != BOARD_BLACK_BISHOP &&
piece != BOARD_RED_KNIGHT && piece != BOARD_BLACK_KNIGHT) ||
is_empty(board->layout, row + i/2, col + j/2);
if (!res) return false;
/* Make move and see if the resulting position is valid. */
int8_t hold = layout_at(board->layout, row+i, col+j);
move_piece(board, row+i, col+j, row, col, BOARD_EMPTY_CELL);
res = is_legal_pos(board);
move_piece(board, row, col, row+i, col+j, hold);
return res;
}
/************** End Rule Related Helper Function Definitions ***************/
/**************** Move Related Helper Function Definitions *****************/
static void pieces_shift_left(piece_t *pieces, int8_t i) {
while (pieces[i].token != BOARD_EMPTY_CELL) {
pieces[i] = pieces[i + 1];
++i;
}
}
static void pieces_insert(piece_t *pieces, int8_t token, int8_t row, int8_t col) {
int8_t i = 0;
while (pieces[i].token != BOARD_EMPTY_CELL) ++i;
pieces[i].token = token;
pieces[i].row = row;
pieces[i].col = col;
pieces[i + 1].token = BOARD_EMPTY_CELL;
}
/**
* @brief Moves the piece at (SRCROW, SRCCOL) to (DESTROW, DESTCOL),
* replacing the source piece with REPLACE, and updates BOARD.
* Does not check if BOARD or the given move is valid.
*/
static void move_piece(board_t *board, int8_t destRow, int8_t destCol,
int8_t srcRow, int8_t srcCol, int8_t replace) {
int8_t destIdx = destRow*BOARD_COLS + destCol;
int8_t srcIdx = srcRow*BOARD_COLS + srcCol;
int8_t moving = layout_at(board->layout, srcRow, srcCol);
int8_t capturing = layout_at(board->layout, destRow, destCol);
piece_t *movingPieces, *capturingPieces;
movingPieces = board->pieces + (!is_red(moving)) * BOARD_PIECES_OFFSET;
capturingPieces = board->pieces + is_red(moving) * BOARD_PIECES_OFFSET;
/* Move current piece. */
int8_t i = 0;
while (movingPieces[i].token != moving ||
movingPieces[i].row != srcRow ||
movingPieces[i].col != srcCol) ++i;
movingPieces[i].row = destRow;
movingPieces[i].col = destCol;
/* Update opponent pieces array if needed. */
if (capturing != BOARD_EMPTY_CELL) {
i = 0;
while (capturingPieces[i].token != capturing ||
capturingPieces[i].row != destRow ||
capturingPieces[i].col != destCol) ++i;
pieces_shift_left(capturingPieces, i);
} else if (replace != BOARD_EMPTY_CELL) {
pieces_insert(capturingPieces, replace, srcRow, srcCol);
}
/* Update layout. */
board->layout[destIdx] = board->layout[srcIdx];
board->layout[srcIdx] = replace;
/* Flip turn bit. */
board->blackTurn = !board->blackTurn;
}
static void move_piece_append(ext_pos_array_t *children, board_t *board,
int8_t destRow, int8_t destCol,
int8_t srcRow, int8_t srcCol) {
int8_t hold = layout_at(board->layout, destRow, destCol);
move_piece(board, destRow, destCol, srcRow, srcCol, BOARD_EMPTY_CELL);
board_to_sa_position(&children->array[children->size++], board);
move_piece(board, srcRow, srcCol, destRow, destCol, hold);
}
// src is the piece to undoMove, dest is the empty space that it undoMoves to.
static void undomove_piece_append(pos_array_t *parents,
const char *tier, board_t *board,
int8_t destRow, int8_t destCol,
int8_t srcRow, int8_t srcCol,
int8_t replace) {
move_piece(board, destRow, destCol, srcRow, srcCol, replace);
if (is_legal_pos(board)) {
parents->array[parents->size++] = game_hash(tier, board);
}
move_piece(board, srcRow, srcCol, destRow, destCol, BOARD_EMPTY_CELL);
}
static bool add_children(ext_pos_array_t *children, board_t *board, int8_t idx) {
int8_t row = board->pieces[idx].row;
int8_t col = board->pieces[idx].col;
int8_t i, j, encounter;
const int8_t piece = layout_at(board->layout, row, col);
switch (piece) {
case BOARD_RED_KING: case BOARD_BLACK_KING:
/* A king can never capture the opponent's king. */
for (i = 0; i <= 1; ++i) {
j = 1 - i;
if (is_valid_move(board, idx, i, j)) {
move_piece_append(children, board, row+i, col+j, row, col);
}
if (is_valid_move(board, idx, -i, -j)) {
move_piece_append(children, board, row-i, col-j, row, col);
}
}
break;
case BOARD_RED_ADVISOR: case BOARD_BLACK_ADVISOR:
/* An advisor can never capture the opponent's king. */
for (i = -1; i <= 1; i += 2) for (j = -1; j <= 1; j += 2) {
if (is_valid_move(board, idx, i, j)) {
move_piece_append(children, board, row+i, col+j, row, col);
}
}
break;
case BOARD_RED_BISHOP: case BOARD_BLACK_BISHOP:
/* A bishop can never capture the opponent's king. */
for (i = -2; i <= 2; i += 4) for (j = -2; j <= 2; j += 4) {
if (is_valid_move(board, idx, i, j)) {
move_piece_append(children, board, row+i, col+j, row, col);
}
}
break;
case BOARD_RED_PAWN: case BOARD_BLACK_PAWN:
/* A pawn may capture the opponent's king. */
/* Horizontal moves. */
for (j = -1; j <= 1; j += 2) {
if (in_board(row, col+j) && is_opponent_king(board, row, col+j)) return false;
if (is_valid_move(board, idx, 0, j)) {
move_piece_append(children, board, row, col+j, row, col);
}
}
/* Forward move. */
i = -1 + ((piece == BOARD_BLACK_PAWN) << 1);
if (in_board(row + i, col) && is_opponent_king(board, row+i, col)) return false;
if (is_valid_move(board, idx, i, 0)) {
move_piece_append(children, board, row+i, col, row, col);
}
break;
case BOARD_RED_KNIGHT: case BOARD_BLACK_KNIGHT:
/* A knight may capture the opponent's king. */
for (i = -1; i <= 1; i += 2) for (j = -1; j <= 1; j += 2) {
if ((in_board(row + i*2, col+j) &&
is_empty(board->layout, row+i, col) &&
is_opponent_king(board, row + i*2, col+j)) ||
(in_board(row+i, col + j*2) &&
is_empty(board->layout, row, col+j) &&
is_opponent_king(board, row+i, col + j*2))
) return false;
if (is_valid_move(board, idx, i*2, j)) {
move_piece_append(children, board, row + i*2, col+j, row, col);
}
if (is_valid_move(board, idx, i, j*2)) {
move_piece_append(children, board, row+i, col + j*2, row, col);
}
}
break;
case BOARD_RED_CANNON: case BOARD_BLACK_CANNON:
/* A cannon may capture the opponent's king. */
// up
for (i = -1, encounter = 0; in_board(row+i, col) && encounter < 2; --i) {
encounter += !is_empty(board->layout, row+i, col);
if (encounter == 2 && is_opponent_king(board, row+i, col)) return false;
if (!(encounter & 1) && is_valid_move(board, idx, i, 0)) {
move_piece_append(children, board, row+i, col, row, col);
}
}
// down
for (i = 1, encounter = 0; in_board(row+i, col) && encounter < 2; ++i) {
encounter += !is_empty(board->layout, row+i, col);
if (encounter == 2 && is_opponent_king(board, row+i, col)) return false;
if (!(encounter & 1) && is_valid_move(board, idx, i, 0)) {
move_piece_append(children, board, row+i, col, row, col);
}
}
// left
for (j = -1, encounter = 0; in_board(row, col+j) && encounter < 2; --j) {
encounter += !is_empty(board->layout, row, col+j);
if (encounter == 2 && is_opponent_king(board, row, col+j)) return false;
if (!(encounter & 1) && is_valid_move(board, idx, 0, j)) {
move_piece_append(children, board, row, col+j, row, col);
}
}
// right
for (j = 1, encounter = 0; in_board(row, col+j) && encounter < 2; ++j) {
encounter += !is_empty(board->layout, row, col+j);
if (encounter == 2 && is_opponent_king(board, row, col+j)) return false;
if (!(encounter & 1) && is_valid_move(board, idx, 0, j)) {
move_piece_append(children, board, row, col+j, row, col);
}
}
break;
case BOARD_RED_ROOK: case BOARD_BLACK_ROOK:
// up
for (i = -1, encounter = 0; in_board(row+i, col) && encounter < 1; --i) {
encounter += !is_empty(board->layout, row+i, col);
if (is_opponent_king(board, row+i, col)) return false;
if (is_valid_move(board, idx, i, 0)) {
move_piece_append(children, board, row+i, col, row, col);
}
}
// down
for (i = 1, encounter = 0; in_board(row+i, col) && encounter < 1; ++i) {
encounter += !is_empty(board->layout, row+i, col);
if (is_opponent_king(board, row+i, col)) return false;
if (is_valid_move(board, idx, i, 0)) {
move_piece_append(children, board, row+i, col, row, col);
}
}
// left
for (j = -1, encounter = 0; in_board(row, col+j) && encounter < 1; --j) {
encounter += !is_empty(board->layout, row, col+j);
if (is_opponent_king(board, row, col+j)) return false;
if (is_valid_move(board, idx, 0, j)) {
move_piece_append(children, board, row, col+j, row, col);
}
}
// right
for (j = 1, encounter = 0; in_board(row, col+j) && encounter < 1; ++j) {
encounter += !is_empty(board->layout, row, col+j);
if (is_opponent_king(board, row, col+j)) return false;
if (is_valid_move(board, idx, 0, j)) {
move_piece_append(children, board, row, col+j, row, col);
}
}
break;
default:
printf("game.c::add_children: invalid piece on board.layout\n");
exit(1);
}
return true;
}
/**
* @brief Appends the legal parent positions of the position given by BOARD to the
* PARENTS array by undo-moving the piece at (ROW, COL) and reverse capturing a
* piece with REVIDX, assuming no backward pawn moves are allowed.
* @param parents: array of parent positions.
* @param tier: tier of the parent position.
* @param board: represents the current (child) position.
* @param row: row of the piece to undo-move.
* @param col: column of the piece to undo-move.
* @param revIdx: index of the piece to reverse capture. Set to BOARD_EMPTY_CELL
* if do not want reverse capturing.
*/
static void add_parents(pos_array_t *parents, const char *tier,
board_t *board, int8_t row, int8_t col, int8_t revIdx) {
const int8_t *layout = board->layout;
int8_t i, j, encounter;
int8_t piece = layout_at(layout, row, col);
scope_t scope = scopes[piece + 2];;
switch (piece) {
case BOARD_RED_KING: case BOARD_BLACK_KING:
for (i = 0; i <= 1; ++i) {
j = 1 - i;
if (in_scope(scope, row+i, col+j) && is_empty(layout, row+i, col+j)) {
undomove_piece_append(parents, tier, board, row+i, col+j, row, col, revIdx);
}
if (in_scope(scope, row-i, col-j) && is_empty(layout, row-i, col-j)) {
undomove_piece_append(parents, tier, board, row-i, col-j, row, col, revIdx);
}
}
break;
case BOARD_RED_ADVISOR: case BOARD_BLACK_ADVISOR:
for (i = -1; i <= 1; i += 2) for (j = -1; j <= 1; j += 2) {
if (in_scope(scope, row+i, col+j) && is_empty(layout, row+i, col+j)) {
undomove_piece_append(parents, tier, board, row+i, col+j, row, col, revIdx);
}
}
break;
case BOARD_RED_BISHOP: case BOARD_BLACK_BISHOP:
for (i = -2; i <= 2; i += 4) for (j = -2; j <= 2; j += 4) {
/* Also need to check if the blocking point is empty. */
if (in_scope(scope, row+i, col+j) && is_empty(layout, row+i, col+j) &&
is_empty(layout, row + i/2, col + j/2)) {
undomove_piece_append(parents, tier, board, row+i, col+j, row, col, revIdx);
}
}
break;
case BOARD_RED_PAWN: case BOARD_BLACK_PAWN:
for (j = -1; j <= 1; j += 2) {
if (in_scope(scope, row, col+j) && is_empty(layout, row, col+j)) {
undomove_piece_append(parents, tier, board, row, col+j, row, col, revIdx);
}
}
break;
case BOARD_RED_KNIGHT: case BOARD_BLACK_KNIGHT:
for (i = -1; i <= 1; i += 2) for (j = -1; j <= 1; j += 2) {
/* If the blocking point (row+i, col+j) is empty. */
if (in_scope(scope, row+i, col+j) && is_empty(layout, row+i, col+j)) {
if (in_scope(scope, row + i*2, col+j) && is_empty(layout, row + i*2, col+j)) {
undomove_piece_append(parents, tier, board, row + i*2, col+j, row, col, revIdx);
}
if (in_scope(scope, row+i, col + j*2) && is_empty(layout, row+i, col + j*2)) {
undomove_piece_append(parents, tier, board, row+i, col + j*2, row, col, revIdx);
}
}
}
break;
case BOARD_RED_CANNON: case BOARD_BLACK_CANNON:
/* Reverse capturing. */
if (revIdx != BOARD_EMPTY_CELL) {
// up
for (i = -1, encounter = 0; in_scope(scope, row+i, col) && encounter < 2; --i) {
if (!is_empty(layout, row+i, col)) ++encounter;
else if (encounter) undomove_piece_append(parents, tier, board, row+i, col, row, col, revIdx);
}
// down
for (i = 1, encounter = 0; in_scope(scope, row+i, col) && encounter < 2; ++i) {
if (!is_empty(layout, row+i, col)) ++encounter;
else if (encounter) undomove_piece_append(parents, tier, board, row+i, col, row, col, revIdx);
}
// left
for (j = -1, encounter = 0; in_scope(scope, row, col+j) && encounter < 2; --j) {
if (!is_empty(layout, row, col+j)) ++encounter;
else if (encounter) undomove_piece_append(parents, tier, board, row, col+j, row, col, revIdx);
}
// right
for (j = 1, encounter = 0; in_scope(scope, row, col+j) && encounter < 2; ++j) {
if (!is_empty(layout, row, col+j)) ++encounter;
else if (encounter) undomove_piece_append(parents, tier, board, row, col+j, row, col, revIdx);
}
break;
}
/* Else, fall through. */
case BOARD_RED_ROOK: case BOARD_BLACK_ROOK:
// up
for (i = -1; in_scope(scope, row+i, col) && is_empty(layout, row+i, col); --i) {
undomove_piece_append(parents, tier, board, row+i, col, row, col, revIdx);
}
// down
for (i = 1; in_scope(scope, row+i, col) && is_empty(layout, row+i, col); ++i) {
undomove_piece_append(parents, tier, board, row+i, col, row, col, revIdx);
}
// left
for (j = -1; in_scope(scope, row, col+j) && is_empty(layout, row, col+j); --j) {
undomove_piece_append(parents, tier, board, row, col+j, row, col, revIdx);
}
// right
for (j = 1; in_scope(scope, row, col+j) && is_empty(layout, row, col+j); ++j) {
undomove_piece_append(parents, tier, board, row, col+j, row, col, revIdx);
}
break;
default:
printf("game.c::add_parents: invalid piece on board.layout\n");
exit(1);
}
}
/*************** End Move Related Helper Function Definitions **************/
/***************** Hash Related Helper Function Definitions ****************/
static uint64_t *hash_to_steps(const char *tier, uint64_t hash) {
uint64_t *steps = (uint64_t*)malloc((NUM_TIER_SIZE_STEPS + 1)*sizeof(uint64_t));
if (!steps) return NULL; // OOM.
uint64_t *stepsMax = tier_size_steps(tier);
if (!stepsMax) {
free(steps);
return NULL;
}
/* Turn bit */
steps[NUM_TIER_SIZE_STEPS] = hash & 1ULL;
hash >>= 1;
/* Steps */
for (int i = NUM_TIER_SIZE_STEPS - 1; i >= 0; --i) {
steps[i] = hash % stepsMax[i];
hash /= stepsMax[i];
}
free(stepsMax);
return steps;
}
static uint64_t steps_to_hash(const char *tier, const uint64_t *steps) {
uint64_t res = 0ULL;
uint64_t *stepsMax = tier_size_steps(tier);
if (!steps || !stepsMax) return ILLEGAL_HASH; // OOM.
/* Steps */
for (int i = 0; i < NUM_TIER_SIZE_STEPS; ++i) {
res *= stepsMax[i];
res += steps[i];
}
/* Turn bit */
res = (res << 1) | steps[NUM_TIER_SIZE_STEPS];
free(stepsMax);
return res;
}
static uint8_t kingSlot[3][3] = {
{0, 0, 0},
{1, 0, 2},
{0, 3, 0}
};
static uint8_t kingIdx[4] = {67, 75, 77, 85};
/**
* @brief Set SLOTS according to LAYOUT, STEP, and SUBSTEP, and returns the
* number of slots set.
*/
static uint8_t set_slots(uint8_t *slots, const int8_t *layout, int step, uint8_t substep) {
int parity = step & 1;
uint8_t i, j;
switch (step) {
case 0: case 1:
slots[0] = 66 - 63*step; slots[1] = 68 - 63*step; slots[2] = 76 - 63*step;
slots[3] = 84 - 63*step; slots[4] = 86 - 63*step;
return 5;
case 2: case 3:
slots[0] = 47 - 45*parity; slots[1] = 51 - 45*parity; slots[2] = 63 - 45*parity;
slots[3] = 67 - 45*parity; slots[4] = 71 - 45*parity; slots[5] = 83 - 45*parity;
slots[6] = 87 - 45*parity;
return 7;
case 4: case 5: case 6: case 11: case 12: case 13:
for (i = 0; i < BOARD_COLS; ++i) {
slots[i] = i + BOARD_COLS*(step - 4); // skip the first (step - 4) rows.
}
return BOARD_COLS;
case 7: case 8: case 9: case 10:
if (!substep) {
for (j = 0; j < BOARD_COLS; j += 2) { // columns 0, 2, 4, 6, 8.
slots[j >> 1] = j + BOARD_COLS*(step - 4); // skip the first (step - 4) rows.
}
return 5;
} else {
for (i = 0, j = 0; j < BOARD_COLS; ++j) {
/* The following line assumes BOARD_RED_PAWN + 1 == BOARD_BLACK_PAWN. */
if (layout_at(layout, step - 4, j) != BOARD_RED_PAWN + (step < 9)) {
slots[i++] = j + BOARD_COLS*(step - 4);
}
}
return i;
}
case 14:
for (i = 0, j = 0; j < BOARD_SIZE; ++j) {
if (layout[j] >= BOARD_RED_KNIGHT) {
slots[i++] = j;
}
}
return i;
default:
return UINT8_MAX;
}
}
static bool steps_to_board(board_t *board, const char *tier, uint64_t *steps) {
if (!steps) return false; // OOM in previous step.
int step, parity;
uint8_t i, j, nLessRestrictedP, nMoreRestrictedP;
uint8_t slots[BOARD_SIZE];
int8_t piecesToPlace[7];
uint8_t rems[7];
uint8_t piecesSizes[2] = {0, 0};
uint8_t pawnsPerRow[2 * BOARD_ROWS];
board->valid = true; // Should an error occur, set this value to false in that step.
tier_get_pawns_per_row(tier, pawnsPerRow);
piecesToPlace[0] = BOARD_EMPTY_CELL; // Empty cell is always the 0-th piece to place.
/* STEP 0 & 1: KINGS AND ADVISORS. */