This repository has been archived by the owner on Jan 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkirin.c
2582 lines (2148 loc) · 73.8 KB
/
kirin.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
/*
, ,
\\ \\ Kirin Chess Engine v0.2 (not officially released)
) \\ \\ _p_ created by Strydr Silverberg
)^\))\)) / *\ sophomore year Colorado School of Mines
\_|| || / /^`-'
__ -\ \\--/ / special thanks to
<' \\___/ ___. )' Maxim Korzh https://github.com/maksimKorzh
`====\ )___/\\ ChessProgramming.org https://www.chessprogramming.org
// `" Talk Chess (Computer Chess Club) https://talkchess.com/
\\ / \
`"
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
/************ Define Bitboard Type ************/
#define U64 unsigned long long
//FEN debug positions
#define emptyBoard "8/8/8/8/8/8/8/8 b - - "
#define startPosition "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 "
#define tricky_position "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1 "
#define killer_position "rnbqkb1r/pp1p1pPp/8/2p1pP2/1P1P4/3P3P/P1P1P3/RNBQKBNR w KQkq e6 0 1"
#define cmk_position "r2q1rk1/ppp2ppp/2n1bn2/2b1p3/3pP3/3P1NPP/PPP1NPB1/R1BQ1RK1 b - - 0 9 "
#define new_pos "r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10 "
#define repetitions "2r3k1/R7/8/1R6/8/8/P4KPP/8 w - - 0 40 "
/************ Board Squares ************/
enum {
a8, b8, c8, d8, e8, f8, g8, h8,
a7, b7, c7, d7, e7, f7, g7, h7,
a6, b6, c6, d6, e6, f6, g6, h6,
a5, b5, c5, d5, e5, f5, g5, h5,
a4, b4, c4, d4, e4, f4, g4, h4,
a3, b3, c3, d3, e3, f3, g3, h3,
a2, b2, c2, d2, e2, f2, g2, h2,
a1, b1, c1, d1, e1, f1, g1, h1, no_sq
};
enum { P, N, B, R, Q, K, p, n, b, r, q, k };
enum { white, black, both};
enum { rook, bishop };
/*
bin dec
0001 1 white king can castle to the king side
0010 2 white king can castle to the queen side
0100 4 black king can castle to the king side
1000 8 black king can castle to the queen side
examples
1111 both sides an castle both directions
1001 black king => queen side
white king => king side
*/
enum { wk = 1, wq = 2, bk = 4, bq = 8};
const char *squareCoordinates[] = {
"a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8",
"a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7",
"a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6",
"a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5",
"a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4",
"a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3",
"a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2",
"a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1"
};
char asciiPieces[12] = "PNBRQKpnbrqk";
char *unicodePieces[12] = {"♙", "♘", "♗", "♖", "♕", "♔", "♟", "♞", "♝", "♜", "♛" ,"♚"};
//convert ascii character pieces to encoded constants
int charPieces[] = {
['P'] = P,
['N'] = N,
['B'] = B,
['R'] = R,
['Q'] = Q,
['K'] = K,
['p'] = p,
['n'] = n,
['b'] = b,
['r'] = r,
['q'] = q,
['k'] = k
};
char promotedPieces[] = {
[Q] = 'q',
[R] = 'r',
[B] = 'b',
[N] = 'n',
[q] = 'q',
[r] = 'r',
[b] = 'b',
[n] = 'n',
};
/************ Board Variables ************/
//define piece bitboards, occupancy bitboards, side to move, enpassant square
U64 bitboards[12];
U64 occupancy[3];
int side;
int enpassant = no_sq;
int castle;
//"almost" unique position identifier -> hash key/position key
U64 hashKey;
U64 repetitionTable[1000];
int repetitionIndex;
//half move counter
int ply;
/************ Time Control Variables ************/
int quit = 0;
int movesToGo = 30;
int moveTime = -1;
int timer = -1;
int inc = 0;
int startTime = 0;
int stopTime = 0;
int timeSet = 0;
int stopped = 0;
/************ UCI Time Control Functions from VICE by Richard Allbert ************/
int getTimeMS() {
//get time in ms
struct timeval timeValue;
gettimeofday(&timeValue, NULL);
return timeValue.tv_sec * 1000 + timeValue.tv_usec / 1000;
}
int inputWaiting() {
fd_set readfds;
struct timeval tv;
FD_ZERO (&readfds);
FD_SET (fileno(stdin), &readfds);
tv.tv_sec=0; tv.tv_usec=0;
select(16, &readfds, 0, 0, &tv);
return (FD_ISSET(fileno(stdin), &readfds));
}
void readInput() {
int bytes;
char input[256] = "", *endc;
if(inputWaiting()) {
stopped = 1;
do {
bytes = read(fileno(stdin), input, 256);
} while(bytes < 0);
endc = strchr(input, '\n');
if(endc) *endc=0;
if(strlen(input) > 0) {
if(!strncmp(input, "quit", 4)) quit = 1;
else if(!strncmp(input, "stop", 4)) quit = 1;
}
}
}
static void communicate() {
if(timeSet == 1 && getTimeMS() > stopTime) stopped = 1;
readInput();
}
/************ Random Magic Numbers! ************/
//from Tord Romstad's proposal to find magic numbers https://www.chessprogramming.org/Looking_for_Magics
//pseudo random number state
unsigned int randState = 1804289383;
//generate 32bit pseudo legal numbers
unsigned int getRandU32() {
//get current state
unsigned int num = randState;
//XOR shift algorithm
num ^= num << 13;
num ^= num >> 17;
num ^= num << 5;
randState = num;
return num;
}
//generate 64bity pseudo legal numbers
U64 getRandU64() {
//define 4 random numbers
U64 n1, n2, n3, n4;
n1 = (U64)(getRandU32()) & 0xFFFF;
n2 = (U64)(getRandU32()) & 0xFFFF;
n3 = (U64)(getRandU32()) & 0xFFFF;
n4 = (U64)(getRandU32()) & 0xFFFF;
return n1 | (n2 << 16) | (n3 << 32) | (n4 << 48);
}
//generate magic number candidate
U64 generateMagicNum() {
return getRandU64() & getRandU64() & getRandU64();
}
/************ Define Bit Macros ************/
#define setBit(bitboard, square) ((bitboard) |= (1ULL << (square)))
#define getBit(bitboard, square) ((bitboard) & (1ULL << (square)))
#define popBit(bitboard, square) ((bitboard) &= ~(1ULL << (square)))
//count bits within bitboard
static inline int countBits(U64 bitboard) {
int count = 0;
//consecutively reset least significant first bit in bitboard
while(bitboard) {
count++;
bitboard &= bitboard - 1;
}
return count;
}
//get least significant first bit index
static inline int getLSBindex(U64 bitboard) {
if(bitboard){
//count trailing bits before lsb
return countBits((bitboard &= -bitboard) -1);
} else return -1;
}
/************ Zobrist Hashing ************/
//random piece keys [piece][square] enpassant[square]
U64 pieceKeys[12][64];
U64 enpassantKeys[64];
U64 castlingKeys[16];
U64 sideKey;
void initRandKeys() {
randState = 1804289383;
for(int piece = P; piece <= k; piece++) {
for(int square = 0; square < 64; square++) {
pieceKeys[piece][square] = getRandU64();
}
}
for(int square = 0; square < 64; square++) {
enpassantKeys[square] = getRandU64();
}
for(int key = 0; key < 16; key++) {
castlingKeys[key] = getRandU64();
}
sideKey = getRandU64();
}
//generate "almost" unique position identifier aka hash key from scratch
U64 generateHashKey() {
U64 finalKey = 0ULL;
U64 bitboard;
for(int piece = P; piece <= k; piece++) {
bitboard = bitboards[piece];
while(bitboard) {
int square = getLSBindex(bitboard);
finalKey ^= pieceKeys[piece][square];
popBit(bitboard, square);
}
}
if(enpassant != no_sq) finalKey ^= enpassantKeys[enpassant];
finalKey ^= castlingKeys[castle];
if(side == black) finalKey ^= sideKey;
return finalKey;
}
/************ Input/Output ************/
void printBitboard(U64 bitboard) {
printf("\n");
for(int rank = 0; rank < 8; rank++) {
for(int file = 0; file < 8; file++) {
int square = rank * 8 + file;
if(!file) printf(" %d ", 8 - rank);
printf(" %d", getBit(bitboard, square) ? 1 : 0);
}
printf("\n");
}
printf("\n a b c d e f g h\n\n");
printf(" Bitboard: %llud\n\n", bitboard);
}
void printBoard() {
printf("\n");
for(int rank = 0; rank < 8; rank++) {
for(int file= 0; file < 8; file++) {
int square = rank * 8 + file;
//define piece variable
if(!file) printf(" %d ", 8 - rank);
int piece = -1;
for(int bbPiece = P; bbPiece <= k; bbPiece++) {
if(getBit(bitboards[bbPiece], square)) piece = bbPiece;
}
printf(" %s", (piece == -1) ? "." : unicodePieces[piece]);
}
printf("\n");
}
printf("\n a b c d e f g h \n\n");
printf(" STM: %s\n", (!side && (side != -1)) ? "white" : "black");
printf(" Enpassant: %s\n", (enpassant != no_sq) ? squareCoordinates[enpassant] : "no");
printf(" Castling: %c%c%c%c\n\n", (castle & wk) ? 'K' : '-',
(castle & wq) ? 'Q' : '-',
(castle & bk) ? 'k' : '-',
(castle & bq) ? 'q' : '-');
printf(" Hash Key: %llx\n", hashKey);
}
void parseFEN(char *fen) {
//reset board position and state variables
memset(bitboards, 0ULL, sizeof(bitboards));
memset(occupancy, 0ULL, sizeof(occupancy));
side = 0;
enpassant = no_sq;
castle = 0;
hashKey = 0ULL;
repetitionIndex = 0;
memset(repetitionTable, 0ULL, sizeof(repetitionTable));
ply = 0;
for(int rank = 0; rank < 8; rank++) {
for(int file = 0; file < 8; file++) {
int square = rank * 8 + file;
//match ascii pieces within FEN string
if((*fen >= 'a' && *fen <= 'z') || (*fen >= 'A' && *fen <= 'Z')) {
int piece = charPieces[*fen];
//set piece on corresponding bitboard
setBit(bitboards[piece], square);
//increment pointer to FEN string
fen++;
}
//match empty square numbers within FEN string
if(*fen >= '0' && *fen <= '9') {
//convert char 0 to int 0
int offset = *fen - '0';
int piece = -1;
for(int bbPiece = P; bbPiece <= k; bbPiece++) {
if(getBit(bitboards[bbPiece], square)) piece = bbPiece;
}
if(piece == -1) file--;
file += offset;
fen++;
}
if(*fen == '/') fen++;
}
}
//parse stm
fen++;
(*fen == 'w') ? (side = white) : (side = black);
//parse castling rights
fen += 2;
while(*fen != ' ') {
switch(*fen) {
case 'K': castle |= wk; break;
case 'Q': castle |= wq; break;
case 'k': castle |= bk; break;
case 'q': castle |= bq; break;
case '-': break;
}
fen++;
}
//parse enpassant
fen++;
if(*fen != '-') {
int file = fen[0] - 'a';
int rank = 8 - (fen[1] - '0');
enpassant = rank * 8 + file;
} else enpassant = no_sq;
for(int piece = P; piece <= K; piece++) {
//populate white occupancy bitboard
occupancy[white] |= bitboards[piece];
}
for(int piece = p; piece <= k; piece++) {
occupancy[black] |= bitboards[piece];
}
occupancy[both] |= occupancy[white];
occupancy[both] |= occupancy[black];
hashKey = generateHashKey();
}
/************ Attacks ************/
//not file constants
const U64 notAfile = 18374403900871474942ULL;
const U64 notHfile = 9187201950435737471ULL;
const U64 notHGfile = 4557430888798830399ULL;
const U64 notABfile = 18229723555195321596ULL;
//relevant occupancy bit count for every square on board
const int bishopRelevantBits[64] = {
6, 5, 5, 5, 5, 5, 5, 6,
5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5,
6, 5, 5, 5, 5, 5, 5, 6
};
const int rookRelevantBits[64] = {
12, 11, 11, 11, 11, 11, 11, 12,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
12, 11, 11, 11, 11, 11, 11, 12
};
//bishop, rook magic numbers
U64 rookMagicNums[64] = {
0x8a80104000800020ULL,
0x140002000100040ULL,
0x2801880a0017001ULL,
0x100081001000420ULL,
0x200020010080420ULL,
0x3001c0002010008ULL,
0x8480008002000100ULL,
0x2080088004402900ULL,
0x800098204000ULL,
0x2024401000200040ULL,
0x100802000801000ULL,
0x120800800801000ULL,
0x208808088000400ULL,
0x2802200800400ULL,
0x2200800100020080ULL,
0x801000060821100ULL,
0x80044006422000ULL,
0x100808020004000ULL,
0x12108a0010204200ULL,
0x140848010000802ULL,
0x481828014002800ULL,
0x8094004002004100ULL,
0x4010040010010802ULL,
0x20008806104ULL,
0x100400080208000ULL,
0x2040002120081000ULL,
0x21200680100081ULL,
0x20100080080080ULL,
0x2000a00200410ULL,
0x20080800400ULL,
0x80088400100102ULL,
0x80004600042881ULL,
0x4040008040800020ULL,
0x440003000200801ULL,
0x4200011004500ULL,
0x188020010100100ULL,
0x14800401802800ULL,
0x2080040080800200ULL,
0x124080204001001ULL,
0x200046502000484ULL,
0x480400080088020ULL,
0x1000422010034000ULL,
0x30200100110040ULL,
0x100021010009ULL,
0x2002080100110004ULL,
0x202008004008002ULL,
0x20020004010100ULL,
0x2048440040820001ULL,
0x101002200408200ULL,
0x40802000401080ULL,
0x4008142004410100ULL,
0x2060820c0120200ULL,
0x1001004080100ULL,
0x20c020080040080ULL,
0x2935610830022400ULL,
0x44440041009200ULL,
0x280001040802101ULL,
0x2100190040002085ULL,
0x80c0084100102001ULL,
0x4024081001000421ULL,
0x20030a0244872ULL,
0x12001008414402ULL,
0x2006104900a0804ULL,
0x1004081002402ULL
};
U64 bishopMagicNums[64] = {
0x40040844404084ULL,
0x2004208a004208ULL,
0x10190041080202ULL,
0x108060845042010ULL,
0x581104180800210ULL,
0x2112080446200010ULL,
0x1080820820060210ULL,
0x3c0808410220200ULL,
0x4050404440404ULL,
0x21001420088ULL,
0x24d0080801082102ULL,
0x1020a0a020400ULL,
0x40308200402ULL,
0x4011002100800ULL,
0x401484104104005ULL,
0x801010402020200ULL,
0x400210c3880100ULL,
0x404022024108200ULL,
0x810018200204102ULL,
0x4002801a02003ULL,
0x85040820080400ULL,
0x810102c808880400ULL,
0xe900410884800ULL,
0x8002020480840102ULL,
0x220200865090201ULL,
0x2010100a02021202ULL,
0x152048408022401ULL,
0x20080002081110ULL,
0x4001001021004000ULL,
0x800040400a011002ULL,
0xe4004081011002ULL,
0x1c004001012080ULL,
0x8004200962a00220ULL,
0x8422100208500202ULL,
0x2000402200300c08ULL,
0x8646020080080080ULL,
0x80020a0200100808ULL,
0x2010004880111000ULL,
0x623000a080011400ULL,
0x42008c0340209202ULL,
0x209188240001000ULL,
0x400408a884001800ULL,
0x110400a6080400ULL,
0x1840060a44020800ULL,
0x90080104000041ULL,
0x201011000808101ULL,
0x1a2208080504f080ULL,
0x8012020600211212ULL,
0x500861011240000ULL,
0x180806108200800ULL,
0x4000020e01040044ULL,
0x300000261044000aULL,
0x802241102020002ULL,
0x20906061210001ULL,
0x5a84841004010310ULL,
0x4010801011c04ULL,
0xa010109502200ULL,
0x4a02012000ULL,
0x500201010098b028ULL,
0x8040002811040900ULL,
0x28000010020204ULL,
0x6000020202d0240ULL,
0x8918844842082200ULL,
0x4010011029020020ULL
};
//pawn attack table [side][square], //king, knight, bishop, rook attack table[square]
U64 pawn_attacks[2][64];
U64 knightAttacks[64];
U64 kingAttacks[64];
U64 bishopMasks[64];
U64 rookMasks[64];
//32K and 256K
U64 bishopAttacks[64][512];
U64 rookAttacks[64][4096];
U64 maskPawnAttacks(int side, int square) {
//result attacks bitboard
U64 attacks = 0ULL;
//piece bitboard
U64 bitboard = 0ULL;
setBit(bitboard, square);
//white pawns
if(!side) {
if((bitboard >> 7) & notAfile) attacks |= (bitboard >> 7);
if((bitboard >> 9) & notHfile) attacks |= (bitboard >> 9);
//black pawns
} else {
if((bitboard << 7) & notHfile) attacks |= (bitboard << 7);
if((bitboard << 9) & notAfile) attacks |= (bitboard << 9);
}
//return attack map
return attacks;
}
U64 maskKnightAttacks(int square) {
U64 attacks = 0ULL;
U64 bitboard = 0ULL;
setBit(bitboard, square);
//knight attacks
if((bitboard >> 15) & notAfile) attacks |= (bitboard >> 15);
if((bitboard >> 17) & notHfile) attacks |= (bitboard >> 17);
if((bitboard >> 10) & notHGfile) attacks |= (bitboard >> 10);
if((bitboard >> 6) & notABfile) attacks |= (bitboard >> 6);
if((bitboard << 15) & notHfile) attacks |= (bitboard << 15);
if((bitboard << 17) & notAfile) attacks |= (bitboard << 17);
if((bitboard << 10) & notABfile) attacks |= (bitboard << 10);
if((bitboard << 6) & notHGfile) attacks |= (bitboard << 6);
return attacks;
}
U64 maskKingAttacks(int square) {
U64 attacks = 0ULL;
U64 bitboard = 0ULL;
setBit(bitboard, square);
//king attacks
if(bitboard >> 8) attacks |= (bitboard >> 8);
if((bitboard >> 9) & notHfile) attacks |= (bitboard >> 9);
if((bitboard >> 7) & notAfile) attacks |= (bitboard >> 7);
if((bitboard >> 1) & notHfile) attacks |= (bitboard >> 1);
if(bitboard << 8) attacks |= (bitboard << 8);
if((bitboard << 9) & notAfile) attacks |= (bitboard << 9);
if((bitboard << 7) & notHfile) attacks |= (bitboard << 7);
if((bitboard << 1) & notAfile) attacks |= (bitboard << 1);
return attacks;
}
U64 maskBishopAttacks(int square) {
U64 attacks = 0ULL;
int rank, file;
int targetRank = square / 8;
int targetFile = square % 8;
//mask relevant bishop occupancy bits
for(rank = targetRank + 1, file = targetFile + 1; rank <= 6 && file <= 6; rank++, file++) attacks |= (1ULL << (rank * 8 + file));
for(rank = targetRank - 1, file = targetFile + 1; rank >= 1 && file <= 6; rank--, file++) attacks |= (1ULL << (rank * 8 + file));
for(rank = targetRank + 1, file = targetFile - 1; rank <= 6 && file >= 1; rank++, file--) attacks |= (1ULL << (rank * 8 + file));
for(rank = targetRank - 1, file = targetFile - 1; rank >= 1 && file >= 1; rank--, file--) attacks |= (1ULL << (rank * 8 + file));
return attacks;
}
U64 bishopAttacksOtf(int square, U64 block) {
U64 attacks = 0ULL;
int rank, file;
int targetRank = square / 8;
int targetFile = square % 8;
//mask relevant bishop occupancy bits
for(rank = targetRank + 1, file = targetFile + 1; rank <= 7 && file <= 7; rank++, file++) {
attacks |= (1ULL << (rank * 8 + file));
if((1ULL << (rank * 8 + file)) & block) break;
}
for(rank = targetRank - 1, file = targetFile + 1; rank >= 0 && file <= 7; rank--, file++) {
attacks |= (1ULL << (rank * 8 + file));
if((1ULL << (rank * 8 + file)) & block) break;
}
for(rank = targetRank + 1, file = targetFile - 1; rank <= 7 && file >= 0; rank++, file--) {
attacks |= (1ULL << (rank * 8 + file));
if((1ULL << (rank * 8 + file)) & block) break;
}
for(rank = targetRank - 1, file = targetFile - 1; rank >= 0 && file >= 0; rank--, file--) {
attacks |= (1ULL << (rank * 8 + file));
if((1ULL << (rank * 8 + file)) & block) break;
}
return attacks;
}
U64 maskRookAttacks(int square) {
U64 attacks = 0ULL;
int rank, file;
int targetRank = square / 8;
int targetFile = square % 8;
for(rank = targetRank + 1; rank <=6; rank++) attacks |= (1ULL << (rank * 8 + targetFile));
for(rank = targetRank - 1; rank >=1; rank--) attacks |= (1ULL << (rank * 8 + targetFile));
for(file = targetFile + 1; file <=6; file++) attacks |= (1ULL << (targetRank * 8 + file));
for(file = targetFile - 1; file >=1; file--) attacks |= (1ULL << (targetRank * 8 + file));
return attacks;
}
U64 rookAttacksOtf(int square, U64 block) {
U64 attacks = 0ULL;
int rank, file;
int targetRank = square / 8;
int targetFile = square % 8;
for(rank = targetRank + 1; rank <=7; rank++) {
attacks |= (1ULL << (rank * 8 + targetFile));
if((1ULL << (rank * 8 + targetFile)) & block) break;
}
for(rank = targetRank - 1; rank >=0; rank--) {
attacks |= (1ULL << (rank * 8 + targetFile));
if((1ULL << (rank * 8 + targetFile)) & block) break;
}
for(file = targetFile + 1; file <=7; file++) {
attacks |= (1ULL << (targetRank * 8 + file));
if((1ULL << (targetRank * 8 + file)) & block) break;
}
for(file = targetFile - 1; file >=0; file--) {
attacks |= (1ULL << (targetRank * 8 + file));
if((1ULL << (targetRank * 8 + file)) & block) break;
}
return attacks;
}
/************ Initialize Leaper Piece Attacks ************/
void initLeaperAttacks() {
//loop over 64 board squares
for(int square = 0; square < 64; square++) {
//init pawn attacks
pawn_attacks[white][square] = maskPawnAttacks(white, square);
pawn_attacks[black][square] = maskPawnAttacks(black, square);
//init knight attacks
knightAttacks[square] = maskKnightAttacks(square);
//init king attacks
kingAttacks[square] = maskKingAttacks(square);
}
}
U64 setOccupancy(int index, int bitsInMask, U64 attackMask){
U64 occupancy = 0ULL;
//loop over the range of bits within attack mask
for(int i = 0; i < bitsInMask; i++) {
int square = getLSBindex(attackMask);
popBit(attackMask, square);
//make sure occupancy is on board
if(index & (1 << i)) occupancy |= (1ULL << square);
}
return occupancy;
}
/************ Magics ************/
U64 findMagicNum(int square, int relevantBits, int bishop) {
//init occupancies, attack tables, used attacks, attack mask, occupancy indicies
U64 occupancies[4096];
U64 attacks[4096];
U64 usedAttacks[4096];
U64 attackMask = bishop ? maskBishopAttacks(square) : maskRookAttacks(square);
int occupancyIndicies = 1 << relevantBits;
for(int i = 0; i < occupancyIndicies; i++) {
occupancies[i] = setOccupancy(i, relevantBits, attackMask);
attacks[i] = bishop ? bishopAttacksOtf(square, occupancies[i]) : rookAttacksOtf(square, occupancies[i]);
}
for(int rand = 0; rand < 100000000; rand++) {
//generate magic number candidate
U64 magicNum = generateMagicNum();
//skip inappropriate magic numbers
if(countBits((attackMask * magicNum) & 0xFF00000000000000) < 6) continue;
//init used attacks
memset(usedAttacks, 0ULL, sizeof(usedAttacks));
//init index & fail flag
int index, fail;
//test magic index loop
for(index = 0, fail = 0; !fail && index < occupancyIndicies; index++) {
//init magic index
int magicIndex = (int)((occupancies[index] * magicNum) >> (64 - relevantBits));
//if magic index works, init used attacks
if(usedAttacks[magicIndex] == 0ULL) usedAttacks[magicIndex] = attacks[index];
else if(usedAttacks[magicIndex] != attacks[index]) fail = 1;
}
if(!fail) return magicNum;
}
printf(" Magic number fails!");
return 0ULL;
}
//init magic numbers
void initMagicNum() {
//loop over 64 board squares
for(int square = 0; square < 64; square++) {
rookMagicNums[square] = findMagicNum(square, rookRelevantBits[square], rook);
}
for(int square = 0; square < 64; square++) {
bishopMagicNums[square] = findMagicNum(square, bishopRelevantBits[square], bishop);
}
}
//init slider piece attack tables
void initSliderAttacks(int bishop) {
for(int square = 0; square < 64; square++) {
//init bishop and rook masks
bishopMasks[square] = maskBishopAttacks(square);
rookMasks[square] = maskRookAttacks(square);
U64 attackMask = bishop ? bishopMasks[square] : rookMasks[square];
//init relevant occupancy bit count
int relevantBitsCount = countBits(attackMask);
//init occupancy indicies
int occupancyIndicies = (1 << relevantBitsCount);
for(int i = 0; i < occupancyIndicies; i++) {
if(bishop) {
U64 occupancy = setOccupancy(i, relevantBitsCount, attackMask);
int magicIndex = occupancy * bishopMagicNums[square] >> (64-bishopRelevantBits[square]);
bishopAttacks[square][magicIndex] = bishopAttacksOtf(square, occupancy);
} else {
U64 occupancy = setOccupancy(i, relevantBitsCount, attackMask);
int magicIndex = occupancy * rookMagicNums[square] >> (64-rookRelevantBits[square]);
rookAttacks[square][magicIndex] = rookAttacksOtf(square, occupancy);
}
}
}
}
static inline U64 getBishopAttacks(int square, U64 occupancy) {
//get bishop attacks assuming current board occupancy
occupancy &= bishopMasks[square];
occupancy *= bishopMagicNums[square];
occupancy >>= 64 - bishopRelevantBits[square];
return bishopAttacks[square][occupancy];
}
static inline U64 getRookAttacks(int square, U64 occupancy) {
//get rook attacks assuming current board occupancy
occupancy &= rookMasks[square];
occupancy *= rookMagicNums[square];
occupancy >>= 64 - rookRelevantBits[square];
return rookAttacks[square][occupancy];
}
static inline U64 getQueenAttacks(int square, U64 occupancy) {
U64 result = 0ULL;
U64 bishopOccupancy = occupancy;
U64 rookOccupancy = occupancy;
bishopOccupancy &= bishopMasks[square];
bishopOccupancy *= bishopMagicNums[square];
bishopOccupancy >>= 64 - bishopRelevantBits[square];
result = bishopAttacks[square][bishopOccupancy];
rookOccupancy &= rookMasks[square];
rookOccupancy *= rookMagicNums[square];
rookOccupancy >>= 64 - rookRelevantBits[square];
result |= rookAttacks[square][rookOccupancy];
return result;
}
//is current given square attacked by the current given side
static inline int isAttacked(int square, int side) {
//attacked by pawns
if((side == white) && (pawn_attacks[black][square] & bitboards[P])) return 1;
if((side == black) && (pawn_attacks[white][square] & bitboards[p])) return 1;
//attacked by knights
if(knightAttacks[square] & ((side == white) ? bitboards[N] : bitboards[n])) return 1;
//attacked by bishops
if(getBishopAttacks(square, occupancy[both]) & ((side == white) ? bitboards[B] : bitboards[b])) return 1;
//attacked by rook
if(getRookAttacks(square, occupancy[both]) & ((side == white) ? bitboards[R] : bitboards[r])) return 1;
//attacked by queens
if(getQueenAttacks(square, occupancy[both]) & ((side == white) ? bitboards[Q] : bitboards[q])) return 1;
//attacked by kings
if(kingAttacks[square] & ((side == white) ? bitboards[K] : bitboards[k])) return 1;
//by default, returns false
return 0;
}
//print attacked squares
void print_attacked(int side) {
printf("\n");
for(int rank = 0; rank < 8; rank++) {
for(int file = 0; file < 8; file++) {
int square = rank * 8 + file;
if(!file) printf(" %d ", 8 - rank);
printf(" %d", (isAttacked(square, side)) ? 1 : 0);
}
printf("\n");
}
printf("\n a b c d e f g h\n\n");
}
//binary move representation encoding hexadecimal constants
//0000 0000 0000 0000 0011 1111 source square 0x3f
//0000 0000 0000 1111 1100 0000 target square 0xfc0
//0000 0000 1111 0000 0000 0000 piece 0xf000
//0000 1111 0000 0000 0000 0000 promoted piece 0xf0000
//0001 0000 0000 0000 0000 0000 capture flag 0x100000
//0010 0000 0000 0000 0000 0000 double pawn push flag 0x200000
//0100 0000 0000 0000 0000 0000 enpassant capture flag 0x400000
//1000 0000 0000 0000 0000 0000 castle flag 0x800000
//encode move macro
#define encodeMove(source, target, piece, promoted, capture, dpp, enpassant, castle) \
(source) | (target << 6) | (piece << 12) | (promoted << 16) | \
(capture << 20) | (dpp << 21) | (enpassant << 22) | (castle << 23)\
//define macros to extract items from move
#define getSource(move) (move & 0x3f)
#define getTarget(move) ((move & 0xfc0) >> 6)
#define getPiece(move) ((move & 0xf000) >> 12)
#define getPromoted(move) ((move & 0xf0000) >> 16)
#define getCapture(move) (move & 0x100000)
#define getDpp(move) (move & 0x200000)
#define getEnpassant(move) (move & 0x400000)
#define getCastle(move) (move & 0x800000)
//move list structure
typedef struct {
int moves[256];
int count;
} moves;
static inline void addMove(moves *moveList, int move) {
moveList->moves[moveList->count] = move;
//increment move count
moveList->count++;
}
//print move
void printMove(int move) {
if(getPromoted(move)) {
printf("%s%s%c", squareCoordinates[getSource(move)],
squareCoordinates[getTarget(move)],
promotedPieces[getPromoted(move)]);
} else {
printf("%s%s", squareCoordinates[getSource(move)],