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"
46 struct PieceLetters : std::map<char, Piece> {
50 operator[]('K') = WK; operator[]('k') = BK;
51 operator[]('Q') = WQ; operator[]('q') = BQ;
52 operator[]('R') = WR; operator[]('r') = BR;
53 operator[]('B') = WB; operator[]('b') = BB;
54 operator[]('N') = WN; operator[]('n') = BN;
55 operator[]('P') = WP; operator[]('p') = BP;
63 Key Position::zobrist[2][8][64];
64 Key Position::zobEp[64];
65 Key Position::zobCastle[16];
66 Key Position::zobSideToMove;
67 Key Position::zobExclusion;
69 Score Position::PieceSquareTable[16][64];
71 static bool RequestPending = false;
76 CheckInfo::CheckInfo(const Position& pos) {
78 Color us = pos.side_to_move();
79 Color them = opposite_color(us);
81 ksq = pos.king_square(them);
82 dcCandidates = pos.discovered_check_candidates(us);
84 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
85 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
86 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
87 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
88 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
89 checkSq[KING] = EmptyBoardBB;
93 /// Position c'tors. Here we always create a copy of the original position
94 /// or the FEN string, we want the new born Position object do not depend
95 /// on any external data so we detach state pointer from the source one.
97 Position::Position(int th) : threadID(th) {}
99 Position::Position(const Position& pos, int th) {
101 memcpy(this, &pos, sizeof(Position));
102 detach(); // Always detach() in copy c'tor to avoid surprises
106 Position::Position(const string& fen, int th) {
113 /// Position::detach() copies the content of the current state and castling
114 /// masks inside the position itself. This is needed when the st pointee could
115 /// become stale, as example because the caller is about to going out of scope.
117 void Position::detach() {
121 st->previous = NULL; // as a safe guard
125 /// Position::from_fen() initializes the position object with the given FEN
126 /// string. This function is not very robust - make sure that input FENs are
127 /// correct (this is assumed to be the responsibility of the GUI).
129 void Position::from_fen(const string& fen) {
131 A FEN string defines a particular position using only the ASCII character set.
133 A FEN string contains six fields. The separator between fields is a space. The fields are:
135 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
136 with rank 1; within each rank, the contents of each square are described from file a through file h.
137 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
138 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
139 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
140 of blank squares), and "/" separate ranks.
142 2) Active color. "w" means white moves next, "b" means black.
144 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
145 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
146 kingside), and/or "q" (Black can castle queenside).
148 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
149 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
150 regardless of whether there is a pawn in position to make an en passant capture.
152 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
153 to determine if a draw can be claimed under the fifty-move rule.
155 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
158 static PieceLetters pieceLetters;
161 std::istringstream ss(fen);
167 // 1. Piece placement field
168 while (ss.get(token) && token != ' ')
172 file += token - '0'; // Skip the given number of files
175 else if (token == '/')
182 if (pieceLetters.find(token) == pieceLetters.end())
185 put_piece(pieceLetters[token], make_square(file, rank));
190 if (!ss.get(token) || (token != 'w' && token != 'b'))
193 sideToMove = (token == 'w' ? WHITE : BLACK);
195 if (!ss.get(token) || token != ' ')
198 // 3. Castling availability
199 while (ss.get(token) && token != ' ')
204 if (!set_castling_rights(token))
208 // 4. En passant square -- ignore if no capture is possible
210 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
211 && (ss.get(row) && (row == '3' || row == '6')))
213 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
214 Color them = opposite_color(sideToMove);
216 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
217 st->epSquare = fenEpSquare;
220 // 5-6. Halfmove clock and fullmove number are not parsed
222 // Various initialisations
223 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
224 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
225 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
226 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
227 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
228 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
232 st->key = compute_key();
233 st->pawnKey = compute_pawn_key();
234 st->materialKey = compute_material_key();
235 st->value = compute_value();
236 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
237 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
241 cout << "Error in FEN string: " << fen << endl;
245 /// Position::set_castling_rights() sets castling parameters castling avaiability.
246 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
247 /// that uses the letters of the columns on which the rooks began the game instead
248 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
249 /// associated with the castling right, the traditional castling tag will be replaced
250 /// by the file letter of the involved rook as for the Shredder-FEN.
252 bool Position::set_castling_rights(char token) {
254 Color c = token >= 'a' ? BLACK : WHITE;
255 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
256 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
257 Piece rook = (c == WHITE ? WR : BR);
259 initialKFile = square_file(king_square(c));
260 token = char(toupper(token));
264 for (Square sq = sqH; sq >= sqA; sq--)
265 if (piece_on(sq) == rook)
268 initialKRFile = square_file(sq);
272 else if (token == 'Q')
274 for (Square sq = sqA; sq <= sqH; sq++)
275 if (piece_on(sq) == rook)
278 initialQRFile = square_file(sq);
282 else if (token >= 'A' && token <= 'H')
284 File rookFile = File(token - 'A') + FILE_A;
285 if (rookFile < initialKFile)
288 initialQRFile = rookFile;
293 initialKRFile = rookFile;
302 /// Position::to_fen() converts the position object to a FEN string. This is
303 /// probably only useful for debugging.
305 const string Position::to_fen() const {
307 static const string pieceLetters = " PNBRQK pnbrqk";
311 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
314 for (File file = FILE_A; file <= FILE_H; file++)
316 Square sq = make_square(file, rank);
317 if (!square_is_occupied(sq))
323 fen += (char)skip + '0';
326 fen += pieceLetters[piece_on(sq)];
329 fen += (char)skip + '0';
331 fen += (rank > RANK_1 ? '/' : ' ');
333 fen += (sideToMove == WHITE ? "w " : "b ");
334 if (st->castleRights != NO_CASTLES)
336 if (initialKFile == FILE_E && initialQRFile == FILE_A && initialKRFile == FILE_H)
338 if (can_castle_kingside(WHITE)) fen += 'K';
339 if (can_castle_queenside(WHITE)) fen += 'Q';
340 if (can_castle_kingside(BLACK)) fen += 'k';
341 if (can_castle_queenside(BLACK)) fen += 'q';
345 if (can_castle_kingside(WHITE))
346 fen += char(toupper(file_to_char(initialKRFile)));
347 if (can_castle_queenside(WHITE))
348 fen += char(toupper(file_to_char(initialQRFile)));
349 if (can_castle_kingside(BLACK))
350 fen += file_to_char(initialKRFile);
351 if (can_castle_queenside(BLACK))
352 fen += file_to_char(initialQRFile);
358 if (ep_square() != SQ_NONE)
359 fen += square_to_string(ep_square());
367 /// Position::print() prints an ASCII representation of the position to
368 /// the standard output. If a move is given then also the san is print.
370 void Position::print(Move m) const {
372 static const string pieceLetters = " PNBRQK PNBRQK .";
374 // Check for reentrancy, as example when called from inside
375 // MovePicker that is used also here in move_to_san()
379 RequestPending = true;
384 Position p(*this, thread());
385 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
386 cout << "Move is: " << col << move_to_san(p, m) << endl;
388 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
390 cout << "+---+---+---+---+---+---+---+---+" << endl;
391 for (File file = FILE_A; file <= FILE_H; file++)
393 Square sq = make_square(file, rank);
394 Piece piece = piece_on(sq);
395 if (piece == EMPTY && square_color(sq) == WHITE)
398 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
399 cout << '|' << col << pieceLetters[piece] << col;
403 cout << "+---+---+---+---+---+---+---+---+" << endl
404 << "Fen is: " << to_fen() << endl
405 << "Key is: " << st->key << endl;
407 RequestPending = false;
411 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
412 /// king) pieces for the given color and for the given pinner type. Or, when
413 /// template parameter FindPinned is false, the pieces of the given color
414 /// candidate for a discovery check against the enemy king.
415 /// Bitboard checkersBB must be already updated when looking for pinners.
417 template<bool FindPinned>
418 Bitboard Position::hidden_checkers(Color c) const {
420 Bitboard result = EmptyBoardBB;
421 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
423 // Pinned pieces protect our king, dicovery checks attack
425 Square ksq = king_square(FindPinned ? c : opposite_color(c));
427 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
428 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
430 if (FindPinned && pinners)
431 pinners &= ~st->checkersBB;
435 Square s = pop_1st_bit(&pinners);
436 Bitboard b = squares_between(s, ksq) & occupied_squares();
440 if ( !(b & (b - 1)) // Only one bit set?
441 && (b & pieces_of_color(c))) // Is an our piece?
448 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
449 /// king) pieces for the given color. Note that checkersBB bitboard must
450 /// be already updated.
452 Bitboard Position::pinned_pieces(Color c) const {
454 return hidden_checkers<true>(c);
458 /// Position:discovered_check_candidates() returns a bitboard containing all
459 /// pieces for the given side which are candidates for giving a discovered
460 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
461 /// to be already updated.
463 Bitboard Position::discovered_check_candidates(Color c) const {
465 return hidden_checkers<false>(c);
468 /// Position::attackers_to() computes a bitboard containing all pieces which
469 /// attacks a given square.
471 Bitboard Position::attackers_to(Square s) const {
473 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
474 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
475 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
476 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
477 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
478 | (attacks_from<KING>(s) & pieces(KING));
481 /// Position::attacks_from() computes a bitboard of all attacks
482 /// of a given piece put in a given square.
484 Bitboard Position::attacks_from(Piece p, Square s) const {
486 assert(square_is_ok(s));
490 case WP: return attacks_from<PAWN>(s, WHITE);
491 case BP: return attacks_from<PAWN>(s, BLACK);
492 case WN: case BN: return attacks_from<KNIGHT>(s);
493 case WB: case BB: return attacks_from<BISHOP>(s);
494 case WR: case BR: return attacks_from<ROOK>(s);
495 case WQ: case BQ: return attacks_from<QUEEN>(s);
496 case WK: case BK: return attacks_from<KING>(s);
503 /// Position::move_attacks_square() tests whether a move from the current
504 /// position attacks a given square.
506 bool Position::move_attacks_square(Move m, Square s) const {
508 assert(move_is_ok(m));
509 assert(square_is_ok(s));
511 Square f = move_from(m), t = move_to(m);
513 assert(square_is_occupied(f));
515 if (bit_is_set(attacks_from(piece_on(f), t), s))
518 // Move the piece and scan for X-ray attacks behind it
519 Bitboard occ = occupied_squares();
520 Color us = color_of_piece_on(f);
523 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
524 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
526 // If we have attacks we need to verify that are caused by our move
527 // and are not already existent ones.
528 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
532 /// Position::find_checkers() computes the checkersBB bitboard, which
533 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
534 /// currently works by calling Position::attackers_to, which is probably
535 /// inefficient. Consider rewriting this function to use the last move
536 /// played, like in non-bitboard versions of Glaurung.
538 void Position::find_checkers() {
540 Color us = side_to_move();
541 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
545 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
547 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
550 assert(move_is_ok(m));
551 assert(pinned == pinned_pieces(side_to_move()));
553 // Castling moves are checked for legality during move generation.
554 if (move_is_castle(m))
557 Color us = side_to_move();
558 Square from = move_from(m);
560 assert(color_of_piece_on(from) == us);
561 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
563 // En passant captures are a tricky special case. Because they are
564 // rather uncommon, we do it simply by testing whether the king is attacked
565 // after the move is made
568 Color them = opposite_color(us);
569 Square to = move_to(m);
570 Square capsq = make_square(square_file(to), square_rank(from));
571 Bitboard b = occupied_squares();
572 Square ksq = king_square(us);
574 assert(to == ep_square());
575 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
576 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
577 assert(piece_on(to) == EMPTY);
580 clear_bit(&b, capsq);
583 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
584 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
587 // If the moving piece is a king, check whether the destination
588 // square is attacked by the opponent.
589 if (type_of_piece_on(from) == KING)
590 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
592 // A non-king move is legal if and only if it is not pinned or it
593 // is moving along the ray towards or away from the king.
595 || !bit_is_set(pinned, from)
596 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
600 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
602 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
606 Color us = side_to_move();
607 Square from = move_from(m);
608 Square to = move_to(m);
610 // King moves and en-passant captures are verified in pl_move_is_legal()
611 if (type_of_piece_on(from) == KING || move_is_ep(m))
612 return pl_move_is_legal(m, pinned);
614 Bitboard target = checkers();
615 Square checksq = pop_1st_bit(&target);
617 if (target) // double check ?
620 // Our move must be a blocking evasion or a capture of the checking piece
621 target = squares_between(checksq, king_square(us)) | checkers();
622 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
626 /// Position::move_is_check() tests whether a pseudo-legal move is a check
628 bool Position::move_is_check(Move m) const {
630 return move_is_check(m, CheckInfo(*this));
633 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
636 assert(move_is_ok(m));
637 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
638 assert(color_of_piece_on(move_from(m)) == side_to_move());
639 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
641 Square from = move_from(m);
642 Square to = move_to(m);
643 PieceType pt = type_of_piece_on(from);
646 if (bit_is_set(ci.checkSq[pt], to))
650 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
652 // For pawn and king moves we need to verify also direction
653 if ( (pt != PAWN && pt != KING)
654 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
658 // Can we skip the ugly special cases ?
659 if (!move_is_special(m))
662 Color us = side_to_move();
663 Bitboard b = occupied_squares();
665 // Promotion with check ?
666 if (move_is_promotion(m))
670 switch (move_promotion_piece(m))
673 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
675 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
677 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
679 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
685 // En passant capture with check ? We have already handled the case
686 // of direct checks and ordinary discovered check, the only case we
687 // need to handle is the unusual case of a discovered check through
688 // the captured pawn.
691 Square capsq = make_square(square_file(to), square_rank(from));
693 clear_bit(&b, capsq);
695 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
696 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
699 // Castling with check ?
700 if (move_is_castle(m))
702 Square kfrom, kto, rfrom, rto;
708 kto = relative_square(us, SQ_G1);
709 rto = relative_square(us, SQ_F1);
711 kto = relative_square(us, SQ_C1);
712 rto = relative_square(us, SQ_D1);
714 clear_bit(&b, kfrom);
715 clear_bit(&b, rfrom);
718 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
725 /// Position::do_move() makes a move, and saves all information necessary
726 /// to a StateInfo object. The move is assumed to be legal.
727 /// Pseudo-legal moves should be filtered out before this function is called.
729 void Position::do_move(Move m, StateInfo& newSt) {
732 do_move(m, newSt, ci, move_is_check(m, ci));
735 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
738 assert(move_is_ok(m));
742 // Copy some fields of old state to our new StateInfo object except the
743 // ones which are recalculated from scratch anyway, then switch our state
744 // pointer to point to the new, ready to be updated, state.
745 struct ReducedStateInfo {
746 Key pawnKey, materialKey;
747 int castleRights, rule50, gamePly, pliesFromNull;
753 memcpy(&newSt, st, sizeof(ReducedStateInfo));
757 // Save the current key to the history[] array, in order to be able to
758 // detect repetition draws.
759 history[st->gamePly++] = key;
761 // Update side to move
762 key ^= zobSideToMove;
764 // Increment the 50 moves rule draw counter. Resetting it to zero in the
765 // case of non-reversible moves is taken care of later.
769 if (move_is_castle(m))
776 Color us = side_to_move();
777 Color them = opposite_color(us);
778 Square from = move_from(m);
779 Square to = move_to(m);
780 bool ep = move_is_ep(m);
781 bool pm = move_is_promotion(m);
783 Piece piece = piece_on(from);
784 PieceType pt = type_of_piece(piece);
785 PieceType capture = ep ? PAWN : type_of_piece_on(to);
787 assert(color_of_piece_on(from) == us);
788 assert(color_of_piece_on(to) == them || square_is_empty(to));
789 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
790 assert(!pm || relative_rank(us, to) == RANK_8);
793 do_capture_move(key, capture, them, to, ep);
796 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
798 // Reset en passant square
799 if (st->epSquare != SQ_NONE)
801 key ^= zobEp[st->epSquare];
802 st->epSquare = SQ_NONE;
805 // Update castle rights, try to shortcut a common case
806 int cm = castleRightsMask[from] & castleRightsMask[to];
807 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
809 key ^= zobCastle[st->castleRights];
810 st->castleRights &= castleRightsMask[from];
811 st->castleRights &= castleRightsMask[to];
812 key ^= zobCastle[st->castleRights];
815 // Prefetch TT access as soon as we know key is updated
816 prefetch((char*)TT.first_entry(key));
819 Bitboard move_bb = make_move_bb(from, to);
820 do_move_bb(&(byColorBB[us]), move_bb);
821 do_move_bb(&(byTypeBB[pt]), move_bb);
822 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
824 board[to] = board[from];
827 // Update piece lists, note that index[from] is not updated and
828 // becomes stale. This works as long as index[] is accessed just
829 // by known occupied squares.
830 index[to] = index[from];
831 pieceList[us][pt][index[to]] = to;
833 // If the moving piece was a pawn do some special extra work
836 // Reset rule 50 draw counter
839 // Update pawn hash key
840 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
842 // Set en passant square, only if moved pawn can be captured
843 if ((to ^ from) == 16)
845 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
847 st->epSquare = Square((int(from) + int(to)) / 2);
848 key ^= zobEp[st->epSquare];
852 if (pm) // promotion ?
854 PieceType promotion = move_promotion_piece(m);
856 assert(promotion >= KNIGHT && promotion <= QUEEN);
858 // Insert promoted piece instead of pawn
859 clear_bit(&(byTypeBB[PAWN]), to);
860 set_bit(&(byTypeBB[promotion]), to);
861 board[to] = piece_of_color_and_type(us, promotion);
863 // Update piece counts
864 pieceCount[us][promotion]++;
865 pieceCount[us][PAWN]--;
867 // Update material key
868 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
869 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
871 // Update piece lists, move the last pawn at index[to] position
872 // and shrink the list. Add a new promotion piece to the list.
873 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
874 index[lastPawnSquare] = index[to];
875 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
876 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
877 index[to] = pieceCount[us][promotion] - 1;
878 pieceList[us][promotion][index[to]] = to;
880 // Partially revert hash keys update
881 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
882 st->pawnKey ^= zobrist[us][PAWN][to];
884 // Partially revert and update incremental scores
885 st->value -= pst(us, PAWN, to);
886 st->value += pst(us, promotion, to);
889 st->npMaterial[us] += piece_value_midgame(promotion);
893 // Update incremental scores
894 st->value += pst_delta(piece, from, to);
897 st->capture = capture;
899 // Update the key with the final value
902 // Update checkers bitboard, piece must be already moved
903 st->checkersBB = EmptyBoardBB;
908 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
912 if (bit_is_set(ci.checkSq[pt], to))
913 st->checkersBB = SetMaskBB[to];
916 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
919 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
922 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
928 sideToMove = opposite_color(sideToMove);
929 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
935 /// Position::do_capture_move() is a private method used to update captured
936 /// piece info. It is called from the main Position::do_move function.
938 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
940 assert(capture != KING);
944 // If the captured piece was a pawn, update pawn hash key,
945 // otherwise update non-pawn material.
948 if (ep) // en passant ?
950 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
952 assert(to == st->epSquare);
953 assert(relative_rank(opposite_color(them), to) == RANK_6);
954 assert(piece_on(to) == EMPTY);
955 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
957 board[capsq] = EMPTY;
959 st->pawnKey ^= zobrist[them][PAWN][capsq];
962 st->npMaterial[them] -= piece_value_midgame(capture);
964 // Remove captured piece
965 clear_bit(&(byColorBB[them]), capsq);
966 clear_bit(&(byTypeBB[capture]), capsq);
967 clear_bit(&(byTypeBB[0]), capsq);
970 key ^= zobrist[them][capture][capsq];
972 // Update incremental scores
973 st->value -= pst(them, capture, capsq);
975 // Update piece count
976 pieceCount[them][capture]--;
978 // Update material hash key
979 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
981 // Update piece list, move the last piece at index[capsq] position
983 // WARNING: This is a not perfectly revresible operation. When we
984 // will reinsert the captured piece in undo_move() we will put it
985 // at the end of the list and not in its original place, it means
986 // index[] and pieceList[] are not guaranteed to be invariant to a
987 // do_move() + undo_move() sequence.
988 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
989 index[lastPieceSquare] = index[capsq];
990 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
991 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
993 // Reset rule 50 counter
998 /// Position::do_castle_move() is a private method used to make a castling
999 /// move. It is called from the main Position::do_move function. Note that
1000 /// castling moves are encoded as "king captures friendly rook" moves, for
1001 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1003 void Position::do_castle_move(Move m) {
1005 assert(move_is_ok(m));
1006 assert(move_is_castle(m));
1008 Color us = side_to_move();
1009 Color them = opposite_color(us);
1011 // Reset capture field
1012 st->capture = NO_PIECE_TYPE;
1014 // Find source squares for king and rook
1015 Square kfrom = move_from(m);
1016 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1019 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1020 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1022 // Find destination squares for king and rook
1023 if (rfrom > kfrom) // O-O
1025 kto = relative_square(us, SQ_G1);
1026 rto = relative_square(us, SQ_F1);
1028 kto = relative_square(us, SQ_C1);
1029 rto = relative_square(us, SQ_D1);
1032 // Remove pieces from source squares:
1033 clear_bit(&(byColorBB[us]), kfrom);
1034 clear_bit(&(byTypeBB[KING]), kfrom);
1035 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1036 clear_bit(&(byColorBB[us]), rfrom);
1037 clear_bit(&(byTypeBB[ROOK]), rfrom);
1038 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1040 // Put pieces on destination squares:
1041 set_bit(&(byColorBB[us]), kto);
1042 set_bit(&(byTypeBB[KING]), kto);
1043 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1044 set_bit(&(byColorBB[us]), rto);
1045 set_bit(&(byTypeBB[ROOK]), rto);
1046 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1048 // Update board array
1049 Piece king = piece_of_color_and_type(us, KING);
1050 Piece rook = piece_of_color_and_type(us, ROOK);
1051 board[kfrom] = board[rfrom] = EMPTY;
1055 // Update piece lists
1056 pieceList[us][KING][index[kfrom]] = kto;
1057 pieceList[us][ROOK][index[rfrom]] = rto;
1058 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1059 index[kto] = index[kfrom];
1062 // Update incremental scores
1063 st->value += pst_delta(king, kfrom, kto);
1064 st->value += pst_delta(rook, rfrom, rto);
1067 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1068 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1070 // Clear en passant square
1071 if (st->epSquare != SQ_NONE)
1073 st->key ^= zobEp[st->epSquare];
1074 st->epSquare = SQ_NONE;
1077 // Update castling rights
1078 st->key ^= zobCastle[st->castleRights];
1079 st->castleRights &= castleRightsMask[kfrom];
1080 st->key ^= zobCastle[st->castleRights];
1082 // Reset rule 50 counter
1085 // Update checkers BB
1086 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1089 sideToMove = opposite_color(sideToMove);
1090 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1096 /// Position::undo_move() unmakes a move. When it returns, the position should
1097 /// be restored to exactly the same state as before the move was made.
1099 void Position::undo_move(Move m) {
1102 assert(move_is_ok(m));
1104 sideToMove = opposite_color(sideToMove);
1106 if (move_is_castle(m))
1108 undo_castle_move(m);
1112 Color us = side_to_move();
1113 Color them = opposite_color(us);
1114 Square from = move_from(m);
1115 Square to = move_to(m);
1116 bool ep = move_is_ep(m);
1117 bool pm = move_is_promotion(m);
1119 PieceType pt = type_of_piece_on(to);
1121 assert(square_is_empty(from));
1122 assert(color_of_piece_on(to) == us);
1123 assert(!pm || relative_rank(us, to) == RANK_8);
1124 assert(!ep || to == st->previous->epSquare);
1125 assert(!ep || relative_rank(us, to) == RANK_6);
1126 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1128 if (pm) // promotion ?
1130 PieceType promotion = move_promotion_piece(m);
1133 assert(promotion >= KNIGHT && promotion <= QUEEN);
1134 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1136 // Replace promoted piece with a pawn
1137 clear_bit(&(byTypeBB[promotion]), to);
1138 set_bit(&(byTypeBB[PAWN]), to);
1140 // Update piece counts
1141 pieceCount[us][promotion]--;
1142 pieceCount[us][PAWN]++;
1144 // Update piece list replacing promotion piece with a pawn
1145 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1146 index[lastPromotionSquare] = index[to];
1147 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1148 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1149 index[to] = pieceCount[us][PAWN] - 1;
1150 pieceList[us][PAWN][index[to]] = to;
1153 // Put the piece back at the source square
1154 Bitboard move_bb = make_move_bb(to, from);
1155 do_move_bb(&(byColorBB[us]), move_bb);
1156 do_move_bb(&(byTypeBB[pt]), move_bb);
1157 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1159 board[from] = piece_of_color_and_type(us, pt);
1162 // Update piece list
1163 index[from] = index[to];
1164 pieceList[us][pt][index[from]] = from;
1171 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1173 assert(st->capture != KING);
1174 assert(!ep || square_is_empty(capsq));
1176 // Restore the captured piece
1177 set_bit(&(byColorBB[them]), capsq);
1178 set_bit(&(byTypeBB[st->capture]), capsq);
1179 set_bit(&(byTypeBB[0]), capsq);
1181 board[capsq] = piece_of_color_and_type(them, st->capture);
1183 // Update piece count
1184 pieceCount[them][st->capture]++;
1186 // Update piece list, add a new captured piece in capsq square
1187 index[capsq] = pieceCount[them][st->capture] - 1;
1188 pieceList[them][st->capture][index[capsq]] = capsq;
1191 // Finally point our state pointer back to the previous state
1198 /// Position::undo_castle_move() is a private method used to unmake a castling
1199 /// move. It is called from the main Position::undo_move function. Note that
1200 /// castling moves are encoded as "king captures friendly rook" moves, for
1201 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1203 void Position::undo_castle_move(Move m) {
1205 assert(move_is_ok(m));
1206 assert(move_is_castle(m));
1208 // When we have arrived here, some work has already been done by
1209 // Position::undo_move. In particular, the side to move has been switched,
1210 // so the code below is correct.
1211 Color us = side_to_move();
1213 // Find source squares for king and rook
1214 Square kfrom = move_from(m);
1215 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1218 // Find destination squares for king and rook
1219 if (rfrom > kfrom) // O-O
1221 kto = relative_square(us, SQ_G1);
1222 rto = relative_square(us, SQ_F1);
1224 kto = relative_square(us, SQ_C1);
1225 rto = relative_square(us, SQ_D1);
1228 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1229 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1231 // Remove pieces from destination squares:
1232 clear_bit(&(byColorBB[us]), kto);
1233 clear_bit(&(byTypeBB[KING]), kto);
1234 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1235 clear_bit(&(byColorBB[us]), rto);
1236 clear_bit(&(byTypeBB[ROOK]), rto);
1237 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1239 // Put pieces on source squares:
1240 set_bit(&(byColorBB[us]), kfrom);
1241 set_bit(&(byTypeBB[KING]), kfrom);
1242 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1243 set_bit(&(byColorBB[us]), rfrom);
1244 set_bit(&(byTypeBB[ROOK]), rfrom);
1245 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1248 board[rto] = board[kto] = EMPTY;
1249 board[rfrom] = piece_of_color_and_type(us, ROOK);
1250 board[kfrom] = piece_of_color_and_type(us, KING);
1252 // Update piece lists
1253 pieceList[us][KING][index[kto]] = kfrom;
1254 pieceList[us][ROOK][index[rto]] = rfrom;
1255 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1256 index[kfrom] = index[kto];
1259 // Finally point our state pointer back to the previous state
1266 /// Position::do_null_move makes() a "null move": It switches the side to move
1267 /// and updates the hash key without executing any move on the board.
1269 void Position::do_null_move(StateInfo& backupSt) {
1272 assert(!is_check());
1274 // Back up the information necessary to undo the null move to the supplied
1275 // StateInfo object.
1276 // Note that differently from normal case here backupSt is actually used as
1277 // a backup storage not as a new state to be used.
1278 backupSt.key = st->key;
1279 backupSt.epSquare = st->epSquare;
1280 backupSt.value = st->value;
1281 backupSt.previous = st->previous;
1282 backupSt.pliesFromNull = st->pliesFromNull;
1283 st->previous = &backupSt;
1285 // Save the current key to the history[] array, in order to be able to
1286 // detect repetition draws.
1287 history[st->gamePly++] = st->key;
1289 // Update the necessary information
1290 if (st->epSquare != SQ_NONE)
1291 st->key ^= zobEp[st->epSquare];
1293 st->key ^= zobSideToMove;
1294 prefetch((char*)TT.first_entry(st->key));
1296 sideToMove = opposite_color(sideToMove);
1297 st->epSquare = SQ_NONE;
1299 st->pliesFromNull = 0;
1300 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1304 /// Position::undo_null_move() unmakes a "null move".
1306 void Position::undo_null_move() {
1309 assert(!is_check());
1311 // Restore information from the our backup StateInfo object
1312 StateInfo* backupSt = st->previous;
1313 st->key = backupSt->key;
1314 st->epSquare = backupSt->epSquare;
1315 st->value = backupSt->value;
1316 st->previous = backupSt->previous;
1317 st->pliesFromNull = backupSt->pliesFromNull;
1319 // Update the necessary information
1320 sideToMove = opposite_color(sideToMove);
1326 /// Position::see() is a static exchange evaluator: It tries to estimate the
1327 /// material gain or loss resulting from a move. There are three versions of
1328 /// this function: One which takes a destination square as input, one takes a
1329 /// move, and one which takes a 'from' and a 'to' square. The function does
1330 /// not yet understand promotions captures.
1332 int Position::see(Square to) const {
1334 assert(square_is_ok(to));
1335 return see(SQ_NONE, to);
1338 int Position::see(Move m) const {
1340 assert(move_is_ok(m));
1341 return see(move_from(m), move_to(m));
1344 int Position::see_sign(Move m) const {
1346 assert(move_is_ok(m));
1348 Square from = move_from(m);
1349 Square to = move_to(m);
1351 // Early return if SEE cannot be negative because captured piece value
1352 // is not less then capturing one. Note that king moves always return
1353 // here because king midgame value is set to 0.
1354 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1357 return see(from, to);
1360 int Position::see(Square from, Square to) const {
1363 static const int seeValues[18] = {
1364 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1365 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1366 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1367 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1371 Bitboard attackers, stmAttackers, b;
1373 assert(square_is_ok(from) || from == SQ_NONE);
1374 assert(square_is_ok(to));
1376 // Initialize colors
1377 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1378 Color them = opposite_color(us);
1380 // Initialize pieces
1381 Piece piece = piece_on(from);
1382 Piece capture = piece_on(to);
1383 Bitboard occ = occupied_squares();
1385 // King cannot be recaptured
1386 if (type_of_piece(piece) == KING)
1387 return seeValues[capture];
1389 // Handle en passant moves
1390 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1392 assert(capture == EMPTY);
1394 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1395 capture = piece_on(capQq);
1396 assert(type_of_piece_on(capQq) == PAWN);
1398 // Remove the captured pawn
1399 clear_bit(&occ, capQq);
1404 // Find all attackers to the destination square, with the moving piece
1405 // removed, but possibly an X-ray attacker added behind it.
1406 clear_bit(&occ, from);
1407 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1408 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1409 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1410 | (attacks_from<KING>(to) & pieces(KING))
1411 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1412 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1414 if (from != SQ_NONE)
1417 // If we don't have any attacker we are finished
1418 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1421 // Locate the least valuable attacker to the destination square
1422 // and use it to initialize from square.
1423 stmAttackers = attackers & pieces_of_color(us);
1425 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1428 from = first_1(stmAttackers & pieces(pt));
1429 piece = piece_on(from);
1432 // If the opponent has no attackers we are finished
1433 stmAttackers = attackers & pieces_of_color(them);
1435 return seeValues[capture];
1437 attackers &= occ; // Remove the moving piece
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 int lastCapturingPieceValue = seeValues[piece];
1446 int swapList[32], n = 1;
1450 swapList[0] = seeValues[capture];
1453 // Locate the least valuable attacker for the side to move. The loop
1454 // below looks like it is potentially infinite, but it isn't. We know
1455 // that the side to move still has at least one attacker left.
1456 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1459 // Remove the attacker we just found from the 'attackers' bitboard,
1460 // and scan for new X-ray attacks behind the attacker.
1461 b = stmAttackers & pieces(pt);
1462 occ ^= (b & (~b + 1));
1463 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1464 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1468 // Add the new entry to the swap list
1470 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1473 // Remember the value of the capturing piece, and change the side to move
1474 // before beginning the next iteration
1475 lastCapturingPieceValue = seeValues[pt];
1476 c = opposite_color(c);
1477 stmAttackers = attackers & pieces_of_color(c);
1479 // Stop after a king capture
1480 if (pt == KING && stmAttackers)
1483 swapList[n++] = QueenValueMidgame*10;
1486 } while (stmAttackers);
1488 // Having built the swap list, we negamax through it to find the best
1489 // achievable score from the point of view of the side to move
1491 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1497 /// Position::clear() erases the position object to a pristine state, with an
1498 /// empty board, white to move, and no castling rights.
1500 void Position::clear() {
1503 memset(st, 0, sizeof(StateInfo));
1504 st->epSquare = SQ_NONE;
1506 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1507 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1508 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1509 memset(index, 0, sizeof(int) * 64);
1511 for (int i = 0; i < 64; i++)
1514 for (int i = 0; i < 8; i++)
1515 for (int j = 0; j < 16; j++)
1516 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1518 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1519 castleRightsMask[sq] = ALL_CASTLES;
1522 initialKFile = FILE_E;
1523 initialKRFile = FILE_H;
1524 initialQRFile = FILE_A;
1528 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1529 /// UCI interface code, whenever a non-reversible move is made in a
1530 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1531 /// for the program to handle games of arbitrary length, as long as the GUI
1532 /// handles draws by the 50 move rule correctly.
1534 void Position::reset_game_ply() {
1540 /// Position::put_piece() puts a piece on the given square of the board,
1541 /// updating the board array, bitboards, and piece counts.
1543 void Position::put_piece(Piece p, Square s) {
1545 Color c = color_of_piece(p);
1546 PieceType pt = type_of_piece(p);
1549 index[s] = pieceCount[c][pt];
1550 pieceList[c][pt][index[s]] = s;
1552 set_bit(&(byTypeBB[pt]), s);
1553 set_bit(&(byColorBB[c]), s);
1554 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1556 pieceCount[c][pt]++;
1560 /// Position::allow_oo() gives the given side the right to castle kingside.
1561 /// Used when setting castling rights during parsing of FEN strings.
1563 void Position::allow_oo(Color c) {
1565 st->castleRights |= (1 + int(c));
1569 /// Position::allow_ooo() gives the given side the right to castle queenside.
1570 /// Used when setting castling rights during parsing of FEN strings.
1572 void Position::allow_ooo(Color c) {
1574 st->castleRights |= (4 + 4*int(c));
1578 /// Position::compute_key() computes the hash key of the position. The hash
1579 /// key is usually updated incrementally as moves are made and unmade, the
1580 /// compute_key() function is only used when a new position is set up, and
1581 /// to verify the correctness of the hash key when running in debug mode.
1583 Key Position::compute_key() const {
1585 Key result = Key(0ULL);
1587 for (Square s = SQ_A1; s <= SQ_H8; s++)
1588 if (square_is_occupied(s))
1589 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1591 if (ep_square() != SQ_NONE)
1592 result ^= zobEp[ep_square()];
1594 result ^= zobCastle[st->castleRights];
1595 if (side_to_move() == BLACK)
1596 result ^= zobSideToMove;
1602 /// Position::compute_pawn_key() computes the hash key of the position. The
1603 /// hash key is usually updated incrementally as moves are made and unmade,
1604 /// the compute_pawn_key() function is only used when a new position is set
1605 /// up, and to verify the correctness of the pawn hash key when running in
1608 Key Position::compute_pawn_key() const {
1610 Key result = Key(0ULL);
1614 for (Color c = WHITE; c <= BLACK; c++)
1616 b = pieces(PAWN, c);
1619 s = pop_1st_bit(&b);
1620 result ^= zobrist[c][PAWN][s];
1627 /// Position::compute_material_key() computes the hash key of the position.
1628 /// The hash key is usually updated incrementally as moves are made and unmade,
1629 /// the compute_material_key() function is only used when a new position is set
1630 /// up, and to verify the correctness of the material hash key when running in
1633 Key Position::compute_material_key() const {
1635 Key result = Key(0ULL);
1636 for (Color c = WHITE; c <= BLACK; c++)
1637 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1639 int count = piece_count(c, pt);
1640 for (int i = 0; i < count; i++)
1641 result ^= zobrist[c][pt][i];
1647 /// Position::compute_value() compute the incremental scores for the middle
1648 /// game and the endgame. These functions are used to initialize the incremental
1649 /// scores when a new position is set up, and to verify that the scores are correctly
1650 /// updated by do_move and undo_move when the program is running in debug mode.
1651 Score Position::compute_value() const {
1653 Score result = make_score(0, 0);
1657 for (Color c = WHITE; c <= BLACK; c++)
1658 for (PieceType pt = PAWN; pt <= KING; pt++)
1663 s = pop_1st_bit(&b);
1664 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1665 result += pst(c, pt, s);
1669 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1674 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1675 /// game material score for the given side. Material scores are updated
1676 /// incrementally during the search, this function is only used while
1677 /// initializing a new Position object.
1679 Value Position::compute_non_pawn_material(Color c) const {
1681 Value result = Value(0);
1683 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1685 Bitboard b = pieces(pt, c);
1688 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1690 result += piece_value_midgame(pt);
1697 /// Position::is_draw() tests whether the position is drawn by material,
1698 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1699 /// must be done by the search.
1700 // FIXME: Currently we are not handling 50 move rule correctly when in check
1702 bool Position::is_draw() const {
1704 // Draw by material?
1706 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1709 // Draw by the 50 moves rule?
1710 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1713 // Draw by repetition?
1714 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1715 if (history[st->gamePly - i] == st->key)
1722 /// Position::is_mate() returns true or false depending on whether the
1723 /// side to move is checkmated.
1725 bool Position::is_mate() const {
1727 MoveStack moves[256];
1728 return is_check() && (generate_moves(*this, moves, false) == moves);
1732 /// Position::has_mate_threat() tests whether a given color has a mate in one
1733 /// from the current position.
1735 bool Position::has_mate_threat(Color c) {
1738 Color stm = side_to_move();
1743 // If the input color is not equal to the side to move, do a null move
1747 MoveStack mlist[120];
1748 bool result = false;
1749 Bitboard pinned = pinned_pieces(sideToMove);
1751 // Generate pseudo-legal non-capture and capture check moves
1752 MoveStack* last = generate_non_capture_checks(*this, mlist);
1753 last = generate_captures(*this, last);
1755 // Loop through the moves, and see if one of them is mate
1756 for (MoveStack* cur = mlist; cur != last; cur++)
1758 Move move = cur->move;
1759 if (!pl_move_is_legal(move, pinned))
1769 // Undo null move, if necessary
1777 /// Position::init_zobrist() is a static member function which initializes the
1778 /// various arrays used to compute hash keys.
1780 void Position::init_zobrist() {
1782 for (int i = 0; i < 2; i++)
1783 for (int j = 0; j < 8; j++)
1784 for (int k = 0; k < 64; k++)
1785 zobrist[i][j][k] = Key(genrand_int64());
1787 for (int i = 0; i < 64; i++)
1788 zobEp[i] = Key(genrand_int64());
1790 for (int i = 0; i < 16; i++)
1791 zobCastle[i] = genrand_int64();
1793 zobSideToMove = genrand_int64();
1794 zobExclusion = genrand_int64();
1798 /// Position::init_piece_square_tables() initializes the piece square tables.
1799 /// This is a two-step operation:
1800 /// First, the white halves of the tables are
1801 /// copied from the MgPST[][] and EgPST[][] arrays.
1802 /// Second, the black halves of the tables are initialized by mirroring
1803 /// and changing the sign of the 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(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(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;