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"
49 //// Position's static data definitions
52 Key Position::zobrist[2][8][64];
53 Key Position::zobEp[64];
54 Key Position::zobCastle[16];
55 Key Position::zobSideToMove;
56 Key Position::zobExclusion;
58 Score Position::PieceSquareTable[16][64];
60 // Material values arrays, indexed by Piece
61 const Value Position::PieceValueMidgame[17] = {
63 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
64 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
65 VALUE_ZERO, VALUE_ZERO,
66 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
67 RookValueMidgame, QueenValueMidgame
70 const Value Position::PieceValueEndgame[17] = {
72 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
73 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
74 VALUE_ZERO, VALUE_ZERO,
75 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
76 RookValueEndgame, QueenValueEndgame
79 // Material values array used by SEE, indexed by PieceType
80 const Value Position::seeValues[] = {
82 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
83 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
89 // Bonus for having the side to move (modified by Joona Kiiski)
90 const Score TempoValue = make_score(48, 22);
92 bool isZero(char c) { return c == '0'; }
94 struct PieceLetters : public std::map<char, Piece> {
98 operator[]('K') = WK; operator[]('k') = BK;
99 operator[]('Q') = WQ; operator[]('q') = BQ;
100 operator[]('R') = WR; operator[]('r') = BR;
101 operator[]('B') = WB; operator[]('b') = BB;
102 operator[]('N') = WN; operator[]('n') = BN;
103 operator[]('P') = WP; operator[]('p') = BP;
104 operator[](' ') = PIECE_NONE;
105 operator[]('.') = PIECE_NONE_DARK_SQ;
108 char from_piece(Piece p) const {
110 std::map<char, Piece>::const_iterator it;
111 for (it = begin(); it != end(); ++it)
120 PieceLetters pieceLetters;
126 CheckInfo::CheckInfo(const Position& pos) {
128 Color us = pos.side_to_move();
129 Color them = opposite_color(us);
131 ksq = pos.king_square(them);
132 dcCandidates = pos.discovered_check_candidates(us);
134 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
135 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
136 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
137 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
138 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
139 checkSq[KING] = EmptyBoardBB;
143 /// Position c'tors. Here we always create a copy of the original position
144 /// or the FEN string, we want the new born Position object do not depend
145 /// on any external data so we detach state pointer from the source one.
147 Position::Position(const Position& pos, int th) {
149 memcpy(this, &pos, sizeof(Position));
150 detach(); // Always detach() in copy c'tor to avoid surprises
155 Position::Position(const string& fen, bool isChess960, int th) {
157 from_fen(fen, isChess960);
162 /// Position::detach() copies the content of the current state and castling
163 /// masks inside the position itself. This is needed when the st pointee could
164 /// become stale, as example because the caller is about to going out of scope.
166 void Position::detach() {
170 st->previous = NULL; // as a safe guard
174 /// Position::from_fen() initializes the position object with the given FEN
175 /// string. This function is not very robust - make sure that input FENs are
176 /// correct (this is assumed to be the responsibility of the GUI).
178 void Position::from_fen(const string& fen, bool c960) {
180 A FEN string defines a particular position using only the ASCII character set.
182 A FEN string contains six fields. The separator between fields is a space. The fields are:
184 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
185 with rank 1; within each rank, the contents of each square are described from file a through file h.
186 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
187 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
188 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
189 of blank squares), and "/" separate ranks.
191 2) Active color. "w" means white moves next, "b" means black.
193 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
194 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
195 kingside), and/or "q" (Black can castle queenside).
197 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
198 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
199 regardless of whether there is a pawn in position to make an en passant capture.
201 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
202 to determine if a draw can be claimed under the fifty-move rule.
204 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
209 std::istringstream ss(fen);
215 // 1. Piece placement field
216 while (ss.get(token) && token != ' ')
220 file += File(token - '0'); // Skip the given number of files
223 else if (token == '/')
230 if (pieceLetters.find(token) == pieceLetters.end())
233 put_piece(pieceLetters[token], make_square(file, rank));
238 if (!ss.get(token) || (token != 'w' && token != 'b'))
241 sideToMove = (token == 'w' ? WHITE : BLACK);
243 if (!ss.get(token) || token != ' ')
246 // 3. Castling availability
247 while (ss.get(token) && token != ' ')
252 if (!set_castling_rights(token))
256 // 4. En passant square -- ignore if no capture is possible
258 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
259 && (ss.get(row) && (row == '3' || row == '6')))
261 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
262 Color them = opposite_color(sideToMove);
264 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
265 st->epSquare = fenEpSquare;
272 // 6. Fullmove number
274 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
276 // Various initialisations
277 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
278 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
279 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
280 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
281 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
282 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
287 st->key = compute_key();
288 st->pawnKey = compute_pawn_key();
289 st->materialKey = compute_material_key();
290 st->value = compute_value();
291 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
292 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
296 cout << "Error in FEN string: " << fen << endl;
300 /// Position::set_castling_rights() sets castling parameters castling avaiability.
301 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
302 /// that uses the letters of the columns on which the rooks began the game instead
303 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
304 /// associated with the castling right, the traditional castling tag will be replaced
305 /// by the file letter of the involved rook as for the Shredder-FEN.
307 bool Position::set_castling_rights(char token) {
309 Color c = token >= 'a' ? BLACK : WHITE;
310 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
311 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
312 Piece rook = (c == WHITE ? WR : BR);
314 initialKFile = square_file(king_square(c));
315 token = char(toupper(token));
319 for (Square sq = sqH; sq >= sqA; sq--)
320 if (piece_on(sq) == rook)
323 initialKRFile = square_file(sq);
327 else if (token == 'Q')
329 for (Square sq = sqA; sq <= sqH; sq++)
330 if (piece_on(sq) == rook)
333 initialQRFile = square_file(sq);
337 else if (token >= 'A' && token <= 'H')
339 File rookFile = File(token - 'A') + FILE_A;
340 if (rookFile < initialKFile)
343 initialQRFile = rookFile;
348 initialKRFile = rookFile;
357 /// Position::to_fen() returns a FEN representation of the position. In case
358 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
360 const string Position::to_fen() const {
366 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
368 for (File file = FILE_A; file <= FILE_H; file++)
370 sq = make_square(file, rank);
372 if (square_is_occupied(sq))
375 fen += pieceLetters.from_piece(piece_on(sq));
385 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
386 fen.erase(--fen.end());
387 fen += (sideToMove == WHITE ? " w " : " b ");
389 if (st->castleRights != CASTLES_NONE)
391 if (can_castle_kingside(WHITE))
392 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
394 if (can_castle_queenside(WHITE))
395 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
397 if (can_castle_kingside(BLACK))
398 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
400 if (can_castle_queenside(BLACK))
401 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
405 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
410 /// Position::print() prints an ASCII representation of the position to
411 /// the standard output. If a move is given then also the san is printed.
413 void Position::print(Move move) const {
415 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
416 static bool requestPending = false;
418 // Check for reentrancy, as example when called from inside
419 // MovePicker that is used also here in move_to_san()
423 requestPending = true;
427 Position p(*this, thread());
428 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
429 cout << "\nMove is: " << dd << move_to_san(p, move);
432 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
434 cout << dottedLine << '|';
435 for (File file = FILE_A; file <= FILE_H; file++)
437 Square sq = make_square(file, rank);
438 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
439 Piece piece = piece_on(sq);
441 if (piece == PIECE_NONE && square_color(sq) == DARK)
442 piece = PIECE_NONE_DARK_SQ;
444 cout << c << pieceLetters.from_piece(piece) << c << '|';
447 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
448 requestPending = false;
452 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
453 /// king) pieces for the given color and for the given pinner type. Or, when
454 /// template parameter FindPinned is false, the pieces of the given color
455 /// candidate for a discovery check against the enemy king.
456 /// Bitboard checkersBB must be already updated when looking for pinners.
458 template<bool FindPinned>
459 Bitboard Position::hidden_checkers(Color c) const {
461 Bitboard result = EmptyBoardBB;
462 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
464 // Pinned pieces protect our king, dicovery checks attack
466 Square ksq = king_square(FindPinned ? c : opposite_color(c));
468 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
469 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
471 if (FindPinned && pinners)
472 pinners &= ~st->checkersBB;
476 Square s = pop_1st_bit(&pinners);
477 Bitboard b = squares_between(s, ksq) & occupied_squares();
481 if ( !(b & (b - 1)) // Only one bit set?
482 && (b & pieces_of_color(c))) // Is an our piece?
489 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
490 /// king) pieces for the given color. Note that checkersBB bitboard must
491 /// be already updated.
493 Bitboard Position::pinned_pieces(Color c) const {
495 return hidden_checkers<true>(c);
499 /// Position:discovered_check_candidates() returns a bitboard containing all
500 /// pieces for the given side which are candidates for giving a discovered
501 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
502 /// to be already updated.
504 Bitboard Position::discovered_check_candidates(Color c) const {
506 return hidden_checkers<false>(c);
509 /// Position::attackers_to() computes a bitboard containing all pieces which
510 /// attacks a given square.
512 Bitboard Position::attackers_to(Square s) const {
514 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
515 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
516 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
517 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
518 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
519 | (attacks_from<KING>(s) & pieces(KING));
522 /// Position::attacks_from() computes a bitboard of all attacks
523 /// of a given piece put in a given square.
525 Bitboard Position::attacks_from(Piece p, Square s) const {
527 assert(square_is_ok(s));
531 case WB: case BB: return attacks_from<BISHOP>(s);
532 case WR: case BR: return attacks_from<ROOK>(s);
533 case WQ: case BQ: return attacks_from<QUEEN>(s);
534 default: return NonSlidingAttacksBB[p][s];
538 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
540 assert(square_is_ok(s));
544 case WB: case BB: return bishop_attacks_bb(s, occ);
545 case WR: case BR: return rook_attacks_bb(s, occ);
546 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
547 default: return NonSlidingAttacksBB[p][s];
552 /// Position::move_attacks_square() tests whether a move from the current
553 /// position attacks a given square.
555 bool Position::move_attacks_square(Move m, Square s) const {
557 assert(move_is_ok(m));
558 assert(square_is_ok(s));
561 Square f = move_from(m), t = move_to(m);
563 assert(square_is_occupied(f));
565 if (bit_is_set(attacks_from(piece_on(f), t), s))
568 // Move the piece and scan for X-ray attacks behind it
569 occ = occupied_squares();
570 do_move_bb(&occ, make_move_bb(f, t));
571 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
572 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
573 & pieces_of_color(color_of_piece_on(f));
575 // If we have attacks we need to verify that are caused by our move
576 // and are not already existent ones.
577 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
581 /// Position::find_checkers() computes the checkersBB bitboard, which
582 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
583 /// currently works by calling Position::attackers_to, which is probably
584 /// inefficient. Consider rewriting this function to use the last move
585 /// played, like in non-bitboard versions of Glaurung.
587 void Position::find_checkers() {
589 Color us = side_to_move();
590 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
594 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
596 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
599 assert(move_is_ok(m));
600 assert(pinned == pinned_pieces(side_to_move()));
602 // Castling moves are checked for legality during move generation.
603 if (move_is_castle(m))
606 // En passant captures are a tricky special case. Because they are
607 // rather uncommon, we do it simply by testing whether the king is attacked
608 // after the move is made
611 Color us = side_to_move();
612 Color them = opposite_color(us);
613 Square from = move_from(m);
614 Square to = move_to(m);
615 Square capsq = make_square(square_file(to), square_rank(from));
616 Square ksq = king_square(us);
617 Bitboard b = occupied_squares();
619 assert(to == ep_square());
620 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
621 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
622 assert(piece_on(to) == PIECE_NONE);
625 clear_bit(&b, capsq);
628 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
629 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
632 Color us = side_to_move();
633 Square from = move_from(m);
635 assert(color_of_piece_on(from) == us);
636 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
638 // If the moving piece is a king, check whether the destination
639 // square is attacked by the opponent.
640 if (type_of_piece_on(from) == KING)
641 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
643 // A non-king move is legal if and only if it is not pinned or it
644 // is moving along the ray towards or away from the king.
646 || !bit_is_set(pinned, from)
647 || squares_aligned(from, move_to(m), king_square(us));
651 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
653 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
657 Color us = side_to_move();
658 Square from = move_from(m);
659 Square to = move_to(m);
661 // King moves and en-passant captures are verified in pl_move_is_legal()
662 if (type_of_piece_on(from) == KING || move_is_ep(m))
663 return pl_move_is_legal(m, pinned);
665 Bitboard target = checkers();
666 Square checksq = pop_1st_bit(&target);
668 if (target) // double check ?
671 // Our move must be a blocking evasion or a capture of the checking piece
672 target = squares_between(checksq, king_square(us)) | checkers();
673 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
677 /// Position::move_is_check() tests whether a pseudo-legal move is a check
679 bool Position::move_is_check(Move m) const {
681 return move_is_check(m, CheckInfo(*this));
684 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
687 assert(move_is_ok(m));
688 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
689 assert(color_of_piece_on(move_from(m)) == side_to_move());
690 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
692 Square from = move_from(m);
693 Square to = move_to(m);
694 PieceType pt = type_of_piece_on(from);
697 if (bit_is_set(ci.checkSq[pt], to))
701 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
703 // For pawn and king moves we need to verify also direction
704 if ( (pt != PAWN && pt != KING)
705 || !squares_aligned(from, to, ci.ksq))
709 // Can we skip the ugly special cases ?
710 if (!move_is_special(m))
713 Color us = side_to_move();
714 Bitboard b = occupied_squares();
716 // Promotion with check ?
717 if (move_is_promotion(m))
721 switch (move_promotion_piece(m))
724 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
726 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
728 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
730 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
736 // En passant capture with check ? We have already handled the case
737 // of direct checks and ordinary discovered check, the only case we
738 // need to handle is the unusual case of a discovered check through
739 // the captured pawn.
742 Square capsq = make_square(square_file(to), square_rank(from));
744 clear_bit(&b, capsq);
746 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
747 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
750 // Castling with check ?
751 if (move_is_castle(m))
753 Square kfrom, kto, rfrom, rto;
759 kto = relative_square(us, SQ_G1);
760 rto = relative_square(us, SQ_F1);
762 kto = relative_square(us, SQ_C1);
763 rto = relative_square(us, SQ_D1);
765 clear_bit(&b, kfrom);
766 clear_bit(&b, rfrom);
769 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
776 /// Position::do_setup_move() makes a permanent move on the board.
777 /// It should be used when setting up a position on board.
778 /// You can't undo the move.
780 void Position::do_setup_move(Move m, StateInfo& newSt) {
784 // Reset "game ply" in case we made a non-reversible move.
785 // "game ply" is used for repetition detection.
789 // Update the number of plies played from the starting position
790 startPosPlyCounter++;
793 /// Position::do_move() makes a move, and saves all information necessary
794 /// to a StateInfo object. The move is assumed to be legal.
795 /// Pseudo-legal moves should be filtered out before this function is called.
797 void Position::do_move(Move m, StateInfo& newSt) {
800 do_move(m, newSt, ci, move_is_check(m, ci));
803 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
806 assert(move_is_ok(m));
811 // Copy some fields of old state to our new StateInfo object except the
812 // ones which are recalculated from scratch anyway, then switch our state
813 // pointer to point to the new, ready to be updated, state.
814 struct ReducedStateInfo {
815 Key pawnKey, materialKey;
816 int castleRights, rule50, gamePly, pliesFromNull;
823 memcpy(&newSt, st, sizeof(ReducedStateInfo));
828 // Save the current key to the history[] array, in order to be able to
829 // detect repetition draws.
830 history[st->gamePly++] = key;
832 // Update side to move
833 key ^= zobSideToMove;
835 // Increment the 50 moves rule draw counter. Resetting it to zero in the
836 // case of non-reversible moves is taken care of later.
840 if (move_is_castle(m))
847 Color us = side_to_move();
848 Color them = opposite_color(us);
849 Square from = move_from(m);
850 Square to = move_to(m);
851 bool ep = move_is_ep(m);
852 bool pm = move_is_promotion(m);
854 Piece piece = piece_on(from);
855 PieceType pt = type_of_piece(piece);
856 PieceType capture = ep ? PAWN : type_of_piece_on(to);
858 assert(color_of_piece_on(from) == us);
859 assert(color_of_piece_on(to) == them || square_is_empty(to));
860 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
861 assert(!pm || relative_rank(us, to) == RANK_8);
864 do_capture_move(key, capture, them, to, ep);
867 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
869 // Reset en passant square
870 if (st->epSquare != SQ_NONE)
872 key ^= zobEp[st->epSquare];
873 st->epSquare = SQ_NONE;
876 // Update castle rights, try to shortcut a common case
877 int cm = castleRightsMask[from] & castleRightsMask[to];
878 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
880 key ^= zobCastle[st->castleRights];
881 st->castleRights &= castleRightsMask[from];
882 st->castleRights &= castleRightsMask[to];
883 key ^= zobCastle[st->castleRights];
886 // Prefetch TT access as soon as we know key is updated
887 prefetch((char*)TT.first_entry(key));
890 Bitboard move_bb = make_move_bb(from, to);
891 do_move_bb(&(byColorBB[us]), move_bb);
892 do_move_bb(&(byTypeBB[pt]), move_bb);
893 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
895 board[to] = board[from];
896 board[from] = PIECE_NONE;
898 // Update piece lists, note that index[from] is not updated and
899 // becomes stale. This works as long as index[] is accessed just
900 // by known occupied squares.
901 index[to] = index[from];
902 pieceList[us][pt][index[to]] = to;
904 // If the moving piece was a pawn do some special extra work
907 // Reset rule 50 draw counter
910 // Update pawn hash key and prefetch in L1/L2 cache
911 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
912 prefetchPawn(st->pawnKey, threadID);
914 // Set en passant square, only if moved pawn can be captured
915 if ((to ^ from) == 16)
917 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
919 st->epSquare = Square((int(from) + int(to)) / 2);
920 key ^= zobEp[st->epSquare];
924 if (pm) // promotion ?
926 PieceType promotion = move_promotion_piece(m);
928 assert(promotion >= KNIGHT && promotion <= QUEEN);
930 // Insert promoted piece instead of pawn
931 clear_bit(&(byTypeBB[PAWN]), to);
932 set_bit(&(byTypeBB[promotion]), to);
933 board[to] = piece_of_color_and_type(us, promotion);
935 // Update piece counts
936 pieceCount[us][promotion]++;
937 pieceCount[us][PAWN]--;
939 // Update material key
940 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
941 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
943 // Update piece lists, move the last pawn at index[to] position
944 // and shrink the list. Add a new promotion piece to the list.
945 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
946 index[lastPawnSquare] = index[to];
947 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
948 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
949 index[to] = pieceCount[us][promotion] - 1;
950 pieceList[us][promotion][index[to]] = to;
952 // Partially revert hash keys update
953 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
954 st->pawnKey ^= zobrist[us][PAWN][to];
956 // Partially revert and update incremental scores
957 st->value -= pst(us, PAWN, to);
958 st->value += pst(us, promotion, to);
961 st->npMaterial[us] += PieceValueMidgame[promotion];
965 // Update incremental scores
966 st->value += pst_delta(piece, from, to);
969 st->capturedType = capture;
971 // Update the key with the final value
974 // Update checkers bitboard, piece must be already moved
975 st->checkersBB = EmptyBoardBB;
980 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
984 if (bit_is_set(ci.checkSq[pt], to))
985 st->checkersBB = SetMaskBB[to];
988 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
991 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
994 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
1000 sideToMove = opposite_color(sideToMove);
1001 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1007 /// Position::do_capture_move() is a private method used to update captured
1008 /// piece info. It is called from the main Position::do_move function.
1010 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1012 assert(capture != KING);
1016 // If the captured piece was a pawn, update pawn hash key,
1017 // otherwise update non-pawn material.
1018 if (capture == PAWN)
1020 if (ep) // en passant ?
1022 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1024 assert(to == st->epSquare);
1025 assert(relative_rank(opposite_color(them), to) == RANK_6);
1026 assert(piece_on(to) == PIECE_NONE);
1027 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1029 board[capsq] = PIECE_NONE;
1031 st->pawnKey ^= zobrist[them][PAWN][capsq];
1034 st->npMaterial[them] -= PieceValueMidgame[capture];
1036 // Remove captured piece
1037 clear_bit(&(byColorBB[them]), capsq);
1038 clear_bit(&(byTypeBB[capture]), capsq);
1039 clear_bit(&(byTypeBB[0]), capsq);
1042 key ^= zobrist[them][capture][capsq];
1044 // Update incremental scores
1045 st->value -= pst(them, capture, capsq);
1047 // Update piece count
1048 pieceCount[them][capture]--;
1050 // Update material hash key
1051 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1053 // Update piece list, move the last piece at index[capsq] position
1055 // WARNING: This is a not perfectly revresible operation. When we
1056 // will reinsert the captured piece in undo_move() we will put it
1057 // at the end of the list and not in its original place, it means
1058 // index[] and pieceList[] are not guaranteed to be invariant to a
1059 // do_move() + undo_move() sequence.
1060 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1061 index[lastPieceSquare] = index[capsq];
1062 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1063 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1065 // Reset rule 50 counter
1070 /// Position::do_castle_move() is a private method used to make a castling
1071 /// move. It is called from the main Position::do_move function. Note that
1072 /// castling moves are encoded as "king captures friendly rook" moves, for
1073 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1075 void Position::do_castle_move(Move m) {
1077 assert(move_is_ok(m));
1078 assert(move_is_castle(m));
1080 Color us = side_to_move();
1081 Color them = opposite_color(us);
1083 // Reset capture field
1084 st->capturedType = PIECE_TYPE_NONE;
1086 // Find source squares for king and rook
1087 Square kfrom = move_from(m);
1088 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1091 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1092 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1094 // Find destination squares for king and rook
1095 if (rfrom > kfrom) // O-O
1097 kto = relative_square(us, SQ_G1);
1098 rto = relative_square(us, SQ_F1);
1100 kto = relative_square(us, SQ_C1);
1101 rto = relative_square(us, SQ_D1);
1104 // Remove pieces from source squares:
1105 clear_bit(&(byColorBB[us]), kfrom);
1106 clear_bit(&(byTypeBB[KING]), kfrom);
1107 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1108 clear_bit(&(byColorBB[us]), rfrom);
1109 clear_bit(&(byTypeBB[ROOK]), rfrom);
1110 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1112 // Put pieces on destination squares:
1113 set_bit(&(byColorBB[us]), kto);
1114 set_bit(&(byTypeBB[KING]), kto);
1115 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1116 set_bit(&(byColorBB[us]), rto);
1117 set_bit(&(byTypeBB[ROOK]), rto);
1118 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1120 // Update board array
1121 Piece king = piece_of_color_and_type(us, KING);
1122 Piece rook = piece_of_color_and_type(us, ROOK);
1123 board[kfrom] = board[rfrom] = PIECE_NONE;
1127 // Update piece lists
1128 pieceList[us][KING][index[kfrom]] = kto;
1129 pieceList[us][ROOK][index[rfrom]] = rto;
1130 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1131 index[kto] = index[kfrom];
1134 // Update incremental scores
1135 st->value += pst_delta(king, kfrom, kto);
1136 st->value += pst_delta(rook, rfrom, rto);
1139 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1140 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1142 // Clear en passant square
1143 if (st->epSquare != SQ_NONE)
1145 st->key ^= zobEp[st->epSquare];
1146 st->epSquare = SQ_NONE;
1149 // Update castling rights
1150 st->key ^= zobCastle[st->castleRights];
1151 st->castleRights &= castleRightsMask[kfrom];
1152 st->key ^= zobCastle[st->castleRights];
1154 // Reset rule 50 counter
1157 // Update checkers BB
1158 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1161 sideToMove = opposite_color(sideToMove);
1162 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1168 /// Position::undo_move() unmakes a move. When it returns, the position should
1169 /// be restored to exactly the same state as before the move was made.
1171 void Position::undo_move(Move m) {
1174 assert(move_is_ok(m));
1176 sideToMove = opposite_color(sideToMove);
1178 if (move_is_castle(m))
1180 undo_castle_move(m);
1184 Color us = side_to_move();
1185 Color them = opposite_color(us);
1186 Square from = move_from(m);
1187 Square to = move_to(m);
1188 bool ep = move_is_ep(m);
1189 bool pm = move_is_promotion(m);
1191 PieceType pt = type_of_piece_on(to);
1193 assert(square_is_empty(from));
1194 assert(color_of_piece_on(to) == us);
1195 assert(!pm || relative_rank(us, to) == RANK_8);
1196 assert(!ep || to == st->previous->epSquare);
1197 assert(!ep || relative_rank(us, to) == RANK_6);
1198 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1200 if (pm) // promotion ?
1202 PieceType promotion = move_promotion_piece(m);
1205 assert(promotion >= KNIGHT && promotion <= QUEEN);
1206 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1208 // Replace promoted piece with a pawn
1209 clear_bit(&(byTypeBB[promotion]), to);
1210 set_bit(&(byTypeBB[PAWN]), to);
1212 // Update piece counts
1213 pieceCount[us][promotion]--;
1214 pieceCount[us][PAWN]++;
1216 // Update piece list replacing promotion piece with a pawn
1217 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1218 index[lastPromotionSquare] = index[to];
1219 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1220 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1221 index[to] = pieceCount[us][PAWN] - 1;
1222 pieceList[us][PAWN][index[to]] = to;
1225 // Put the piece back at the source square
1226 Bitboard move_bb = make_move_bb(to, from);
1227 do_move_bb(&(byColorBB[us]), move_bb);
1228 do_move_bb(&(byTypeBB[pt]), move_bb);
1229 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1231 board[from] = piece_of_color_and_type(us, pt);
1232 board[to] = PIECE_NONE;
1234 // Update piece list
1235 index[from] = index[to];
1236 pieceList[us][pt][index[from]] = from;
1238 if (st->capturedType)
1243 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1245 assert(st->capturedType != KING);
1246 assert(!ep || square_is_empty(capsq));
1248 // Restore the captured piece
1249 set_bit(&(byColorBB[them]), capsq);
1250 set_bit(&(byTypeBB[st->capturedType]), capsq);
1251 set_bit(&(byTypeBB[0]), capsq);
1253 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1255 // Update piece count
1256 pieceCount[them][st->capturedType]++;
1258 // Update piece list, add a new captured piece in capsq square
1259 index[capsq] = pieceCount[them][st->capturedType] - 1;
1260 pieceList[them][st->capturedType][index[capsq]] = capsq;
1263 // Finally point our state pointer back to the previous state
1270 /// Position::undo_castle_move() is a private method used to unmake a castling
1271 /// move. It is called from the main Position::undo_move function. Note that
1272 /// castling moves are encoded as "king captures friendly rook" moves, for
1273 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1275 void Position::undo_castle_move(Move m) {
1277 assert(move_is_ok(m));
1278 assert(move_is_castle(m));
1280 // When we have arrived here, some work has already been done by
1281 // Position::undo_move. In particular, the side to move has been switched,
1282 // so the code below is correct.
1283 Color us = side_to_move();
1285 // Find source squares for king and rook
1286 Square kfrom = move_from(m);
1287 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1290 // Find destination squares for king and rook
1291 if (rfrom > kfrom) // O-O
1293 kto = relative_square(us, SQ_G1);
1294 rto = relative_square(us, SQ_F1);
1296 kto = relative_square(us, SQ_C1);
1297 rto = relative_square(us, SQ_D1);
1300 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1301 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1303 // Remove pieces from destination squares:
1304 clear_bit(&(byColorBB[us]), kto);
1305 clear_bit(&(byTypeBB[KING]), kto);
1306 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1307 clear_bit(&(byColorBB[us]), rto);
1308 clear_bit(&(byTypeBB[ROOK]), rto);
1309 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1311 // Put pieces on source squares:
1312 set_bit(&(byColorBB[us]), kfrom);
1313 set_bit(&(byTypeBB[KING]), kfrom);
1314 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1315 set_bit(&(byColorBB[us]), rfrom);
1316 set_bit(&(byTypeBB[ROOK]), rfrom);
1317 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1320 board[rto] = board[kto] = PIECE_NONE;
1321 board[rfrom] = piece_of_color_and_type(us, ROOK);
1322 board[kfrom] = piece_of_color_and_type(us, KING);
1324 // Update piece lists
1325 pieceList[us][KING][index[kto]] = kfrom;
1326 pieceList[us][ROOK][index[rto]] = rfrom;
1327 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1328 index[kfrom] = index[kto];
1331 // Finally point our state pointer back to the previous state
1338 /// Position::do_null_move makes() a "null move": It switches the side to move
1339 /// and updates the hash key without executing any move on the board.
1341 void Position::do_null_move(StateInfo& backupSt) {
1344 assert(!is_check());
1346 // Back up the information necessary to undo the null move to the supplied
1347 // StateInfo object.
1348 // Note that differently from normal case here backupSt is actually used as
1349 // a backup storage not as a new state to be used.
1350 backupSt.key = st->key;
1351 backupSt.epSquare = st->epSquare;
1352 backupSt.value = st->value;
1353 backupSt.previous = st->previous;
1354 backupSt.pliesFromNull = st->pliesFromNull;
1355 st->previous = &backupSt;
1357 // Save the current key to the history[] array, in order to be able to
1358 // detect repetition draws.
1359 history[st->gamePly++] = st->key;
1361 // Update the necessary information
1362 if (st->epSquare != SQ_NONE)
1363 st->key ^= zobEp[st->epSquare];
1365 st->key ^= zobSideToMove;
1366 prefetch((char*)TT.first_entry(st->key));
1368 sideToMove = opposite_color(sideToMove);
1369 st->epSquare = SQ_NONE;
1371 st->pliesFromNull = 0;
1372 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1376 /// Position::undo_null_move() unmakes a "null move".
1378 void Position::undo_null_move() {
1381 assert(!is_check());
1383 // Restore information from the our backup StateInfo object
1384 StateInfo* backupSt = st->previous;
1385 st->key = backupSt->key;
1386 st->epSquare = backupSt->epSquare;
1387 st->value = backupSt->value;
1388 st->previous = backupSt->previous;
1389 st->pliesFromNull = backupSt->pliesFromNull;
1391 // Update the necessary information
1392 sideToMove = opposite_color(sideToMove);
1398 /// Position::see() is a static exchange evaluator: It tries to estimate the
1399 /// material gain or loss resulting from a move. There are three versions of
1400 /// this function: One which takes a destination square as input, one takes a
1401 /// move, and one which takes a 'from' and a 'to' square. The function does
1402 /// not yet understand promotions captures.
1404 int Position::see(Move m) const {
1406 assert(move_is_ok(m));
1407 return see(move_from(m), move_to(m));
1410 int Position::see_sign(Move m) const {
1412 assert(move_is_ok(m));
1414 Square from = move_from(m);
1415 Square to = move_to(m);
1417 // Early return if SEE cannot be negative because captured piece value
1418 // is not less then capturing one. Note that king moves always return
1419 // here because king midgame value is set to 0.
1420 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1423 return see(from, to);
1426 int Position::see(Square from, Square to) const {
1428 Bitboard occupied, attackers, stmAttackers, b;
1429 int swapList[32], slIndex = 1;
1430 PieceType capturedType, pt;
1433 assert(square_is_ok(from));
1434 assert(square_is_ok(to));
1436 capturedType = type_of_piece_on(to);
1438 // King cannot be recaptured
1439 if (capturedType == KING)
1440 return seeValues[capturedType];
1442 occupied = occupied_squares();
1444 // Handle en passant moves
1445 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1447 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1449 assert(capturedType == PIECE_TYPE_NONE);
1450 assert(type_of_piece_on(capQq) == PAWN);
1452 // Remove the captured pawn
1453 clear_bit(&occupied, capQq);
1454 capturedType = PAWN;
1457 // Find all attackers to the destination square, with the moving piece
1458 // removed, but possibly an X-ray attacker added behind it.
1459 clear_bit(&occupied, from);
1460 attackers = (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1461 | (bishop_attacks_bb(to, occupied)& pieces(BISHOP, QUEEN))
1462 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1463 | (attacks_from<KING>(to) & pieces(KING))
1464 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1465 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1467 // If the opponent has no attackers we are finished
1468 stm = opposite_color(color_of_piece_on(from));
1469 stmAttackers = attackers & pieces_of_color(stm);
1471 return seeValues[capturedType];
1473 // The destination square is defended, which makes things rather more
1474 // difficult to compute. We proceed by building up a "swap list" containing
1475 // the material gain or loss at each stop in a sequence of captures to the
1476 // destination square, where the sides alternately capture, and always
1477 // capture with the least valuable piece. After each capture, we look for
1478 // new X-ray attacks from behind the capturing piece.
1479 swapList[0] = seeValues[capturedType];
1480 capturedType = type_of_piece_on(from);
1483 // Locate the least valuable attacker for the side to move. The loop
1484 // below looks like it is potentially infinite, but it isn't. We know
1485 // that the side to move still has at least one attacker left.
1486 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1489 // Remove the attacker we just found from the 'occupied' bitboard,
1490 // and scan for new X-ray attacks behind the attacker.
1491 b = stmAttackers & pieces(pt);
1492 occupied ^= (b & (~b + 1));
1493 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1494 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1496 attackers &= occupied; // Cut out pieces we've already done
1498 // Add the new entry to the swap list
1499 assert(slIndex < 32);
1500 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1503 // Remember the value of the capturing piece, and change the side to
1504 // move before beginning the next iteration.
1506 stm = opposite_color(stm);
1507 stmAttackers = attackers & pieces_of_color(stm);
1509 // Stop before processing a king capture
1510 if (capturedType == KING && stmAttackers)
1512 assert(slIndex < 32);
1513 swapList[slIndex++] = QueenValueMidgame*10;
1516 } while (stmAttackers);
1518 // Having built the swap list, we negamax through it to find the best
1519 // achievable score from the point of view of the side to move.
1521 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1527 /// Position::clear() erases the position object to a pristine state, with an
1528 /// empty board, white to move, and no castling rights.
1530 void Position::clear() {
1533 memset(st, 0, sizeof(StateInfo));
1534 st->epSquare = SQ_NONE;
1535 startPosPlyCounter = 0;
1538 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1539 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1540 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1541 memset(index, 0, sizeof(int) * 64);
1543 for (int i = 0; i < 64; i++)
1544 board[i] = PIECE_NONE;
1546 for (int i = 0; i < 8; i++)
1547 for (int j = 0; j < 16; j++)
1548 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1550 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1551 castleRightsMask[sq] = ALL_CASTLES;
1554 initialKFile = FILE_E;
1555 initialKRFile = FILE_H;
1556 initialQRFile = FILE_A;
1560 /// Position::put_piece() puts a piece on the given square of the board,
1561 /// updating the board array, pieces list, bitboards, and piece counts.
1563 void Position::put_piece(Piece p, Square s) {
1565 Color c = color_of_piece(p);
1566 PieceType pt = type_of_piece(p);
1569 index[s] = pieceCount[c][pt]++;
1570 pieceList[c][pt][index[s]] = s;
1572 set_bit(&(byTypeBB[pt]), s);
1573 set_bit(&(byColorBB[c]), s);
1574 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1578 /// Position::compute_key() computes the hash key of the position. The hash
1579 /// key is usually updated incrementally as moves are made and unmade, the
1580 /// compute_key() function is only used when a new position is set up, and
1581 /// to verify the correctness of the hash key when running in debug mode.
1583 Key Position::compute_key() const {
1585 Key result = zobCastle[st->castleRights];
1587 for (Square s = SQ_A1; s <= SQ_H8; s++)
1588 if (square_is_occupied(s))
1589 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1591 if (ep_square() != SQ_NONE)
1592 result ^= zobEp[ep_square()];
1594 if (side_to_move() == BLACK)
1595 result ^= zobSideToMove;
1601 /// Position::compute_pawn_key() computes the hash key of the position. The
1602 /// hash key is usually updated incrementally as moves are made and unmade,
1603 /// the compute_pawn_key() function is only used when a new position is set
1604 /// up, and to verify the correctness of the pawn hash key when running in
1607 Key Position::compute_pawn_key() const {
1612 for (Color c = WHITE; c <= BLACK; c++)
1614 b = pieces(PAWN, c);
1616 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1622 /// Position::compute_material_key() computes the hash key of the position.
1623 /// The hash key is usually updated incrementally as moves are made and unmade,
1624 /// the compute_material_key() function is only used when a new position is set
1625 /// up, and to verify the correctness of the material hash key when running in
1628 Key Position::compute_material_key() const {
1633 for (Color c = WHITE; c <= BLACK; c++)
1634 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1636 count = piece_count(c, pt);
1637 for (int i = 0; i < count; i++)
1638 result ^= zobrist[c][pt][i];
1644 /// Position::compute_value() compute the incremental scores for the middle
1645 /// game and the endgame. These functions are used to initialize the incremental
1646 /// scores when a new position is set up, and to verify that the scores are correctly
1647 /// updated by do_move and undo_move when the program is running in debug mode.
1648 Score Position::compute_value() const {
1651 Score result = SCORE_ZERO;
1653 for (Color c = WHITE; c <= BLACK; c++)
1654 for (PieceType pt = PAWN; pt <= KING; pt++)
1658 result += pst(c, pt, pop_1st_bit(&b));
1661 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1666 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1667 /// game material value for the given side. Material values are updated
1668 /// incrementally during the search, this function is only used while
1669 /// initializing a new Position object.
1671 Value Position::compute_non_pawn_material(Color c) const {
1673 Value result = VALUE_ZERO;
1675 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1676 result += piece_count(c, pt) * PieceValueMidgame[pt];
1682 /// Position::is_draw() tests whether the position is drawn by material,
1683 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1684 /// must be done by the search.
1686 bool Position::is_draw() const {
1688 // Draw by material?
1690 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1693 // Draw by the 50 moves rule?
1694 if (st->rule50 > 99 && !is_mate())
1697 // Draw by repetition?
1698 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1699 if (history[st->gamePly - i] == st->key)
1706 /// Position::is_mate() returns true or false depending on whether the
1707 /// side to move is checkmated.
1709 bool Position::is_mate() const {
1711 MoveStack moves[MOVES_MAX];
1712 return is_check() && generate_moves(*this, moves) == moves;
1716 /// Position::has_mate_threat() tests whether the side to move is under
1717 /// a threat of being mated in one from the current position.
1719 bool Position::has_mate_threat() {
1721 MoveStack mlist[MOVES_MAX], *last, *cur;
1723 bool mateFound = false;
1725 // If we are under check it's up to evasions to do the job
1729 // First pass the move to our opponent doing a null move
1732 // Then generate pseudo-legal moves that could give check
1733 last = generate_non_capture_checks(*this, mlist);
1734 last = generate_captures(*this, last);
1736 // Loop through the moves, and see if one of them gives mate
1737 Bitboard pinned = pinned_pieces(sideToMove);
1738 CheckInfo ci(*this);
1739 for (cur = mlist; cur != last && !mateFound; cur++)
1741 Move move = cur->move;
1742 if ( !pl_move_is_legal(move, pinned)
1743 || !move_is_check(move, ci))
1746 do_move(move, st2, ci, true);
1759 /// Position::init_zobrist() is a static member function which initializes at
1760 /// startup the various arrays used to compute hash keys.
1762 void Position::init_zobrist() {
1767 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1768 zobrist[i][j][k] = rk.rand<Key>();
1770 for (i = 0; i < 64; i++)
1771 zobEp[i] = rk.rand<Key>();
1773 for (i = 0; i < 16; i++)
1774 zobCastle[i] = rk.rand<Key>();
1776 zobSideToMove = rk.rand<Key>();
1777 zobExclusion = rk.rand<Key>();
1781 /// Position::init_piece_square_tables() initializes the piece square tables.
1782 /// This is a two-step operation: First, the white halves of the tables are
1783 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1784 /// of the tables are initialized by mirroring and changing the sign of the
1785 /// corresponding white scores.
1787 void Position::init_piece_square_tables() {
1789 for (Square s = SQ_A1; s <= SQ_H8; s++)
1790 for (Piece p = WP; p <= WK; p++)
1791 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1793 for (Square s = SQ_A1; s <= SQ_H8; s++)
1794 for (Piece p = BP; p <= BK; p++)
1795 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1799 /// Position::flipped_copy() makes a copy of the input position, but with
1800 /// the white and black sides reversed. This is only useful for debugging,
1801 /// especially for finding evaluation symmetry bugs.
1803 void Position::flipped_copy(const Position& pos) {
1805 assert(pos.is_ok());
1808 threadID = pos.thread();
1811 for (Square s = SQ_A1; s <= SQ_H8; s++)
1812 if (!pos.square_is_empty(s))
1813 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1816 sideToMove = opposite_color(pos.side_to_move());
1819 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1820 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1821 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1822 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1824 initialKFile = pos.initialKFile;
1825 initialKRFile = pos.initialKRFile;
1826 initialQRFile = pos.initialQRFile;
1828 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1829 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1830 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1831 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1832 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1833 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1835 // En passant square
1836 if (pos.st->epSquare != SQ_NONE)
1837 st->epSquare = flip_square(pos.st->epSquare);
1843 st->key = compute_key();
1844 st->pawnKey = compute_pawn_key();
1845 st->materialKey = compute_material_key();
1847 // Incremental scores
1848 st->value = compute_value();
1851 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1852 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1858 /// Position::is_ok() performs some consitency checks for the position object.
1859 /// This is meant to be helpful when debugging.
1861 bool Position::is_ok(int* failedStep) const {
1863 // What features of the position should be verified?
1864 const bool debugAll = false;
1866 const bool debugBitboards = debugAll || false;
1867 const bool debugKingCount = debugAll || false;
1868 const bool debugKingCapture = debugAll || false;
1869 const bool debugCheckerCount = debugAll || false;
1870 const bool debugKey = debugAll || false;
1871 const bool debugMaterialKey = debugAll || false;
1872 const bool debugPawnKey = debugAll || false;
1873 const bool debugIncrementalEval = debugAll || false;
1874 const bool debugNonPawnMaterial = debugAll || false;
1875 const bool debugPieceCounts = debugAll || false;
1876 const bool debugPieceList = debugAll || false;
1877 const bool debugCastleSquares = debugAll || false;
1879 if (failedStep) *failedStep = 1;
1882 if (!color_is_ok(side_to_move()))
1885 // Are the king squares in the position correct?
1886 if (failedStep) (*failedStep)++;
1887 if (piece_on(king_square(WHITE)) != WK)
1890 if (failedStep) (*failedStep)++;
1891 if (piece_on(king_square(BLACK)) != BK)
1895 if (failedStep) (*failedStep)++;
1896 if (!file_is_ok(initialKRFile))
1899 if (!file_is_ok(initialQRFile))
1902 // Do both sides have exactly one king?
1903 if (failedStep) (*failedStep)++;
1906 int kingCount[2] = {0, 0};
1907 for (Square s = SQ_A1; s <= SQ_H8; s++)
1908 if (type_of_piece_on(s) == KING)
1909 kingCount[color_of_piece_on(s)]++;
1911 if (kingCount[0] != 1 || kingCount[1] != 1)
1915 // Can the side to move capture the opponent's king?
1916 if (failedStep) (*failedStep)++;
1917 if (debugKingCapture)
1919 Color us = side_to_move();
1920 Color them = opposite_color(us);
1921 Square ksq = king_square(them);
1922 if (attackers_to(ksq) & pieces_of_color(us))
1926 // Is there more than 2 checkers?
1927 if (failedStep) (*failedStep)++;
1928 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1932 if (failedStep) (*failedStep)++;
1935 // The intersection of the white and black pieces must be empty
1936 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1939 // The union of the white and black pieces must be equal to all
1941 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1944 // Separate piece type bitboards must have empty intersections
1945 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1946 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1947 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1951 // En passant square OK?
1952 if (failedStep) (*failedStep)++;
1953 if (ep_square() != SQ_NONE)
1955 // The en passant square must be on rank 6, from the point of view of the
1957 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1962 if (failedStep) (*failedStep)++;
1963 if (debugKey && st->key != compute_key())
1966 // Pawn hash key OK?
1967 if (failedStep) (*failedStep)++;
1968 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1971 // Material hash key OK?
1972 if (failedStep) (*failedStep)++;
1973 if (debugMaterialKey && st->materialKey != compute_material_key())
1976 // Incremental eval OK?
1977 if (failedStep) (*failedStep)++;
1978 if (debugIncrementalEval && st->value != compute_value())
1981 // Non-pawn material OK?
1982 if (failedStep) (*failedStep)++;
1983 if (debugNonPawnMaterial)
1985 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1988 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1993 if (failedStep) (*failedStep)++;
1994 if (debugPieceCounts)
1995 for (Color c = WHITE; c <= BLACK; c++)
1996 for (PieceType pt = PAWN; pt <= KING; pt++)
1997 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2000 if (failedStep) (*failedStep)++;
2003 for (Color c = WHITE; c <= BLACK; c++)
2004 for (PieceType pt = PAWN; pt <= KING; pt++)
2005 for (int i = 0; i < pieceCount[c][pt]; i++)
2007 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2010 if (index[piece_list(c, pt, i)] != i)
2015 if (failedStep) (*failedStep)++;
2016 if (debugCastleSquares) {
2017 for (Color c = WHITE; c <= BLACK; c++) {
2018 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2020 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2023 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2025 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2027 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2029 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2033 if (failedStep) *failedStep = 0;