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-2010 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[64];
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 TempoValue = 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 = flip(pos.side_to_move());
81 Square 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];
91 checkSq[KING] = EmptyBoardBB;
95 /// Position c'tors. Here we always create a copy of the original position
96 /// or the FEN string, we want the new born Position object do not depend
97 /// on any external data so we detach state pointer from the source one.
99 Position::Position(const Position& pos, int th) {
101 memcpy(this, &pos, sizeof(Position));
108 Position::Position(const string& fen, bool isChess960, int th) {
110 from_fen(fen, isChess960);
115 /// Position::from_fen() initializes the position object with the given FEN
116 /// string. This function is not very robust - make sure that input FENs are
117 /// correct (this is assumed to be the responsibility of the GUI).
119 void Position::from_fen(const string& fenStr, bool isChess960) {
121 A FEN string defines a particular position using only the ASCII character set.
123 A FEN string contains six fields. The separator between fields is a space. The fields are:
125 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
126 with rank 1; within each rank, the contents of each square are described from file A through file H.
127 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
128 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
129 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
130 of blank squares), and "/" separate ranks.
132 2) Active color. "w" means white moves next, "b" means black.
134 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
135 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
136 kingside), and/or "q" (Black can castle queenside).
138 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
139 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
140 regardless of whether there is a pawn in position to make an en passant capture.
142 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
143 to determine if a draw can be claimed under the fifty-move rule.
145 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
148 char col, row, token;
151 std::istringstream fen(fenStr);
154 fen >> std::noskipws;
156 // 1. Piece placement
157 while ((fen >> token) && !isspace(token))
160 sq -= Square(16); // Jump back of 2 rows
162 else if (isdigit(token))
163 sq += Square(token - '0'); // Skip the given number of files
165 else if ((p = PieceToChar.find(token)) != string::npos)
167 put_piece(Piece(p), sq);
174 sideToMove = (token == 'w' ? WHITE : BLACK);
177 // 3. Castling availability
178 while ((fen >> token) && !isspace(token))
179 set_castling_rights(token);
181 // 4. En passant square. Ignore if no pawn capture is possible
182 if ( ((fen >> col) && (col >= 'a' && col <= 'h'))
183 && ((fen >> row) && (row == '3' || row == '6')))
185 st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
186 Color them = flip(sideToMove);
188 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
189 st->epSquare = SQ_NONE;
192 // 5-6. Halfmove clock and fullmove number
193 fen >> std::skipws >> st->rule50 >> startPosPly;
195 // Convert from fullmove starting from 1 to ply starting from 0,
196 // handle also common incorrect FEN with fullmove = 0.
197 startPosPly = Max(2 * (startPosPly - 1), 0) + int(sideToMove == BLACK);
199 // Various initialisations
200 chess960 = isChess960;
201 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(flip(sideToMove));
203 st->key = compute_key();
204 st->pawnKey = compute_pawn_key();
205 st->materialKey = compute_material_key();
206 st->value = compute_value();
207 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
208 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
214 /// Position::set_castle() is an helper function used to set
215 /// correct castling related flags.
217 void Position::set_castle(int f, Square ksq, Square rsq) {
219 st->castleRights |= f;
220 castleRightsMask[ksq] ^= f;
221 castleRightsMask[rsq] ^= f;
222 castleRookSquare[f] = rsq;
226 /// Position::set_castling_rights() sets castling parameters castling avaiability.
227 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
228 /// that uses the letters of the columns on which the rooks began the game instead
229 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
230 /// associated with the castling right, the traditional castling tag will be replaced
231 /// by the file letter of the involved rook as for the Shredder-FEN.
233 void Position::set_castling_rights(char token) {
235 Color c = islower(token) ? BLACK : WHITE;
237 Square sqA = relative_square(c, SQ_A1);
238 Square sqH = relative_square(c, SQ_H1);
239 Square rsq, ksq = king_square(c);
241 token = char(toupper(token));
244 for (rsq = sqH; piece_on(rsq) != make_piece(c, ROOK); rsq--) {}
246 else if (token == 'Q')
247 for (rsq = sqA; piece_on(rsq) != make_piece(c, ROOK); rsq++) {}
249 else if (token >= 'A' && token <= 'H')
250 rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
254 if (file_of(rsq) < file_of(ksq))
255 set_castle(WHITE_OOO << c, ksq, rsq);
257 set_castle(WHITE_OO << c, ksq, rsq);
261 /// Position::to_fen() returns a FEN representation of the position. In case
262 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
264 const string Position::to_fen() const {
266 std::ostringstream fen;
270 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
274 for (File file = FILE_A; file <= FILE_H; file++)
276 sq = make_square(file, rank);
278 if (!square_is_empty(sq))
285 fen << PieceToChar[piece_on(sq)];
298 fen << (sideToMove == WHITE ? " w " : " b ");
300 if (st->castleRights != CASTLES_NONE)
302 if (can_castle(WHITE_OO))
303 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OO))))) : 'K');
305 if (can_castle(WHITE_OOO))
306 fen << (chess960 ? char(toupper(file_to_char(file_of(castle_rook_square(WHITE_OOO))))) : 'Q');
308 if (can_castle(BLACK_OO))
309 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OO))) : 'k');
311 if (can_castle(BLACK_OOO))
312 fen << (chess960 ? file_to_char(file_of(castle_rook_square(BLACK_OOO))) : 'q');
316 fen << (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()))
317 << " " << st->rule50 << " " << 1 + (startPosPly - int(sideToMove == BLACK)) / 2;
323 /// Position::print() prints an ASCII representation of the position to
324 /// the standard output. If a move is given then also the san is printed.
326 void Position::print(Move move) const {
328 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
332 Position p(*this, thread());
333 string dd = (sideToMove == BLACK ? ".." : "");
334 cout << "\nMove is: " << dd << 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);
345 if (piece == PIECE_NONE && color_of(sq) == DARK)
346 piece = PIECE_NONE_DARK_SQ;
348 char c = (color_of(piece_on(sq)) == BLACK ? '=' : ' ');
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.
361 template<bool FindPinned>
362 Bitboard Position::hidden_checkers() const {
364 // Pinned pieces protect our king, dicovery checks attack the enemy king
365 Bitboard b, result = EmptyBoardBB;
366 Bitboard pinners = pieces(FindPinned ? flip(sideToMove) : sideToMove);
367 Square ksq = king_square(FindPinned ? sideToMove : flip(sideToMove));
369 // Pinners are sliders, that give check when candidate pinned is removed
370 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq])
371 | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
375 b = squares_between(ksq, pop_1st_bit(&pinners)) & occupied_squares();
377 // Only one bit set and is an our piece?
378 if (b && !(b & (b - 1)) && (b & pieces(sideToMove)))
385 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
386 /// king) pieces for the side to move.
388 Bitboard Position::pinned_pieces() const {
390 return hidden_checkers<true>();
394 /// Position:discovered_check_candidates() returns a bitboard containing all
395 /// pieces for the side to move which are candidates for giving a discovered
398 Bitboard Position::discovered_check_candidates() const {
400 return hidden_checkers<false>();
403 /// Position::attackers_to() computes a bitboard of all pieces which attacks a
404 /// given square. Slider attacks use occ bitboard as occupancy.
406 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
408 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
409 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
410 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
411 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
412 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
413 | (attacks_from<KING>(s) & pieces(KING));
416 /// Position::attacks_from() computes a bitboard of all attacks of a given piece
417 /// put in a given square. Slider attacks use occ bitboard as occupancy.
419 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
421 assert(square_is_ok(s));
425 case WB: case BB: return bishop_attacks_bb(s, occ);
426 case WR: case BR: return rook_attacks_bb(s, occ);
427 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
428 default: return StepAttacksBB[p][s];
433 /// Position::move_attacks_square() tests whether a move from the current
434 /// position attacks a given square.
436 bool Position::move_attacks_square(Move m, Square s) const {
439 assert(square_is_ok(s));
442 Square f = move_from(m), t = move_to(m);
444 assert(!square_is_empty(f));
446 if (bit_is_set(attacks_from(piece_on(f), t), s))
449 // Move the piece and scan for X-ray attacks behind it
450 occ = occupied_squares();
451 do_move_bb(&occ, make_move_bb(f, t));
452 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
453 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
454 & pieces(color_of(piece_on(f)));
456 // If we have attacks we need to verify that are caused by our move
457 // and are not already existent ones.
458 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
462 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
464 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
467 assert(pinned == pinned_pieces());
469 Color us = side_to_move();
470 Square from = move_from(m);
472 assert(color_of(piece_on(from)) == us);
473 assert(piece_on(king_square(us)) == make_piece(us, KING));
475 // En passant captures are a tricky special case. Because they are rather
476 // uncommon, we do it simply by testing whether the king is attacked after
480 Color them = flip(us);
481 Square to = move_to(m);
482 Square capsq = to + pawn_push(them);
483 Square ksq = king_square(us);
484 Bitboard b = occupied_squares();
486 assert(to == ep_square());
487 assert(piece_on(from) == make_piece(us, PAWN));
488 assert(piece_on(capsq) == make_piece(them, PAWN));
489 assert(piece_on(to) == PIECE_NONE);
492 clear_bit(&b, capsq);
495 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
496 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
499 // If the moving piece is a king, check whether the destination
500 // square is attacked by the opponent. Castling moves are checked
501 // for legality during move generation.
502 if (type_of(piece_on(from)) == KING)
503 return is_castle(m) || !(attackers_to(move_to(m)) & pieces(flip(us)));
505 // A non-king move is legal if and only if it is not pinned or it
506 // is moving along the ray towards or away from the king.
508 || !bit_is_set(pinned, from)
509 || squares_aligned(from, move_to(m), king_square(us));
513 /// Position::move_is_legal() takes a random move and tests whether the move
514 /// is legal. This version is not very fast and should be used only
515 /// in non time-critical paths.
517 bool Position::move_is_legal(const Move m) const {
519 for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
527 /// Position::is_pseudo_legal() takes a random move and tests whether the move
528 /// is pseudo legal. It is used to validate moves from TT that can be corrupted
529 /// due to SMP concurrent access or hash position key aliasing.
531 bool Position::is_pseudo_legal(const Move m) const {
533 Color us = sideToMove;
534 Color them = flip(sideToMove);
535 Square from = move_from(m);
536 Square to = move_to(m);
537 Piece pc = piece_on(from);
539 // Use a slower but simpler function for uncommon cases
541 return move_is_legal(m);
543 // Is not a promotion, so promotion piece must be empty
544 if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
547 // If the from square is not occupied by a piece belonging to the side to
548 // move, the move is obviously not legal.
549 if (pc == PIECE_NONE || color_of(pc) != us)
552 // The destination square cannot be occupied by a friendly piece
553 if (color_of(piece_on(to)) == us)
556 // Handle the special case of a pawn move
557 if (type_of(pc) == PAWN)
559 // Move direction must be compatible with pawn color
560 int direction = to - from;
561 if ((us == WHITE) != (direction > 0))
564 // We have already handled promotion moves, so destination
565 // cannot be on the 8/1th rank.
566 if (rank_of(to) == RANK_8 || rank_of(to) == RANK_1)
569 // Proceed according to the square delta between the origin and
570 // destination squares.
577 // Capture. The destination square must be occupied by an enemy
578 // piece (en passant captures was handled earlier).
579 if (color_of(piece_on(to)) != them)
582 // From and to files must be one file apart, avoids a7h5
583 if (abs(file_of(from) - file_of(to)) != 1)
589 // Pawn push. The destination square must be empty.
590 if (!square_is_empty(to))
595 // Double white pawn push. The destination square must be on the fourth
596 // rank, and both the destination square and the square between the
597 // source and destination squares must be empty.
598 if ( rank_of(to) != RANK_4
599 || !square_is_empty(to)
600 || !square_is_empty(from + DELTA_N))
605 // Double black pawn push. The destination square must be on the fifth
606 // rank, and both the destination square and the square between the
607 // source and destination squares must be empty.
608 if ( rank_of(to) != RANK_5
609 || !square_is_empty(to)
610 || !square_is_empty(from + DELTA_S))
618 else if (!bit_is_set(attacks_from(pc, from), to))
621 // Evasions generator already takes care to avoid some kind of illegal moves
622 // and pl_move_is_legal() relies on this. So we have to take care that the
623 // same kind of moves are filtered out here.
626 // In case of king moves under check we have to remove king so to catch
627 // as invalid moves like b1a1 when opposite queen is on c1.
628 if (type_of(piece_on(from)) == KING)
630 Bitboard b = occupied_squares();
632 if (attackers_to(move_to(m), b) & pieces(flip(us)))
637 Bitboard target = checkers();
638 Square checksq = pop_1st_bit(&target);
640 if (target) // double check ? In this case a king move is required
643 // Our move must be a blocking evasion or a capture of the checking piece
644 target = squares_between(checksq, king_square(us)) | checkers();
645 if (!bit_is_set(target, move_to(m)))
654 /// Position::move_gives_check() tests whether a pseudo-legal move gives a check
656 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
659 assert(ci.dcCandidates == discovered_check_candidates());
660 assert(color_of(piece_on(move_from(m))) == side_to_move());
662 Square from = move_from(m);
663 Square to = move_to(m);
664 PieceType pt = type_of(piece_on(from));
667 if (bit_is_set(ci.checkSq[pt], to))
671 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
673 // For pawn and king moves we need to verify also direction
674 if ( (pt != PAWN && pt != KING)
675 || !squares_aligned(from, to, king_square(flip(side_to_move()))))
679 // Can we skip the ugly special cases ?
683 Color us = side_to_move();
684 Bitboard b = occupied_squares();
685 Square ksq = king_square(flip(us));
687 // Promotion with check ?
691 return bit_is_set(attacks_from(Piece(promotion_piece_type(m)), to, b), ksq);
694 // En passant capture with check ? We have already handled the case
695 // of direct checks and ordinary discovered check, the only case we
696 // need to handle is the unusual case of a discovered check through
697 // the captured pawn.
700 Square capsq = make_square(file_of(to), rank_of(from));
702 clear_bit(&b, capsq);
704 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
705 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
708 // Castling with check ?
711 Square kfrom, kto, rfrom, rto;
717 kto = relative_square(us, SQ_G1);
718 rto = relative_square(us, SQ_F1);
720 kto = relative_square(us, SQ_C1);
721 rto = relative_square(us, SQ_D1);
723 clear_bit(&b, kfrom);
724 clear_bit(&b, rfrom);
727 return bit_is_set(rook_attacks_bb(rto, b), ksq);
734 /// Position::do_move() makes a move, and saves all information necessary
735 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
736 /// moves should be filtered out before this function is called.
738 void Position::do_move(Move m, StateInfo& newSt) {
741 do_move(m, newSt, ci, move_gives_check(m, ci));
744 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
747 assert(&newSt != st);
752 // Copy some fields of old state to our new StateInfo object except the
753 // ones which are recalculated from scratch anyway, then switch our state
754 // pointer to point to the new, ready to be updated, state.
755 struct ReducedStateInfo {
756 Key pawnKey, materialKey;
758 int castleRights, rule50, pliesFromNull;
763 memcpy(&newSt, st, sizeof(ReducedStateInfo));
768 // Update side to move
769 key ^= zobSideToMove;
771 // Increment the 50 moves rule draw counter. Resetting it to zero in the
772 // case of non-reversible moves is taken care of later.
783 Color us = side_to_move();
784 Color them = flip(us);
785 Square from = move_from(m);
786 Square to = move_to(m);
787 bool ep = is_enpassant(m);
788 bool pm = is_promotion(m);
790 Piece piece = piece_on(from);
791 PieceType pt = type_of(piece);
792 PieceType capture = ep ? PAWN : type_of(piece_on(to));
794 assert(color_of(piece_on(from)) == us);
795 assert(color_of(piece_on(to)) == them || square_is_empty(to));
796 assert(!(ep || pm) || piece == make_piece(us, PAWN));
797 assert(!pm || relative_rank(us, to) == RANK_8);
800 do_capture_move(key, capture, them, to, ep);
803 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
805 // Reset en passant square
806 if (st->epSquare != SQ_NONE)
808 key ^= zobEp[st->epSquare];
809 st->epSquare = SQ_NONE;
812 // Update castle rights if needed
813 if ( st->castleRights != CASTLES_NONE
814 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
816 key ^= zobCastle[st->castleRights];
817 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
818 key ^= zobCastle[st->castleRights];
821 // Prefetch TT access as soon as we know key is updated
822 prefetch((char*)TT.first_entry(key));
825 Bitboard move_bb = make_move_bb(from, to);
826 do_move_bb(&byColorBB[us], move_bb);
827 do_move_bb(&byTypeBB[pt], move_bb);
828 do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
830 board[to] = board[from];
831 board[from] = PIECE_NONE;
833 // Update piece lists, note that index[from] is not updated and
834 // becomes stale. This works as long as index[] is accessed just
835 // by known occupied squares.
836 index[to] = index[from];
837 pieceList[us][pt][index[to]] = to;
839 // If the moving piece was a pawn do some special extra work
842 // Reset rule 50 draw counter
845 // Update pawn hash key and prefetch in L1/L2 cache
846 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
848 // Set en passant square, only if moved pawn can be captured
849 if ((to ^ from) == 16)
851 if (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(PAWN, them))
853 st->epSquare = Square((int(from) + int(to)) / 2);
854 key ^= zobEp[st->epSquare];
858 if (pm) // promotion ?
860 PieceType promotion = promotion_piece_type(m);
862 assert(promotion >= KNIGHT && promotion <= QUEEN);
864 // Insert promoted piece instead of pawn
865 clear_bit(&byTypeBB[PAWN], to);
866 set_bit(&byTypeBB[promotion], to);
867 board[to] = make_piece(us, promotion);
869 // Update piece counts
870 pieceCount[us][promotion]++;
871 pieceCount[us][PAWN]--;
873 // Update material key
874 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
875 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
877 // Update piece lists, move the last pawn at index[to] position
878 // and shrink the list. Add a new promotion piece to the list.
879 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
880 index[lastPawnSquare] = index[to];
881 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
882 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
883 index[to] = pieceCount[us][promotion] - 1;
884 pieceList[us][promotion][index[to]] = to;
886 // Partially revert hash keys update
887 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
888 st->pawnKey ^= zobrist[us][PAWN][to];
890 // Partially revert and update incremental scores
891 st->value -= pst(make_piece(us, PAWN), to);
892 st->value += pst(make_piece(us, promotion), to);
895 st->npMaterial[us] += PieceValueMidgame[promotion];
899 // Prefetch pawn and material hash tables
900 Threads[threadID].pawnTable.prefetch(st->pawnKey);
901 Threads[threadID].materialTable.prefetch(st->materialKey);
903 // Update incremental scores
904 st->value += pst_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
913 st->checkersBB = EmptyBoardBB;
918 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
922 if (bit_is_set(ci.checkSq[pt], to))
923 st->checkersBB = SetMaskBB[to];
926 if (ci.dcCandidates && bit_is_set(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 = flip(sideToMove);
939 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
945 /// Position::do_capture_move() is a private method used to update captured
946 /// piece info. It is called from the main Position::do_move function.
948 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
950 assert(capture != KING);
954 // If the captured piece was a pawn, update pawn hash key,
955 // otherwise update non-pawn material.
958 if (ep) // en passant ?
960 capsq = to + pawn_push(them);
962 assert(to == st->epSquare);
963 assert(relative_rank(flip(them), to) == RANK_6);
964 assert(piece_on(to) == PIECE_NONE);
965 assert(piece_on(capsq) == make_piece(them, PAWN));
967 board[capsq] = PIECE_NONE;
969 st->pawnKey ^= zobrist[them][PAWN][capsq];
972 st->npMaterial[them] -= PieceValueMidgame[capture];
974 // Remove captured piece
975 clear_bit(&byColorBB[them], capsq);
976 clear_bit(&byTypeBB[capture], capsq);
977 clear_bit(&byTypeBB[0], capsq);
980 key ^= zobrist[them][capture][capsq];
982 // Update incremental scores
983 st->value -= pst(make_piece(them, capture), capsq);
985 // Update piece count
986 pieceCount[them][capture]--;
988 // Update material hash key
989 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
991 // Update piece list, move the last piece at index[capsq] position
993 // WARNING: This is a not perfectly revresible operation. When we
994 // will reinsert the captured piece in undo_move() we will put it
995 // at the end of the list and not in its original place, it means
996 // index[] and pieceList[] are not guaranteed to be invariant to a
997 // do_move() + undo_move() sequence.
998 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
999 index[lastPieceSquare] = index[capsq];
1000 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1001 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1003 // Reset rule 50 counter
1008 /// Position::do_castle_move() is a private method used to make a castling
1009 /// move. It is called from the main Position::do_move function. Note that
1010 /// castling moves are encoded as "king captures friendly rook" moves, for
1011 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1013 void Position::do_castle_move(Move m) {
1016 assert(is_castle(m));
1018 Color us = side_to_move();
1019 Color them = flip(us);
1021 // Find source squares for king and rook
1022 Square kfrom = move_from(m);
1023 Square rfrom = move_to(m);
1026 assert(piece_on(kfrom) == make_piece(us, KING));
1027 assert(piece_on(rfrom) == make_piece(us, ROOK));
1029 // Find destination squares for king and rook
1030 if (rfrom > kfrom) // O-O
1032 kto = relative_square(us, SQ_G1);
1033 rto = relative_square(us, SQ_F1);
1037 kto = relative_square(us, SQ_C1);
1038 rto = relative_square(us, SQ_D1);
1041 // Remove pieces from source squares
1042 clear_bit(&byColorBB[us], kfrom);
1043 clear_bit(&byTypeBB[KING], kfrom);
1044 clear_bit(&byTypeBB[0], kfrom);
1045 clear_bit(&byColorBB[us], rfrom);
1046 clear_bit(&byTypeBB[ROOK], rfrom);
1047 clear_bit(&byTypeBB[0], rfrom);
1049 // Put pieces on destination squares
1050 set_bit(&byColorBB[us], kto);
1051 set_bit(&byTypeBB[KING], kto);
1052 set_bit(&byTypeBB[0], kto);
1053 set_bit(&byColorBB[us], rto);
1054 set_bit(&byTypeBB[ROOK], rto);
1055 set_bit(&byTypeBB[0], rto);
1058 Piece king = make_piece(us, KING);
1059 Piece rook = make_piece(us, ROOK);
1060 board[kfrom] = board[rfrom] = PIECE_NONE;
1064 // Update piece lists
1065 pieceList[us][KING][index[kfrom]] = kto;
1066 pieceList[us][ROOK][index[rfrom]] = rto;
1067 int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1068 index[kto] = index[kfrom];
1071 // Reset capture field
1072 st->capturedType = PIECE_TYPE_NONE;
1074 // Update incremental scores
1075 st->value += pst_delta(king, kfrom, kto);
1076 st->value += pst_delta(rook, rfrom, rto);
1079 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1080 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1082 // Clear en passant square
1083 if (st->epSquare != SQ_NONE)
1085 st->key ^= zobEp[st->epSquare];
1086 st->epSquare = SQ_NONE;
1089 // Update castling rights
1090 st->key ^= zobCastle[st->castleRights];
1091 st->castleRights &= castleRightsMask[kfrom];
1092 st->key ^= zobCastle[st->castleRights];
1094 // Reset rule 50 counter
1097 // Update checkers BB
1098 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
1101 sideToMove = flip(sideToMove);
1102 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1104 assert(pos_is_ok());
1108 /// Position::undo_move() unmakes a move. When it returns, the position should
1109 /// be restored to exactly the same state as before the move was made.
1111 void Position::undo_move(Move m) {
1115 sideToMove = flip(sideToMove);
1119 undo_castle_move(m);
1123 Color us = side_to_move();
1124 Color them = flip(us);
1125 Square from = move_from(m);
1126 Square to = move_to(m);
1127 bool ep = is_enpassant(m);
1128 bool pm = is_promotion(m);
1130 PieceType pt = type_of(piece_on(to));
1132 assert(square_is_empty(from));
1133 assert(color_of(piece_on(to)) == us);
1134 assert(!pm || relative_rank(us, to) == RANK_8);
1135 assert(!ep || to == st->previous->epSquare);
1136 assert(!ep || relative_rank(us, to) == RANK_6);
1137 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1139 if (pm) // promotion ?
1141 PieceType promotion = promotion_piece_type(m);
1144 assert(promotion >= KNIGHT && promotion <= QUEEN);
1145 assert(piece_on(to) == make_piece(us, promotion));
1147 // Replace promoted piece with a pawn
1148 clear_bit(&byTypeBB[promotion], to);
1149 set_bit(&byTypeBB[PAWN], to);
1151 // Update piece counts
1152 pieceCount[us][promotion]--;
1153 pieceCount[us][PAWN]++;
1155 // Update piece list replacing promotion piece with a pawn
1156 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1157 index[lastPromotionSquare] = index[to];
1158 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1159 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1160 index[to] = pieceCount[us][PAWN] - 1;
1161 pieceList[us][PAWN][index[to]] = to;
1164 // Put the piece back at the source square
1165 Bitboard move_bb = make_move_bb(to, from);
1166 do_move_bb(&byColorBB[us], move_bb);
1167 do_move_bb(&byTypeBB[pt], move_bb);
1168 do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
1170 board[from] = make_piece(us, pt);
1171 board[to] = PIECE_NONE;
1173 // Update piece list
1174 index[from] = index[to];
1175 pieceList[us][pt][index[from]] = from;
1177 if (st->capturedType)
1182 capsq = to - pawn_push(us);
1184 assert(st->capturedType != KING);
1185 assert(!ep || square_is_empty(capsq));
1187 // Restore the captured piece
1188 set_bit(&byColorBB[them], capsq);
1189 set_bit(&byTypeBB[st->capturedType], capsq);
1190 set_bit(&byTypeBB[0], capsq);
1192 board[capsq] = make_piece(them, st->capturedType);
1194 // Update piece count
1195 pieceCount[them][st->capturedType]++;
1197 // Update piece list, add a new captured piece in capsq square
1198 index[capsq] = pieceCount[them][st->capturedType] - 1;
1199 pieceList[them][st->capturedType][index[capsq]] = capsq;
1202 // Finally point our state pointer back to the previous state
1205 assert(pos_is_ok());
1209 /// Position::undo_castle_move() is a private method used to unmake a castling
1210 /// move. It is called from the main Position::undo_move function. Note that
1211 /// castling moves are encoded as "king captures friendly rook" moves, for
1212 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1214 void Position::undo_castle_move(Move m) {
1217 assert(is_castle(m));
1219 // When we have arrived here, some work has already been done by
1220 // Position::undo_move. In particular, the side to move has been switched,
1221 // so the code below is correct.
1222 Color us = side_to_move();
1224 // Find source squares for king and rook
1225 Square kfrom = move_from(m);
1226 Square rfrom = move_to(m);
1229 // Find destination squares for king and rook
1230 if (rfrom > kfrom) // O-O
1232 kto = relative_square(us, SQ_G1);
1233 rto = relative_square(us, SQ_F1);
1237 kto = relative_square(us, SQ_C1);
1238 rto = relative_square(us, SQ_D1);
1241 assert(piece_on(kto) == make_piece(us, KING));
1242 assert(piece_on(rto) == make_piece(us, ROOK));
1244 // Remove pieces from destination squares
1245 clear_bit(&byColorBB[us], kto);
1246 clear_bit(&byTypeBB[KING], kto);
1247 clear_bit(&byTypeBB[0], kto);
1248 clear_bit(&byColorBB[us], rto);
1249 clear_bit(&byTypeBB[ROOK], rto);
1250 clear_bit(&byTypeBB[0], rto);
1252 // Put pieces on source squares
1253 set_bit(&byColorBB[us], kfrom);
1254 set_bit(&byTypeBB[KING], kfrom);
1255 set_bit(&byTypeBB[0], kfrom);
1256 set_bit(&byColorBB[us], rfrom);
1257 set_bit(&byTypeBB[ROOK], rfrom);
1258 set_bit(&byTypeBB[0], rfrom);
1261 Piece king = make_piece(us, KING);
1262 Piece rook = make_piece(us, ROOK);
1263 board[kto] = board[rto] = PIECE_NONE;
1264 board[kfrom] = king;
1265 board[rfrom] = rook;
1267 // Update piece lists
1268 pieceList[us][KING][index[kto]] = kfrom;
1269 pieceList[us][ROOK][index[rto]] = rfrom;
1270 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1271 index[kfrom] = index[kto];
1274 // Finally point our state pointer back to the previous state
1277 assert(pos_is_ok());
1281 /// Position::do_null_move makes() a "null move": It switches the side to move
1282 /// and updates the hash key without executing any move on the board.
1284 void Position::do_null_move(StateInfo& backupSt) {
1286 assert(!in_check());
1288 // Back up the information necessary to undo the null move to the supplied
1289 // StateInfo object.
1290 // Note that differently from normal case here backupSt is actually used as
1291 // a backup storage not as a new state to be used.
1292 backupSt.key = st->key;
1293 backupSt.epSquare = st->epSquare;
1294 backupSt.value = st->value;
1295 backupSt.previous = st->previous;
1296 backupSt.pliesFromNull = st->pliesFromNull;
1297 st->previous = &backupSt;
1299 // Update the necessary information
1300 if (st->epSquare != SQ_NONE)
1301 st->key ^= zobEp[st->epSquare];
1303 st->key ^= zobSideToMove;
1304 prefetch((char*)TT.first_entry(st->key));
1306 sideToMove = flip(sideToMove);
1307 st->epSquare = SQ_NONE;
1309 st->pliesFromNull = 0;
1310 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1312 assert(pos_is_ok());
1316 /// Position::undo_null_move() unmakes a "null move".
1318 void Position::undo_null_move() {
1320 assert(!in_check());
1322 // Restore information from the our backup StateInfo object
1323 StateInfo* backupSt = st->previous;
1324 st->key = backupSt->key;
1325 st->epSquare = backupSt->epSquare;
1326 st->value = backupSt->value;
1327 st->previous = backupSt->previous;
1328 st->pliesFromNull = backupSt->pliesFromNull;
1330 // Update the necessary information
1331 sideToMove = flip(sideToMove);
1334 assert(pos_is_ok());
1338 /// Position::see() is a static exchange evaluator: It tries to estimate the
1339 /// material gain or loss resulting from a move. There are three versions of
1340 /// this function: One which takes a destination square as input, one takes a
1341 /// move, and one which takes a 'from' and a 'to' square. The function does
1342 /// not yet understand promotions captures.
1344 int Position::see_sign(Move m) const {
1348 Square from = move_from(m);
1349 Square to = move_to(m);
1351 // Early return if SEE cannot be negative because captured piece value
1352 // is not less then capturing one. Note that king moves always return
1353 // here because king midgame value is set to 0.
1354 if (PieceValueMidgame[piece_on(to)] >= PieceValueMidgame[piece_on(from)])
1360 int Position::see(Move m) const {
1363 Bitboard occupied, attackers, stmAttackers, b;
1364 int swapList[32], slIndex = 1;
1365 PieceType capturedType, pt;
1370 // As castle moves are implemented as capturing the rook, they have
1371 // SEE == RookValueMidgame most of the times (unless the rook is under
1376 from = move_from(m);
1378 capturedType = type_of(piece_on(to));
1379 occupied = occupied_squares();
1381 // Handle en passant moves
1382 if (st->epSquare == to && type_of(piece_on(from)) == PAWN)
1384 Square capQq = to - pawn_push(side_to_move());
1386 assert(capturedType == PIECE_TYPE_NONE);
1387 assert(type_of(piece_on(capQq)) == PAWN);
1389 // Remove the captured pawn
1390 clear_bit(&occupied, capQq);
1391 capturedType = PAWN;
1394 // Find all attackers to the destination square, with the moving piece
1395 // removed, but possibly an X-ray attacker added behind it.
1396 clear_bit(&occupied, from);
1397 attackers = attackers_to(to, occupied);
1399 // If the opponent has no attackers we are finished
1400 stm = flip(color_of(piece_on(from)));
1401 stmAttackers = attackers & pieces(stm);
1403 return PieceValueMidgame[capturedType];
1405 // The destination square is defended, which makes things rather more
1406 // difficult to compute. We proceed by building up a "swap list" containing
1407 // the material gain or loss at each stop in a sequence of captures to the
1408 // destination square, where the sides alternately capture, and always
1409 // capture with the least valuable piece. After each capture, we look for
1410 // new X-ray attacks from behind the capturing piece.
1411 swapList[0] = PieceValueMidgame[capturedType];
1412 capturedType = type_of(piece_on(from));
1415 // Locate the least valuable attacker for the side to move. The loop
1416 // below looks like it is potentially infinite, but it isn't. We know
1417 // that the side to move still has at least one attacker left.
1418 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1421 // Remove the attacker we just found from the 'occupied' bitboard,
1422 // and scan for new X-ray attacks behind the attacker.
1423 b = stmAttackers & pieces(pt);
1424 occupied ^= (b & (~b + 1));
1425 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1426 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1428 attackers &= occupied; // Cut out pieces we've already done
1430 // Add the new entry to the swap list
1431 assert(slIndex < 32);
1432 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1435 // Remember the value of the capturing piece, and change the side to
1436 // move before beginning the next iteration.
1439 stmAttackers = attackers & pieces(stm);
1441 // Stop before processing a king capture
1442 if (capturedType == KING && stmAttackers)
1444 assert(slIndex < 32);
1445 swapList[slIndex++] = QueenValueMidgame*10;
1448 } while (stmAttackers);
1450 // Having built the swap list, we negamax through it to find the best
1451 // achievable score from the point of view of the side to move.
1453 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1459 /// Position::clear() erases the position object to a pristine state, with an
1460 /// empty board, white to move, and no castling rights.
1462 void Position::clear() {
1465 memset(st, 0, sizeof(StateInfo));
1466 st->epSquare = SQ_NONE;
1468 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1469 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1470 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1471 memset(index, 0, sizeof(int) * 64);
1473 for (int i = 0; i < 8; i++)
1474 for (int j = 0; j < 16; j++)
1475 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1477 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1479 board[sq] = PIECE_NONE;
1480 castleRightsMask[sq] = ALL_CASTLES;
1487 /// Position::put_piece() puts a piece on the given square of the board,
1488 /// updating the board array, pieces list, bitboards, and piece counts.
1490 void Position::put_piece(Piece p, Square s) {
1492 Color c = color_of(p);
1493 PieceType pt = type_of(p);
1496 index[s] = pieceCount[c][pt]++;
1497 pieceList[c][pt][index[s]] = s;
1499 set_bit(&byTypeBB[pt], s);
1500 set_bit(&byColorBB[c], s);
1501 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1505 /// Position::compute_key() computes the hash key of the position. The hash
1506 /// key is usually updated incrementally as moves are made and unmade, the
1507 /// compute_key() function is only used when a new position is set up, and
1508 /// to verify the correctness of the hash key when running in debug mode.
1510 Key Position::compute_key() const {
1512 Key result = zobCastle[st->castleRights];
1514 for (Square s = SQ_A1; s <= SQ_H8; s++)
1515 if (!square_is_empty(s))
1516 result ^= zobrist[color_of(piece_on(s))][type_of(piece_on(s))][s];
1518 if (ep_square() != SQ_NONE)
1519 result ^= zobEp[ep_square()];
1521 if (side_to_move() == BLACK)
1522 result ^= zobSideToMove;
1528 /// Position::compute_pawn_key() computes the hash key of the position. The
1529 /// hash key is usually updated incrementally as moves are made and unmade,
1530 /// the compute_pawn_key() function is only used when a new position is set
1531 /// up, and to verify the correctness of the pawn hash key when running in
1534 Key Position::compute_pawn_key() const {
1539 for (Color c = WHITE; c <= BLACK; c++)
1541 b = pieces(PAWN, c);
1543 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1549 /// Position::compute_material_key() computes the hash key of the position.
1550 /// The hash key is usually updated incrementally as moves are made and unmade,
1551 /// the compute_material_key() function is only used when a new position is set
1552 /// up, and to verify the correctness of the material hash key when running in
1555 Key Position::compute_material_key() const {
1559 for (Color c = WHITE; c <= BLACK; c++)
1560 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1561 for (int i = 0; i < piece_count(c, pt); i++)
1562 result ^= zobrist[c][pt][i];
1568 /// Position::compute_value() compute the incremental scores for the middle
1569 /// game and the endgame. These functions are used to initialize the incremental
1570 /// scores when a new position is set up, and to verify that the scores are correctly
1571 /// updated by do_move and undo_move when the program is running in debug mode.
1572 Score Position::compute_value() const {
1575 Score result = SCORE_ZERO;
1577 for (Color c = WHITE; c <= BLACK; c++)
1578 for (PieceType pt = PAWN; pt <= KING; pt++)
1582 result += pst(make_piece(c, pt), pop_1st_bit(&b));
1585 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1590 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1591 /// game material value for the given side. Material values are updated
1592 /// incrementally during the search, this function is only used while
1593 /// initializing a new Position object.
1595 Value Position::compute_non_pawn_material(Color c) const {
1597 Value result = VALUE_ZERO;
1599 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1600 result += piece_count(c, pt) * PieceValueMidgame[pt];
1606 /// Position::is_draw() tests whether the position is drawn by material,
1607 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1608 /// must be done by the search.
1609 template<bool SkipRepetition>
1610 bool Position::is_draw() const {
1612 // Draw by material?
1614 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1617 // Draw by the 50 moves rule?
1618 if (st->rule50 > 99 && !is_mate())
1621 // Draw by repetition?
1622 if (!SkipRepetition)
1624 int i = 4, e = Min(st->rule50, st->pliesFromNull);
1628 StateInfo* stp = st->previous->previous;
1631 stp = stp->previous->previous;
1633 if (stp->key == st->key)
1645 // Explicit template instantiations
1646 template bool Position::is_draw<false>() const;
1647 template bool Position::is_draw<true>() const;
1650 /// Position::is_mate() returns true or false depending on whether the
1651 /// side to move is checkmated.
1653 bool Position::is_mate() const {
1655 return in_check() && !MoveList<MV_LEGAL>(*this).size();
1659 /// Position::init() is a static member function which initializes at startup
1660 /// the various arrays used to compute hash keys and the piece square tables.
1661 /// The latter is a two-step operation: First, the white halves of the tables
1662 /// are copied from PSQT[] tables. Second, the black halves of the tables are
1663 /// initialized by flipping and changing the sign of the white scores.
1665 void Position::init() {
1669 for (Color c = WHITE; c <= BLACK; c++)
1670 for (PieceType pt = PAWN; pt <= KING; pt++)
1671 for (Square s = SQ_A1; s <= SQ_H8; s++)
1672 zobrist[c][pt][s] = rk.rand<Key>();
1674 for (Square s = SQ_A1; s <= SQ_H8; s++)
1675 zobEp[s] = rk.rand<Key>();
1677 for (int i = 0; i < 16; i++)
1678 zobCastle[i] = rk.rand<Key>();
1680 zobSideToMove = rk.rand<Key>();
1681 zobExclusion = rk.rand<Key>();
1683 for (Piece p = WP; p <= WK; p++)
1685 Score ps = make_score(PieceValueMidgame[p], PieceValueEndgame[p]);
1687 for (Square s = SQ_A1; s <= SQ_H8; s++)
1689 pieceSquareTable[p][s] = ps + PSQT[p][s];
1690 pieceSquareTable[p+8][flip(s)] = -pieceSquareTable[p][s];
1696 /// Position::flip_me() flips position with the white and black sides reversed. This
1697 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1699 void Position::flip_me() {
1701 // Make a copy of current position before to start changing
1702 const Position pos(*this, threadID);
1705 threadID = pos.thread();
1708 for (Square s = SQ_A1; s <= SQ_H8; s++)
1709 if (!pos.square_is_empty(s))
1710 put_piece(Piece(pos.piece_on(s) ^ 8), flip(s));
1713 sideToMove = flip(pos.side_to_move());
1716 if (pos.can_castle(WHITE_OO))
1717 set_castle(BLACK_OO, king_square(BLACK), flip(pos.castle_rook_square(WHITE_OO)));
1718 if (pos.can_castle(WHITE_OOO))
1719 set_castle(BLACK_OOO, king_square(BLACK), flip(pos.castle_rook_square(WHITE_OOO)));
1720 if (pos.can_castle(BLACK_OO))
1721 set_castle(WHITE_OO, king_square(WHITE), flip(pos.castle_rook_square(BLACK_OO)));
1722 if (pos.can_castle(BLACK_OOO))
1723 set_castle(WHITE_OOO, king_square(WHITE), flip(pos.castle_rook_square(BLACK_OOO)));
1725 // En passant square
1726 if (pos.st->epSquare != SQ_NONE)
1727 st->epSquare = flip(pos.st->epSquare);
1730 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(flip(sideToMove));
1733 st->key = compute_key();
1734 st->pawnKey = compute_pawn_key();
1735 st->materialKey = compute_material_key();
1737 // Incremental scores
1738 st->value = compute_value();
1741 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1742 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1744 assert(pos_is_ok());
1748 /// Position::pos_is_ok() performs some consitency checks for the position object.
1749 /// This is meant to be helpful when debugging.
1751 bool Position::pos_is_ok(int* failedStep) const {
1753 // What features of the position should be verified?
1754 const bool debugAll = false;
1756 const bool debugBitboards = debugAll || false;
1757 const bool debugKingCount = debugAll || false;
1758 const bool debugKingCapture = debugAll || false;
1759 const bool debugCheckerCount = debugAll || false;
1760 const bool debugKey = debugAll || false;
1761 const bool debugMaterialKey = debugAll || false;
1762 const bool debugPawnKey = debugAll || false;
1763 const bool debugIncrementalEval = debugAll || false;
1764 const bool debugNonPawnMaterial = debugAll || false;
1765 const bool debugPieceCounts = debugAll || false;
1766 const bool debugPieceList = debugAll || false;
1767 const bool debugCastleSquares = debugAll || false;
1769 if (failedStep) *failedStep = 1;
1772 if (side_to_move() != WHITE && side_to_move() != BLACK)
1775 // Are the king squares in the position correct?
1776 if (failedStep) (*failedStep)++;
1777 if (piece_on(king_square(WHITE)) != WK)
1780 if (failedStep) (*failedStep)++;
1781 if (piece_on(king_square(BLACK)) != BK)
1784 // Do both sides have exactly one king?
1785 if (failedStep) (*failedStep)++;
1788 int kingCount[2] = {0, 0};
1789 for (Square s = SQ_A1; s <= SQ_H8; s++)
1790 if (type_of(piece_on(s)) == KING)
1791 kingCount[color_of(piece_on(s))]++;
1793 if (kingCount[0] != 1 || kingCount[1] != 1)
1797 // Can the side to move capture the opponent's king?
1798 if (failedStep) (*failedStep)++;
1799 if (debugKingCapture)
1801 Color us = side_to_move();
1802 Color them = flip(us);
1803 Square ksq = king_square(them);
1804 if (attackers_to(ksq) & pieces(us))
1808 // Is there more than 2 checkers?
1809 if (failedStep) (*failedStep)++;
1810 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1814 if (failedStep) (*failedStep)++;
1817 // The intersection of the white and black pieces must be empty
1818 if ((pieces(WHITE) & pieces(BLACK)) != EmptyBoardBB)
1821 // The union of the white and black pieces must be equal to all
1823 if ((pieces(WHITE) | pieces(BLACK)) != occupied_squares())
1826 // Separate piece type bitboards must have empty intersections
1827 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1828 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1829 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1833 // En passant square OK?
1834 if (failedStep) (*failedStep)++;
1835 if (ep_square() != SQ_NONE)
1837 // The en passant square must be on rank 6, from the point of view of the
1839 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1844 if (failedStep) (*failedStep)++;
1845 if (debugKey && st->key != compute_key())
1848 // Pawn hash key OK?
1849 if (failedStep) (*failedStep)++;
1850 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1853 // Material hash key OK?
1854 if (failedStep) (*failedStep)++;
1855 if (debugMaterialKey && st->materialKey != compute_material_key())
1858 // Incremental eval OK?
1859 if (failedStep) (*failedStep)++;
1860 if (debugIncrementalEval && st->value != compute_value())
1863 // Non-pawn material OK?
1864 if (failedStep) (*failedStep)++;
1865 if (debugNonPawnMaterial)
1867 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1870 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1875 if (failedStep) (*failedStep)++;
1876 if (debugPieceCounts)
1877 for (Color c = WHITE; c <= BLACK; c++)
1878 for (PieceType pt = PAWN; pt <= KING; pt++)
1879 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1882 if (failedStep) (*failedStep)++;
1884 for (Color c = WHITE; c <= BLACK; c++)
1885 for (PieceType pt = PAWN; pt <= KING; pt++)
1886 for (int i = 0; i < pieceCount[c][pt]; i++)
1888 if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1891 if (index[piece_list(c, pt)[i]] != i)
1895 if (failedStep) (*failedStep)++;
1896 if (debugCastleSquares)
1897 for (CastleRight f = WHITE_OO; f <= BLACK_OOO; f = CastleRight(f << 1))
1902 Piece rook = (f & (WHITE_OO | WHITE_OOO) ? WR : BR);
1904 if ( castleRightsMask[castleRookSquare[f]] != (ALL_CASTLES ^ f)
1905 || piece_on(castleRookSquare[f]) != rook)
1909 if (failedStep) *failedStep = 0;