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; 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)
123 CheckInfo::CheckInfo(const Position& pos) {
125 Color us = pos.side_to_move();
126 Color them = opposite_color(us);
128 ksq = pos.king_square(them);
129 dcCandidates = pos.discovered_check_candidates(us);
131 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
132 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
133 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
134 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
135 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
136 checkSq[KING] = EmptyBoardBB;
140 /// Position c'tors. Here we always create a copy of the original position
141 /// or the FEN string, we want the new born Position object do not depend
142 /// on any external data so we detach state pointer from the source one.
144 Position::Position(const Position& pos, int th) {
146 memcpy(this, &pos, sizeof(Position));
147 detach(); // Always detach() in copy c'tor to avoid surprises
152 Position::Position(const string& fen, int th) {
159 /// Position::detach() copies the content of the current state and castling
160 /// masks inside the position itself. This is needed when the st pointee could
161 /// become stale, as example because the caller is about to going out of scope.
163 void Position::detach() {
167 st->previous = NULL; // as a safe guard
171 /// Position::from_fen() initializes the position object with the given FEN
172 /// string. This function is not very robust - make sure that input FENs are
173 /// correct (this is assumed to be the responsibility of the GUI).
175 void Position::from_fen(const string& fen) {
177 A FEN string defines a particular position using only the ASCII character set.
179 A FEN string contains six fields. The separator between fields is a space. The fields are:
181 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
182 with rank 1; within each rank, the contents of each square are described from file a through file h.
183 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
184 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
185 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
186 of blank squares), and "/" separate ranks.
188 2) Active color. "w" means white moves next, "b" means black.
190 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
191 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
192 kingside), and/or "q" (Black can castle queenside).
194 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
195 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
196 regardless of whether there is a pawn in position to make an en passant capture.
198 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
199 to determine if a draw can be claimed under the fifty-move rule.
201 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
205 std::istringstream ss(fen);
211 // 1. Piece placement field
212 while (ss.get(token) && token != ' ')
216 file += File(token - '0'); // Skip the given number of files
219 else if (token == '/')
226 if (pieceLetters.find(token) == pieceLetters.end())
229 put_piece(pieceLetters[token], make_square(file, rank));
234 if (!ss.get(token) || (token != 'w' && token != 'b'))
237 sideToMove = (token == 'w' ? WHITE : BLACK);
239 if (!ss.get(token) || token != ' ')
242 // 3. Castling availability
243 while (ss.get(token) && token != ' ')
248 if (!set_castling_rights(token))
252 // 4. En passant square -- ignore if no capture is possible
254 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
255 && (ss.get(row) && (row == '3' || row == '6')))
257 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
258 Color them = opposite_color(sideToMove);
260 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
261 st->epSquare = fenEpSquare;
264 // 5-6. Halfmove clock and fullmove number are not parsed
266 // Various initialisations
267 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
268 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
269 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
270 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
271 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
272 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
274 isChess960 = initialKFile != FILE_E
275 || initialQRFile != FILE_A
276 || initialKRFile != FILE_H;
280 st->key = compute_key();
281 st->pawnKey = compute_pawn_key();
282 st->materialKey = compute_material_key();
283 st->value = compute_value();
284 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
285 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
289 cout << "Error in FEN string: " << fen << endl;
293 /// Position::set_castling_rights() sets castling parameters castling avaiability.
294 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
295 /// that uses the letters of the columns on which the rooks began the game instead
296 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
297 /// associated with the castling right, the traditional castling tag will be replaced
298 /// by the file letter of the involved rook as for the Shredder-FEN.
300 bool Position::set_castling_rights(char token) {
302 Color c = token >= 'a' ? BLACK : WHITE;
303 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
304 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
305 Piece rook = (c == WHITE ? WR : BR);
307 initialKFile = square_file(king_square(c));
308 token = char(toupper(token));
312 for (Square sq = sqH; sq >= sqA; sq--)
313 if (piece_on(sq) == rook)
316 initialKRFile = square_file(sq);
320 else if (token == 'Q')
322 for (Square sq = sqA; sq <= sqH; sq++)
323 if (piece_on(sq) == rook)
326 initialQRFile = square_file(sq);
330 else if (token >= 'A' && token <= 'H')
332 File rookFile = File(token - 'A') + FILE_A;
333 if (rookFile < initialKFile)
336 initialQRFile = rookFile;
341 initialKRFile = rookFile;
350 /// Position::to_fen() returns a FEN representation of the position. In case
351 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
353 const string Position::to_fen() const {
359 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
361 for (File file = FILE_A; file <= FILE_H; file++)
363 sq = make_square(file, rank);
365 if (square_is_occupied(sq))
368 fen += pieceLetters.from_piece(piece_on(sq));
378 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
379 fen.erase(--fen.end());
380 fen += (sideToMove == WHITE ? " w " : " b ");
382 if (st->castleRights != CASTLES_NONE)
384 if (can_castle_kingside(WHITE))
385 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
387 if (can_castle_queenside(WHITE))
388 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
390 if (can_castle_kingside(BLACK))
391 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
393 if (can_castle_queenside(BLACK))
394 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
398 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
403 /// Position::print() prints an ASCII representation of the position to
404 /// the standard output. If a move is given then also the san is printed.
406 void Position::print(Move move) const {
408 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
409 static bool requestPending = false;
411 // Check for reentrancy, as example when called from inside
412 // MovePicker that is used also here in move_to_san()
416 requestPending = true;
420 Position p(*this, thread());
421 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
422 cout << "\nMove is: " << dd << move_to_san(p, move);
425 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
427 cout << dottedLine << '|';
428 for (File file = FILE_A; file <= FILE_H; file++)
430 Square sq = make_square(file, rank);
431 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
432 Piece piece = piece_on(sq);
434 if (piece == PIECE_NONE && square_color(sq) == DARK)
435 piece = PIECE_NONE_DARK_SQ;
437 cout << c << pieceLetters.from_piece(piece) << c << '|';
440 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
441 requestPending = false;
445 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
446 /// king) pieces for the given color and for the given pinner type. Or, when
447 /// template parameter FindPinned is false, the pieces of the given color
448 /// candidate for a discovery check against the enemy king.
449 /// Bitboard checkersBB must be already updated when looking for pinners.
451 template<bool FindPinned>
452 Bitboard Position::hidden_checkers(Color c) const {
454 Bitboard result = EmptyBoardBB;
455 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
457 // Pinned pieces protect our king, dicovery checks attack
459 Square ksq = king_square(FindPinned ? c : opposite_color(c));
461 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
462 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
464 if (FindPinned && pinners)
465 pinners &= ~st->checkersBB;
469 Square s = pop_1st_bit(&pinners);
470 Bitboard b = squares_between(s, ksq) & occupied_squares();
474 if ( !(b & (b - 1)) // Only one bit set?
475 && (b & pieces_of_color(c))) // Is an our piece?
482 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
483 /// king) pieces for the given color. Note that checkersBB bitboard must
484 /// be already updated.
486 Bitboard Position::pinned_pieces(Color c) const {
488 return hidden_checkers<true>(c);
492 /// Position:discovered_check_candidates() returns a bitboard containing all
493 /// pieces for the given side which are candidates for giving a discovered
494 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
495 /// to be already updated.
497 Bitboard Position::discovered_check_candidates(Color c) const {
499 return hidden_checkers<false>(c);
502 /// Position::attackers_to() computes a bitboard containing all pieces which
503 /// attacks a given square.
505 Bitboard Position::attackers_to(Square s) const {
507 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
508 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
509 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
510 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
511 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
512 | (attacks_from<KING>(s) & pieces(KING));
515 /// Position::attacks_from() computes a bitboard of all attacks
516 /// of a given piece put in a given square.
518 Bitboard Position::attacks_from(Piece p, Square s) const {
520 assert(square_is_ok(s));
524 case WP: return attacks_from<PAWN>(s, WHITE);
525 case BP: return attacks_from<PAWN>(s, BLACK);
526 case WN: case BN: return attacks_from<KNIGHT>(s);
527 case WB: case BB: return attacks_from<BISHOP>(s);
528 case WR: case BR: return attacks_from<ROOK>(s);
529 case WQ: case BQ: return attacks_from<QUEEN>(s);
530 case WK: case BK: return attacks_from<KING>(s);
537 /// Position::move_attacks_square() tests whether a move from the current
538 /// position attacks a given square.
540 bool Position::move_attacks_square(Move m, Square s) const {
542 assert(move_is_ok(m));
543 assert(square_is_ok(s));
546 Square f = move_from(m), t = move_to(m);
548 assert(square_is_occupied(f));
550 if (bit_is_set(attacks_from(piece_on(f), t), s))
553 // Move the piece and scan for X-ray attacks behind it
554 occ = occupied_squares();
555 do_move_bb(&occ, make_move_bb(f, t));
556 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
557 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
558 & pieces_of_color(color_of_piece_on(f));
560 // If we have attacks we need to verify that are caused by our move
561 // and are not already existent ones.
562 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
566 /// Position::find_checkers() computes the checkersBB bitboard, which
567 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
568 /// currently works by calling Position::attackers_to, which is probably
569 /// inefficient. Consider rewriting this function to use the last move
570 /// played, like in non-bitboard versions of Glaurung.
572 void Position::find_checkers() {
574 Color us = side_to_move();
575 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
579 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
581 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
584 assert(move_is_ok(m));
585 assert(pinned == pinned_pieces(side_to_move()));
587 // Castling moves are checked for legality during move generation.
588 if (move_is_castle(m))
591 Color us = side_to_move();
592 Square from = move_from(m);
594 assert(color_of_piece_on(from) == us);
595 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
597 // En passant captures are a tricky special case. Because they are
598 // rather uncommon, we do it simply by testing whether the king is attacked
599 // after the move is made
602 Color them = opposite_color(us);
603 Square to = move_to(m);
604 Square capsq = make_square(square_file(to), square_rank(from));
605 Bitboard b = occupied_squares();
606 Square ksq = king_square(us);
608 assert(to == ep_square());
609 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
610 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
611 assert(piece_on(to) == PIECE_NONE);
614 clear_bit(&b, capsq);
617 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
618 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
621 // If the moving piece is a king, check whether the destination
622 // square is attacked by the opponent.
623 if (type_of_piece_on(from) == KING)
624 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
626 // A non-king move is legal if and only if it is not pinned or it
627 // is moving along the ray towards or away from the king.
629 || !bit_is_set(pinned, from)
630 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
634 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
636 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
640 Color us = side_to_move();
641 Square from = move_from(m);
642 Square to = move_to(m);
644 // King moves and en-passant captures are verified in pl_move_is_legal()
645 if (type_of_piece_on(from) == KING || move_is_ep(m))
646 return pl_move_is_legal(m, pinned);
648 Bitboard target = checkers();
649 Square checksq = pop_1st_bit(&target);
651 if (target) // double check ?
654 // Our move must be a blocking evasion or a capture of the checking piece
655 target = squares_between(checksq, king_square(us)) | checkers();
656 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
660 /// Position::move_is_check() tests whether a pseudo-legal move is a check
662 bool Position::move_is_check(Move m) const {
664 return move_is_check(m, CheckInfo(*this));
667 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
670 assert(move_is_ok(m));
671 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
672 assert(color_of_piece_on(move_from(m)) == side_to_move());
673 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
675 Square from = move_from(m);
676 Square to = move_to(m);
677 PieceType pt = type_of_piece_on(from);
680 if (bit_is_set(ci.checkSq[pt], to))
684 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
686 // For pawn and king moves we need to verify also direction
687 if ( (pt != PAWN && pt != KING)
688 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
692 // Can we skip the ugly special cases ?
693 if (!move_is_special(m))
696 Color us = side_to_move();
697 Bitboard b = occupied_squares();
699 // Promotion with check ?
700 if (move_is_promotion(m))
704 switch (move_promotion_piece(m))
707 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
709 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
711 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
713 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
719 // En passant capture with check ? We have already handled the case
720 // of direct checks and ordinary discovered check, the only case we
721 // need to handle is the unusual case of a discovered check through
722 // the captured pawn.
725 Square capsq = make_square(square_file(to), square_rank(from));
727 clear_bit(&b, capsq);
729 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
730 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
733 // Castling with check ?
734 if (move_is_castle(m))
736 Square kfrom, kto, rfrom, rto;
742 kto = relative_square(us, SQ_G1);
743 rto = relative_square(us, SQ_F1);
745 kto = relative_square(us, SQ_C1);
746 rto = relative_square(us, SQ_D1);
748 clear_bit(&b, kfrom);
749 clear_bit(&b, rfrom);
752 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
759 /// Position::do_move() makes a move, and saves all information necessary
760 /// to a StateInfo object. The move is assumed to be legal.
761 /// Pseudo-legal moves should be filtered out before this function is called.
763 void Position::do_move(Move m, StateInfo& newSt) {
766 do_move(m, newSt, ci, move_is_check(m, ci));
769 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
772 assert(move_is_ok(m));
777 // Copy some fields of old state to our new StateInfo object except the
778 // ones which are recalculated from scratch anyway, then switch our state
779 // pointer to point to the new, ready to be updated, state.
780 struct ReducedStateInfo {
781 Key pawnKey, materialKey;
782 int castleRights, rule50, gamePly, pliesFromNull;
789 memcpy(&newSt, st, sizeof(ReducedStateInfo));
794 // Save the current key to the history[] array, in order to be able to
795 // detect repetition draws.
796 history[st->gamePly++] = key;
798 // Update side to move
799 key ^= zobSideToMove;
801 // Increment the 50 moves rule draw counter. Resetting it to zero in the
802 // case of non-reversible moves is taken care of later.
806 if (move_is_castle(m))
813 Color us = side_to_move();
814 Color them = opposite_color(us);
815 Square from = move_from(m);
816 Square to = move_to(m);
817 bool ep = move_is_ep(m);
818 bool pm = move_is_promotion(m);
820 Piece piece = piece_on(from);
821 PieceType pt = type_of_piece(piece);
822 PieceType capture = ep ? PAWN : type_of_piece_on(to);
824 assert(color_of_piece_on(from) == us);
825 assert(color_of_piece_on(to) == them || square_is_empty(to));
826 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
827 assert(!pm || relative_rank(us, to) == RANK_8);
830 do_capture_move(key, capture, them, to, ep);
833 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
835 // Reset en passant square
836 if (st->epSquare != SQ_NONE)
838 key ^= zobEp[st->epSquare];
839 st->epSquare = SQ_NONE;
842 // Update castle rights, try to shortcut a common case
843 int cm = castleRightsMask[from] & castleRightsMask[to];
844 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
846 key ^= zobCastle[st->castleRights];
847 st->castleRights &= castleRightsMask[from];
848 st->castleRights &= castleRightsMask[to];
849 key ^= zobCastle[st->castleRights];
852 // Prefetch TT access as soon as we know key is updated
853 prefetch((char*)TT.first_entry(key));
856 Bitboard move_bb = make_move_bb(from, to);
857 do_move_bb(&(byColorBB[us]), move_bb);
858 do_move_bb(&(byTypeBB[pt]), move_bb);
859 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
861 board[to] = board[from];
862 board[from] = PIECE_NONE;
864 // Update piece lists, note that index[from] is not updated and
865 // becomes stale. This works as long as index[] is accessed just
866 // by known occupied squares.
867 index[to] = index[from];
868 pieceList[us][pt][index[to]] = to;
870 // If the moving piece was a pawn do some special extra work
873 // Reset rule 50 draw counter
876 // Update pawn hash key and prefetch in L1/L2 cache
877 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
878 prefetchPawn(st->pawnKey, threadID);
880 // Set en passant square, only if moved pawn can be captured
881 if ((to ^ from) == 16)
883 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
885 st->epSquare = Square((int(from) + int(to)) / 2);
886 key ^= zobEp[st->epSquare];
890 if (pm) // promotion ?
892 PieceType promotion = move_promotion_piece(m);
894 assert(promotion >= KNIGHT && promotion <= QUEEN);
896 // Insert promoted piece instead of pawn
897 clear_bit(&(byTypeBB[PAWN]), to);
898 set_bit(&(byTypeBB[promotion]), to);
899 board[to] = piece_of_color_and_type(us, promotion);
901 // Update piece counts
902 pieceCount[us][promotion]++;
903 pieceCount[us][PAWN]--;
905 // Update material key
906 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
907 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
909 // Update piece lists, move the last pawn at index[to] position
910 // and shrink the list. Add a new promotion piece to the list.
911 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
912 index[lastPawnSquare] = index[to];
913 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
914 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
915 index[to] = pieceCount[us][promotion] - 1;
916 pieceList[us][promotion][index[to]] = to;
918 // Partially revert hash keys update
919 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
920 st->pawnKey ^= zobrist[us][PAWN][to];
922 // Partially revert and update incremental scores
923 st->value -= pst(us, PAWN, to);
924 st->value += pst(us, promotion, to);
927 st->npMaterial[us] += PieceValueMidgame[promotion];
931 // Update incremental scores
932 st->value += pst_delta(piece, from, to);
935 st->capturedType = capture;
937 // Update the key with the final value
940 // Update checkers bitboard, piece must be already moved
941 st->checkersBB = EmptyBoardBB;
946 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
950 if (bit_is_set(ci.checkSq[pt], to))
951 st->checkersBB = SetMaskBB[to];
954 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
957 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
960 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
966 sideToMove = opposite_color(sideToMove);
967 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
973 /// Position::do_capture_move() is a private method used to update captured
974 /// piece info. It is called from the main Position::do_move function.
976 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
978 assert(capture != KING);
982 // If the captured piece was a pawn, update pawn hash key,
983 // otherwise update non-pawn material.
986 if (ep) // en passant ?
988 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
990 assert(to == st->epSquare);
991 assert(relative_rank(opposite_color(them), to) == RANK_6);
992 assert(piece_on(to) == PIECE_NONE);
993 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
995 board[capsq] = PIECE_NONE;
997 st->pawnKey ^= zobrist[them][PAWN][capsq];
1000 st->npMaterial[them] -= PieceValueMidgame[capture];
1002 // Remove captured piece
1003 clear_bit(&(byColorBB[them]), capsq);
1004 clear_bit(&(byTypeBB[capture]), capsq);
1005 clear_bit(&(byTypeBB[0]), capsq);
1008 key ^= zobrist[them][capture][capsq];
1010 // Update incremental scores
1011 st->value -= pst(them, capture, capsq);
1013 // Update piece count
1014 pieceCount[them][capture]--;
1016 // Update material hash key
1017 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1019 // Update piece list, move the last piece at index[capsq] position
1021 // WARNING: This is a not perfectly revresible operation. When we
1022 // will reinsert the captured piece in undo_move() we will put it
1023 // at the end of the list and not in its original place, it means
1024 // index[] and pieceList[] are not guaranteed to be invariant to a
1025 // do_move() + undo_move() sequence.
1026 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1027 index[lastPieceSquare] = index[capsq];
1028 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1029 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1031 // Reset rule 50 counter
1036 /// Position::do_castle_move() is a private method used to make a castling
1037 /// move. It is called from the main Position::do_move function. Note that
1038 /// castling moves are encoded as "king captures friendly rook" moves, for
1039 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1041 void Position::do_castle_move(Move m) {
1043 assert(move_is_ok(m));
1044 assert(move_is_castle(m));
1046 Color us = side_to_move();
1047 Color them = opposite_color(us);
1049 // Reset capture field
1050 st->capturedType = PIECE_TYPE_NONE;
1052 // Find source squares for king and rook
1053 Square kfrom = move_from(m);
1054 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1057 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1058 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1060 // Find destination squares for king and rook
1061 if (rfrom > kfrom) // O-O
1063 kto = relative_square(us, SQ_G1);
1064 rto = relative_square(us, SQ_F1);
1066 kto = relative_square(us, SQ_C1);
1067 rto = relative_square(us, SQ_D1);
1070 // Remove pieces from source squares:
1071 clear_bit(&(byColorBB[us]), kfrom);
1072 clear_bit(&(byTypeBB[KING]), kfrom);
1073 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1074 clear_bit(&(byColorBB[us]), rfrom);
1075 clear_bit(&(byTypeBB[ROOK]), rfrom);
1076 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1078 // Put pieces on destination squares:
1079 set_bit(&(byColorBB[us]), kto);
1080 set_bit(&(byTypeBB[KING]), kto);
1081 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1082 set_bit(&(byColorBB[us]), rto);
1083 set_bit(&(byTypeBB[ROOK]), rto);
1084 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1086 // Update board array
1087 Piece king = piece_of_color_and_type(us, KING);
1088 Piece rook = piece_of_color_and_type(us, ROOK);
1089 board[kfrom] = board[rfrom] = PIECE_NONE;
1093 // Update piece lists
1094 pieceList[us][KING][index[kfrom]] = kto;
1095 pieceList[us][ROOK][index[rfrom]] = rto;
1096 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1097 index[kto] = index[kfrom];
1100 // Update incremental scores
1101 st->value += pst_delta(king, kfrom, kto);
1102 st->value += pst_delta(rook, rfrom, rto);
1105 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1106 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1108 // Clear en passant square
1109 if (st->epSquare != SQ_NONE)
1111 st->key ^= zobEp[st->epSquare];
1112 st->epSquare = SQ_NONE;
1115 // Update castling rights
1116 st->key ^= zobCastle[st->castleRights];
1117 st->castleRights &= castleRightsMask[kfrom];
1118 st->key ^= zobCastle[st->castleRights];
1120 // Reset rule 50 counter
1123 // Update checkers BB
1124 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1127 sideToMove = opposite_color(sideToMove);
1128 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1134 /// Position::undo_move() unmakes a move. When it returns, the position should
1135 /// be restored to exactly the same state as before the move was made.
1137 void Position::undo_move(Move m) {
1140 assert(move_is_ok(m));
1142 sideToMove = opposite_color(sideToMove);
1144 if (move_is_castle(m))
1146 undo_castle_move(m);
1150 Color us = side_to_move();
1151 Color them = opposite_color(us);
1152 Square from = move_from(m);
1153 Square to = move_to(m);
1154 bool ep = move_is_ep(m);
1155 bool pm = move_is_promotion(m);
1157 PieceType pt = type_of_piece_on(to);
1159 assert(square_is_empty(from));
1160 assert(color_of_piece_on(to) == us);
1161 assert(!pm || relative_rank(us, to) == RANK_8);
1162 assert(!ep || to == st->previous->epSquare);
1163 assert(!ep || relative_rank(us, to) == RANK_6);
1164 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1166 if (pm) // promotion ?
1168 PieceType promotion = move_promotion_piece(m);
1171 assert(promotion >= KNIGHT && promotion <= QUEEN);
1172 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1174 // Replace promoted piece with a pawn
1175 clear_bit(&(byTypeBB[promotion]), to);
1176 set_bit(&(byTypeBB[PAWN]), to);
1178 // Update piece counts
1179 pieceCount[us][promotion]--;
1180 pieceCount[us][PAWN]++;
1182 // Update piece list replacing promotion piece with a pawn
1183 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1184 index[lastPromotionSquare] = index[to];
1185 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1186 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1187 index[to] = pieceCount[us][PAWN] - 1;
1188 pieceList[us][PAWN][index[to]] = to;
1191 // Put the piece back at the source square
1192 Bitboard move_bb = make_move_bb(to, from);
1193 do_move_bb(&(byColorBB[us]), move_bb);
1194 do_move_bb(&(byTypeBB[pt]), move_bb);
1195 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1197 board[from] = piece_of_color_and_type(us, pt);
1198 board[to] = PIECE_NONE;
1200 // Update piece list
1201 index[from] = index[to];
1202 pieceList[us][pt][index[from]] = from;
1204 if (st->capturedType)
1209 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1211 assert(st->capturedType != KING);
1212 assert(!ep || square_is_empty(capsq));
1214 // Restore the captured piece
1215 set_bit(&(byColorBB[them]), capsq);
1216 set_bit(&(byTypeBB[st->capturedType]), capsq);
1217 set_bit(&(byTypeBB[0]), capsq);
1219 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1221 // Update piece count
1222 pieceCount[them][st->capturedType]++;
1224 // Update piece list, add a new captured piece in capsq square
1225 index[capsq] = pieceCount[them][st->capturedType] - 1;
1226 pieceList[them][st->capturedType][index[capsq]] = capsq;
1229 // Finally point our state pointer back to the previous state
1236 /// Position::undo_castle_move() is a private method used to unmake a castling
1237 /// move. It is called from the main Position::undo_move function. Note that
1238 /// castling moves are encoded as "king captures friendly rook" moves, for
1239 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1241 void Position::undo_castle_move(Move m) {
1243 assert(move_is_ok(m));
1244 assert(move_is_castle(m));
1246 // When we have arrived here, some work has already been done by
1247 // Position::undo_move. In particular, the side to move has been switched,
1248 // so the code below is correct.
1249 Color us = side_to_move();
1251 // Find source squares for king and rook
1252 Square kfrom = move_from(m);
1253 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1256 // Find destination squares for king and rook
1257 if (rfrom > kfrom) // O-O
1259 kto = relative_square(us, SQ_G1);
1260 rto = relative_square(us, SQ_F1);
1262 kto = relative_square(us, SQ_C1);
1263 rto = relative_square(us, SQ_D1);
1266 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1267 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1269 // Remove pieces from destination squares:
1270 clear_bit(&(byColorBB[us]), kto);
1271 clear_bit(&(byTypeBB[KING]), kto);
1272 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1273 clear_bit(&(byColorBB[us]), rto);
1274 clear_bit(&(byTypeBB[ROOK]), rto);
1275 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1277 // Put pieces on source squares:
1278 set_bit(&(byColorBB[us]), kfrom);
1279 set_bit(&(byTypeBB[KING]), kfrom);
1280 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1281 set_bit(&(byColorBB[us]), rfrom);
1282 set_bit(&(byTypeBB[ROOK]), rfrom);
1283 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1286 board[rto] = board[kto] = PIECE_NONE;
1287 board[rfrom] = piece_of_color_and_type(us, ROOK);
1288 board[kfrom] = piece_of_color_and_type(us, KING);
1290 // Update piece lists
1291 pieceList[us][KING][index[kto]] = kfrom;
1292 pieceList[us][ROOK][index[rto]] = rfrom;
1293 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1294 index[kfrom] = index[kto];
1297 // Finally point our state pointer back to the previous state
1304 /// Position::do_null_move makes() a "null move": It switches the side to move
1305 /// and updates the hash key without executing any move on the board.
1307 void Position::do_null_move(StateInfo& backupSt) {
1310 assert(!is_check());
1312 // Back up the information necessary to undo the null move to the supplied
1313 // StateInfo object.
1314 // Note that differently from normal case here backupSt is actually used as
1315 // a backup storage not as a new state to be used.
1316 backupSt.key = st->key;
1317 backupSt.epSquare = st->epSquare;
1318 backupSt.value = st->value;
1319 backupSt.previous = st->previous;
1320 backupSt.pliesFromNull = st->pliesFromNull;
1321 st->previous = &backupSt;
1323 // Save the current key to the history[] array, in order to be able to
1324 // detect repetition draws.
1325 history[st->gamePly++] = st->key;
1327 // Update the necessary information
1328 if (st->epSquare != SQ_NONE)
1329 st->key ^= zobEp[st->epSquare];
1331 st->key ^= zobSideToMove;
1332 prefetch((char*)TT.first_entry(st->key));
1334 sideToMove = opposite_color(sideToMove);
1335 st->epSquare = SQ_NONE;
1337 st->pliesFromNull = 0;
1338 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1342 /// Position::undo_null_move() unmakes a "null move".
1344 void Position::undo_null_move() {
1347 assert(!is_check());
1349 // Restore information from the our backup StateInfo object
1350 StateInfo* backupSt = st->previous;
1351 st->key = backupSt->key;
1352 st->epSquare = backupSt->epSquare;
1353 st->value = backupSt->value;
1354 st->previous = backupSt->previous;
1355 st->pliesFromNull = backupSt->pliesFromNull;
1357 // Update the necessary information
1358 sideToMove = opposite_color(sideToMove);
1364 /// Position::see() is a static exchange evaluator: It tries to estimate the
1365 /// material gain or loss resulting from a move. There are three versions of
1366 /// this function: One which takes a destination square as input, one takes a
1367 /// move, and one which takes a 'from' and a 'to' square. The function does
1368 /// not yet understand promotions captures.
1370 int Position::see(Move m) const {
1372 assert(move_is_ok(m));
1373 return see(move_from(m), move_to(m));
1376 int Position::see_sign(Move m) const {
1378 assert(move_is_ok(m));
1380 Square from = move_from(m);
1381 Square to = move_to(m);
1383 // Early return if SEE cannot be negative because captured piece value
1384 // is not less then capturing one. Note that king moves always return
1385 // here because king midgame value is set to 0.
1386 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1389 return see(from, to);
1392 int Position::see(Square from, Square to) const {
1394 Bitboard occ, attackers, stmAttackers, b;
1395 int swapList[32], slIndex = 1;
1396 PieceType capturedType, pt;
1399 assert(square_is_ok(from));
1400 assert(square_is_ok(to));
1402 capturedType = type_of_piece_on(to);
1404 // King cannot be recaptured
1405 if (capturedType == KING)
1406 return seeValues[capturedType];
1408 occ = occupied_squares();
1410 // Handle en passant moves
1411 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1413 Square capQq = (side_to_move() == WHITE) ? (to - DELTA_N) : (to - DELTA_S);
1415 assert(capturedType == PIECE_TYPE_NONE);
1416 assert(type_of_piece_on(capQq) == PAWN);
1418 // Remove the captured pawn
1419 clear_bit(&occ, capQq);
1420 capturedType = PAWN;
1423 // Find all attackers to the destination square, with the moving piece
1424 // removed, but possibly an X-ray attacker added behind it.
1425 clear_bit(&occ, from);
1426 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1427 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1428 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1429 | (attacks_from<KING>(to) & pieces(KING))
1430 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1431 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1433 // If the opponent has no attackers we are finished
1434 stm = opposite_color(color_of_piece_on(from));
1435 stmAttackers = attackers & pieces_of_color(stm);
1437 return seeValues[capturedType];
1439 // The destination square is defended, which makes things rather more
1440 // difficult to compute. We proceed by building up a "swap list" containing
1441 // the material gain or loss at each stop in a sequence of captures to the
1442 // destination square, where the sides alternately capture, and always
1443 // capture with the least valuable piece. After each capture, we look for
1444 // new X-ray attacks from behind the capturing piece.
1445 swapList[0] = seeValues[capturedType];
1446 capturedType = type_of_piece_on(from);
1449 // Locate the least valuable attacker for the side to move. The loop
1450 // below looks like it is potentially infinite, but it isn't. We know
1451 // that the side to move still has at least one attacker left.
1452 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1455 // Remove the attacker we just found from the 'attackers' bitboard,
1456 // and scan for new X-ray attacks behind the attacker.
1457 b = stmAttackers & pieces(pt);
1458 occ ^= (b & (~b + 1));
1459 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1460 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1462 attackers &= occ; // Cut out pieces we've already done
1464 // Add the new entry to the swap list
1465 assert(slIndex < 32);
1466 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1469 // Remember the value of the capturing piece, and change the side to move
1470 // before beginning the next iteration
1472 stm = opposite_color(stm);
1473 stmAttackers = attackers & pieces_of_color(stm);
1475 // Stop after a king capture
1476 if (pt == KING && stmAttackers)
1478 assert(slIndex < 32);
1479 swapList[slIndex++] = QueenValueMidgame*10;
1482 } while (stmAttackers);
1484 // Having built the swap list, we negamax through it to find the best
1485 // achievable score from the point of view of the side to move
1487 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1493 /// Position::clear() erases the position object to a pristine state, with an
1494 /// empty board, white to move, and no castling rights.
1496 void Position::clear() {
1499 memset(st, 0, sizeof(StateInfo));
1500 st->epSquare = SQ_NONE;
1501 startPosPlyCounter = 0;
1504 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1505 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1506 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1507 memset(index, 0, sizeof(int) * 64);
1509 for (int i = 0; i < 64; i++)
1510 board[i] = PIECE_NONE;
1512 for (int i = 0; i < 8; i++)
1513 for (int j = 0; j < 16; j++)
1514 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1516 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1517 castleRightsMask[sq] = ALL_CASTLES;
1520 initialKFile = FILE_E;
1521 initialKRFile = FILE_H;
1522 initialQRFile = FILE_A;
1526 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1527 /// UCI interface code, whenever a non-reversible move is made in a
1528 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1529 /// for the program to handle games of arbitrary length, as long as the GUI
1530 /// handles draws by the 50 move rule correctly.
1532 void Position::reset_game_ply() {
1537 void Position::inc_startpos_ply_counter() {
1539 startPosPlyCounter++;
1542 /// Position::put_piece() puts a piece on the given square of the board,
1543 /// updating the board array, bitboards, and piece counts.
1545 void Position::put_piece(Piece p, Square s) {
1547 Color c = color_of_piece(p);
1548 PieceType pt = type_of_piece(p);
1551 index[s] = pieceCount[c][pt];
1552 pieceList[c][pt][index[s]] = s;
1554 set_bit(&(byTypeBB[pt]), s);
1555 set_bit(&(byColorBB[c]), s);
1556 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1558 pieceCount[c][pt]++;
1562 /// Position::allow_oo() gives the given side the right to castle kingside.
1563 /// Used when setting castling rights during parsing of FEN strings.
1565 void Position::allow_oo(Color c) {
1567 st->castleRights |= (1 + int(c));
1571 /// Position::allow_ooo() gives the given side the right to castle queenside.
1572 /// Used when setting castling rights during parsing of FEN strings.
1574 void Position::allow_ooo(Color c) {
1576 st->castleRights |= (4 + 4*int(c));
1580 /// Position::compute_key() computes the hash key of the position. The hash
1581 /// key is usually updated incrementally as moves are made and unmade, the
1582 /// compute_key() function is only used when a new position is set up, and
1583 /// to verify the correctness of the hash key when running in debug mode.
1585 Key Position::compute_key() const {
1589 for (Square s = SQ_A1; s <= SQ_H8; s++)
1590 if (square_is_occupied(s))
1591 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1593 if (ep_square() != SQ_NONE)
1594 result ^= zobEp[ep_square()];
1596 result ^= zobCastle[st->castleRights];
1597 if (side_to_move() == BLACK)
1598 result ^= zobSideToMove;
1604 /// Position::compute_pawn_key() computes the hash key of the position. The
1605 /// hash key is usually updated incrementally as moves are made and unmade,
1606 /// the compute_pawn_key() function is only used when a new position is set
1607 /// up, and to verify the correctness of the pawn hash key when running in
1610 Key Position::compute_pawn_key() const {
1616 for (Color c = WHITE; c <= BLACK; c++)
1618 b = pieces(PAWN, c);
1621 s = pop_1st_bit(&b);
1622 result ^= zobrist[c][PAWN][s];
1629 /// Position::compute_material_key() computes the hash key of the position.
1630 /// The hash key is usually updated incrementally as moves are made and unmade,
1631 /// the compute_material_key() function is only used when a new position is set
1632 /// up, and to verify the correctness of the material hash key when running in
1635 Key Position::compute_material_key() const {
1638 for (Color c = WHITE; c <= BLACK; c++)
1639 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1641 int count = piece_count(c, pt);
1642 for (int i = 0; i < count; i++)
1643 result ^= zobrist[c][pt][i];
1649 /// Position::compute_value() compute the incremental scores for the middle
1650 /// game and the endgame. These functions are used to initialize the incremental
1651 /// scores when a new position is set up, and to verify that the scores are correctly
1652 /// updated by do_move and undo_move when the program is running in debug mode.
1653 Score Position::compute_value() const {
1655 Score result = SCORE_ZERO;
1659 for (Color c = WHITE; c <= BLACK; c++)
1660 for (PieceType pt = PAWN; pt <= KING; pt++)
1665 s = pop_1st_bit(&b);
1666 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1667 result += pst(c, pt, s);
1671 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1676 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1677 /// game material score for the given side. Material scores are updated
1678 /// incrementally during the search, this function is only used while
1679 /// initializing a new Position object.
1681 Value Position::compute_non_pawn_material(Color c) const {
1683 Value result = VALUE_ZERO;
1685 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1687 Bitboard b = pieces(pt, c);
1690 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1693 result += PieceValueMidgame[pt];
1700 /// Position::is_draw() tests whether the position is drawn by material,
1701 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1702 /// must be done by the search.
1704 bool Position::is_draw() const {
1706 // Draw by material?
1708 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1711 // Draw by the 50 moves rule?
1712 if (st->rule50 > 99 && (st->rule50 > 100 || !is_mate()))
1715 // Draw by repetition?
1716 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1717 if (history[st->gamePly - i] == st->key)
1724 /// Position::is_mate() returns true or false depending on whether the
1725 /// side to move is checkmated.
1727 bool Position::is_mate() const {
1729 MoveStack moves[MOVES_MAX];
1730 return is_check() && (generate_moves(*this, moves) == moves);
1734 /// Position::has_mate_threat() tests whether the side to move is under
1735 /// a threat of being mated in one from the current position.
1737 bool Position::has_mate_threat() {
1739 MoveStack mlist[MOVES_MAX], *last, *cur;
1741 bool mateFound = false;
1743 // If we are under check it's up to evasions to do the job
1747 // First pass the move to our opponent doing a null move
1750 // Then generate pseudo-legal moves that give check
1751 last = generate_non_capture_checks(*this, mlist);
1752 last = generate_captures(*this, last);
1754 // Loop through the moves, and see if one of them gives mate
1755 Bitboard pinned = pinned_pieces(sideToMove);
1756 CheckInfo ci(*this);
1757 for (cur = mlist; cur != last && !mateFound; cur++)
1759 Move move = cur->move;
1760 if ( !pl_move_is_legal(move, pinned)
1761 || !move_is_check(move, ci))
1764 do_move(move, st2, ci, true);
1777 /// Position::init_zobrist() is a static member function which initializes at
1778 /// startup the various arrays used to compute hash keys.
1780 void Position::init_zobrist() {
1785 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1786 zobrist[i][j][k] = RKiss.rand<Key>();
1788 for (i = 0; i < 64; i++)
1789 zobEp[i] = RKiss.rand<Key>();
1791 for (i = 0; i < 16; i++)
1792 zobCastle[i] = RKiss.rand<Key>();
1794 zobSideToMove = RKiss.rand<Key>();
1795 zobExclusion = RKiss.rand<Key>();
1799 /// Position::init_piece_square_tables() initializes the piece square tables.
1800 /// This is a two-step operation: First, the white halves of the tables are
1801 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1802 /// of the tables are initialized by mirroring and changing the sign of the
1803 /// corresponding white scores.
1805 void Position::init_piece_square_tables() {
1807 for (Square s = SQ_A1; s <= SQ_H8; s++)
1808 for (Piece p = WP; p <= WK; p++)
1809 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1811 for (Square s = SQ_A1; s <= SQ_H8; s++)
1812 for (Piece p = BP; p <= BK; p++)
1813 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1817 /// Position::flipped_copy() makes a copy of the input position, but with
1818 /// the white and black sides reversed. This is only useful for debugging,
1819 /// especially for finding evaluation symmetry bugs.
1821 void Position::flipped_copy(const Position& pos) {
1823 assert(pos.is_ok());
1826 threadID = pos.thread();
1829 for (Square s = SQ_A1; s <= SQ_H8; s++)
1830 if (!pos.square_is_empty(s))
1831 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1834 sideToMove = opposite_color(pos.side_to_move());
1837 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1838 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1839 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1840 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1842 initialKFile = pos.initialKFile;
1843 initialKRFile = pos.initialKRFile;
1844 initialQRFile = pos.initialQRFile;
1846 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1847 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1848 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1849 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1850 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1851 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1853 // En passant square
1854 if (pos.st->epSquare != SQ_NONE)
1855 st->epSquare = flip_square(pos.st->epSquare);
1861 st->key = compute_key();
1862 st->pawnKey = compute_pawn_key();
1863 st->materialKey = compute_material_key();
1865 // Incremental scores
1866 st->value = compute_value();
1869 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1870 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1876 /// Position::is_ok() performs some consitency checks for the position object.
1877 /// This is meant to be helpful when debugging.
1879 bool Position::is_ok(int* failedStep) const {
1881 // What features of the position should be verified?
1882 static const bool debugBitboards = false;
1883 static const bool debugKingCount = false;
1884 static const bool debugKingCapture = false;
1885 static const bool debugCheckerCount = false;
1886 static const bool debugKey = false;
1887 static const bool debugMaterialKey = false;
1888 static const bool debugPawnKey = false;
1889 static const bool debugIncrementalEval = false;
1890 static const bool debugNonPawnMaterial = false;
1891 static const bool debugPieceCounts = false;
1892 static const bool debugPieceList = false;
1893 static const bool debugCastleSquares = false;
1895 if (failedStep) *failedStep = 1;
1898 if (!color_is_ok(side_to_move()))
1901 // Are the king squares in the position correct?
1902 if (failedStep) (*failedStep)++;
1903 if (piece_on(king_square(WHITE)) != WK)
1906 if (failedStep) (*failedStep)++;
1907 if (piece_on(king_square(BLACK)) != BK)
1911 if (failedStep) (*failedStep)++;
1912 if (!file_is_ok(initialKRFile))
1915 if (!file_is_ok(initialQRFile))
1918 // Do both sides have exactly one king?
1919 if (failedStep) (*failedStep)++;
1922 int kingCount[2] = {0, 0};
1923 for (Square s = SQ_A1; s <= SQ_H8; s++)
1924 if (type_of_piece_on(s) == KING)
1925 kingCount[color_of_piece_on(s)]++;
1927 if (kingCount[0] != 1 || kingCount[1] != 1)
1931 // Can the side to move capture the opponent's king?
1932 if (failedStep) (*failedStep)++;
1933 if (debugKingCapture)
1935 Color us = side_to_move();
1936 Color them = opposite_color(us);
1937 Square ksq = king_square(them);
1938 if (attackers_to(ksq) & pieces_of_color(us))
1942 // Is there more than 2 checkers?
1943 if (failedStep) (*failedStep)++;
1944 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1948 if (failedStep) (*failedStep)++;
1951 // The intersection of the white and black pieces must be empty
1952 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1955 // The union of the white and black pieces must be equal to all
1957 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1960 // Separate piece type bitboards must have empty intersections
1961 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1962 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1963 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1967 // En passant square OK?
1968 if (failedStep) (*failedStep)++;
1969 if (ep_square() != SQ_NONE)
1971 // The en passant square must be on rank 6, from the point of view of the
1973 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1978 if (failedStep) (*failedStep)++;
1979 if (debugKey && st->key != compute_key())
1982 // Pawn hash key OK?
1983 if (failedStep) (*failedStep)++;
1984 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1987 // Material hash key OK?
1988 if (failedStep) (*failedStep)++;
1989 if (debugMaterialKey && st->materialKey != compute_material_key())
1992 // Incremental eval OK?
1993 if (failedStep) (*failedStep)++;
1994 if (debugIncrementalEval && st->value != compute_value())
1997 // Non-pawn material OK?
1998 if (failedStep) (*failedStep)++;
1999 if (debugNonPawnMaterial)
2001 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2004 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2009 if (failedStep) (*failedStep)++;
2010 if (debugPieceCounts)
2011 for (Color c = WHITE; c <= BLACK; c++)
2012 for (PieceType pt = PAWN; pt <= KING; pt++)
2013 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2016 if (failedStep) (*failedStep)++;
2019 for (Color c = WHITE; c <= BLACK; c++)
2020 for (PieceType pt = PAWN; pt <= KING; pt++)
2021 for (int i = 0; i < pieceCount[c][pt]; i++)
2023 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2026 if (index[piece_list(c, pt, i)] != i)
2031 if (failedStep) (*failedStep)++;
2032 if (debugCastleSquares) {
2033 for (Color c = WHITE; c <= BLACK; c++) {
2034 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2036 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2039 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2041 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2043 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2045 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2049 if (failedStep) *failedStep = 0;