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/>.
41 #include "ucioption.h"
47 static inline bool isZero(char c) { return c == '0'; }
49 struct PieceLetters : public std::map<char, Piece> {
53 operator[]('K') = WK; operator[]('k') = BK;
54 operator[]('Q') = WQ; operator[]('q') = BQ;
55 operator[]('R') = WR; operator[]('r') = BR;
56 operator[]('B') = WB; operator[]('b') = BB;
57 operator[]('N') = WN; operator[]('n') = BN;
58 operator[]('P') = WP; operator[]('p') = BP;
59 operator[](' ') = PIECE_NONE; operator[]('.') = PIECE_NONE_DARK_SQ;
62 char from_piece(Piece p) const {
64 std::map<char, Piece>::const_iterator it;
65 for (it = begin(); it != end(); ++it)
76 //// Constants and variables
79 /// Bonus for having the side to move (modified by Joona Kiiski)
81 static const Score TempoValue = make_score(48, 22);
84 Key Position::zobrist[2][8][64];
85 Key Position::zobEp[64];
86 Key Position::zobCastle[16];
87 Key Position::zobSideToMove;
88 Key Position::zobExclusion;
90 Score Position::PieceSquareTable[16][64];
92 static PieceLetters pieceLetters;
94 // Material values used by SEE, indexed by PieceType
95 const Value Position::seeValues[] = {
96 VALUE_ZERO, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
97 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
103 CheckInfo::CheckInfo(const Position& pos) {
105 Color us = pos.side_to_move();
106 Color them = opposite_color(us);
108 ksq = pos.king_square(them);
109 dcCandidates = pos.discovered_check_candidates(us);
111 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
112 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
113 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
114 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
115 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
116 checkSq[KING] = EmptyBoardBB;
120 /// Position c'tors. Here we always create a copy of the original position
121 /// or the FEN string, we want the new born Position object do not depend
122 /// on any external data so we detach state pointer from the source one.
124 Position::Position(int th) : threadID(th) {}
126 Position::Position(const Position& pos, int th) {
128 memcpy(this, &pos, sizeof(Position));
129 detach(); // Always detach() in copy c'tor to avoid surprises
133 Position::Position(const string& fen, int th) {
140 /// Position::detach() copies the content of the current state and castling
141 /// masks inside the position itself. This is needed when the st pointee could
142 /// become stale, as example because the caller is about to going out of scope.
144 void Position::detach() {
148 st->previous = NULL; // as a safe guard
152 /// Position::from_fen() initializes the position object with the given FEN
153 /// string. This function is not very robust - make sure that input FENs are
154 /// correct (this is assumed to be the responsibility of the GUI).
156 void Position::from_fen(const string& fen) {
158 A FEN string defines a particular position using only the ASCII character set.
160 A FEN string contains six fields. The separator between fields is a space. The fields are:
162 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
163 with rank 1; within each rank, the contents of each square are described from file a through file h.
164 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
165 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
166 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
167 of blank squares), and "/" separate ranks.
169 2) Active color. "w" means white moves next, "b" means black.
171 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
172 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
173 kingside), and/or "q" (Black can castle queenside).
175 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
176 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
177 regardless of whether there is a pawn in position to make an en passant capture.
179 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
180 to determine if a draw can be claimed under the fifty-move rule.
182 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
186 std::istringstream ss(fen);
192 // 1. Piece placement field
193 while (ss.get(token) && token != ' ')
197 file += File(token - '0'); // Skip the given number of files
200 else if (token == '/')
207 if (pieceLetters.find(token) == pieceLetters.end())
210 put_piece(pieceLetters[token], make_square(file, rank));
215 if (!ss.get(token) || (token != 'w' && token != 'b'))
218 sideToMove = (token == 'w' ? WHITE : BLACK);
220 if (!ss.get(token) || token != ' ')
223 // 3. Castling availability
224 while (ss.get(token) && token != ' ')
229 if (!set_castling_rights(token))
233 // 4. En passant square -- ignore if no capture is possible
235 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
236 && (ss.get(row) && (row == '3' || row == '6')))
238 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
239 Color them = opposite_color(sideToMove);
241 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
242 st->epSquare = fenEpSquare;
245 // 5-6. Halfmove clock and fullmove number are not parsed
247 // Various initialisations
248 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
249 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
250 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
251 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
252 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
253 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
255 isChess960 = initialKFile != FILE_E
256 || initialQRFile != FILE_A
257 || initialKRFile != FILE_H;
261 st->key = compute_key();
262 st->pawnKey = compute_pawn_key();
263 st->materialKey = compute_material_key();
264 st->value = compute_value();
265 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
266 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
270 cout << "Error in FEN string: " << fen << endl;
274 /// Position::set_castling_rights() sets castling parameters castling avaiability.
275 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
276 /// that uses the letters of the columns on which the rooks began the game instead
277 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
278 /// associated with the castling right, the traditional castling tag will be replaced
279 /// by the file letter of the involved rook as for the Shredder-FEN.
281 bool Position::set_castling_rights(char token) {
283 Color c = token >= 'a' ? BLACK : WHITE;
284 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
285 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
286 Piece rook = (c == WHITE ? WR : BR);
288 initialKFile = square_file(king_square(c));
289 token = char(toupper(token));
293 for (Square sq = sqH; sq >= sqA; sq--)
294 if (piece_on(sq) == rook)
297 initialKRFile = square_file(sq);
301 else if (token == 'Q')
303 for (Square sq = sqA; sq <= sqH; sq++)
304 if (piece_on(sq) == rook)
307 initialQRFile = square_file(sq);
311 else if (token >= 'A' && token <= 'H')
313 File rookFile = File(token - 'A') + FILE_A;
314 if (rookFile < initialKFile)
317 initialQRFile = rookFile;
322 initialKRFile = rookFile;
331 /// Position::to_fen() returns a FEN representation of the position. In case
332 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
334 const string Position::to_fen() const {
340 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
342 for (File file = FILE_A; file <= FILE_H; file++)
344 sq = make_square(file, rank);
346 if (square_is_occupied(sq))
349 fen += pieceLetters.from_piece(piece_on(sq));
359 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
360 fen.erase(--fen.end());
361 fen += (sideToMove == WHITE ? " w " : " b ");
363 if (st->castleRights != CASTLES_NONE)
365 if (can_castle_kingside(WHITE))
366 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
368 if (can_castle_queenside(WHITE))
369 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
371 if (can_castle_kingside(BLACK))
372 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
374 if (can_castle_queenside(BLACK))
375 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
379 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
384 /// Position::print() prints an ASCII representation of the position to
385 /// the standard output. If a move is given then also the san is print.
387 void Position::print(Move move) const {
389 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
390 static bool requestPending = false;
392 // Check for reentrancy, as example when called from inside
393 // MovePicker that is used also here in move_to_san()
397 requestPending = true;
401 Position p(*this, thread());
402 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
403 cout << "\nMove is: " << dd << move_to_san(p, move);
406 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
408 cout << dottedLine << '|';
409 for (File file = FILE_A; file <= FILE_H; file++)
411 Square sq = make_square(file, rank);
412 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
413 Piece piece = piece_on(sq);
415 if (piece == PIECE_NONE && square_color(sq) == DARK)
416 piece = PIECE_NONE_DARK_SQ;
418 cout << c << pieceLetters.from_piece(piece) << c << '|';
421 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
422 requestPending = false;
426 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
427 /// king) pieces for the given color and for the given pinner type. Or, when
428 /// template parameter FindPinned is false, the pieces of the given color
429 /// candidate for a discovery check against the enemy king.
430 /// Bitboard checkersBB must be already updated when looking for pinners.
432 template<bool FindPinned>
433 Bitboard Position::hidden_checkers(Color c) const {
435 Bitboard result = EmptyBoardBB;
436 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
438 // Pinned pieces protect our king, dicovery checks attack
440 Square ksq = king_square(FindPinned ? c : opposite_color(c));
442 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
443 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
445 if (FindPinned && pinners)
446 pinners &= ~st->checkersBB;
450 Square s = pop_1st_bit(&pinners);
451 Bitboard b = squares_between(s, ksq) & occupied_squares();
455 if ( !(b & (b - 1)) // Only one bit set?
456 && (b & pieces_of_color(c))) // Is an our piece?
463 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
464 /// king) pieces for the given color. Note that checkersBB bitboard must
465 /// be already updated.
467 Bitboard Position::pinned_pieces(Color c) const {
469 return hidden_checkers<true>(c);
473 /// Position:discovered_check_candidates() returns a bitboard containing all
474 /// pieces for the given side which are candidates for giving a discovered
475 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
476 /// to be already updated.
478 Bitboard Position::discovered_check_candidates(Color c) const {
480 return hidden_checkers<false>(c);
483 /// Position::attackers_to() computes a bitboard containing all pieces which
484 /// attacks a given square.
486 Bitboard Position::attackers_to(Square s) const {
488 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
489 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
490 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
491 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
492 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
493 | (attacks_from<KING>(s) & pieces(KING));
496 /// Position::attacks_from() computes a bitboard of all attacks
497 /// of a given piece put in a given square.
499 Bitboard Position::attacks_from(Piece p, Square s) const {
501 assert(square_is_ok(s));
505 case WP: return attacks_from<PAWN>(s, WHITE);
506 case BP: return attacks_from<PAWN>(s, BLACK);
507 case WN: case BN: return attacks_from<KNIGHT>(s);
508 case WB: case BB: return attacks_from<BISHOP>(s);
509 case WR: case BR: return attacks_from<ROOK>(s);
510 case WQ: case BQ: return attacks_from<QUEEN>(s);
511 case WK: case BK: return attacks_from<KING>(s);
518 /// Position::move_attacks_square() tests whether a move from the current
519 /// position attacks a given square.
521 bool Position::move_attacks_square(Move m, Square s) const {
523 assert(move_is_ok(m));
524 assert(square_is_ok(s));
526 Square f = move_from(m), t = move_to(m);
528 assert(square_is_occupied(f));
530 if (bit_is_set(attacks_from(piece_on(f), t), s))
533 // Move the piece and scan for X-ray attacks behind it
534 Bitboard occ = occupied_squares();
535 Color us = color_of_piece_on(f);
538 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
539 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
541 // If we have attacks we need to verify that are caused by our move
542 // and are not already existent ones.
543 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
547 /// Position::find_checkers() computes the checkersBB bitboard, which
548 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
549 /// currently works by calling Position::attackers_to, which is probably
550 /// inefficient. Consider rewriting this function to use the last move
551 /// played, like in non-bitboard versions of Glaurung.
553 void Position::find_checkers() {
555 Color us = side_to_move();
556 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
560 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
562 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
565 assert(move_is_ok(m));
566 assert(pinned == pinned_pieces(side_to_move()));
568 // Castling moves are checked for legality during move generation.
569 if (move_is_castle(m))
572 Color us = side_to_move();
573 Square from = move_from(m);
575 assert(color_of_piece_on(from) == us);
576 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
578 // En passant captures are a tricky special case. Because they are
579 // rather uncommon, we do it simply by testing whether the king is attacked
580 // after the move is made
583 Color them = opposite_color(us);
584 Square to = move_to(m);
585 Square capsq = make_square(square_file(to), square_rank(from));
586 Bitboard b = occupied_squares();
587 Square ksq = king_square(us);
589 assert(to == ep_square());
590 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
591 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
592 assert(piece_on(to) == PIECE_NONE);
595 clear_bit(&b, capsq);
598 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
599 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
602 // If the moving piece is a king, check whether the destination
603 // square is attacked by the opponent.
604 if (type_of_piece_on(from) == KING)
605 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
607 // A non-king move is legal if and only if it is not pinned or it
608 // is moving along the ray towards or away from the king.
610 || !bit_is_set(pinned, from)
611 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
615 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
617 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
621 Color us = side_to_move();
622 Square from = move_from(m);
623 Square to = move_to(m);
625 // King moves and en-passant captures are verified in pl_move_is_legal()
626 if (type_of_piece_on(from) == KING || move_is_ep(m))
627 return pl_move_is_legal(m, pinned);
629 Bitboard target = checkers();
630 Square checksq = pop_1st_bit(&target);
632 if (target) // double check ?
635 // Our move must be a blocking evasion or a capture of the checking piece
636 target = squares_between(checksq, king_square(us)) | checkers();
637 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
641 /// Position::move_is_check() tests whether a pseudo-legal move is a check
643 bool Position::move_is_check(Move m) const {
645 return move_is_check(m, CheckInfo(*this));
648 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
651 assert(move_is_ok(m));
652 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
653 assert(color_of_piece_on(move_from(m)) == side_to_move());
654 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
656 Square from = move_from(m);
657 Square to = move_to(m);
658 PieceType pt = type_of_piece_on(from);
661 if (bit_is_set(ci.checkSq[pt], to))
665 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
667 // For pawn and king moves we need to verify also direction
668 if ( (pt != PAWN && pt != KING)
669 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
673 // Can we skip the ugly special cases ?
674 if (!move_is_special(m))
677 Color us = side_to_move();
678 Bitboard b = occupied_squares();
680 // Promotion with check ?
681 if (move_is_promotion(m))
685 switch (move_promotion_piece(m))
688 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
690 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
692 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
694 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
700 // En passant capture with check ? We have already handled the case
701 // of direct checks and ordinary discovered check, the only case we
702 // need to handle is the unusual case of a discovered check through
703 // the captured pawn.
706 Square capsq = make_square(square_file(to), square_rank(from));
708 clear_bit(&b, capsq);
710 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
711 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
714 // Castling with check ?
715 if (move_is_castle(m))
717 Square kfrom, kto, rfrom, rto;
723 kto = relative_square(us, SQ_G1);
724 rto = relative_square(us, SQ_F1);
726 kto = relative_square(us, SQ_C1);
727 rto = relative_square(us, SQ_D1);
729 clear_bit(&b, kfrom);
730 clear_bit(&b, rfrom);
733 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
740 /// Position::do_move() makes a move, and saves all information necessary
741 /// to a StateInfo object. The move is assumed to be legal.
742 /// Pseudo-legal moves should be filtered out before this function is called.
744 void Position::do_move(Move m, StateInfo& newSt) {
747 do_move(m, newSt, ci, move_is_check(m, ci));
750 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
753 assert(move_is_ok(m));
757 // Copy some fields of old state to our new StateInfo object except the
758 // ones which are recalculated from scratch anyway, then switch our state
759 // pointer to point to the new, ready to be updated, state.
760 struct ReducedStateInfo {
761 Key pawnKey, materialKey;
762 int castleRights, rule50, gamePly, pliesFromNull;
768 memcpy(&newSt, st, sizeof(ReducedStateInfo));
772 // Save the current key to the history[] array, in order to be able to
773 // detect repetition draws.
774 history[st->gamePly++] = key;
776 // Update side to move
777 key ^= zobSideToMove;
779 // Increment the 50 moves rule draw counter. Resetting it to zero in the
780 // case of non-reversible moves is taken care of later.
784 if (move_is_castle(m))
791 Color us = side_to_move();
792 Color them = opposite_color(us);
793 Square from = move_from(m);
794 Square to = move_to(m);
795 bool ep = move_is_ep(m);
796 bool pm = move_is_promotion(m);
798 Piece piece = piece_on(from);
799 PieceType pt = type_of_piece(piece);
800 PieceType capture = ep ? PAWN : type_of_piece_on(to);
802 assert(color_of_piece_on(from) == us);
803 assert(color_of_piece_on(to) == them || square_is_empty(to));
804 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
805 assert(!pm || relative_rank(us, to) == RANK_8);
808 do_capture_move(key, capture, them, to, ep);
811 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
813 // Reset en passant square
814 if (st->epSquare != SQ_NONE)
816 key ^= zobEp[st->epSquare];
817 st->epSquare = SQ_NONE;
820 // Update castle rights, try to shortcut a common case
821 int cm = castleRightsMask[from] & castleRightsMask[to];
822 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
824 key ^= zobCastle[st->castleRights];
825 st->castleRights &= castleRightsMask[from];
826 st->castleRights &= castleRightsMask[to];
827 key ^= zobCastle[st->castleRights];
830 // Prefetch TT access as soon as we know key is updated
831 prefetch((char*)TT.first_entry(key));
834 Bitboard move_bb = make_move_bb(from, to);
835 do_move_bb(&(byColorBB[us]), move_bb);
836 do_move_bb(&(byTypeBB[pt]), move_bb);
837 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
839 board[to] = board[from];
840 board[from] = PIECE_NONE;
842 // Update piece lists, note that index[from] is not updated and
843 // becomes stale. This works as long as index[] is accessed just
844 // by known occupied squares.
845 index[to] = index[from];
846 pieceList[us][pt][index[to]] = to;
848 // If the moving piece was a pawn do some special extra work
851 // Reset rule 50 draw counter
854 // Update pawn hash key and prefetch in L1/L2 cache
855 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
856 prefetchPawn(st->pawnKey, threadID);
858 // Set en passant square, only if moved pawn can be captured
859 if ((to ^ from) == 16)
861 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
863 st->epSquare = Square((int(from) + int(to)) / 2);
864 key ^= zobEp[st->epSquare];
868 if (pm) // promotion ?
870 PieceType promotion = move_promotion_piece(m);
872 assert(promotion >= KNIGHT && promotion <= QUEEN);
874 // Insert promoted piece instead of pawn
875 clear_bit(&(byTypeBB[PAWN]), to);
876 set_bit(&(byTypeBB[promotion]), to);
877 board[to] = piece_of_color_and_type(us, promotion);
879 // Update piece counts
880 pieceCount[us][promotion]++;
881 pieceCount[us][PAWN]--;
883 // Update material key
884 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
885 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
887 // Update piece lists, move the last pawn at index[to] position
888 // and shrink the list. Add a new promotion piece to the list.
889 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
890 index[lastPawnSquare] = index[to];
891 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
892 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
893 index[to] = pieceCount[us][promotion] - 1;
894 pieceList[us][promotion][index[to]] = to;
896 // Partially revert hash keys update
897 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
898 st->pawnKey ^= zobrist[us][PAWN][to];
900 // Partially revert and update incremental scores
901 st->value -= pst(us, PAWN, to);
902 st->value += pst(us, promotion, to);
905 st->npMaterial[us] += PieceValueMidgame[promotion];
909 // Update incremental scores
910 st->value += pst_delta(piece, from, to);
913 st->capturedType = capture;
915 // Update the key with the final value
918 // Update checkers bitboard, piece must be already moved
919 st->checkersBB = EmptyBoardBB;
924 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
928 if (bit_is_set(ci.checkSq[pt], to))
929 st->checkersBB = SetMaskBB[to];
932 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
935 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
938 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
944 sideToMove = opposite_color(sideToMove);
945 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
951 /// Position::do_capture_move() is a private method used to update captured
952 /// piece info. It is called from the main Position::do_move function.
954 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
956 assert(capture != KING);
960 // If the captured piece was a pawn, update pawn hash key,
961 // otherwise update non-pawn material.
964 if (ep) // en passant ?
966 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
968 assert(to == st->epSquare);
969 assert(relative_rank(opposite_color(them), to) == RANK_6);
970 assert(piece_on(to) == PIECE_NONE);
971 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
973 board[capsq] = PIECE_NONE;
975 st->pawnKey ^= zobrist[them][PAWN][capsq];
978 st->npMaterial[them] -= PieceValueMidgame[capture];
980 // Remove captured piece
981 clear_bit(&(byColorBB[them]), capsq);
982 clear_bit(&(byTypeBB[capture]), capsq);
983 clear_bit(&(byTypeBB[0]), capsq);
986 key ^= zobrist[them][capture][capsq];
988 // Update incremental scores
989 st->value -= pst(them, capture, capsq);
991 // Update piece count
992 pieceCount[them][capture]--;
994 // Update material hash key
995 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
997 // Update piece list, move the last piece at index[capsq] position
999 // WARNING: This is a not perfectly revresible operation. When we
1000 // will reinsert the captured piece in undo_move() we will put it
1001 // at the end of the list and not in its original place, it means
1002 // index[] and pieceList[] are not guaranteed to be invariant to a
1003 // do_move() + undo_move() sequence.
1004 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1005 index[lastPieceSquare] = index[capsq];
1006 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1007 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1009 // Reset rule 50 counter
1014 /// Position::do_castle_move() is a private method used to make a castling
1015 /// move. It is called from the main Position::do_move function. Note that
1016 /// castling moves are encoded as "king captures friendly rook" moves, for
1017 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1019 void Position::do_castle_move(Move m) {
1021 assert(move_is_ok(m));
1022 assert(move_is_castle(m));
1024 Color us = side_to_move();
1025 Color them = opposite_color(us);
1027 // Reset capture field
1028 st->capturedType = PIECE_TYPE_NONE;
1030 // Find source squares for king and rook
1031 Square kfrom = move_from(m);
1032 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1035 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1036 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1038 // Find destination squares for king and rook
1039 if (rfrom > kfrom) // O-O
1041 kto = relative_square(us, SQ_G1);
1042 rto = relative_square(us, SQ_F1);
1044 kto = relative_square(us, SQ_C1);
1045 rto = relative_square(us, SQ_D1);
1048 // Remove pieces from source squares:
1049 clear_bit(&(byColorBB[us]), kfrom);
1050 clear_bit(&(byTypeBB[KING]), kfrom);
1051 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1052 clear_bit(&(byColorBB[us]), rfrom);
1053 clear_bit(&(byTypeBB[ROOK]), rfrom);
1054 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1056 // Put pieces on destination squares:
1057 set_bit(&(byColorBB[us]), kto);
1058 set_bit(&(byTypeBB[KING]), kto);
1059 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1060 set_bit(&(byColorBB[us]), rto);
1061 set_bit(&(byTypeBB[ROOK]), rto);
1062 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1064 // Update board array
1065 Piece king = piece_of_color_and_type(us, KING);
1066 Piece rook = piece_of_color_and_type(us, ROOK);
1067 board[kfrom] = board[rfrom] = PIECE_NONE;
1071 // Update piece lists
1072 pieceList[us][KING][index[kfrom]] = kto;
1073 pieceList[us][ROOK][index[rfrom]] = rto;
1074 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1075 index[kto] = index[kfrom];
1078 // Update incremental scores
1079 st->value += pst_delta(king, kfrom, kto);
1080 st->value += pst_delta(rook, rfrom, rto);
1083 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1084 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1086 // Clear en passant square
1087 if (st->epSquare != SQ_NONE)
1089 st->key ^= zobEp[st->epSquare];
1090 st->epSquare = SQ_NONE;
1093 // Update castling rights
1094 st->key ^= zobCastle[st->castleRights];
1095 st->castleRights &= castleRightsMask[kfrom];
1096 st->key ^= zobCastle[st->castleRights];
1098 // Reset rule 50 counter
1101 // Update checkers BB
1102 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1105 sideToMove = opposite_color(sideToMove);
1106 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1112 /// Position::undo_move() unmakes a move. When it returns, the position should
1113 /// be restored to exactly the same state as before the move was made.
1115 void Position::undo_move(Move m) {
1118 assert(move_is_ok(m));
1120 sideToMove = opposite_color(sideToMove);
1122 if (move_is_castle(m))
1124 undo_castle_move(m);
1128 Color us = side_to_move();
1129 Color them = opposite_color(us);
1130 Square from = move_from(m);
1131 Square to = move_to(m);
1132 bool ep = move_is_ep(m);
1133 bool pm = move_is_promotion(m);
1135 PieceType pt = type_of_piece_on(to);
1137 assert(square_is_empty(from));
1138 assert(color_of_piece_on(to) == us);
1139 assert(!pm || relative_rank(us, to) == RANK_8);
1140 assert(!ep || to == st->previous->epSquare);
1141 assert(!ep || relative_rank(us, to) == RANK_6);
1142 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1144 if (pm) // promotion ?
1146 PieceType promotion = move_promotion_piece(m);
1149 assert(promotion >= KNIGHT && promotion <= QUEEN);
1150 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1152 // Replace promoted piece with a pawn
1153 clear_bit(&(byTypeBB[promotion]), to);
1154 set_bit(&(byTypeBB[PAWN]), to);
1156 // Update piece counts
1157 pieceCount[us][promotion]--;
1158 pieceCount[us][PAWN]++;
1160 // Update piece list replacing promotion piece with a pawn
1161 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1162 index[lastPromotionSquare] = index[to];
1163 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1164 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1165 index[to] = pieceCount[us][PAWN] - 1;
1166 pieceList[us][PAWN][index[to]] = to;
1169 // Put the piece back at the source square
1170 Bitboard move_bb = make_move_bb(to, from);
1171 do_move_bb(&(byColorBB[us]), move_bb);
1172 do_move_bb(&(byTypeBB[pt]), move_bb);
1173 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1175 board[from] = piece_of_color_and_type(us, pt);
1176 board[to] = PIECE_NONE;
1178 // Update piece list
1179 index[from] = index[to];
1180 pieceList[us][pt][index[from]] = from;
1182 if (st->capturedType)
1187 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1189 assert(st->capturedType != KING);
1190 assert(!ep || square_is_empty(capsq));
1192 // Restore the captured piece
1193 set_bit(&(byColorBB[them]), capsq);
1194 set_bit(&(byTypeBB[st->capturedType]), capsq);
1195 set_bit(&(byTypeBB[0]), capsq);
1197 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1199 // Update piece count
1200 pieceCount[them][st->capturedType]++;
1202 // Update piece list, add a new captured piece in capsq square
1203 index[capsq] = pieceCount[them][st->capturedType] - 1;
1204 pieceList[them][st->capturedType][index[capsq]] = capsq;
1207 // Finally point our state pointer back to the previous state
1214 /// Position::undo_castle_move() is a private method used to unmake a castling
1215 /// move. It is called from the main Position::undo_move function. Note that
1216 /// castling moves are encoded as "king captures friendly rook" moves, for
1217 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1219 void Position::undo_castle_move(Move m) {
1221 assert(move_is_ok(m));
1222 assert(move_is_castle(m));
1224 // When we have arrived here, some work has already been done by
1225 // Position::undo_move. In particular, the side to move has been switched,
1226 // so the code below is correct.
1227 Color us = side_to_move();
1229 // Find source squares for king and rook
1230 Square kfrom = move_from(m);
1231 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1234 // Find destination squares for king and rook
1235 if (rfrom > kfrom) // O-O
1237 kto = relative_square(us, SQ_G1);
1238 rto = relative_square(us, SQ_F1);
1240 kto = relative_square(us, SQ_C1);
1241 rto = relative_square(us, SQ_D1);
1244 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1245 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1247 // Remove pieces from destination squares:
1248 clear_bit(&(byColorBB[us]), kto);
1249 clear_bit(&(byTypeBB[KING]), kto);
1250 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1251 clear_bit(&(byColorBB[us]), rto);
1252 clear_bit(&(byTypeBB[ROOK]), rto);
1253 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1255 // Put pieces on source squares:
1256 set_bit(&(byColorBB[us]), kfrom);
1257 set_bit(&(byTypeBB[KING]), kfrom);
1258 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1259 set_bit(&(byColorBB[us]), rfrom);
1260 set_bit(&(byTypeBB[ROOK]), rfrom);
1261 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1264 board[rto] = board[kto] = PIECE_NONE;
1265 board[rfrom] = piece_of_color_and_type(us, ROOK);
1266 board[kfrom] = piece_of_color_and_type(us, KING);
1268 // Update piece lists
1269 pieceList[us][KING][index[kto]] = kfrom;
1270 pieceList[us][ROOK][index[rto]] = rfrom;
1271 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1272 index[kfrom] = index[kto];
1275 // Finally point our state pointer back to the previous state
1282 /// Position::do_null_move makes() a "null move": It switches the side to move
1283 /// and updates the hash key without executing any move on the board.
1285 void Position::do_null_move(StateInfo& backupSt) {
1288 assert(!is_check());
1290 // Back up the information necessary to undo the null move to the supplied
1291 // StateInfo object.
1292 // Note that differently from normal case here backupSt is actually used as
1293 // a backup storage not as a new state to be used.
1294 backupSt.key = st->key;
1295 backupSt.epSquare = st->epSquare;
1296 backupSt.value = st->value;
1297 backupSt.previous = st->previous;
1298 backupSt.pliesFromNull = st->pliesFromNull;
1299 st->previous = &backupSt;
1301 // Save the current key to the history[] array, in order to be able to
1302 // detect repetition draws.
1303 history[st->gamePly++] = st->key;
1305 // Update the necessary information
1306 if (st->epSquare != SQ_NONE)
1307 st->key ^= zobEp[st->epSquare];
1309 st->key ^= zobSideToMove;
1310 prefetch((char*)TT.first_entry(st->key));
1312 sideToMove = opposite_color(sideToMove);
1313 st->epSquare = SQ_NONE;
1315 st->pliesFromNull = 0;
1316 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1320 /// Position::undo_null_move() unmakes a "null move".
1322 void Position::undo_null_move() {
1325 assert(!is_check());
1327 // Restore information from the our backup StateInfo object
1328 StateInfo* backupSt = st->previous;
1329 st->key = backupSt->key;
1330 st->epSquare = backupSt->epSquare;
1331 st->value = backupSt->value;
1332 st->previous = backupSt->previous;
1333 st->pliesFromNull = backupSt->pliesFromNull;
1335 // Update the necessary information
1336 sideToMove = opposite_color(sideToMove);
1342 /// Position::see() is a static exchange evaluator: It tries to estimate the
1343 /// material gain or loss resulting from a move. There are three versions of
1344 /// this function: One which takes a destination square as input, one takes a
1345 /// move, and one which takes a 'from' and a 'to' square. The function does
1346 /// not yet understand promotions captures.
1348 int Position::see(Move m) const {
1350 assert(move_is_ok(m));
1351 return see(move_from(m), move_to(m));
1354 int Position::see_sign(Move m) const {
1356 assert(move_is_ok(m));
1358 Square from = move_from(m);
1359 Square to = move_to(m);
1361 // Early return if SEE cannot be negative because captured piece value
1362 // is not less then capturing one. Note that king moves always return
1363 // here because king midgame value is set to 0.
1364 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1367 return see(from, to);
1370 int Position::see(Square from, Square to) const {
1372 Bitboard occ, attackers, stmAttackers, b;
1373 int swapList[32], slIndex = 1;
1374 PieceType capturedType, pt;
1377 assert(square_is_ok(from));
1378 assert(square_is_ok(to));
1380 capturedType = type_of_piece_on(to);
1382 // King cannot be recaptured
1383 if (capturedType == KING)
1384 return seeValues[capturedType];
1386 occ = occupied_squares();
1388 // Handle en passant moves
1389 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1391 Square capQq = (side_to_move() == WHITE) ? (to - DELTA_N) : (to - DELTA_S);
1393 assert(capturedType == PIECE_TYPE_NONE);
1394 assert(type_of_piece_on(capQq) == PAWN);
1396 // Remove the captured pawn
1397 clear_bit(&occ, capQq);
1398 capturedType = PAWN;
1401 // Find all attackers to the destination square, with the moving piece
1402 // removed, but possibly an X-ray attacker added behind it.
1403 clear_bit(&occ, from);
1404 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1405 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1406 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1407 | (attacks_from<KING>(to) & pieces(KING))
1408 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1409 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1411 // If the opponent has no attackers we are finished
1412 stm = opposite_color(color_of_piece_on(from));
1413 stmAttackers = attackers & pieces_of_color(stm);
1415 return seeValues[capturedType];
1417 // The destination square is defended, which makes things rather more
1418 // difficult to compute. We proceed by building up a "swap list" containing
1419 // the material gain or loss at each stop in a sequence of captures to the
1420 // destination square, where the sides alternately capture, and always
1421 // capture with the least valuable piece. After each capture, we look for
1422 // new X-ray attacks from behind the capturing piece.
1423 swapList[0] = seeValues[capturedType];
1424 capturedType = type_of_piece_on(from);
1427 // Locate the least valuable attacker for the side to move. The loop
1428 // below looks like it is potentially infinite, but it isn't. We know
1429 // that the side to move still has at least one attacker left.
1430 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1433 // Remove the attacker we just found from the 'attackers' bitboard,
1434 // and scan for new X-ray attacks behind the attacker.
1435 b = stmAttackers & pieces(pt);
1436 occ ^= (b & (~b + 1));
1437 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1438 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1440 attackers &= occ; // Cut out pieces we've already done
1442 // Add the new entry to the swap list
1443 assert(slIndex < 32);
1444 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1447 // Remember the value of the capturing piece, and change the side to move
1448 // before beginning the next iteration
1450 stm = opposite_color(stm);
1451 stmAttackers = attackers & pieces_of_color(stm);
1453 // Stop after a king capture
1454 if (pt == KING && stmAttackers)
1456 assert(slIndex < 32);
1457 swapList[slIndex++] = QueenValueMidgame*10;
1460 } while (stmAttackers);
1462 // Having built the swap list, we negamax through it to find the best
1463 // achievable score from the point of view of the side to move
1465 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1471 /// Position::clear() erases the position object to a pristine state, with an
1472 /// empty board, white to move, and no castling rights.
1474 void Position::clear() {
1477 memset(st, 0, sizeof(StateInfo));
1478 st->epSquare = SQ_NONE;
1479 startPosPlyCounter = 0;
1481 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1482 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1483 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1484 memset(index, 0, sizeof(int) * 64);
1486 for (int i = 0; i < 64; i++)
1487 board[i] = PIECE_NONE;
1489 for (int i = 0; i < 8; i++)
1490 for (int j = 0; j < 16; j++)
1491 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1493 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1494 castleRightsMask[sq] = ALL_CASTLES;
1497 initialKFile = FILE_E;
1498 initialKRFile = FILE_H;
1499 initialQRFile = FILE_A;
1503 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1504 /// UCI interface code, whenever a non-reversible move is made in a
1505 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1506 /// for the program to handle games of arbitrary length, as long as the GUI
1507 /// handles draws by the 50 move rule correctly.
1509 void Position::reset_game_ply() {
1514 void Position::inc_startpos_ply_counter() {
1516 startPosPlyCounter++;
1519 /// Position::put_piece() puts a piece on the given square of the board,
1520 /// updating the board array, bitboards, and piece counts.
1522 void Position::put_piece(Piece p, Square s) {
1524 Color c = color_of_piece(p);
1525 PieceType pt = type_of_piece(p);
1528 index[s] = pieceCount[c][pt];
1529 pieceList[c][pt][index[s]] = s;
1531 set_bit(&(byTypeBB[pt]), s);
1532 set_bit(&(byColorBB[c]), s);
1533 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1535 pieceCount[c][pt]++;
1539 /// Position::allow_oo() gives the given side the right to castle kingside.
1540 /// Used when setting castling rights during parsing of FEN strings.
1542 void Position::allow_oo(Color c) {
1544 st->castleRights |= (1 + int(c));
1548 /// Position::allow_ooo() gives the given side the right to castle queenside.
1549 /// Used when setting castling rights during parsing of FEN strings.
1551 void Position::allow_ooo(Color c) {
1553 st->castleRights |= (4 + 4*int(c));
1557 /// Position::compute_key() computes the hash key of the position. The hash
1558 /// key is usually updated incrementally as moves are made and unmade, the
1559 /// compute_key() function is only used when a new position is set up, and
1560 /// to verify the correctness of the hash key when running in debug mode.
1562 Key Position::compute_key() const {
1564 Key result = Key(0ULL);
1566 for (Square s = SQ_A1; s <= SQ_H8; s++)
1567 if (square_is_occupied(s))
1568 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1570 if (ep_square() != SQ_NONE)
1571 result ^= zobEp[ep_square()];
1573 result ^= zobCastle[st->castleRights];
1574 if (side_to_move() == BLACK)
1575 result ^= zobSideToMove;
1581 /// Position::compute_pawn_key() computes the hash key of the position. The
1582 /// hash key is usually updated incrementally as moves are made and unmade,
1583 /// the compute_pawn_key() function is only used when a new position is set
1584 /// up, and to verify the correctness of the pawn hash key when running in
1587 Key Position::compute_pawn_key() const {
1589 Key result = Key(0ULL);
1593 for (Color c = WHITE; c <= BLACK; c++)
1595 b = pieces(PAWN, c);
1598 s = pop_1st_bit(&b);
1599 result ^= zobrist[c][PAWN][s];
1606 /// Position::compute_material_key() computes the hash key of the position.
1607 /// The hash key is usually updated incrementally as moves are made and unmade,
1608 /// the compute_material_key() function is only used when a new position is set
1609 /// up, and to verify the correctness of the material hash key when running in
1612 Key Position::compute_material_key() const {
1614 Key result = Key(0ULL);
1615 for (Color c = WHITE; c <= BLACK; c++)
1616 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1618 int count = piece_count(c, pt);
1619 for (int i = 0; i < count; i++)
1620 result ^= zobrist[c][pt][i];
1626 /// Position::compute_value() compute the incremental scores for the middle
1627 /// game and the endgame. These functions are used to initialize the incremental
1628 /// scores when a new position is set up, and to verify that the scores are correctly
1629 /// updated by do_move and undo_move when the program is running in debug mode.
1630 Score Position::compute_value() const {
1632 Score result = SCORE_ZERO;
1636 for (Color c = WHITE; c <= BLACK; c++)
1637 for (PieceType pt = PAWN; pt <= KING; pt++)
1642 s = pop_1st_bit(&b);
1643 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1644 result += pst(c, pt, s);
1648 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1653 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1654 /// game material score for the given side. Material scores are updated
1655 /// incrementally during the search, this function is only used while
1656 /// initializing a new Position object.
1658 Value Position::compute_non_pawn_material(Color c) const {
1660 Value result = VALUE_ZERO;
1662 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1664 Bitboard b = pieces(pt, c);
1667 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1670 result += PieceValueMidgame[pt];
1677 /// Position::is_draw() tests whether the position is drawn by material,
1678 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1679 /// must be done by the search.
1680 // FIXME: Currently we are not handling 50 move rule correctly when in check
1682 bool Position::is_draw() const {
1684 // Draw by material?
1686 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1689 // Draw by the 50 moves rule?
1690 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1693 // Draw by repetition?
1694 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1695 if (history[st->gamePly - i] == st->key)
1702 /// Position::is_mate() returns true or false depending on whether the
1703 /// side to move is checkmated.
1705 bool Position::is_mate() const {
1707 MoveStack moves[256];
1708 return is_check() && (generate_moves(*this, moves) == moves);
1712 /// Position::has_mate_threat() tests whether the side to move is under
1713 /// a threat of being mated in one from the current position.
1715 bool Position::has_mate_threat() {
1717 MoveStack mlist[256], *last, *cur;
1719 bool mateFound = false;
1721 // If we are under check it's up to evasions to do the job
1725 // First pass the move to our opponent doing a null move
1728 // Then generate pseudo-legal moves that give check
1729 last = generate_non_capture_checks(*this, mlist);
1730 last = generate_captures(*this, last);
1732 // Loop through the moves, and see if one of them gives mate
1733 Bitboard pinned = pinned_pieces(sideToMove);
1734 CheckInfo ci(*this);
1735 for (cur = mlist; cur != last && !mateFound; cur++)
1737 Move move = cur->move;
1738 if ( !pl_move_is_legal(move, pinned)
1739 || !move_is_check(move, ci))
1742 do_move(move, st2, ci, true);
1755 /// Position::init_zobrist() is a static member function which initializes at
1756 /// startup the various arrays used to compute hash keys.
1758 void Position::init_zobrist() {
1762 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1763 zobrist[i][j][k] = Key(genrand_int64());
1765 for (i = 0; i < 64; i++)
1766 zobEp[i] = Key(genrand_int64());
1768 for (i = 0; i < 16; i++)
1769 zobCastle[i] = Key(genrand_int64());
1771 zobSideToMove = Key(genrand_int64());
1772 zobExclusion = Key(genrand_int64());
1776 /// Position::init_piece_square_tables() initializes the piece square tables.
1777 /// This is a two-step operation: First, the white halves of the tables are
1778 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1779 /// of the tables are initialized by mirroring and changing the sign of the
1780 /// corresponding white scores.
1782 void Position::init_piece_square_tables() {
1784 for (Square s = SQ_A1; s <= SQ_H8; s++)
1785 for (Piece p = WP; p <= WK; p++)
1786 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1788 for (Square s = SQ_A1; s <= SQ_H8; s++)
1789 for (Piece p = BP; p <= BK; p++)
1790 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1794 /// Position::flipped_copy() makes a copy of the input position, but with
1795 /// the white and black sides reversed. This is only useful for debugging,
1796 /// especially for finding evaluation symmetry bugs.
1798 void Position::flipped_copy(const Position& pos) {
1800 assert(pos.is_ok());
1803 threadID = pos.thread();
1806 for (Square s = SQ_A1; s <= SQ_H8; s++)
1807 if (!pos.square_is_empty(s))
1808 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1811 sideToMove = opposite_color(pos.side_to_move());
1814 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1815 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1816 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1817 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1819 initialKFile = pos.initialKFile;
1820 initialKRFile = pos.initialKRFile;
1821 initialQRFile = pos.initialQRFile;
1823 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1824 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1825 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1826 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1827 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1828 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1830 // En passant square
1831 if (pos.st->epSquare != SQ_NONE)
1832 st->epSquare = flip_square(pos.st->epSquare);
1838 st->key = compute_key();
1839 st->pawnKey = compute_pawn_key();
1840 st->materialKey = compute_material_key();
1842 // Incremental scores
1843 st->value = compute_value();
1846 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1847 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1853 /// Position::is_ok() performs some consitency checks for the position object.
1854 /// This is meant to be helpful when debugging.
1856 bool Position::is_ok(int* failedStep) const {
1858 // What features of the position should be verified?
1859 static const bool debugBitboards = false;
1860 static const bool debugKingCount = false;
1861 static const bool debugKingCapture = false;
1862 static const bool debugCheckerCount = false;
1863 static const bool debugKey = false;
1864 static const bool debugMaterialKey = false;
1865 static const bool debugPawnKey = false;
1866 static const bool debugIncrementalEval = false;
1867 static const bool debugNonPawnMaterial = false;
1868 static const bool debugPieceCounts = false;
1869 static const bool debugPieceList = false;
1870 static const bool debugCastleSquares = false;
1872 if (failedStep) *failedStep = 1;
1875 if (!color_is_ok(side_to_move()))
1878 // Are the king squares in the position correct?
1879 if (failedStep) (*failedStep)++;
1880 if (piece_on(king_square(WHITE)) != WK)
1883 if (failedStep) (*failedStep)++;
1884 if (piece_on(king_square(BLACK)) != BK)
1888 if (failedStep) (*failedStep)++;
1889 if (!file_is_ok(initialKRFile))
1892 if (!file_is_ok(initialQRFile))
1895 // Do both sides have exactly one king?
1896 if (failedStep) (*failedStep)++;
1899 int kingCount[2] = {0, 0};
1900 for (Square s = SQ_A1; s <= SQ_H8; s++)
1901 if (type_of_piece_on(s) == KING)
1902 kingCount[color_of_piece_on(s)]++;
1904 if (kingCount[0] != 1 || kingCount[1] != 1)
1908 // Can the side to move capture the opponent's king?
1909 if (failedStep) (*failedStep)++;
1910 if (debugKingCapture)
1912 Color us = side_to_move();
1913 Color them = opposite_color(us);
1914 Square ksq = king_square(them);
1915 if (attackers_to(ksq) & pieces_of_color(us))
1919 // Is there more than 2 checkers?
1920 if (failedStep) (*failedStep)++;
1921 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1925 if (failedStep) (*failedStep)++;
1928 // The intersection of the white and black pieces must be empty
1929 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1932 // The union of the white and black pieces must be equal to all
1934 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1937 // Separate piece type bitboards must have empty intersections
1938 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1939 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1940 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1944 // En passant square OK?
1945 if (failedStep) (*failedStep)++;
1946 if (ep_square() != SQ_NONE)
1948 // The en passant square must be on rank 6, from the point of view of the
1950 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1955 if (failedStep) (*failedStep)++;
1956 if (debugKey && st->key != compute_key())
1959 // Pawn hash key OK?
1960 if (failedStep) (*failedStep)++;
1961 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1964 // Material hash key OK?
1965 if (failedStep) (*failedStep)++;
1966 if (debugMaterialKey && st->materialKey != compute_material_key())
1969 // Incremental eval OK?
1970 if (failedStep) (*failedStep)++;
1971 if (debugIncrementalEval && st->value != compute_value())
1974 // Non-pawn material OK?
1975 if (failedStep) (*failedStep)++;
1976 if (debugNonPawnMaterial)
1978 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1981 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1986 if (failedStep) (*failedStep)++;
1987 if (debugPieceCounts)
1988 for (Color c = WHITE; c <= BLACK; c++)
1989 for (PieceType pt = PAWN; pt <= KING; pt++)
1990 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
1993 if (failedStep) (*failedStep)++;
1996 for (Color c = WHITE; c <= BLACK; c++)
1997 for (PieceType pt = PAWN; pt <= KING; pt++)
1998 for (int i = 0; i < pieceCount[c][pt]; i++)
2000 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2003 if (index[piece_list(c, pt, i)] != i)
2008 if (failedStep) (*failedStep)++;
2009 if (debugCastleSquares) {
2010 for (Color c = WHITE; c <= BLACK; c++) {
2011 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2013 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2016 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2018 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2020 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2022 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2026 if (failedStep) *failedStep = 0;