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/>.
40 #include "ucioption.h"
48 //// Position's static data definitions
51 Key Position::zobrist[2][8][64];
52 Key Position::zobEp[64];
53 Key Position::zobCastle[16];
54 Key Position::zobSideToMove;
55 Key Position::zobExclusion;
57 Score Position::PieceSquareTable[16][64];
59 // Material values arrays, indexed by Piece
60 const Value Position::PieceValueMidgame[17] = {
62 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
63 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
64 VALUE_ZERO, VALUE_ZERO,
65 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
66 RookValueMidgame, QueenValueMidgame
69 const Value Position::PieceValueEndgame[17] = {
71 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
72 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
73 VALUE_ZERO, VALUE_ZERO,
74 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
75 RookValueEndgame, QueenValueEndgame
78 // Material values array used by SEE, indexed by PieceType
79 const Value Position::seeValues[] = {
81 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
82 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
88 // Bonus for having the side to move (modified by Joona Kiiski)
89 const Score TempoValue = make_score(48, 22);
91 bool isZero(char c) { return c == '0'; }
93 struct PieceLetters : public std::map<char, Piece> {
97 operator[]('K') = WK; operator[]('k') = BK;
98 operator[]('Q') = WQ; operator[]('q') = BQ;
99 operator[]('R') = WR; operator[]('r') = BR;
100 operator[]('B') = WB; operator[]('b') = BB;
101 operator[]('N') = WN; operator[]('n') = BN;
102 operator[]('P') = WP; operator[]('p') = BP;
103 operator[](' ') = PIECE_NONE;
104 operator[]('.') = PIECE_NONE_DARK_SQ;
107 char from_piece(Piece p) const {
109 std::map<char, Piece>::const_iterator it;
110 for (it = begin(); it != end(); ++it)
119 PieceLetters pieceLetters;
125 CheckInfo::CheckInfo(const Position& pos) {
127 Color us = pos.side_to_move();
128 Color them = opposite_color(us);
130 ksq = pos.king_square(them);
131 dcCandidates = pos.discovered_check_candidates(us);
133 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
134 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
135 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
136 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
137 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
138 checkSq[KING] = EmptyBoardBB;
142 /// Position c'tors. Here we always create a copy of the original position
143 /// or the FEN string, we want the new born Position object do not depend
144 /// on any external data so we detach state pointer from the source one.
146 Position::Position(const Position& pos, int th) {
148 memcpy(this, &pos, sizeof(Position));
149 detach(); // Always detach() in copy c'tor to avoid surprises
154 Position::Position(const string& fen, bool isChess960, int th) {
156 from_fen(fen, isChess960);
161 /// Position::detach() copies the content of the current state and castling
162 /// masks inside the position itself. This is needed when the st pointee could
163 /// become stale, as example because the caller is about to going out of scope.
165 void Position::detach() {
169 st->previous = NULL; // as a safe guard
173 /// Position::from_fen() initializes the position object with the given FEN
174 /// string. This function is not very robust - make sure that input FENs are
175 /// correct (this is assumed to be the responsibility of the GUI).
177 void Position::from_fen(const string& fen, bool c960) {
179 A FEN string defines a particular position using only the ASCII character set.
181 A FEN string contains six fields. The separator between fields is a space. The fields are:
183 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
184 with rank 1; within each rank, the contents of each square are described from file a through file h.
185 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
186 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
187 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
188 of blank squares), and "/" separate ranks.
190 2) Active color. "w" means white moves next, "b" means black.
192 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
193 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
194 kingside), and/or "q" (Black can castle queenside).
196 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
197 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
198 regardless of whether there is a pawn in position to make an en passant capture.
200 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
201 to determine if a draw can be claimed under the fifty-move rule.
203 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
208 std::istringstream ss(fen);
214 // 1. Piece placement field
215 while (ss.get(token) && token != ' ')
219 file += File(token - '0'); // Skip the given number of files
222 else if (token == '/')
229 if (pieceLetters.find(token) == pieceLetters.end())
232 put_piece(pieceLetters[token], make_square(file, rank));
237 if (!ss.get(token) || (token != 'w' && token != 'b'))
240 sideToMove = (token == 'w' ? WHITE : BLACK);
242 if (!ss.get(token) || token != ' ')
245 // 3. Castling availability
246 while (ss.get(token) && token != ' ')
251 if (!set_castling_rights(token))
255 // 4. En passant square -- ignore if no capture is possible
257 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
258 && (ss.get(row) && (row == '3' || row == '6')))
260 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
261 Color them = opposite_color(sideToMove);
263 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
264 st->epSquare = fenEpSquare;
271 // 6. Fullmove number
273 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
275 // Various initialisations
276 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
277 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
278 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
279 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
280 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
281 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
286 st->key = compute_key();
287 st->pawnKey = compute_pawn_key();
288 st->materialKey = compute_material_key();
289 st->value = compute_value();
290 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
291 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
295 cout << "Error in FEN string: " << fen << endl;
299 /// Position::set_castling_rights() sets castling parameters castling avaiability.
300 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
301 /// that uses the letters of the columns on which the rooks began the game instead
302 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
303 /// associated with the castling right, the traditional castling tag will be replaced
304 /// by the file letter of the involved rook as for the Shredder-FEN.
306 bool Position::set_castling_rights(char token) {
308 Color c = token >= 'a' ? BLACK : WHITE;
309 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
310 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
311 Piece rook = (c == WHITE ? WR : BR);
313 initialKFile = square_file(king_square(c));
314 token = char(toupper(token));
318 for (Square sq = sqH; sq >= sqA; sq--)
319 if (piece_on(sq) == rook)
322 initialKRFile = square_file(sq);
326 else if (token == 'Q')
328 for (Square sq = sqA; sq <= sqH; sq++)
329 if (piece_on(sq) == rook)
332 initialQRFile = square_file(sq);
336 else if (token >= 'A' && token <= 'H')
338 File rookFile = File(token - 'A') + FILE_A;
339 if (rookFile < initialKFile)
342 initialQRFile = rookFile;
347 initialKRFile = rookFile;
356 /// Position::to_fen() returns a FEN representation of the position. In case
357 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
359 const string Position::to_fen() const {
365 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
367 for (File file = FILE_A; file <= FILE_H; file++)
369 sq = make_square(file, rank);
371 if (square_is_occupied(sq))
374 fen += pieceLetters.from_piece(piece_on(sq));
384 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
385 fen.erase(--fen.end());
386 fen += (sideToMove == WHITE ? " w " : " b ");
388 if (st->castleRights != CASTLES_NONE)
390 if (can_castle_kingside(WHITE))
391 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
393 if (can_castle_queenside(WHITE))
394 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
396 if (can_castle_kingside(BLACK))
397 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
399 if (can_castle_queenside(BLACK))
400 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
404 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
409 /// Position::print() prints an ASCII representation of the position to
410 /// the standard output. If a move is given then also the san is printed.
412 void Position::print(Move move) const {
414 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
415 static bool requestPending = false;
417 // Check for reentrancy, as example when called from inside
418 // MovePicker that is used also here in move_to_san()
422 requestPending = true;
426 Position p(*this, thread());
427 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
428 cout << "\nMove is: " << dd << move_to_san(p, move);
431 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
433 cout << dottedLine << '|';
434 for (File file = FILE_A; file <= FILE_H; file++)
436 Square sq = make_square(file, rank);
437 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
438 Piece piece = piece_on(sq);
440 if (piece == PIECE_NONE && square_color(sq) == DARK)
441 piece = PIECE_NONE_DARK_SQ;
443 cout << c << pieceLetters.from_piece(piece) << c << '|';
446 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
447 requestPending = false;
451 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
452 /// king) pieces for the given color and for the given pinner type. Or, when
453 /// template parameter FindPinned is false, the pieces of the given color
454 /// candidate for a discovery check against the enemy king.
455 /// Bitboard checkersBB must be already updated when looking for pinners.
457 template<bool FindPinned>
458 Bitboard Position::hidden_checkers(Color c) const {
460 Bitboard result = EmptyBoardBB;
461 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
463 // Pinned pieces protect our king, dicovery checks attack
465 Square ksq = king_square(FindPinned ? c : opposite_color(c));
467 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
468 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
470 if (FindPinned && pinners)
471 pinners &= ~st->checkersBB;
475 Square s = pop_1st_bit(&pinners);
476 Bitboard b = squares_between(s, ksq) & occupied_squares();
480 if ( !(b & (b - 1)) // Only one bit set?
481 && (b & pieces_of_color(c))) // Is an our piece?
488 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
489 /// king) pieces for the given color. Note that checkersBB bitboard must
490 /// be already updated.
492 Bitboard Position::pinned_pieces(Color c) const {
494 return hidden_checkers<true>(c);
498 /// Position:discovered_check_candidates() returns a bitboard containing all
499 /// pieces for the given side which are candidates for giving a discovered
500 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
501 /// to be already updated.
503 Bitboard Position::discovered_check_candidates(Color c) const {
505 return hidden_checkers<false>(c);
508 /// Position::attackers_to() computes a bitboard containing all pieces which
509 /// attacks a given square.
511 Bitboard Position::attackers_to(Square s) const {
513 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
514 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
515 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
516 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
517 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
518 | (attacks_from<KING>(s) & pieces(KING));
521 /// Position::attacks_from() computes a bitboard of all attacks
522 /// of a given piece put in a given square.
524 Bitboard Position::attacks_from(Piece p, Square s) const {
526 assert(square_is_ok(s));
530 case WB: case BB: return attacks_from<BISHOP>(s);
531 case WR: case BR: return attacks_from<ROOK>(s);
532 case WQ: case BQ: return attacks_from<QUEEN>(s);
533 default: return NonSlidingAttacksBB[p][s];
537 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
539 assert(square_is_ok(s));
543 case WB: case BB: return bishop_attacks_bb(s, occ);
544 case WR: case BR: return rook_attacks_bb(s, occ);
545 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
546 default: return NonSlidingAttacksBB[p][s];
551 /// Position::move_attacks_square() tests whether a move from the current
552 /// position attacks a given square.
554 bool Position::move_attacks_square(Move m, Square s) const {
556 assert(move_is_ok(m));
557 assert(square_is_ok(s));
560 Square f = move_from(m), t = move_to(m);
562 assert(square_is_occupied(f));
564 if (bit_is_set(attacks_from(piece_on(f), t), s))
567 // Move the piece and scan for X-ray attacks behind it
568 occ = occupied_squares();
569 do_move_bb(&occ, make_move_bb(f, t));
570 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
571 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
572 & pieces_of_color(color_of_piece_on(f));
574 // If we have attacks we need to verify that are caused by our move
575 // and are not already existent ones.
576 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
580 /// Position::find_checkers() computes the checkersBB bitboard, which
581 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
582 /// currently works by calling Position::attackers_to, which is probably
583 /// inefficient. Consider rewriting this function to use the last move
584 /// played, like in non-bitboard versions of Glaurung.
586 void Position::find_checkers() {
588 Color us = side_to_move();
589 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
593 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
595 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
598 assert(move_is_ok(m));
599 assert(pinned == pinned_pieces(side_to_move()));
601 // Castling moves are checked for legality during move generation.
602 if (move_is_castle(m))
605 // En passant captures are a tricky special case. Because they are
606 // rather uncommon, we do it simply by testing whether the king is attacked
607 // after the move is made
610 Color us = side_to_move();
611 Color them = opposite_color(us);
612 Square from = move_from(m);
613 Square to = move_to(m);
614 Square capsq = make_square(square_file(to), square_rank(from));
615 Square ksq = king_square(us);
616 Bitboard b = occupied_squares();
618 assert(to == ep_square());
619 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
620 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
621 assert(piece_on(to) == PIECE_NONE);
624 clear_bit(&b, capsq);
627 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
628 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
631 Color us = side_to_move();
632 Square from = move_from(m);
634 assert(color_of_piece_on(from) == us);
635 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
637 // If the moving piece is a king, check whether the destination
638 // square is attacked by the opponent.
639 if (type_of_piece_on(from) == KING)
640 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
642 // A non-king move is legal if and only if it is not pinned or it
643 // is moving along the ray towards or away from the king.
645 || !bit_is_set(pinned, from)
646 || squares_aligned(from, move_to(m), king_square(us));
650 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
652 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
656 Color us = side_to_move();
657 Square from = move_from(m);
658 Square to = move_to(m);
660 // King moves and en-passant captures are verified in pl_move_is_legal()
661 if (type_of_piece_on(from) == KING || move_is_ep(m))
662 return pl_move_is_legal(m, pinned);
664 Bitboard target = checkers();
665 Square checksq = pop_1st_bit(&target);
667 if (target) // double check ?
670 // Our move must be a blocking evasion or a capture of the checking piece
671 target = squares_between(checksq, king_square(us)) | checkers();
672 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
676 /// Position::move_is_check() tests whether a pseudo-legal move is a check
678 bool Position::move_is_check(Move m) const {
680 return move_is_check(m, CheckInfo(*this));
683 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
686 assert(move_is_ok(m));
687 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
688 assert(color_of_piece_on(move_from(m)) == side_to_move());
689 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
691 Square from = move_from(m);
692 Square to = move_to(m);
693 PieceType pt = type_of_piece_on(from);
696 if (bit_is_set(ci.checkSq[pt], to))
700 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
702 // For pawn and king moves we need to verify also direction
703 if ( (pt != PAWN && pt != KING)
704 || !squares_aligned(from, to, ci.ksq))
708 // Can we skip the ugly special cases ?
709 if (!move_is_special(m))
712 Color us = side_to_move();
713 Bitboard b = occupied_squares();
715 // Promotion with check ?
716 if (move_is_promotion(m))
720 switch (move_promotion_piece(m))
723 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
725 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
727 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
729 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
735 // En passant capture with check ? We have already handled the case
736 // of direct checks and ordinary discovered check, the only case we
737 // need to handle is the unusual case of a discovered check through
738 // the captured pawn.
741 Square capsq = make_square(square_file(to), square_rank(from));
743 clear_bit(&b, capsq);
745 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
746 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
749 // Castling with check ?
750 if (move_is_castle(m))
752 Square kfrom, kto, rfrom, rto;
758 kto = relative_square(us, SQ_G1);
759 rto = relative_square(us, SQ_F1);
761 kto = relative_square(us, SQ_C1);
762 rto = relative_square(us, SQ_D1);
764 clear_bit(&b, kfrom);
765 clear_bit(&b, rfrom);
768 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
775 /// Position::do_setup_move() makes a permanent move on the board.
776 /// It should be used when setting up a position on board.
777 /// You can't undo the move.
779 void Position::do_setup_move(Move m, StateInfo& newSt) {
783 // Reset "game ply" in case we made a non-reversible move.
784 // "game ply" is used for repetition detection.
788 // Update the number of plies played from the starting position
789 startPosPlyCounter++;
792 /// Position::do_move() makes a move, and saves all information necessary
793 /// to a StateInfo object. The move is assumed to be legal.
794 /// Pseudo-legal moves should be filtered out before this function is called.
796 void Position::do_move(Move m, StateInfo& newSt) {
799 do_move(m, newSt, ci, move_is_check(m, ci));
802 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
805 assert(move_is_ok(m));
810 // Copy some fields of old state to our new StateInfo object except the
811 // ones which are recalculated from scratch anyway, then switch our state
812 // pointer to point to the new, ready to be updated, state.
813 struct ReducedStateInfo {
814 Key pawnKey, materialKey;
815 int castleRights, rule50, gamePly, pliesFromNull;
822 memcpy(&newSt, st, sizeof(ReducedStateInfo));
827 // Save the current key to the history[] array, in order to be able to
828 // detect repetition draws.
829 history[st->gamePly++] = key;
831 // Update side to move
832 key ^= zobSideToMove;
834 // Increment the 50 moves rule draw counter. Resetting it to zero in the
835 // case of non-reversible moves is taken care of later.
839 if (move_is_castle(m))
846 Color us = side_to_move();
847 Color them = opposite_color(us);
848 Square from = move_from(m);
849 Square to = move_to(m);
850 bool ep = move_is_ep(m);
851 bool pm = move_is_promotion(m);
853 Piece piece = piece_on(from);
854 PieceType pt = type_of_piece(piece);
855 PieceType capture = ep ? PAWN : type_of_piece_on(to);
857 assert(color_of_piece_on(from) == us);
858 assert(color_of_piece_on(to) == them || square_is_empty(to));
859 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
860 assert(!pm || relative_rank(us, to) == RANK_8);
863 do_capture_move(key, capture, them, to, ep);
866 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
868 // Reset en passant square
869 if (st->epSquare != SQ_NONE)
871 key ^= zobEp[st->epSquare];
872 st->epSquare = SQ_NONE;
875 // Update castle rights, try to shortcut a common case
876 int cm = castleRightsMask[from] & castleRightsMask[to];
877 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
879 key ^= zobCastle[st->castleRights];
880 st->castleRights &= castleRightsMask[from];
881 st->castleRights &= castleRightsMask[to];
882 key ^= zobCastle[st->castleRights];
885 // Prefetch TT access as soon as we know key is updated
886 prefetch((char*)TT.first_entry(key));
889 Bitboard move_bb = make_move_bb(from, to);
890 do_move_bb(&(byColorBB[us]), move_bb);
891 do_move_bb(&(byTypeBB[pt]), move_bb);
892 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
894 board[to] = board[from];
895 board[from] = PIECE_NONE;
897 // Update piece lists, note that index[from] is not updated and
898 // becomes stale. This works as long as index[] is accessed just
899 // by known occupied squares.
900 index[to] = index[from];
901 pieceList[us][pt][index[to]] = to;
903 // If the moving piece was a pawn do some special extra work
906 // Reset rule 50 draw counter
909 // Update pawn hash key and prefetch in L1/L2 cache
910 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
911 prefetchPawn(st->pawnKey, threadID);
913 // Set en passant square, only if moved pawn can be captured
914 if ((to ^ from) == 16)
916 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
918 st->epSquare = Square((int(from) + int(to)) / 2);
919 key ^= zobEp[st->epSquare];
923 if (pm) // promotion ?
925 PieceType promotion = move_promotion_piece(m);
927 assert(promotion >= KNIGHT && promotion <= QUEEN);
929 // Insert promoted piece instead of pawn
930 clear_bit(&(byTypeBB[PAWN]), to);
931 set_bit(&(byTypeBB[promotion]), to);
932 board[to] = piece_of_color_and_type(us, promotion);
934 // Update piece counts
935 pieceCount[us][promotion]++;
936 pieceCount[us][PAWN]--;
938 // Update material key
939 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
940 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
942 // Update piece lists, move the last pawn at index[to] position
943 // and shrink the list. Add a new promotion piece to the list.
944 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
945 index[lastPawnSquare] = index[to];
946 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
947 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
948 index[to] = pieceCount[us][promotion] - 1;
949 pieceList[us][promotion][index[to]] = to;
951 // Partially revert hash keys update
952 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
953 st->pawnKey ^= zobrist[us][PAWN][to];
955 // Partially revert and update incremental scores
956 st->value -= pst(us, PAWN, to);
957 st->value += pst(us, promotion, to);
960 st->npMaterial[us] += PieceValueMidgame[promotion];
964 // Update incremental scores
965 st->value += pst_delta(piece, from, to);
968 st->capturedType = capture;
970 // Update the key with the final value
973 // Update checkers bitboard, piece must be already moved
974 st->checkersBB = EmptyBoardBB;
979 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
983 if (bit_is_set(ci.checkSq[pt], to))
984 st->checkersBB = SetMaskBB[to];
987 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
990 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
993 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
999 sideToMove = opposite_color(sideToMove);
1000 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1006 /// Position::do_capture_move() is a private method used to update captured
1007 /// piece info. It is called from the main Position::do_move function.
1009 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1011 assert(capture != KING);
1015 // If the captured piece was a pawn, update pawn hash key,
1016 // otherwise update non-pawn material.
1017 if (capture == PAWN)
1019 if (ep) // en passant ?
1021 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1023 assert(to == st->epSquare);
1024 assert(relative_rank(opposite_color(them), to) == RANK_6);
1025 assert(piece_on(to) == PIECE_NONE);
1026 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1028 board[capsq] = PIECE_NONE;
1030 st->pawnKey ^= zobrist[them][PAWN][capsq];
1033 st->npMaterial[them] -= PieceValueMidgame[capture];
1035 // Remove captured piece
1036 clear_bit(&(byColorBB[them]), capsq);
1037 clear_bit(&(byTypeBB[capture]), capsq);
1038 clear_bit(&(byTypeBB[0]), capsq);
1041 key ^= zobrist[them][capture][capsq];
1043 // Update incremental scores
1044 st->value -= pst(them, capture, capsq);
1046 // Update piece count
1047 pieceCount[them][capture]--;
1049 // Update material hash key
1050 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1052 // Update piece list, move the last piece at index[capsq] position
1054 // WARNING: This is a not perfectly revresible operation. When we
1055 // will reinsert the captured piece in undo_move() we will put it
1056 // at the end of the list and not in its original place, it means
1057 // index[] and pieceList[] are not guaranteed to be invariant to a
1058 // do_move() + undo_move() sequence.
1059 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1060 index[lastPieceSquare] = index[capsq];
1061 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1062 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1064 // Reset rule 50 counter
1069 /// Position::do_castle_move() is a private method used to make a castling
1070 /// move. It is called from the main Position::do_move function. Note that
1071 /// castling moves are encoded as "king captures friendly rook" moves, for
1072 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1074 void Position::do_castle_move(Move m) {
1076 assert(move_is_ok(m));
1077 assert(move_is_castle(m));
1079 Color us = side_to_move();
1080 Color them = opposite_color(us);
1082 // Reset capture field
1083 st->capturedType = PIECE_TYPE_NONE;
1085 // Find source squares for king and rook
1086 Square kfrom = move_from(m);
1087 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1090 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1091 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1093 // Find destination squares for king and rook
1094 if (rfrom > kfrom) // O-O
1096 kto = relative_square(us, SQ_G1);
1097 rto = relative_square(us, SQ_F1);
1099 kto = relative_square(us, SQ_C1);
1100 rto = relative_square(us, SQ_D1);
1103 // Remove pieces from source squares:
1104 clear_bit(&(byColorBB[us]), kfrom);
1105 clear_bit(&(byTypeBB[KING]), kfrom);
1106 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1107 clear_bit(&(byColorBB[us]), rfrom);
1108 clear_bit(&(byTypeBB[ROOK]), rfrom);
1109 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1111 // Put pieces on destination squares:
1112 set_bit(&(byColorBB[us]), kto);
1113 set_bit(&(byTypeBB[KING]), kto);
1114 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1115 set_bit(&(byColorBB[us]), rto);
1116 set_bit(&(byTypeBB[ROOK]), rto);
1117 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1119 // Update board array
1120 Piece king = piece_of_color_and_type(us, KING);
1121 Piece rook = piece_of_color_and_type(us, ROOK);
1122 board[kfrom] = board[rfrom] = PIECE_NONE;
1126 // Update piece lists
1127 pieceList[us][KING][index[kfrom]] = kto;
1128 pieceList[us][ROOK][index[rfrom]] = rto;
1129 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1130 index[kto] = index[kfrom];
1133 // Update incremental scores
1134 st->value += pst_delta(king, kfrom, kto);
1135 st->value += pst_delta(rook, rfrom, rto);
1138 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1139 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1141 // Clear en passant square
1142 if (st->epSquare != SQ_NONE)
1144 st->key ^= zobEp[st->epSquare];
1145 st->epSquare = SQ_NONE;
1148 // Update castling rights
1149 st->key ^= zobCastle[st->castleRights];
1150 st->castleRights &= castleRightsMask[kfrom];
1151 st->key ^= zobCastle[st->castleRights];
1153 // Reset rule 50 counter
1156 // Update checkers BB
1157 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1160 sideToMove = opposite_color(sideToMove);
1161 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1167 /// Position::undo_move() unmakes a move. When it returns, the position should
1168 /// be restored to exactly the same state as before the move was made.
1170 void Position::undo_move(Move m) {
1173 assert(move_is_ok(m));
1175 sideToMove = opposite_color(sideToMove);
1177 if (move_is_castle(m))
1179 undo_castle_move(m);
1183 Color us = side_to_move();
1184 Color them = opposite_color(us);
1185 Square from = move_from(m);
1186 Square to = move_to(m);
1187 bool ep = move_is_ep(m);
1188 bool pm = move_is_promotion(m);
1190 PieceType pt = type_of_piece_on(to);
1192 assert(square_is_empty(from));
1193 assert(color_of_piece_on(to) == us);
1194 assert(!pm || relative_rank(us, to) == RANK_8);
1195 assert(!ep || to == st->previous->epSquare);
1196 assert(!ep || relative_rank(us, to) == RANK_6);
1197 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1199 if (pm) // promotion ?
1201 PieceType promotion = move_promotion_piece(m);
1204 assert(promotion >= KNIGHT && promotion <= QUEEN);
1205 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1207 // Replace promoted piece with a pawn
1208 clear_bit(&(byTypeBB[promotion]), to);
1209 set_bit(&(byTypeBB[PAWN]), to);
1211 // Update piece counts
1212 pieceCount[us][promotion]--;
1213 pieceCount[us][PAWN]++;
1215 // Update piece list replacing promotion piece with a pawn
1216 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1217 index[lastPromotionSquare] = index[to];
1218 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1219 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1220 index[to] = pieceCount[us][PAWN] - 1;
1221 pieceList[us][PAWN][index[to]] = to;
1224 // Put the piece back at the source square
1225 Bitboard move_bb = make_move_bb(to, from);
1226 do_move_bb(&(byColorBB[us]), move_bb);
1227 do_move_bb(&(byTypeBB[pt]), move_bb);
1228 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1230 board[from] = piece_of_color_and_type(us, pt);
1231 board[to] = PIECE_NONE;
1233 // Update piece list
1234 index[from] = index[to];
1235 pieceList[us][pt][index[from]] = from;
1237 if (st->capturedType)
1242 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1244 assert(st->capturedType != KING);
1245 assert(!ep || square_is_empty(capsq));
1247 // Restore the captured piece
1248 set_bit(&(byColorBB[them]), capsq);
1249 set_bit(&(byTypeBB[st->capturedType]), capsq);
1250 set_bit(&(byTypeBB[0]), capsq);
1252 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1254 // Update piece count
1255 pieceCount[them][st->capturedType]++;
1257 // Update piece list, add a new captured piece in capsq square
1258 index[capsq] = pieceCount[them][st->capturedType] - 1;
1259 pieceList[them][st->capturedType][index[capsq]] = capsq;
1262 // Finally point our state pointer back to the previous state
1269 /// Position::undo_castle_move() is a private method used to unmake a castling
1270 /// move. It is called from the main Position::undo_move function. Note that
1271 /// castling moves are encoded as "king captures friendly rook" moves, for
1272 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1274 void Position::undo_castle_move(Move m) {
1276 assert(move_is_ok(m));
1277 assert(move_is_castle(m));
1279 // When we have arrived here, some work has already been done by
1280 // Position::undo_move. In particular, the side to move has been switched,
1281 // so the code below is correct.
1282 Color us = side_to_move();
1284 // Find source squares for king and rook
1285 Square kfrom = move_from(m);
1286 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1289 // Find destination squares for king and rook
1290 if (rfrom > kfrom) // O-O
1292 kto = relative_square(us, SQ_G1);
1293 rto = relative_square(us, SQ_F1);
1295 kto = relative_square(us, SQ_C1);
1296 rto = relative_square(us, SQ_D1);
1299 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1300 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1302 // Remove pieces from destination squares:
1303 clear_bit(&(byColorBB[us]), kto);
1304 clear_bit(&(byTypeBB[KING]), kto);
1305 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1306 clear_bit(&(byColorBB[us]), rto);
1307 clear_bit(&(byTypeBB[ROOK]), rto);
1308 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1310 // Put pieces on source squares:
1311 set_bit(&(byColorBB[us]), kfrom);
1312 set_bit(&(byTypeBB[KING]), kfrom);
1313 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1314 set_bit(&(byColorBB[us]), rfrom);
1315 set_bit(&(byTypeBB[ROOK]), rfrom);
1316 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1319 board[rto] = board[kto] = PIECE_NONE;
1320 board[rfrom] = piece_of_color_and_type(us, ROOK);
1321 board[kfrom] = piece_of_color_and_type(us, KING);
1323 // Update piece lists
1324 pieceList[us][KING][index[kto]] = kfrom;
1325 pieceList[us][ROOK][index[rto]] = rfrom;
1326 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1327 index[kfrom] = index[kto];
1330 // Finally point our state pointer back to the previous state
1337 /// Position::do_null_move makes() a "null move": It switches the side to move
1338 /// and updates the hash key without executing any move on the board.
1340 void Position::do_null_move(StateInfo& backupSt) {
1343 assert(!is_check());
1345 // Back up the information necessary to undo the null move to the supplied
1346 // StateInfo object.
1347 // Note that differently from normal case here backupSt is actually used as
1348 // a backup storage not as a new state to be used.
1349 backupSt.key = st->key;
1350 backupSt.epSquare = st->epSquare;
1351 backupSt.value = st->value;
1352 backupSt.previous = st->previous;
1353 backupSt.pliesFromNull = st->pliesFromNull;
1354 st->previous = &backupSt;
1356 // Save the current key to the history[] array, in order to be able to
1357 // detect repetition draws.
1358 history[st->gamePly++] = st->key;
1360 // Update the necessary information
1361 if (st->epSquare != SQ_NONE)
1362 st->key ^= zobEp[st->epSquare];
1364 st->key ^= zobSideToMove;
1365 prefetch((char*)TT.first_entry(st->key));
1367 sideToMove = opposite_color(sideToMove);
1368 st->epSquare = SQ_NONE;
1370 st->pliesFromNull = 0;
1371 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1375 /// Position::undo_null_move() unmakes a "null move".
1377 void Position::undo_null_move() {
1380 assert(!is_check());
1382 // Restore information from the our backup StateInfo object
1383 StateInfo* backupSt = st->previous;
1384 st->key = backupSt->key;
1385 st->epSquare = backupSt->epSquare;
1386 st->value = backupSt->value;
1387 st->previous = backupSt->previous;
1388 st->pliesFromNull = backupSt->pliesFromNull;
1390 // Update the necessary information
1391 sideToMove = opposite_color(sideToMove);
1397 /// Position::see() is a static exchange evaluator: It tries to estimate the
1398 /// material gain or loss resulting from a move. There are three versions of
1399 /// this function: One which takes a destination square as input, one takes a
1400 /// move, and one which takes a 'from' and a 'to' square. The function does
1401 /// not yet understand promotions captures.
1403 int Position::see(Move m) const {
1405 assert(move_is_ok(m));
1406 return see(move_from(m), move_to(m));
1409 int Position::see_sign(Move m) const {
1411 assert(move_is_ok(m));
1413 Square from = move_from(m);
1414 Square to = move_to(m);
1416 // Early return if SEE cannot be negative because captured piece value
1417 // is not less then capturing one. Note that king moves always return
1418 // here because king midgame value is set to 0.
1419 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1422 return see(from, to);
1425 int Position::see(Square from, Square to) const {
1427 Bitboard occupied, attackers, stmAttackers, b;
1428 int swapList[32], slIndex = 1;
1429 PieceType capturedType, pt;
1432 assert(square_is_ok(from));
1433 assert(square_is_ok(to));
1435 capturedType = type_of_piece_on(to);
1437 // King cannot be recaptured
1438 if (capturedType == KING)
1439 return seeValues[capturedType];
1441 occupied = occupied_squares();
1443 // Handle en passant moves
1444 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1446 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1448 assert(capturedType == PIECE_TYPE_NONE);
1449 assert(type_of_piece_on(capQq) == PAWN);
1451 // Remove the captured pawn
1452 clear_bit(&occupied, capQq);
1453 capturedType = PAWN;
1456 // Find all attackers to the destination square, with the moving piece
1457 // removed, but possibly an X-ray attacker added behind it.
1458 clear_bit(&occupied, from);
1459 attackers = (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1460 | (bishop_attacks_bb(to, occupied)& pieces(BISHOP, QUEEN))
1461 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1462 | (attacks_from<KING>(to) & pieces(KING))
1463 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1464 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1466 // If the opponent has no attackers we are finished
1467 stm = opposite_color(color_of_piece_on(from));
1468 stmAttackers = attackers & pieces_of_color(stm);
1470 return seeValues[capturedType];
1472 // The destination square is defended, which makes things rather more
1473 // difficult to compute. We proceed by building up a "swap list" containing
1474 // the material gain or loss at each stop in a sequence of captures to the
1475 // destination square, where the sides alternately capture, and always
1476 // capture with the least valuable piece. After each capture, we look for
1477 // new X-ray attacks from behind the capturing piece.
1478 swapList[0] = seeValues[capturedType];
1479 capturedType = type_of_piece_on(from);
1482 // Locate the least valuable attacker for the side to move. The loop
1483 // below looks like it is potentially infinite, but it isn't. We know
1484 // that the side to move still has at least one attacker left.
1485 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1488 // Remove the attacker we just found from the 'occupied' bitboard,
1489 // and scan for new X-ray attacks behind the attacker.
1490 b = stmAttackers & pieces(pt);
1491 occupied ^= (b & (~b + 1));
1492 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1493 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1495 attackers &= occupied; // Cut out pieces we've already done
1497 // Add the new entry to the swap list
1498 assert(slIndex < 32);
1499 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1502 // Remember the value of the capturing piece, and change the side to
1503 // move before beginning the next iteration.
1505 stm = opposite_color(stm);
1506 stmAttackers = attackers & pieces_of_color(stm);
1508 // Stop before processing a king capture
1509 if (capturedType == KING && stmAttackers)
1511 assert(slIndex < 32);
1512 swapList[slIndex++] = QueenValueMidgame*10;
1515 } while (stmAttackers);
1517 // Having built the swap list, we negamax through it to find the best
1518 // achievable score from the point of view of the side to move.
1520 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1526 /// Position::clear() erases the position object to a pristine state, with an
1527 /// empty board, white to move, and no castling rights.
1529 void Position::clear() {
1532 memset(st, 0, sizeof(StateInfo));
1533 st->epSquare = SQ_NONE;
1534 startPosPlyCounter = 0;
1537 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1538 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1539 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1540 memset(index, 0, sizeof(int) * 64);
1542 for (int i = 0; i < 64; i++)
1543 board[i] = PIECE_NONE;
1545 for (int i = 0; i < 8; i++)
1546 for (int j = 0; j < 16; j++)
1547 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1549 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1550 castleRightsMask[sq] = ALL_CASTLES;
1553 initialKFile = FILE_E;
1554 initialKRFile = FILE_H;
1555 initialQRFile = FILE_A;
1559 /// Position::put_piece() puts a piece on the given square of the board,
1560 /// updating the board array, pieces list, bitboards, and piece counts.
1562 void Position::put_piece(Piece p, Square s) {
1564 Color c = color_of_piece(p);
1565 PieceType pt = type_of_piece(p);
1568 index[s] = pieceCount[c][pt]++;
1569 pieceList[c][pt][index[s]] = s;
1571 set_bit(&(byTypeBB[pt]), s);
1572 set_bit(&(byColorBB[c]), s);
1573 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1577 /// Position::compute_key() computes the hash key of the position. The hash
1578 /// key is usually updated incrementally as moves are made and unmade, the
1579 /// compute_key() function is only used when a new position is set up, and
1580 /// to verify the correctness of the hash key when running in debug mode.
1582 Key Position::compute_key() const {
1584 Key result = zobCastle[st->castleRights];
1586 for (Square s = SQ_A1; s <= SQ_H8; s++)
1587 if (square_is_occupied(s))
1588 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1590 if (ep_square() != SQ_NONE)
1591 result ^= zobEp[ep_square()];
1593 if (side_to_move() == BLACK)
1594 result ^= zobSideToMove;
1600 /// Position::compute_pawn_key() computes the hash key of the position. The
1601 /// hash key is usually updated incrementally as moves are made and unmade,
1602 /// the compute_pawn_key() function is only used when a new position is set
1603 /// up, and to verify the correctness of the pawn hash key when running in
1606 Key Position::compute_pawn_key() const {
1611 for (Color c = WHITE; c <= BLACK; c++)
1613 b = pieces(PAWN, c);
1615 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1621 /// Position::compute_material_key() computes the hash key of the position.
1622 /// The hash key is usually updated incrementally as moves are made and unmade,
1623 /// the compute_material_key() function is only used when a new position is set
1624 /// up, and to verify the correctness of the material hash key when running in
1627 Key Position::compute_material_key() const {
1632 for (Color c = WHITE; c <= BLACK; c++)
1633 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1635 count = piece_count(c, pt);
1636 for (int i = 0; i < count; i++)
1637 result ^= zobrist[c][pt][i];
1643 /// Position::compute_value() compute the incremental scores for the middle
1644 /// game and the endgame. These functions are used to initialize the incremental
1645 /// scores when a new position is set up, and to verify that the scores are correctly
1646 /// updated by do_move and undo_move when the program is running in debug mode.
1647 Score Position::compute_value() const {
1650 Score result = SCORE_ZERO;
1652 for (Color c = WHITE; c <= BLACK; c++)
1653 for (PieceType pt = PAWN; pt <= KING; pt++)
1657 result += pst(c, pt, pop_1st_bit(&b));
1660 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1665 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1666 /// game material value for the given side. Material values are updated
1667 /// incrementally during the search, this function is only used while
1668 /// initializing a new Position object.
1670 Value Position::compute_non_pawn_material(Color c) const {
1672 Value result = VALUE_ZERO;
1674 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1675 result += piece_count(c, pt) * PieceValueMidgame[pt];
1681 /// Position::is_draw() tests whether the position is drawn by material,
1682 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1683 /// must be done by the search.
1685 bool Position::is_draw() const {
1687 // Draw by material?
1689 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1692 // Draw by the 50 moves rule?
1693 if (st->rule50 > 99 && !is_mate())
1696 // Draw by repetition?
1697 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1698 if (history[st->gamePly - i] == st->key)
1705 /// Position::is_mate() returns true or false depending on whether the
1706 /// side to move is checkmated.
1708 bool Position::is_mate() const {
1710 MoveStack moves[MOVES_MAX];
1711 return is_check() && generate<MV_LEGAL>(*this, moves) == moves;
1715 /// Position::has_mate_threat() tests whether the side to move is under
1716 /// a threat of being mated in one from the current position.
1718 bool Position::has_mate_threat() {
1720 MoveStack mlist[MOVES_MAX], *last, *cur;
1722 bool mateFound = false;
1724 // If we are under check it's up to evasions to do the job
1728 // First pass the move to our opponent doing a null move
1731 // Then generate pseudo-legal moves that could give check
1732 last = generate<MV_NON_CAPTURE_CHECK>(*this, mlist);
1733 last = generate<MV_CAPTURE>(*this, last);
1735 // Loop through the moves, and see if one of them gives mate
1736 Bitboard pinned = pinned_pieces(sideToMove);
1737 CheckInfo ci(*this);
1738 for (cur = mlist; cur != last && !mateFound; cur++)
1740 Move move = cur->move;
1741 if ( !pl_move_is_legal(move, pinned)
1742 || !move_is_check(move, ci))
1745 do_move(move, st2, ci, true);
1758 /// Position::init_zobrist() is a static member function which initializes at
1759 /// startup the various arrays used to compute hash keys.
1761 void Position::init_zobrist() {
1766 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1767 zobrist[i][j][k] = rk.rand<Key>();
1769 for (i = 0; i < 64; i++)
1770 zobEp[i] = rk.rand<Key>();
1772 for (i = 0; i < 16; i++)
1773 zobCastle[i] = rk.rand<Key>();
1775 zobSideToMove = rk.rand<Key>();
1776 zobExclusion = rk.rand<Key>();
1780 /// Position::init_piece_square_tables() initializes the piece square tables.
1781 /// This is a two-step operation: First, the white halves of the tables are
1782 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1783 /// of the tables are initialized by mirroring and changing the sign of the
1784 /// corresponding white scores.
1786 void Position::init_piece_square_tables() {
1788 for (Square s = SQ_A1; s <= SQ_H8; s++)
1789 for (Piece p = WP; p <= WK; p++)
1790 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1792 for (Square s = SQ_A1; s <= SQ_H8; s++)
1793 for (Piece p = BP; p <= BK; p++)
1794 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1798 /// Position::flipped_copy() makes a copy of the input position, but with
1799 /// the white and black sides reversed. This is only useful for debugging,
1800 /// especially for finding evaluation symmetry bugs.
1802 void Position::flipped_copy(const Position& pos) {
1804 assert(pos.is_ok());
1807 threadID = pos.thread();
1810 for (Square s = SQ_A1; s <= SQ_H8; s++)
1811 if (!pos.square_is_empty(s))
1812 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1815 sideToMove = opposite_color(pos.side_to_move());
1818 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1819 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1820 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1821 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1823 initialKFile = pos.initialKFile;
1824 initialKRFile = pos.initialKRFile;
1825 initialQRFile = pos.initialQRFile;
1827 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1828 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1829 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1830 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1831 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1832 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1834 // En passant square
1835 if (pos.st->epSquare != SQ_NONE)
1836 st->epSquare = flip_square(pos.st->epSquare);
1842 st->key = compute_key();
1843 st->pawnKey = compute_pawn_key();
1844 st->materialKey = compute_material_key();
1846 // Incremental scores
1847 st->value = compute_value();
1850 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1851 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1857 /// Position::is_ok() performs some consitency checks for the position object.
1858 /// This is meant to be helpful when debugging.
1860 bool Position::is_ok(int* failedStep) const {
1862 // What features of the position should be verified?
1863 const bool debugAll = false;
1865 const bool debugBitboards = debugAll || false;
1866 const bool debugKingCount = debugAll || false;
1867 const bool debugKingCapture = debugAll || false;
1868 const bool debugCheckerCount = debugAll || false;
1869 const bool debugKey = debugAll || false;
1870 const bool debugMaterialKey = debugAll || false;
1871 const bool debugPawnKey = debugAll || false;
1872 const bool debugIncrementalEval = debugAll || false;
1873 const bool debugNonPawnMaterial = debugAll || false;
1874 const bool debugPieceCounts = debugAll || false;
1875 const bool debugPieceList = debugAll || false;
1876 const bool debugCastleSquares = debugAll || false;
1878 if (failedStep) *failedStep = 1;
1881 if (!color_is_ok(side_to_move()))
1884 // Are the king squares in the position correct?
1885 if (failedStep) (*failedStep)++;
1886 if (piece_on(king_square(WHITE)) != WK)
1889 if (failedStep) (*failedStep)++;
1890 if (piece_on(king_square(BLACK)) != BK)
1894 if (failedStep) (*failedStep)++;
1895 if (!file_is_ok(initialKRFile))
1898 if (!file_is_ok(initialQRFile))
1901 // Do both sides have exactly one king?
1902 if (failedStep) (*failedStep)++;
1905 int kingCount[2] = {0, 0};
1906 for (Square s = SQ_A1; s <= SQ_H8; s++)
1907 if (type_of_piece_on(s) == KING)
1908 kingCount[color_of_piece_on(s)]++;
1910 if (kingCount[0] != 1 || kingCount[1] != 1)
1914 // Can the side to move capture the opponent's king?
1915 if (failedStep) (*failedStep)++;
1916 if (debugKingCapture)
1918 Color us = side_to_move();
1919 Color them = opposite_color(us);
1920 Square ksq = king_square(them);
1921 if (attackers_to(ksq) & pieces_of_color(us))
1925 // Is there more than 2 checkers?
1926 if (failedStep) (*failedStep)++;
1927 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1931 if (failedStep) (*failedStep)++;
1934 // The intersection of the white and black pieces must be empty
1935 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1938 // The union of the white and black pieces must be equal to all
1940 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1943 // Separate piece type bitboards must have empty intersections
1944 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1945 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1946 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1950 // En passant square OK?
1951 if (failedStep) (*failedStep)++;
1952 if (ep_square() != SQ_NONE)
1954 // The en passant square must be on rank 6, from the point of view of the
1956 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1961 if (failedStep) (*failedStep)++;
1962 if (debugKey && st->key != compute_key())
1965 // Pawn hash key OK?
1966 if (failedStep) (*failedStep)++;
1967 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1970 // Material hash key OK?
1971 if (failedStep) (*failedStep)++;
1972 if (debugMaterialKey && st->materialKey != compute_material_key())
1975 // Incremental eval OK?
1976 if (failedStep) (*failedStep)++;
1977 if (debugIncrementalEval && st->value != compute_value())
1980 // Non-pawn material OK?
1981 if (failedStep) (*failedStep)++;
1982 if (debugNonPawnMaterial)
1984 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1987 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1992 if (failedStep) (*failedStep)++;
1993 if (debugPieceCounts)
1994 for (Color c = WHITE; c <= BLACK; c++)
1995 for (PieceType pt = PAWN; pt <= KING; pt++)
1996 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1999 if (failedStep) (*failedStep)++;
2002 for (Color c = WHITE; c <= BLACK; c++)
2003 for (PieceType pt = PAWN; pt <= KING; pt++)
2004 for (int i = 0; i < pieceCount[c][pt]; i++)
2006 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2009 if (index[piece_list(c, pt, i)] != i)
2014 if (failedStep) (*failedStep)++;
2015 if (debugCastleSquares) {
2016 for (Color c = WHITE; c <= BLACK; c++) {
2017 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2019 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2022 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2024 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2026 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2028 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2032 if (failedStep) *failedStep = 0;