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;
251 st->key = compute_key();
252 st->pawnKey = compute_pawn_key();
253 st->materialKey = compute_material_key();
254 st->value = compute_value();
255 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
256 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
260 cout << "Error in FEN string: " << fen << endl;
264 /// Position::set_castling_rights() sets castling parameters castling avaiability.
265 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
266 /// that uses the letters of the columns on which the rooks began the game instead
267 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
268 /// associated with the castling right, the traditional castling tag will be replaced
269 /// by the file letter of the involved rook as for the Shredder-FEN.
271 bool Position::set_castling_rights(char token) {
273 Color c = token >= 'a' ? BLACK : WHITE;
274 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
275 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
276 Piece rook = (c == WHITE ? WR : BR);
278 initialKFile = square_file(king_square(c));
279 token = char(toupper(token));
283 for (Square sq = sqH; sq >= sqA; sq--)
284 if (piece_on(sq) == rook)
287 initialKRFile = square_file(sq);
291 else if (token == 'Q')
293 for (Square sq = sqA; sq <= sqH; sq++)
294 if (piece_on(sq) == rook)
297 initialQRFile = square_file(sq);
301 else if (token >= 'A' && token <= 'H')
303 File rookFile = File(token - 'A') + FILE_A;
304 if (rookFile < initialKFile)
307 initialQRFile = rookFile;
312 initialKRFile = rookFile;
321 /// Position::to_fen() returns a FEN representation of the position. In case
322 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
324 const string Position::to_fen() const {
330 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
332 for (File file = FILE_A; file <= FILE_H; file++)
334 sq = make_square(file, rank);
336 if (square_is_occupied(sq))
339 fen += pieceLetters.from_piece(piece_on(sq));
349 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
350 fen.erase(--fen.end());
351 fen += (sideToMove == WHITE ? " w " : " b ");
353 if (st->castleRights != CASTLES_NONE)
355 const bool Chess960 = initialKFile != FILE_E
356 || initialQRFile != FILE_A
357 || initialKRFile != FILE_H;
359 if (can_castle_kingside(WHITE))
360 fen += Chess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
362 if (can_castle_queenside(WHITE))
363 fen += Chess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
365 if (can_castle_kingside(BLACK))
366 fen += Chess960 ? file_to_char(initialKRFile) : 'k';
368 if (can_castle_queenside(BLACK))
369 fen += Chess960 ? 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
849 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
851 // Set en passant square, only if moved pawn can be captured
852 if ((to ^ from) == 16)
854 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
856 st->epSquare = Square((int(from) + int(to)) / 2);
857 key ^= zobEp[st->epSquare];
861 if (pm) // promotion ?
863 PieceType promotion = move_promotion_piece(m);
865 assert(promotion >= KNIGHT && promotion <= QUEEN);
867 // Insert promoted piece instead of pawn
868 clear_bit(&(byTypeBB[PAWN]), to);
869 set_bit(&(byTypeBB[promotion]), to);
870 board[to] = piece_of_color_and_type(us, promotion);
872 // Update piece counts
873 pieceCount[us][promotion]++;
874 pieceCount[us][PAWN]--;
876 // Update material key
877 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
878 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
880 // Update piece lists, move the last pawn at index[to] position
881 // and shrink the list. Add a new promotion piece to the list.
882 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
883 index[lastPawnSquare] = index[to];
884 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
885 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
886 index[to] = pieceCount[us][promotion] - 1;
887 pieceList[us][promotion][index[to]] = to;
889 // Partially revert hash keys update
890 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
891 st->pawnKey ^= zobrist[us][PAWN][to];
893 // Partially revert and update incremental scores
894 st->value -= pst(us, PAWN, to);
895 st->value += pst(us, promotion, to);
898 st->npMaterial[us] += PieceValueMidgame[promotion];
902 // Update incremental scores
903 st->value += pst_delta(piece, from, to);
906 st->capturedType = capture;
908 // Update the key with the final value
911 // Update checkers bitboard, piece must be already moved
912 st->checkersBB = EmptyBoardBB;
917 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
921 if (bit_is_set(ci.checkSq[pt], to))
922 st->checkersBB = SetMaskBB[to];
925 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
928 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
931 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
937 sideToMove = opposite_color(sideToMove);
938 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
944 /// Position::do_capture_move() is a private method used to update captured
945 /// piece info. It is called from the main Position::do_move function.
947 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
949 assert(capture != KING);
953 // If the captured piece was a pawn, update pawn hash key,
954 // otherwise update non-pawn material.
957 if (ep) // en passant ?
959 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
961 assert(to == st->epSquare);
962 assert(relative_rank(opposite_color(them), to) == RANK_6);
963 assert(piece_on(to) == PIECE_NONE);
964 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
966 board[capsq] = PIECE_NONE;
968 st->pawnKey ^= zobrist[them][PAWN][capsq];
971 st->npMaterial[them] -= PieceValueMidgame[capture];
973 // Remove captured piece
974 clear_bit(&(byColorBB[them]), capsq);
975 clear_bit(&(byTypeBB[capture]), capsq);
976 clear_bit(&(byTypeBB[0]), capsq);
979 key ^= zobrist[them][capture][capsq];
981 // Update incremental scores
982 st->value -= pst(them, capture, capsq);
984 // Update piece count
985 pieceCount[them][capture]--;
987 // Update material hash key
988 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
990 // Update piece list, move the last piece at index[capsq] position
992 // WARNING: This is a not perfectly revresible operation. When we
993 // will reinsert the captured piece in undo_move() we will put it
994 // at the end of the list and not in its original place, it means
995 // index[] and pieceList[] are not guaranteed to be invariant to a
996 // do_move() + undo_move() sequence.
997 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
998 index[lastPieceSquare] = index[capsq];
999 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1000 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1002 // Reset rule 50 counter
1007 /// Position::do_castle_move() is a private method used to make a castling
1008 /// move. It is called from the main Position::do_move function. Note that
1009 /// castling moves are encoded as "king captures friendly rook" moves, for
1010 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1012 void Position::do_castle_move(Move m) {
1014 assert(move_is_ok(m));
1015 assert(move_is_castle(m));
1017 Color us = side_to_move();
1018 Color them = opposite_color(us);
1020 // Reset capture field
1021 st->capturedType = PIECE_TYPE_NONE;
1023 // Find source squares for king and rook
1024 Square kfrom = move_from(m);
1025 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1028 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1029 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1031 // Find destination squares for king and rook
1032 if (rfrom > kfrom) // O-O
1034 kto = relative_square(us, SQ_G1);
1035 rto = relative_square(us, SQ_F1);
1037 kto = relative_square(us, SQ_C1);
1038 rto = relative_square(us, SQ_D1);
1041 // Remove pieces from source squares:
1042 clear_bit(&(byColorBB[us]), kfrom);
1043 clear_bit(&(byTypeBB[KING]), kfrom);
1044 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1045 clear_bit(&(byColorBB[us]), rfrom);
1046 clear_bit(&(byTypeBB[ROOK]), rfrom);
1047 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1049 // Put pieces on destination squares:
1050 set_bit(&(byColorBB[us]), kto);
1051 set_bit(&(byTypeBB[KING]), kto);
1052 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1053 set_bit(&(byColorBB[us]), rto);
1054 set_bit(&(byTypeBB[ROOK]), rto);
1055 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1057 // Update board array
1058 Piece king = piece_of_color_and_type(us, KING);
1059 Piece rook = piece_of_color_and_type(us, ROOK);
1060 board[kfrom] = board[rfrom] = PIECE_NONE;
1064 // Update piece lists
1065 pieceList[us][KING][index[kfrom]] = kto;
1066 pieceList[us][ROOK][index[rfrom]] = rto;
1067 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1068 index[kto] = index[kfrom];
1071 // Update incremental scores
1072 st->value += pst_delta(king, kfrom, kto);
1073 st->value += pst_delta(rook, rfrom, rto);
1076 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1077 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1079 // Clear en passant square
1080 if (st->epSquare != SQ_NONE)
1082 st->key ^= zobEp[st->epSquare];
1083 st->epSquare = SQ_NONE;
1086 // Update castling rights
1087 st->key ^= zobCastle[st->castleRights];
1088 st->castleRights &= castleRightsMask[kfrom];
1089 st->key ^= zobCastle[st->castleRights];
1091 // Reset rule 50 counter
1094 // Update checkers BB
1095 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1098 sideToMove = opposite_color(sideToMove);
1099 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1105 /// Position::undo_move() unmakes a move. When it returns, the position should
1106 /// be restored to exactly the same state as before the move was made.
1108 void Position::undo_move(Move m) {
1111 assert(move_is_ok(m));
1113 sideToMove = opposite_color(sideToMove);
1115 if (move_is_castle(m))
1117 undo_castle_move(m);
1121 Color us = side_to_move();
1122 Color them = opposite_color(us);
1123 Square from = move_from(m);
1124 Square to = move_to(m);
1125 bool ep = move_is_ep(m);
1126 bool pm = move_is_promotion(m);
1128 PieceType pt = type_of_piece_on(to);
1130 assert(square_is_empty(from));
1131 assert(color_of_piece_on(to) == us);
1132 assert(!pm || relative_rank(us, to) == RANK_8);
1133 assert(!ep || to == st->previous->epSquare);
1134 assert(!ep || relative_rank(us, to) == RANK_6);
1135 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1137 if (pm) // promotion ?
1139 PieceType promotion = move_promotion_piece(m);
1142 assert(promotion >= KNIGHT && promotion <= QUEEN);
1143 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1145 // Replace promoted piece with a pawn
1146 clear_bit(&(byTypeBB[promotion]), to);
1147 set_bit(&(byTypeBB[PAWN]), to);
1149 // Update piece counts
1150 pieceCount[us][promotion]--;
1151 pieceCount[us][PAWN]++;
1153 // Update piece list replacing promotion piece with a pawn
1154 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1155 index[lastPromotionSquare] = index[to];
1156 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1157 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1158 index[to] = pieceCount[us][PAWN] - 1;
1159 pieceList[us][PAWN][index[to]] = to;
1162 // Put the piece back at the source square
1163 Bitboard move_bb = make_move_bb(to, from);
1164 do_move_bb(&(byColorBB[us]), move_bb);
1165 do_move_bb(&(byTypeBB[pt]), move_bb);
1166 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1168 board[from] = piece_of_color_and_type(us, pt);
1169 board[to] = PIECE_NONE;
1171 // Update piece list
1172 index[from] = index[to];
1173 pieceList[us][pt][index[from]] = from;
1175 if (st->capturedType)
1180 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1182 assert(st->capturedType != KING);
1183 assert(!ep || square_is_empty(capsq));
1185 // Restore the captured piece
1186 set_bit(&(byColorBB[them]), capsq);
1187 set_bit(&(byTypeBB[st->capturedType]), capsq);
1188 set_bit(&(byTypeBB[0]), capsq);
1190 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1192 // Update piece count
1193 pieceCount[them][st->capturedType]++;
1195 // Update piece list, add a new captured piece in capsq square
1196 index[capsq] = pieceCount[them][st->capturedType] - 1;
1197 pieceList[them][st->capturedType][index[capsq]] = capsq;
1200 // Finally point our state pointer back to the previous state
1207 /// Position::undo_castle_move() is a private method used to unmake a castling
1208 /// move. It is called from the main Position::undo_move function. Note that
1209 /// castling moves are encoded as "king captures friendly rook" moves, for
1210 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1212 void Position::undo_castle_move(Move m) {
1214 assert(move_is_ok(m));
1215 assert(move_is_castle(m));
1217 // When we have arrived here, some work has already been done by
1218 // Position::undo_move. In particular, the side to move has been switched,
1219 // so the code below is correct.
1220 Color us = side_to_move();
1222 // Find source squares for king and rook
1223 Square kfrom = move_from(m);
1224 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1227 // Find destination squares for king and rook
1228 if (rfrom > kfrom) // O-O
1230 kto = relative_square(us, SQ_G1);
1231 rto = relative_square(us, SQ_F1);
1233 kto = relative_square(us, SQ_C1);
1234 rto = relative_square(us, SQ_D1);
1237 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1238 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1240 // Remove pieces from destination squares:
1241 clear_bit(&(byColorBB[us]), kto);
1242 clear_bit(&(byTypeBB[KING]), kto);
1243 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1244 clear_bit(&(byColorBB[us]), rto);
1245 clear_bit(&(byTypeBB[ROOK]), rto);
1246 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1248 // Put pieces on source squares:
1249 set_bit(&(byColorBB[us]), kfrom);
1250 set_bit(&(byTypeBB[KING]), kfrom);
1251 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1252 set_bit(&(byColorBB[us]), rfrom);
1253 set_bit(&(byTypeBB[ROOK]), rfrom);
1254 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1257 board[rto] = board[kto] = PIECE_NONE;
1258 board[rfrom] = piece_of_color_and_type(us, ROOK);
1259 board[kfrom] = piece_of_color_and_type(us, KING);
1261 // Update piece lists
1262 pieceList[us][KING][index[kto]] = kfrom;
1263 pieceList[us][ROOK][index[rto]] = rfrom;
1264 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1265 index[kfrom] = index[kto];
1268 // Finally point our state pointer back to the previous state
1275 /// Position::do_null_move makes() a "null move": It switches the side to move
1276 /// and updates the hash key without executing any move on the board.
1278 void Position::do_null_move(StateInfo& backupSt) {
1281 assert(!is_check());
1283 // Back up the information necessary to undo the null move to the supplied
1284 // StateInfo object.
1285 // Note that differently from normal case here backupSt is actually used as
1286 // a backup storage not as a new state to be used.
1287 backupSt.key = st->key;
1288 backupSt.epSquare = st->epSquare;
1289 backupSt.value = st->value;
1290 backupSt.previous = st->previous;
1291 backupSt.pliesFromNull = st->pliesFromNull;
1292 st->previous = &backupSt;
1294 // Save the current key to the history[] array, in order to be able to
1295 // detect repetition draws.
1296 history[st->gamePly++] = st->key;
1298 // Update the necessary information
1299 if (st->epSquare != SQ_NONE)
1300 st->key ^= zobEp[st->epSquare];
1302 st->key ^= zobSideToMove;
1303 prefetch((char*)TT.first_entry(st->key));
1305 sideToMove = opposite_color(sideToMove);
1306 st->epSquare = SQ_NONE;
1308 st->pliesFromNull = 0;
1309 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1313 /// Position::undo_null_move() unmakes a "null move".
1315 void Position::undo_null_move() {
1318 assert(!is_check());
1320 // Restore information from the our backup StateInfo object
1321 StateInfo* backupSt = st->previous;
1322 st->key = backupSt->key;
1323 st->epSquare = backupSt->epSquare;
1324 st->value = backupSt->value;
1325 st->previous = backupSt->previous;
1326 st->pliesFromNull = backupSt->pliesFromNull;
1328 // Update the necessary information
1329 sideToMove = opposite_color(sideToMove);
1335 /// Position::see() is a static exchange evaluator: It tries to estimate the
1336 /// material gain or loss resulting from a move. There are three versions of
1337 /// this function: One which takes a destination square as input, one takes a
1338 /// move, and one which takes a 'from' and a 'to' square. The function does
1339 /// not yet understand promotions captures.
1341 int Position::see(Square to) const {
1343 assert(square_is_ok(to));
1344 return see(SQ_NONE, to);
1347 int Position::see(Move m) const {
1349 assert(move_is_ok(m));
1350 return see(move_from(m), move_to(m));
1353 int Position::see_sign(Move m) const {
1355 assert(move_is_ok(m));
1357 Square from = move_from(m);
1358 Square to = move_to(m);
1360 // Early return if SEE cannot be negative because captured piece value
1361 // is not less then capturing one. Note that king moves always return
1362 // here because king midgame value is set to 0.
1363 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1366 return see(from, to);
1369 int Position::see(Square from, Square to) const {
1372 static const int seeValues[18] = {
1373 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1374 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1375 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1376 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1380 Bitboard attackers, stmAttackers, b;
1382 assert(square_is_ok(from) || from == SQ_NONE);
1383 assert(square_is_ok(to));
1385 // Initialize colors
1386 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1387 Color them = opposite_color(us);
1389 // Initialize pieces
1390 Piece piece = piece_on(from);
1391 Piece capture = piece_on(to);
1392 Bitboard occ = occupied_squares();
1394 // King cannot be recaptured
1395 if (type_of_piece(piece) == KING)
1396 return seeValues[capture];
1398 // Handle en passant moves
1399 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1401 assert(capture == PIECE_NONE);
1403 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1404 capture = piece_on(capQq);
1405 assert(type_of_piece_on(capQq) == PAWN);
1407 // Remove the captured pawn
1408 clear_bit(&occ, capQq);
1413 // Find all attackers to the destination square, with the moving piece
1414 // removed, but possibly an X-ray attacker added behind it.
1415 clear_bit(&occ, from);
1416 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1417 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1418 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1419 | (attacks_from<KING>(to) & pieces(KING))
1420 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1421 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1423 if (from != SQ_NONE)
1426 // If we don't have any attacker we are finished
1427 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1430 // Locate the least valuable attacker to the destination square
1431 // and use it to initialize from square.
1432 stmAttackers = attackers & pieces_of_color(us);
1434 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1437 from = first_1(stmAttackers & pieces(pt));
1438 piece = piece_on(from);
1441 // If the opponent has no attackers we are finished
1442 stmAttackers = attackers & pieces_of_color(them);
1444 return seeValues[capture];
1446 attackers &= occ; // Remove the moving piece
1448 // The destination square is defended, which makes things rather more
1449 // difficult to compute. We proceed by building up a "swap list" containing
1450 // the material gain or loss at each stop in a sequence of captures to the
1451 // destination square, where the sides alternately capture, and always
1452 // capture with the least valuable piece. After each capture, we look for
1453 // new X-ray attacks from behind the capturing piece.
1454 int lastCapturingPieceValue = seeValues[piece];
1455 int swapList[32], n = 1;
1459 swapList[0] = seeValues[capture];
1462 // Locate the least valuable attacker for the side to move. The loop
1463 // below looks like it is potentially infinite, but it isn't. We know
1464 // that the side to move still has at least one attacker left.
1465 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1468 // Remove the attacker we just found from the 'attackers' bitboard,
1469 // and scan for new X-ray attacks behind the attacker.
1470 b = stmAttackers & pieces(pt);
1471 occ ^= (b & (~b + 1));
1472 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1473 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1477 // Add the new entry to the swap list
1479 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1482 // Remember the value of the capturing piece, and change the side to move
1483 // before beginning the next iteration
1484 lastCapturingPieceValue = seeValues[pt];
1485 c = opposite_color(c);
1486 stmAttackers = attackers & pieces_of_color(c);
1488 // Stop after a king capture
1489 if (pt == KING && stmAttackers)
1492 swapList[n++] = QueenValueMidgame*10;
1495 } while (stmAttackers);
1497 // Having built the swap list, we negamax through it to find the best
1498 // achievable score from the point of view of the side to move
1500 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1506 /// Position::clear() erases the position object to a pristine state, with an
1507 /// empty board, white to move, and no castling rights.
1509 void Position::clear() {
1512 memset(st, 0, sizeof(StateInfo));
1513 st->epSquare = SQ_NONE;
1514 startPosPlyCounter = 0;
1516 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1517 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1518 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1519 memset(index, 0, sizeof(int) * 64);
1521 for (int i = 0; i < 64; i++)
1522 board[i] = PIECE_NONE;
1524 for (int i = 0; i < 8; i++)
1525 for (int j = 0; j < 16; j++)
1526 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1528 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1529 castleRightsMask[sq] = ALL_CASTLES;
1532 initialKFile = FILE_E;
1533 initialKRFile = FILE_H;
1534 initialQRFile = FILE_A;
1538 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1539 /// UCI interface code, whenever a non-reversible move is made in a
1540 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1541 /// for the program to handle games of arbitrary length, as long as the GUI
1542 /// handles draws by the 50 move rule correctly.
1544 void Position::reset_game_ply() {
1549 void Position::inc_startpos_ply_counter() {
1551 startPosPlyCounter++;
1554 /// Position::put_piece() puts a piece on the given square of the board,
1555 /// updating the board array, bitboards, and piece counts.
1557 void Position::put_piece(Piece p, Square s) {
1559 Color c = color_of_piece(p);
1560 PieceType pt = type_of_piece(p);
1563 index[s] = pieceCount[c][pt];
1564 pieceList[c][pt][index[s]] = s;
1566 set_bit(&(byTypeBB[pt]), s);
1567 set_bit(&(byColorBB[c]), s);
1568 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1570 pieceCount[c][pt]++;
1574 /// Position::allow_oo() gives the given side the right to castle kingside.
1575 /// Used when setting castling rights during parsing of FEN strings.
1577 void Position::allow_oo(Color c) {
1579 st->castleRights |= (1 + int(c));
1583 /// Position::allow_ooo() gives the given side the right to castle queenside.
1584 /// Used when setting castling rights during parsing of FEN strings.
1586 void Position::allow_ooo(Color c) {
1588 st->castleRights |= (4 + 4*int(c));
1592 /// Position::compute_key() computes the hash key of the position. The hash
1593 /// key is usually updated incrementally as moves are made and unmade, the
1594 /// compute_key() function is only used when a new position is set up, and
1595 /// to verify the correctness of the hash key when running in debug mode.
1597 Key Position::compute_key() const {
1599 Key result = Key(0ULL);
1601 for (Square s = SQ_A1; s <= SQ_H8; s++)
1602 if (square_is_occupied(s))
1603 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1605 if (ep_square() != SQ_NONE)
1606 result ^= zobEp[ep_square()];
1608 result ^= zobCastle[st->castleRights];
1609 if (side_to_move() == BLACK)
1610 result ^= zobSideToMove;
1616 /// Position::compute_pawn_key() computes the hash key of the position. The
1617 /// hash key is usually updated incrementally as moves are made and unmade,
1618 /// the compute_pawn_key() function is only used when a new position is set
1619 /// up, and to verify the correctness of the pawn hash key when running in
1622 Key Position::compute_pawn_key() const {
1624 Key result = Key(0ULL);
1628 for (Color c = WHITE; c <= BLACK; c++)
1630 b = pieces(PAWN, c);
1633 s = pop_1st_bit(&b);
1634 result ^= zobrist[c][PAWN][s];
1641 /// Position::compute_material_key() computes the hash key of the position.
1642 /// The hash key is usually updated incrementally as moves are made and unmade,
1643 /// the compute_material_key() function is only used when a new position is set
1644 /// up, and to verify the correctness of the material hash key when running in
1647 Key Position::compute_material_key() const {
1649 Key result = Key(0ULL);
1650 for (Color c = WHITE; c <= BLACK; c++)
1651 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1653 int count = piece_count(c, pt);
1654 for (int i = 0; i < count; i++)
1655 result ^= zobrist[c][pt][i];
1661 /// Position::compute_value() compute the incremental scores for the middle
1662 /// game and the endgame. These functions are used to initialize the incremental
1663 /// scores when a new position is set up, and to verify that the scores are correctly
1664 /// updated by do_move and undo_move when the program is running in debug mode.
1665 Score Position::compute_value() const {
1667 Score result = SCORE_ZERO;
1671 for (Color c = WHITE; c <= BLACK; c++)
1672 for (PieceType pt = PAWN; pt <= KING; pt++)
1677 s = pop_1st_bit(&b);
1678 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1679 result += pst(c, pt, s);
1683 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1688 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1689 /// game material score for the given side. Material scores are updated
1690 /// incrementally during the search, this function is only used while
1691 /// initializing a new Position object.
1693 Value Position::compute_non_pawn_material(Color c) const {
1695 Value result = VALUE_ZERO;
1697 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1699 Bitboard b = pieces(pt, c);
1702 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1705 result += PieceValueMidgame[pt];
1712 /// Position::is_draw() tests whether the position is drawn by material,
1713 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1714 /// must be done by the search.
1715 // FIXME: Currently we are not handling 50 move rule correctly when in check
1717 bool Position::is_draw() const {
1719 // Draw by material?
1721 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1724 // Draw by the 50 moves rule?
1725 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1728 // Draw by repetition?
1729 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1730 if (history[st->gamePly - i] == st->key)
1737 /// Position::is_mate() returns true or false depending on whether the
1738 /// side to move is checkmated.
1740 bool Position::is_mate() const {
1742 MoveStack moves[256];
1743 return is_check() && (generate_moves(*this, moves) == moves);
1747 /// Position::has_mate_threat() tests whether the side to move is under
1748 /// a threat of being mated in one from the current position.
1750 bool Position::has_mate_threat() {
1752 MoveStack mlist[256], *last, *cur;
1754 bool mateFound = false;
1756 // If we are under check it's up to evasions to do the job
1760 // First pass the move to our opponent doing a null move
1763 // Then generate pseudo-legal moves that give check
1764 last = generate_non_capture_checks(*this, mlist);
1765 last = generate_captures(*this, last);
1767 // Loop through the moves, and see if one of them gives mate
1768 Bitboard pinned = pinned_pieces(sideToMove);
1769 CheckInfo ci(*this);
1770 for (cur = mlist; cur != last && !mateFound; cur++)
1772 Move move = cur->move;
1773 if ( !pl_move_is_legal(move, pinned)
1774 || !move_is_check(move, ci))
1777 do_move(move, st2, ci, true);
1790 /// Position::init_zobrist() is a static member function which initializes at
1791 /// startup the various arrays used to compute hash keys.
1793 void Position::init_zobrist() {
1797 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1798 zobrist[i][j][k] = Key(genrand_int64());
1800 for (i = 0; i < 64; i++)
1801 zobEp[i] = Key(genrand_int64());
1803 for (i = 0; i < 16; i++)
1804 zobCastle[i] = Key(genrand_int64());
1806 zobSideToMove = Key(genrand_int64());
1807 zobExclusion = Key(genrand_int64());
1811 /// Position::init_piece_square_tables() initializes the piece square tables.
1812 /// This is a two-step operation: First, the white halves of the tables are
1813 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1814 /// of the tables are initialized by mirroring and changing the sign of the
1815 /// corresponding white scores.
1817 void Position::init_piece_square_tables() {
1819 for (Square s = SQ_A1; s <= SQ_H8; s++)
1820 for (Piece p = WP; p <= WK; p++)
1821 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1823 for (Square s = SQ_A1; s <= SQ_H8; s++)
1824 for (Piece p = BP; p <= BK; p++)
1825 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1829 /// Position::flipped_copy() makes a copy of the input position, but with
1830 /// the white and black sides reversed. This is only useful for debugging,
1831 /// especially for finding evaluation symmetry bugs.
1833 void Position::flipped_copy(const Position& pos) {
1835 assert(pos.is_ok());
1838 threadID = pos.thread();
1841 for (Square s = SQ_A1; s <= SQ_H8; s++)
1842 if (!pos.square_is_empty(s))
1843 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1846 sideToMove = opposite_color(pos.side_to_move());
1849 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1850 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1851 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1852 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1854 initialKFile = pos.initialKFile;
1855 initialKRFile = pos.initialKRFile;
1856 initialQRFile = pos.initialQRFile;
1858 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1859 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1860 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1861 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1862 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1863 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1865 // En passant square
1866 if (pos.st->epSquare != SQ_NONE)
1867 st->epSquare = flip_square(pos.st->epSquare);
1873 st->key = compute_key();
1874 st->pawnKey = compute_pawn_key();
1875 st->materialKey = compute_material_key();
1877 // Incremental scores
1878 st->value = compute_value();
1881 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1882 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1888 /// Position::is_ok() performs some consitency checks for the position object.
1889 /// This is meant to be helpful when debugging.
1891 bool Position::is_ok(int* failedStep) const {
1893 // What features of the position should be verified?
1894 static const bool debugBitboards = false;
1895 static const bool debugKingCount = false;
1896 static const bool debugKingCapture = false;
1897 static const bool debugCheckerCount = false;
1898 static const bool debugKey = false;
1899 static const bool debugMaterialKey = false;
1900 static const bool debugPawnKey = false;
1901 static const bool debugIncrementalEval = false;
1902 static const bool debugNonPawnMaterial = false;
1903 static const bool debugPieceCounts = false;
1904 static const bool debugPieceList = false;
1905 static const bool debugCastleSquares = false;
1907 if (failedStep) *failedStep = 1;
1910 if (!color_is_ok(side_to_move()))
1913 // Are the king squares in the position correct?
1914 if (failedStep) (*failedStep)++;
1915 if (piece_on(king_square(WHITE)) != WK)
1918 if (failedStep) (*failedStep)++;
1919 if (piece_on(king_square(BLACK)) != BK)
1923 if (failedStep) (*failedStep)++;
1924 if (!file_is_ok(initialKRFile))
1927 if (!file_is_ok(initialQRFile))
1930 // Do both sides have exactly one king?
1931 if (failedStep) (*failedStep)++;
1934 int kingCount[2] = {0, 0};
1935 for (Square s = SQ_A1; s <= SQ_H8; s++)
1936 if (type_of_piece_on(s) == KING)
1937 kingCount[color_of_piece_on(s)]++;
1939 if (kingCount[0] != 1 || kingCount[1] != 1)
1943 // Can the side to move capture the opponent's king?
1944 if (failedStep) (*failedStep)++;
1945 if (debugKingCapture)
1947 Color us = side_to_move();
1948 Color them = opposite_color(us);
1949 Square ksq = king_square(them);
1950 if (attackers_to(ksq) & pieces_of_color(us))
1954 // Is there more than 2 checkers?
1955 if (failedStep) (*failedStep)++;
1956 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1960 if (failedStep) (*failedStep)++;
1963 // The intersection of the white and black pieces must be empty
1964 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1967 // The union of the white and black pieces must be equal to all
1969 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1972 // Separate piece type bitboards must have empty intersections
1973 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1974 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1975 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1979 // En passant square OK?
1980 if (failedStep) (*failedStep)++;
1981 if (ep_square() != SQ_NONE)
1983 // The en passant square must be on rank 6, from the point of view of the
1985 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1990 if (failedStep) (*failedStep)++;
1991 if (debugKey && st->key != compute_key())
1994 // Pawn hash key OK?
1995 if (failedStep) (*failedStep)++;
1996 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1999 // Material hash key OK?
2000 if (failedStep) (*failedStep)++;
2001 if (debugMaterialKey && st->materialKey != compute_material_key())
2004 // Incremental eval OK?
2005 if (failedStep) (*failedStep)++;
2006 if (debugIncrementalEval && st->value != compute_value())
2009 // Non-pawn material OK?
2010 if (failedStep) (*failedStep)++;
2011 if (debugNonPawnMaterial)
2013 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2016 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2021 if (failedStep) (*failedStep)++;
2022 if (debugPieceCounts)
2023 for (Color c = WHITE; c <= BLACK; c++)
2024 for (PieceType pt = PAWN; pt <= KING; pt++)
2025 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2028 if (failedStep) (*failedStep)++;
2031 for (Color c = WHITE; c <= BLACK; c++)
2032 for (PieceType pt = PAWN; pt <= KING; pt++)
2033 for (int i = 0; i < pieceCount[c][pt]; i++)
2035 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2038 if (index[piece_list(c, pt, i)] != i)
2043 if (failedStep) (*failedStep)++;
2044 if (debugCastleSquares) {
2045 for (Color c = WHITE; c <= BLACK; c++) {
2046 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2048 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2051 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2053 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2055 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2057 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2061 if (failedStep) *failedStep = 0;