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 : 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;
97 CheckInfo::CheckInfo(const Position& pos) {
99 Color us = pos.side_to_move();
100 Color them = opposite_color(us);
102 ksq = pos.king_square(them);
103 dcCandidates = pos.discovered_check_candidates(us);
105 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
106 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
107 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
108 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
109 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
110 checkSq[KING] = EmptyBoardBB;
114 /// Position c'tors. Here we always create a copy of the original position
115 /// or the FEN string, we want the new born Position object do not depend
116 /// on any external data so we detach state pointer from the source one.
118 Position::Position(int th) : threadID(th) {}
120 Position::Position(const Position& pos, int th) {
122 memcpy(this, &pos, sizeof(Position));
123 detach(); // Always detach() in copy c'tor to avoid surprises
127 Position::Position(const string& fen, int th) {
134 /// Position::detach() copies the content of the current state and castling
135 /// masks inside the position itself. This is needed when the st pointee could
136 /// become stale, as example because the caller is about to going out of scope.
138 void Position::detach() {
142 st->previous = NULL; // as a safe guard
146 /// Position::from_fen() initializes the position object with the given FEN
147 /// string. This function is not very robust - make sure that input FENs are
148 /// correct (this is assumed to be the responsibility of the GUI).
150 void Position::from_fen(const string& fen) {
152 A FEN string defines a particular position using only the ASCII character set.
154 A FEN string contains six fields. The separator between fields is a space. The fields are:
156 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
157 with rank 1; within each rank, the contents of each square are described from file a through file h.
158 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
159 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
160 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
161 of blank squares), and "/" separate ranks.
163 2) Active color. "w" means white moves next, "b" means black.
165 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
166 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
167 kingside), and/or "q" (Black can castle queenside).
169 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
170 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
171 regardless of whether there is a pawn in position to make an en passant capture.
173 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
174 to determine if a draw can be claimed under the fifty-move rule.
176 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
180 std::istringstream ss(fen);
186 // 1. Piece placement field
187 while (ss.get(token) && token != ' ')
191 file += File(token - '0'); // Skip the given number of files
194 else if (token == '/')
201 if (pieceLetters.find(token) == pieceLetters.end())
204 put_piece(pieceLetters[token], make_square(file, rank));
209 if (!ss.get(token) || (token != 'w' && token != 'b'))
212 sideToMove = (token == 'w' ? WHITE : BLACK);
214 if (!ss.get(token) || token != ' ')
217 // 3. Castling availability
218 while (ss.get(token) && token != ' ')
223 if (!set_castling_rights(token))
227 // 4. En passant square -- ignore if no capture is possible
229 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
230 && (ss.get(row) && (row == '3' || row == '6')))
232 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
233 Color them = opposite_color(sideToMove);
235 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
236 st->epSquare = fenEpSquare;
239 // 5-6. Halfmove clock and fullmove number are not parsed
241 // Various initialisations
242 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
243 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
244 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
245 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
246 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
247 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
249 isChess960 = initialKFile != FILE_E
250 || initialQRFile != FILE_A
251 || initialKRFile != FILE_H;
255 st->key = compute_key();
256 st->pawnKey = compute_pawn_key();
257 st->materialKey = compute_material_key();
258 st->value = compute_value();
259 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
260 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
264 cout << "Error in FEN string: " << fen << endl;
268 /// Position::set_castling_rights() sets castling parameters castling avaiability.
269 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
270 /// that uses the letters of the columns on which the rooks began the game instead
271 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
272 /// associated with the castling right, the traditional castling tag will be replaced
273 /// by the file letter of the involved rook as for the Shredder-FEN.
275 bool Position::set_castling_rights(char token) {
277 Color c = token >= 'a' ? BLACK : WHITE;
278 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
279 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
280 Piece rook = (c == WHITE ? WR : BR);
282 initialKFile = square_file(king_square(c));
283 token = char(toupper(token));
287 for (Square sq = sqH; sq >= sqA; sq--)
288 if (piece_on(sq) == rook)
291 initialKRFile = square_file(sq);
295 else if (token == 'Q')
297 for (Square sq = sqA; sq <= sqH; sq++)
298 if (piece_on(sq) == rook)
301 initialQRFile = square_file(sq);
305 else if (token >= 'A' && token <= 'H')
307 File rookFile = File(token - 'A') + FILE_A;
308 if (rookFile < initialKFile)
311 initialQRFile = rookFile;
316 initialKRFile = rookFile;
325 /// Position::to_fen() returns a FEN representation of the position. In case
326 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
328 const string Position::to_fen() const {
334 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
336 for (File file = FILE_A; file <= FILE_H; file++)
338 sq = make_square(file, rank);
340 if (square_is_occupied(sq))
343 fen += pieceLetters.from_piece(piece_on(sq));
353 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
354 fen.erase(--fen.end());
355 fen += (sideToMove == WHITE ? " w " : " b ");
357 if (st->castleRights != CASTLES_NONE)
359 if (can_castle_kingside(WHITE))
360 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
362 if (can_castle_queenside(WHITE))
363 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
365 if (can_castle_kingside(BLACK))
366 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
368 if (can_castle_queenside(BLACK))
369 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
373 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
378 /// Position::print() prints an ASCII representation of the position to
379 /// the standard output. If a move is given then also the san is print.
381 void Position::print(Move move) const {
383 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
384 static bool requestPending = false;
386 // Check for reentrancy, as example when called from inside
387 // MovePicker that is used also here in move_to_san()
391 requestPending = true;
395 Position p(*this, thread());
396 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
397 cout << "\nMove is: " << dd << move_to_san(p, move);
400 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
402 cout << dottedLine << '|';
403 for (File file = FILE_A; file <= FILE_H; file++)
405 Square sq = make_square(file, rank);
406 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
407 Piece piece = piece_on(sq);
409 if (piece == PIECE_NONE && square_color(sq) == DARK)
410 piece = PIECE_NONE_DARK_SQ;
412 cout << c << pieceLetters.from_piece(piece) << c << '|';
415 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
416 requestPending = false;
420 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
421 /// king) pieces for the given color and for the given pinner type. Or, when
422 /// template parameter FindPinned is false, the pieces of the given color
423 /// candidate for a discovery check against the enemy king.
424 /// Bitboard checkersBB must be already updated when looking for pinners.
426 template<bool FindPinned>
427 Bitboard Position::hidden_checkers(Color c) const {
429 Bitboard result = EmptyBoardBB;
430 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
432 // Pinned pieces protect our king, dicovery checks attack
434 Square ksq = king_square(FindPinned ? c : opposite_color(c));
436 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
437 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
439 if (FindPinned && pinners)
440 pinners &= ~st->checkersBB;
444 Square s = pop_1st_bit(&pinners);
445 Bitboard b = squares_between(s, ksq) & occupied_squares();
449 if ( !(b & (b - 1)) // Only one bit set?
450 && (b & pieces_of_color(c))) // Is an our piece?
457 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
458 /// king) pieces for the given color. Note that checkersBB bitboard must
459 /// be already updated.
461 Bitboard Position::pinned_pieces(Color c) const {
463 return hidden_checkers<true>(c);
467 /// Position:discovered_check_candidates() returns a bitboard containing all
468 /// pieces for the given side which are candidates for giving a discovered
469 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
470 /// to be already updated.
472 Bitboard Position::discovered_check_candidates(Color c) const {
474 return hidden_checkers<false>(c);
477 /// Position::attackers_to() computes a bitboard containing all pieces which
478 /// attacks a given square.
480 Bitboard Position::attackers_to(Square s) const {
482 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
483 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
484 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
485 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
486 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
487 | (attacks_from<KING>(s) & pieces(KING));
490 /// Position::attacks_from() computes a bitboard of all attacks
491 /// of a given piece put in a given square.
493 Bitboard Position::attacks_from(Piece p, Square s) const {
495 assert(square_is_ok(s));
499 case WP: return attacks_from<PAWN>(s, WHITE);
500 case BP: return attacks_from<PAWN>(s, BLACK);
501 case WN: case BN: return attacks_from<KNIGHT>(s);
502 case WB: case BB: return attacks_from<BISHOP>(s);
503 case WR: case BR: return attacks_from<ROOK>(s);
504 case WQ: case BQ: return attacks_from<QUEEN>(s);
505 case WK: case BK: return attacks_from<KING>(s);
512 /// Position::move_attacks_square() tests whether a move from the current
513 /// position attacks a given square.
515 bool Position::move_attacks_square(Move m, Square s) const {
517 assert(move_is_ok(m));
518 assert(square_is_ok(s));
520 Square f = move_from(m), t = move_to(m);
522 assert(square_is_occupied(f));
524 if (bit_is_set(attacks_from(piece_on(f), t), s))
527 // Move the piece and scan for X-ray attacks behind it
528 Bitboard occ = occupied_squares();
529 Color us = color_of_piece_on(f);
532 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
533 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
535 // If we have attacks we need to verify that are caused by our move
536 // and are not already existent ones.
537 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
541 /// Position::find_checkers() computes the checkersBB bitboard, which
542 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
543 /// currently works by calling Position::attackers_to, which is probably
544 /// inefficient. Consider rewriting this function to use the last move
545 /// played, like in non-bitboard versions of Glaurung.
547 void Position::find_checkers() {
549 Color us = side_to_move();
550 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
554 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
556 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
559 assert(move_is_ok(m));
560 assert(pinned == pinned_pieces(side_to_move()));
562 // Castling moves are checked for legality during move generation.
563 if (move_is_castle(m))
566 Color us = side_to_move();
567 Square from = move_from(m);
569 assert(color_of_piece_on(from) == us);
570 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
572 // En passant captures are a tricky special case. Because they are
573 // rather uncommon, we do it simply by testing whether the king is attacked
574 // after the move is made
577 Color them = opposite_color(us);
578 Square to = move_to(m);
579 Square capsq = make_square(square_file(to), square_rank(from));
580 Bitboard b = occupied_squares();
581 Square ksq = king_square(us);
583 assert(to == ep_square());
584 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
585 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
586 assert(piece_on(to) == PIECE_NONE);
589 clear_bit(&b, capsq);
592 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
593 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
596 // If the moving piece is a king, check whether the destination
597 // square is attacked by the opponent.
598 if (type_of_piece_on(from) == KING)
599 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
601 // A non-king move is legal if and only if it is not pinned or it
602 // is moving along the ray towards or away from the king.
604 || !bit_is_set(pinned, from)
605 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
609 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
611 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
615 Color us = side_to_move();
616 Square from = move_from(m);
617 Square to = move_to(m);
619 // King moves and en-passant captures are verified in pl_move_is_legal()
620 if (type_of_piece_on(from) == KING || move_is_ep(m))
621 return pl_move_is_legal(m, pinned);
623 Bitboard target = checkers();
624 Square checksq = pop_1st_bit(&target);
626 if (target) // double check ?
629 // Our move must be a blocking evasion or a capture of the checking piece
630 target = squares_between(checksq, king_square(us)) | checkers();
631 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
635 /// Position::move_is_check() tests whether a pseudo-legal move is a check
637 bool Position::move_is_check(Move m) const {
639 return move_is_check(m, CheckInfo(*this));
642 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
645 assert(move_is_ok(m));
646 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
647 assert(color_of_piece_on(move_from(m)) == side_to_move());
648 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
650 Square from = move_from(m);
651 Square to = move_to(m);
652 PieceType pt = type_of_piece_on(from);
655 if (bit_is_set(ci.checkSq[pt], to))
659 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
661 // For pawn and king moves we need to verify also direction
662 if ( (pt != PAWN && pt != KING)
663 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
667 // Can we skip the ugly special cases ?
668 if (!move_is_special(m))
671 Color us = side_to_move();
672 Bitboard b = occupied_squares();
674 // Promotion with check ?
675 if (move_is_promotion(m))
679 switch (move_promotion_piece(m))
682 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
684 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
686 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
688 return bit_is_set(queen_attacks_bb(to, b), ci.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(square_file(to), square_rank(from));
702 clear_bit(&b, capsq);
704 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
705 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
708 // Castling with check ?
709 if (move_is_castle(m))
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), ci.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.
736 /// Pseudo-legal 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_is_check(m, ci));
744 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
747 assert(move_is_ok(m));
751 // Copy some fields of old state to our new StateInfo object except the
752 // ones which are recalculated from scratch anyway, then switch our state
753 // pointer to point to the new, ready to be updated, state.
754 struct ReducedStateInfo {
755 Key pawnKey, materialKey;
756 int castleRights, rule50, gamePly, pliesFromNull;
762 memcpy(&newSt, st, sizeof(ReducedStateInfo));
766 // Save the current key to the history[] array, in order to be able to
767 // detect repetition draws.
768 history[st->gamePly++] = key;
770 // Update side to move
771 key ^= zobSideToMove;
773 // Increment the 50 moves rule draw counter. Resetting it to zero in the
774 // case of non-reversible moves is taken care of later.
778 if (move_is_castle(m))
785 Color us = side_to_move();
786 Color them = opposite_color(us);
787 Square from = move_from(m);
788 Square to = move_to(m);
789 bool ep = move_is_ep(m);
790 bool pm = move_is_promotion(m);
792 Piece piece = piece_on(from);
793 PieceType pt = type_of_piece(piece);
794 PieceType capture = ep ? PAWN : type_of_piece_on(to);
796 assert(color_of_piece_on(from) == us);
797 assert(color_of_piece_on(to) == them || square_is_empty(to));
798 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
799 assert(!pm || relative_rank(us, to) == RANK_8);
802 do_capture_move(key, capture, them, to, ep);
805 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
807 // Reset en passant square
808 if (st->epSquare != SQ_NONE)
810 key ^= zobEp[st->epSquare];
811 st->epSquare = SQ_NONE;
814 // Update castle rights, try to shortcut a common case
815 int cm = castleRightsMask[from] & castleRightsMask[to];
816 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
818 key ^= zobCastle[st->castleRights];
819 st->castleRights &= castleRightsMask[from];
820 st->castleRights &= castleRightsMask[to];
821 key ^= zobCastle[st->castleRights];
824 // Prefetch TT access as soon as we know key is updated
825 prefetch((char*)TT.first_entry(key));
828 Bitboard move_bb = make_move_bb(from, to);
829 do_move_bb(&(byColorBB[us]), move_bb);
830 do_move_bb(&(byTypeBB[pt]), move_bb);
831 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
833 board[to] = board[from];
834 board[from] = PIECE_NONE;
836 // Update piece lists, note that index[from] is not updated and
837 // becomes stale. This works as long as index[] is accessed just
838 // by known occupied squares.
839 index[to] = index[from];
840 pieceList[us][pt][index[to]] = to;
842 // If the moving piece was a pawn do some special extra work
845 // Reset rule 50 draw counter
848 // Update pawn hash key and prefetch in L1/L2 cache
849 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
850 prefetchPawn(st->pawnKey, threadID);
852 // Set en passant square, only if moved pawn can be captured
853 if ((to ^ from) == 16)
855 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
857 st->epSquare = Square((int(from) + int(to)) / 2);
858 key ^= zobEp[st->epSquare];
862 if (pm) // promotion ?
864 PieceType promotion = move_promotion_piece(m);
866 assert(promotion >= KNIGHT && promotion <= QUEEN);
868 // Insert promoted piece instead of pawn
869 clear_bit(&(byTypeBB[PAWN]), to);
870 set_bit(&(byTypeBB[promotion]), to);
871 board[to] = piece_of_color_and_type(us, promotion);
873 // Update piece counts
874 pieceCount[us][promotion]++;
875 pieceCount[us][PAWN]--;
877 // Update material key
878 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
879 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
881 // Update piece lists, move the last pawn at index[to] position
882 // and shrink the list. Add a new promotion piece to the list.
883 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
884 index[lastPawnSquare] = index[to];
885 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
886 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
887 index[to] = pieceCount[us][promotion] - 1;
888 pieceList[us][promotion][index[to]] = to;
890 // Partially revert hash keys update
891 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
892 st->pawnKey ^= zobrist[us][PAWN][to];
894 // Partially revert and update incremental scores
895 st->value -= pst(us, PAWN, to);
896 st->value += pst(us, promotion, to);
899 st->npMaterial[us] += PieceValueMidgame[promotion];
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_of_color(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>(ci.ksq) & pieces(ROOK, QUEEN, us));
932 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
938 sideToMove = opposite_color(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 = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
962 assert(to == st->epSquare);
963 assert(relative_rank(opposite_color(them), to) == RANK_6);
964 assert(piece_on(to) == PIECE_NONE);
965 assert(piece_on(capsq) == piece_of_color_and_type(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(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) {
1015 assert(move_is_ok(m));
1016 assert(move_is_castle(m));
1018 Color us = side_to_move();
1019 Color them = opposite_color(us);
1021 // Reset capture field
1022 st->capturedType = PIECE_TYPE_NONE;
1024 // Find source squares for king and rook
1025 Square kfrom = move_from(m);
1026 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1029 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1030 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1032 // Find destination squares for king and rook
1033 if (rfrom > kfrom) // O-O
1035 kto = relative_square(us, SQ_G1);
1036 rto = relative_square(us, SQ_F1);
1038 kto = relative_square(us, SQ_C1);
1039 rto = relative_square(us, SQ_D1);
1042 // Remove pieces from source squares:
1043 clear_bit(&(byColorBB[us]), kfrom);
1044 clear_bit(&(byTypeBB[KING]), kfrom);
1045 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1046 clear_bit(&(byColorBB[us]), rfrom);
1047 clear_bit(&(byTypeBB[ROOK]), rfrom);
1048 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1050 // Put pieces on destination squares:
1051 set_bit(&(byColorBB[us]), kto);
1052 set_bit(&(byTypeBB[KING]), kto);
1053 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1054 set_bit(&(byColorBB[us]), rto);
1055 set_bit(&(byTypeBB[ROOK]), rto);
1056 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1058 // Update board array
1059 Piece king = piece_of_color_and_type(us, KING);
1060 Piece rook = piece_of_color_and_type(us, ROOK);
1061 board[kfrom] = board[rfrom] = PIECE_NONE;
1065 // Update piece lists
1066 pieceList[us][KING][index[kfrom]] = kto;
1067 pieceList[us][ROOK][index[rfrom]] = rto;
1068 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1069 index[kto] = index[kfrom];
1072 // Update incremental scores
1073 st->value += pst_delta(king, kfrom, kto);
1074 st->value += pst_delta(rook, rfrom, rto);
1077 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1078 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1080 // Clear en passant square
1081 if (st->epSquare != SQ_NONE)
1083 st->key ^= zobEp[st->epSquare];
1084 st->epSquare = SQ_NONE;
1087 // Update castling rights
1088 st->key ^= zobCastle[st->castleRights];
1089 st->castleRights &= castleRightsMask[kfrom];
1090 st->key ^= zobCastle[st->castleRights];
1092 // Reset rule 50 counter
1095 // Update checkers BB
1096 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1099 sideToMove = opposite_color(sideToMove);
1100 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1106 /// Position::undo_move() unmakes a move. When it returns, the position should
1107 /// be restored to exactly the same state as before the move was made.
1109 void Position::undo_move(Move m) {
1112 assert(move_is_ok(m));
1114 sideToMove = opposite_color(sideToMove);
1116 if (move_is_castle(m))
1118 undo_castle_move(m);
1122 Color us = side_to_move();
1123 Color them = opposite_color(us);
1124 Square from = move_from(m);
1125 Square to = move_to(m);
1126 bool ep = move_is_ep(m);
1127 bool pm = move_is_promotion(m);
1129 PieceType pt = type_of_piece_on(to);
1131 assert(square_is_empty(from));
1132 assert(color_of_piece_on(to) == us);
1133 assert(!pm || relative_rank(us, to) == RANK_8);
1134 assert(!ep || to == st->previous->epSquare);
1135 assert(!ep || relative_rank(us, to) == RANK_6);
1136 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1138 if (pm) // promotion ?
1140 PieceType promotion = move_promotion_piece(m);
1143 assert(promotion >= KNIGHT && promotion <= QUEEN);
1144 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1146 // Replace promoted piece with a pawn
1147 clear_bit(&(byTypeBB[promotion]), to);
1148 set_bit(&(byTypeBB[PAWN]), to);
1150 // Update piece counts
1151 pieceCount[us][promotion]--;
1152 pieceCount[us][PAWN]++;
1154 // Update piece list replacing promotion piece with a pawn
1155 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1156 index[lastPromotionSquare] = index[to];
1157 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1158 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1159 index[to] = pieceCount[us][PAWN] - 1;
1160 pieceList[us][PAWN][index[to]] = to;
1163 // Put the piece back at the source square
1164 Bitboard move_bb = make_move_bb(to, from);
1165 do_move_bb(&(byColorBB[us]), move_bb);
1166 do_move_bb(&(byTypeBB[pt]), move_bb);
1167 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1169 board[from] = piece_of_color_and_type(us, pt);
1170 board[to] = PIECE_NONE;
1172 // Update piece list
1173 index[from] = index[to];
1174 pieceList[us][pt][index[from]] = from;
1176 if (st->capturedType)
1181 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1183 assert(st->capturedType != KING);
1184 assert(!ep || square_is_empty(capsq));
1186 // Restore the captured piece
1187 set_bit(&(byColorBB[them]), capsq);
1188 set_bit(&(byTypeBB[st->capturedType]), capsq);
1189 set_bit(&(byTypeBB[0]), capsq);
1191 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1193 // Update piece count
1194 pieceCount[them][st->capturedType]++;
1196 // Update piece list, add a new captured piece in capsq square
1197 index[capsq] = pieceCount[them][st->capturedType] - 1;
1198 pieceList[them][st->capturedType][index[capsq]] = capsq;
1201 // Finally point our state pointer back to the previous state
1208 /// Position::undo_castle_move() is a private method used to unmake a castling
1209 /// move. It is called from the main Position::undo_move function. Note that
1210 /// castling moves are encoded as "king captures friendly rook" moves, for
1211 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1213 void Position::undo_castle_move(Move m) {
1215 assert(move_is_ok(m));
1216 assert(move_is_castle(m));
1218 // When we have arrived here, some work has already been done by
1219 // Position::undo_move. In particular, the side to move has been switched,
1220 // so the code below is correct.
1221 Color us = side_to_move();
1223 // Find source squares for king and rook
1224 Square kfrom = move_from(m);
1225 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1228 // Find destination squares for king and rook
1229 if (rfrom > kfrom) // O-O
1231 kto = relative_square(us, SQ_G1);
1232 rto = relative_square(us, SQ_F1);
1234 kto = relative_square(us, SQ_C1);
1235 rto = relative_square(us, SQ_D1);
1238 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1239 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1241 // Remove pieces from destination squares:
1242 clear_bit(&(byColorBB[us]), kto);
1243 clear_bit(&(byTypeBB[KING]), kto);
1244 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1245 clear_bit(&(byColorBB[us]), rto);
1246 clear_bit(&(byTypeBB[ROOK]), rto);
1247 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1249 // Put pieces on source squares:
1250 set_bit(&(byColorBB[us]), kfrom);
1251 set_bit(&(byTypeBB[KING]), kfrom);
1252 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1253 set_bit(&(byColorBB[us]), rfrom);
1254 set_bit(&(byTypeBB[ROOK]), rfrom);
1255 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1258 board[rto] = board[kto] = PIECE_NONE;
1259 board[rfrom] = piece_of_color_and_type(us, ROOK);
1260 board[kfrom] = piece_of_color_and_type(us, KING);
1262 // Update piece lists
1263 pieceList[us][KING][index[kto]] = kfrom;
1264 pieceList[us][ROOK][index[rto]] = rfrom;
1265 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1266 index[kfrom] = index[kto];
1269 // Finally point our state pointer back to the previous state
1276 /// Position::do_null_move makes() a "null move": It switches the side to move
1277 /// and updates the hash key without executing any move on the board.
1279 void Position::do_null_move(StateInfo& backupSt) {
1282 assert(!is_check());
1284 // Back up the information necessary to undo the null move to the supplied
1285 // StateInfo object.
1286 // Note that differently from normal case here backupSt is actually used as
1287 // a backup storage not as a new state to be used.
1288 backupSt.key = st->key;
1289 backupSt.epSquare = st->epSquare;
1290 backupSt.value = st->value;
1291 backupSt.previous = st->previous;
1292 backupSt.pliesFromNull = st->pliesFromNull;
1293 st->previous = &backupSt;
1295 // Save the current key to the history[] array, in order to be able to
1296 // detect repetition draws.
1297 history[st->gamePly++] = st->key;
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 = opposite_color(sideToMove);
1307 st->epSquare = SQ_NONE;
1309 st->pliesFromNull = 0;
1310 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1314 /// Position::undo_null_move() unmakes a "null move".
1316 void Position::undo_null_move() {
1319 assert(!is_check());
1321 // Restore information from the our backup StateInfo object
1322 StateInfo* backupSt = st->previous;
1323 st->key = backupSt->key;
1324 st->epSquare = backupSt->epSquare;
1325 st->value = backupSt->value;
1326 st->previous = backupSt->previous;
1327 st->pliesFromNull = backupSt->pliesFromNull;
1329 // Update the necessary information
1330 sideToMove = opposite_color(sideToMove);
1336 /// Position::see() is a static exchange evaluator: It tries to estimate the
1337 /// material gain or loss resulting from a move. There are three versions of
1338 /// this function: One which takes a destination square as input, one takes a
1339 /// move, and one which takes a 'from' and a 'to' square. The function does
1340 /// not yet understand promotions captures.
1342 int Position::see(Square to) const {
1344 assert(square_is_ok(to));
1345 return see(SQ_NONE, to);
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 {
1373 static const int seeValues[18] = {
1374 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1375 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1376 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1377 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1381 Bitboard attackers, stmAttackers, b;
1383 assert(square_is_ok(from) || from == SQ_NONE);
1384 assert(square_is_ok(to));
1386 // Initialize colors
1387 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1388 Color them = opposite_color(us);
1390 // Initialize pieces
1391 Piece piece = piece_on(from);
1392 Piece capture = piece_on(to);
1393 Bitboard occ = occupied_squares();
1395 // King cannot be recaptured
1396 if (type_of_piece(piece) == KING)
1397 return seeValues[capture];
1399 // Handle en passant moves
1400 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1402 assert(capture == PIECE_NONE);
1404 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1405 capture = piece_on(capQq);
1406 assert(type_of_piece_on(capQq) == PAWN);
1408 // Remove the captured pawn
1409 clear_bit(&occ, capQq);
1414 // Find all attackers to the destination square, with the moving piece
1415 // removed, but possibly an X-ray attacker added behind it.
1416 clear_bit(&occ, from);
1417 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1418 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1419 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1420 | (attacks_from<KING>(to) & pieces(KING))
1421 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1422 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1424 if (from != SQ_NONE)
1427 // If we don't have any attacker we are finished
1428 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1431 // Locate the least valuable attacker to the destination square
1432 // and use it to initialize from square.
1433 stmAttackers = attackers & pieces_of_color(us);
1435 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1438 from = first_1(stmAttackers & pieces(pt));
1439 piece = piece_on(from);
1442 // If the opponent has no attackers we are finished
1443 stmAttackers = attackers & pieces_of_color(them);
1445 return seeValues[capture];
1447 attackers &= occ; // Remove the moving piece
1449 // The destination square is defended, which makes things rather more
1450 // difficult to compute. We proceed by building up a "swap list" containing
1451 // the material gain or loss at each stop in a sequence of captures to the
1452 // destination square, where the sides alternately capture, and always
1453 // capture with the least valuable piece. After each capture, we look for
1454 // new X-ray attacks from behind the capturing piece.
1455 int lastCapturingPieceValue = seeValues[piece];
1456 int swapList[32], n = 1;
1460 swapList[0] = seeValues[capture];
1463 // Locate the least valuable attacker for the side to move. The loop
1464 // below looks like it is potentially infinite, but it isn't. We know
1465 // that the side to move still has at least one attacker left.
1466 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1469 // Remove the attacker we just found from the 'attackers' bitboard,
1470 // and scan for new X-ray attacks behind the attacker.
1471 b = stmAttackers & pieces(pt);
1472 occ ^= (b & (~b + 1));
1473 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1474 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1478 // Add the new entry to the swap list
1480 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1483 // Remember the value of the capturing piece, and change the side to move
1484 // before beginning the next iteration
1485 lastCapturingPieceValue = seeValues[pt];
1486 c = opposite_color(c);
1487 stmAttackers = attackers & pieces_of_color(c);
1489 // Stop after a king capture
1490 if (pt == KING && stmAttackers)
1493 swapList[n++] = QueenValueMidgame*10;
1496 } while (stmAttackers);
1498 // Having built the swap list, we negamax through it to find the best
1499 // achievable score from the point of view of the side to move
1501 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1507 /// Position::clear() erases the position object to a pristine state, with an
1508 /// empty board, white to move, and no castling rights.
1510 void Position::clear() {
1513 memset(st, 0, sizeof(StateInfo));
1514 st->epSquare = SQ_NONE;
1515 startPosPlyCounter = 0;
1517 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1518 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1519 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1520 memset(index, 0, sizeof(int) * 64);
1522 for (int i = 0; i < 64; i++)
1523 board[i] = PIECE_NONE;
1525 for (int i = 0; i < 8; i++)
1526 for (int j = 0; j < 16; j++)
1527 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1529 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1530 castleRightsMask[sq] = ALL_CASTLES;
1533 initialKFile = FILE_E;
1534 initialKRFile = FILE_H;
1535 initialQRFile = FILE_A;
1539 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1540 /// UCI interface code, whenever a non-reversible move is made in a
1541 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1542 /// for the program to handle games of arbitrary length, as long as the GUI
1543 /// handles draws by the 50 move rule correctly.
1545 void Position::reset_game_ply() {
1550 void Position::inc_startpos_ply_counter() {
1552 startPosPlyCounter++;
1555 /// Position::put_piece() puts a piece on the given square of the board,
1556 /// updating the board array, bitboards, and piece counts.
1558 void Position::put_piece(Piece p, Square s) {
1560 Color c = color_of_piece(p);
1561 PieceType pt = type_of_piece(p);
1564 index[s] = pieceCount[c][pt];
1565 pieceList[c][pt][index[s]] = s;
1567 set_bit(&(byTypeBB[pt]), s);
1568 set_bit(&(byColorBB[c]), s);
1569 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1571 pieceCount[c][pt]++;
1575 /// Position::allow_oo() gives the given side the right to castle kingside.
1576 /// Used when setting castling rights during parsing of FEN strings.
1578 void Position::allow_oo(Color c) {
1580 st->castleRights |= (1 + int(c));
1584 /// Position::allow_ooo() gives the given side the right to castle queenside.
1585 /// Used when setting castling rights during parsing of FEN strings.
1587 void Position::allow_ooo(Color c) {
1589 st->castleRights |= (4 + 4*int(c));
1593 /// Position::compute_key() computes the hash key of the position. The hash
1594 /// key is usually updated incrementally as moves are made and unmade, the
1595 /// compute_key() function is only used when a new position is set up, and
1596 /// to verify the correctness of the hash key when running in debug mode.
1598 Key Position::compute_key() const {
1600 Key result = Key(0ULL);
1602 for (Square s = SQ_A1; s <= SQ_H8; s++)
1603 if (square_is_occupied(s))
1604 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1606 if (ep_square() != SQ_NONE)
1607 result ^= zobEp[ep_square()];
1609 result ^= zobCastle[st->castleRights];
1610 if (side_to_move() == BLACK)
1611 result ^= zobSideToMove;
1617 /// Position::compute_pawn_key() computes the hash key of the position. The
1618 /// hash key is usually updated incrementally as moves are made and unmade,
1619 /// the compute_pawn_key() function is only used when a new position is set
1620 /// up, and to verify the correctness of the pawn hash key when running in
1623 Key Position::compute_pawn_key() const {
1625 Key result = Key(0ULL);
1629 for (Color c = WHITE; c <= BLACK; c++)
1631 b = pieces(PAWN, c);
1634 s = pop_1st_bit(&b);
1635 result ^= zobrist[c][PAWN][s];
1642 /// Position::compute_material_key() computes the hash key of the position.
1643 /// The hash key is usually updated incrementally as moves are made and unmade,
1644 /// the compute_material_key() function is only used when a new position is set
1645 /// up, and to verify the correctness of the material hash key when running in
1648 Key Position::compute_material_key() const {
1650 Key result = Key(0ULL);
1651 for (Color c = WHITE; c <= BLACK; c++)
1652 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1654 int count = piece_count(c, pt);
1655 for (int i = 0; i < count; i++)
1656 result ^= zobrist[c][pt][i];
1662 /// Position::compute_value() compute the incremental scores for the middle
1663 /// game and the endgame. These functions are used to initialize the incremental
1664 /// scores when a new position is set up, and to verify that the scores are correctly
1665 /// updated by do_move and undo_move when the program is running in debug mode.
1666 Score Position::compute_value() const {
1668 Score result = SCORE_ZERO;
1672 for (Color c = WHITE; c <= BLACK; c++)
1673 for (PieceType pt = PAWN; pt <= KING; pt++)
1678 s = pop_1st_bit(&b);
1679 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1680 result += pst(c, pt, s);
1684 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1689 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1690 /// game material score for the given side. Material scores are updated
1691 /// incrementally during the search, this function is only used while
1692 /// initializing a new Position object.
1694 Value Position::compute_non_pawn_material(Color c) const {
1696 Value result = VALUE_ZERO;
1698 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1700 Bitboard b = pieces(pt, c);
1703 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1706 result += PieceValueMidgame[pt];
1713 /// Position::is_draw() tests whether the position is drawn by material,
1714 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1715 /// must be done by the search.
1716 // FIXME: Currently we are not handling 50 move rule correctly when in check
1718 bool Position::is_draw() const {
1720 // Draw by material?
1722 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1725 // Draw by the 50 moves rule?
1726 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1729 // Draw by repetition?
1730 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1731 if (history[st->gamePly - i] == st->key)
1738 /// Position::is_mate() returns true or false depending on whether the
1739 /// side to move is checkmated.
1741 bool Position::is_mate() const {
1743 MoveStack moves[256];
1744 return is_check() && (generate_moves(*this, moves) == moves);
1748 /// Position::has_mate_threat() tests whether the side to move is under
1749 /// a threat of being mated in one from the current position.
1751 bool Position::has_mate_threat() {
1753 MoveStack mlist[256], *last, *cur;
1755 bool mateFound = false;
1757 // If we are under check it's up to evasions to do the job
1761 // First pass the move to our opponent doing a null move
1764 // Then generate pseudo-legal moves that give check
1765 last = generate_non_capture_checks(*this, mlist);
1766 last = generate_captures(*this, last);
1768 // Loop through the moves, and see if one of them gives mate
1769 Bitboard pinned = pinned_pieces(sideToMove);
1770 CheckInfo ci(*this);
1771 for (cur = mlist; cur != last && !mateFound; cur++)
1773 Move move = cur->move;
1774 if ( !pl_move_is_legal(move, pinned)
1775 || !move_is_check(move, ci))
1778 do_move(move, st2, ci, true);
1791 /// Position::init_zobrist() is a static member function which initializes at
1792 /// startup the various arrays used to compute hash keys.
1794 void Position::init_zobrist() {
1798 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1799 zobrist[i][j][k] = Key(genrand_int64());
1801 for (i = 0; i < 64; i++)
1802 zobEp[i] = Key(genrand_int64());
1804 for (i = 0; i < 16; i++)
1805 zobCastle[i] = Key(genrand_int64());
1807 zobSideToMove = Key(genrand_int64());
1808 zobExclusion = Key(genrand_int64());
1812 /// Position::init_piece_square_tables() initializes the piece square tables.
1813 /// This is a two-step operation: First, the white halves of the tables are
1814 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1815 /// of the tables are initialized by mirroring and changing the sign of the
1816 /// corresponding white scores.
1818 void Position::init_piece_square_tables() {
1820 for (Square s = SQ_A1; s <= SQ_H8; s++)
1821 for (Piece p = WP; p <= WK; p++)
1822 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1824 for (Square s = SQ_A1; s <= SQ_H8; s++)
1825 for (Piece p = BP; p <= BK; p++)
1826 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1830 /// Position::flipped_copy() makes a copy of the input position, but with
1831 /// the white and black sides reversed. This is only useful for debugging,
1832 /// especially for finding evaluation symmetry bugs.
1834 void Position::flipped_copy(const Position& pos) {
1836 assert(pos.is_ok());
1839 threadID = pos.thread();
1842 for (Square s = SQ_A1; s <= SQ_H8; s++)
1843 if (!pos.square_is_empty(s))
1844 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1847 sideToMove = opposite_color(pos.side_to_move());
1850 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1851 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1852 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1853 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1855 initialKFile = pos.initialKFile;
1856 initialKRFile = pos.initialKRFile;
1857 initialQRFile = pos.initialQRFile;
1859 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1860 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1861 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1862 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1863 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1864 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1866 // En passant square
1867 if (pos.st->epSquare != SQ_NONE)
1868 st->epSquare = flip_square(pos.st->epSquare);
1874 st->key = compute_key();
1875 st->pawnKey = compute_pawn_key();
1876 st->materialKey = compute_material_key();
1878 // Incremental scores
1879 st->value = compute_value();
1882 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1883 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1889 /// Position::is_ok() performs some consitency checks for the position object.
1890 /// This is meant to be helpful when debugging.
1892 bool Position::is_ok(int* failedStep) const {
1894 // What features of the position should be verified?
1895 static const bool debugBitboards = false;
1896 static const bool debugKingCount = false;
1897 static const bool debugKingCapture = false;
1898 static const bool debugCheckerCount = false;
1899 static const bool debugKey = false;
1900 static const bool debugMaterialKey = false;
1901 static const bool debugPawnKey = false;
1902 static const bool debugIncrementalEval = false;
1903 static const bool debugNonPawnMaterial = false;
1904 static const bool debugPieceCounts = false;
1905 static const bool debugPieceList = false;
1906 static const bool debugCastleSquares = false;
1908 if (failedStep) *failedStep = 1;
1911 if (!color_is_ok(side_to_move()))
1914 // Are the king squares in the position correct?
1915 if (failedStep) (*failedStep)++;
1916 if (piece_on(king_square(WHITE)) != WK)
1919 if (failedStep) (*failedStep)++;
1920 if (piece_on(king_square(BLACK)) != BK)
1924 if (failedStep) (*failedStep)++;
1925 if (!file_is_ok(initialKRFile))
1928 if (!file_is_ok(initialQRFile))
1931 // Do both sides have exactly one king?
1932 if (failedStep) (*failedStep)++;
1935 int kingCount[2] = {0, 0};
1936 for (Square s = SQ_A1; s <= SQ_H8; s++)
1937 if (type_of_piece_on(s) == KING)
1938 kingCount[color_of_piece_on(s)]++;
1940 if (kingCount[0] != 1 || kingCount[1] != 1)
1944 // Can the side to move capture the opponent's king?
1945 if (failedStep) (*failedStep)++;
1946 if (debugKingCapture)
1948 Color us = side_to_move();
1949 Color them = opposite_color(us);
1950 Square ksq = king_square(them);
1951 if (attackers_to(ksq) & pieces_of_color(us))
1955 // Is there more than 2 checkers?
1956 if (failedStep) (*failedStep)++;
1957 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1961 if (failedStep) (*failedStep)++;
1964 // The intersection of the white and black pieces must be empty
1965 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1968 // The union of the white and black pieces must be equal to all
1970 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1973 // Separate piece type bitboards must have empty intersections
1974 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1975 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1976 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1980 // En passant square OK?
1981 if (failedStep) (*failedStep)++;
1982 if (ep_square() != SQ_NONE)
1984 // The en passant square must be on rank 6, from the point of view of the
1986 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1991 if (failedStep) (*failedStep)++;
1992 if (debugKey && st->key != compute_key())
1995 // Pawn hash key OK?
1996 if (failedStep) (*failedStep)++;
1997 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2000 // Material hash key OK?
2001 if (failedStep) (*failedStep)++;
2002 if (debugMaterialKey && st->materialKey != compute_material_key())
2005 // Incremental eval OK?
2006 if (failedStep) (*failedStep)++;
2007 if (debugIncrementalEval && st->value != compute_value())
2010 // Non-pawn material OK?
2011 if (failedStep) (*failedStep)++;
2012 if (debugNonPawnMaterial)
2014 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2017 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2022 if (failedStep) (*failedStep)++;
2023 if (debugPieceCounts)
2024 for (Color c = WHITE; c <= BLACK; c++)
2025 for (PieceType pt = PAWN; pt <= KING; pt++)
2026 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2029 if (failedStep) (*failedStep)++;
2032 for (Color c = WHITE; c <= BLACK; c++)
2033 for (PieceType pt = PAWN; pt <= KING; pt++)
2034 for (int i = 0; i < pieceCount[c][pt]; i++)
2036 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2039 if (index[piece_list(c, pt, i)] != i)
2044 if (failedStep) (*failedStep)++;
2045 if (debugCastleSquares) {
2046 for (Color c = WHITE; c <= BLACK; c++) {
2047 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2049 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2052 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2054 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2056 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2058 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2062 if (failedStep) *failedStep = 0;