-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.cpp
More file actions
971 lines (824 loc) · 37.8 KB
/
Copy pathboard.cpp
File metadata and controls
971 lines (824 loc) · 37.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
#include "board.h"
#include "magics.h"
Evaluation::Score Board::evaluatePiece(uint64_t bb, int val, const Evaluation::Score pst[64], bool white) const {
Evaluation::Score s = {0, 0};
while (bb) {
int sq = __builtin_ctzll(bb);
int idx = white ? sq : (sq ^ 56);
s.mg += val + pst[idx].mg;
s.eg += val + pst[idx].eg;
bb &= (bb - 1);
}
return s;
}
void Board::checkTime() {
if (isPondering) return;
if (timeLimit != -1) {
auto now = chrono::steady_clock::now();
auto elapsed = chrono::duration_cast<chrono::milliseconds>(now - startTime).count();
if (elapsed >= timeLimit) stopSearch = true;
}
}
uint16_t Board::getPonderMove() const {
if (pvLength[0] > 1) return pvTable[0][1];
return 0;
}
uint64_t Board::generateHashKey() {
uint64_t h = 0;
uint64_t occupancy = (whitePawn | whiteKing | whiteQueen | whiteBishop | whiteKnight | whiteRook) |
(blackPawn | blackKing | blackQueen | blackBishop | blackKnight | blackRook);
uint64_t temp = occupancy;
while (temp) {
int sq = __builtin_ctzll(temp);
int pt = getPieceAt(sq, true);
if (pt != NONE) h ^= Evaluation::pieceKeys[pt - 1][sq];
else {
pt = getPieceAt(sq, false);
if (pt != NONE) h ^= Evaluation::pieceKeys[pt + 5][sq];
}
temp &= (temp - 1);
}
if (!sideToMove) h ^= Evaluation::sideKey;
h ^= Evaluation::castleKeys[castlingRights];
if (enPassantSquare != -1) h ^= Evaluation::enPassantKeys[enPassantSquare % 8];
return h;
}
uint64_t Board::getPolyglotHash() const {
uint64_t h = 0;
uint64_t occupancy = (whitePawn | whiteKing | whiteQueen | whiteBishop | whiteKnight | whiteRook) |
(blackPawn | blackKing | blackQueen | blackBishop | blackKnight | blackRook);
uint64_t temp = occupancy;
while (temp) {
int sq = __builtin_ctzll(temp);
int pt = getPieceAt(sq, true);
if (pt != NONE) {
// White pieces are at odd indices: 2*(pt-1) + 1
h ^= Polyglot::RANDOM_ARRAY[64 * (2 * (pt - 1) + 1) + sq];
}
else {
pt = getPieceAt(sq, false);
if (pt != NONE) {
// Black pieces are at even indices: 2*(pt-1)
h ^= Polyglot::RANDOM_ARRAY[64 * (2 * (pt - 1)) + sq];
}
}
temp &= (temp - 1);
}
if (castlingRights & WK) h ^= Polyglot::RANDOM_ARRAY[768];
if (castlingRights & WQ) h ^= Polyglot::RANDOM_ARRAY[769];
if (castlingRights & BK) h ^= Polyglot::RANDOM_ARRAY[770];
if (castlingRights & BQ) h ^= Polyglot::RANDOM_ARRAY[771];
if (enPassantSquare != -1) {
bool capturePossible = false;
if (sideToMove) {
if (enPassantSquare % 8 > 0 && (whitePawn & (1ULL << (enPassantSquare - 9)))) capturePossible = true;
if (enPassantSquare % 8 < 7 && (whitePawn & (1ULL << (enPassantSquare - 7)))) capturePossible = true;
} else {
if (enPassantSquare % 8 > 0 && (blackPawn & (1ULL << (enPassantSquare + 7)))) capturePossible = true;
if (enPassantSquare % 8 < 7 && (blackPawn & (1ULL << (enPassantSquare + 9)))) capturePossible = true;
}
if (capturePossible) h ^= Polyglot::RANDOM_ARRAY[772 + (enPassantSquare % 8)];
}
if (sideToMove) h ^= Polyglot::RANDOM_ARRAY[780];
return h;
}
int Board::evaluate() const {
Evaluation::Score score = {0, 0};
int phase = 0;
uint64_t whitePieces = whitePawn | whiteKing | whiteQueen | whiteBishop | whiteKnight | whiteRook;
uint64_t blackPieces = blackPawn | blackKing | blackQueen | blackBishop | blackKnight | blackRook;
uint64_t occupancy = whitePieces | blackPieces;
// White pieces
score += evaluatePiece(whitePawn, Evaluation::PAWN_VAL, Evaluation::pawn_pst, true);
Evaluation::Score wN = evaluatePiece(whiteKnight, Evaluation::KNIGHT_VAL, Evaluation::knight_pst, true);
score += wN;
phase += __builtin_popcountll(whiteKnight) * 1;
uint64_t wn_temp = whiteKnight;
while (wn_temp) {
int sq = __builtin_ctzll(wn_temp);
int rank = sq / 8;
if (rank >= 3 && rank <= 5) {
bool supported = false;
if (sq % 8 > 0 && (whitePawn & (1ULL << (sq - 9)))) supported = true;
if (sq % 8 < 7 && (whitePawn & (1ULL << (sq - 7)))) supported = true;
if (supported) {
if (!(blackPawn & Evaluation::passedPawnMasks[1][sq] & ~Evaluation::fileMasks[sq % 8])) {
score += {Evaluation::KNIGHT_OUTPOST_BONUS, Evaluation::KNIGHT_OUTPOST_BONUS};
}
}
}
int mob = __builtin_popcountll(knightMoveMask[sq] & ~whitePieces);
score += {mob * Evaluation::MOBILITY_BONUS[KNIGHT], mob * Evaluation::MOBILITY_BONUS[KNIGHT]};
wn_temp &= (wn_temp - 1);
}
Evaluation::Score wB = evaluatePiece(whiteBishop, Evaluation::BISHOP_VAL, Evaluation::bishop_pst, true);
score += wB;
phase += __builtin_popcountll(whiteBishop) * 1;
if (__builtin_popcountll(whiteBishop) >= 2) score += {Evaluation::BISHOP_PAIR_BONUS, Evaluation::BISHOP_PAIR_BONUS};
uint64_t wb_temp = whiteBishop;
while (wb_temp) {
int sq = __builtin_ctzll(wb_temp);
int mob = __builtin_popcountll(getBishopAttacks(sq, occupancy) & ~whitePieces);
score += {mob * Evaluation::MOBILITY_BONUS[BISHOP], mob * Evaluation::MOBILITY_BONUS[BISHOP]};
wb_temp &= (wb_temp - 1);
}
Evaluation::Score wR = evaluatePiece(whiteRook, Evaluation::ROOK_VAL, Evaluation::rook_pst, true);
score += wR;
phase += __builtin_popcountll(whiteRook) * 2;
uint64_t wr_temp = whiteRook;
while (wr_temp) {
int sq = __builtin_ctzll(wr_temp);
int mob = __builtin_popcountll(getRookMoves(sq, occupancy) & ~whitePieces);
score += {mob * Evaluation::MOBILITY_BONUS[ROOK], mob * Evaluation::MOBILITY_BONUS[ROOK]};
wr_temp &= (wr_temp - 1);
}
Evaluation::Score wQ = evaluatePiece(whiteQueen, Evaluation::QUEEN_VAL, Evaluation::queen_pst, true);
score += wQ;
phase += __builtin_popcountll(whiteQueen) * 4;
uint64_t wq_temp = whiteQueen;
while (wq_temp) {
int sq = __builtin_ctzll(wq_temp);
int mob = __builtin_popcountll((getBishopAttacks(sq, occupancy) | getRookMoves(sq, occupancy)) & ~whitePieces);
score += {mob * Evaluation::MOBILITY_BONUS[QUEEN], mob * Evaluation::MOBILITY_BONUS[QUEEN]};
wq_temp &= (wq_temp - 1);
}
score += evaluatePiece(whiteKing, Evaluation::KING_VAL, Evaluation::king_pst, true);
// Black pieces
score -= evaluatePiece(blackPawn, Evaluation::PAWN_VAL, Evaluation::pawn_pst, false);
Evaluation::Score bN = evaluatePiece(blackKnight, Evaluation::KNIGHT_VAL, Evaluation::knight_pst, false);
score -= bN;
phase += __builtin_popcountll(blackKnight) * 1;
uint64_t bn_temp = blackKnight;
while (bn_temp) {
int sq = __builtin_ctzll(bn_temp);
int rank = sq / 8;
if (rank >= 2 && rank <= 4) {
bool supported = false;
if (sq % 8 > 0 && (blackPawn & (1ULL << (sq + 7)))) supported = true;
if (sq % 8 < 7 && (blackPawn & (1ULL << (sq + 9)))) supported = true;
if (supported) {
if (!(whitePawn & Evaluation::passedPawnMasks[0][sq] & ~Evaluation::fileMasks[sq % 8])) {
score -= {Evaluation::KNIGHT_OUTPOST_BONUS, Evaluation::KNIGHT_OUTPOST_BONUS};
}
}
}
int mob = __builtin_popcountll(knightMoveMask[sq] & ~blackPieces);
score -= {mob * Evaluation::MOBILITY_BONUS[KNIGHT], mob * Evaluation::MOBILITY_BONUS[KNIGHT]};
bn_temp &= (bn_temp - 1);
}
Evaluation::Score bB = evaluatePiece(blackBishop, Evaluation::BISHOP_VAL, Evaluation::bishop_pst, false);
score -= bB;
phase += __builtin_popcountll(blackBishop) * 1;
if (__builtin_popcountll(blackBishop) >= 2) score -= {Evaluation::BISHOP_PAIR_BONUS, Evaluation::BISHOP_PAIR_BONUS};
uint64_t bb_temp = blackBishop;
while (bb_temp) {
int sq = __builtin_ctzll(bb_temp);
int mob = __builtin_popcountll(getBishopAttacks(sq, occupancy) & ~blackPieces);
score -= {mob * Evaluation::MOBILITY_BONUS[BISHOP], mob * Evaluation::MOBILITY_BONUS[BISHOP]};
bb_temp &= (bb_temp - 1);
}
Evaluation::Score bR = evaluatePiece(blackRook, Evaluation::ROOK_VAL, Evaluation::rook_pst, false);
score -= bR;
phase += __builtin_popcountll(blackRook) * 2;
uint64_t br_temp = blackRook;
while (br_temp) {
int sq = __builtin_ctzll(br_temp);
int mob = __builtin_popcountll(getRookMoves(sq, occupancy) & ~blackPieces);
score -= {mob * Evaluation::MOBILITY_BONUS[ROOK], mob * Evaluation::MOBILITY_BONUS[ROOK]};
br_temp &= (br_temp - 1);
}
Evaluation::Score bQ = evaluatePiece(blackQueen, Evaluation::QUEEN_VAL, Evaluation::queen_pst, false);
score -= bQ;
phase += __builtin_popcountll(blackQueen) * 4;
uint64_t bq_temp = blackQueen;
while (bq_temp) {
int sq = __builtin_ctzll(bq_temp);
int mob = __builtin_popcountll((getBishopAttacks(sq, occupancy) | getRookMoves(sq, occupancy)) & ~blackPieces);
score -= {mob * Evaluation::MOBILITY_BONUS[QUEEN], mob * Evaluation::MOBILITY_BONUS[QUEEN]};
bq_temp &= (bq_temp - 1);
}
score -= evaluatePiece(blackKing, Evaluation::KING_VAL, Evaluation::king_pst, false);
// Pawn Structure & Passed Pawns
for (int file = 0; file < 8; file++) {
int wCount = __builtin_popcountll(whitePawn & Evaluation::fileMasks[file]);
if (wCount > 1) score -= {Evaluation::DOUBLED_PAWN_PENALTY * (wCount - 1), Evaluation::DOUBLED_PAWN_PENALTY * (wCount - 1)};
int bCount = __builtin_popcountll(blackPawn & Evaluation::fileMasks[file]);
if (bCount > 1) score += {Evaluation::DOUBLED_PAWN_PENALTY * (bCount - 1), Evaluation::DOUBLED_PAWN_PENALTY * (bCount - 1)};
}
uint64_t wp = whitePawn;
while (wp) {
int sq = __builtin_ctzll(wp);
int file = sq % 8;
int r = sq / 8;
// Isolated pawns
if (!(whitePawn & Evaluation::adjacentFileMasks[file])) {
score -= {Evaluation::ISOLATED_PAWN_PENALTY, Evaluation::ISOLATED_PAWN_PENALTY};
} else if (!(whitePawn & Evaluation::passedPawnMasks[0][sq] & Evaluation::adjacentFileMasks[file])) {
// Backward pawn (not isolated, but no friendly pawns behind it on adjacent files)
score -= {Evaluation::BACKWARD_PAWN_PENALTY, Evaluation::BACKWARD_PAWN_PENALTY};
}
// Connected pawns
uint64_t connectedMask = 0;
if (file > 0) {
if (r > 0) connectedMask |= (1ULL << (sq - 9));
connectedMask |= (1ULL << (sq - 1));
if (r < 7) connectedMask |= (1ULL << (sq + 7));
}
if (file < 7) {
if (r > 0) connectedMask |= (1ULL << (sq - 7));
connectedMask |= (1ULL << (sq + 1));
if (r < 7) connectedMask |= (1ULL << (sq + 9));
}
if (whitePawn & connectedMask) {
score += {Evaluation::CONNECTED_PAWN_BONUS, Evaluation::CONNECTED_PAWN_BONUS};
}
// Undermining (attacking enemy pawns)
uint64_t attacks = 0;
if (file > 0 && r < 7) attacks |= (1ULL << (sq + 7));
if (file < 7 && r < 7) attacks |= (1ULL << (sq + 9));
if (attacks & blackPawn) {
score += {Evaluation::UNDERMINING_BONUS, Evaluation::UNDERMINING_BONUS};
}
// Passed pawns
if (!(blackPawn & Evaluation::passedPawnMasks[1][sq]))
score += Evaluation::passedPawnBonus[r];
wp &= (wp - 1);
}
uint64_t bp = blackPawn;
while (bp) {
int sq = __builtin_ctzll(bp);
int file = sq % 8;
int r = sq / 8;
// Isolated pawns
if (!(blackPawn & Evaluation::adjacentFileMasks[file])) {
score += {Evaluation::ISOLATED_PAWN_PENALTY, Evaluation::ISOLATED_PAWN_PENALTY};
} else if (!(blackPawn & Evaluation::passedPawnMasks[1][sq] & Evaluation::adjacentFileMasks[file])) {
// Backward pawn (for black, behind means ranks > r, which is passedPawnMasks[1])
score += {Evaluation::BACKWARD_PAWN_PENALTY, Evaluation::BACKWARD_PAWN_PENALTY};
}
// Connected pawns
uint64_t connectedMask = 0;
if (file > 0) {
if (r > 0) connectedMask |= (1ULL << (sq - 9));
connectedMask |= (1ULL << (sq - 1));
if (r < 7) connectedMask |= (1ULL << (sq + 7));
}
if (file < 7) {
if (r > 0) connectedMask |= (1ULL << (sq - 7));
connectedMask |= (1ULL << (sq + 1));
if (r < 7) connectedMask |= (1ULL << (sq + 9));
}
if (blackPawn & connectedMask) {
score -= {Evaluation::CONNECTED_PAWN_BONUS, Evaluation::CONNECTED_PAWN_BONUS};
}
// Undermining (attacking enemy pawns)
uint64_t attacks = 0;
if (file > 0 && r > 0) attacks |= (1ULL << (sq - 9));
if (file < 7 && r > 0) attacks |= (1ULL << (sq - 7));
if (attacks & whitePawn) {
score -= {Evaluation::UNDERMINING_BONUS, Evaluation::UNDERMINING_BONUS};
}
// Passed pawns
if (!(whitePawn & Evaluation::passedPawnMasks[0][sq]))
score -= Evaluation::passedPawnBonus[7 - r];
bp &= (bp - 1);
}
// Rook Evaluation
uint64_t wr = whiteRook;
while (wr) {
int sq = __builtin_ctzll(wr);
int file = sq % 8;
if (!(whitePawn & Evaluation::fileMasks[file])) {
if (!(blackPawn & Evaluation::fileMasks[file])) score += {Evaluation::ROOK_OPEN_FILE_BONUS, Evaluation::ROOK_OPEN_FILE_BONUS};
else score += {Evaluation::ROOK_SEMI_OPEN_FILE_BONUS, Evaluation::ROOK_SEMI_OPEN_FILE_BONUS};
}
if (sq / 8 == 6) score += {Evaluation::ROOK_ON_7TH_BONUS, Evaluation::ROOK_ON_7TH_BONUS};
wr &= (wr - 1);
}
uint64_t br = blackRook;
while (br) {
int sq = __builtin_ctzll(br);
int file = sq % 8;
if (!(blackPawn & Evaluation::fileMasks[file])) {
if (!(whitePawn & Evaluation::fileMasks[file])) score -= {Evaluation::ROOK_OPEN_FILE_BONUS, Evaluation::ROOK_OPEN_FILE_BONUS};
else score -= {Evaluation::ROOK_SEMI_OPEN_FILE_BONUS, Evaluation::ROOK_SEMI_OPEN_FILE_BONUS};
}
if (sq / 8 == 1) score -= {Evaluation::ROOK_ON_7TH_BONUS, Evaluation::ROOK_ON_7TH_BONUS};
br &= (br - 1);
}
// King Safety
int wKingSq = __builtin_ctzll(whiteKing);
int wKf = wKingSq % 8;
if (wKingSq < 24) { // Ranks 1-3
int pawnsInShield = __builtin_popcountll(whitePawn & Evaluation::pawnShieldMasks[1][wKingSq]);
int missingShield = std::max(0, 3 - pawnsInShield);
score.mg -= Evaluation::shieldPenalty[missingShield];
// Pawn Storms against White King (only on flanks / castled positions)
if (wKf < 3 || wKf > 4) {
for (int f = std::max(0, wKf - 1); f <= std::min(7, wKf + 1); f++) {
uint64_t bpOnF = blackPawn & Evaluation::fileMasks[f];
if (bpOnF) {
int rank = __builtin_ctzll(bpOnF) / 8; // Lowest rank (closest to white king)
score.mg -= Evaluation::PAWN_STORM_PENALTY[7 - rank]; // Penalty to white
score.mg -= Evaluation::PAWN_STORM_BONUS[7 - rank]; // Bonus to black's attack
}
}
}
}
int bKingSq = __builtin_ctzll(blackKing);
int bKf = bKingSq % 8;
if (bKingSq >= 40) { // Ranks 6-8
int pawnsInShield = __builtin_popcountll(blackPawn & Evaluation::pawnShieldMasks[0][bKingSq]);
int missingShield = std::max(0, 3 - pawnsInShield);
score.mg += Evaluation::shieldPenalty[missingShield];
// Pawn Storms against Black King (only on flanks / castled positions)
if (bKf < 3 || bKf > 4) {
for (int f = std::max(0, bKf - 1); f <= std::min(7, bKf + 1); f++) {
uint64_t wpOnF = whitePawn & Evaluation::fileMasks[f];
if (wpOnF) {
int rank = (63 - __builtin_clzll(wpOnF)) / 8; // Highest rank (closest to black king)
score.mg += Evaluation::PAWN_STORM_PENALTY[rank]; // Penalty to black
score.mg += Evaluation::PAWN_STORM_BONUS[rank]; // Bonus to white's attack
}
}
}
}
// King Zone Attacks (Weighted)
uint64_t wKz = Evaluation::kingZoneMasks[1][wKingSq];
int wAttackScore = 0;
uint64_t tempKnights = blackKnight;
while (tempKnights) { int sq = __builtin_ctzll(tempKnights); wAttackScore += __builtin_popcountll(knightMoveMask[sq] & wKz) * Evaluation::attackWeight[KNIGHT]; tempKnights &= (tempKnights - 1); }
uint64_t tempBishops = blackBishop | blackQueen;
while (tempBishops) { int sq = __builtin_ctzll(tempBishops); wAttackScore += __builtin_popcountll(getBishopAttacks(sq, occupancy) & wKz) * Evaluation::attackWeight[BISHOP]; tempBishops &= (tempBishops - 1); }
uint64_t tempRooks = blackRook | blackQueen;
while (tempRooks) { int sq = __builtin_ctzll(tempRooks); wAttackScore += __builtin_popcountll(getRookMoves(sq, occupancy) & wKz) * Evaluation::attackWeight[ROOK]; tempRooks &= (tempRooks - 1); }
if (wAttackScore > 99) wAttackScore = 99;
score.mg -= Evaluation::safetyTable[wAttackScore];
uint64_t bKz = Evaluation::kingZoneMasks[0][bKingSq];
int bAttackScore = 0;
tempKnights = whiteKnight;
while (tempKnights) { int sq = __builtin_ctzll(tempKnights); bAttackScore += __builtin_popcountll(knightMoveMask[sq] & bKz) * Evaluation::attackWeight[KNIGHT]; tempKnights &= (tempKnights - 1); }
tempBishops = whiteBishop | whiteQueen;
while (tempBishops) { int sq = __builtin_ctzll(tempBishops); bAttackScore += __builtin_popcountll(getBishopAttacks(sq, occupancy) & bKz) * Evaluation::attackWeight[BISHOP]; tempBishops &= (tempBishops - 1); }
tempRooks = whiteRook | whiteQueen;
while (tempRooks) { int sq = __builtin_ctzll(tempRooks); bAttackScore += __builtin_popcountll(getRookMoves(sq, occupancy) & bKz) * Evaluation::attackWeight[ROOK]; tempRooks &= (tempRooks - 1); }
if (bAttackScore > 99) bAttackScore = 99;
score.mg += Evaluation::safetyTable[bAttackScore];
const int totalPhase = 24;
if (phase > totalPhase) phase = totalPhase;
int finalScore = (score.mg * phase + score.eg * (totalPhase - phase)) / totalPhase;
return sideToMove ? finalScore : -finalScore;
}
bool Board::getSideToMove() const {
return sideToMove;
}
uint8_t Board::getCastlingRights() const {
return castlingRights;
}
int Board::getEnPassantSquare() const {
return enPassantSquare;
}
int Board::getPieceAt(int square, bool side) const {
uint64_t bit = (1ULL << square);
if (side) { // White
if (whitePawn & bit) return PAWN;
if (whiteKnight & bit) return KNIGHT;
if (whiteBishop & bit) return BISHOP;
if (whiteRook & bit) return ROOK;
if (whiteQueen & bit) return QUEEN;
if (whiteKing & bit) return KING;
} else { // Black
if (blackPawn & bit) return PAWN;
if (blackKnight & bit) return KNIGHT;
if (blackBishop & bit) return BISHOP;
if (blackRook & bit) return ROOK;
if (blackQueen & bit) return QUEEN;
if (blackKing & bit) return KING;
}
return NONE;
}
bool Board::inCheck(bool side) const {
uint64_t kingBB = side ? whiteKing : blackKing;
return (attackedSquares(!side) & kingBB) != 0;
}
bool Board::isRepetition() const {
// Current position is at historyIndex - 1.
// Check back to the last irreversible move.
int start = max(0, historyIndex - halfmoveClock - 1);
// Positions only repeat on the same side's turn.
// i starts at historyIndex - 3 (the position 2 steps back from current).
for (int i = historyIndex - 3; i >= start; i -= 2) {
if (historyStack[i] == hashKey) return true;
}
return false;
}
uint64_t Board::getLeastValuableAttacker(int square, bool side, uint64_t& occupied, int& pieceType) const {
uint64_t attackers;
// Pawns
attackers = 0;
if (side) { // White attackers
if (square >= 7 && (square % 8 != 0) && (whitePawn & (1ULL << (square - 7)))) attackers |= (1ULL << (square - 7));
if (square >= 9 && (square % 8 != 7) && (whitePawn & (1ULL << (square - 9)))) attackers |= (1ULL << (square - 9));
} else { // Black attackers
if (square <= 56 && (square % 8 != 0) && (blackPawn & (1ULL << (square + 7)))) attackers |= (1ULL << (square + 7));
if (square <= 54 && (square % 8 != 7) && (blackPawn & (1ULL << (square + 9)))) attackers |= (1ULL << (square + 9));
}
if (attackers & occupied) {
pieceType = PAWN;
uint64_t bit = attackers & occupied;
bit = (1ULL << __builtin_ctzll(bit));
occupied ^= bit;
return bit;
}
// Knights
attackers = knightMoveMask[square] & (side ? whiteKnight : blackKnight);
if (attackers & occupied) {
pieceType = KNIGHT;
uint64_t bit = attackers & occupied;
bit = (1ULL << __builtin_ctzll(bit));
occupied ^= bit;
return bit;
}
// Bishops
attackers = getBishopAttacks(square, occupied) & (side ? whiteBishop : blackBishop);
if (attackers & occupied) {
pieceType = BISHOP;
uint64_t bit = attackers & occupied;
bit = (1ULL << __builtin_ctzll(bit));
occupied ^= bit;
return bit;
}
// Rooks
attackers = getRookMoves(square, occupied) & (side ? whiteRook : blackRook);
if (attackers & occupied) {
pieceType = ROOK;
uint64_t bit = attackers & occupied;
bit = (1ULL << __builtin_ctzll(bit));
occupied ^= bit;
return bit;
}
// Queens
attackers = (getBishopAttacks(square, occupied) | getRookMoves(square, occupied)) & (side ? whiteQueen : blackQueen);
if (attackers & occupied) {
pieceType = QUEEN;
uint64_t bit = attackers & occupied;
bit = (1ULL << __builtin_ctzll(bit));
occupied ^= bit;
return bit;
}
// Kings
attackers = kingMoveMask[square] & (side ? whiteKing : blackKing);
if (attackers & occupied) {
pieceType = KING;
uint64_t bit = attackers & occupied;
bit = (1ULL << __builtin_ctzll(bit));
occupied ^= bit;
return bit;
}
pieceType = NONE;
return 0;
}
int Board::see(uint16_t move) const {
int from = getFrom(move);
int to = getTo(move);
int flags = getFlags(move);
int pieceValue[] = {0, 100, 320, 330, 500, 900, 20000};
// The piece being captured at 'to' is the one that belongs to the opponent
// of the side making the move.
int capturedPieceType = getPieceAt(to, !sideToMove);
if (flags == EP_CAPTURE) capturedPieceType = PAWN;
int attackingPieceType = getPieceAt(from, sideToMove);
int promoValue = 0;
if (flags >= PROMO_KNIGHT) {
int pt = flags & 3;
if (pt == 0) attackingPieceType = KNIGHT;
else if (pt == 1) attackingPieceType = BISHOP;
else if (pt == 2) attackingPieceType = ROOK;
else if (pt == 3) attackingPieceType = QUEEN;
promoValue = pieceValue[attackingPieceType] - 100;
}
int score[32];
score[0] = pieceValue[capturedPieceType] + promoValue;
int n = 1;
uint64_t occupied = (whitePawn | whiteKnight | whiteBishop | whiteRook | whiteQueen | whiteKing |
blackPawn | blackKnight | blackBishop | blackRook | blackQueen | blackKing);
occupied ^= (1ULL << from);
bool currentSide = !sideToMove; // The next side to move (the recycler)
int currentAttackerValue = pieceValue[attackingPieceType];
while (true) {
int nextPieceType;
uint64_t bit = getLeastValuableAttacker(to, currentSide, occupied, nextPieceType);
if (!bit) break;
score[n] = currentAttackerValue - score[n-1];
currentAttackerValue = pieceValue[nextPieceType];
n++;
currentSide = !currentSide;
}
while (--n > 0) {
score[n-1] = -max(-score[n-1], score[n]);
}
return score[0];
}
int Board::getMoveScore(uint16_t move, uint16_t hashMove, int ply) const {
if (move == hashMove) return 2000000;
int flags = getFlags(move);
if (flags & CAPTURE) {
int score = see(move);
if (score >= 0) return 1000000 + score;
// Bad capture: Base 50000 + negative SEE (Range ~49,100 to 49,999)
return 50000 + score;
}
if (ply < 128) {
if (killerMoves[ply][0] && move == killerMoves[ply][0]) return 900000;
if (killerMoves[ply][1] && move == killerMoves[ply][1]) return 800000;
}
// Quiet move: Base 50000 + History (Range ~33,616 to 66,384)
return 50000 + historyHeuristic[sideToMove][getFrom(move)][getTo(move)];
}
void Board::togglePiece(int pieceType, int square, bool side) {
uint64_t bit = (1ULL << square);
if (side) {
hashKey ^= Evaluation::pieceKeys[pieceType - 1][square];
switch (pieceType) {
case PAWN: whitePawn ^= bit; break;
case KNIGHT: whiteKnight ^= bit; break;
case BISHOP: whiteBishop ^= bit; break;
case ROOK: whiteRook ^= bit; break;
case QUEEN: whiteQueen ^= bit; break;
case KING: whiteKing ^= bit; break;
}
} else {
hashKey ^= Evaluation::pieceKeys[pieceType + 5][square];
switch (pieceType) {
case PAWN: blackPawn ^= bit; break;
case KNIGHT: blackKnight ^= bit; break;
case BISHOP: blackBishop ^= bit; break;
case ROOK: blackRook ^= bit; break;
case QUEEN: blackQueen ^= bit; break;
case KING: blackKing ^= bit; break;
}
}
}
bool Board::makeMove(uint16_t move, UndoInfo& undo) {
int from = getFrom(move);
int to = getTo(move);
int flags = getFlags(move);
bool side = sideToMove;
undo.castlingRights = castlingRights;
undo.enPassantSquare = enPassantSquare;
undo.halfmoveClock = halfmoveClock;
undo.capturedPieceType = NONE;
undo.move = move;
undo.hashKey = hashKey;
int piece = getPieceAt(from, side);
hashKey ^= Evaluation::castleKeys[castlingRights];
if (enPassantSquare != -1) hashKey ^= Evaluation::enPassantKeys[enPassantSquare % 8];
togglePiece(piece, from, side);
if (flags & CAPTURE) {
if (flags == EP_CAPTURE) {
int epSq = side ? to - 8 : to + 8;
undo.capturedPieceType = PAWN;
togglePiece(PAWN, epSq, !side);
} else {
undo.capturedPieceType = getPieceAt(to, !side);
if (undo.capturedPieceType != NONE) {
togglePiece(undo.capturedPieceType, to, !side);
}
}
}
if (flags == K_CASTLE) {
if (side) { togglePiece(ROOK, 7, 1); togglePiece(ROOK, 5, 1); }
else { togglePiece(ROOK, 63, 0); togglePiece(ROOK, 61, 0); }
} else if (flags == Q_CASTLE) {
if (side) { togglePiece(ROOK, 0, 1); togglePiece(ROOK, 3, 1); }
else { togglePiece(ROOK, 56, 0); togglePiece(ROOK, 59, 0); }
}
if (flags >= PROMO_KNIGHT) {
int promoPiece = KNIGHT;
int promoType = flags & 3;
if (promoType == 1) promoPiece = BISHOP;
else if (promoType == 2) promoPiece = ROOK;
else if (promoType == 3) promoPiece = QUEEN;
togglePiece(promoPiece, to, side);
} else {
togglePiece(piece, to, side);
}
castlingRights &= (castlingMask[from] & castlingMask[to]);
enPassantSquare = (flags == DOUBLE_PUSH) ? (side ? from + 8 : from - 8) : -1;
hashKey ^= Evaluation::castleKeys[castlingRights];
if (enPassantSquare != -1) hashKey ^= Evaluation::enPassantKeys[enPassantSquare % 8];
halfmoveClock++;
if (piece == PAWN || (flags & CAPTURE)) halfmoveClock = 0;
if (!side) fullmoveNumber++;
sideToMove = !sideToMove;
hashKey ^= Evaluation::sideKey;
historyStack[historyIndex++] = hashKey;
uint64_t kingBB = side ? whiteKing : blackKing;
uint64_t attacks = attackedSquares(!side);
if (attacks & kingBB) {
unmakeMove(move, undo);
return false;
}
return true;
}
void Board::unmakeMove(uint16_t move, const UndoInfo& undo) {
historyIndex--;
int from = getFrom(move);
int to = getTo(move);
int flags = getFlags(move);
sideToMove = !sideToMove;
bool side = sideToMove;
int piece = getPieceAt(to, side);
if (flags >= PROMO_KNIGHT) {
togglePiece(piece, to, side);
togglePiece(PAWN, to, side);
piece = PAWN;
}
togglePiece(piece, to, side);
togglePiece(piece, from, side);
if (flags & CAPTURE) {
if (flags == EP_CAPTURE) {
int epSq = side ? to - 8 : to + 8;
togglePiece(PAWN, epSq, !side);
} else if (undo.capturedPieceType != NONE) {
togglePiece(undo.capturedPieceType, to, !side);
}
}
if (flags == K_CASTLE) {
if (side) { togglePiece(ROOK, 7, 1); togglePiece(ROOK, 5, 1); }
else { togglePiece(ROOK, 63, 0); togglePiece(ROOK, 61, 0); }
} else if (flags == Q_CASTLE) {
if (side) { togglePiece(ROOK, 0, 1); togglePiece(ROOK, 3, 1); }
else { togglePiece(ROOK, 56, 0); togglePiece(ROOK, 59, 0); }
}
castlingRights = undo.castlingRights;
enPassantSquare = undo.enPassantSquare;
halfmoveClock = undo.halfmoveClock;
if (!side) fullmoveNumber--;
hashKey = undo.hashKey;
}
void Board::makeNullMove(UndoInfo& undo) {
undo.castlingRights = castlingRights;
undo.enPassantSquare = enPassantSquare;
undo.halfmoveClock = halfmoveClock;
undo.capturedPieceType = NONE;
undo.move = 0;
undo.hashKey = hashKey;
if (enPassantSquare != -1) hashKey ^= Evaluation::enPassantKeys[enPassantSquare % 8];
enPassantSquare = -1;
bool side = sideToMove;
sideToMove = !sideToMove;
hashKey ^= Evaluation::sideKey;
halfmoveClock++;
if (!side) fullmoveNumber++;
}
void Board::unmakeNullMove(const UndoInfo& undo) {
bool side = !sideToMove; // The side that made the null move
if (!side) fullmoveNumber--;
sideToMove = !sideToMove;
castlingRights = undo.castlingRights;
enPassantSquare = undo.enPassantSquare;
halfmoveClock = undo.halfmoveClock;
hashKey = undo.hashKey;
}
uint16_t Board::package_move(int from, int to, int flags) const {
return (uint16_t)(from | (to << 6) | (flags << 12));
}
void Board::resetBoard() {
whitePawn = 0x000000000000FF00ULL;
whiteKing = 0x0000000000000010ULL;
whiteQueen = 0x0000000000000008ULL;
whiteBishop = 0x0000000000000024ULL;
whiteKnight = 0x0000000000000042ULL;
whiteRook = 0x0000000000000081ULL;
blackPawn = 0x00FF000000000000ULL;
blackKing = 0x1000000000000000ULL;
blackQueen = 0x0800000000000000ULL;
blackBishop = 0x2400000000000000ULL;
blackKnight = 0x4200000000000000ULL;
blackRook = 0x8100000000000000ULL;
castlingRights = 15;
enPassantSquare = -1;
sideToMove = 1;
halfmoveClock = 0;
fullmoveNumber = 1;
hashKey = generateHashKey();
historyIndex = 0;
historyStack[historyIndex++] = hashKey;
}
void Board::parseFEN(const string& fen) {
whitePawn = whiteKnight = whiteBishop = whiteRook = whiteQueen = whiteKing = 0;
blackPawn = blackKnight = blackBishop = blackRook = blackQueen = blackKing = 0;
castlingRights = 0;
enPassantSquare = -1;
halfmoveClock = 0;
fullmoveNumber = 1;
sideToMove = true;
istringstream ss(fen);
string pieces, side, castling, ep, halfmove, fullmove;
if (!(ss >> pieces)) return;
if (!(ss >> side)) side = "w";
if (!(ss >> castling)) castling = "-";
if (!(ss >> ep)) ep = "-";
if (!(ss >> halfmove)) halfmove = "0";
if (!(ss >> fullmove)) fullmove = "1";
int rank = 7, file = 0;
for (char c : pieces) {
if (c == '/') { rank--; file = 0; }
else if (isdigit(c)) { file += (c - '0'); }
else {
int square = rank * 8 + file;
if (c == 'P') whitePawn |= (1ULL << square);
else if (c == 'N') whiteKnight |= (1ULL << square);
else if (c == 'B') whiteBishop |= (1ULL << square);
else if (c == 'R') whiteRook |= (1ULL << square);
else if (c == 'Q') whiteQueen |= (1ULL << square);
else if (c == 'K') whiteKing |= (1ULL << square);
else if (c == 'p') blackPawn |= (1ULL << square);
else if (c == 'n') blackKnight |= (1ULL << square);
else if (c == 'b') blackBishop |= (1ULL << square);
else if (c == 'r') blackRook |= (1ULL << square);
else if (c == 'q') blackQueen |= (1ULL << square);
else if (c == 'k') blackKing |= (1ULL << square);
file++;
}
}
sideToMove = (side == "w");
for (char c : castling) {
if (c == 'K') castlingRights |= WK;
else if (c == 'Q') castlingRights |= WQ;
else if (c == 'k') castlingRights |= BK;
else if (c == 'q') castlingRights |= BQ;
}
if (ep != "-" && ep.length() >= 2) {
enPassantSquare = (ep[1] - '1') * 8 + (ep[0] - 'a');
}
try {
halfmoveClock = stoi(halfmove);
fullmoveNumber = stoi(fullmove);
} catch (...) {}
hashKey = generateHashKey();
historyIndex = 0;
historyStack[historyIndex++] = hashKey;
}
uint16_t Board::parseMove(string moveStr) {
MoveList list;
generateMoves(sideToMove, list);
for (int i = 0; i < list.count; i++) {
uint16_t move = list.moves[i];
if (moveToString(move) == moveStr) {
UndoInfo undo;
if (makeMove(move, undo)) {
unmakeMove(move, undo);
return move;
}
}
}
return 0;
}
void Board::init() {
for (int i = 0; i < 64; i++) castlingMask[i] = 15;
castlingMask[0] = 13; castlingMask[7] = 14; castlingMask[4] = 12;
castlingMask[56] = 7; castlingMask[63] = 11; castlingMask[60] = 3;
tt.resize(TT_SIZE);
clearTT();
clearSearchState();
resetBoard();
calculateLeapers();
Magics::init();
}
string Board::squareToCoord(int sq) {
string s = ""; s += (char)('a' + (sq % 8)); s += (char)('1' + (sq / 8)); return s;
}
string Board::moveToString(uint16_t move) {
int from = getFrom(move), to = getTo(move), flags = getFlags(move);
string s = squareToCoord(from) + squareToCoord(to);
if (flags >= PROMO_KNIGHT) {
int pt = flags & 3;
if (pt == 0) s += 'n'; else if (pt == 1) s += 'b'; else if (pt == 2) s += 'r'; else if (pt == 3) s += 'q';
}
return s;
}
uint64_t Board::perft(int depth) {
if (depth == 0) return 1ULL;
uint64_t nodes = 0;
MoveList list;
generateMoves(sideToMove, list);
for (int i = 0; i < list.count; i++) {
uint16_t move = list.moves[i];
UndoInfo undo;
if (makeMove(move, undo)) { nodes += perft(depth - 1); unmakeMove(move, undo); }
}
return nodes;
}
void Board::perftDivide(int depth) {
uint64_t totalNodes = 0;
MoveList list;
generateMoves(sideToMove, list);
for (int i = 0; i < list.count; i++) {
uint16_t move = list.moves[i];
UndoInfo undo;
if (makeMove(move, undo)) { uint64_t nodes = perft(depth - 1); unmakeMove(move, undo); cout << moveToString(move) << ": " << nodes << endl; totalNodes += nodes; }
}
cout << "\nTotal nodes at depth " << depth << ": " << totalNodes << endl;
}