This repository has been archived by the owner on Jan 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
1778 lines (1468 loc) · 64.7 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
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 <iostream>
#include <string>
#include <fstream>
#include <deque>
#include <chrono>
#include <array>
#include <bitset>
#include <algorithm>
#include <cassert>
#define ctzll(x) ((x) ? _tzcnt_u64(x) : 64)
#define clzll(x) ((x) ? __lzcnt64(x) : 64)
//#define popcountll(x) __popcnt64(x)
//#define ctzll(x) ((x) ? __builtin_ctzll(x) : 64)
//#define clzll(x) ((x) ? __builtin_clzll(x) : 64)
#define popcountll(x) __builtin_popcountll(x)
#define DEBUG true
#define IFDBG if constexpr (DEBUG)
typedef uint64_t u64;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint8_t u8;
using std::string;
using std::cout;
using std::endl;
constexpr u64 POS_INF = std::numeric_limits<uint64_t>::max();
enum Color : int {
WHITE = 1, BLACK = 0
};
//Inverts the color (WHITE -> BLACK) and (BLACK -> WHITE)
constexpr Color operator~(Color c) {
return Color(c ^ 1);
}
enum PieceType : int {
PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, NO_PIECE_TYPE
};
enum Square : int {
a1, b1, c1, d1, e1, f1, g1, h1,
a2, b2, c2, d2, e2, f2, g2, h2,
a3, b3, c3, d3, e3, f3, g3, h3,
a4, b4, c4, d4, e4, f4, g4, h4,
a5, b5, c5, d5, e5, f5, g5, h5,
a6, b6, c6, d6, e6, f6, g6, h6,
a7, b7, c7, d7, e7, f7, g7, h7,
a8, b8, c8, d8, e8, f8, g8, h8,
NO_SQUARE
};
enum Direction : int {
NORTH = 8, NORTH_EAST = 9, EAST = 1, SOUTH_EAST = -7,
SOUTH = -8, SOUTH_WEST = -9, WEST = -1, NORTH_WEST = 7,
NORTH_NORTH = 16, SOUTH_SOUTH = -16
};
enum File : int {
AFILE, BFILE, CFILE, DFILE, EFILE, FFILE, GFILE, HFILE
};
enum Rank : int {
RANK1, RANK2, RANK3, RANK4, RANK5, RANK6, RANK7, RANK8
};
Square& operator++(Square& s) { return s = Square(int(s) + 1); }
Square& operator--(Square& s) { return s = Square(int(s) - 1); }
constexpr Square operator+(Square s, Direction d) { return Square(int(s) + int(d)); }
constexpr Square operator-(Square s, Direction d) { return Square(int(s) - int(d)); }
Square& operator+=(Square& s, Direction d) { return s = s + d; }
Square& operator-=(Square& s, Direction d) { return s = s - d; }
// Names binary encoding flags from Move class
enum MoveType {
STANDARD_MOVE = 0, DOUBLE_PUSH = 0b1, CASTLE_K = 0b10, CASTLE_Q = 0b11, CAPTURE = 0b100, EN_PASSANT = 0b101, KNIGHT_PROMO = 0b1000, BISHOP_PROMO = 0b1001, ROOK_PROMO = 0b1010, QUEEN_PROMO = 0b1011, KNIGHT_PROMO_CAPTURE = 0b1100, BISHOP_PROMO_CAPTURE = 0b1101, ROOK_PROMO_CAPTURE = 0b1110, QUEEN_PROMO_CAPTURE = 0b1111
};
struct shifts {
static inline int NORTH = 8;
static inline int NORTH_EAST = 9;
static inline int EAST = 1;
static inline int SOUTH_EAST = -7;
static inline int SOUTH = -8;
static inline int SOUTH_WEST = -9;
static inline int WEST = -1;
static inline int NORTH_WEST = 7;
static inline std::array<int, 8> dirs = { NORTH, NORTH_EAST, EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST, NORTH_WEST };
static inline std::array<int, 4> straightDirs = { NORTH, EAST, SOUTH, WEST };
static inline std::array<int, 4> diagonalDirs = { NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST };
};
struct indexes {
static inline int NORTH = 0;
static inline int NORTH_EAST = 1;
static inline int EAST = 2;
static inline int SOUTH_EAST = 3;
static inline int SOUTH = 4;
static inline int SOUTH_WEST = 5;
static inline int WEST = 6;
static inline int NORTH_WEST = 7;
static inline int all = 8;
static inline std::array<int, 8> dirs = { NORTH, NORTH_EAST, EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST, NORTH_WEST };
static inline std::array<int, 4> straightDirs = { NORTH, EAST, SOUTH, WEST };
static inline std::array<int, 4> diagonalDirs = { NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST };
};
static int parseSquare(const string& square) {
return (square.at(1) - '1') * 8 + (square.at(0) - 'a'); // Calculate the index of any square
}
static string squareToAlgebraic(int sq) {
return string(1, 'a' + (sq % 8)) + string(1, '1' + (sq / 8));
};
template <typename BitboardType>
static bool readBit(BitboardType bitboard, int index) {
return (bitboard & (1ULL << index)) != 0;
}
template <typename BitboardType>
static void setBit(BitboardType& bitboard, int index, bool value) {
if (value) bitboard |= (1ULL << index);
else bitboard &= ~(1ULL << index);
}
class Board;
class Move {
// Bit indexes of various things
// See https://www.chessprogramming.org/Encoding_Moves
// Does not use double pawn push flag
// PROMO = 15
// CAPTURE = 14
// SPECIAL 1 = 13
// SPECIAL 0 = 12
private:
uint16_t move;
public:
Move() {
move = 0;
}
Move(string in, Board& board);
Move(u8 startSquare, u8 endSquare, int flags = STANDARD_MOVE) {
move = startSquare;
move |= endSquare << 6;
move |= flags << 12;
}
string toString();
int startSquare() { return move & 0b111111; }
int endSquare() { return (move >> 6) & 0b111111; }
MoveType typeOf() { return MoveType(move >> 12); } // Return the flag bits
};
std::deque<string> split(const string& s, char delim) {
std::deque<string> result;
std::stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
result.push_back(item);
}
return result;
}
int findIndexOf(const std::deque<string>& deque, string entry) {
auto it = std::find(deque.begin(), deque.end(), entry);
if (it != deque.end()) {
return std::distance(deque.begin(), it); // Calculate the index
}
return -1; // Not found
}
void printBitboard(u64 bitboard) {
for (int rank = 7; rank >= 0; --rank) {
cout << "+---+---+---+---+---+---+---+---+" << endl;
for (int file = 0; file < 8; ++file) {
int i = rank * 8 + file; // Map rank and file to bitboard index
char currentPiece = readBit(bitboard, i) ? '1' : ' ';
cout << "| " << currentPiece << " ";
}
cout << "|" << endl;
}
cout << "+---+---+---+---+---+---+---+---+" << endl;
}
string formatNum(u64 v) {
auto s = std::to_string(v);
int n = s.length() - 3;
while (n > 0) {
s.insert(n, ",");
n -= 3;
}
return s;
}
class Precomputed {
public:
static std::array<u64, 64> knightMoves;
static std::array<u64, 64> kingMoves;
static u64 isOnA;
static u64 isOnB;
static u64 isOnC;
static u64 isOnD;
static u64 isOnE;
static u64 isOnF;
static u64 isOnG;
static u64 isOnH;
static u64 isOn1;
static u64 isOn2;
static u64 isOn3;
static u64 isOn4;
static u64 isOn5;
static u64 isOn6;
static u64 isOn7;
static u64 isOn8;
static void compute() {
// *** FILE AND COL ARRAYS ***
isOnA = 0;
isOnB = 0;
isOnC = 0;
isOnD = 0;
isOnE = 0;
isOnF = 0;
isOnG = 0;
isOnH = 0;
isOn1 = 0;
isOn2 = 0;
isOn3 = 0;
isOn4 = 0;
isOn5 = 0;
isOn6 = 0;
isOn7 = 0;
isOn8 = 0;
for (int i = 0; i < 64; ++i) {
int file = i % 8; // File index (0 = A, 1 = B, ..., 7 = H)
if (file == 0) isOnA |= 1ULL << i;
if (file == 1) isOnB |= 1ULL << i;
if (file == 2) isOnC |= 1ULL << i;
if (file == 3) isOnD |= 1ULL << i;
if (file == 4) isOnE |= 1ULL << i;
if (file == 5) isOnF |= 1ULL << i;
if (file == 6) isOnG |= 1ULL << i;
if (file == 7) isOnH |= 1ULL << i;
// Fill ranks (1-8)
int rank = i / 8; // Rank index (0 = 1, 1 = 2, ..., 7 = 8)
if (rank == 0) isOn1 |= 1ULL << i;
if (rank == 1) isOn2 |= 1ULL << i;
if (rank == 2) isOn3 |= 1ULL << i;
if (rank == 3) isOn4 |= 1ULL << i;
if (rank == 4) isOn5 |= 1ULL << i;
if (rank == 5) isOn6 |= 1ULL << i;
if (rank == 6) isOn7 |= 1ULL << i;
if (rank == 7) isOn8 |= 1ULL << i;
}
// *** KNIGHT MOVES ***
bool onNEdge;
bool onNEdge2;
bool onEEdge;
bool onEEdge2;
bool onSEdge;
bool onSEdge2;
bool onWEdge;
bool onWEdge2;
for (int i = 0; i < 64; ++i) {
onNEdge = i / 8 == 7;
onNEdge2 = i / 8 == 7 || i / 8 == 6;
onEEdge = i % 8 == 7;
onEEdge2 = i % 8 == 7 || i % 8 == 6;
onSEdge = i / 8 == 0;
onSEdge2 = i / 8 == 0 || i / 8 == 1;
onWEdge = i % 8 == 0;
onWEdge2 = i % 8 == 0 || i % 8 == 1;
u64 positions = 0;
if (!onNEdge2 && !onEEdge) setBit(positions, i + 17, 1); // Up 2, right 1
if (!onNEdge && !onEEdge2) setBit(positions, i + 10, 1); // Up 1, right 2
if (!onSEdge && !onEEdge2) setBit(positions, i - 6, 1); // Down 1, right 2
if (!onSEdge2 && !onEEdge) setBit(positions, i - 15, 1); // Down 2, right 1
if (!onSEdge2 && !onWEdge) setBit(positions, i - 17, 1); // Down 2, left 1
if (!onSEdge && !onWEdge2) setBit(positions, i - 10, 1); // Down 1, left 2
if (!onNEdge && !onWEdge2) setBit(positions, i + 6, 1); // Up 1, left 2
if (!onNEdge2 && !onWEdge) setBit(positions, i + 15, 1); // Up 2, left 1
knightMoves[i] = positions;
}
// *** KING MOVES ***
for (int i = 0; i < 64; ++i) {
onNEdge = (1ULL << i) & isOn8;
onEEdge = (1ULL << i) & isOnH;
onSEdge = (1ULL << i) & isOn1;
onWEdge = (1ULL << i) & isOnA;
u64 positions = 0;
// Horizontal
if (!onNEdge) setBit(positions, i + shifts::NORTH, 1);
if (!onEEdge) setBit(positions, i + shifts::EAST, 1);
if (!onSEdge) setBit(positions, i + shifts::SOUTH, 1);
if (!onWEdge) setBit(positions, i + shifts::WEST, 1);
// Diagonal
if (!onNEdge && !onEEdge) setBit(positions, i + shifts::NORTH_EAST, 1);
if (!onNEdge && !onWEdge) setBit(positions, i + shifts::NORTH_WEST, 1);
if (!onSEdge && !onEEdge) setBit(positions, i + shifts::SOUTH_EAST, 1);
if (!onSEdge && !onWEdge) setBit(positions, i + shifts::SOUTH_WEST, 1);
kingMoves[i] = positions;
}
}
};
std::array<u64, 64> Precomputed::knightMoves;
std::array<u64, 64> Precomputed::kingMoves;
u64 Precomputed::isOnA;
u64 Precomputed::isOnB;
u64 Precomputed::isOnC;
u64 Precomputed::isOnD;
u64 Precomputed::isOnE;
u64 Precomputed::isOnF;
u64 Precomputed::isOnG;
u64 Precomputed::isOnH;
u64 Precomputed::isOn1;
u64 Precomputed::isOn2;
u64 Precomputed::isOn3;
u64 Precomputed::isOn4;
u64 Precomputed::isOn5;
u64 Precomputed::isOn6;
u64 Precomputed::isOn7;
u64 Precomputed::isOn8;
constexpr Rank rankOf(Square s) { return Rank(s >> 3); }
constexpr File fileOf(Square s) { return File(s & 0b111); }
// *** MANY A PROGRAMMER HAS "BORROWED" CODE. I AM NO EXCEPTION ***
// Original code from https://github.com/nkarve/surge/blob/master/src/tables.cpp
constexpr int diagonalOf(Square s) { return 7 + rankOf(s) - fileOf(s); }
constexpr int antiDiagonalOf(Square s) { return rankOf(s) + fileOf(s); }
//Precomputed file masks
const u64 MASK_FILE[8] = {
0x101010101010101, 0x202020202020202, 0x404040404040404, 0x808080808080808,
0x1010101010101010, 0x2020202020202020, 0x4040404040404040, 0x8080808080808080,
};
//Precomputed rank masks
const u64 MASK_RANK[8] = {
0xff, 0xff00, 0xff0000, 0xff000000,
0xff00000000, 0xff0000000000, 0xff000000000000, 0xff00000000000000
};
//Precomputed diagonal masks
const u64 MASK_DIAGONAL[15] = {
0x80, 0x8040, 0x804020,
0x80402010, 0x8040201008, 0x804020100804,
0x80402010080402, 0x8040201008040201, 0x4020100804020100,
0x2010080402010000, 0x1008040201000000, 0x804020100000000,
0x402010000000000, 0x201000000000000, 0x100000000000000,
};
//Precomputed anti-diagonal masks
const u64 MASK_ANTI_DIAGONAL[15] = {
0x1, 0x102, 0x10204,
0x1020408, 0x102040810, 0x10204081020,
0x1020408102040, 0x102040810204080, 0x204081020408000,
0x408102040800000, 0x810204080000000, 0x1020408000000000,
0x2040800000000000, 0x4080000000000000, 0x8000000000000000,
};
//Precomputed square masks
const u64 SQUARE_BB[65] = {
0x1, 0x2, 0x4, 0x8,
0x10, 0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800,
0x1000, 0x2000, 0x4000, 0x8000,
0x10000, 0x20000, 0x40000, 0x80000,
0x100000, 0x200000, 0x400000, 0x800000,
0x1000000, 0x2000000, 0x4000000, 0x8000000,
0x10000000, 0x20000000, 0x40000000, 0x80000000,
0x100000000, 0x200000000, 0x400000000, 0x800000000,
0x1000000000, 0x2000000000, 0x4000000000, 0x8000000000,
0x10000000000, 0x20000000000, 0x40000000000, 0x80000000000,
0x100000000000, 0x200000000000, 0x400000000000, 0x800000000000,
0x1000000000000, 0x2000000000000, 0x4000000000000, 0x8000000000000,
0x10000000000000, 0x20000000000000, 0x40000000000000, 0x80000000000000,
0x100000000000000, 0x200000000000000, 0x400000000000000, 0x800000000000000,
0x1000000000000000, 0x2000000000000000, 0x4000000000000000, 0x8000000000000000,
0x0
};
//Reverses a bitboard
u64 reverse(u64 b) {
b = (b & 0x5555555555555555) << 1 | (b >> 1) & 0x5555555555555555;
b = (b & 0x3333333333333333) << 2 | (b >> 2) & 0x3333333333333333;
b = (b & 0x0f0f0f0f0f0f0f0f) << 4 | (b >> 4) & 0x0f0f0f0f0f0f0f0f;
b = (b & 0x00ff00ff00ff00ff) << 8 | (b >> 8) & 0x00ff00ff00ff00ff;
return (b << 48) | ((b & 0xffff0000) << 16) |
((b >> 16) & 0xffff0000) | (b >> 48);
}
//Calculates sliding attacks from a given square, on a given axis, taking into
//account the blocking pieces. This uses the Hyperbola Quintessence Algorithm.
u64 sliding_attacks(Square square, u64 occ, u64 mask) {
return (((mask & occ) - SQUARE_BB[square] * 2) ^
reverse(reverse(mask & occ) - reverse(SQUARE_BB[square]) * 2)) & mask;
}
//Returns rook attacks from a given square, using the Hyperbola Quintessence Algorithm. Only used to initialize
//the magic lookup table
u64 get_rook_attacks_for_init(Square square, u64 occ) {
return sliding_attacks(square, occ, MASK_FILE[fileOf(square)]) |
sliding_attacks(square, occ, MASK_RANK[rankOf(square)]);
}
u64 ROOK_ATTACK_MASKS[64];
int ROOK_ATTACK_SHIFTS[64];
u64 ROOK_ATTACKS[64][4096];
const u64 ROOK_MAGICS[64] = {
0x0080001020400080, 0x0040001000200040, 0x0080081000200080, 0x0080040800100080,
0x0080020400080080, 0x0080010200040080, 0x0080008001000200, 0x0080002040800100,
0x0000800020400080, 0x0000400020005000, 0x0000801000200080, 0x0000800800100080,
0x0000800400080080, 0x0000800200040080, 0x0000800100020080, 0x0000800040800100,
0x0000208000400080, 0x0000404000201000, 0x0000808010002000, 0x0000808008001000,
0x0000808004000800, 0x0000808002000400, 0x0000010100020004, 0x0000020000408104,
0x0000208080004000, 0x0000200040005000, 0x0000100080200080, 0x0000080080100080,
0x0000040080080080, 0x0000020080040080, 0x0000010080800200, 0x0000800080004100,
0x0000204000800080, 0x0000200040401000, 0x0000100080802000, 0x0000080080801000,
0x0000040080800800, 0x0000020080800400, 0x0000020001010004, 0x0000800040800100,
0x0000204000808000, 0x0000200040008080, 0x0000100020008080, 0x0000080010008080,
0x0000040008008080, 0x0000020004008080, 0x0000010002008080, 0x0000004081020004,
0x0000204000800080, 0x0000200040008080, 0x0000100020008080, 0x0000080010008080,
0x0000040008008080, 0x0000020004008080, 0x0000800100020080, 0x0000800041000080,
0x00FFFCDDFCED714A, 0x007FFCDDFCED714A, 0x003FFFCDFFD88096, 0x0000040810002101,
0x0001000204080011, 0x0001000204000801, 0x0001000082000401, 0x0001FFFAABFAD1A2
};
//Initializes the magic lookup table for rooks
void initializeRookAttacks() {
u64 edges, subset, index;
for (Square sq = a1; sq <= h8; ++sq) {
edges = ((MASK_RANK[AFILE] | MASK_RANK[HFILE]) & ~MASK_RANK[rankOf(sq)]) |
((MASK_FILE[AFILE] | MASK_FILE[HFILE]) & ~MASK_FILE[fileOf(sq)]);
ROOK_ATTACK_MASKS[sq] = (MASK_RANK[rankOf(sq)]
^ MASK_FILE[fileOf(sq)]) & ~edges;
ROOK_ATTACK_SHIFTS[sq] = 64 - popcountll(ROOK_ATTACK_MASKS[sq]);
subset = 0;
do {
index = subset;
index = index * ROOK_MAGICS[sq];
index = index >> ROOK_ATTACK_SHIFTS[sq];
ROOK_ATTACKS[sq][index] = get_rook_attacks_for_init(sq, subset);
subset = (subset - ROOK_ATTACK_MASKS[sq]) & ROOK_ATTACK_MASKS[sq];
} while (subset);
}
}
//Returns the attacks bitboard for a rook at a given square, using the magic lookup table
constexpr u64 getRookAttacks(Square square, u64 occ) {
return ROOK_ATTACKS[square][((occ & ROOK_ATTACK_MASKS[square]) * ROOK_MAGICS[square])
>> ROOK_ATTACK_SHIFTS[square]];
}
//Returns the 'x-ray attacks' for a rook at a given square. X-ray attacks cover squares that are not immediately
//accessible by the rook, but become available when the immediate blockers are removed from the board
u64 getXrayRookAttacks(Square square, u64 occ, u64 blockers) {
u64 attacks = getRookAttacks(square, occ);
blockers &= attacks;
return attacks ^ getRookAttacks(square, occ ^ blockers);
}
//Returns bishop attacks from a given square, using the Hyperbola Quintessence Algorithm. Only used to initialize
//the magic lookup table
u64 getBishopAttacksForInit(Square square, u64 occ) {
return sliding_attacks(square, occ, MASK_DIAGONAL[diagonalOf(square)]) |
sliding_attacks(square, occ, MASK_ANTI_DIAGONAL[antiDiagonalOf(square)]);
}
u64 BISHOP_ATTACK_MASKS[64];
int BISHOP_ATTACK_SHIFTS[64];
u64 BISHOP_ATTACKS[64][512];
const u64 BISHOP_MAGICS[64] = {
0x0002020202020200, 0x0002020202020000, 0x0004010202000000, 0x0004040080000000,
0x0001104000000000, 0x0000821040000000, 0x0000410410400000, 0x0000104104104000,
0x0000040404040400, 0x0000020202020200, 0x0000040102020000, 0x0000040400800000,
0x0000011040000000, 0x0000008210400000, 0x0000004104104000, 0x0000002082082000,
0x0004000808080800, 0x0002000404040400, 0x0001000202020200, 0x0000800802004000,
0x0000800400A00000, 0x0000200100884000, 0x0000400082082000, 0x0000200041041000,
0x0002080010101000, 0x0001040008080800, 0x0000208004010400, 0x0000404004010200,
0x0000840000802000, 0x0000404002011000, 0x0000808001041000, 0x0000404000820800,
0x0001041000202000, 0x0000820800101000, 0x0000104400080800, 0x0000020080080080,
0x0000404040040100, 0x0000808100020100, 0x0001010100020800, 0x0000808080010400,
0x0000820820004000, 0x0000410410002000, 0x0000082088001000, 0x0000002011000800,
0x0000080100400400, 0x0001010101000200, 0x0002020202000400, 0x0001010101000200,
0x0000410410400000, 0x0000208208200000, 0x0000002084100000, 0x0000000020880000,
0x0000001002020000, 0x0000040408020000, 0x0004040404040000, 0x0002020202020000,
0x0000104104104000, 0x0000002082082000, 0x0000000020841000, 0x0000000000208800,
0x0000000010020200, 0x0000000404080200, 0x0000040404040400, 0x0002020202020200
};
//Initializes the magic lookup table for bishops
void initializeBishopAttacks() {
u64 edges, subset, index;
for (Square sq = a1; sq <= h8; ++sq) {
edges = ((MASK_RANK[AFILE] | MASK_RANK[HFILE]) & ~MASK_RANK[rankOf(sq)]) |
((MASK_FILE[AFILE] | MASK_FILE[HFILE]) & ~MASK_FILE[fileOf(sq)]);
BISHOP_ATTACK_MASKS[sq] = (MASK_DIAGONAL[diagonalOf(sq)]
^ MASK_ANTI_DIAGONAL[antiDiagonalOf(sq)]) & ~edges;
BISHOP_ATTACK_SHIFTS[sq] = 64 - popcountll(BISHOP_ATTACK_MASKS[sq]);
subset = 0;
do {
index = subset;
index = index * BISHOP_MAGICS[sq];
index = index >> BISHOP_ATTACK_SHIFTS[sq];
BISHOP_ATTACKS[sq][index] = getBishopAttacksForInit(sq, subset);
subset = (subset - BISHOP_ATTACK_MASKS[sq]) & BISHOP_ATTACK_MASKS[sq];
} while (subset);
}
}
//Returns the attacks bitboard for a bishop at a given square, using the magic lookup table
constexpr u64 getBishopAttacks(Square square, u64 occ) {
return BISHOP_ATTACKS[square][((occ & BISHOP_ATTACK_MASKS[square]) * BISHOP_MAGICS[square])
>> BISHOP_ATTACK_SHIFTS[square]];
}
//Returns the 'x-ray attacks' for a bishop at a given square. X-ray attacks cover squares that are not immediately
//accessible by the rook, but become available when the immediate blockers are removed from the board
u64 getXrayBishopAttacks(Square square, u64 occ, u64 blockers) {
u64 attacks = getBishopAttacks(square, occ);
blockers &= attacks;
return attacks ^ getBishopAttacks(square, occ ^ blockers);
}
u64 SQUARES_BETWEEN_BB[64][64];
//Initializes the lookup table for the bitboard of squares in between two given squares (0 if the
//two squares are not aligned)
void initializeSquaresBetween() {
u64 sqs;
for (Square sq1 = a1; sq1 <= h8; ++sq1)
for (Square sq2 = a1; sq2 <= h8; ++sq2) {
sqs = SQUARE_BB[sq1] | SQUARE_BB[sq2];
if (fileOf(sq1) == fileOf(sq2) || rankOf(sq1) == rankOf(sq2))
SQUARES_BETWEEN_BB[sq1][sq2] =
get_rook_attacks_for_init(sq1, sqs) & get_rook_attacks_for_init(sq2, sqs);
else if (diagonalOf(sq1) == diagonalOf(sq2) || antiDiagonalOf(sq1) == antiDiagonalOf(sq2))
SQUARES_BETWEEN_BB[sq1][sq2] =
getBishopAttacksForInit(sq1, sqs) & getBishopAttacksForInit(sq2, sqs);
}
}
u64 LINE[64][64];
u64 LINESEG[64][64]; // ADDITION, SEGMENTS OF A LINE BETWEEN SQUARES GIVEN, FOR FINDING PINNED PIECES.
//Initializes the lookup table for the bitboard of all squares along the line of two given squares (0 if the
//two squares are not aligned)
void initializeLine() {
for (Square sq1 = a1; sq1 <= h8; ++sq1) {
for (Square sq2 = a1; sq2 <= h8; ++sq2) {
if (fileOf(sq1) == fileOf(sq2) || rankOf(sq1) == rankOf(sq2))
LINE[sq1][sq2] =
get_rook_attacks_for_init(sq1, 0) & get_rook_attacks_for_init(sq2, 0)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
else if (diagonalOf(sq1) == diagonalOf(sq2) || antiDiagonalOf(sq1) == antiDiagonalOf(sq2))
LINE[sq1][sq2] =
getBishopAttacksForInit(sq1, 0) & getBishopAttacksForInit(sq2, 0)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
}
}
for (Square sq1 = a1; sq1 <= h8; ++sq1) {
for (Square sq2 = a1; sq2 <= h8; ++sq2) {
u64 blockers = (1ULL << sq1) | (1ULL << sq2);
if (fileOf(sq1) == fileOf(sq2) || rankOf(sq1) == rankOf(sq2))
LINESEG[sq1][sq2] =
get_rook_attacks_for_init(sq1, blockers) & get_rook_attacks_for_init(sq2, blockers)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
else if (diagonalOf(sq1) == diagonalOf(sq2) || antiDiagonalOf(sq1) == antiDiagonalOf(sq2))
LINESEG[sq1][sq2] =
getBishopAttacksForInit(sq1, blockers) & getBishopAttacksForInit(sq2, blockers)
| SQUARE_BB[sq1] | SQUARE_BB[sq2];
}
}
}
//Initializes lookup tables for rook moves, bishop moves, in-between squares, aligned squares and pseudolegal moves
void initializeAllDatabases() {
initializeRookAttacks();
initializeBishopAttacks();
initializeSquaresBetween();
initializeLine();
}
// Back to my code from here and below
struct MoveEvaluation {
Move move;
int eval;
};
struct MoveList {
std::array<Move, 218> moves;
int count;
MoveList() {
count = 0;
}
void add(Move m) {
moves[count++] = m;
}
void sortByString(Board& board) {
std::array<string, 218> movesStr;
movesStr.fill("zzzz"); // Fill with values to be sorted to back.
for (int i = 0; i < count; ++i) {
movesStr[i] = moves[i].toString();
}
std::sort(movesStr.begin(), movesStr.end());
for (auto& str : movesStr) {
if (str == "zzzz") {
str = "a1a1";
}
}
for (int i = 0; i < count; ++i) {
moves[i] = Move(movesStr[i], board);
}
}
};
class Board {
public:
std::array<u64, 6> white; // Goes pawns, knights, bishops, rooks, queens, king
std::array<u64, 6> black; // Goes pawns, knights, bishops, rooks, queens, king
u64 blackPieces;
u64 whitePieces;
u64 emptySquares;
uint64_t enPassant;
u8 castlingRights;
Color side = WHITE;
int halfMoveClock;
bool doubleCheck = false;
u64 checkMask = 0;
u64 pinned = 0;
void reset() {
// Reset position
white[0] = 0xFF00ULL;
white[1] = 0x42ULL;
white[2] = 0x24ULL;
white[3] = 0x81ULL;
white[4] = 0x8ULL;
white[5] = 0x10ULL;
black[0] = 0xFF000000000000ULL;
black[1] = 0x4200000000000000ULL;
black[2] = 0x2400000000000000ULL;
black[3] = 0x8100000000000000ULL;
black[4] = 0x800000000000000ULL;
black[5] = 0x1000000000000000ULL;
castlingRights = 0xF;
enPassant = 0; // No en passant target square
side = WHITE;
halfMoveClock = 0;
recompute();
updateCheckPin();
}
void clearIndex(int index) {
const u64 mask = ~(1ULL << index);
white[0] &= mask;
white[1] &= mask;
white[2] &= mask;
white[3] &= mask;
white[4] &= mask;
white[5] &= mask;
black[0] &= mask;
black[1] &= mask;
black[2] &= mask;
black[3] &= mask;
black[4] &= mask;
black[5] &= mask;
}
void recompute() {
whitePieces = white[0] | white[1] | white[2] | white[3] | white[4] | white[5];
blackPieces = black[0] | black[1] | black[2] | black[3] | black[4] | black[5];
emptySquares = ~(whitePieces | blackPieces);
}
void generatePawnMoves(MoveList& moves) {
u64 pawns = side ? white[0] : black[0];
u64 pawnPushes = side ? (white[0] << 8) : (black[0] >> 8);
pawnPushes &= emptySquares;
int currentIndex;
u64 pawnCaptureRight = pawns & ~(Precomputed::isOnH);
pawnCaptureRight = side ? (pawnCaptureRight << 9) : (pawnCaptureRight >> 7);
pawnCaptureRight &= side ? blackPieces : whitePieces;
u64 pawnCaptureLeft = pawns & ~(Precomputed::isOnA);
pawnCaptureLeft = side ? (pawnCaptureLeft << 7) : (pawnCaptureLeft >> 9);
pawnCaptureLeft &= side ? blackPieces : whitePieces;
u64 pawnCaptureRightEP = pawns & ~(Precomputed::isOnH);
pawnCaptureRightEP = side ? (pawnCaptureRightEP << 9) : (pawnCaptureRightEP >> 7);
pawnCaptureRightEP &= enPassant;
u64 pawnCaptureLeftEP = pawns & ~(Precomputed::isOnA);
pawnCaptureLeftEP = side ? (pawnCaptureLeftEP << 7) : (pawnCaptureLeftEP >> 9);
pawnCaptureLeftEP &= enPassant;
u64 pawnDoublePush = side ? (white[0] << 16) : (black[0] >> 16);
pawnDoublePush &= emptySquares & (side ? (emptySquares << 8) : (emptySquares >> 8));
pawnDoublePush &= side ? (Precomputed::isOn2 << 16) : (Precomputed::isOn7 >> 16);
while (pawnDoublePush) {
currentIndex = ctzll(pawnDoublePush);
moves.add(Move((side) * (currentIndex - 16) + (!side) * (currentIndex + 16), currentIndex, DOUBLE_PUSH));
pawnDoublePush &= pawnDoublePush - 1;
}
while (pawnPushes) {
currentIndex = ctzll(pawnPushes);
if ((1ULL << currentIndex) & (Precomputed::isOn1 | Precomputed::isOn8)) {
moves.add(Move((side) * (currentIndex - 8) + (!side) * (currentIndex + 8), currentIndex, QUEEN_PROMO));
moves.add(Move((side) * (currentIndex - 8) + (!side) * (currentIndex + 8), currentIndex, ROOK_PROMO));
moves.add(Move((side) * (currentIndex - 8) + (!side) * (currentIndex + 8), currentIndex, BISHOP_PROMO));
moves.add(Move((side) * (currentIndex - 8) + (!side) * (currentIndex + 8), currentIndex, KNIGHT_PROMO));
}
else moves.add(Move((side) * (currentIndex - 8) + (!side) * (currentIndex + 8), currentIndex));
pawnPushes &= pawnPushes - 1;
}
while (pawnCaptureRight) {
currentIndex = ctzll(pawnCaptureRight);
if ((1ULL << currentIndex) & (Precomputed::isOn1 | Precomputed::isOn8)) {
moves.add(Move((side) * (currentIndex - 9) + (!side) * (currentIndex + 7), currentIndex, QUEEN_PROMO_CAPTURE));
moves.add(Move((side) * (currentIndex - 9) + (!side) * (currentIndex + 7), currentIndex, ROOK_PROMO_CAPTURE));
moves.add(Move((side) * (currentIndex - 9) + (!side) * (currentIndex + 7), currentIndex, BISHOP_PROMO_CAPTURE));
moves.add(Move((side) * (currentIndex - 9) + (!side) * (currentIndex + 7), currentIndex, KNIGHT_PROMO_CAPTURE));
}
else moves.add(Move((side) * (currentIndex - 9) + (!side) * (currentIndex + 7), currentIndex, CAPTURE));
pawnCaptureRight &= pawnCaptureRight - 1;
}
while (pawnCaptureLeft) {
currentIndex = ctzll(pawnCaptureLeft);
if ((1ULL << currentIndex) & (Precomputed::isOn1 | Precomputed::isOn8)) {
moves.add(Move((side) * (currentIndex - 7) + (!side) * (currentIndex + 9), currentIndex, QUEEN_PROMO_CAPTURE));
moves.add(Move((side) * (currentIndex - 7) + (!side) * (currentIndex + 9), currentIndex, ROOK_PROMO_CAPTURE));
moves.add(Move((side) * (currentIndex - 7) + (!side) * (currentIndex + 9), currentIndex, BISHOP_PROMO_CAPTURE));
moves.add(Move((side) * (currentIndex - 7) + (!side) * (currentIndex + 9), currentIndex, KNIGHT_PROMO_CAPTURE));
}
else moves.add(Move((side) * (currentIndex - 7) + (!side) * (currentIndex + 9), currentIndex, CAPTURE));
pawnCaptureLeft &= pawnCaptureLeft - 1;
}
while (pawnCaptureRightEP) {
currentIndex = ctzll(pawnCaptureRightEP);
moves.add(Move((side) * (currentIndex - 9) + (!side) * (currentIndex + 7), currentIndex, EN_PASSANT));
pawnCaptureRightEP &= pawnCaptureRightEP - 1;
}
while (pawnCaptureLeftEP) {
currentIndex = ctzll(pawnCaptureLeftEP);
moves.add(Move((side) * (currentIndex - 7) + (!side) * (currentIndex + 9), currentIndex, EN_PASSANT));
pawnCaptureLeftEP &= pawnCaptureLeftEP - 1;
}
}
void generateKnightMoves(MoveList& moves) {
int currentIndex;
u64 knightBitboard = side ? white[1] : black[1];
u64 ourBitboard = side ? whitePieces : blackPieces;
while (knightBitboard > 0) {
u64 knightEmptyMoves = 0;
u64 knightCaptures = 0;
currentIndex = ctzll(knightBitboard);
u64 knightMoves = Precomputed::knightMoves[currentIndex];
knightMoves &= ~ourBitboard;
knightEmptyMoves = knightMoves & emptySquares;
knightCaptures = knightMoves & ~(emptySquares | ourBitboard);
while (knightEmptyMoves > 0) {
moves.add(Move(currentIndex, ctzll(knightEmptyMoves)));
knightEmptyMoves &= knightEmptyMoves - 1;
}
while (knightCaptures > 0) {
moves.add(Move(currentIndex, ctzll(knightCaptures), CAPTURE));
knightCaptures &= knightCaptures - 1;
}
knightBitboard &= knightBitboard - 1; // Clear least significant bit
}
}
void generateBishopMoves(MoveList& moves) {
int currentIndex;
u64 bishopBitboard = side ? (white[2] | white[4]) : (black[2] | black[4]);
u64 ourBitboard = side ? whitePieces : blackPieces;
u64 occupancy = whitePieces | blackPieces;
u64 moveMask;
while (bishopBitboard > 0) {
currentIndex = ctzll(bishopBitboard);
moveMask = getBishopAttacks(Square(currentIndex), occupancy);
moveMask &= ~ourBitboard;
u64 emptyMoves = moveMask & emptySquares;
u64 captures = moveMask & ~(emptySquares | ourBitboard);
// Make move with each legal move in mask
while (emptyMoves > 0) {
int maskIndex = ctzll(emptyMoves);
moves.add(Move(currentIndex, maskIndex));
emptyMoves &= emptyMoves - 1;
}
while (captures > 0) {
int maskIndex = ctzll(captures);
moves.add(Move(currentIndex, maskIndex, CAPTURE));
captures &= captures - 1;
}
bishopBitboard &= bishopBitboard - 1; // Clear least significant bit
}
}
void generateRookMoves(MoveList& moves) {
int currentIndex;
u64 rookBitboard = side ? (white[3] | white[4]) : (black[3] | black[4]);
u64 ourBitboard = side ? whitePieces : blackPieces;
u64 occupancy = whitePieces | blackPieces;
u64 moveMask;
while (rookBitboard > 0) {
currentIndex = ctzll(rookBitboard);
moveMask = getRookAttacks(Square(currentIndex), occupancy);
moveMask &= ~ourBitboard;
u64 emptyMoves = moveMask & emptySquares;
u64 captures = moveMask & ~(emptySquares | ourBitboard);
// Make move with each legal move in mask
while (emptyMoves > 0) {
int maskIndex = ctzll(emptyMoves);
moves.add(Move(currentIndex, maskIndex));
emptyMoves &= emptyMoves - 1;
}
while (captures > 0) {
int maskIndex = ctzll(captures);
moves.add(Move(currentIndex, maskIndex, CAPTURE));
captures &= captures - 1;
}
rookBitboard &= rookBitboard - 1; // Clear least significant bit
}
}
void generateKingMoves(MoveList& moves) {
u64 kingBitboard = side ? white[5] : black[5];
IFDBG assert(("King bitboard is 0", !kingBitboard));
u64 ourBitboard = side ? whitePieces : blackPieces;
int currentIndex = ctzll(kingBitboard);
u64 kingMoves = Precomputed::kingMoves[currentIndex];
kingMoves &= ~ourBitboard;
u64 emptyMoves = kingMoves & emptySquares;
u64 captures = kingMoves & ~(emptySquares | ourBitboard);
// Make move with each legal move in mask
while (emptyMoves > 0) {
int maskIndex = ctzll(emptyMoves);
moves.add(Move(currentIndex, maskIndex));
emptyMoves &= emptyMoves - 1;
}
while (captures > 0) {
int maskIndex = ctzll(captures);
moves.add(Move(currentIndex, maskIndex, CAPTURE));
captures &= captures - 1;
}
// Castling moves
if (side && currentIndex == e1) {
moves.add(Move(e1, g1, CASTLE_K));
moves.add(Move(e1, c1, CASTLE_Q));
}
else if (!side && currentIndex == e8) {
moves.add(Move(e8, g8, CASTLE_K));
moves.add(Move(e8, c8, CASTLE_Q));
}
}
MoveList generateMoves() {
MoveList moves;
generateKingMoves(moves);
if (doubleCheck) { // Returns early when double checks
return moves;
}
generatePawnMoves(moves);
generateKnightMoves(moves);
generateBishopMoves(moves);
generateRookMoves(moves);
// Queen moves are part of bishop/rook gen
return moves;
}
template<PieceType pt>
Square square(Color c) {
return Square(c * (white[pt]) + ~c * (black[pt]));
}
u64 pieces() {
return whitePieces | blackPieces;
}
u64 pieces(PieceType p1, PieceType p2) {
return white[p1] | white[p2] | black[p1] | black[p2];
}
u64 pieces(Color c) {
return (c * whitePieces + ~c * blackPieces);
}