-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.cpp
More file actions
1051 lines (888 loc) · 34.1 KB
/
Copy pathboard.cpp
File metadata and controls
1051 lines (888 loc) · 34.1 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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "board.h"
#include "movegen.h"
#include "nnue.h"
#include <iostream>
#include <sstream>
#include <cctype>
#include <cassert>
#include <charconv>
#include <limits>
// Define static members of Board
U64 Board::zobrist_pieces[2][6][64];
U64 Board::zobrist_castling[16];
U64 Board::zobrist_ep[8];
U64 Board::zobrist_side;
// Castling rights update mask for fast updates in make_move
const int castling_rights_mask[64] = {
13, 15, 15, 15, 12, 15, 15, 14, // Rank 1 (A1=13, E1=12, H1=14)
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
7, 15, 15, 15, 3, 15, 15, 11 // Rank 8 (A8=7, E8=3, H8=11)
};
Board::Board() {
clear();
}
void Board::clear() {
for (int c = 0; c < 2; c++) {
for (int pt = 0; pt < 6; pt++) {
pieces[c][pt] = 0ULL;
}
}
for (int i = 0; i < 3; i++) {
occupancies[i] = 0ULL;
}
for (int sq = 0; sq < 64; sq++) {
board_array[sq] = NO_PIECE;
}
side_to_move = WHITE;
castling_rights = NO_CASTLING;
en_passant_square = SQ_NONE;
halfmove_clock = 0;
fullmove_number = 1;
hash_key = 0ULL;
pawn_key = 0ULL;
non_pawn_key[WHITE] = 0ULL;
non_pawn_key[BLACK] = 0ULL;
history_ply = 0;
// Initialize NNUE accumulator
g_nnue.init_accumulator(*this, accumulator);
}
void Board::init_zobrist() {
U64 state = 1804289383ULL;
auto next_random = [&]() {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
return state * 2685821657736338717ULL;
};
for (int c = 0; c < 2; c++) {
for (int pt = 0; pt < 6; pt++) {
for (int sq = 0; sq < 64; sq++) {
zobrist_pieces[c][pt][sq] = next_random();
}
}
}
for (int i = 0; i < 16; i++) {
zobrist_castling[i] = next_random();
}
for (int i = 0; i < 8; i++) {
zobrist_ep[i] = next_random();
}
zobrist_side = next_random();
}
U64 Board::calculate_hash() const {
U64 k = 0;
for (int sq = 0; sq < 64; sq++) {
Piece p = board_array[sq];
if (p != NO_PIECE) {
k ^= zobrist_pieces[p / 6][p % 6][sq];
}
}
k ^= zobrist_castling[castling_rights];
if (en_passant_square != SQ_NONE) {
k ^= zobrist_ep[en_passant_square % 8];
}
if (side_to_move == BLACK) {
k ^= zobrist_side;
}
return k;
}
uint16_t Board::calculate_pawn_key() const {
uint16_t key = 0;
for (int color = WHITE; color <= BLACK; ++color) {
U64 pawns = pieces[color][PAWN];
while (pawns) {
const int square = pop_lsb(pawns);
key ^= static_cast<uint16_t>(zobrist_pieces[color][PAWN][square]);
}
}
return key;
}
uint16_t Board::calculate_non_pawn_key(Color color) const {
uint16_t key = 0;
for (int piece_type = KNIGHT; piece_type <= KING; ++piece_type) {
U64 occupied = pieces[color][piece_type];
while (occupied) {
const int square = pop_lsb(occupied);
key ^= static_cast<uint16_t>(zobrist_pieces[color][piece_type][square]);
}
}
return key;
}
bool Board::has_en_passant_capture() const {
if (en_passant_square == SQ_NONE) {
return false;
}
int expected_rank = side_to_move == WHITE ? 5 : 2;
if (en_passant_square / 8 != expected_rank ||
board_array[en_passant_square] != NO_PIECE) {
return false;
}
int captured_sq = en_passant_square + (side_to_move == WHITE ? -8 : 8);
int origin_sq = en_passant_square + (side_to_move == WHITE ? 8 : -8);
Piece expected_pawn = side_to_move == WHITE ? B_PAWN : W_PAWN;
if (captured_sq < 0 || captured_sq >= 64 || origin_sq < 0 || origin_sq >= 64 ||
board_array[captured_sq] != expected_pawn || board_array[origin_sq] != NO_PIECE) {
return false;
}
U64 capturers = get_pawn_attacks(side_to_move ^ 1, en_passant_square) &
pieces[side_to_move][PAWN];
return capturers != 0;
}
void Board::update_occupancies() {
occupancies[WHITE] = 0;
for (int pt = 0; pt < 6; pt++) {
occupancies[WHITE] |= pieces[WHITE][pt];
}
occupancies[BLACK] = 0;
for (int pt = 0; pt < 6; pt++) {
occupancies[BLACK] |= pieces[BLACK][pt];
}
occupancies[BOTH] = occupancies[WHITE] | occupancies[BLACK];
}
bool Board::parse_fen(const std::string& fen) {
std::istringstream input(fen);
std::string placement, active, castling, ep, halfmove, fullmove, extra;
if (!(input >> placement >> active >> castling >> ep >> halfmove >> fullmove)
|| (input >> extra)) {
return false;
}
int rank = 7;
int file = 0;
int white_kings = 0;
int black_kings = 0;
for (char c : placement) {
if (c == '/') {
if (file != 8 || rank == 0) return false;
--rank;
file = 0;
} else if (c >= '1' && c <= '8') {
file += c - '0';
if (file > 8) return false;
} else {
const char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (lower != 'p' && lower != 'n' && lower != 'b'
&& lower != 'r' && lower != 'q' && lower != 'k') return false;
if (++file > 8) return false;
if (c == 'K') ++white_kings;
if (c == 'k') ++black_kings;
}
}
if (rank != 0 || file != 8 || white_kings != 1 || black_kings != 1) return false;
if (active != "w" && active != "b") return false;
if (castling != "-") {
int seen = 0;
for (char c : castling) {
int bit = c == 'K' ? 1 : c == 'Q' ? 2 : c == 'k' ? 4 : c == 'q' ? 8 : 0;
if (bit == 0 || (seen & bit)) return false;
seen |= bit;
}
}
if (ep != "-" && (ep.size() != 2 || ep[0] < 'a' || ep[0] > 'h'
|| (ep[1] != '3' && ep[1] != '6'))) return false;
auto parse_clock = [](const std::string& text, int minimum, int& value) {
if (text.empty()) return false;
int parsed = 0;
const auto result = std::from_chars(text.data(), text.data() + text.size(), parsed);
if (result.ec != std::errc{} || result.ptr != text.data() + text.size()
|| parsed < minimum) return false;
value = parsed;
return true;
};
int parsed_halfmove = 0;
int parsed_fullmove = 1;
if (!parse_clock(halfmove, 0, parsed_halfmove)
|| !parse_clock(fullmove, 1, parsed_fullmove)) return false;
// Validation is complete. From here onward every square index is bounded,
// so malformed protocol input can never partially replace the live board.
clear();
rank = 7;
file = 0;
for (char c : placement) {
if (c == '/') {
--rank;
file = 0;
} else if (c >= '1' && c <= '8') {
file += c - '0';
} else {
const Color color = std::isupper(static_cast<unsigned char>(c)) ? WHITE : BLACK;
const char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
PieceType pt = lower == 'p' ? PAWN : lower == 'n' ? KNIGHT
: lower == 'b' ? BISHOP : lower == 'r' ? ROOK
: lower == 'q' ? QUEEN : KING;
const int sq = rank * 8 + file++;
set_bit(pieces[color][pt], sq);
board_array[sq] = static_cast<Piece>(color * 6 + pt);
}
}
side_to_move = active == "w" ? WHITE : BLACK;
castling_rights = NO_CASTLING;
for (char c : castling) {
if (c == 'K') castling_rights |= WHITE_OO;
else if (c == 'Q') castling_rights |= WHITE_OOO;
else if (c == 'k') castling_rights |= BLACK_OO;
else if (c == 'q') castling_rights |= BLACK_OOO;
}
en_passant_square = ep == "-" ? SQ_NONE
: static_cast<Square>((ep[1] - '1') * 8 + ep[0] - 'a');
halfmove_clock = parsed_halfmove;
fullmove_number = parsed_fullmove;
update_occupancies();
if (!has_en_passant_capture()) {
en_passant_square = SQ_NONE;
}
hash_key = calculate_hash();
pawn_key = calculate_pawn_key();
non_pawn_key[WHITE] = calculate_non_pawn_key(WHITE);
non_pawn_key[BLACK] = calculate_non_pawn_key(BLACK);
history_ply = 0;
// Initialize NNUE accumulator
g_nnue.init_accumulator(*this, accumulator);
return true;
}
std::string Board::get_fen() const {
std::string fen = "";
for (int r = 7; r >= 0; r--) {
int empty_count = 0;
for (int f = 0; f < 8; f++) {
int sq = r * 8 + f;
Piece p = board_array[sq];
if (p == NO_PIECE) {
empty_count++;
} else {
if (empty_count > 0) {
fen += std::to_string(empty_count);
empty_count = 0;
}
char c;
PieceType pt = (PieceType)(p % 6);
Color color = (Color)(p / 6);
if (pt == PAWN) c = 'p';
else if (pt == KNIGHT) c = 'n';
else if (pt == BISHOP) c = 'b';
else if (pt == ROOK) c = 'r';
else if (pt == QUEEN) c = 'q';
else c = 'k';
if (color == WHITE) c = toupper(c);
fen += c;
}
}
if (empty_count > 0) {
fen += std::to_string(empty_count);
}
if (r > 0) fen += '/';
}
fen += " ";
fen += (side_to_move == WHITE) ? "w" : "b";
fen += " ";
std::string castling = "";
if (castling_rights & WHITE_OO) castling += "K";
if (castling_rights & WHITE_OOO) castling += "Q";
if (castling_rights & BLACK_OO) castling += "k";
if (castling_rights & BLACK_OOO) castling += "q";
if (castling.empty()) castling = "-";
fen += castling;
fen += " ";
fen += square_to_str(en_passant_square);
fen += " ";
fen += std::to_string(halfmove_clock);
fen += " ";
fen += std::to_string(fullmove_number);
return fen;
}
bool Board::is_square_attacked(int square, int attacker_color) const {
// 1. Attacked by pawns
int defender_color = attacker_color ^ 1;
U64 pawn_attackers = get_pawn_attacks(defender_color, square) & pieces[attacker_color][PAWN];
if (pawn_attackers) return true;
// 2. Attacked by knights
U64 knight_attackers = get_knight_attacks(square) & pieces[attacker_color][KNIGHT];
if (knight_attackers) return true;
// 3. Attacked by bishops/queens (diagonal sliding)
U64 bishop_queen_attackers = get_bishop_attacks(square, occupancies[BOTH]) & (pieces[attacker_color][BISHOP] | pieces[attacker_color][QUEEN]);
if (bishop_queen_attackers) return true;
// 4. Attacked by rooks/queens (orthogonal sliding)
U64 rook_queen_attackers = get_rook_attacks(square, occupancies[BOTH]) & (pieces[attacker_color][ROOK] | pieces[attacker_color][QUEEN]);
if (rook_queen_attackers) return true;
// 5. Attacked by king
U64 king_attackers = get_king_attacks(square) & pieces[attacker_color][KING];
if (king_attackers) return true;
return false;
}
bool Board::make_move(Move move, bool checked) {
if (history_ply < 0 || history_ply >= HISTORY_CAPACITY) {
return false;
}
assert(history_ply >= 0 && history_ply < HISTORY_CAPACITY);
int from = move.from();
int to = move.to();
int flag = move.flag();
Color us = side_to_move;
Color them = (Color)(us ^ 1);
Piece moving_piece = board_array[from];
PieceType pt = (PieceType)(moving_piece % 6);
side_to_move = them;
if (us == BLACK) {
fullmove_number++;
}
// Save state before making the move
history[history_ply] = {
castling_rights,
en_passant_square,
halfmove_clock,
NO_PIECE,
hash_key,
pawn_key,
{non_pawn_key[WHITE], non_pawn_key[BLACK]}
};
history_ply++;
// XOR out old side, castling, and EP
hash_key ^= zobrist_side;
hash_key ^= zobrist_castling[castling_rights];
if (en_passant_square != SQ_NONE) {
hash_key ^= zobrist_ep[en_passant_square % 8];
}
// Default next EP square is none
int new_en_passant_square = SQ_NONE;
// Handle captures
if (move.is_capture()) {
if (flag == FLAG_EP) {
int ep_pawn_sq = (us == WHITE) ? (to - 8) : (to + 8);
Piece captured = board_array[ep_pawn_sq];
history[history_ply - 1].captured_piece = captured;
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
nnue_deactivate_piece(them, PAWN, ep_pawn_sq);
clear_bit(pieces[them][PAWN], ep_pawn_sq);
board_array[ep_pawn_sq] = NO_PIECE;
clear_bit(occupancies[them], ep_pawn_sq);
clear_bit(occupancies[BOTH], ep_pawn_sq);
xor_piece_keys(them, PAWN, ep_pawn_sq);
} else {
Piece captured = board_array[to];
history[history_ply - 1].captured_piece = captured;
PieceType cap_type = (PieceType)(captured % 6);
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
nnue_deactivate_piece(them, cap_type, to);
clear_bit(pieces[them][cap_type], to);
clear_bit(occupancies[them], to);
clear_bit(occupancies[BOTH], to);
xor_piece_keys(them, cap_type, to);
}
halfmove_clock = 0; // Reset on capture
} else {
halfmove_clock++;
}
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
nnue_deactivate_piece(us, pt, from);
nnue_activate_piece(us, pt, to);
clear_bit(pieces[us][pt], from);
set_bit(pieces[us][pt], to);
clear_bit(occupancies[us], from);
set_bit(occupancies[us], to);
clear_bit(occupancies[BOTH], from);
set_bit(occupancies[BOTH], to);
board_array[from] = NO_PIECE;
board_array[to] = moving_piece;
xor_piece_keys(us, pt, from);
xor_piece_keys(us, pt, to);
// Handle promotions
if (move.is_promotion()) {
PieceType promo_pt = (PieceType)move.promotion_piece_type();
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
nnue_deactivate_piece(us, PAWN, to);
nnue_activate_piece(us, promo_pt, to);
clear_bit(pieces[us][PAWN], to);
set_bit(pieces[us][promo_pt], to);
board_array[to] = (Piece)(us * 6 + promo_pt);
xor_piece_keys(us, PAWN, to);
xor_piece_keys(us, promo_pt, to);
}
// Handle double pawn pushes (setup en passant)
if (flag == FLAG_DOUBLE_PAWN) {
new_en_passant_square = (us == WHITE) ? (from + 8) : (from - 8);
}
// Handle castling
if (flag == FLAG_KING_CASTLE) {
int r_from = (us == WHITE) ? SQ_H1 : SQ_H8;
int r_to = (us == WHITE) ? SQ_F1 : SQ_F8;
Piece rook = (us == WHITE) ? W_ROOK : B_ROOK;
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
nnue_deactivate_piece(us, ROOK, r_from);
nnue_activate_piece(us, ROOK, r_to);
clear_bit(pieces[us][ROOK], r_from);
set_bit(pieces[us][ROOK], r_to);
clear_bit(occupancies[us], r_from);
set_bit(occupancies[us], r_to);
clear_bit(occupancies[BOTH], r_from);
set_bit(occupancies[BOTH], r_to);
board_array[r_from] = NO_PIECE;
board_array[r_to] = rook;
xor_piece_keys(us, ROOK, r_from);
xor_piece_keys(us, ROOK, r_to);
} else if (flag == FLAG_QUEEN_CASTLE) {
int r_from = (us == WHITE) ? SQ_A1 : SQ_A8;
int r_to = (us == WHITE) ? SQ_D1 : SQ_D8;
Piece rook = (us == WHITE) ? W_ROOK : B_ROOK;
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
nnue_deactivate_piece(us, ROOK, r_from);
nnue_activate_piece(us, ROOK, r_to);
clear_bit(pieces[us][ROOK], r_from);
set_bit(pieces[us][ROOK], r_to);
clear_bit(occupancies[us], r_from);
set_bit(occupancies[us], r_to);
clear_bit(occupancies[BOTH], r_from);
set_bit(occupancies[BOTH], r_to);
board_array[r_from] = NO_PIECE;
board_array[r_to] = rook;
xor_piece_keys(us, ROOK, r_from);
xor_piece_keys(us, ROOK, r_to);
}
// Verify move legality (cannot expose king to check)
if (!checked) {
int king_sq = get_lsb(pieces[us][KING]);
if (is_square_attacked(king_sq, them)) {
unmake_move(move);
return false;
}
}
// Finalize state updates
int new_castling_rights = castling_rights & castling_rights_mask[from] & castling_rights_mask[to];
hash_key ^= zobrist_castling[new_castling_rights];
castling_rights = new_castling_rights;
en_passant_square = new_en_passant_square;
if (!has_en_passant_capture()) {
en_passant_square = SQ_NONE;
}
if (en_passant_square != SQ_NONE) {
hash_key ^= zobrist_ep[en_passant_square % 8];
}
return true;
}
void Board::unmake_move(Move move) {
assert(history_ply > 0);
if (history_ply <= 0) {
return;
}
// Pop state info
history_ply--;
StateInfo state = history[history_ply];
int from = move.from();
int to = move.to();
int flag = move.flag();
Color us = side_to_move; // us is the color to move NOW (which is them of the move)
Color player = (Color)(us ^ 1);
Piece moving_piece = board_array[to];
// Reverse the exact NNUE feature changes made by make_move. This avoids
// storing a 2 KiB accumulator snapshot in every history entry.
if (move.is_promotion()) {
PieceType promo_pt = (PieceType)move.promotion_piece_type();
nnue_deactivate_piece(player, promo_pt, to);
nnue_activate_piece(player, PAWN, from);
} else {
PieceType moved_pt = (PieceType)(moving_piece % 6);
nnue_deactivate_piece(player, moved_pt, to);
nnue_activate_piece(player, moved_pt, from);
}
if (move.is_capture()) {
int captured_sq = (flag == FLAG_EP)
? ((player == WHITE) ? (to - 8) : (to + 8))
: to;
Piece captured = state.captured_piece;
nnue_activate_piece(us, captured % 6, captured_sq);
}
if (flag == FLAG_KING_CASTLE || flag == FLAG_QUEEN_CASTLE) {
int rook_from = flag == FLAG_KING_CASTLE
? ((player == WHITE) ? SQ_H1 : SQ_H8)
: ((player == WHITE) ? SQ_A1 : SQ_A8);
int rook_to = flag == FLAG_KING_CASTLE
? ((player == WHITE) ? SQ_F1 : SQ_F8)
: ((player == WHITE) ? SQ_D1 : SQ_D8);
nnue_deactivate_piece(player, ROOK, rook_to);
nnue_activate_piece(player, ROOK, rook_from);
}
// Restore side to move
side_to_move = player;
// Handle promotions: revert piece back to pawn before moving back
if (move.is_promotion()) {
PieceType promo_pt = (PieceType)move.promotion_piece_type();
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
clear_bit(pieces[player][promo_pt], to);
set_bit(pieces[player][PAWN], to);
board_array[to] = (Piece)(player * 6 + PAWN);
moving_piece = board_array[to];
}
PieceType pt = (PieceType)(moving_piece % 6);
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
// Move the piece from to -> from
clear_bit(pieces[player][pt], to);
set_bit(pieces[player][pt], from);
clear_bit(occupancies[player], to);
set_bit(occupancies[player], from);
clear_bit(occupancies[BOTH], to);
set_bit(occupancies[BOTH], from);
board_array[from] = moving_piece;
board_array[to] = NO_PIECE;
// Handle captured pieces
if (move.is_capture()) {
Piece captured = state.captured_piece;
PieceType cap_type = (PieceType)(captured % 6);
if (flag == FLAG_EP) {
int ep_pawn_sq = (player == WHITE) ? (to - 8) : (to + 8);
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
set_bit(pieces[us][PAWN], ep_pawn_sq);
set_bit(occupancies[us], ep_pawn_sq);
set_bit(occupancies[BOTH], ep_pawn_sq);
board_array[ep_pawn_sq] = captured;
} else {
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
set_bit(pieces[us][cap_type], to);
set_bit(occupancies[us], to);
set_bit(occupancies[BOTH], to);
board_array[to] = captured;
}
}
// Handle castling rook moves back
if (flag == FLAG_KING_CASTLE) {
int r_from = (player == WHITE) ? SQ_H1 : SQ_H8;
int r_to = (player == WHITE) ? SQ_F1 : SQ_F8;
Piece rook = (player == WHITE) ? W_ROOK : B_ROOK;
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
clear_bit(pieces[player][ROOK], r_to);
set_bit(pieces[player][ROOK], r_from);
clear_bit(occupancies[player], r_to);
set_bit(occupancies[player], r_from);
clear_bit(occupancies[BOTH], r_to);
set_bit(occupancies[BOTH], r_from);
board_array[r_to] = NO_PIECE;
board_array[r_from] = rook;
} else if (flag == FLAG_QUEEN_CASTLE) {
int r_from = (player == WHITE) ? SQ_A1 : SQ_A8;
int r_to = (player == WHITE) ? SQ_D1 : SQ_D8;
Piece rook = (player == WHITE) ? W_ROOK : B_ROOK;
// NNUE INCREMENTAL ACCUMULATOR UPDATE HOOK
clear_bit(pieces[player][ROOK], r_to);
set_bit(pieces[player][ROOK], r_from);
clear_bit(occupancies[player], r_to);
set_bit(occupancies[player], r_from);
clear_bit(occupancies[BOTH], r_to);
set_bit(occupancies[BOTH], r_from);
board_array[r_to] = NO_PIECE;
board_array[r_from] = rook;
}
// Restore state variables
castling_rights = state.castling_rights;
en_passant_square = state.en_passant_square;
halfmove_clock = state.halfmove_clock;
hash_key = state.hash_key;
pawn_key = state.pawn_key;
non_pawn_key[WHITE] = state.non_pawn_key[WHITE];
non_pawn_key[BLACK] = state.non_pawn_key[BLACK];
if (player == BLACK) {
fullmove_number--;
}
}
void Board::print() const {
std::cout << "\n +---+---+---+---+---+---+---+---+\n";
for (int r = 7; r >= 0; r--) {
std::cout << (r + 1) << " |";
for (int f = 0; f < 8; f++) {
int sq = r * 8 + f;
Piece p = board_array[sq];
char c = ' ';
if (p != NO_PIECE) {
PieceType pt = (PieceType)(p % 6);
Color col = (Color)(p / 6);
if (pt == PAWN) c = 'P';
else if (pt == KNIGHT) c = 'N';
else if (pt == BISHOP) c = 'B';
else if (pt == ROOK) c = 'R';
else if (pt == QUEEN) c = 'Q';
else if (pt == KING) c = 'K';
if (col == BLACK) c = tolower(c);
}
std::cout << " " << c << " |";
}
std::cout << "\n +---+---+---+---+---+---+---+---+\n";
}
std::cout << " a b c d e f g h\n\n";
std::cout << "Fen: " << get_fen() << "\n";
std::cout << "Side to move: " << (side_to_move == WHITE ? "White" : "Black") << "\n";
std::cout << "Castling Rights: "
<< ((castling_rights & WHITE_OO) ? "K" : "")
<< ((castling_rights & WHITE_OOO) ? "Q" : "")
<< ((castling_rights & BLACK_OO) ? "k" : "")
<< ((castling_rights & BLACK_OOO) ? "q" : "")
<< "\n";
std::cout << "En Passant Square: " << square_to_str(en_passant_square) << "\n";
std::cout << "Halfmove Clock: " << halfmove_clock << "\n";
std::cout << "Fullmove Number: " << fullmove_number << "\n";
std::cout << "Zobrist Hash: 0x" << std::hex << hash_key << std::dec << "\n\n";
}
void Board::nnue_activate_piece(int color, int pt, int sq) {
int idx_w = get_feature_index_white(color, pt, sq);
int idx_b = get_feature_index_black(color, pt, sq);
g_nnue.accumulator_activate(accumulator, WHITE, idx_w);
g_nnue.accumulator_activate(accumulator, BLACK, idx_b);
}
void Board::nnue_deactivate_piece(int color, int pt, int sq) {
int idx_w = get_feature_index_white(color, pt, sq);
int idx_b = get_feature_index_black(color, pt, sq);
g_nnue.accumulator_deactivate(accumulator, WHITE, idx_w);
g_nnue.accumulator_deactivate(accumulator, BLACK, idx_b);
}
bool Board::make_null_move() {
if (history_ply < 0 || history_ply >= HISTORY_CAPACITY) {
return false;
}
assert(history_ply >= 0 && history_ply < HISTORY_CAPACITY);
// Save current state on history stack
history[history_ply] = {
castling_rights,
en_passant_square,
halfmove_clock,
NO_PIECE,
hash_key,
pawn_key,
{non_pawn_key[WHITE], non_pawn_key[BLACK]}
};
history_ply++;
// XOR out old side and en passant target
hash_key ^= zobrist_side;
if (en_passant_square != SQ_NONE) {
hash_key ^= zobrist_ep[en_passant_square % 8];
}
// Toggle side to move
side_to_move = (Color)(side_to_move ^ 1);
// Clear en passant square
en_passant_square = SQ_NONE;
return true;
}
void Board::unmake_null_move() {
assert(history_ply > 0);
if (history_ply <= 0) {
return;
}
history_ply--;
StateInfo state = history[history_ply];
castling_rights = state.castling_rights;
en_passant_square = state.en_passant_square;
halfmove_clock = state.halfmove_clock;
hash_key = state.hash_key;
pawn_key = state.pawn_key;
non_pawn_key[WHITE] = state.non_pawn_key[WHITE];
non_pawn_key[BLACK] = state.non_pawn_key[BLACK];
side_to_move = (Color)(side_to_move ^ 1);
}
bool Board::is_repetition() const {
int limit = std::min(halfmove_clock, history_ply);
for (int i = 2; i <= limit; i += 2) {
int idx = history_ply - i;
if (idx < 0) break; // Defensive boundary shield against stack underflow
if (history[idx].hash_key == hash_key) {
return true;
}
}
return false;
}
U64 Board::get_all_attackers(int square, U64 occ) const {
U64 attackers = 0;
// Pawns
attackers |= get_pawn_attacks(BLACK, square) & pieces[WHITE][PAWN];
attackers |= get_pawn_attacks(WHITE, square) & pieces[BLACK][PAWN];
// Knights
attackers |= get_knight_attacks(square) & (pieces[WHITE][KNIGHT] | pieces[BLACK][KNIGHT]);
// Bishops / Queens
attackers |= get_bishop_attacks(square, occ) & (pieces[WHITE][BISHOP] | pieces[BLACK][BISHOP] | pieces[WHITE][QUEEN] | pieces[BLACK][QUEEN]);
// Rooks / Queens
attackers |= get_rook_attacks(square, occ) & (pieces[WHITE][ROOK] | pieces[BLACK][ROOK] | pieces[WHITE][QUEEN] | pieces[BLACK][QUEEN]);
// Kings
attackers |= get_king_attacks(square) & (pieces[WHITE][KING] | pieces[BLACK][KING]);
return attackers & occ;
}
int Board::see(Move move) const {
int from = move.from();
int to = move.to();
int flag = move.flag();
int us = side_to_move;
int them = us ^ 1;
Piece moving_piece = board_array[from];
PieceType pt = (PieceType)(moving_piece % 6);
Piece captured = (flag == FLAG_EP) ? (us == WHITE ? B_PAWN : W_PAWN) : board_array[to];
const int piece_values[6] = { 100, 320, 330, 500, 900, 20000 };
int cap_value = (captured != NO_PIECE) ? piece_values[captured % 6] : 0;
int gain[32];
gain[0] = cap_value;
if (move.is_promotion()) {
int promo_pt = move.promotion_piece_type();
gain[0] += piece_values[promo_pt] - piece_values[PAWN];
}
U64 occ = occupancies[BOTH];
clear_bit(occ, from);
U64 remaining[2] = { occupancies[WHITE], occupancies[BLACK] };
clear_bit(remaining[us], from);
if (captured != NO_PIECE) {
const int captured_square = move.is_en_passant()
? to + (us == WHITE ? -8 : 8)
: to;
clear_bit(occ, captured_square);
clear_bit(remaining[them], captured_square);
}
int depth = 1;
int active_side = them;
int current_piece_value = move.is_promotion()
? piece_values[move.promotion_piece_type()]
: piece_values[pt];
U64 attackers = get_all_attackers(to, occ);
while (true) {
int cheapest_sq = -1;
int cheapest_val = 999999;
U64 side_attackers = attackers & remaining[active_side];
if (!side_attackers) break;
U64 temp = side_attackers;
while (temp) {
int sq = pop_lsb(temp);
Piece p = board_array[sq];
int type = p % 6;
if (piece_values[type] < cheapest_val) {
cheapest_val = piece_values[type];
cheapest_sq = sq;
}
}
if (cheapest_sq == -1) break;
clear_bit(occ, cheapest_sq);
clear_bit(remaining[active_side], cheapest_sq);
gain[depth] = current_piece_value;
current_piece_value = cheapest_val;
if (board_array[cheapest_sq] % 6 == KING) {
depth++;
break;
}
attackers = get_all_attackers(to, occ);
active_side ^= 1;
depth++;
}
while (--depth > 0) {
gain[depth - 1] = gain[depth - 1] - gain[depth];
if (depth - 1 > 0) {
gain[depth - 1] = std::max(0, gain[depth - 1]);
}
}
return gain[0];
}
LegalityMasks Board::get_legality_masks() const {
LegalityMasks masks;
masks.checkers = 0;
masks.pinned = 0;
std::fill(std::begin(masks.pin_rays), std::end(masks.pin_rays), 0ULL);
int us = side_to_move;
int them = us ^ 1;
int king_sq = get_lsb(pieces[us][KING]);
// 1. Get checkers
masks.checkers = (get_knight_attacks(king_sq) & pieces[them][KNIGHT]) |
(get_pawn_attacks(us, king_sq) & pieces[them][PAWN]) |
(get_bishop_attacks(king_sq, occupancies[BOTH]) & (pieces[them][BISHOP] | pieces[them][QUEEN])) |
(get_rook_attacks(king_sq, occupancies[BOTH]) & (pieces[them][ROOK] | pieces[them][QUEEN]));
// 2. Get pinned pieces and their pin rays
U64 potential_pinners = (get_bishop_attacks(king_sq, 0) & (pieces[them][BISHOP] | pieces[them][QUEEN])) |
(get_rook_attacks(king_sq, 0) & (pieces[them][ROOK] | pieces[them][QUEEN]));
while (potential_pinners) {
int slider_sq = pop_lsb(potential_pinners);
U64 blockers = between_bb[king_sq][slider_sq] & occupancies[BOTH];
if (count_bits(blockers) == 1) {
int pinned_sq = get_lsb(blockers);
if (occupancies[us] & (1ULL << pinned_sq)) {
masks.pinned |= (1ULL << pinned_sq);
masks.pin_rays[pinned_sq] = line_bb[king_sq][slider_sq];
}
}
}
// 3. Compute threats (all squares attacked by the opponent)
U64 threats = 0;
// Kingless occupancy: remove our king so slider rays "see through" it
U64 kingless_occ = occupancies[BOTH] ^ (1ULL << king_sq);
// Pawns (setwise, no loop)
U64 their_pawns = pieces[them][PAWN];
threats |= (them == WHITE) ? pawn_attacks_white(their_pawns)
: pawn_attacks_black(their_pawns);
// Knights (loop)
U64 their_knights = pieces[them][KNIGHT];
while (their_knights) {
threats |= get_knight_attacks(pop_lsb(their_knights));
}
// Bishops + Queen diagonals (loop, using kingless_occ)
U64 their_bishops = pieces[them][BISHOP] | pieces[them][QUEEN];
while (their_bishops) {
threats |= get_bishop_attacks(pop_lsb(their_bishops), kingless_occ);
}
// Rooks + Queen orthogonals (loop, using kingless_occ)
U64 their_rooks = pieces[them][ROOK] | pieces[them][QUEEN];
while (their_rooks) {
threats |= get_rook_attacks(pop_lsb(their_rooks), kingless_occ);
}
// Enemy king
threats |= get_king_attacks(get_lsb(pieces[them][KING]));
masks.threats = threats;
return masks;
}
bool Board::is_move_legal(Move move, const LegalityMasks& masks) const {
int from = move.from();
int to = move.to();
int flag = move.flag();
int us = side_to_move;
int them = us ^ 1;
Piece moving_piece = board_array[from];
PieceType pt = (PieceType)(moving_piece % 6);
int king_sq = get_lsb(pieces[us][KING]);
if (pt == KING) {
U64 temp_occ = occupancies[BOTH] ^ (1ULL << from);
Piece captured = board_array[to];
int cap_type = (captured != NO_PIECE) ? (captured % 6) : -1;
if (cap_type != -1) {
temp_occ ^= (1ULL << to);
}
U64 pawn_attackers = get_pawn_attacks(us, to) & pieces[them][PAWN];
if (pawn_attackers) return false;