-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposition.cpp
More file actions
820 lines (743 loc) · 32.1 KB
/
position.cpp
File metadata and controls
820 lines (743 loc) · 32.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
#include "position.h"
#include "movegen.h"
#include "moves_io.h"
#include "position.h"
#include <sstream>
#ifndef GENERATE_AT_RUNTIME
#define _POSSIBLY_CONSTEXPR constexpr
#else
#define _POSSIBLY_CONSTEXPR const
#endif
#if defined(__EXCEPTIONS)
#define THROW_IF_EXCEPTIONS_ON(stuff) throw stuff
#else
#define THROW_IF_EXCEPTIONS_ON(stuff) ((void)0)
#endif
#if defined(_DEBUG) || !defined(NDEBUG)
#define INVALID_ARG_IF(c, s) assert(!(c) && s)
#elif defined(__EXCEPTIONS)
#define INVALID_ARG_IF(c, s) \
if (c) \
THROW_IF_EXCEPTIONS_ON(std::invalid_argument(s))
#else
#define INVALID_ARG_IF(c, s)
#endif
namespace chess {
template <typename PieceC, typename T> template <bool Strict> void _Position<PieceC, T>::doMove(const Move &move) {
assert(move.is_ok() && "doMove called with invalid move");
Square from_sq = move.from_sq(), to_sq = move.to_sq();
Color us = side_to_move(), them = ~us;
MoveType move_type = move.type_of();
PieceC moving_piece = piece_on(from_sq);
PieceC target_piece = piece_on(to_sq);
PieceType moving_piecetype = piece_of(moving_piece);
PieceType target_piecetype = piece_of(target_piece);
Color target_color = color_of(target_piece);
bool is_capture = isCapture(move);
history.push_back(current_state);
current_state.incr_sqs[0] = current_state.incr_sqs[1] = current_state.incr_sqs[2] = current_state.incr_sqs[3] = SQ_NONE;
current_state.incr_pc[0] = current_state.incr_pc[1] = current_state.incr_pc[2] = current_state.incr_pc[3] =
PieceC::NO_PIECE;
current_state.mv = move; // Update the move in the current state
if (target_piecetype == KING) {
std::cerr << *this << '\n';
std::cerr << "Move: " << move << "\n";
std::cerr << "From: " << from_sq << " To: " << to_sq << "\n";
std::cerr << "Target piece: " << target_piece << "\n";
std::cerr << "Side to move: " << us << "\n";
std::cerr << "movetrace: \n";
for (int i = 0; i < history.size(); i++)
std::cerr << uci::moveToUci(history[i].mv, _chess960) << '\n';
}
INVALID_ARG_IF(target_piecetype == KING, "Capturing kings is illegal");
INVALID_ARG_IF(moving_piecetype == NO_PIECE_TYPE, "Expected a piece to move.");
{
switch (move_type) {
case NORMAL:
removePiece(target_piecetype, to_sq, target_color);
removePiece(moving_piecetype, from_sq, us);
placePiece(moving_piecetype, to_sq, us);
current_state.incr_sqs[0] = from_sq;
current_state.incr_pc[0] = moving_piece;
current_state.incr_sqs[1] = to_sq;
current_state.incr_pc[1] = target_piece;
break;
case PROMOTION:
removePiece(target_piecetype, to_sq, target_color);
removePiece(moving_piecetype, from_sq, us);
placePiece(move.promotion_type(), to_sq, us);
current_state.incr_sqs[0] = from_sq;
current_state.incr_pc[0] = moving_piece;
current_state.incr_sqs[1] = to_sq;
current_state.incr_pc[1] = target_piece;
break;
case EN_PASSANT: {
Square ep_capture_sq = to_sq + pawn_push(them);
removePiece(moving_piecetype, from_sq, us);
removePiece<PAWN>(ep_capture_sq, them);
placePiece<PAWN>(to_sq, us);
current_state.incr_sqs[0] = from_sq;
current_state.incr_pc[0] = moving_piece;
current_state.incr_sqs[1] = ep_capture_sq;
current_state.incr_pc[1] = make_piece<PieceC>(PAWN, them);
current_state.incr_sqs[2] = to_sq;
current_state.incr_pc[2] = PieceC::NO_PIECE;
break;
}
case CASTLING: {
const bool is_king_side = file_of(from_sq) < file_of(to_sq);
const Square rook_dest = castling_rook_square(us, is_king_side);
const Square king_dest = castling_king_square(us, is_king_side);
const PieceC prev_king_dest = piece_on(king_dest);
const PieceC prev_rook_dest = piece_on(rook_dest);
current_state.incr_sqs[0] = from_sq, current_state.incr_pc[0] = moving_piece;
current_state.incr_sqs[1] = to_sq, current_state.incr_pc[1] = target_piece;
current_state.incr_sqs[2] = king_dest, current_state.incr_pc[2] = prev_king_dest;
current_state.incr_sqs[3] = rook_dest, current_state.incr_pc[3] = prev_rook_dest;
Square rook_start = is_king_side ? current_state.castlingMetadata[us].rook_start_ks
: current_state.castlingMetadata[us].rook_start_qs;
removePiece<KING>(from_sq, us);
removePiece<ROOK>(rook_start, us);
placePiece<KING>(king_dest, us);
placePiece<ROOK>(rook_dest, us);
break;
}
}
}
{
// Detect a two-square pawn push.
bool isDoublePush = (moving_piecetype == PAWN) && (abs(to_sq - from_sq) == 16);
// Remove old EP key if it was actually included.
bool _ir_1 = current_state.enPassant != SQ_NONE && current_state.epIncluded;
current_state.hash ^= _ir_1 ? zobrist::RandomEP[file_of(current_state.enPassant)] : 0;
// Default: no EP square and not included.
current_state.epIncluded = false;
// If the move creates a potential EP target:
current_state.enPassant = isDoublePush ? (from_sq + pawn_push(us)) : SQ_NONE;
if (isDoublePush) {
// Now side to move is the *opponent*.
Color stm = ~us;
File f = file_of(current_state.enPassant);
Bitboard ep_mask = (1ULL << current_state.enPassant);
// Shift toward the side-to-move's capturing rank.
ep_mask = (stm == WHITE) ? (ep_mask >> 8) : (ep_mask << 8);
// Keep adjacent files only.
ep_mask = ((ep_mask << 1) & ~attacks::MASK_FILE[0]) | ((ep_mask >> 1) & ~attacks::MASK_FILE[7]);
// Include key if their pawns can attack it.
current_state.epIncluded = (ep_mask & pieces<PAWN>(stm)) != 0;
current_state.hash ^= current_state.epIncluded ? zobrist::RandomEP[f] : 0;
}
}
{
CastlingRights clear_mask = NO_CASTLING;
// Moving piece
if (moving_piecetype == KING && from_sq == current_state.castlingMetadata[us].king_start) {
clear_mask |= (us == WHITE ? WHITE_CASTLING : BLACK_CASTLING);
} else if (moving_piecetype == ROOK) {
if (from_sq == current_state.castlingMetadata[us].rook_start_ks) {
clear_mask |= (us == WHITE ? WHITE_OO : BLACK_OO);
} else if (from_sq == current_state.castlingMetadata[us].rook_start_qs) {
clear_mask |= (us == WHITE ? WHITE_OOO : BLACK_OOO);
}
}
// Captured piece
if (target_piecetype == ROOK) {
if (to_sq == current_state.castlingMetadata[target_color].rook_start_ks)
clear_mask |= (target_color == WHITE ? WHITE_OO : BLACK_OO);
else if (to_sq == current_state.castlingMetadata[target_color].rook_start_qs)
clear_mask |= (target_color == WHITE ? WHITE_OOO : BLACK_OOO);
}
CastlingRights prev = current_state.castlingRights;
current_state.castlingRights &= ~clear_mask;
current_state.hash ^= zobrist::RandomCastle[prev] ^ zobrist::RandomCastle[current_state.castlingRights];
}
current_state.turn = ~current_state.turn;
// Update halfmoves, fullmoves and stm
current_state.fullMoveNumber += (current_state.turn == WHITE);
current_state.halfMoveClock = (is_capture || moving_piecetype == PAWN) ? 0 : (current_state.halfMoveClock + 1);
current_state.hash ^= zobrist::RandomTurn;
refresh_attacks();
// DO NOT MIX REPETITIONS
current_state.pliesFromNull++;
if constexpr (Strict) {
// Calculate the repetition info. It is the ply distance from the previous
// occurrence of the same position, negative in the 3-fold case, or zero
// if the position was not repeated.
current_state.repetition = 0;
int end = std::min(rule50_count(), current_state.pliesFromNull);
if (end >= 4) {
auto *stp = &history[history.size_ - 1];
stp -= 1;
for (int i = 4; i <= end; i += 2) {
stp -= 2;
if (stp->hash == hash()) {
current_state.repetition = stp->repetition ? -i : i;
break;
}
}
}
}
}
template <typename PieceC, typename T> void _Position<PieceC, T>::setFEN(const std::string &str, bool chess960) {
current_state = HistoryEntry<PieceC>();
history.clear();
_chess960 = chess960;
std::istringstream ss(str);
std::string board_fen, active_color, castling, enpassant;
int halfmove = 0, fullmove = 1;
ss >> board_fen;
ss >> active_color;
ss >> castling;
ss >> enpassant;
ss >> halfmove;
ss >> fullmove;
// 1. Parse board
{
File f = FILE_A;
Rank r = RANK_8;
int file_count = 0;
int rank_count = 0;
for (char c : board_fen) {
if (c == '/') {
INVALID_ARG_IF(file_count != 8, "Each rank must contain exactly 8 squares");
f = FILE_A;
--r;
file_count = 0;
++rank_count;
continue;
}
if (c >= '1' && c <= '8') {
int empty_squares = c - '0';
file_count += empty_squares;
f = static_cast<File>(static_cast<uint8_t>(f) + empty_squares);
} else {
INVALID_ARG_IF(file_count >= 8, "Too many pieces in one rank");
INVALID_ARG_IF(!chess::is_valid(r, f), "Invalid file/rank position");
switch (c) {
case 'p':
placePiece<PAWN>(make_sq(r, f), BLACK);
break;
case 'P':
placePiece<PAWN>(make_sq(r, f), WHITE);
break;
case 'n':
placePiece<KNIGHT>(make_sq(r, f), BLACK);
break;
case 'N':
placePiece<KNIGHT>(make_sq(r, f), WHITE);
break;
case 'b':
placePiece<BISHOP>(make_sq(r, f), BLACK);
break;
case 'B':
placePiece<BISHOP>(make_sq(r, f), WHITE);
break;
case 'r':
placePiece<ROOK>(make_sq(r, f), BLACK);
break;
case 'R':
placePiece<ROOK>(make_sq(r, f), WHITE);
break;
case 'q':
placePiece<QUEEN>(make_sq(r, f), BLACK);
break;
case 'Q':
placePiece<QUEEN>(make_sq(r, f), WHITE);
break;
case 'k':
placePiece<KING>(make_sq(r, f), BLACK);
break;
case 'K':
placePiece<KING>(make_sq(r, f), WHITE);
break;
default:
INVALID_ARG_IF(false, "Invalid FEN character");
break;
}
++file_count;
f = static_cast<File>(static_cast<uint8_t>(f) + 1);
}
}
// Final assertions after parsing
INVALID_ARG_IF(file_count != 8, "Last rank must have 8 squares");
INVALID_ARG_IF(rank_count != 7, "FEN must contain exactly 8 ranks");
}
// 2. Turn
if (active_color == "w") {
current_state.turn = WHITE;
current_state.hash ^= zobrist::RandomTurn;
} else if (active_color == "b") {
current_state.turn = BLACK;
} else {
INVALID_ARG_IF(active_color != "w" && active_color != "b", "Expected white or black, got something else.");
}
// 3. Castling rights
current_state.castlingRights = NO_CASTLING;
for (char c : castling) {
switch (c) {
case 'K':
INVALID_ARG_IF(chess960, "Chess960 needs specific file");
current_state.castlingRights |= WHITE_OO;
current_state.castlingMetadata[WHITE].king_start = kingSq(WHITE);
current_state.castlingMetadata[WHITE].rook_start_ks = SQ_H1;
break;
case 'Q':
INVALID_ARG_IF(chess960, "Chess960 needs specific file");
current_state.castlingRights |= WHITE_OOO;
current_state.castlingMetadata[WHITE].king_start = kingSq(WHITE);
current_state.castlingMetadata[WHITE].rook_start_qs = SQ_A1;
break;
case 'k':
INVALID_ARG_IF(chess960, "Chess960 needs specific file");
current_state.castlingRights |= BLACK_OO;
current_state.castlingMetadata[BLACK].king_start = kingSq(BLACK);
current_state.castlingMetadata[BLACK].rook_start_ks = SQ_H8;
break;
case 'q':
INVALID_ARG_IF(chess960, "Chess960 needs specific file");
current_state.castlingRights |= BLACK_OOO;
current_state.castlingMetadata[BLACK].king_start = kingSq(BLACK);
current_state.castlingMetadata[BLACK].rook_start_qs = SQ_A8;
break;
// some optional chess960? maybe not.
case '-':
break;
default: {
INVALID_ARG_IF(!chess960, "Invalid castling right for non-Chess960");
if (c >= 'A' && c <= 'H') // white-castling
{
const auto king_start = kingSq(WHITE);
const auto rook_start = make_sq(RANK_1, static_cast<File>(c - 'A'));
CastlingRights cr = (file_of(rook_start) > file_of(king_start) ? WHITE_OO : WHITE_OOO);
current_state.castlingRights |= cr;
current_state.castlingMetadata[WHITE].king_start = kingSq(WHITE);
if (cr & KING_SIDE)
current_state.castlingMetadata[WHITE].rook_start_ks = rook_start;
else
current_state.castlingMetadata[WHITE].rook_start_qs = rook_start;
} else if (c >= 'a' && c <= 'h') // white-castling
{
const auto king_start = kingSq(BLACK);
const auto rook_start = make_sq(RANK_8, static_cast<File>(c - 'a'));
CastlingRights cr = (file_of(rook_start) > file_of(king_start) ? BLACK_OO : BLACK_OOO);
current_state.castlingRights |= cr;
current_state.castlingMetadata[BLACK].king_start = king_start;
if (cr & KING_SIDE)
current_state.castlingMetadata[BLACK].rook_start_ks = rook_start;
else
current_state.castlingMetadata[BLACK].rook_start_qs = rook_start;
}
break;
}
}
}
current_state.hash ^= zobrist::RandomCastle[current_state.castlingRights];
for (Color c : { WHITE, BLACK }) {
// king
if (castlingRights() & (c & KING_SIDE)) {
const auto king_from = current_state.castlingMetadata[c].king_start;
const auto rook_from = make_sq(file_of(current_state.castlingMetadata[c].rook_start_ks), rank_of(king_from));
const auto king_to = castling_king_square(c, true);
const auto rook_to = castling_rook_square(c, true);
current_state.castlingMetadata[c].castling_paths[true] =
(movegen::between(rook_from, rook_to) | movegen::between(king_from, king_to)) &
~((1ULL << king_from) | (1ULL << rook_from));
}
// queen
if (castlingRights() & (c & QUEEN_SIDE)) {
const auto king_from = current_state.castlingMetadata[c].king_start;
const auto rook_from = make_sq(file_of(current_state.castlingMetadata[c].rook_start_qs), rank_of(king_from));
const auto king_to = castling_king_square(c, false);
const auto rook_to = castling_rook_square(c, false);
current_state.castlingMetadata[c].castling_paths[false] =
(movegen::between(rook_from, rook_to) | movegen::between(king_from, king_to)) &
~((1ULL << king_from) | (1ULL << rook_from));
}
}
if (enpassant != "-" && enpassant.length() == 2 && enpassant[0] >= 'a' && enpassant[0] <= 'h' && enpassant[1] >= '1' &&
enpassant[1] <= '8') {
File f = static_cast<File>(enpassant[0] - 'a');
Rank r = static_cast<Rank>(enpassant[1] - '1');
Square ep_sq = make_sq(r, f);
current_state.enPassant = ep_sq;
Bitboard ep_mask = 1ULL << ep_sq;
if (sideToMove() == WHITE) {
ep_mask >>= 8;
} else
ep_mask <<= 8;
ep_mask = ((ep_mask << 1) & ~attacks::MASK_FILE[0]) | ((ep_mask >> 1) & ~attacks::MASK_FILE[7]);
if (ep_mask & pieces<PAWN>(sideToMove())) {
current_state.hash ^= zobrist::RandomEP[f];
current_state.epIncluded = true;
}
} else {
INVALID_ARG_IF(enpassant != "-", "Invalid en passant FEN field");
current_state.enPassant = SQ_NONE;
}
// 5. Halfmove clock
current_state.halfMoveClock = static_cast<uint8_t>(halfmove);
// 6. Fullmove number
current_state.fullMoveNumber = fullmove;
refresh_attacks();
current_state.repetition = current_state.pliesFromNull = 0;
}
template <typename PieceC, typename T> std::string _Position<PieceC, T>::fen() const {
std::ostringstream ss;
// 1) Piece placement
for (Rank rank = RANK_8; rank >= RANK_1; --rank) {
int emptyCount = 0;
for (File file = FILE_A; file <= FILE_H; ++file) {
Square sq = make_sq(rank, file); // Assuming 0..63 indexing
PieceC piece = piece_on(sq);
if (piece == PieceC::NO_PIECE) {
emptyCount++;
} else {
if (emptyCount > 0) {
ss << std::to_string(emptyCount);
emptyCount = 0;
}
ss << piece;
}
}
if (emptyCount > 0)
ss << std::to_string(emptyCount);
if (rank > 0)
ss << '/';
}
// 2) Side to move
ss << ' ' << (sideToMove() == WHITE ? 'w' : 'b');
// 3) Castling availability
ss << ' ';
std::string castlingStr;
if (chess960()) {
if (castlingRights() & WHITE_OO)
castlingStr += static_cast<char>('A' + file_of(current_state.castlingMetadata[WHITE].rook_start_ks));
if (castlingRights() & WHITE_OOO)
castlingStr += static_cast<char>('A' + file_of(current_state.castlingMetadata[WHITE].rook_start_qs));
if (castlingRights() & BLACK_OO)
castlingStr += static_cast<char>('a' + file_of(current_state.castlingMetadata[BLACK].rook_start_ks));
if (castlingRights() & BLACK_OOO)
castlingStr += static_cast<char>('a' + file_of(current_state.castlingMetadata[BLACK].rook_start_qs));
} else {
if (castlingRights() & WHITE_OO)
castlingStr += 'K';
if (castlingRights() & WHITE_OOO)
castlingStr += 'Q';
if (castlingRights() & BLACK_OO)
castlingStr += 'k';
if (castlingRights() & BLACK_OOO)
castlingStr += 'q';
}
ss << (castlingStr.empty() ? "-" : castlingStr);
// 4) En passant target square or '-'
ss << ' ';
Square ep = ep_square();
ss << (ep == SQ_NONE ? "-" : uci::squareToString(ep));
// 5) Halfmove clock
ss << ' ' << (int)halfmoveClock();
// 6) Fullmove number
ss << ' ' << (int)fullmoveNumber();
return ss.str();
}
template <typename PieceC, typename T> template <bool Strict> bool _Position<PieceC, T>::is_valid() const {
if (count<KING, WHITE>() != 1)
return false;
if (count<KING, BLACK>() != 1)
return false;
Color stm = sideToMove();
// stm checking
bool whiteInCheck = isAttacked(kingSq(WHITE), BLACK);
bool blackInCheck = isAttacked(kingSq(BLACK), WHITE);
// Both kings cannot be in check simultaneously
if (whiteInCheck && blackInCheck)
return false;
// The side to move cannot have its king currently in check from itself (nonsense)
if (isAttacked(kingSq(~stm), stm))
return false;
if (piece_on(SQ_A1) != PieceC::WROOK && (castlingRights() & WHITE_OOO) != 0)
return false;
// pawns not on backrank
if ((pieces(PAWN) & (attacks::MASK_RANK[RANK_1] | attacks::MASK_RANK[RANK_8])) != 0)
return false;
if constexpr (Strict) {
// pawns not > 8
{
int pawns = count<PAWN, WHITE>();
int queens = count<QUEEN, WHITE>();
int rooks = count<ROOK, WHITE>();
int bishops = count<BISHOP, WHITE>();
int knights = count<KNIGHT, WHITE>();
// Base set: 1 queen, 2 rooks, 2 bishops, 2 knights
int promotions =
std::max(0, (queens - 1)) + std::max(0, (rooks - 2)) + std::max(0, (bishops - 2)) + std::max(0, (knights - 2));
if (pawns + promotions > 8)
return false; // impossible
}
{
int pawns = count<PAWN, BLACK>();
int queens = count<QUEEN, BLACK>();
int rooks = count<ROOK, BLACK>();
int bishops = count<BISHOP, BLACK>();
int knights = count<KNIGHT, BLACK>();
// Base set: 1 queen, 2 rooks, 2 bishops, 2 knights
int promotions =
std::max(0, (queens - 1)) + std::max(0, (rooks - 2)) + std::max(0, (bishops - 2)) + std::max(0, (knights - 2));
if (pawns + promotions > 8)
return false; // impossible
}
}
if (Square ep_sq = ep_square(); ep_sq != SQ_NONE) {
if ((stm == WHITE && rank_of(ep_sq) != RANK_6) || (stm == BLACK && rank_of(ep_sq) != RANK_3))
return false;
Square behind = ep_sq + ((stm == WHITE) ? SOUTH : NORTH);
if (piece_at(behind) != make_piece<PieceC>(PAWN, ~stm))
return false;
if (!(attacks::pawn(~stm, ep_sq) & pieces<PAWN>(stm)))
return false;
}
// Too many checkers
if (popcount(checkers()) > 2)
return false;
return true;
}
template <typename PieceC, typename T> CheckType _Position<PieceC, T>::givesCheck(Move m) const {
const static auto getSniper = [](const _Position<PieceC> *p, Square ksq, Bitboard oc) {
const auto us_occ = p->us(p->sideToMove());
const auto bishop = attacks::bishop(ksq, oc) & p->pieces(PieceType::BISHOP, PieceType::QUEEN) & us_occ;
const auto rook = attacks::rook(ksq, oc) & p->pieces(PieceType::ROOK, PieceType::QUEEN) & us_occ;
return (bishop | rook);
};
assert(color_of(at(m.from())) == sideToMove());
const Square from = m.from();
const Square to = m.to();
const Square ksq = kingSq(~sideToMove());
const Bitboard toBB = 1ULL << (to);
const PieceType pt = piece_of(at(from));
Bitboard fromKing = 0ull;
if (pt == PieceType::PAWN) {
fromKing = attacks::pawn(~side_to_move(), ksq);
} else if (pt == PieceType::KNIGHT) {
fromKing = attacks::knight(ksq);
} else if (pt == PieceType::BISHOP) {
fromKing = attacks::bishop(ksq, occ());
} else if (pt == PieceType::ROOK) {
fromKing = attacks::rook(ksq, occ());
} else if (pt == PieceType::QUEEN) {
fromKing = attacks::queen(ksq, occ());
}
if (fromKing & toBB)
return CheckType::DIRECT_CHECK;
// Discovery check
const Bitboard fromBB = 1ULL << (from);
const Bitboard oc = occ() ^ fromBB;
Bitboard sniper = getSniper(this, ksq, oc);
if (sniper) {
Square sq = (Square)pop_lsb(sniper);
return (!(movegen::between(ksq, sq) & toBB) || m.typeOf() == Move::CASTLING) ? CheckType::DISCOVERY_CHECK
: CheckType::NO_CHECK;
}
switch (m.typeOf()) {
case Move::NORMAL:
return CheckType::NO_CHECK;
case Move::PROMOTION: {
Bitboard attacks = 0ull;
switch (m.promotionType()) {
case KNIGHT:
attacks = attacks::knight(to);
break;
case BISHOP:
attacks = attacks::bishop(to, oc);
break;
case ROOK:
attacks = attacks::rook(to, oc);
break;
case QUEEN:
attacks = attacks::queen(to, oc);
break;
default:
break;
}
return (attacks & pieces(PieceType::KING, ~sideToMove())) ? CheckType::DIRECT_CHECK : CheckType::NO_CHECK;
}
case Move::ENPASSANT: {
Square capSq = make_sq(file_of(to), rank_of(from));
return (getSniper(this, ksq, (oc ^ (1ULL << capSq)) | toBB)) ? CheckType::DISCOVERY_CHECK : CheckType::NO_CHECK;
}
case Move::CASTLING: {
Square rookTo = relative_square(side_to_move(), to > from ? SQ_F1 : SQ_D1);
return (attacks::rook(ksq, occ()) & (1ULL << rookTo)) ? CheckType::DISCOVERY_CHECK : CheckType::NO_CHECK;
}
}
assert(false);
return CheckType::NO_CHECK; // Prevent a compiler warning
}
template <typename PieceC, typename T> void _Position<PieceC, T>::refresh_attacks() {
Color c = sideToMove();
Square king_sq = kingSq(c);
_bishop_pin = pinMask<BISHOP>(c, king_sq);
_rook_pin = pinMask<ROOK>(c, king_sq);
_pin_mask = _bishop_pin | _rook_pin;
_checkers = attackers(~c, king_sq);
int num_checks = popcount(_checkers);
switch (num_checks) {
case 0:
_check_mask = ~0ULL; // no checks, full mask
break;
case 1: {
Square sq = static_cast<Square>(lsb(_checkers));
Bitboard mask = (1ULL << sq) | movegen::between(king_sq, sq);
_check_mask = mask;
break;
}
default:
_check_mask = 0ULL; // multiple checks, no blocking mask
break;
}
}
template <typename PieceC, typename T> uint64_t _Position<PieceC, T>::zobrist() const {
uint64_t hash = 0;
for (int sq = 0; sq < 64; ++sq) {
auto p = piece_on((Square)sq);
hash ^= (p == PieceC::NO_PIECE) ? 0 : zobrist::RandomPiece[enum_idx<PieceC>()][(int)p][sq];
}
hash ^= (current_state.turn == WHITE) ? zobrist::RandomTurn : 0;
hash ^= zobrist::RandomCastle[current_state.castlingRights];
auto ep_sq = current_state.enPassant;
if (ep_sq == SQ_NONE)
return hash;
if (ep_sq != SQ_NONE) {
File f = file_of(ep_sq);
Bitboard ep_mask = (1ULL << ep_sq);
// Shift to the rank where the opposing pawn sits
Color stm = sideToMove();
// Color them = ~stm;
ep_mask = (stm == WHITE) ? (ep_mask >> 8) : (ep_mask << 8);
// Pawns on adjacent files only
ep_mask = ((ep_mask << 1) & ~attacks::MASK_FILE[0]) | ((ep_mask >> 1) & ~attacks::MASK_FILE[7]);
if (ep_mask & pieces<PAWN>(stm))
hash ^= zobrist::RandomEP[f];
}
return hash;
}
template <typename PieceC, typename T> Move _Position<PieceC, T>::parse_uci(std::string uci) const {
return chess::uci::uciToMove(*this, uci);
}
template <typename PieceC, typename T> Move _Position<PieceC, T>::push_uci(std::string uci) {
auto mv = parse_uci(uci);
doMove(mv);
return mv;
}
template <typename PieceC, typename T> Square _Position<PieceC, T>::_valid_ep_square() const {
if (ep_square() == SQ_NONE)
return SQ_NONE;
Rank ep_rank = sideToMove() == WHITE ? RANK_6 : RANK_3;
Bitboard mask = 1ULL << ep_square();
Bitboard pawn_mask = mask << 8;
Bitboard org_pawn_mask = mask >> 8;
if (sideToMove() == BLACK)
std::swap(pawn_mask, org_pawn_mask);
// rank 3 or rank 6, depending on color
if (rank_of(ep_square()) != ep_rank)
return SQ_NONE;
// a pawn in 2 ranks behind
if (!(pieces(PAWN) & occ(~sideToMove()) & pawn_mask))
return SQ_NONE;
// ep_sq must be empty
if (occ() & mask)
return SQ_NONE;
// emptied second rank
if (occ() & org_pawn_mask)
return SQ_NONE;
return ep_square();
}
template <typename PieceC, typename T> bool _Position<PieceC, T>::is_insufficient_material(Color c) const {
const auto count = popcount(occ());
// only kings, draw
if (count == 2)
return true;
// only bishop + knight, can't mate
if (count == 3) {
if (pieces(PieceType::BISHOP, Color::WHITE) || pieces(PieceType::BISHOP, Color::BLACK))
return true;
if (pieces(PieceType::KNIGHT, Color::WHITE) || pieces(PieceType::KNIGHT, Color::BLACK))
return true;
}
// same-colored bishops, can't mate
if (count == 4) {
// bishops on same color (one per side)
if (pieces(PieceType::BISHOP, Color::WHITE) && pieces(PieceType::BISHOP, Color::BLACK)) {
Square w = (Square)lsb(pieces(PieceType::BISHOP, Color::WHITE));
Square b = (Square)lsb(pieces(PieceType::BISHOP, Color::BLACK));
if (((9 * (w ^ b)) & 8) == 0)
return true;
}
// one side with two bishops on same color
auto white_bishops = pieces(PieceType::BISHOP, Color::WHITE);
auto black_bishops = pieces(PieceType::BISHOP, Color::BLACK);
if (popcount(white_bishops) == 2) {
Square b1 = (Square)lsb(white_bishops);
Square b2 = (Square)msb(white_bishops);
if (((9 * (b1 ^ b2)) & 8) == 0)
return true;
} else if (popcount(black_bishops) == 2) {
Square b1 = (Square)lsb(black_bishops);
Square b2 = (Square)msb(black_bishops);
if (((9 * (b1 ^ b2)) & 8) == 0)
return true;
}
}
return false;
}
template <typename PieceC, typename T> CastlingRights _Position<PieceC, T>::clean_castling_rights() const {
constexpr Bitboard cr_WOO = 1ULL << SQ_H1;
constexpr Bitboard cr_WOOO = 1ULL << SQ_A1;
constexpr Bitboard cr_BOO = 1ULL << SQ_H8;
constexpr Bitboard cr_BOOO = 1ULL << SQ_A8;
if (history.size())
return castlingRights();
Bitboard castling = 0;
// mappings
castling |= (castlingRights() & WHITE_OO) ? cr_WOO : 0;
castling |= (castlingRights() & WHITE_OOO) ? cr_WOOO : 0;
castling |= (castlingRights() & BLACK_OO) ? cr_BOO : 0;
castling |= (castlingRights() & BLACK_OOO) ? cr_BOOO : 0;
castling &= pieces(ROOK);
Bitboard white_castling = castling & attacks::MASK_RANK[RANK_1] & occ(WHITE);
Bitboard black_castling = castling & attacks::MASK_RANK[RANK_8] & occ(BLACK);
// rook exists in corresponding square
white_castling &= (cr_WOO | cr_WOOO);
black_castling &= (cr_BOO | cr_BOOO);
// king exists in e1/e8 depending on color
if (!(occ(WHITE) & pieces(KING) & (1ULL << SQ_E1)))
white_castling = 0;
if (!(occ(BLACK) & pieces(KING) & (1ULL << SQ_E8)))
black_castling = 0;
castling = white_castling | black_castling;
// Re-map
CastlingRights cr = NO_CASTLING;
cr |= (castling & cr_WOO) ? WHITE_OO : NO_CASTLING;
cr |= (castling & cr_WOOO) ? WHITE_OOO : NO_CASTLING;
cr |= (castling & cr_BOO) ? BLACK_OO : NO_CASTLING;
cr |= (castling & cr_BOOO) ? BLACK_OOO : NO_CASTLING;
return cr;
}
// clang-format off
#define INSTANTIATE(PieceC) \
template void _Position<PieceC, void>::setFEN(const std::string &, bool); \
template std::string _Position<PieceC, void>::fen() const; \
template void _Position<PieceC, void>::doMove<false>(const Move &move); \
template void _Position<PieceC, void>::doMove<true>(const Move &move); \
template void _Position<PieceC, void>::refresh_attacks(); \
template uint64_t _Position<PieceC, void>::zobrist() const; \
template Move _Position<PieceC, void>::parse_uci(std::string) const; \
template Move _Position<PieceC, void>::push_uci(std::string); \
template bool _Position<PieceC, void>::is_valid<false>() const; \
template bool _Position<PieceC, void>::is_valid<true>() const; \
template CheckType _Position<PieceC, void>::givesCheck(Move) const; \
template bool _Position<PieceC, void>::is_insufficient_material() const;
// clang-format off
INSTANTIATE(PolyglotPiece)
INSTANTIATE(EnginePiece)
INSTANTIATE(ContiguousMappingPiece)
#undef INSTANTIATE
} // namespace chess