2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
38 Key Position::zobrist[2][8][64];
39 Key Position::zobEp[8];
40 Key Position::zobCastle[16];
41 Key Position::zobSideToMove;
42 Key Position::zobExclusion;
44 Score Position::pieceSquareTable[16][64];
46 // Material values arrays, indexed by Piece
47 const Value PieceValueMidgame[17] = {
49 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
50 RookValueMidgame, QueenValueMidgame,
51 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
52 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
53 RookValueMidgame, QueenValueMidgame
56 const Value PieceValueEndgame[17] = {
58 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
59 RookValueEndgame, QueenValueEndgame,
60 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
61 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
62 RookValueEndgame, QueenValueEndgame
68 // Bonus for having the side to move (modified by Joona Kiiski)
69 const Score Tempo = make_score(48, 22);
71 // To convert a Piece to and from a FEN char
72 const string PieceToChar(" PNBRQK pnbrqk .");
78 CheckInfo::CheckInfo(const Position& pos) {
80 Color them = ~pos.side_to_move();
81 ksq = pos.king_square(them);
83 pinned = pos.pinned_pieces();
84 dcCandidates = pos.discovered_check_candidates();
86 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
87 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
88 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
89 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
90 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
95 /// Position::operator=() creates a copy of 'pos'. We want the new born Position
96 /// object do not depend on any external data so we detach state pointer from
99 void Position::operator=(const Position& pos) {
101 memcpy(this, &pos, sizeof(Position));
110 /// Position::from_fen() initializes the position object with the given FEN
111 /// string. This function is not very robust - make sure that input FENs are
112 /// correct (this is assumed to be the responsibility of the GUI).
114 void Position::from_fen(const string& fenStr, bool isChess960, Thread* th) {
116 A FEN string defines a particular position using only the ASCII character set.
118 A FEN string contains six fields separated by a space. The fields are:
120 1) Piece placement (from white's perspective). Each rank is described, starting
121 with rank 8 and ending with rank 1; within each rank, the contents of each
122 square are described from file A through file H. Following the Standard
123 Algebraic Notation (SAN), each piece is identified by a single letter taken
124 from the standard English names. White pieces are designated using upper-case
125 letters ("PNBRQK") while Black take lowercase ("pnbrqk"). Blank squares are
126 noted using digits 1 through 8 (the number of blank squares), and "/"
129 2) Active color. "w" means white moves next, "b" means black.
131 3) Castling availability. If neither side can castle, this is "-". Otherwise,
132 this has one or more letters: "K" (White can castle kingside), "Q" (White
133 can castle queenside), "k" (Black can castle kingside), and/or "q" (Black
134 can castle queenside).
136 4) En passant target square (in algebraic notation). If there's no en passant
137 target square, this is "-". If a pawn has just made a 2-square move, this
138 is the position "behind" the pawn. This is recorded regardless of whether
139 there is a pawn in position to make an en passant capture.
141 5) Halfmove clock. This is the number of halfmoves since the last pawn advance
142 or capture. This is used to determine if a draw can be claimed under the
145 6) Fullmove number. The number of the full move. It starts at 1, and is
146 incremented after Black's move.
149 char col, row, token;
152 std::istringstream fen(fenStr);
155 fen >> std::noskipws;
157 // 1. Piece placement
158 while ((fen >> token) && !isspace(token))
161 sq += Square(token - '0'); // Advance the given number of files
163 else if (token == '/')
164 sq = make_square(FILE_A, rank_of(sq) - Rank(2));
166 else if ((p = PieceToChar.find(token)) != string::npos)
168 put_piece(Piece(p), sq);
175 sideToMove = (token == 'w' ? WHITE : BLACK);
178 // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
179 // Shredder-FEN that uses the letters of the columns on which the rooks began
180 // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
181 // if an inner rook is associated with the castling right, the castling tag is
182 // replaced by the file letter of the involved rook, as for the Shredder-FEN.
183 while ((fen >> token) && !isspace(token))
186 Color c = islower(token) ? BLACK : WHITE;
188 token = char(toupper(token));
191 for (rsq = relative_square(c, SQ_H1); type_of(piece_on(rsq)) != ROOK; rsq--) {}
193 else if (token == 'Q')
194 for (rsq = relative_square(c, SQ_A1); type_of(piece_on(rsq)) != ROOK; rsq++) {}
196 else if (token >= 'A' && token <= 'H')
197 rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
202 set_castle_right(c, rsq);
205 // 4. En passant square. Ignore if no pawn capture is possible
206 if ( ((fen >> col) && (col >= 'a' && col <= 'h'))
207 && ((fen >> row) && (row == '3' || row == '6')))
209 st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
211 if (!(attackers_to(st->epSquare) & pieces(PAWN, sideToMove)))
212 st->epSquare = SQ_NONE;
215 // 5-6. Halfmove clock and fullmove number
216 fen >> std::skipws >> st->rule50 >> startPosPly;
218 // Convert from fullmove starting from 1 to ply starting from 0,
219 // handle also common incorrect FEN with fullmove = 0.
220 startPosPly = std::max(2 * (startPosPly - 1), 0) + int(sideToMove == BLACK);
222 st->key = compute_key();
223 st->pawnKey = compute_pawn_key();
224 st->materialKey = compute_material_key();
225 st->psqScore = compute_psq_score();
226 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
227 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
228 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(~sideToMove);
229 chess960 = isChess960;
236 /// Position::set_castle_right() is an helper function used to set castling
237 /// rights given the corresponding color and the rook starting square.
239 void Position::set_castle_right(Color c, Square rfrom) {
241 Square kfrom = king_square(c);
242 CastlingSide cs = kfrom < rfrom ? KING_SIDE : QUEEN_SIDE;
243 CastleRight cr = make_castle_right(c, cs);
245 st->castleRights |= cr;
246 castleRightsMask[kfrom] |= cr;
247 castleRightsMask[rfrom] |= cr;
248 castleRookSquare[c][cs] = rfrom;
250 Square kto = relative_square(c, cs == KING_SIDE ? SQ_G1 : SQ_C1);
251 Square rto = relative_square(c, cs == KING_SIDE ? SQ_F1 : SQ_D1);
253 for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); s++)
254 if (s != kfrom && s != rfrom)
255 castlePath[c][cs] |= s;
257 for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); s++)
258 if (s != kfrom && s != rfrom)
259 castlePath[c][cs] |= s;
263 /// Position::to_fen() returns a FEN representation of the position. In case
264 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
266 const string Position::to_fen() const {
268 std::ostringstream fen;
272 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
276 for (File file = FILE_A; file <= FILE_H; file++)
278 sq = make_square(file, rank);
280 if (square_empty(sq))
289 fen << PieceToChar[piece_on(sq)];
300 fen << (sideToMove == WHITE ? " w " : " b ");
302 if (can_castle(WHITE_OO))
303 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE, KING_SIDE))))) : 'K');
305 if (can_castle(WHITE_OOO))
306 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE, QUEEN_SIDE))))) : 'Q');
308 if (can_castle(BLACK_OO))
309 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK, KING_SIDE))) : 'k');
311 if (can_castle(BLACK_OOO))
312 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK, QUEEN_SIDE))) : 'q');
314 if (st->castleRights == CASTLES_NONE)
317 fen << (ep_square() == SQ_NONE ? " - " : " " + square_to_string(ep_square()) + " ")
318 << st->rule50 << " " << 1 + (startPosPly - int(sideToMove == BLACK)) / 2;
324 /// Position::print() prints an ASCII representation of the position to
325 /// the standard output. If a move is given then also the san is printed.
327 void Position::print(Move move) const {
329 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
334 cout << "\nMove is: " << (sideToMove == BLACK ? ".." : "") << move_to_san(p, move);
337 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
339 cout << dottedLine << '|';
340 for (File file = FILE_A; file <= FILE_H; file++)
342 Square sq = make_square(file, rank);
343 Piece piece = piece_on(sq);
344 char c = (color_of(piece) == BLACK ? '=' : ' ');
346 if (piece == NO_PIECE && !opposite_colors(sq, SQ_A1))
347 piece++; // Index the dot
349 cout << c << PieceToChar[piece] << c << '|';
352 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
356 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
357 /// king) pieces for the given color. Or, when template parameter FindPinned is
358 /// false, the function return the pieces of the given color candidate for a
359 /// discovery check against the enemy king.
360 template<bool FindPinned>
361 Bitboard Position::hidden_checkers() const {
363 // Pinned pieces protect our king, dicovery checks attack the enemy king
364 Bitboard b, result = 0;
365 Bitboard pinners = pieces(FindPinned ? ~sideToMove : sideToMove);
366 Square ksq = king_square(FindPinned ? sideToMove : ~sideToMove);
368 // Pinners are sliders, that give check when candidate pinned is removed
369 pinners &= (pieces(ROOK, QUEEN) & PseudoAttacks[ROOK][ksq])
370 | (pieces(BISHOP, QUEEN) & PseudoAttacks[BISHOP][ksq]);
374 b = squares_between(ksq, pop_1st_bit(&pinners)) & pieces();
376 if (b && single_bit(b) && (b & pieces(sideToMove)))
382 // Explicit template instantiations
383 template Bitboard Position::hidden_checkers<true>() const;
384 template Bitboard Position::hidden_checkers<false>() const;
387 /// Position::attackers_to() computes a bitboard of all pieces which attack a
388 /// given square. Slider attacks use occ bitboard as occupancy.
390 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
392 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
393 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
394 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
395 | (attacks_bb<ROOK>(s, occ) & pieces(ROOK, QUEEN))
396 | (attacks_bb<BISHOP>(s, occ) & pieces(BISHOP, QUEEN))
397 | (attacks_from<KING>(s) & pieces(KING));
401 /// Position::attacks_from() computes a bitboard of all attacks of a given piece
402 /// put in a given square. Slider attacks use occ bitboard as occupancy.
404 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
410 case BISHOP: return attacks_bb<BISHOP>(s, occ);
411 case ROOK : return attacks_bb<ROOK>(s, occ);
412 case QUEEN : return attacks_bb<BISHOP>(s, occ) | attacks_bb<ROOK>(s, occ);
413 default : return StepAttacksBB[p][s];
418 /// Position::move_attacks_square() tests whether a move from the current
419 /// position attacks a given square.
421 bool Position::move_attacks_square(Move m, Square s) const {
427 Square from = from_sq(m);
428 Square to = to_sq(m);
429 Piece piece = piece_moved(m);
431 assert(!square_empty(from));
433 // Update occupancy as if the piece is moving
434 occ = pieces() ^ from ^ to;
436 // The piece moved in 'to' attacks the square 's' ?
437 if (attacks_from(piece, to, occ) & s)
440 // Scan for possible X-ray attackers behind the moved piece
441 xray = (attacks_bb<ROOK>(s, occ) & pieces(ROOK, QUEEN, color_of(piece)))
442 |(attacks_bb<BISHOP>(s, occ) & pieces(BISHOP, QUEEN, color_of(piece)));
444 // Verify attackers are triggered by our move and not already existing
445 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
449 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
451 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
454 assert(pinned == pinned_pieces());
456 Color us = sideToMove;
457 Square from = from_sq(m);
459 assert(color_of(piece_moved(m)) == us);
460 assert(piece_on(king_square(us)) == make_piece(us, KING));
462 // En passant captures are a tricky special case. Because they are rather
463 // uncommon, we do it simply by testing whether the king is attacked after
468 Square to = to_sq(m);
469 Square capsq = to + pawn_push(them);
470 Square ksq = king_square(us);
471 Bitboard b = (pieces() ^ from ^ capsq) | to;
473 assert(to == ep_square());
474 assert(piece_moved(m) == make_piece(us, PAWN));
475 assert(piece_on(capsq) == make_piece(them, PAWN));
476 assert(piece_on(to) == NO_PIECE);
478 return !(attacks_bb<ROOK>(ksq, b) & pieces(ROOK, QUEEN, them))
479 && !(attacks_bb<BISHOP>(ksq, b) & pieces(BISHOP, QUEEN, them));
482 // If the moving piece is a king, check whether the destination
483 // square is attacked by the opponent. Castling moves are checked
484 // for legality during move generation.
485 if (type_of(piece_on(from)) == KING)
486 return is_castle(m) || !(attackers_to(to_sq(m)) & pieces(~us));
488 // A non-king move is legal if and only if it is not pinned or it
489 // is moving along the ray towards or away from the king.
492 || squares_aligned(from, to_sq(m), king_square(us));
496 /// Position::move_is_legal() takes a random move and tests whether the move
497 /// is legal. This version is not very fast and should be used only in non
498 /// time-critical paths.
500 bool Position::move_is_legal(const Move m) const {
502 for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
510 /// Position::is_pseudo_legal() takes a random move and tests whether the move
511 /// is pseudo legal. It is used to validate moves from TT that can be corrupted
512 /// due to SMP concurrent access or hash position key aliasing.
514 bool Position::is_pseudo_legal(const Move m) const {
516 Color us = sideToMove;
517 Color them = ~sideToMove;
518 Square from = from_sq(m);
519 Square to = to_sq(m);
520 Piece pc = piece_moved(m);
522 // Use a slower but simpler function for uncommon cases
524 return move_is_legal(m);
526 // Is not a promotion, so promotion piece must be empty
527 if (promotion_type(m) - 2 != NO_PIECE_TYPE)
530 // If the from square is not occupied by a piece belonging to the side to
531 // move, the move is obviously not legal.
532 if (pc == NO_PIECE || color_of(pc) != us)
535 // The destination square cannot be occupied by a friendly piece
536 if (color_of(piece_on(to)) == us)
539 // Handle the special case of a pawn move
540 if (type_of(pc) == PAWN)
542 // Move direction must be compatible with pawn color
543 int direction = to - from;
544 if ((us == WHITE) != (direction > 0))
547 // We have already handled promotion moves, so destination
548 // cannot be on the 8/1th rank.
549 if (rank_of(to) == RANK_8 || rank_of(to) == RANK_1)
552 // Proceed according to the square delta between the origin and
553 // destination squares.
560 // Capture. The destination square must be occupied by an enemy
561 // piece (en passant captures was handled earlier).
562 if (color_of(piece_on(to)) != them)
565 // From and to files must be one file apart, avoids a7h5
566 if (abs(file_of(from) - file_of(to)) != 1)
572 // Pawn push. The destination square must be empty.
573 if (!square_empty(to))
578 // Double white pawn push. The destination square must be on the fourth
579 // rank, and both the destination square and the square between the
580 // source and destination squares must be empty.
581 if ( rank_of(to) != RANK_4
583 || !square_empty(from + DELTA_N))
588 // Double black pawn push. The destination square must be on the fifth
589 // rank, and both the destination square and the square between the
590 // source and destination squares must be empty.
591 if ( rank_of(to) != RANK_5
593 || !square_empty(from + DELTA_S))
601 else if (!(attacks_from(pc, from) & to))
604 // Evasions generator already takes care to avoid some kind of illegal moves
605 // and pl_move_is_legal() relies on this. So we have to take care that the
606 // same kind of moves are filtered out here.
609 if (type_of(pc) != KING)
611 Bitboard b = checkers();
612 Square checksq = pop_1st_bit(&b);
614 if (b) // double check ? In this case a king move is required
617 // Our move must be a blocking evasion or a capture of the checking piece
618 if (!((squares_between(checksq, king_square(us)) | checkers()) & to))
621 // In case of king moves under check we have to remove king so to catch
622 // as invalid moves like b1a1 when opposite queen is on c1.
623 else if (attackers_to(to, pieces() ^ from) & pieces(~us))
631 /// Position::move_gives_check() tests whether a pseudo-legal move gives a check
633 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
636 assert(ci.dcCandidates == discovered_check_candidates());
637 assert(color_of(piece_moved(m)) == sideToMove);
639 Square from = from_sq(m);
640 Square to = to_sq(m);
641 PieceType pt = type_of(piece_on(from));
644 if (ci.checkSq[pt] & to)
648 if (ci.dcCandidates && (ci.dcCandidates & from))
650 // For pawn and king moves we need to verify also direction
651 if ( (pt != PAWN && pt != KING)
652 || !squares_aligned(from, to, king_square(~sideToMove)))
656 // Can we skip the ugly special cases ?
660 Color us = sideToMove;
661 Square ksq = king_square(~us);
663 // Promotion with check ?
665 return attacks_from(Piece(promotion_type(m)), to, pieces() ^ from) & ksq;
667 // En passant capture with check ? We have already handled the case
668 // of direct checks and ordinary discovered check, the only case we
669 // need to handle is the unusual case of a discovered check through
670 // the captured pawn.
673 Square capsq = make_square(file_of(to), rank_of(from));
674 Bitboard b = (pieces() ^ from ^ capsq) | to;
676 return (attacks_bb< ROOK>(ksq, b) & pieces( ROOK, QUEEN, us))
677 | (attacks_bb<BISHOP>(ksq, b) & pieces(BISHOP, QUEEN, us));
680 // Castling with check ?
684 Square rfrom = to; // 'King captures the rook' notation
685 Square kto = relative_square(us, rfrom > kfrom ? SQ_G1 : SQ_C1);
686 Square rto = relative_square(us, rfrom > kfrom ? SQ_F1 : SQ_D1);
687 Bitboard b = (pieces() ^ kfrom ^ rfrom) | rto | kto;
689 return attacks_bb<ROOK>(rto, b) & ksq;
696 /// Position::do_move() makes a move, and saves all information necessary
697 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
698 /// moves should be filtered out before this function is called.
700 void Position::do_move(Move m, StateInfo& newSt) {
703 do_move(m, newSt, ci, move_gives_check(m, ci));
706 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
709 assert(&newSt != st);
714 // Copy some fields of old state to our new StateInfo object except the ones
715 // which are recalculated from scratch anyway, then switch our state pointer
716 // to point to the new, ready to be updated, state.
717 struct ReducedStateInfo {
718 Key pawnKey, materialKey;
720 int castleRights, rule50, pliesFromNull;
725 memcpy(&newSt, st, sizeof(ReducedStateInfo));
730 // Update side to move
733 // Increment the 50 moves rule draw counter. Resetting it to zero in the
734 // case of a capture or a pawn move is taken care of later.
741 do_castle_move<true>(m);
745 Color us = sideToMove;
747 Square from = from_sq(m);
748 Square to = to_sq(m);
749 Piece piece = piece_on(from);
750 PieceType pt = type_of(piece);
751 PieceType capture = is_enpassant(m) ? PAWN : type_of(piece_on(to));
753 assert(color_of(piece) == us);
754 assert(color_of(piece_on(to)) != us);
755 assert(capture != KING);
761 // If the captured piece is a pawn, update pawn hash key, otherwise
762 // update non-pawn material.
767 capsq += pawn_push(them);
770 assert(to == st->epSquare);
771 assert(relative_rank(us, to) == RANK_6);
772 assert(piece_on(to) == NO_PIECE);
773 assert(piece_on(capsq) == make_piece(them, PAWN));
775 board[capsq] = NO_PIECE;
778 st->pawnKey ^= zobrist[them][PAWN][capsq];
781 st->npMaterial[them] -= PieceValueMidgame[capture];
783 // Remove the captured piece
784 byTypeBB[ALL_PIECES] ^= capsq;
785 byTypeBB[capture] ^= capsq;
786 byColorBB[them] ^= capsq;
788 // Update piece list, move the last piece at index[capsq] position and
791 // WARNING: This is a not revresible operation. When we will reinsert the
792 // captured piece in undo_move() we will put it at the end of the list and
793 // not in its original place, it means index[] and pieceList[] are not
794 // guaranteed to be invariant to a do_move() + undo_move() sequence.
795 Square lastSquare = pieceList[them][capture][--pieceCount[them][capture]];
796 index[lastSquare] = index[capsq];
797 pieceList[them][capture][index[lastSquare]] = lastSquare;
798 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
801 k ^= zobrist[them][capture][capsq];
802 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
804 // Update incremental scores
805 st->psqScore -= pieceSquareTable[make_piece(them, capture)][capsq];
807 // Reset rule 50 counter
812 k ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
814 // Reset en passant square
815 if (st->epSquare != SQ_NONE)
817 k ^= zobEp[file_of(st->epSquare)];
818 st->epSquare = SQ_NONE;
821 // Update castle rights if needed
822 if (st->castleRights && (castleRightsMask[from] | castleRightsMask[to]))
824 int cr = castleRightsMask[from] | castleRightsMask[to];
825 k ^= zobCastle[st->castleRights & cr];
826 st->castleRights &= ~cr;
829 // Prefetch TT access as soon as we know key is updated
830 prefetch((char*)TT.first_entry(k));
833 Bitboard from_to_bb = SquareBB[from] ^ SquareBB[to];
834 byTypeBB[ALL_PIECES] ^= from_to_bb;
835 byTypeBB[pt] ^= from_to_bb;
836 byColorBB[us] ^= from_to_bb;
838 board[to] = board[from];
839 board[from] = NO_PIECE;
841 // Update piece lists, index[from] is not updated and becomes stale. This
842 // works as long as index[] is accessed just by known occupied squares.
843 index[to] = index[from];
844 pieceList[us][pt][index[to]] = to;
846 // If the moving piece is a pawn do some special extra work
849 // Set en-passant square, only if moved pawn can be captured
850 if ( (int(to) ^ int(from)) == 16
851 && (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(PAWN, them)))
853 st->epSquare = Square((from + to) / 2);
854 k ^= zobEp[file_of(st->epSquare)];
859 PieceType promotion = promotion_type(m);
861 assert(relative_rank(us, to) == RANK_8);
862 assert(promotion >= KNIGHT && promotion <= QUEEN);
864 // Replace the pawn with the promoted piece
865 byTypeBB[PAWN] ^= to;
866 byTypeBB[promotion] |= to;
867 board[to] = make_piece(us, promotion);
869 // Update piece lists, move the last pawn at index[to] position
870 // and shrink the list. Add a new promotion piece to the list.
871 Square lastSquare = pieceList[us][PAWN][--pieceCount[us][PAWN]];
872 index[lastSquare] = index[to];
873 pieceList[us][PAWN][index[lastSquare]] = lastSquare;
874 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
875 index[to] = pieceCount[us][promotion];
876 pieceList[us][promotion][index[to]] = to;
879 k ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
880 st->pawnKey ^= zobrist[us][PAWN][to];
881 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]++]
882 ^ zobrist[us][PAWN][pieceCount[us][PAWN]];
884 // Update incremental score
885 st->psqScore += pieceSquareTable[make_piece(us, promotion)][to]
886 - pieceSquareTable[make_piece(us, PAWN)][to];
889 st->npMaterial[us] += PieceValueMidgame[promotion];
892 // Update pawn hash key
893 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
895 // Reset rule 50 draw counter
899 // Prefetch pawn and material hash tables
900 prefetch((char*)thisThread->pawnTable.entries[st->pawnKey]);
901 prefetch((char*)thisThread->materialTable.entries[st->materialKey]);
903 // Update incremental scores
904 st->psqScore += psq_delta(piece, from, to);
907 st->capturedType = capture;
909 // Update the key with the final value
912 // Update checkers bitboard, piece must be already moved
918 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
922 if (ci.checkSq[pt] & to)
923 st->checkersBB |= to;
926 if (ci.dcCandidates && (ci.dcCandidates & from))
929 st->checkersBB |= attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us);
932 st->checkersBB |= attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us);
938 sideToMove = ~sideToMove;
939 st->psqScore += (sideToMove == WHITE ? Tempo : -Tempo);
945 /// Position::undo_move() unmakes a move. When it returns, the position should
946 /// be restored to exactly the same state as before the move was made.
948 void Position::undo_move(Move m) {
952 sideToMove = ~sideToMove;
956 do_castle_move<false>(m);
960 Color us = sideToMove;
962 Square from = from_sq(m);
963 Square to = to_sq(m);
964 Piece piece = piece_on(to);
965 PieceType pt = type_of(piece);
966 PieceType capture = st->capturedType;
968 assert(square_empty(from));
969 assert(color_of(piece) == us);
970 assert(capture != KING);
974 PieceType promotion = promotion_type(m);
976 assert(promotion == pt);
977 assert(relative_rank(us, to) == RANK_8);
978 assert(promotion >= KNIGHT && promotion <= QUEEN);
980 // Replace the promoted piece with the pawn
981 byTypeBB[promotion] ^= to;
982 byTypeBB[PAWN] |= to;
983 board[to] = make_piece(us, PAWN);
985 // Update piece lists, move the last promoted piece at index[to] position
986 // and shrink the list. Add a new pawn to the list.
987 Square lastSquare = pieceList[us][promotion][--pieceCount[us][promotion]];
988 index[lastSquare] = index[to];
989 pieceList[us][promotion][index[lastSquare]] = lastSquare;
990 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
991 index[to] = pieceCount[us][PAWN]++;
992 pieceList[us][PAWN][index[to]] = to;
997 // Put the piece back at the source square
998 Bitboard from_to_bb = SquareBB[from] ^ SquareBB[to];
999 byTypeBB[ALL_PIECES] ^= from_to_bb;
1000 byTypeBB[pt] ^= from_to_bb;
1001 byColorBB[us] ^= from_to_bb;
1003 board[from] = board[to];
1004 board[to] = NO_PIECE;
1006 // Update piece lists, index[to] is not updated and becomes stale. This
1007 // works as long as index[] is accessed just by known occupied squares.
1008 index[from] = index[to];
1009 pieceList[us][pt][index[from]] = from;
1015 if (is_enpassant(m))
1017 capsq -= pawn_push(us);
1020 assert(to == st->previous->epSquare);
1021 assert(relative_rank(us, to) == RANK_6);
1022 assert(piece_on(capsq) == NO_PIECE);
1025 // Restore the captured piece
1026 byTypeBB[ALL_PIECES] |= capsq;
1027 byTypeBB[capture] |= capsq;
1028 byColorBB[them] |= capsq;
1030 board[capsq] = make_piece(them, capture);
1032 // Update piece list, add a new captured piece in capsq square
1033 index[capsq] = pieceCount[them][capture]++;
1034 pieceList[them][capture][index[capsq]] = capsq;
1037 // Finally point our state pointer back to the previous state
1040 assert(pos_is_ok());
1044 /// Position::do_castle_move() is a private method used to do/undo a castling
1045 /// move. Note that castling moves are encoded as "king captures friendly rook"
1046 /// moves, for instance white short castling in a non-Chess960 game is encoded
1049 void Position::do_castle_move(Move m) {
1052 assert(is_castle(m));
1054 Square kto, kfrom, rfrom, rto, kAfter, rAfter;
1056 Color us = sideToMove;
1057 Square kBefore = from_sq(m);
1058 Square rBefore = to_sq(m);
1060 // Find after-castle squares for king and rook
1061 if (rBefore > kBefore) // O-O
1063 kAfter = relative_square(us, SQ_G1);
1064 rAfter = relative_square(us, SQ_F1);
1068 kAfter = relative_square(us, SQ_C1);
1069 rAfter = relative_square(us, SQ_D1);
1072 kfrom = Do ? kBefore : kAfter;
1073 rfrom = Do ? rBefore : rAfter;
1075 kto = Do ? kAfter : kBefore;
1076 rto = Do ? rAfter : rBefore;
1078 assert(piece_on(kfrom) == make_piece(us, KING));
1079 assert(piece_on(rfrom) == make_piece(us, ROOK));
1081 // Move the pieces, with some care; in chess960 could be kto == rfrom
1082 Bitboard k_from_to_bb = SquareBB[kfrom] ^ SquareBB[kto];
1083 Bitboard r_from_to_bb = SquareBB[rfrom] ^ SquareBB[rto];
1084 byTypeBB[KING] ^= k_from_to_bb;
1085 byTypeBB[ROOK] ^= r_from_to_bb;
1086 byTypeBB[ALL_PIECES] ^= k_from_to_bb ^ r_from_to_bb;
1087 byColorBB[us] ^= k_from_to_bb ^ r_from_to_bb;
1090 Piece king = make_piece(us, KING);
1091 Piece rook = make_piece(us, ROOK);
1092 board[kfrom] = board[rfrom] = NO_PIECE;
1096 // Update piece lists
1097 pieceList[us][KING][index[kfrom]] = kto;
1098 pieceList[us][ROOK][index[rfrom]] = rto;
1099 int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1100 index[kto] = index[kfrom];
1105 // Reset capture field
1106 st->capturedType = NO_PIECE_TYPE;
1108 // Update incremental scores
1109 st->psqScore += psq_delta(king, kfrom, kto);
1110 st->psqScore += psq_delta(rook, rfrom, rto);
1113 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1114 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1116 // Clear en passant square
1117 if (st->epSquare != SQ_NONE)
1119 st->key ^= zobEp[file_of(st->epSquare)];
1120 st->epSquare = SQ_NONE;
1123 // Update castling rights
1124 st->key ^= zobCastle[st->castleRights & castleRightsMask[kfrom]];
1125 st->castleRights &= ~castleRightsMask[kfrom];
1127 // Update checkers BB
1128 st->checkersBB = attackers_to(king_square(~us)) & pieces(us);
1131 sideToMove = ~sideToMove;
1132 st->psqScore += (sideToMove == WHITE ? Tempo : -Tempo);
1135 // Undo: point our state pointer back to the previous state
1138 assert(pos_is_ok());
1142 /// Position::do_null_move() is used to do/undo a "null move": It flips the side
1143 /// to move and updates the hash key without executing any move on the board.
1145 void Position::do_null_move(StateInfo& backupSt) {
1147 assert(!in_check());
1149 // Back up the information necessary to undo the null move to the supplied
1150 // StateInfo object. Note that differently from normal case here backupSt
1151 // is actually used as a backup storage not as the new state. This reduces
1152 // the number of fields to be copied.
1153 StateInfo* src = Do ? st : &backupSt;
1154 StateInfo* dst = Do ? &backupSt : st;
1156 dst->key = src->key;
1157 dst->epSquare = src->epSquare;
1158 dst->psqScore = src->psqScore;
1159 dst->rule50 = src->rule50;
1160 dst->pliesFromNull = src->pliesFromNull;
1162 sideToMove = ~sideToMove;
1166 if (st->epSquare != SQ_NONE)
1167 st->key ^= zobEp[file_of(st->epSquare)];
1169 st->key ^= zobSideToMove;
1170 prefetch((char*)TT.first_entry(st->key));
1172 st->epSquare = SQ_NONE;
1174 st->pliesFromNull = 0;
1175 st->psqScore += (sideToMove == WHITE ? Tempo : -Tempo);
1178 assert(pos_is_ok());
1181 // Explicit template instantiations
1182 template void Position::do_null_move<false>(StateInfo& backupSt);
1183 template void Position::do_null_move<true>(StateInfo& backupSt);
1186 /// Position::see() is a static exchange evaluator: It tries to estimate the
1187 /// material gain or loss resulting from a move. There are three versions of
1188 /// this function: One which takes a destination square as input, one takes a
1189 /// move, and one which takes a 'from' and a 'to' square. The function does
1190 /// not yet understand promotions captures.
1192 int Position::see_sign(Move m) const {
1196 // Early return if SEE cannot be negative because captured piece value
1197 // is not less then capturing one. Note that king moves always return
1198 // here because king midgame value is set to 0.
1199 if (PieceValueMidgame[piece_on(to_sq(m))] >= PieceValueMidgame[piece_moved(m)])
1205 int Position::see(Move m) const {
1208 Bitboard occ, attackers, stmAttackers, b;
1209 int swapList[32], slIndex = 1;
1210 PieceType capturedType, pt;
1215 // As castle moves are implemented as capturing the rook, they have
1216 // SEE == RookValueMidgame most of the times (unless the rook is under
1223 capturedType = type_of(piece_on(to));
1226 // Handle en passant moves
1227 if (is_enpassant(m))
1229 Square capQq = to - pawn_push(sideToMove);
1231 assert(!capturedType);
1232 assert(type_of(piece_on(capQq)) == PAWN);
1234 // Remove the captured pawn
1236 capturedType = PAWN;
1239 // Find all attackers to the destination square, with the moving piece
1240 // removed, but possibly an X-ray attacker added behind it.
1242 attackers = attackers_to(to, occ);
1244 // If the opponent has no attackers we are finished
1245 stm = ~color_of(piece_on(from));
1246 stmAttackers = attackers & pieces(stm);
1248 return PieceValueMidgame[capturedType];
1250 // The destination square is defended, which makes things rather more
1251 // difficult to compute. We proceed by building up a "swap list" containing
1252 // the material gain or loss at each stop in a sequence of captures to the
1253 // destination square, where the sides alternately capture, and always
1254 // capture with the least valuable piece. After each capture, we look for
1255 // new X-ray attacks from behind the capturing piece.
1256 swapList[0] = PieceValueMidgame[capturedType];
1257 capturedType = type_of(piece_on(from));
1260 // Locate the least valuable attacker for the side to move. The loop
1261 // below looks like it is potentially infinite, but it isn't. We know
1262 // that the side to move still has at least one attacker left.
1263 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1266 // Remove the attacker we just found from the 'occupied' bitboard,
1267 // and scan for new X-ray attacks behind the attacker.
1268 b = stmAttackers & pieces(pt);
1269 occ ^= (b & (~b + 1));
1270 attackers |= (attacks_bb<ROOK>(to, occ) & pieces(ROOK, QUEEN))
1271 | (attacks_bb<BISHOP>(to, occ) & pieces(BISHOP, QUEEN));
1273 attackers &= occ; // Cut out pieces we've already done
1275 // Add the new entry to the swap list
1276 assert(slIndex < 32);
1277 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1280 // Remember the value of the capturing piece, and change the side to
1281 // move before beginning the next iteration.
1284 stmAttackers = attackers & pieces(stm);
1286 // Stop before processing a king capture
1287 if (capturedType == KING && stmAttackers)
1289 assert(slIndex < 32);
1290 swapList[slIndex++] = QueenValueMidgame*10;
1293 } while (stmAttackers);
1295 // Having built the swap list, we negamax through it to find the best
1296 // achievable score from the point of view of the side to move.
1298 swapList[slIndex-1] = std::min(-swapList[slIndex], swapList[slIndex-1]);
1304 /// Position::clear() erases the position object to a pristine state, with an
1305 /// empty board, white to move, and no castling rights.
1307 void Position::clear() {
1309 memset(this, 0, sizeof(Position));
1310 startState.epSquare = SQ_NONE;
1313 for (int i = 0; i < 8; i++)
1314 for (int j = 0; j < 16; j++)
1315 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1317 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1318 board[sq] = NO_PIECE;
1322 /// Position::put_piece() puts a piece on the given square of the board,
1323 /// updating the board array, pieces list, bitboards, and piece counts.
1325 void Position::put_piece(Piece p, Square s) {
1327 Color c = color_of(p);
1328 PieceType pt = type_of(p);
1331 index[s] = pieceCount[c][pt]++;
1332 pieceList[c][pt][index[s]] = s;
1334 byTypeBB[ALL_PIECES] |= s;
1340 /// Position::compute_key() computes the hash key of the position. The hash
1341 /// key is usually updated incrementally as moves are made and unmade, the
1342 /// compute_key() function is only used when a new position is set up, and
1343 /// to verify the correctness of the hash key when running in debug mode.
1345 Key Position::compute_key() const {
1347 Key result = zobCastle[st->castleRights];
1349 for (Square s = SQ_A1; s <= SQ_H8; s++)
1350 if (!square_empty(s))
1351 result ^= zobrist[color_of(piece_on(s))][type_of(piece_on(s))][s];
1353 if (ep_square() != SQ_NONE)
1354 result ^= zobEp[file_of(ep_square())];
1356 if (sideToMove == BLACK)
1357 result ^= zobSideToMove;
1363 /// Position::compute_pawn_key() computes the hash key of the position. The
1364 /// hash key is usually updated incrementally as moves are made and unmade,
1365 /// the compute_pawn_key() function is only used when a new position is set
1366 /// up, and to verify the correctness of the pawn hash key when running in
1369 Key Position::compute_pawn_key() const {
1374 for (Color c = WHITE; c <= BLACK; c++)
1376 b = pieces(PAWN, c);
1378 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1384 /// Position::compute_material_key() computes the hash key of the position.
1385 /// The hash key is usually updated incrementally as moves are made and unmade,
1386 /// the compute_material_key() function is only used when a new position is set
1387 /// up, and to verify the correctness of the material hash key when running in
1390 Key Position::compute_material_key() const {
1394 for (Color c = WHITE; c <= BLACK; c++)
1395 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1396 for (int i = 0; i < piece_count(c, pt); i++)
1397 result ^= zobrist[c][pt][i];
1403 /// Position::compute_psq_score() computes the incremental scores for the middle
1404 /// game and the endgame. These functions are used to initialize the incremental
1405 /// scores when a new position is set up, and to verify that the scores are correctly
1406 /// updated by do_move and undo_move when the program is running in debug mode.
1407 Score Position::compute_psq_score() const {
1410 Score result = SCORE_ZERO;
1412 for (Color c = WHITE; c <= BLACK; c++)
1413 for (PieceType pt = PAWN; pt <= KING; pt++)
1417 result += pieceSquareTable[make_piece(c, pt)][pop_1st_bit(&b)];
1420 result += (sideToMove == WHITE ? Tempo / 2 : -Tempo / 2);
1425 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1426 /// game material value for the given side. Material values are updated
1427 /// incrementally during the search, this function is only used while
1428 /// initializing a new Position object.
1430 Value Position::compute_non_pawn_material(Color c) const {
1432 Value result = VALUE_ZERO;
1434 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1435 result += piece_count(c, pt) * PieceValueMidgame[pt];
1441 /// Position::is_draw() tests whether the position is drawn by material,
1442 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1443 /// must be done by the search.
1444 template<bool SkipRepetition>
1445 bool Position::is_draw() const {
1447 // Draw by material?
1449 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1452 // Draw by the 50 moves rule?
1453 if (st->rule50 > 99 && (!in_check() || MoveList<MV_LEGAL>(*this).size()))
1456 // Draw by repetition?
1457 if (!SkipRepetition)
1459 int i = 4, e = std::min(st->rule50, st->pliesFromNull);
1463 StateInfo* stp = st->previous->previous;
1466 stp = stp->previous->previous;
1468 if (stp->key == st->key)
1480 // Explicit template instantiations
1481 template bool Position::is_draw<false>() const;
1482 template bool Position::is_draw<true>() const;
1485 /// Position::init() is a static member function which initializes at startup
1486 /// the various arrays used to compute hash keys and the piece square tables.
1487 /// The latter is a two-step operation: First, the white halves of the tables
1488 /// are copied from PSQT[] tables. Second, the black halves of the tables are
1489 /// initialized by flipping and changing the sign of the white scores.
1491 void Position::init() {
1495 for (Color c = WHITE; c <= BLACK; c++)
1496 for (PieceType pt = PAWN; pt <= KING; pt++)
1497 for (Square s = SQ_A1; s <= SQ_H8; s++)
1498 zobrist[c][pt][s] = rk.rand<Key>();
1500 for (File f = FILE_A; f <= FILE_H; f++)
1501 zobEp[f] = rk.rand<Key>();
1503 for (int cr = CASTLES_NONE; cr <= ALL_CASTLES; cr++)
1508 Key k = zobCastle[1ULL << pop_1st_bit(&b)];
1509 zobCastle[cr] ^= k ? k : rk.rand<Key>();
1513 zobSideToMove = rk.rand<Key>();
1514 zobExclusion = rk.rand<Key>();
1516 for (Piece p = W_PAWN; p <= W_KING; p++)
1518 Score ps = make_score(PieceValueMidgame[p], PieceValueEndgame[p]);
1520 for (Square s = SQ_A1; s <= SQ_H8; s++)
1522 pieceSquareTable[p][s] = ps + PSQT[p][s];
1523 pieceSquareTable[p+8][~s] = -pieceSquareTable[p][s];
1529 /// Position::flip() flips position with the white and black sides reversed. This
1530 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1532 void Position::flip() {
1534 const Position pos(*this);
1538 sideToMove = ~pos.side_to_move();
1539 thisThread = pos.this_thread();
1540 nodes = pos.nodes_searched();
1541 chess960 = pos.is_chess960();
1542 startPosPly = pos.startpos_ply_counter();
1544 for (Square s = SQ_A1; s <= SQ_H8; s++)
1545 if (!pos.square_empty(s))
1546 put_piece(Piece(pos.piece_on(s) ^ 8), ~s);
1548 if (pos.can_castle(WHITE_OO))
1549 set_castle_right(BLACK, ~pos.castle_rook_square(WHITE, KING_SIDE));
1550 if (pos.can_castle(WHITE_OOO))
1551 set_castle_right(BLACK, ~pos.castle_rook_square(WHITE, QUEEN_SIDE));
1552 if (pos.can_castle(BLACK_OO))
1553 set_castle_right(WHITE, ~pos.castle_rook_square(BLACK, KING_SIDE));
1554 if (pos.can_castle(BLACK_OOO))
1555 set_castle_right(WHITE, ~pos.castle_rook_square(BLACK, QUEEN_SIDE));
1557 if (pos.st->epSquare != SQ_NONE)
1558 st->epSquare = ~pos.st->epSquare;
1560 st->key = compute_key();
1561 st->pawnKey = compute_pawn_key();
1562 st->materialKey = compute_material_key();
1563 st->psqScore = compute_psq_score();
1564 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(~sideToMove);
1565 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1566 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1568 assert(pos_is_ok());
1572 /// Position::pos_is_ok() performs some consitency checks for the position object.
1573 /// This is meant to be helpful when debugging.
1575 bool Position::pos_is_ok(int* failedStep) const {
1577 // What features of the position should be verified?
1578 const bool debugAll = false;
1580 const bool debugBitboards = debugAll || false;
1581 const bool debugKingCount = debugAll || false;
1582 const bool debugKingCapture = debugAll || false;
1583 const bool debugCheckerCount = debugAll || false;
1584 const bool debugKey = debugAll || false;
1585 const bool debugMaterialKey = debugAll || false;
1586 const bool debugPawnKey = debugAll || false;
1587 const bool debugIncrementalEval = debugAll || false;
1588 const bool debugNonPawnMaterial = debugAll || false;
1589 const bool debugPieceCounts = debugAll || false;
1590 const bool debugPieceList = debugAll || false;
1591 const bool debugCastleSquares = debugAll || false;
1593 if (failedStep) *failedStep = 1;
1596 if (sideToMove != WHITE && sideToMove != BLACK)
1599 // Are the king squares in the position correct?
1600 if (failedStep) (*failedStep)++;
1601 if (piece_on(king_square(WHITE)) != W_KING)
1604 if (failedStep) (*failedStep)++;
1605 if (piece_on(king_square(BLACK)) != B_KING)
1608 // Do both sides have exactly one king?
1609 if (failedStep) (*failedStep)++;
1612 int kingCount[2] = {0, 0};
1613 for (Square s = SQ_A1; s <= SQ_H8; s++)
1614 if (type_of(piece_on(s)) == KING)
1615 kingCount[color_of(piece_on(s))]++;
1617 if (kingCount[0] != 1 || kingCount[1] != 1)
1621 // Can the side to move capture the opponent's king?
1622 if (failedStep) (*failedStep)++;
1623 if (debugKingCapture)
1625 Color us = sideToMove;
1627 Square ksq = king_square(them);
1628 if (attackers_to(ksq) & pieces(us))
1632 // Is there more than 2 checkers?
1633 if (failedStep) (*failedStep)++;
1634 if (debugCheckerCount && popcount<Full>(st->checkersBB) > 2)
1638 if (failedStep) (*failedStep)++;
1641 // The intersection of the white and black pieces must be empty
1642 if (pieces(WHITE) & pieces(BLACK))
1645 // The union of the white and black pieces must be equal to all
1647 if ((pieces(WHITE) | pieces(BLACK)) != pieces())
1650 // Separate piece type bitboards must have empty intersections
1651 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1652 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1653 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1657 // En passant square OK?
1658 if (failedStep) (*failedStep)++;
1659 if (ep_square() != SQ_NONE)
1661 // The en passant square must be on rank 6, from the point of view of the
1663 if (relative_rank(sideToMove, ep_square()) != RANK_6)
1668 if (failedStep) (*failedStep)++;
1669 if (debugKey && st->key != compute_key())
1672 // Pawn hash key OK?
1673 if (failedStep) (*failedStep)++;
1674 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1677 // Material hash key OK?
1678 if (failedStep) (*failedStep)++;
1679 if (debugMaterialKey && st->materialKey != compute_material_key())
1682 // Incremental eval OK?
1683 if (failedStep) (*failedStep)++;
1684 if (debugIncrementalEval && st->psqScore != compute_psq_score())
1687 // Non-pawn material OK?
1688 if (failedStep) (*failedStep)++;
1689 if (debugNonPawnMaterial)
1691 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1694 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1699 if (failedStep) (*failedStep)++;
1700 if (debugPieceCounts)
1701 for (Color c = WHITE; c <= BLACK; c++)
1702 for (PieceType pt = PAWN; pt <= KING; pt++)
1703 if (pieceCount[c][pt] != popcount<Full>(pieces(pt, c)))
1706 if (failedStep) (*failedStep)++;
1708 for (Color c = WHITE; c <= BLACK; c++)
1709 for (PieceType pt = PAWN; pt <= KING; pt++)
1710 for (int i = 0; i < pieceCount[c][pt]; i++)
1712 if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1715 if (index[piece_list(c, pt)[i]] != i)
1719 if (failedStep) (*failedStep)++;
1720 if (debugCastleSquares)
1721 for (Color c = WHITE; c <= BLACK; c++)
1722 for (CastlingSide s = KING_SIDE; s <= QUEEN_SIDE; s = CastlingSide(s + 1))
1724 if (!can_castle(make_castle_right(c, s)))
1727 if ( piece_on(castleRookSquare[c][s]) != make_piece(c, ROOK)
1728 || castleRightsMask[castleRookSquare[c][s]] != make_castle_right(c, s))
1732 if (failedStep) *failedStep = 0;