-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.cc
1536 lines (1318 loc) · 61.3 KB
/
board.cc
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 "board.h"
#include "move.h"
#include "zobrist.h"
#include "evaluator.h"
#include <algorithm>
#include <map>
#include <chrono>
Index Board::getFileIndexOfSquare(Square square) {
assert(square != None);
//squares are laid out sequentially in rank, so their file is mod 8
return static_cast<Index>(square % NumFiles);
}
Index Board::getRankIndexOfSquare(Square square) {
assert(square != None);
//ranks are groups of 8 (numFiles) in the layout, so truncate and divide
return static_cast<Index>(square / NumFiles);
}
Index Board::getMirrorFileIndex(Index fileIndex) {
//compile time optimization
/*const static Index Mirror[] = {Zero, One, Two, Three, Three, Two, One};
return Mirror[fileIndex];*/
return fileIndex > 3 ? (static_cast<Index>(7 - fileIndex)) : fileIndex;
}
Index Board::getRelativeRankIndexOfSquare(Color side, Square square) {
assert(square != None);
//get the rank our piece is on relative to our starting side
return side == White ? getRankIndexOfSquare(square) : static_cast<Index>(7 - getRankIndexOfSquare(square));
}
Square Board::getSquare(Index rankIndex, Index fileIndex) {
return getSquare(rankIndex * NumFiles + fileIndex);
}
Square Board::getRelativeSquare(Color side, Square square) {
assert(square != None);
//get the relative square ours is on relative to our side
return getSquare(getRelativeRankIndexOfSquare(side, square), getFileIndexOfSquare(square));
}
Square Board::getRelativeSquare32(Color side, Square square) {
assert(square != None);
//get the relative square ours is on relative to our side and limited to the left half of the board
return getSquare(4 * getRelativeRankIndexOfSquare(side, square) + getMirrorFileIndex(getFileIndexOfSquare(square)));
}
Board::SquareColor Board::getSquareColor(Square square) {
assert(square != None);
return testBit(LightSquares, square) ? LightSquares : DarkSquares;
}
//Some fast compiler intrinsics for bit math
int Board::popCnt(Bitboard bb) {
return __builtin_popcountll(bb);
}
int Board::getMsb(Bitboard bb) {
assert(bb); //msb is undefined for zero
//count leading zeroes and invert to get index
return __builtin_clzll(bb) ^ 63;
}
int Board::getLsb(Bitboard bb) {
assert(bb); //lsb is undefined for zero
//count trailing zeroes
return __builtin_ctzll(bb);
}
int Board::popMsb(Bitboard& bb) {
//get the msb, xor it out, then return it
int msb = getMsb(bb);
bb ^= 1ull << msb;
return msb;
}
int Board::popLsb(Bitboard& bb) {
//get the lsb, and it out, then return it
int lsb = getLsb(bb);
bb &= bb - 1;
return lsb;
}
bool Board::isNonSingular(Bitboard bb) {
//more than one 1 only if both it and its predecessor have a 1
return bb & (bb - 1);
}
void Board::setBit(Bitboard& bb, Square bit) {
assert(!testBit(bb, bit));
bb ^= 1ull << bit;
}
void Board::clearBit(Bitboard& bb, Square bit) {
assert(testBit(bb, bit));
bb ^= 1ull << bit;
}
bool Board::testBit(Bitboard bb, Square bit) {
assert(bit != None);
return bb & (1ull << bit);
}
void Board::debugPrintBitboard(Bitboard bb) {
for(int i = NumRanks - 1; i >= 0; i--) {
for(int j = 0; j < NumFiles; j++) {
std::cout << testBit(bb, getSquare(i, j));
}
std::cout << std::endl;
}
std::cout << std::endl;
}
bool Board::hasNonPawns(Color side) const {
return (sides[side] & (pieces[King] & pieces[Pawn])) != sides[side];
}
bool Board::isDrawn() const {
return isFiftyMoveRuleDraw() || isThreefoldDraw() || isInsufficientMaterialDraw();
}
bool Board::isFiftyMoveRuleDraw() const {
return plies > 99;
}
bool Board::isThreefoldDraw() const {
int repetitions = 0;
//Look through all the moves played thus far
for(int i = fullmoves - 2; i >= 0; i -= 2) {
//we can no longer repeat if a fifty-move-rule resetting move was made
if(i < fullmoves - plies) {
break;
}
if(undoStack[i].positionHash == positionHash) {
if(++repetitions == 3) {
return true;
}
}
}
return false;
}
bool Board::isInsufficientMaterialDraw() const {
//insuff material is only forced if one side has only 1 knight, 1 bishop, or 2 knights
return !(pieces[Queen] | pieces[Rook] | pieces[Pawn]) && (!isNonSingular(sides[White]) || !isNonSingular(sides[Black])) && (!isNonSingular(pieces[Bishop] | pieces[Knight]) || (popCnt(pieces[Knight]) <= 2 && !pieces[Bishop]));
}
std::string Board::squareToString(Square square) {
std::string output;
if(square == None) {
output.append("-");
} else {
output += 'a' + getFileIndexOfSquare(square);
output += '1' + getRankIndexOfSquare(square);
}
return output;
}
Square Board::squareFromString(const std::string& string) {
assert(string.size() <= 2);
if(string == "-") {
return None;
}
return getSquare(string[1] - '1', string[0] - 'a');
}
Board::Board() : positionHash{0}, kingAttackers{0}, castlingRooks{0}, turn{White}, plies{0}, fullmoves{0}, enpassantSquare{None} {
for(int i = 0; i < 6; i++) {
pieces[i] = 0;
}
for(int i = 0; i < 2; i++) {
sides[i] = 0;
}
for(int i = 0; i < 64; i++) {
squares[i] = Empty;
castleMasks[i] = 0;
}
//shorter thing to type, who said programmers weren't lazy
PrecomputedBinary::getBinary().init();
}
void Board::setBitboardSquare(Bitboard& board, int rankIndex, int fileIndex) {
if(0 <= rankIndex && rankIndex < NumRanks && 0 <= fileIndex && fileIndex < NumFiles) {
board |= 1ull << getSquare(rankIndex, fileIndex);
}
}
//Trivial constructor since we super care about Board's constructor body running BEFORE we initialize this
Board::PrecomputedBinary::PrecomputedBinary() { }
void Board::PrecomputedBinary::init() {
if(hasBeenInitialized) {
return;
}
//Initialize attacks:
//all possible movements of pieces
const MultiArray<int, 2, 2> pawnAttackDelta{ std::array<int, 2>{1, -1}, std::array<int, 2>{1, 1} };
const MultiArray<int, 8, 2> knightMovementDelta{ std::array<int, 2>{-2, -1}, std::array<int, 2>{-2, 1}, std::array<int, 2>{-1, -2}, std::array<int, 2>{-1, 2}, std::array<int, 2>{1, -2}, std::array<int, 2>{1, 2}, std::array<int, 2>{2, -1}, std::array<int, 2>{2, 1} };
const MultiArray<int, 8, 2> kingMovementDelta{ std::array<int, 2>{-1,-1}, std::array<int, 2>{-1, 0}, std::array<int, 2>{-1, 1}, std::array<int, 2>{0,-1}, std::array<int, 2>{0, 1}, std::array<int, 2>{1,-1}, std::array<int, 2>{1, 0}, std::array<int, 2>{1, 1} };
const MultiArray<int, 4, 2> bishopMovementDelta{ std::array<int, 2>{-1, -1}, std::array<int, 2>{-1, 1}, std::array<int, 2>{1, -1}, std::array<int, 2>{1, 1} };
const MultiArray<int, 4, 2> rookMovementDelta{ std::array<int, 2>{-1, 0}, std::array<int, 2>{0, -1}, std::array<int, 2>{0, 1}, std::array<int, 2>{1, 0} };
//we will use the arrays we have allocated already as the initial offsets
RookTable[a1].offset = RookAttack;
BishopTable[a1].offset = BishopAttack;
//In what follows, we initialize the attack bitboards.
//For the basic pieces, we just compute their movements, check if that movement gives valid coordinates (as checked in setBitboardSquare),
//and if so set the respective bitboard.
for(int square = a1; square <= h8; square++) {
Square sq = getSquare(square);
for(int direction = 0; direction < 2; direction++) {
setBitboardSquare(PawnAttack[White][square], getRankIndexOfSquare(sq) + pawnAttackDelta[direction][0], getFileIndexOfSquare(sq) + pawnAttackDelta[direction][1]);
setBitboardSquare(PawnAttack[Black][square], getRankIndexOfSquare(sq) - pawnAttackDelta[direction][0], getFileIndexOfSquare(sq) - pawnAttackDelta[direction][1]);
setBitboardSquare(KnightAttack[square], getRankIndexOfSquare(sq) + knightMovementDelta[direction][0], getFileIndexOfSquare(sq) + knightMovementDelta[direction][1]);
setBitboardSquare(KingAttack[square], getRankIndexOfSquare(sq) + kingMovementDelta[direction][0], getFileIndexOfSquare(sq) + kingMovementDelta[direction][1]);
}
for(int direction = 2; direction < 8; direction++) {
setBitboardSquare(KnightAttack[square], getRankIndexOfSquare(sq) + knightMovementDelta[direction][0], getFileIndexOfSquare(sq) + knightMovementDelta[direction][1]);
setBitboardSquare(KingAttack[square], getRankIndexOfSquare(sq) + kingMovementDelta[direction][0], getFileIndexOfSquare(sq) + kingMovementDelta[direction][1]);
}
populateHashTable(BishopTable, sq, BishopHashes[sq], bishopMovementDelta);
populateHashTable(RookTable, sq, RookHashes[sq], rookMovementDelta);
}
//Initialize masks (depend on attacks being done)
for(int square1 = a1; square1 <= h8; square1++) {
for(int square2 = a1; square2 <= h8; square2++) {
//Align this on rank/file if the squares are straight away
if(testBit(getRookAttacksFromSquare(getSquare(square1), 0), getSquare(square2))) {
BetweenSquaresMasks[square1][square2] = getRookAttacksFromSquare(getSquare(square1), 1ull << square2) & getRookAttacksFromSquare(getSquare(square2), 1ull << square1);
}
//Align this on diagonal if the squares are diagonally away
if(testBit(getBishopAttacksFromSquare(getSquare(square1), 0), getSquare(square2))) {
BetweenSquaresMasks[square1][square2] = getBishopAttacksFromSquare(getSquare(square1), 1ull << square2) & getBishopAttacksFromSquare(getSquare(square2), 1ull << square1);
}
}
}
//Populate masks that indicate adjacent files
for(int file = 0; file < NumFiles; file++) {
//The max and min deal with the edge case (literally)
//And we don't include the current file
AdjacentFilesMasks[file] = getFile(std::max(0, file - 1));
AdjacentFilesMasks[file] |= getFile(std::min(NumFiles - 1, file + 1));
AdjacentFilesMasks[file] &= ~getFile(file);
}
for(int color = 0; color < NumColors; color++) {
for(int square = 0; square < NumSquares; square++) {
Bitboard files = AdjacentFilesMasks[getFileIndexOfSquare(getSquare(square))] | getFile(getFileIndexOfSquare(getSquare(square)));
Bitboard ranks = 0;
for(int rank = getRankIndexOfSquare(getSquare(square)); 0 <= rank && rank < NumRanks; White == color ? rank-- : rank++) {
ranks |= getRank(rank);
}
PassedPawnMasks[color][square] = ~ranks & files;
}
}
hasBeenInitialized = true;
}
Bitboard Board::PrecomputedBinary::getPassedPawnMask(Color side, Square square) {
assert(square != None);
return PassedPawnMasks[side][square];
}
Bitboard Board::PrecomputedBinary::getBetweenSquaresMask(Square square1, Square square2) {
assert(square1 != None && square2 != None);
return BetweenSquaresMasks[square1][square2];
}
Bitboard Board::PrecomputedBinary::getAdjacentFilesMask(Index fileIndex) {
return AdjacentFilesMasks[fileIndex];
}
Bitboard Board::PrecomputedBinary::getKnightAttacksFromSquare(Square square) {
return KnightAttack[square];
}
Bitboard Board::PrecomputedBinary::getKingAttacksFromSquare(Square square) {
return KingAttack[square];
}
Bitboard Board::PrecomputedBinary::getPawnAttacksFromSquare(Square square, Color side) {
return PawnAttack[side][square];
}
Bitboard Board::PrecomputedBinary::getBishopAttacksFromSquare(Square square, Bitboard occupiedBoard) {
return BishopTable[square].offset[computeHashTableIndex(occupiedBoard, BishopTable[square])];
}
Bitboard Board::PrecomputedBinary::getRookAttacksFromSquare(Square square, Bitboard occupiedBoard) {
return RookTable[square].offset[computeHashTableIndex(occupiedBoard, RookTable[square])];
}
Bitboard Board::PrecomputedBinary::getQueenAttacksFromSquare(Square square, Bitboard occupiedBoard) {
return getBishopAttacksFromSquare(square, occupiedBoard) | getRookAttacksFromSquare(square, occupiedBoard);
}
Bitboard Board::getPawnLeftAttacks(Bitboard pawnBoard, Bitboard targets, Color side) {
return targets & (side == White ? (pawnBoard << 7) & ~FileH : (pawnBoard >> 7) & ~FileA);
}
Bitboard Board::getPawnRightAttacks(Bitboard pawnBoard, Bitboard targets, Color side) {
return targets & (side == White ? (pawnBoard << 9) & ~FileA : (pawnBoard >> 9) & ~FileH);
}
Bitboard Board::getPawnAdvances(Bitboard pawnBoard, Bitboard occupiedBoard, Color side) {
return ~occupiedBoard & (side == White ? pawnBoard << 8 : pawnBoard >> 8);
}
Bitboard Board::getPawnEnpassantCaptures(Bitboard pawnBoard, Square enpassantSquare, Color side) {
return (enpassantSquare == None) ? 0 : PrecomputedBinary::getBinary().getPawnAttacksFromSquare(enpassantSquare, flipColor(side)) & pawnBoard;
}
Bitboard Board::getAllSquareAttackers(Bitboard occupiedBoard, Square square) const {
return (PrecomputedBinary::getBinary().getPawnAttacksFromSquare(square, White) & sides[Black] & pieces[Pawn])
| (PrecomputedBinary::getBinary().getPawnAttacksFromSquare(square, Black) & sides[White] & pieces[Pawn])
| (PrecomputedBinary::getBinary().getKnightAttacksFromSquare(square) & pieces[Knight])
| (PrecomputedBinary::getBinary().getBishopAttacksFromSquare(square, occupiedBoard) & (pieces[Bishop] | pieces[Queen]))
| (PrecomputedBinary::getBinary().getRookAttacksFromSquare(square, occupiedBoard) & (pieces[Rook] | pieces[Queen]))
| (PrecomputedBinary::getBinary().getKingAttacksFromSquare(square) & pieces[King]);
}
Bitboard Board::getAllKingAttackers() {
Square square = getSquare(getLsb(sides[turn] & pieces[King]));
Bitboard occupiedBoard = sides[White] | sides[Black];
return getAllSquareAttackers(occupiedBoard, square) & sides[flipColor(turn)];
}
bool Board::isSquareAttacked(Square square, Color side) {
Bitboard enemyPieces = sides[flipColor(side)];
Bitboard occupiedBoard = sides[White] | sides[Black];
Bitboard enemyPawns = enemyPieces & pieces[Pawn];
Bitboard enemyKnights = enemyPieces & pieces[Knight];
Bitboard enemyBishops = enemyPieces & (pieces[Bishop] | pieces[Queen]);
Bitboard enemyRooks = enemyPieces & (pieces[Rook] | pieces[Queen]);
Bitboard enemyKings = enemyPieces & pieces[King];
//avoid doing hash lookups via short circuit if we can
return ((PrecomputedBinary::getBinary().getPawnAttacksFromSquare(square, side) & enemyPawns) != 0)
|| ((PrecomputedBinary::getBinary().getKnightAttacksFromSquare(square) & enemyKnights) != 0)
|| ((PrecomputedBinary::getBinary().getKingAttacksFromSquare(square) & enemyKings) != 0)
|| ((enemyBishops != 0) && ((PrecomputedBinary::getBinary().getBishopAttacksFromSquare(square, occupiedBoard) & enemyBishops) != 0))
|| ((enemyRooks != 0) && ((PrecomputedBinary::getBinary().getRookAttacksFromSquare(square, occupiedBoard) & enemyRooks) != 0));
}
bool Board::debugIsSquareAttacked(Square square, Color side) {
Bitboard enemyPieces = sides[flipColor(side)];
Bitboard occupiedBoard = sides[White] | sides[Black];
Bitboard enemyPawns = enemyPieces & pieces[Pawn];
Bitboard enemyKnights = enemyPieces & pieces[Knight];
Bitboard enemyBishops = enemyPieces & (pieces[Bishop] | pieces[Queen]);
Bitboard enemyRooks = enemyPieces & (pieces[Rook] | pieces[Queen]);
Bitboard enemyKings = enemyPieces & pieces[King];
bool attackedByPawns = (PrecomputedBinary::getBinary().getPawnAttacksFromSquare(square, side) & enemyPawns) != 0;
bool attackedByKnights = (PrecomputedBinary::getBinary().getKnightAttacksFromSquare(square) & enemyKnights) != 0;
bool attackedByKings = (PrecomputedBinary::getBinary().getKingAttacksFromSquare(square) & enemyKings) != 0;
bool attackedByBishops = ((enemyBishops != 0) && ((PrecomputedBinary::getBinary().getBishopAttacksFromSquare(square, occupiedBoard) & enemyBishops) != 0));
bool attackedByRooks = ((enemyRooks != 0) && ((PrecomputedBinary::getBinary().getRookAttacksFromSquare(square, occupiedBoard) & enemyRooks) != 0));
debugPrintBitboard(enemyPieces);
std::cerr << std::endl;
debugPrintBitboard(enemyKnights);
std::cerr << std::endl;
std::cerr << attackedByPawns << " " << attackedByKnights << " " << attackedByKings << " " << attackedByBishops << " " << attackedByRooks << std::endl;
return attackedByPawns || attackedByKnights || attackedByKings || attackedByBishops || attackedByRooks;
}
bool Board::setCastlingRight(Color side, bool isKingside) {
if(side == White && isKingside) {
if((sides[White] & pieces[Rook] & Rank1) == 0) {
return false;
}
if(!testBit(castlingRooks, getSquare(getMsb(sides[White] & pieces[Rook] & Rank1)))) {
setBit(castlingRooks, getSquare(getMsb(sides[White] & pieces[Rook] & Rank1)));
return true;
}
} else if(side == White && !isKingside) {
if((sides[White] & pieces[Rook] & Rank1) == 0) {
return false;
}
if(!testBit(castlingRooks, getSquare(getLsb(sides[White] & pieces[Rook] & Rank1)))) {
setBit(castlingRooks, getSquare(getLsb(sides[White] & pieces[Rook] & Rank1)));
return true;
}
} else if(isKingside) {
if((sides[Black] & pieces[Rook] & Rank8) == 0) {
return false;
}
if(!testBit(castlingRooks, getSquare(getMsb(sides[Black] & pieces[Rook] & Rank8)))) {
setBit(castlingRooks, getSquare(getMsb(sides[Black] & pieces[Rook] & Rank8)));
return true;
}
} else {
if((sides[Black] & pieces[Rook] & Rank8) == 0) {
return false;
}
if(!testBit(castlingRooks, getSquare(getLsb(sides[Black] & pieces[Rook] & Rank8)))) {
setBit(castlingRooks, getSquare(getLsb(sides[Black] & pieces[Rook] & Rank8)));
return true;
}
}
return false;
}
bool Board::clearCastlingRight(Color side, bool isKingside) {
if(side == White && isKingside) {
if((sides[White] & pieces[Rook] & Rank1) == 0) {
return false;
}
if(testBit(castlingRooks, getSquare(getMsb(sides[White] & pieces[Rook] & Rank1)))) {
clearBit(castlingRooks, getSquare(getMsb(sides[White] & pieces[Rook] & Rank1)));
return true;
}
} else if(side == White && !isKingside) {
if((sides[White] & pieces[Rook] & Rank1) == 0) {
return false;
}
if(testBit(castlingRooks, getSquare(getLsb(sides[White] & pieces[Rook] & Rank1)))) {
clearBit(castlingRooks, getSquare(getLsb(sides[White] & pieces[Rook] & Rank1)));
return true;
}
} else if(isKingside) {
if((sides[Black] & pieces[Rook] & Rank8) == 0) {
return false;
}
if(testBit(castlingRooks, getSquare(getMsb(sides[Black] & pieces[Rook] & Rank8)))) {
clearBit(castlingRooks, getSquare(getMsb(sides[Black] & pieces[Rook] & Rank8)));
return true;
}
} else {
if((sides[Black] & pieces[Rook] & Rank8) == 0) {
return false;
}
if(testBit(castlingRooks, getSquare(getLsb(sides[Black] & pieces[Rook] & Rank8)))) {
clearBit(castlingRooks, getSquare(getLsb(sides[Black] & pieces[Rook] & Rank8)));
return true;
}
}
return false;
}
std::string Board::getCastlingRights() const {
std::string output;
Bitboard castlingRooks = sides[White] & pieces[Rook];
while(castlingRooks != 0) {
Square square = getSquare(popMsb(castlingRooks));
if(testBit(FileH, square)) {
output += "K";
} else if(testBit(FileA, square)) {
output += "Q";
}
}
castlingRooks = sides[Black] & pieces[Rook];
while(castlingRooks != 0) {
Square square = getSquare(popMsb(castlingRooks));
if(testBit(FileA, square)) {
output += "k";
} else if(testBit(FileA, square)) {
output += "q";
}
}
return output.empty() ? "-" : output;
}
void Board::setEnpassantSquare(Square square) {
enpassantSquare = square;
}
Square Board::getEnpassantSquare() {
return enpassantSquare;
}
void Board::setSquare(Color side, Piece piece, Square square) {
assert(square != None);
squares[square] = makePiece(piece, side);
setBit(sides[side], square);
setBit(pieces[piece], square);
}
void Board::clearSquare(Square square) {
assert(square != None);
ColorPiece pieceOn = squares[square];
if(pieceOn == Empty) {
return;
}
squares[square] = Empty;
clearBit(sides[getColorOfPiece(pieceOn)], square);
clearBit(pieces[getPieceType(pieceOn)], square);
if(testBit(castlingRooks, square)) {
clearBit(castlingRooks, square);
}
}
Board::BoardLegality Board::getBoardLegalityState() const {
if(popCnt(pieces[King]) != 2 || popCnt(pieces[King] & sides[White]) != 1 || popCnt(pieces[King] & sides[Black]) != 1) {
return IllegalKings;
}
Bitboard kingAttacks = getAllSquareAttackers(sides[White] | sides[Black], getSquare(getLsb(pieces[King] & sides[flipColor(turn)]))) & sides[turn];
if(kingAttacks != 0) {
return IllegalKingPosition;
}
if((pieces[Pawn] & Rank1) != 0 || (pieces[Pawn] & Rank8) != 0) {
return IllegalPawns;
}
if(enpassantSquare != None && (getRelativeRankIndexOfSquare(turn, enpassantSquare) != Five || (squares[getSquare(enpassantSquare - 8 + (turn << 4))] != WhitePawn && squares[getSquare(enpassantSquare - 8 + (turn << 4))] != BlackPawn))) {
return IllegalEnpassant;
}
return Legal;
}
Board Board::createBoardFromFEN(std::string fen) {
Board board;
int square = a8;
std::string token = fen.substr(0, fen.find(" "));
for(char& c : token) {
if(std::isdigit(c)) {
//in FEN, a digit in this place corresponds to skipping that many positions
square += c - '0';
} else if(c == '/') {
//go down a rank
square -= 2 * NumRanks;
} else {
//place a piece
Color color = std::islower(c) ? Black : White;
Piece piece;
switch(std::toupper(c)) {
case 'P':
piece = Pawn;
break;
case 'N':
piece = Knight;
break;
case 'B':
piece = Bishop;
break;
case 'R':
piece = Rook;
break;
case 'Q':
piece = Queen;
break;
case 'K':
piece = King;
break;
default:
std::cerr << "hey you suck this isn't a chess piece give me a real chess piece" << std::endl;
return board;
}
board.setSquare(color, piece, getSquare(square));
//this won't overflow under the assumption the FEN is well-formed (since a / should follow)
square++;
}
}
fen.erase(0, fen.find(" ") + 1);
token = fen.substr(0, fen.find(" "));
board.turn = token[0] == 'w' ? White : Black;
fen.erase(0, fen.find(" ") + 1);
token = fen.substr(0, fen.find(" "));
//castling rights
for(char& c : token) {
if(c == 'K') {
setBit(board.castlingRooks, getSquare(getMsb(board.sides[White] & board.pieces[Rook] & Rank1)));
} else if(c == 'Q') {
setBit(board.castlingRooks, getSquare(getLsb(board.sides[White] & board.pieces[Rook] & Rank1)));
} else if(c == 'k') {
setBit(board.castlingRooks, getSquare(getMsb(board.sides[Black] & board.pieces[Rook] & Rank8)));
} else if(c == 'q') {
setBit(board.castlingRooks, getSquare(getLsb(board.sides[Black] & board.pieces[Rook] & Rank8)));
}
}
fen.erase(0, fen.find(" ") + 1);
token = fen.substr(0, fen.find(" "));
board.enpassantSquare = squareFromString(token);
fen.erase(0, fen.find(" ") + 1);
token = fen.substr(0, fen.find(" "));
board.plies = std::stoi(token);
fen.erase(0, fen.find(" ") + 1);
token = fen.substr(0, fen.find(" "));
board.fullmoves = 0;
return board;
}
void Board::validateLegality() {
assert(getBoardLegalityState() == Legal);
//Create a bit mask of where the kings and rooks are
for(int sq = 0; sq < NumSquares; sq++) {
Square s = getSquare(sq);
castleMasks[s] = ~0ull;
if(testBit(castlingRooks, s)) {
clearBit(castleMasks[sq], s);
} else if(testBit(sides[White] & pieces[King], s)) {
castleMasks[sq] &= ~sides[White];
} else if(testBit(sides[Black] & pieces[King], s)) {
castleMasks[sq] &= ~sides[Black];
}
}
kingAttackers = getAllKingAttackers();
initMaterialEval();
}
std::string Board::getFEN() const {
return "not implemented yet";
}
ColorPiece Board::getPieceAt(Square square) const {
assert(square != None);
return squares[square];
}
Square Board::getKing() const {
if((pieces[King] & sides[turn]) == 0) {
return None;
}
return getSquare(getLsb(pieces[King] & sides[turn]));
}
Color Board::getTurn() const {
return turn;
}
void Board::setTurn(Color turn) {
this->turn = turn;
}
void Board::perftTest(int depth) {
perftRootDepth = depth;
std::map<std::string, int> divideTree;
int promotions = 0;
int castles = 0;
int enpassant = 0;
auto start = std::chrono::system_clock::now();
unsigned long long nodes = perft(divideTree, depth, enpassant, promotions, castles);
auto end = std::chrono::system_clock::now();
std::cout << " ◌ Perft test generated " << nodes << " in " << std::chrono::duration_cast<std::chrono::milliseconds>((end - start)).count() << " milliseconds." << std::endl;
std::cout << " ◌ Promotion moves in leaf nodes: " << promotions << std::endl;
std::cout << " ◌ Castling moves in leaf nodes: " << castles << std::endl;
std::cout << " ◌ Enpassant moves in leaf nodes: " << enpassant << std::endl;
std::cout << " ◌ Divide tree:" << std::endl;
for(auto const& x : divideTree) {
std::cout << " ◌ " << x.first << ":" << x.second << std::endl;
}
}
unsigned long long Board::perft(std::map<std::string, int>& divideTree, int depth, int& enpassant, int& promotions, int& castles) {
if(depth == 0) {
return 1;
}
unsigned long long numMoves = 0;
undoStack.emplace_back();
std::vector<Move> moveList;
moveList.reserve(MaxNumMoves);
generateAllNoisyMoves(moveList);
generateAllQuietMoves(moveList);
for(Move& move : moveList) {
applyMoveWithUndo(move, undoStack.back());
if(!didLastMoveLeaveInCheck()) {
if(depth == 1) {
if(move.getMoveType() == Move::MoveType::Enpassant) {
enpassant++;
} else if(move.getMoveType() == Move::MoveType::Promotion) {
promotions++;
} else if(move.getMoveType() == Move::MoveType::Castle) {
castles++;
}
}
int subNodes = perft(divideTree, depth - 1, enpassant, promotions, castles);
if(depth == perftRootDepth) {
divideTree[move.toString()] += subNodes;
}
numMoves += subNodes;
}
revertMove(undoStack.back());
}
undoStack.pop_back();
return numMoves;
}
Bitboard Board::PrecomputedBinary::calculateRookBishopAttacks(Square square, Bitboard occupiedBoard, const MultiArray<int, 4, 2>& movementDelta) {
Bitboard result = 0;
for(int i = 0; i < 4; i++) {
int rankChange = movementDelta[i][0];
int fileChange = movementDelta[i][1];
for(int rankIndex = getRankIndexOfSquare(square) + rankChange, fileIndex = getFileIndexOfSquare(square) + fileChange; 0 <= rankIndex && rankIndex < NumRanks && 0 <= fileIndex && fileIndex < NumFiles; rankIndex += rankChange, fileIndex += fileChange) {
//in the direction we move, add a bit to the bitboard
setBit(result, getSquare(rankIndex, fileIndex));
//stop if we hit something that blocks us
if(testBit(occupiedBoard, getSquare(rankIndex, fileIndex))) {
break;
}
}
}
return result;
}
void Board::PrecomputedBinary::populateHashTable(HashEntry* table, Square square, Bitboard hash, const MultiArray<int, 4, 2>& movementDelta) {
Bitboard occupiedBoard = 0;
table[square].hash = hash;
//Subtract the edges of the board that we aren't on, since if we hit the edge we can't be blocked by anything (there is nowhere left to go)
table[square].mask = calculateRookBishopAttacks(square, 0, movementDelta) & ~(((FileA | FileH) & ~getFile(getFileIndexOfSquare(square))) | ((Rank1 | Rank8) & ~getRank(getRankIndexOfSquare(square))));
table[square].shift = 64 - popCnt(table[square].mask);
if(square != h8) {
table[square + 1].offset = table[square].offset + (1 << popCnt(table[square].mask));
}
//Initialize the attacks at every square
table[square].offset[computeHashTableIndex(occupiedBoard, table[square])] = calculateRookBishopAttacks(square, occupiedBoard, movementDelta);
occupiedBoard = (occupiedBoard - table[square].mask) & table[square].mask;
while(occupiedBoard != 0) {
table[square].offset[computeHashTableIndex(occupiedBoard, table[square])] = calculateRookBishopAttacks(square, occupiedBoard, movementDelta);
occupiedBoard = (occupiedBoard - table[square].mask) & table[square].mask;
}
}
void Board::evalAddPiece(ColorPiece piece, Square location) {
currentEval += psqt.at(piece)[location];
}
void Board::evalRemovePiece(ColorPiece piece, Square location) {
currentEval -= psqt.at(piece)[location];
}
void Board::initMaterialEval() {
currentEval = 0;
for (int i = 0; i < NumSquares; ++i) {
evalAddPiece(squares[getSquare(i)], getSquare(i));
}
}
bool Board::applyMove(Move& move) {
if(move.isMoveNone()) {
return false;
}
undoStack.emplace_back();
applyMoveWithUndo(move, undoStack.back());
if(didLastMoveLeaveInCheck()) {
revertMove(undoStack.back());
undoStack.pop_back();
return false;
}
return true;
}
bool Board::didLastMoveLeaveInCheck() {
Square kingSquare = getSquare(getLsb(sides[flipColor(turn)] & pieces[King]));
return isSquareAttacked(kingSquare, flipColor(turn));
}
bool Board::isSideInCheck(Color side) {
return isSquareAttacked(getSquare(getLsb(pieces[King] & sides[side])), side);
}
void Board::applyLegalMove(Move& move) {
undoStack.emplace_back();
applyMoveWithUndo(move, undoStack.back());
assert(!didLastMoveLeaveInCheck());
}
void Board::applyMoveWithUndo(Move& move, UndoData& undo) {
undo.positionHash = positionHash;
undo.kingAttackers = kingAttackers;
undo.castlingRooks = castlingRooks;
undo.enpassantSquare = enpassantSquare;
undo.plies = plies;
undo.move = move;
undo.currentEval = currentEval;
fullmoves++;
switch(move.getMoveType()) {
case Move::MoveType::Normal:
applyNormalMoveWithUndo(move, undo);
break;
case Move::MoveType::Castle:
applyCastlingMoveWithUndo(move, undo);
break;
case Move::MoveType::Enpassant:
applyEnpassantMoveWithUndo(move, undo);
break;
case Move::MoveType::Promotion:
applyPromotionMoveWithUndo(move, undo);
break;
}
//if the enpassant square was not updated (i.e. no 2 pawn forward move was played),
//then enpassant expires and we must remove it
if(enpassantSquare == undo.enpassantSquare) {
if (enpassantSquare != None) {
ZobristNums::changeEnPassant(positionHash, getFileIndexOfSquare(enpassantSquare));
}
enpassantSquare = None;
}
// if castling permissions are different, reflect this in zobrist
Bitboard rookChanges = castlingRooks & (~undo.castlingRooks);
if ((rookChanges & sides[White] & FileA) != 0) {
ZobristNums::changeCastleRights(positionHash, White, true);
}
if ((rookChanges & sides[Black] & FileA) != 0) {
ZobristNums::changeCastleRights(positionHash, White, false);
}
if ((rookChanges & sides[White] & FileH) != 0) {
ZobristNums::changeCastleRights(positionHash, Black, true);
}
if ((rookChanges & sides[Black] & FileH) != 0) {
ZobristNums::changeCastleRights(positionHash, Black, false);
}
//flip whose turn it is
turn = flipColor(turn);
ZobristNums::flipColor(positionHash);
kingAttackers = getAllKingAttackers();
}
void Board::applyNormalMoveWithUndo(Move& move, UndoData& undo) {
ColorPiece from = squares[move.getFrom()];
ColorPiece to = squares[move.getTo()];
//If we capture a piece OR move a pawn, reset the fifty move rule
if(getPieceType(from) == Pawn || to != Empty) {
plies = 0;
} else {
plies++;
}
pieces[getPieceType(from)] ^= (1ull << move.getFrom()) ^ (1ull << move.getTo());
sides[turn] ^= (1ull << move.getFrom()) ^ (1ull << move.getTo());
//zobrist hash update
ZobristNums::changePiece(positionHash, getColorOfPiece(from), getPieceType(from), move.getFrom());
ZobristNums::changePiece(positionHash, getColorOfPiece(from), getPieceType(from), move.getTo());
// material eval update
evalAddPiece(from, move.getTo());
evalRemovePiece(from, move.getFrom());
//if we captured
if(to != Empty) {
pieces[getPieceType(to)] ^= (1ull << move.getTo());
sides[flipColor(turn)] ^= (1ull << move.getTo());
ZobristNums::changePiece(positionHash, getColorOfPiece(to), getPieceType(to), move.getTo());
evalRemovePiece(to, move.getTo());
}
squares[move.getFrom()] = Empty;
squares[move.getTo()] = from;
castlingRooks &= castleMasks[move.getFrom()];
castlingRooks &= castleMasks[move.getTo()];
undo.pieceCaptured = to;
//if we move 2 forward, set enpassant data
if(getPieceType(from) == Pawn && (move.getTo() ^ move.getFrom()) == 16
&& 0 != (pieces[Pawn] & sides[flipColor(turn)] & PrecomputedBinary::getBinary().getAdjacentFilesMask(getFileIndexOfSquare(move.getFrom())) & ((turn == White) ? Rank4 : Rank5))) {
enpassantSquare = getSquare((turn == White) ? move.getFrom() + 8 : move.getFrom() - 8);
ZobristNums::changeEnPassant(positionHash, getFileIndexOfSquare(enpassantSquare));
}
}
Square Board::getKingCastlingSquare(Square king, Square rook) {
return getSquare(getRankIndexOfSquare(king), static_cast<Index>(rook > king ? 6 : 2)); //return the castling square on the king's rank (which corresponds to the file)
}
Square Board::getRookCastlingSquare(Square king, Square rook) {
return getSquare(getRankIndexOfSquare(king), static_cast<Index>(rook > king ? 5 : 3));
}
void Board::applyCastlingMoveWithUndo(Move& move, Board::UndoData& undo) {
Square kingFrom = move.getFrom();
Square rookFrom = move.getTo();
assert(getPieceType(squares[kingFrom]) == King);
Square kingTo = getKingCastlingSquare(kingFrom, rookFrom);
Square rookTo = getRookCastlingSquare(kingFrom, rookFrom);
//zobrist hash update
ZobristNums::changePiece(positionHash, getColorOfPiece(squares[move.getFrom()]), King, kingTo);
ZobristNums::changePiece(positionHash, getColorOfPiece(squares[move.getFrom()]), King, kingFrom);
ZobristNums::changePiece(positionHash, getColorOfPiece(squares[move.getFrom()]), Rook, rookTo);
ZobristNums::changePiece(positionHash, getColorOfPiece(squares[move.getFrom()]), Rook, rookFrom);
//material eval update
evalAddPiece(squares[kingFrom], kingTo);
evalRemovePiece(squares[kingFrom], kingFrom);
evalAddPiece(squares[rookFrom], rookTo);
evalRemovePiece(squares[rookFrom], rookFrom);
pieces[King] ^= (1ull << kingFrom) ^ (1ull << kingTo);
sides[turn] ^= (1ull << kingFrom) ^ (1ull << kingTo);
pieces[Rook] ^= (1ull << rookFrom) ^ (1ull << rookTo);
sides[turn] ^= (1ull << rookFrom) ^ (1ull << rookTo);
squares[kingFrom] = Empty;
squares[rookFrom] = Empty;
squares[kingTo] = makePiece(King, turn);
squares[rookTo] = makePiece(Rook, turn);
castlingRooks &= castleMasks[kingFrom];
undo.pieceCaptured = Empty;
plies++;
}
void Board::applyEnpassantMoveWithUndo(Move& move, Board::UndoData& undo) {
Square capturedSquare = getSquare(move.getTo() - 8 + (turn << 4));
//zobrist hash update
ZobristNums::changePiece(positionHash, getColorOfPiece(squares[move.getFrom()]), Pawn, move.getTo());
ZobristNums::changePiece(positionHash, getColorOfPiece(squares[move.getFrom()]), Pawn, move.getFrom());
ZobristNums::changePiece(positionHash, flipColor(getColorOfPiece(squares[move.getFrom()])), Pawn, capturedSquare);
//materialEval update
evalAddPiece(squares[move.getFrom()], move.getTo());
evalRemovePiece(squares[move.getFrom()], move.getFrom());
evalRemovePiece(squares[capturedSquare], capturedSquare);
//en passant is a capture, so reset the fifty move rule
plies = 0;
pieces[Pawn] ^= (1ull << move.getFrom()) ^ (1ull << move.getTo());
sides[turn] ^= (1ull << move.getFrom()) ^ (1ull << move.getTo());
pieces[Pawn] ^= (1ull << capturedSquare);
sides[flipColor(turn)] ^= (1ull << capturedSquare);
squares[move.getFrom()] = Empty;
squares[move.getTo()] = makePiece(Pawn, turn);
squares[capturedSquare] = Empty;
undo.pieceCaptured = makePiece(Pawn, flipColor(turn));
}
void Board::applyPromotionMoveWithUndo(Move& move, Board::UndoData& undo) {
ColorPiece promotedPiece = makePiece(move.getPromoType(), turn);
ColorPiece capturedPiece = squares[move.getTo()];
//zobrist hash update
ZobristNums::changePiece(positionHash, getColorOfPiece(promotedPiece), Pawn, move.getFrom());
ZobristNums::changePiece(positionHash, getColorOfPiece(promotedPiece), move.getPromoType(), move.getTo());
//material eval
evalAddPiece(promotedPiece, move.getTo());
evalRemovePiece(squares[move.getFrom()], move.getFrom());
//promotion resets the fifty move rule
plies = 0;
pieces[Pawn] ^= (1ull << move.getFrom());
pieces[move.getPromoType()] ^= (1ull << move.getTo());
sides[turn] ^= (1ull << move.getFrom()) ^ (1ull << move.getTo());
if(capturedPiece != Empty) {
ZobristNums::changePiece(positionHash, getColorOfPiece(capturedPiece), getPieceType(capturedPiece), move.getTo());
evalRemovePiece(squares[move.getTo()], move.getTo());
pieces[getPieceType(capturedPiece)] ^= (1ull << move.getTo());
sides[getColorOfPiece(capturedPiece)] ^= (1ull << move.getTo());
}
squares[move.getFrom()] = Empty;
squares[move.getTo()] = promotedPiece;
undo.pieceCaptured = capturedPiece;
castlingRooks &= castleMasks[move.getTo()];
}
int Board::countLegalMoves() {
std::vector<Move> moveList;
moveList.reserve(MaxNumMoves);
return generateAllLegalMoves(moveList);
}
void Board::revertMostRecent() {
revertMove(undoStack.back());
undoStack.pop_back();
}
void Board::revertMove(UndoData& undo) {
positionHash = undo.positionHash;