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/>.
39 Key Position::zobrist[2][8][64];
40 Key Position::zobEp[64];
41 Key Position::zobCastle[16];
42 Key Position::zobSideToMove;
43 Key Position::zobExclusion;
45 Score Position::pieceSquareTable[16][64];
47 // Material values arrays, indexed by Piece
48 const Value PieceValueMidgame[17] = {
50 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
51 RookValueMidgame, QueenValueMidgame,
52 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
53 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
54 RookValueMidgame, QueenValueMidgame
57 const Value PieceValueEndgame[17] = {
59 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
60 RookValueEndgame, QueenValueEndgame,
61 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
62 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
63 RookValueEndgame, QueenValueEndgame
69 // Bonus for having the side to move (modified by Joona Kiiski)
70 const Score TempoValue = make_score(48, 22);
72 // To convert a Piece to and from a FEN char
73 const string PieceToChar(" PNBRQK pnbrqk .");
79 CheckInfo::CheckInfo(const Position& pos) {
81 Color them = flip(pos.side_to_move());
82 Square ksq = pos.king_square(them);
84 pinned = pos.pinned_pieces();
85 dcCandidates = pos.discovered_check_candidates();
87 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
88 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
89 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
90 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
91 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
96 /// Position c'tors. Here we always create a copy of the original position
97 /// or the FEN string, we want the new born Position object do not depend
98 /// on any external data so we detach state pointer from the source one.
100 void Position::copy(const Position& pos, int th) {
102 memcpy(this, &pos, sizeof(Position));
111 Position::Position(const string& fen, bool isChess960, int th) {
113 from_fen(fen, isChess960);
118 /// Position::from_fen() initializes the position object with the given FEN
119 /// string. This function is not very robust - make sure that input FENs are
120 /// correct (this is assumed to be the responsibility of the GUI).
122 void Position::from_fen(const string& fenStr, bool isChess960) {
124 A FEN string defines a particular position using only the ASCII character set.
126 A FEN string contains six fields separated by a space. The fields are:
128 1) Piece placement (from white's perspective). Each rank is described, starting
129 with rank 8 and ending with rank 1; within each rank, the contents of each
130 square are described from file A through file H. Following the Standard
131 Algebraic Notation (SAN), each piece is identified by a single letter taken
132 from the standard English names. White pieces are designated using upper-case
133 letters ("PNBRQK") while Black take lowercase ("pnbrqk"). Blank squares are
134 noted using digits 1 through 8 (the number of blank squares), and "/"
137 2) Active color. "w" means white moves next, "b" means black.
139 3) Castling availability. If neither side can castle, this is "-". Otherwise,
140 this has one or more letters: "K" (White can castle kingside), "Q" (White
141 can castle queenside), "k" (Black can castle kingside), and/or "q" (Black
142 can castle queenside).
144 4) En passant target square (in algebraic notation). If there's no en passant
145 target square, this is "-". If a pawn has just made a 2-square move, this
146 is the position "behind" the pawn. This is recorded regardless of whether
147 there is a pawn in position to make an en passant capture.
149 5) Halfmove clock. This is the number of halfmoves since the last pawn advance
150 or capture. This is used to determine if a draw can be claimed under the
153 6) Fullmove number. The number of the full move. It starts at 1, and is
154 incremented after Black's move.
157 char col, row, token;
160 std::istringstream fen(fenStr);
163 fen >> std::noskipws;
165 // 1. Piece placement
166 while ((fen >> token) && !isspace(token))
169 sq -= Square(16); // Jump back of 2 rows
171 else if (isdigit(token))
172 sq += Square(token - '0'); // Skip the given number of files
174 else if ((p = PieceToChar.find(token)) != string::npos)
176 put_piece(Piece(p), sq);
183 sideToMove = (token == 'w' ? WHITE : BLACK);
186 // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
187 // Shredder-FEN that uses the letters of the columns on which the rooks began
188 // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
189 // if an inner rook is associated with the castling right, the castling tag is
190 // replaced by the file letter of the involved rook, as for the Shredder-FEN.
191 while ((fen >> token) && !isspace(token))
194 Color c = islower(token) ? BLACK : WHITE;
195 Piece rook = make_piece(c, ROOK);
197 token = char(toupper(token));
200 for (rsq = relative_square(c, SQ_H1); piece_on(rsq) != rook; rsq--) {}
202 else if (token == 'Q')
203 for (rsq = relative_square(c, SQ_A1); piece_on(rsq) != rook; rsq++) {}
205 else if (token >= 'A' && token <= 'H')
206 rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
211 set_castle_right(king_square(c), rsq);
214 // 4. En passant square. Ignore if no pawn capture is possible
215 if ( ((fen >> col) && (col >= 'a' && col <= 'h'))
216 && ((fen >> row) && (row == '3' || row == '6')))
218 st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
220 if (!(attackers_to(st->epSquare) & pieces(PAWN, sideToMove)))
221 st->epSquare = SQ_NONE;
224 // 5-6. Halfmove clock and fullmove number
225 fen >> std::skipws >> st->rule50 >> startPosPly;
227 // Convert from fullmove starting from 1 to ply starting from 0,
228 // handle also common incorrect FEN with fullmove = 0.
229 startPosPly = std::max(2 * (startPosPly - 1), 0) + int(sideToMove == BLACK);
231 st->key = compute_key();
232 st->pawnKey = compute_pawn_key();
233 st->materialKey = compute_material_key();
234 st->value = compute_value();
235 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
236 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
237 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(flip(sideToMove));
238 chess960 = isChess960;
244 /// Position::set_castle_right() is an helper function used to set castling
245 /// rights given the corresponding king and rook starting squares.
247 void Position::set_castle_right(Square ksq, Square rsq) {
249 int f = (rsq < ksq ? WHITE_OOO : WHITE_OO) << color_of(piece_on(ksq));
251 st->castleRights |= f;
252 castleRightsMask[ksq] ^= f;
253 castleRightsMask[rsq] ^= f;
254 castleRookSquare[f] = rsq;
258 /// Position::to_fen() returns a FEN representation of the position. In case
259 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
261 const string Position::to_fen() const {
263 std::ostringstream fen;
267 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
271 for (File file = FILE_A; file <= FILE_H; file++)
273 sq = make_square(file, rank);
275 if (square_is_empty(sq))
284 fen << PieceToChar[piece_on(sq)];
295 fen << (sideToMove == WHITE ? " w " : " b ");
297 if (can_castle(WHITE_OO))
298 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OO))))) : 'K');
300 if (can_castle(WHITE_OOO))
301 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OOO))))) : 'Q');
303 if (can_castle(BLACK_OO))
304 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OO))) : 'k');
306 if (can_castle(BLACK_OOO))
307 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OOO))) : 'q');
309 if (st->castleRights == CASTLES_NONE)
312 fen << (ep_square() == SQ_NONE ? " - " : " " + square_to_string(ep_square()) + " ")
313 << st->rule50 << " " << 1 + (startPosPly - int(sideToMove == BLACK)) / 2;
319 /// Position::print() prints an ASCII representation of the position to
320 /// the standard output. If a move is given then also the san is printed.
322 void Position::print(Move move) const {
324 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
328 Position p(*this, thread());
329 cout << "\nMove is: " << (sideToMove == BLACK ? ".." : "") << move_to_san(p, move);
332 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
334 cout << dottedLine << '|';
335 for (File file = FILE_A; file <= FILE_H; file++)
337 Square sq = make_square(file, rank);
338 Piece piece = piece_on(sq);
339 char c = (color_of(piece) == BLACK ? '=' : ' ');
341 if (piece == NO_PIECE && !opposite_colors(sq, SQ_A1))
342 piece++; // Index the dot
344 cout << c << PieceToChar[piece] << c << '|';
347 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
351 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
352 /// king) pieces for the given color. Or, when template parameter FindPinned is
353 /// false, the function return the pieces of the given color candidate for a
354 /// discovery check against the enemy king.
355 template<bool FindPinned>
356 Bitboard Position::hidden_checkers() const {
358 // Pinned pieces protect our king, dicovery checks attack the enemy king
359 Bitboard b, result = 0;
360 Bitboard pinners = pieces(FindPinned ? flip(sideToMove) : sideToMove);
361 Square ksq = king_square(FindPinned ? sideToMove : flip(sideToMove));
363 // Pinners are sliders, that give check when candidate pinned is removed
364 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq])
365 | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
369 b = squares_between(ksq, pop_1st_bit(&pinners)) & occupied_squares();
371 // Only one bit set and is an our piece?
372 if (b && !(b & (b - 1)) && (b & pieces(sideToMove)))
378 // Explicit template instantiations
379 template Bitboard Position::hidden_checkers<true>() const;
380 template Bitboard Position::hidden_checkers<false>() const;
383 /// Position::attackers_to() computes a bitboard of all pieces which attack a
384 /// given square. Slider attacks use occ bitboard as occupancy.
386 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
388 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
389 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
390 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
391 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
392 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
393 | (attacks_from<KING>(s) & pieces(KING));
397 /// Position::attacks_from() computes a bitboard of all attacks of a given piece
398 /// put in a given square. Slider attacks use occ bitboard as occupancy.
400 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
402 assert(square_is_ok(s));
406 case BISHOP: return bishop_attacks_bb(s, occ);
407 case ROOK : return rook_attacks_bb(s, occ);
408 case QUEEN : return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
409 default : return StepAttacksBB[p][s];
414 /// Position::move_attacks_square() tests whether a move from the current
415 /// position attacks a given square.
417 bool Position::move_attacks_square(Move m, Square s) const {
420 assert(square_is_ok(s));
423 Square from = from_sq(m);
424 Square to = to_sq(m);
425 Piece piece = piece_on(from);
427 assert(!square_is_empty(from));
429 // Update occupancy as if the piece is moving
430 occ = occupied_squares();
431 do_move_bb(&occ, make_move_bb(from, to));
433 // The piece moved in 'to' attacks the square 's' ?
434 if (bit_is_set(attacks_from(piece, to, occ), s))
437 // Scan for possible X-ray attackers behind the moved piece
438 xray = (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN, color_of(piece)))
439 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN, color_of(piece)));
441 // Verify attackers are triggered by our move and not already existing
442 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
446 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
448 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
451 assert(pinned == pinned_pieces());
453 Color us = side_to_move();
454 Square from = from_sq(m);
456 assert(color_of(piece_on(from)) == us);
457 assert(piece_on(king_square(us)) == make_piece(us, KING));
459 // En passant captures are a tricky special case. Because they are rather
460 // uncommon, we do it simply by testing whether the king is attacked after
464 Color them = flip(us);
465 Square to = to_sq(m);
466 Square capsq = to + pawn_push(them);
467 Square ksq = king_square(us);
468 Bitboard b = occupied_squares();
470 assert(to == ep_square());
471 assert(piece_on(from) == make_piece(us, PAWN));
472 assert(piece_on(capsq) == make_piece(them, PAWN));
473 assert(piece_on(to) == NO_PIECE);
476 clear_bit(&b, capsq);
479 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
480 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
483 // If the moving piece is a king, check whether the destination
484 // square is attacked by the opponent. Castling moves are checked
485 // for legality during move generation.
486 if (type_of(piece_on(from)) == KING)
487 return is_castle(m) || !(attackers_to(to_sq(m)) & pieces(flip(us)));
489 // A non-king move is legal if and only if it is not pinned or it
490 // is moving along the ray towards or away from the king.
492 || !bit_is_set(pinned, from)
493 || squares_aligned(from, to_sq(m), king_square(us));
497 /// Position::move_is_legal() takes a random move and tests whether the move
498 /// is legal. This version is not very fast and should be used only in non
499 /// time-critical paths.
501 bool Position::move_is_legal(const Move m) const {
503 for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
511 /// Position::is_pseudo_legal() takes a random move and tests whether the move
512 /// is pseudo legal. It is used to validate moves from TT that can be corrupted
513 /// due to SMP concurrent access or hash position key aliasing.
515 bool Position::is_pseudo_legal(const Move m) const {
517 Color us = sideToMove;
518 Color them = flip(sideToMove);
519 Square from = from_sq(m);
520 Square to = to_sq(m);
521 Piece pc = piece_on(from);
523 // Use a slower but simpler function for uncommon cases
525 return move_is_legal(m);
527 // Is not a promotion, so promotion piece must be empty
528 if (promotion_piece_type(m) - 2 != NO_PIECE_TYPE)
531 // If the from square is not occupied by a piece belonging to the side to
532 // move, the move is obviously not legal.
533 if (pc == NO_PIECE || color_of(pc) != us)
536 // The destination square cannot be occupied by a friendly piece
537 if (color_of(piece_on(to)) == us)
540 // Handle the special case of a pawn move
541 if (type_of(pc) == PAWN)
543 // Move direction must be compatible with pawn color
544 int direction = to - from;
545 if ((us == WHITE) != (direction > 0))
548 // We have already handled promotion moves, so destination
549 // cannot be on the 8/1th rank.
550 if (rank_of(to) == RANK_8 || rank_of(to) == RANK_1)
553 // Proceed according to the square delta between the origin and
554 // destination squares.
561 // Capture. The destination square must be occupied by an enemy
562 // piece (en passant captures was handled earlier).
563 if (color_of(piece_on(to)) != them)
566 // From and to files must be one file apart, avoids a7h5
567 if (abs(file_of(from) - file_of(to)) != 1)
573 // Pawn push. The destination square must be empty.
574 if (!square_is_empty(to))
579 // Double white pawn push. The destination square must be on the fourth
580 // rank, and both the destination square and the square between the
581 // source and destination squares must be empty.
582 if ( rank_of(to) != RANK_4
583 || !square_is_empty(to)
584 || !square_is_empty(from + DELTA_N))
589 // Double black pawn push. The destination square must be on the fifth
590 // rank, and both the destination square and the square between the
591 // source and destination squares must be empty.
592 if ( rank_of(to) != RANK_5
593 || !square_is_empty(to)
594 || !square_is_empty(from + DELTA_S))
602 else if (!bit_is_set(attacks_from(pc, from), to))
605 // Evasions generator already takes care to avoid some kind of illegal moves
606 // and pl_move_is_legal() relies on this. So we have to take care that the
607 // same kind of moves are filtered out here.
610 // In case of king moves under check we have to remove king so to catch
611 // as invalid moves like b1a1 when opposite queen is on c1.
612 if (type_of(piece_on(from)) == KING)
614 Bitboard b = occupied_squares();
616 if (attackers_to(to_sq(m), b) & pieces(flip(us)))
621 Bitboard target = checkers();
622 Square checksq = pop_1st_bit(&target);
624 if (target) // double check ? In this case a king move is required
627 // Our move must be a blocking evasion or a capture of the checking piece
628 target = squares_between(checksq, king_square(us)) | checkers();
629 if (!bit_is_set(target, to_sq(m)))
638 /// Position::move_gives_check() tests whether a pseudo-legal move gives a check
640 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
643 assert(ci.dcCandidates == discovered_check_candidates());
644 assert(color_of(piece_on(from_sq(m))) == side_to_move());
646 Square from = from_sq(m);
647 Square to = to_sq(m);
648 PieceType pt = type_of(piece_on(from));
651 if (bit_is_set(ci.checkSq[pt], to))
655 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
657 // For pawn and king moves we need to verify also direction
658 if ( (pt != PAWN && pt != KING)
659 || !squares_aligned(from, to, king_square(flip(side_to_move()))))
663 // Can we skip the ugly special cases ?
667 Color us = side_to_move();
668 Bitboard b = occupied_squares();
669 Square ksq = king_square(flip(us));
671 // Promotion with check ?
675 return bit_is_set(attacks_from(Piece(promotion_piece_type(m)), to, b), ksq);
678 // En passant capture with check ? We have already handled the case
679 // of direct checks and ordinary discovered check, the only case we
680 // need to handle is the unusual case of a discovered check through
681 // the captured pawn.
684 Square capsq = make_square(file_of(to), rank_of(from));
686 clear_bit(&b, capsq);
688 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
689 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
692 // Castling with check ?
695 Square kfrom, kto, rfrom, rto;
701 kto = relative_square(us, SQ_G1);
702 rto = relative_square(us, SQ_F1);
704 kto = relative_square(us, SQ_C1);
705 rto = relative_square(us, SQ_D1);
707 clear_bit(&b, kfrom);
708 clear_bit(&b, rfrom);
711 return bit_is_set(rook_attacks_bb(rto, b), ksq);
718 /// Position::do_move() makes a move, and saves all information necessary
719 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
720 /// moves should be filtered out before this function is called.
722 void Position::do_move(Move m, StateInfo& newSt) {
725 do_move(m, newSt, ci, move_gives_check(m, ci));
728 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
731 assert(&newSt != st);
736 // Copy some fields of old state to our new StateInfo object except the ones
737 // which are recalculated from scratch anyway, then switch our state pointer
738 // to point to the new, ready to be updated, state.
739 struct ReducedStateInfo {
740 Key pawnKey, materialKey;
742 int castleRights, rule50, pliesFromNull;
747 memcpy(&newSt, st, sizeof(ReducedStateInfo));
752 // Update side to move
755 // Increment the 50 moves rule draw counter. Resetting it to zero in the
756 // case of non-reversible moves is taken care of later.
763 do_castle_move<true>(m);
767 Color us = side_to_move();
768 Color them = flip(us);
769 Square from = from_sq(m);
770 Square to = to_sq(m);
771 Piece piece = piece_on(from);
772 PieceType pt = type_of(piece);
773 PieceType capture = is_enpassant(m) ? PAWN : type_of(piece_on(to));
775 assert(color_of(piece) == us);
776 assert(color_of(piece_on(to)) != us);
777 assert(capture != KING);
783 // If the captured piece is a pawn, update pawn hash key, otherwise
784 // update non-pawn material.
789 capsq += pawn_push(them);
792 assert(to == st->epSquare);
793 assert(relative_rank(us, to) == RANK_6);
794 assert(piece_on(to) == NO_PIECE);
795 assert(piece_on(capsq) == make_piece(them, PAWN));
797 board[capsq] = NO_PIECE;
800 st->pawnKey ^= zobrist[them][PAWN][capsq];
803 st->npMaterial[them] -= PieceValueMidgame[capture];
805 // Remove the captured piece
806 clear_bit(&byColorBB[them], capsq);
807 clear_bit(&byTypeBB[capture], capsq);
808 clear_bit(&occupied, capsq);
810 // Update piece list, move the last piece at index[capsq] position and
813 // WARNING: This is a not revresible operation. When we will reinsert the
814 // captured piece in undo_move() we will put it at the end of the list and
815 // not in its original place, it means index[] and pieceList[] are not
816 // guaranteed to be invariant to a do_move() + undo_move() sequence.
817 Square lastSquare = pieceList[them][capture][--pieceCount[them][capture]];
818 index[lastSquare] = index[capsq];
819 pieceList[them][capture][index[lastSquare]] = lastSquare;
820 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
823 k ^= zobrist[them][capture][capsq];
824 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
826 // Update incremental scores
827 st->value -= pst(make_piece(them, capture), capsq);
829 // Reset rule 50 counter
834 k ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
836 // Reset en passant square
837 if (st->epSquare != SQ_NONE)
839 k ^= zobEp[st->epSquare];
840 st->epSquare = SQ_NONE;
843 // Update castle rights if needed
844 if ( st->castleRights != CASTLES_NONE
845 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
847 k ^= zobCastle[st->castleRights];
848 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
849 k ^= zobCastle[st->castleRights];
852 // Prefetch TT access as soon as we know key is updated
853 prefetch((char*)TT.first_entry(k));
856 Bitboard move_bb = make_move_bb(from, to);
857 do_move_bb(&byColorBB[us], move_bb);
858 do_move_bb(&byTypeBB[pt], move_bb);
859 do_move_bb(&occupied, move_bb);
861 board[to] = board[from];
862 board[from] = NO_PIECE;
864 // Update piece lists, index[from] is not updated and becomes stale. This
865 // works as long as index[] is accessed just by known occupied squares.
866 index[to] = index[from];
867 pieceList[us][pt][index[to]] = to;
869 // If the moving piece is a pawn do some special extra work
872 // Set en-passant square, only if moved pawn can be captured
873 if ( (to ^ from) == 16
874 && (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(PAWN, them)))
876 st->epSquare = Square((from + to) / 2);
877 k ^= zobEp[st->epSquare];
882 PieceType promotion = promotion_piece_type(m);
884 assert(relative_rank(us, to) == RANK_8);
885 assert(promotion >= KNIGHT && promotion <= QUEEN);
887 // Replace the pawn with the promoted piece
888 clear_bit(&byTypeBB[PAWN], to);
889 set_bit(&byTypeBB[promotion], to);
890 board[to] = make_piece(us, promotion);
892 // Update piece lists, move the last pawn at index[to] position
893 // and shrink the list. Add a new promotion piece to the list.
894 Square lastSquare = pieceList[us][PAWN][--pieceCount[us][PAWN]];
895 index[lastSquare] = index[to];
896 pieceList[us][PAWN][index[lastSquare]] = lastSquare;
897 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
898 index[to] = pieceCount[us][promotion];
899 pieceList[us][promotion][index[to]] = to;
902 k ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
903 st->pawnKey ^= zobrist[us][PAWN][to];
904 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]++]
905 ^ zobrist[us][PAWN][pieceCount[us][PAWN]];
907 // Update incremental score
908 st->value += pst(make_piece(us, promotion), to)
909 - pst(make_piece(us, PAWN), to);
912 st->npMaterial[us] += PieceValueMidgame[promotion];
915 // Update pawn hash key
916 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
918 // Reset rule 50 draw counter
922 // Prefetch pawn and material hash tables
923 Threads[threadID].pawnTable.prefetch(st->pawnKey);
924 Threads[threadID].materialTable.prefetch(st->materialKey);
926 // Update incremental scores
927 st->value += pst_delta(piece, from, to);
930 st->capturedType = capture;
932 // Update the key with the final value
935 // Update checkers bitboard, piece must be already moved
941 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
945 if (bit_is_set(ci.checkSq[pt], to))
946 st->checkersBB = SetMaskBB[to];
949 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
952 st->checkersBB |= attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us);
955 st->checkersBB |= attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us);
961 sideToMove = flip(sideToMove);
962 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
968 /// Position::undo_move() unmakes a move. When it returns, the position should
969 /// be restored to exactly the same state as before the move was made.
971 void Position::undo_move(Move m) {
975 sideToMove = flip(sideToMove);
979 do_castle_move<false>(m);
983 Color us = side_to_move();
984 Color them = flip(us);
985 Square from = from_sq(m);
986 Square to = to_sq(m);
987 Piece piece = piece_on(to);
988 PieceType pt = type_of(piece);
989 PieceType capture = st->capturedType;
991 assert(square_is_empty(from));
992 assert(color_of(piece) == us);
993 assert(capture != KING);
997 PieceType promotion = promotion_piece_type(m);
999 assert(promotion == pt);
1000 assert(relative_rank(us, to) == RANK_8);
1001 assert(promotion >= KNIGHT && promotion <= QUEEN);
1003 // Replace the promoted piece with the pawn
1004 clear_bit(&byTypeBB[promotion], to);
1005 set_bit(&byTypeBB[PAWN], to);
1006 board[to] = make_piece(us, PAWN);
1008 // Update piece lists, move the last promoted piece at index[to] position
1009 // and shrink the list. Add a new pawn to the list.
1010 Square lastSquare = pieceList[us][promotion][--pieceCount[us][promotion]];
1011 index[lastSquare] = index[to];
1012 pieceList[us][promotion][index[lastSquare]] = lastSquare;
1013 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1014 index[to] = pieceCount[us][PAWN]++;
1015 pieceList[us][PAWN][index[to]] = to;
1020 // Put the piece back at the source square
1021 Bitboard move_bb = make_move_bb(to, from);
1022 do_move_bb(&byColorBB[us], move_bb);
1023 do_move_bb(&byTypeBB[pt], move_bb);
1024 do_move_bb(&occupied, move_bb);
1026 board[from] = board[to];
1027 board[to] = NO_PIECE;
1029 // Update piece lists, index[to] is not updated and becomes stale. This
1030 // works as long as index[] is accessed just by known occupied squares.
1031 index[from] = index[to];
1032 pieceList[us][pt][index[from]] = from;
1038 if (is_enpassant(m))
1040 capsq -= pawn_push(us);
1043 assert(to == st->previous->epSquare);
1044 assert(relative_rank(us, to) == RANK_6);
1045 assert(piece_on(capsq) == NO_PIECE);
1048 // Restore the captured piece
1049 set_bit(&byColorBB[them], capsq);
1050 set_bit(&byTypeBB[capture], capsq);
1051 set_bit(&occupied, capsq);
1053 board[capsq] = make_piece(them, capture);
1055 // Update piece list, add a new captured piece in capsq square
1056 index[capsq] = pieceCount[them][capture]++;
1057 pieceList[them][capture][index[capsq]] = capsq;
1060 // Finally point our state pointer back to the previous state
1063 assert(pos_is_ok());
1067 /// Position::do_castle_move() is a private method used to do/undo a castling
1068 /// move. Note that castling moves are encoded as "king captures friendly rook"
1069 /// moves, for instance white short castling in a non-Chess960 game is encoded
1072 void Position::do_castle_move(Move m) {
1075 assert(is_castle(m));
1077 Square kto, kfrom, rfrom, rto, kAfter, rAfter;
1079 Color us = side_to_move();
1080 Square kBefore = from_sq(m);
1081 Square rBefore = to_sq(m);
1083 // Find after-castle squares for king and rook
1084 if (rBefore > kBefore) // O-O
1086 kAfter = relative_square(us, SQ_G1);
1087 rAfter = relative_square(us, SQ_F1);
1091 kAfter = relative_square(us, SQ_C1);
1092 rAfter = relative_square(us, SQ_D1);
1095 kfrom = Do ? kBefore : kAfter;
1096 rfrom = Do ? rBefore : rAfter;
1098 kto = Do ? kAfter : kBefore;
1099 rto = Do ? rAfter : rBefore;
1101 assert(piece_on(kfrom) == make_piece(us, KING));
1102 assert(piece_on(rfrom) == make_piece(us, ROOK));
1104 // Remove pieces from source squares
1105 clear_bit(&byColorBB[us], kfrom);
1106 clear_bit(&byTypeBB[KING], kfrom);
1107 clear_bit(&occupied, kfrom);
1108 clear_bit(&byColorBB[us], rfrom);
1109 clear_bit(&byTypeBB[ROOK], rfrom);
1110 clear_bit(&occupied, rfrom);
1112 // Put pieces on destination squares
1113 set_bit(&byColorBB[us], kto);
1114 set_bit(&byTypeBB[KING], kto);
1115 set_bit(&occupied, kto);
1116 set_bit(&byColorBB[us], rto);
1117 set_bit(&byTypeBB[ROOK], rto);
1118 set_bit(&occupied, rto);
1121 Piece king = make_piece(us, KING);
1122 Piece rook = make_piece(us, ROOK);
1123 board[kfrom] = board[rfrom] = NO_PIECE;
1127 // Update piece lists
1128 pieceList[us][KING][index[kfrom]] = kto;
1129 pieceList[us][ROOK][index[rfrom]] = rto;
1130 int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1131 index[kto] = index[kfrom];
1136 // Reset capture field
1137 st->capturedType = NO_PIECE_TYPE;
1139 // Update incremental scores
1140 st->value += pst_delta(king, kfrom, kto);
1141 st->value += pst_delta(rook, rfrom, rto);
1144 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1145 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1147 // Clear en passant square
1148 if (st->epSquare != SQ_NONE)
1150 st->key ^= zobEp[st->epSquare];
1151 st->epSquare = SQ_NONE;
1154 // Update castling rights
1155 st->key ^= zobCastle[st->castleRights];
1156 st->castleRights &= castleRightsMask[kfrom];
1157 st->key ^= zobCastle[st->castleRights];
1159 // Reset rule 50 counter
1162 // Update checkers BB
1163 st->checkersBB = attackers_to(king_square(flip(us))) & pieces(us);
1166 sideToMove = flip(sideToMove);
1167 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1170 // Undo: point our state pointer back to the previous state
1173 assert(pos_is_ok());
1177 /// Position::do_null_move() is used to do/undo a "null move": It flips the side
1178 /// to move and updates the hash key without executing any move on the board.
1180 void Position::do_null_move(StateInfo& backupSt) {
1182 assert(!in_check());
1184 // Back up the information necessary to undo the null move to the supplied
1185 // StateInfo object. Note that differently from normal case here backupSt
1186 // is actually used as a backup storage not as the new state. This reduces
1187 // the number of fields to be copied.
1188 StateInfo* src = Do ? st : &backupSt;
1189 StateInfo* dst = Do ? &backupSt : st;
1191 dst->key = src->key;
1192 dst->epSquare = src->epSquare;
1193 dst->value = src->value;
1194 dst->rule50 = src->rule50;
1195 dst->pliesFromNull = src->pliesFromNull;
1197 sideToMove = flip(sideToMove);
1201 if (st->epSquare != SQ_NONE)
1202 st->key ^= zobEp[st->epSquare];
1204 st->key ^= zobSideToMove;
1205 prefetch((char*)TT.first_entry(st->key));
1207 st->epSquare = SQ_NONE;
1209 st->pliesFromNull = 0;
1210 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1213 assert(pos_is_ok());
1216 // Explicit template instantiations
1217 template void Position::do_null_move<false>(StateInfo& backupSt);
1218 template void Position::do_null_move<true>(StateInfo& backupSt);
1221 /// Position::see() is a static exchange evaluator: It tries to estimate the
1222 /// material gain or loss resulting from a move. There are three versions of
1223 /// this function: One which takes a destination square as input, one takes a
1224 /// move, and one which takes a 'from' and a 'to' square. The function does
1225 /// not yet understand promotions captures.
1227 int Position::see_sign(Move m) const {
1231 Square from = from_sq(m);
1232 Square to = to_sq(m);
1234 // Early return if SEE cannot be negative because captured piece value
1235 // is not less then capturing one. Note that king moves always return
1236 // here because king midgame value is set to 0.
1237 if (PieceValueMidgame[piece_on(to)] >= PieceValueMidgame[piece_on(from)])
1243 int Position::see(Move m) const {
1246 Bitboard occ, attackers, stmAttackers, b;
1247 int swapList[32], slIndex = 1;
1248 PieceType capturedType, pt;
1253 // As castle moves are implemented as capturing the rook, they have
1254 // SEE == RookValueMidgame most of the times (unless the rook is under
1261 capturedType = type_of(piece_on(to));
1262 occ = occupied_squares();
1264 // Handle en passant moves
1265 if (is_enpassant(m))
1267 Square capQq = to - pawn_push(side_to_move());
1269 assert(capturedType == NO_PIECE_TYPE);
1270 assert(type_of(piece_on(capQq)) == PAWN);
1272 // Remove the captured pawn
1273 clear_bit(&occ, capQq);
1274 capturedType = PAWN;
1277 // Find all attackers to the destination square, with the moving piece
1278 // removed, but possibly an X-ray attacker added behind it.
1279 clear_bit(&occ, from);
1280 attackers = attackers_to(to, occ);
1282 // If the opponent has no attackers we are finished
1283 stm = flip(color_of(piece_on(from)));
1284 stmAttackers = attackers & pieces(stm);
1286 return PieceValueMidgame[capturedType];
1288 // The destination square is defended, which makes things rather more
1289 // difficult to compute. We proceed by building up a "swap list" containing
1290 // the material gain or loss at each stop in a sequence of captures to the
1291 // destination square, where the sides alternately capture, and always
1292 // capture with the least valuable piece. After each capture, we look for
1293 // new X-ray attacks from behind the capturing piece.
1294 swapList[0] = PieceValueMidgame[capturedType];
1295 capturedType = type_of(piece_on(from));
1298 // Locate the least valuable attacker for the side to move. The loop
1299 // below looks like it is potentially infinite, but it isn't. We know
1300 // that the side to move still has at least one attacker left.
1301 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1304 // Remove the attacker we just found from the 'occupied' bitboard,
1305 // and scan for new X-ray attacks behind the attacker.
1306 b = stmAttackers & pieces(pt);
1307 occ ^= (b & (~b + 1));
1308 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1309 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1311 attackers &= occ; // Cut out pieces we've already done
1313 // Add the new entry to the swap list
1314 assert(slIndex < 32);
1315 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1318 // Remember the value of the capturing piece, and change the side to
1319 // move before beginning the next iteration.
1322 stmAttackers = attackers & pieces(stm);
1324 // Stop before processing a king capture
1325 if (capturedType == KING && stmAttackers)
1327 assert(slIndex < 32);
1328 swapList[slIndex++] = QueenValueMidgame*10;
1331 } while (stmAttackers);
1333 // Having built the swap list, we negamax through it to find the best
1334 // achievable score from the point of view of the side to move.
1336 swapList[slIndex-1] = std::min(-swapList[slIndex], swapList[slIndex-1]);
1342 /// Position::clear() erases the position object to a pristine state, with an
1343 /// empty board, white to move, and no castling rights.
1345 void Position::clear() {
1348 memset(st, 0, sizeof(StateInfo));
1349 st->epSquare = SQ_NONE;
1351 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1352 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1353 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1354 memset(index, 0, sizeof(int) * 64);
1356 for (int i = 0; i < 8; i++)
1357 for (int j = 0; j < 16; j++)
1358 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1360 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1362 board[sq] = NO_PIECE;
1363 castleRightsMask[sq] = ALL_CASTLES;
1371 /// Position::put_piece() puts a piece on the given square of the board,
1372 /// updating the board array, pieces list, bitboards, and piece counts.
1374 void Position::put_piece(Piece p, Square s) {
1376 Color c = color_of(p);
1377 PieceType pt = type_of(p);
1380 index[s] = pieceCount[c][pt]++;
1381 pieceList[c][pt][index[s]] = s;
1383 set_bit(&byTypeBB[pt], s);
1384 set_bit(&byColorBB[c], s);
1385 set_bit(&occupied, s);
1389 /// Position::compute_key() computes the hash key of the position. The hash
1390 /// key is usually updated incrementally as moves are made and unmade, the
1391 /// compute_key() function is only used when a new position is set up, and
1392 /// to verify the correctness of the hash key when running in debug mode.
1394 Key Position::compute_key() const {
1396 Key result = zobCastle[st->castleRights];
1398 for (Square s = SQ_A1; s <= SQ_H8; s++)
1399 if (!square_is_empty(s))
1400 result ^= zobrist[color_of(piece_on(s))][type_of(piece_on(s))][s];
1402 if (ep_square() != SQ_NONE)
1403 result ^= zobEp[ep_square()];
1405 if (side_to_move() == BLACK)
1406 result ^= zobSideToMove;
1412 /// Position::compute_pawn_key() computes the hash key of the position. The
1413 /// hash key is usually updated incrementally as moves are made and unmade,
1414 /// the compute_pawn_key() function is only used when a new position is set
1415 /// up, and to verify the correctness of the pawn hash key when running in
1418 Key Position::compute_pawn_key() const {
1423 for (Color c = WHITE; c <= BLACK; c++)
1425 b = pieces(PAWN, c);
1427 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1433 /// Position::compute_material_key() computes the hash key of the position.
1434 /// The hash key is usually updated incrementally as moves are made and unmade,
1435 /// the compute_material_key() function is only used when a new position is set
1436 /// up, and to verify the correctness of the material hash key when running in
1439 Key Position::compute_material_key() const {
1443 for (Color c = WHITE; c <= BLACK; c++)
1444 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1445 for (int i = 0; i < piece_count(c, pt); i++)
1446 result ^= zobrist[c][pt][i];
1452 /// Position::compute_value() compute the incremental scores for the middle
1453 /// game and the endgame. These functions are used to initialize the incremental
1454 /// scores when a new position is set up, and to verify that the scores are correctly
1455 /// updated by do_move and undo_move when the program is running in debug mode.
1456 Score Position::compute_value() const {
1459 Score result = SCORE_ZERO;
1461 for (Color c = WHITE; c <= BLACK; c++)
1462 for (PieceType pt = PAWN; pt <= KING; pt++)
1466 result += pst(make_piece(c, pt), pop_1st_bit(&b));
1469 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1474 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1475 /// game material value for the given side. Material values are updated
1476 /// incrementally during the search, this function is only used while
1477 /// initializing a new Position object.
1479 Value Position::compute_non_pawn_material(Color c) const {
1481 Value result = VALUE_ZERO;
1483 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1484 result += piece_count(c, pt) * PieceValueMidgame[pt];
1490 /// Position::is_draw() tests whether the position is drawn by material,
1491 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1492 /// must be done by the search.
1493 template<bool SkipRepetition>
1494 bool Position::is_draw() const {
1496 // Draw by material?
1498 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1501 // Draw by the 50 moves rule?
1502 if (st->rule50 > 99 && !is_mate())
1505 // Draw by repetition?
1506 if (!SkipRepetition)
1508 int i = 4, e = std::min(st->rule50, st->pliesFromNull);
1512 StateInfo* stp = st->previous->previous;
1515 stp = stp->previous->previous;
1517 if (stp->key == st->key)
1529 // Explicit template instantiations
1530 template bool Position::is_draw<false>() const;
1531 template bool Position::is_draw<true>() const;
1534 /// Position::is_mate() returns true or false depending on whether the
1535 /// side to move is checkmated.
1537 bool Position::is_mate() const {
1539 return in_check() && !MoveList<MV_LEGAL>(*this).size();
1543 /// Position::init() is a static member function which initializes at startup
1544 /// the various arrays used to compute hash keys and the piece square tables.
1545 /// The latter is a two-step operation: First, the white halves of the tables
1546 /// are copied from PSQT[] tables. Second, the black halves of the tables are
1547 /// initialized by flipping and changing the sign of the white scores.
1549 void Position::init() {
1553 for (Color c = WHITE; c <= BLACK; c++)
1554 for (PieceType pt = PAWN; pt <= KING; pt++)
1555 for (Square s = SQ_A1; s <= SQ_H8; s++)
1556 zobrist[c][pt][s] = rk.rand<Key>();
1558 for (Square s = SQ_A1; s <= SQ_H8; s++)
1559 zobEp[s] = rk.rand<Key>();
1561 for (int i = 0; i < 16; i++)
1562 zobCastle[i] = rk.rand<Key>();
1564 zobSideToMove = rk.rand<Key>();
1565 zobExclusion = rk.rand<Key>();
1567 for (Piece p = W_PAWN; p <= W_KING; p++)
1569 Score ps = make_score(PieceValueMidgame[p], PieceValueEndgame[p]);
1571 for (Square s = SQ_A1; s <= SQ_H8; s++)
1573 pieceSquareTable[p][s] = ps + PSQT[p][s];
1574 pieceSquareTable[p+8][flip(s)] = -pieceSquareTable[p][s];
1580 /// Position::flip_me() flips position with the white and black sides reversed. This
1581 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1583 void Position::flip_me() {
1585 // Make a copy of current position before to start changing
1586 const Position pos(*this, threadID);
1589 threadID = pos.thread();
1592 for (Square s = SQ_A1; s <= SQ_H8; s++)
1593 if (!pos.square_is_empty(s))
1594 put_piece(Piece(pos.piece_on(s) ^ 8), flip(s));
1597 sideToMove = flip(pos.side_to_move());
1600 if (pos.can_castle(WHITE_OO))
1601 set_castle_right(king_square(BLACK), flip(pos.castle_rook_square(WHITE_OO)));
1602 if (pos.can_castle(WHITE_OOO))
1603 set_castle_right(king_square(BLACK), flip(pos.castle_rook_square(WHITE_OOO)));
1604 if (pos.can_castle(BLACK_OO))
1605 set_castle_right(king_square(WHITE), flip(pos.castle_rook_square(BLACK_OO)));
1606 if (pos.can_castle(BLACK_OOO))
1607 set_castle_right(king_square(WHITE), flip(pos.castle_rook_square(BLACK_OOO)));
1609 // En passant square
1610 if (pos.st->epSquare != SQ_NONE)
1611 st->epSquare = flip(pos.st->epSquare);
1614 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(flip(sideToMove));
1617 st->key = compute_key();
1618 st->pawnKey = compute_pawn_key();
1619 st->materialKey = compute_material_key();
1621 // Incremental scores
1622 st->value = compute_value();
1625 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1626 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1628 assert(pos_is_ok());
1632 /// Position::pos_is_ok() performs some consitency checks for the position object.
1633 /// This is meant to be helpful when debugging.
1635 bool Position::pos_is_ok(int* failedStep) const {
1637 // What features of the position should be verified?
1638 const bool debugAll = false;
1640 const bool debugBitboards = debugAll || false;
1641 const bool debugKingCount = debugAll || false;
1642 const bool debugKingCapture = debugAll || false;
1643 const bool debugCheckerCount = debugAll || false;
1644 const bool debugKey = debugAll || false;
1645 const bool debugMaterialKey = debugAll || false;
1646 const bool debugPawnKey = debugAll || false;
1647 const bool debugIncrementalEval = debugAll || false;
1648 const bool debugNonPawnMaterial = debugAll || false;
1649 const bool debugPieceCounts = debugAll || false;
1650 const bool debugPieceList = debugAll || false;
1651 const bool debugCastleSquares = debugAll || false;
1653 if (failedStep) *failedStep = 1;
1656 if (side_to_move() != WHITE && side_to_move() != BLACK)
1659 // Are the king squares in the position correct?
1660 if (failedStep) (*failedStep)++;
1661 if (piece_on(king_square(WHITE)) != W_KING)
1664 if (failedStep) (*failedStep)++;
1665 if (piece_on(king_square(BLACK)) != B_KING)
1668 // Do both sides have exactly one king?
1669 if (failedStep) (*failedStep)++;
1672 int kingCount[2] = {0, 0};
1673 for (Square s = SQ_A1; s <= SQ_H8; s++)
1674 if (type_of(piece_on(s)) == KING)
1675 kingCount[color_of(piece_on(s))]++;
1677 if (kingCount[0] != 1 || kingCount[1] != 1)
1681 // Can the side to move capture the opponent's king?
1682 if (failedStep) (*failedStep)++;
1683 if (debugKingCapture)
1685 Color us = side_to_move();
1686 Color them = flip(us);
1687 Square ksq = king_square(them);
1688 if (attackers_to(ksq) & pieces(us))
1692 // Is there more than 2 checkers?
1693 if (failedStep) (*failedStep)++;
1694 if (debugCheckerCount && popcount<Full>(st->checkersBB) > 2)
1698 if (failedStep) (*failedStep)++;
1701 // The intersection of the white and black pieces must be empty
1702 if (!(pieces(WHITE) & pieces(BLACK)))
1705 // The union of the white and black pieces must be equal to all
1707 if ((pieces(WHITE) | pieces(BLACK)) != occupied_squares())
1710 // Separate piece type bitboards must have empty intersections
1711 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1712 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1713 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1717 // En passant square OK?
1718 if (failedStep) (*failedStep)++;
1719 if (ep_square() != SQ_NONE)
1721 // The en passant square must be on rank 6, from the point of view of the
1723 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1728 if (failedStep) (*failedStep)++;
1729 if (debugKey && st->key != compute_key())
1732 // Pawn hash key OK?
1733 if (failedStep) (*failedStep)++;
1734 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1737 // Material hash key OK?
1738 if (failedStep) (*failedStep)++;
1739 if (debugMaterialKey && st->materialKey != compute_material_key())
1742 // Incremental eval OK?
1743 if (failedStep) (*failedStep)++;
1744 if (debugIncrementalEval && st->value != compute_value())
1747 // Non-pawn material OK?
1748 if (failedStep) (*failedStep)++;
1749 if (debugNonPawnMaterial)
1751 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1754 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1759 if (failedStep) (*failedStep)++;
1760 if (debugPieceCounts)
1761 for (Color c = WHITE; c <= BLACK; c++)
1762 for (PieceType pt = PAWN; pt <= KING; pt++)
1763 if (pieceCount[c][pt] != popcount<Full>(pieces(pt, c)))
1766 if (failedStep) (*failedStep)++;
1768 for (Color c = WHITE; c <= BLACK; c++)
1769 for (PieceType pt = PAWN; pt <= KING; pt++)
1770 for (int i = 0; i < pieceCount[c][pt]; i++)
1772 if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1775 if (index[piece_list(c, pt)[i]] != i)
1779 if (failedStep) (*failedStep)++;
1780 if (debugCastleSquares)
1781 for (CastleRight f = WHITE_OO; f <= BLACK_OOO; f = CastleRight(f << 1))
1786 Piece rook = (f & (WHITE_OO | WHITE_OOO) ? W_ROOK : B_ROOK);
1788 if ( castleRightsMask[castleRookSquare[f]] != (ALL_CASTLES ^ f)
1789 || piece_on(castleRookSquare[f]) != rook)
1793 if (failedStep) *failedStep = 0;