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 Marco Costalba
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/>.
36 #include "ucioption.h"
43 extern SearchStack EmptySearchStack;
45 int Position::castleRightsMask[64];
47 Key Position::zobrist[2][8][64];
48 Key Position::zobEp[64];
49 Key Position::zobCastle[16];
50 Key Position::zobMaterial[2][8][16];
51 Key Position::zobSideToMove;
53 Value Position::MgPieceSquareTable[16][64];
54 Value Position::EgPieceSquareTable[16][64];
56 static bool RequestPending = false;
64 Position::Position(const Position& pos) {
68 Position::Position(const std::string& fen) {
73 /// Position::from_fen() initializes the position object with the given FEN
74 /// string. This function is not very robust - make sure that input FENs are
75 /// correct (this is assumed to be the responsibility of the GUI).
77 void Position::from_fen(const std::string& fen) {
79 static const std::string pieceLetters = "KQRBNPkqrbnp";
80 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
88 for ( ; fen[i] != ' '; i++)
92 // Skip the given number of files
93 file += (fen[i] - '1' + 1);
96 else if (fen[i] == '/')
102 size_t idx = pieceLetters.find(fen[i]);
103 if (idx == std::string::npos)
105 std::cout << "Error in FEN at character " << i << std::endl;
108 Square square = make_square(file, rank);
109 put_piece(pieces[idx], square);
115 if (fen[i] != 'w' && fen[i] != 'b')
117 std::cout << "Error in FEN at character " << i << std::endl;
120 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
126 std::cout << "Error in FEN at character " << i << std::endl;
131 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
137 else if(fen[i] == 'K') allow_oo(WHITE);
138 else if(fen[i] == 'Q') allow_ooo(WHITE);
139 else if(fen[i] == 'k') allow_oo(BLACK);
140 else if(fen[i] == 'q') allow_ooo(BLACK);
141 else if(fen[i] >= 'A' && fen[i] <= 'H') {
142 File rookFile, kingFile = FILE_NONE;
143 for(Square square = SQ_B1; square <= SQ_G1; square++)
144 if(piece_on(square) == WK)
145 kingFile = square_file(square);
146 if(kingFile == FILE_NONE) {
147 std::cout << "Error in FEN at character " << i << std::endl;
150 initialKFile = kingFile;
151 rookFile = File(fen[i] - 'A') + FILE_A;
152 if(rookFile < initialKFile) {
154 initialQRFile = rookFile;
158 initialKRFile = rookFile;
161 else if(fen[i] >= 'a' && fen[i] <= 'h') {
162 File rookFile, kingFile = FILE_NONE;
163 for(Square square = SQ_B8; square <= SQ_G8; square++)
164 if(piece_on(square) == BK)
165 kingFile = square_file(square);
166 if(kingFile == FILE_NONE) {
167 std::cout << "Error in FEN at character " << i << std::endl;
170 initialKFile = kingFile;
171 rookFile = File(fen[i] - 'a') + FILE_A;
172 if(rookFile < initialKFile) {
174 initialQRFile = rookFile;
178 initialKRFile = rookFile;
182 std::cout << "Error in FEN at character " << i << std::endl;
189 while (fen[i] == ' ')
193 if ( i < fen.length() - 2
194 && (fen[i] >= 'a' && fen[i] <= 'h')
195 && (fen[i+1] == '3' || fen[i+1] == '6'))
196 st->epSquare = square_from_string(fen.substr(i, 2));
198 // Various initialisation
199 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
200 castleRightsMask[sq] = ALL_CASTLES;
202 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
203 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
204 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
205 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
206 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
207 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
210 find_hidden_checks();
212 st->key = compute_key();
213 st->pawnKey = compute_pawn_key();
214 st->materialKey = compute_material_key();
215 st->mgValue = compute_value<MidGame>();
216 st->egValue = compute_value<EndGame>();
217 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
218 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
222 /// Position::to_fen() converts the position object to a FEN string. This is
223 /// probably only useful for debugging.
225 const std::string Position::to_fen() const {
227 static const std::string pieceLetters = " PNBRQK pnbrqk";
231 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
234 for (File file = FILE_A; file <= FILE_H; file++)
236 Square sq = make_square(file, rank);
237 if (!square_is_occupied(sq))
243 fen += (char)skip + '0';
246 fen += pieceLetters[piece_on(sq)];
249 fen += (char)skip + '0';
251 fen += (rank > RANK_1 ? '/' : ' ');
253 fen += (sideToMove == WHITE ? "w " : "b ");
254 if (st->castleRights != NO_CASTLES)
256 if (can_castle_kingside(WHITE)) fen += 'K';
257 if (can_castle_queenside(WHITE)) fen += 'Q';
258 if (can_castle_kingside(BLACK)) fen += 'k';
259 if (can_castle_queenside(BLACK)) fen += 'q';
264 if (ep_square() != SQ_NONE)
265 fen += square_to_string(ep_square());
273 /// Position::print() prints an ASCII representation of the position to
274 /// the standard output. If a move is given then also the san is print.
276 void Position::print(Move m) const {
278 static const std::string pieceLetters = " PNBRQK PNBRQK .";
280 // Check for reentrancy, as example when called from inside
281 // MovePicker that is used also here in move_to_san()
285 RequestPending = true;
287 std::cout << std::endl;
290 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
291 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
293 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
295 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
296 for (File file = FILE_A; file <= FILE_H; file++)
298 Square sq = make_square(file, rank);
299 Piece piece = piece_on(sq);
300 if (piece == EMPTY && square_color(sq) == WHITE)
303 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
304 std::cout << '|' << col << pieceLetters[piece] << col;
306 std::cout << '|' << std::endl;
308 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
309 << "Fen is: " << to_fen() << std::endl
310 << "Key is: " << st->key << std::endl;
312 RequestPending = false;
316 /// Position::copy() creates a copy of the input position.
318 void Position::copy(const Position &pos) {
320 memcpy(this, &pos, sizeof(Position));
324 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
325 /// king) pieces for the given color and for the given pinner type. Or, when
326 /// template parameter FindPinned is false, the pinned pieces of opposite color
327 /// that are, indeed, the pieces candidate for a discovery check.
328 /// Note that checkersBB bitboard must be already updated.
329 template<PieceType Piece, bool FindPinned>
330 Bitboard Position::hidden_checks(Color c, Square ksq, Bitboard& pinners) const {
333 Bitboard sliders, result = EmptyBoardBB;
335 if (Piece == ROOK) // Resolved at compile time
336 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
338 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
340 if (sliders && (!FindPinned || (sliders & ~st->checkersBB)))
342 // King blockers are candidate pinned pieces
343 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
345 // Pinners are sliders, not checkers, that give check when
346 // candidate pinned are removed.
347 pinners = (FindPinned ? sliders & ~st->checkersBB : sliders);
350 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
352 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
354 // Finally for each pinner find the corresponding pinned piece (if same color of king)
355 // or discovery checker (if opposite color) among the candidates.
356 Bitboard p = pinners;
360 result |= (squares_between(s, ksq) & candidate_pinned);
364 pinners = EmptyBoardBB;
370 /// Position::attacks_to() computes a bitboard containing all pieces which
371 /// attacks a given square. There are two versions of this function: One
372 /// which finds attackers of both colors, and one which only finds the
373 /// attackers for one side.
375 Bitboard Position::attacks_to(Square s) const {
377 return (pawn_attacks(BLACK, s) & pawns(WHITE))
378 | (pawn_attacks(WHITE, s) & pawns(BLACK))
379 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
380 | (piece_attacks<ROOK>(s) & rooks_and_queens())
381 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
382 | (piece_attacks<KING>(s) & pieces_of_type(KING));
385 /// Position::piece_attacks_square() tests whether the piece on square f
386 /// attacks square t.
388 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
390 assert(square_is_ok(f));
391 assert(square_is_ok(t));
395 case WP: return pawn_attacks_square(WHITE, f, t);
396 case BP: return pawn_attacks_square(BLACK, f, t);
397 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
398 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
399 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
400 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
401 case WK: case BK: return piece_attacks_square<KING>(f, t);
408 /// Position::move_attacks_square() tests whether a move from the current
409 /// position attacks a given square.
411 bool Position::move_attacks_square(Move m, Square s) const {
413 assert(move_is_ok(m));
414 assert(square_is_ok(s));
416 Square f = move_from(m), t = move_to(m);
418 assert(square_is_occupied(f));
420 if (piece_attacks_square(piece_on(f), t, s))
423 // Move the piece and scan for X-ray attacks behind it
424 Bitboard occ = occupied_squares();
425 Color us = color_of_piece_on(f);
428 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
429 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
431 // If we have attacks we need to verify that are caused by our move
432 // and are not already existent ones.
433 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
437 /// Position::find_checkers() computes the checkersBB bitboard, which
438 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
439 /// currently works by calling Position::attacks_to, which is probably
440 /// inefficient. Consider rewriting this function to use the last move
441 /// played, like in non-bitboard versions of Glaurung.
443 void Position::find_checkers() {
445 Color us = side_to_move();
446 st->checkersBB = attacks_to(king_square(us), opposite_color(us));
449 /// Position:find_hidden_checks() computes the pinned, pinners and dcCandidates
450 /// bitboards. There are two versions of this function. One takes a color and
451 /// computes bitboards relative to that color only, the other computes both
452 /// colors. Bitboard checkersBB must be already updated.
454 void Position::find_hidden_checks(Color us) {
457 Color them = opposite_color(us);
458 Square ksq = king_square(them);
459 st->pinned[them] = hidden_checks<ROOK, true>(them, ksq, p1) | hidden_checks<BISHOP, true>(them, ksq, p2);
460 st->pinners[them] = p1 | p2;
461 st->dcCandidates[us] = hidden_checks<ROOK, false>(us, ksq, p1) | hidden_checks<BISHOP, false>(us, ksq, p2);
464 void Position::find_hidden_checks() {
466 for (Color c = WHITE; c <= BLACK; c++)
467 find_hidden_checks(c);
471 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
473 bool Position::pl_move_is_legal(Move m) const {
476 assert(move_is_ok(m));
478 // If we're in check, all pseudo-legal moves are legal, because our
479 // check evasion generator only generates true legal moves.
483 // Castling moves are checked for legality during move generation.
484 if (move_is_castle(m))
487 Color us = side_to_move();
488 Color them = opposite_color(us);
489 Square from = move_from(m);
490 Square ksq = king_square(us);
492 assert(color_of_piece_on(from) == us);
493 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
495 // En passant captures are a tricky special case. Because they are
496 // rather uncommon, we do it simply by testing whether the king is attacked
497 // after the move is made
500 Square to = move_to(m);
501 Square capsq = make_square(square_file(to), square_rank(from));
502 Bitboard b = occupied_squares();
504 assert(to == ep_square());
505 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
506 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
507 assert(piece_on(to) == EMPTY);
510 clear_bit(&b, capsq);
513 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
514 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
517 // If the moving piece is a king, check whether the destination
518 // square is attacked by the opponent.
520 return !(square_is_attacked(move_to(m), them));
522 // A non-king move is legal if and only if it is not pinned or it
523 // is moving along the ray towards or away from the king.
524 return ( !bit_is_set(pinned_pieces(us), from)
525 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
529 /// Position::move_is_check() tests whether a pseudo-legal move is a check
531 bool Position::move_is_check(Move m) const {
534 assert(move_is_ok(m));
536 Color us = side_to_move();
537 Color them = opposite_color(us);
538 Square from = move_from(m);
539 Square to = move_to(m);
540 Square ksq = king_square(them);
541 Bitboard dcCandidates = discovered_check_candidates(us);
543 assert(color_of_piece_on(from) == us);
544 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
546 // Proceed according to the type of the moving piece
547 switch (type_of_piece_on(from))
551 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
554 if ( bit_is_set(dcCandidates, from) // Discovered check?
555 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
558 if (move_promotion(m)) // Promotion with check?
560 Bitboard b = occupied_squares();
563 switch (move_promotion(m))
566 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
568 return bit_is_set(bishop_attacks_bb(to, b), ksq);
570 return bit_is_set(rook_attacks_bb(to, b), ksq);
572 return bit_is_set(queen_attacks_bb(to, b), ksq);
577 // En passant capture with check? We have already handled the case
578 // of direct checks and ordinary discovered check, the only case we
579 // need to handle is the unusual case of a discovered check through the
581 else if (move_is_ep(m))
583 Square capsq = make_square(square_file(to), square_rank(from));
584 Bitboard b = occupied_squares();
586 clear_bit(&b, capsq);
588 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
589 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
594 return bit_is_set(dcCandidates, from) // Discovered check?
595 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
598 return bit_is_set(dcCandidates, from) // Discovered check?
599 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
602 return bit_is_set(dcCandidates, from) // Discovered check?
603 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
606 // Discovered checks are impossible!
607 assert(!bit_is_set(dcCandidates, from));
608 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
612 if ( bit_is_set(dcCandidates, from)
613 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
616 // Castling with check?
617 if (move_is_castle(m))
619 Square kfrom, kto, rfrom, rto;
620 Bitboard b = occupied_squares();
626 kto = relative_square(us, SQ_G1);
627 rto = relative_square(us, SQ_F1);
629 kto = relative_square(us, SQ_C1);
630 rto = relative_square(us, SQ_D1);
632 clear_bit(&b, kfrom);
633 clear_bit(&b, rfrom);
636 return bit_is_set(rook_attacks_bb(rto, b), ksq);
640 default: // NO_PIECE_TYPE
648 /// Position::move_is_capture() tests whether a move from the current
649 /// position is a capture. Move must not be MOVE_NONE.
651 bool Position::move_is_capture(Move m) const {
653 assert(m != MOVE_NONE);
655 return ( !square_is_empty(move_to(m))
656 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
662 /// Position::update_checkers() udpates chekers info given the move. It is called
663 /// in do_move() and is faster then find_checkers().
665 template<PieceType Piece>
666 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
667 Square to, Bitboard dcCandidates) {
669 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
670 set_bit(pCheckersBB, to);
672 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
675 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
678 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
683 /// Position::update_hidden_checks() udpates pinned, pinners and dcCandidates
684 /// bitboards incrementally, given the move. It is called in do_move and is
685 /// faster then find_hidden_checks().
687 void Position::update_hidden_checks(Square from, Square to) {
689 Color us = sideToMove;
690 Color them = opposite_color(us);
691 Square ksq = king_square(opposite_color(us));
693 Bitboard moveSquares = EmptyBoardBB;
694 set_bit(&moveSquares, from);
695 set_bit(&moveSquares, to);
697 // Our moving piece could have been a possible pinner or hidden checker behind a dcCandidates?
698 bool checkerMoved = (st->dcCandidates[us] | st->pinners[them]) && (moveSquares & sliders());
700 // If we are moving from/to an opponent king attack direction and we was a possible hidden checker
701 // or there exsist some possible hidden checker on that line then recalculate the position
702 // otherwise skip because our dcCandidates and opponent pinned pieces are not changed.
703 if ( (moveSquares & RookPseudoAttacks[ksq]) && (checkerMoved || (rooks_and_queens(us) & RookPseudoAttacks[ksq]))
704 || (moveSquares & BishopPseudoAttacks[ksq]) && (checkerMoved || (bishops_and_queens(us) & BishopPseudoAttacks[ksq])))
705 find_hidden_checks(us);
707 ksq = king_square(us);
711 find_hidden_checks(them);
715 // It is possible that we have captured an opponent hidden checker?
716 Bitboard checkerCaptured = (st->dcCandidates[them] | st->pinners[us]) && st->capture;
718 // If we are moving from/to an our king attack direction and there was/is some possible
719 // opponent hidden checker then calculate the position otherwise skip because opponent
720 // dcCandidates and our pinned pieces are not changed.
721 if ( (moveSquares & RookPseudoAttacks[ksq]) && (checkerCaptured || (rooks_and_queens(them) & RookPseudoAttacks[ksq]))
722 || (moveSquares & BishopPseudoAttacks[ksq]) && (checkerCaptured || (bishops_and_queens(them) & BishopPseudoAttacks[ksq])))
723 find_hidden_checks(them);
727 /// Position::do_move() makes a move, and saves all information necessary
728 /// to a StateInfo object. The move is assumed to be legal.
729 /// Pseudo-legal moves should be filtered out before this function is called.
731 void Position::do_move(Move m, StateInfo& newSt) {
734 assert(move_is_ok(m));
736 // Get now the current (before to move) dc candidates that we will use
737 // in update_checkers().
738 Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
740 // Copy some fields of old state to our new StateInfo object (except the
741 // captured piece, which is taken care of later) and switch state pointer
742 // to point to the new, ready to be updated, state.
744 newSt.capture = NO_PIECE_TYPE;
748 // Save the current key to the history[] array, in order to be able to
749 // detect repetition draws.
750 history[gamePly] = st->key;
752 // Increment the 50 moves rule draw counter. Resetting it to zero in the
753 // case of non-reversible moves is taken care of later.
756 if (move_is_castle(m))
758 else if (move_promotion(m))
759 do_promotion_move(m);
760 else if (move_is_ep(m))
764 Color us = side_to_move();
765 Color them = opposite_color(us);
766 Square from = move_from(m);
767 Square to = move_to(m);
769 assert(color_of_piece_on(from) == us);
770 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
772 PieceType piece = type_of_piece_on(from);
774 st->capture = type_of_piece_on(to);
777 do_capture_move(m, st->capture, them, to);
780 clear_bit(&(byColorBB[us]), from);
781 clear_bit(&(byTypeBB[piece]), from);
782 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
783 set_bit(&(byColorBB[us]), to);
784 set_bit(&(byTypeBB[piece]), to);
785 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
786 board[to] = board[from];
790 st->key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
792 // Update incremental scores
793 st->mgValue -= pst<MidGame>(us, piece, from);
794 st->mgValue += pst<MidGame>(us, piece, to);
795 st->egValue -= pst<EndGame>(us, piece, from);
796 st->egValue += pst<EndGame>(us, piece, to);
798 // If the moving piece was a king, update the king square
802 // Reset en passant square
803 if (st->epSquare != SQ_NONE)
805 st->key ^= zobEp[st->epSquare];
806 st->epSquare = SQ_NONE;
809 // If the moving piece was a pawn do some special extra work
812 // Reset rule 50 draw counter
815 // Update pawn hash key
816 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
818 // Set en passant square, only if moved pawn can be captured
819 if (abs(int(to) - int(from)) == 16)
821 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
822 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
824 st->epSquare = Square((int(from) + int(to)) / 2);
825 st->key ^= zobEp[st->epSquare];
830 // Update piece lists
831 pieceList[us][piece][index[from]] = to;
832 index[to] = index[from];
834 // Update castle rights
835 st->key ^= zobCastle[st->castleRights];
836 st->castleRights &= castleRightsMask[from];
837 st->castleRights &= castleRightsMask[to];
838 st->key ^= zobCastle[st->castleRights];
840 // Update checkers bitboard, piece must be already moved
841 st->checkersBB = EmptyBoardBB;
842 Square ksq = king_square(them);
845 case PAWN: update_checkers<PAWN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
846 case KNIGHT: update_checkers<KNIGHT>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
847 case BISHOP: update_checkers<BISHOP>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
848 case ROOK: update_checkers<ROOK>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
849 case QUEEN: update_checkers<QUEEN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
850 case KING: update_checkers<KING>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
851 default: assert(false); break;
854 update_hidden_checks(from, to);
858 st->key ^= zobSideToMove;
859 sideToMove = opposite_color(sideToMove);
862 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
863 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
869 /// Position::do_capture_move() is a private method used to update captured
870 /// piece info. It is called from the main Position::do_move function.
872 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
874 assert(capture != KING);
876 // Remove captured piece
877 clear_bit(&(byColorBB[them]), to);
878 clear_bit(&(byTypeBB[capture]), to);
881 st->key ^= zobrist[them][capture][to];
883 // If the captured piece was a pawn, update pawn hash key
885 st->pawnKey ^= zobrist[them][PAWN][to];
887 // Update incremental scores
888 st->mgValue -= pst<MidGame>(them, capture, to);
889 st->egValue -= pst<EndGame>(them, capture, to);
891 assert(!move_promotion(m) || capture != PAWN);
895 npMaterial[them] -= piece_value_midgame(capture);
897 // Update material hash key
898 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
900 // Update piece count
901 pieceCount[them][capture]--;
904 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
905 index[pieceList[them][capture][index[to]]] = index[to];
907 // Reset rule 50 counter
912 /// Position::do_castle_move() is a private method used to make a castling
913 /// move. It is called from the main Position::do_move function. Note that
914 /// castling moves are encoded as "king captures friendly rook" moves, for
915 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
917 void Position::do_castle_move(Move m) {
920 assert(move_is_ok(m));
921 assert(move_is_castle(m));
923 Color us = side_to_move();
924 Color them = opposite_color(us);
926 // Find source squares for king and rook
927 Square kfrom = move_from(m);
928 Square rfrom = move_to(m); // HACK: See comment at beginning of function
931 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
932 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
934 // Find destination squares for king and rook
935 if (rfrom > kfrom) // O-O
937 kto = relative_square(us, SQ_G1);
938 rto = relative_square(us, SQ_F1);
940 kto = relative_square(us, SQ_C1);
941 rto = relative_square(us, SQ_D1);
944 // Remove pieces from source squares
945 clear_bit(&(byColorBB[us]), kfrom);
946 clear_bit(&(byTypeBB[KING]), kfrom);
947 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
948 clear_bit(&(byColorBB[us]), rfrom);
949 clear_bit(&(byTypeBB[ROOK]), rfrom);
950 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
952 // Put pieces on destination squares
953 set_bit(&(byColorBB[us]), kto);
954 set_bit(&(byTypeBB[KING]), kto);
955 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
956 set_bit(&(byColorBB[us]), rto);
957 set_bit(&(byTypeBB[ROOK]), rto);
958 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
960 // Update board array
961 board[kfrom] = board[rfrom] = EMPTY;
962 board[kto] = piece_of_color_and_type(us, KING);
963 board[rto] = piece_of_color_and_type(us, ROOK);
965 // Update king square
966 kingSquare[us] = kto;
968 // Update piece lists
969 pieceList[us][KING][index[kfrom]] = kto;
970 pieceList[us][ROOK][index[rfrom]] = rto;
971 int tmp = index[rfrom];
972 index[kto] = index[kfrom];
975 // Update incremental scores
976 st->mgValue -= pst<MidGame>(us, KING, kfrom);
977 st->mgValue += pst<MidGame>(us, KING, kto);
978 st->egValue -= pst<EndGame>(us, KING, kfrom);
979 st->egValue += pst<EndGame>(us, KING, kto);
980 st->mgValue -= pst<MidGame>(us, ROOK, rfrom);
981 st->mgValue += pst<MidGame>(us, ROOK, rto);
982 st->egValue -= pst<EndGame>(us, ROOK, rfrom);
983 st->egValue += pst<EndGame>(us, ROOK, rto);
986 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
987 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
989 // Clear en passant square
990 if (st->epSquare != SQ_NONE)
992 st->key ^= zobEp[st->epSquare];
993 st->epSquare = SQ_NONE;
996 // Update castling rights
997 st->key ^= zobCastle[st->castleRights];
998 st->castleRights &= castleRightsMask[kfrom];
999 st->key ^= zobCastle[st->castleRights];
1001 // Reset rule 50 counter
1004 // Update checkers BB
1005 st->checkersBB = attacks_to(king_square(them), us);
1007 // Update hidden checks
1008 find_hidden_checks();
1012 /// Position::do_promotion_move() is a private method used to make a promotion
1013 /// move. It is called from the main Position::do_move function.
1015 void Position::do_promotion_move(Move m) {
1019 PieceType promotion;
1022 assert(move_is_ok(m));
1023 assert(move_promotion(m));
1025 us = side_to_move();
1026 them = opposite_color(us);
1027 from = move_from(m);
1030 assert(relative_rank(us, to) == RANK_8);
1031 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1032 assert(color_of_piece_on(to) == them || square_is_empty(to));
1034 st->capture = type_of_piece_on(to);
1037 do_capture_move(m, st->capture, them, to);
1040 clear_bit(&(byColorBB[us]), from);
1041 clear_bit(&(byTypeBB[PAWN]), from);
1042 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1043 board[from] = EMPTY;
1045 // Insert promoted piece
1046 promotion = move_promotion(m);
1047 assert(promotion >= KNIGHT && promotion <= QUEEN);
1048 set_bit(&(byColorBB[us]), to);
1049 set_bit(&(byTypeBB[promotion]), to);
1050 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1051 board[to] = piece_of_color_and_type(us, promotion);
1054 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1056 // Update pawn hash key
1057 st->pawnKey ^= zobrist[us][PAWN][from];
1059 // Update material key
1060 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1061 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1063 // Update piece counts
1064 pieceCount[us][PAWN]--;
1065 pieceCount[us][promotion]++;
1067 // Update piece lists
1068 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1069 index[pieceList[us][PAWN][index[from]]] = index[from];
1070 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1071 index[to] = pieceCount[us][promotion] - 1;
1073 // Update incremental scores
1074 st->mgValue -= pst<MidGame>(us, PAWN, from);
1075 st->mgValue += pst<MidGame>(us, promotion, to);
1076 st->egValue -= pst<EndGame>(us, PAWN, from);
1077 st->egValue += pst<EndGame>(us, promotion, to);
1080 npMaterial[us] += piece_value_midgame(promotion);
1082 // Clear the en passant square
1083 if (st->epSquare != SQ_NONE)
1085 st->key ^= zobEp[st->epSquare];
1086 st->epSquare = SQ_NONE;
1089 // Update castle rights
1090 st->key ^= zobCastle[st->castleRights];
1091 st->castleRights &= castleRightsMask[to];
1092 st->key ^= zobCastle[st->castleRights];
1094 // Reset rule 50 counter
1097 // Update checkers BB
1098 st->checkersBB = attacks_to(king_square(them), us);
1100 // Update hidden checks
1101 find_hidden_checks();
1105 /// Position::do_ep_move() is a private method used to make an en passant
1106 /// capture. It is called from the main Position::do_move function.
1108 void Position::do_ep_move(Move m) {
1111 Square from, to, capsq;
1114 assert(move_is_ok(m));
1115 assert(move_is_ep(m));
1117 us = side_to_move();
1118 them = opposite_color(us);
1119 from = move_from(m);
1121 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1123 assert(to == st->epSquare);
1124 assert(relative_rank(us, to) == RANK_6);
1125 assert(piece_on(to) == EMPTY);
1126 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1127 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1129 // Remove captured piece
1130 clear_bit(&(byColorBB[them]), capsq);
1131 clear_bit(&(byTypeBB[PAWN]), capsq);
1132 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1133 board[capsq] = EMPTY;
1135 // Remove moving piece from source square
1136 clear_bit(&(byColorBB[us]), from);
1137 clear_bit(&(byTypeBB[PAWN]), from);
1138 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1140 // Put moving piece on destination square
1141 set_bit(&(byColorBB[us]), to);
1142 set_bit(&(byTypeBB[PAWN]), to);
1143 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1144 board[to] = board[from];
1145 board[from] = EMPTY;
1147 // Update material hash key
1148 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1150 // Update piece count
1151 pieceCount[them][PAWN]--;
1153 // Update piece list
1154 pieceList[us][PAWN][index[from]] = to;
1155 index[to] = index[from];
1156 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1157 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1160 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1161 st->key ^= zobrist[them][PAWN][capsq];
1162 st->key ^= zobEp[st->epSquare];
1164 // Update pawn hash key
1165 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1166 st->pawnKey ^= zobrist[them][PAWN][capsq];
1168 // Update incremental scores
1169 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1170 st->mgValue -= pst<MidGame>(us, PAWN, from);
1171 st->mgValue += pst<MidGame>(us, PAWN, to);
1172 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1173 st->egValue -= pst<EndGame>(us, PAWN, from);
1174 st->egValue += pst<EndGame>(us, PAWN, to);
1176 // Reset en passant square
1177 st->epSquare = SQ_NONE;
1179 // Reset rule 50 counter
1182 // Update checkers BB
1183 st->checkersBB = attacks_to(king_square(them), us);
1185 // Update hidden checks
1186 find_hidden_checks();
1190 /// Position::undo_move() unmakes a move. When it returns, the position should
1191 /// be restored to exactly the same state as before the move was made.
1193 void Position::undo_move(Move m) {
1196 assert(move_is_ok(m));
1199 sideToMove = opposite_color(sideToMove);
1201 if (move_is_castle(m))
1202 undo_castle_move(m);
1203 else if (move_promotion(m))
1204 undo_promotion_move(m);
1205 else if (move_is_ep(m))
1213 us = side_to_move();
1214 them = opposite_color(us);
1215 from = move_from(m);
1218 assert(piece_on(from) == EMPTY);
1219 assert(color_of_piece_on(to) == us);
1221 // Put the piece back at the source square
1222 piece = type_of_piece_on(to);
1223 set_bit(&(byColorBB[us]), from);
1224 set_bit(&(byTypeBB[piece]), from);
1225 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1226 board[from] = piece_of_color_and_type(us, piece);
1228 // Clear the destination square
1229 clear_bit(&(byColorBB[us]), to);
1230 clear_bit(&(byTypeBB[piece]), to);
1231 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1233 // If the moving piece was a king, update the king square
1235 kingSquare[us] = from;
1237 // Update piece list
1238 pieceList[us][piece][index[to]] = from;
1239 index[from] = index[to];
1243 assert(st->capture != KING);
1245 // Replace the captured piece
1246 set_bit(&(byColorBB[them]), to);
1247 set_bit(&(byTypeBB[st->capture]), to);
1248 set_bit(&(byTypeBB[0]), to);
1249 board[to] = piece_of_color_and_type(them, st->capture);
1252 if (st->capture != PAWN)
1253 npMaterial[them] += piece_value_midgame(st->capture);
1255 // Update piece list
1256 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1257 index[to] = pieceCount[them][st->capture];
1259 // Update piece count
1260 pieceCount[them][st->capture]++;
1265 // Finally point out state pointer back to the previous state
1272 /// Position::undo_castle_move() is a private method used to unmake a castling
1273 /// move. It is called from the main Position::undo_move function. Note that
1274 /// castling moves are encoded as "king captures friendly rook" moves, for
1275 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1277 void Position::undo_castle_move(Move m) {
1279 assert(move_is_ok(m));
1280 assert(move_is_castle(m));
1282 // When we have arrived here, some work has already been done by
1283 // Position::undo_move. In particular, the side to move has been switched,
1284 // so the code below is correct.
1285 Color us = side_to_move();
1287 // Find source squares for king and rook
1288 Square kfrom = move_from(m);
1289 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1292 // Find destination squares for king and rook
1293 if (rfrom > kfrom) // O-O
1295 kto = relative_square(us, SQ_G1);
1296 rto = relative_square(us, SQ_F1);
1298 kto = relative_square(us, SQ_C1);
1299 rto = relative_square(us, SQ_D1);
1302 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1303 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1305 // Remove pieces from destination squares
1306 clear_bit(&(byColorBB[us]), kto);
1307 clear_bit(&(byTypeBB[KING]), kto);
1308 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1309 clear_bit(&(byColorBB[us]), rto);
1310 clear_bit(&(byTypeBB[ROOK]), rto);
1311 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1313 // Put pieces on source squares
1314 set_bit(&(byColorBB[us]), kfrom);
1315 set_bit(&(byTypeBB[KING]), kfrom);
1316 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1317 set_bit(&(byColorBB[us]), rfrom);
1318 set_bit(&(byTypeBB[ROOK]), rfrom);
1319 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1322 board[rto] = board[kto] = EMPTY;
1323 board[rfrom] = piece_of_color_and_type(us, ROOK);
1324 board[kfrom] = piece_of_color_and_type(us, KING);
1326 // Update king square
1327 kingSquare[us] = kfrom;
1329 // Update piece lists
1330 pieceList[us][KING][index[kto]] = kfrom;
1331 pieceList[us][ROOK][index[rto]] = rfrom;
1332 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1333 index[kfrom] = index[kto];
1338 /// Position::undo_promotion_move() is a private method used to unmake a
1339 /// promotion move. It is called from the main Position::do_move
1342 void Position::undo_promotion_move(Move m) {
1346 PieceType promotion;
1348 assert(move_is_ok(m));
1349 assert(move_promotion(m));
1351 // When we have arrived here, some work has already been done by
1352 // Position::undo_move. In particular, the side to move has been switched,
1353 // so the code below is correct.
1354 us = side_to_move();
1355 them = opposite_color(us);
1356 from = move_from(m);
1359 assert(relative_rank(us, to) == RANK_8);
1360 assert(piece_on(from) == EMPTY);
1362 // Remove promoted piece
1363 promotion = move_promotion(m);
1364 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1365 assert(promotion >= KNIGHT && promotion <= QUEEN);
1366 clear_bit(&(byColorBB[us]), to);
1367 clear_bit(&(byTypeBB[promotion]), to);
1368 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1370 // Insert pawn at source square
1371 set_bit(&(byColorBB[us]), from);
1372 set_bit(&(byTypeBB[PAWN]), from);
1373 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1374 board[from] = piece_of_color_and_type(us, PAWN);
1377 npMaterial[us] -= piece_value_midgame(promotion);
1379 // Update piece list
1380 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1381 index[from] = pieceCount[us][PAWN];
1382 pieceList[us][promotion][index[to]] =
1383 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1384 index[pieceList[us][promotion][index[to]]] = index[to];
1386 // Update piece counts
1387 pieceCount[us][promotion]--;
1388 pieceCount[us][PAWN]++;
1392 assert(st->capture != KING);
1394 // Insert captured piece:
1395 set_bit(&(byColorBB[them]), to);
1396 set_bit(&(byTypeBB[st->capture]), to);
1397 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1398 board[to] = piece_of_color_and_type(them, st->capture);
1400 // Update material. Because the move is a promotion move, we know
1401 // that the captured piece cannot be a pawn.
1402 assert(st->capture != PAWN);
1403 npMaterial[them] += piece_value_midgame(st->capture);
1405 // Update piece list
1406 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1407 index[to] = pieceCount[them][st->capture];
1409 // Update piece count
1410 pieceCount[them][st->capture]++;
1416 /// Position::undo_ep_move() is a private method used to unmake an en passant
1417 /// capture. It is called from the main Position::undo_move function.
1419 void Position::undo_ep_move(Move m) {
1421 assert(move_is_ok(m));
1422 assert(move_is_ep(m));
1424 // When we have arrived here, some work has already been done by
1425 // Position::undo_move. In particular, the side to move has been switched,
1426 // so the code below is correct.
1427 Color us = side_to_move();
1428 Color them = opposite_color(us);
1429 Square from = move_from(m);
1430 Square to = move_to(m);
1431 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1433 assert(to == st->previous->epSquare);
1434 assert(relative_rank(us, to) == RANK_6);
1435 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1436 assert(piece_on(from) == EMPTY);
1437 assert(piece_on(capsq) == EMPTY);
1439 // Replace captured piece
1440 set_bit(&(byColorBB[them]), capsq);
1441 set_bit(&(byTypeBB[PAWN]), capsq);
1442 set_bit(&(byTypeBB[0]), capsq);
1443 board[capsq] = piece_of_color_and_type(them, PAWN);
1445 // Remove moving piece from destination square
1446 clear_bit(&(byColorBB[us]), to);
1447 clear_bit(&(byTypeBB[PAWN]), to);
1448 clear_bit(&(byTypeBB[0]), to);
1451 // Replace moving piece at source square
1452 set_bit(&(byColorBB[us]), from);
1453 set_bit(&(byTypeBB[PAWN]), from);
1454 set_bit(&(byTypeBB[0]), from);
1455 board[from] = piece_of_color_and_type(us, PAWN);
1457 // Update piece list:
1458 pieceList[us][PAWN][index[to]] = from;
1459 index[from] = index[to];
1460 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1461 index[capsq] = pieceCount[them][PAWN];
1463 // Update piece count:
1464 pieceCount[them][PAWN]++;
1468 /// Position::do_null_move makes() a "null move": It switches the side to move
1469 /// and updates the hash key without executing any move on the board.
1471 void Position::do_null_move(StateInfo& newSt) {
1474 assert(!is_check());
1476 // Back up the information necessary to undo the null move to the supplied
1477 // StateInfo object. In the case of a null move, the only thing we need to
1478 // remember is the last move made and the en passant square.
1479 newSt.lastMove = st->lastMove;
1480 newSt.epSquare = st->epSquare;
1481 newSt.previous = st->previous;
1482 st->previous = &newSt;
1484 // Save the current key to the history[] array, in order to be able to
1485 // detect repetition draws.
1486 history[gamePly] = st->key;
1488 // Update the necessary information
1489 sideToMove = opposite_color(sideToMove);
1490 if (st->epSquare != SQ_NONE)
1491 st->key ^= zobEp[st->epSquare];
1493 st->epSquare = SQ_NONE;
1496 st->key ^= zobSideToMove;
1498 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1499 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1505 /// Position::undo_null_move() unmakes a "null move".
1507 void Position::undo_null_move() {
1510 assert(!is_check());
1512 // Restore information from the our StateInfo object
1513 st->lastMove = st->previous->lastMove;
1514 st->epSquare = st->previous->epSquare;
1515 st->previous = st->previous->previous;
1517 if (st->epSquare != SQ_NONE)
1518 st->key ^= zobEp[st->epSquare];
1520 // Update the necessary information
1521 sideToMove = opposite_color(sideToMove);
1524 st->key ^= zobSideToMove;
1526 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1527 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1533 /// Position::see() is a static exchange evaluator: It tries to estimate the
1534 /// material gain or loss resulting from a move. There are three versions of
1535 /// this function: One which takes a destination square as input, one takes a
1536 /// move, and one which takes a 'from' and a 'to' square. The function does
1537 /// not yet understand promotions captures.
1539 int Position::see(Square to) const {
1541 assert(square_is_ok(to));
1542 return see(SQ_NONE, to);
1545 int Position::see(Move m) const {
1547 assert(move_is_ok(m));
1548 return see(move_from(m), move_to(m));
1551 int Position::see(Square from, Square to) const {
1554 static const int seeValues[18] = {
1555 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1556 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1557 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1558 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1562 Bitboard attackers, occ, b;
1564 assert(square_is_ok(from) || from == SQ_NONE);
1565 assert(square_is_ok(to));
1567 // Initialize colors
1568 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1569 Color them = opposite_color(us);
1571 // Initialize pinned and pinners bitboards
1572 Bitboard pinned[2], pinners[2];
1573 pinned[us] = pinned_pieces(us, pinners[us]);
1574 pinned[them] = pinned_pieces(them, pinners[them]);
1576 // Initialize pieces
1577 Piece piece = piece_on(from);
1578 Piece capture = piece_on(to);
1580 // Find all attackers to the destination square, with the moving piece
1581 // removed, but possibly an X-ray attacker added behind it.
1582 occ = occupied_squares();
1584 // Handle en passant moves
1585 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1587 assert(capture == EMPTY);
1589 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1590 capture = piece_on(capQq);
1592 assert(type_of_piece_on(capQq) == PAWN);
1594 // Remove the captured pawn
1595 clear_bit(&occ, capQq);
1600 clear_bit(&occ, from);
1601 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1602 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1603 | (piece_attacks<KNIGHT>(to) & knights())
1604 | (piece_attacks<KING>(to) & kings())
1605 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1606 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1608 // Remove our pinned pieces from attacks if the captured piece is not
1609 // a pinner, otherwise we could remove a valid "capture the pinner" attack.
1610 if (pinned[us] != EmptyBoardBB && !bit_is_set(pinners[us], to))
1611 attackers &= ~pinned[us];
1613 // Remove opponent pinned pieces from attacks if the moving piece is not
1614 // a pinner, otherwise we could remove a piece that is no more pinned
1615 // due to our pinner piece is moving away.
1616 if (pinned[them] != EmptyBoardBB && !bit_is_set(pinners[them], from))
1617 attackers &= ~pinned[them];
1619 if (from != SQ_NONE)
1622 // If we don't have any attacker we are finished
1623 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1626 // Locate the least valuable attacker to the destination square
1627 // and use it to initialize from square.
1629 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1632 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1633 piece = piece_on(from);
1636 // If the opponent has no attackers we are finished
1637 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1638 return seeValues[capture];
1640 attackers &= occ; // Remove the moving piece
1642 // The destination square is defended, which makes things rather more
1643 // difficult to compute. We proceed by building up a "swap list" containing
1644 // the material gain or loss at each stop in a sequence of captures to the
1645 // destination square, where the sides alternately capture, and always
1646 // capture with the least valuable piece. After each capture, we look for
1647 // new X-ray attacks from behind the capturing piece.
1648 int lastCapturingPieceValue = seeValues[piece];
1649 int swapList[32], n = 1;
1653 swapList[0] = seeValues[capture];
1656 // Locate the least valuable attacker for the side to move. The loop
1657 // below looks like it is potentially infinite, but it isn't. We know
1658 // that the side to move still has at least one attacker left.
1659 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1662 // Remove the attacker we just found from the 'attackers' bitboard,
1663 // and scan for new X-ray attacks behind the attacker.
1664 b = attackers & pieces_of_color_and_type(c, pt);
1666 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1667 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1671 // Add the new entry to the swap list
1673 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1676 // Remember the value of the capturing piece, and change the side to move
1677 // before beginning the next iteration
1678 lastCapturingPieceValue = seeValues[pt];
1679 c = opposite_color(c);
1681 // Remove pinned pieces from attackers
1682 if ( pinned[c] != EmptyBoardBB
1683 && !bit_is_set(pinners[c], to)
1684 && !(pinners[c] & attackers))
1685 attackers &= ~pinned[c];
1687 // Stop after a king capture
1688 if (pt == KING && (attackers & pieces_of_color(c)))
1691 swapList[n++] = 100;
1694 } while (attackers & pieces_of_color(c));
1696 // Having built the swap list, we negamax through it to find the best
1697 // achievable score from the point of view of the side to move
1699 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1705 /// Position::setStartState() copies the content of the argument
1706 /// inside startState and makes st point to it. This is needed
1707 /// when the st pointee could become stale, as example because
1708 /// the caller is about to going out of scope.
1710 void Position::setStartState(const StateInfo& s) {
1717 /// Position::clear() erases the position object to a pristine state, with an
1718 /// empty board, white to move, and no castling rights.
1720 void Position::clear() {
1723 memset(st, 0, sizeof(StateInfo));
1724 st->epSquare = SQ_NONE;
1726 memset(index, 0, sizeof(int) * 64);
1727 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1729 for (int i = 0; i < 64; i++)
1732 for (int i = 0; i < 7; i++)
1734 byTypeBB[i] = EmptyBoardBB;
1735 pieceCount[0][i] = pieceCount[1][i] = 0;
1736 for (int j = 0; j < 8; j++)
1737 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1742 initialKFile = FILE_E;
1743 initialKRFile = FILE_H;
1744 initialQRFile = FILE_A;
1748 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1749 /// UCI interface code, whenever a non-reversible move is made in a
1750 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1751 /// for the program to handle games of arbitrary length, as long as the GUI
1752 /// handles draws by the 50 move rule correctly.
1754 void Position::reset_game_ply() {
1760 /// Position::put_piece() puts a piece on the given square of the board,
1761 /// updating the board array, bitboards, and piece counts.
1763 void Position::put_piece(Piece p, Square s) {
1765 Color c = color_of_piece(p);
1766 PieceType pt = type_of_piece(p);
1769 index[s] = pieceCount[c][pt];
1770 pieceList[c][pt][index[s]] = s;
1772 set_bit(&(byTypeBB[pt]), s);
1773 set_bit(&(byColorBB[c]), s);
1774 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1776 pieceCount[c][pt]++;
1783 /// Position::allow_oo() gives the given side the right to castle kingside.
1784 /// Used when setting castling rights during parsing of FEN strings.
1786 void Position::allow_oo(Color c) {
1788 st->castleRights |= (1 + int(c));
1792 /// Position::allow_ooo() gives the given side the right to castle queenside.
1793 /// Used when setting castling rights during parsing of FEN strings.
1795 void Position::allow_ooo(Color c) {
1797 st->castleRights |= (4 + 4*int(c));
1801 /// Position::compute_key() computes the hash key of the position. The hash
1802 /// key is usually updated incrementally as moves are made and unmade, the
1803 /// compute_key() function is only used when a new position is set up, and
1804 /// to verify the correctness of the hash key when running in debug mode.
1806 Key Position::compute_key() const {
1808 Key result = Key(0ULL);
1810 for (Square s = SQ_A1; s <= SQ_H8; s++)
1811 if (square_is_occupied(s))
1812 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1814 if (ep_square() != SQ_NONE)
1815 result ^= zobEp[ep_square()];
1817 result ^= zobCastle[st->castleRights];
1818 if (side_to_move() == BLACK)
1819 result ^= zobSideToMove;
1825 /// Position::compute_pawn_key() computes the hash key of the position. The
1826 /// hash key is usually updated incrementally as moves are made and unmade,
1827 /// the compute_pawn_key() function is only used when a new position is set
1828 /// up, and to verify the correctness of the pawn hash key when running in
1831 Key Position::compute_pawn_key() const {
1833 Key result = Key(0ULL);
1837 for (Color c = WHITE; c <= BLACK; c++)
1842 s = pop_1st_bit(&b);
1843 result ^= zobrist[c][PAWN][s];
1850 /// Position::compute_material_key() computes the hash key of the position.
1851 /// The hash key is usually updated incrementally as moves are made and unmade,
1852 /// the compute_material_key() function is only used when a new position is set
1853 /// up, and to verify the correctness of the material hash key when running in
1856 Key Position::compute_material_key() const {
1858 Key result = Key(0ULL);
1859 for (Color c = WHITE; c <= BLACK; c++)
1860 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1862 int count = piece_count(c, pt);
1863 for (int i = 0; i <= count; i++)
1864 result ^= zobMaterial[c][pt][i];
1870 /// Position::compute_value() compute the incremental scores for the middle
1871 /// game and the endgame. These functions are used to initialize the incremental
1872 /// scores when a new position is set up, and to verify that the scores are correctly
1873 /// updated by do_move and undo_move when the program is running in debug mode.
1874 template<Position::GamePhase Phase>
1875 Value Position::compute_value() const {
1877 Value result = Value(0);
1881 for (Color c = WHITE; c <= BLACK; c++)
1882 for (PieceType pt = PAWN; pt <= KING; pt++)
1884 b = pieces_of_color_and_type(c, pt);
1887 s = pop_1st_bit(&b);
1888 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1889 result += pst<Phase>(c, pt, s);
1893 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1894 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1899 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1900 /// game material score for the given side. Material scores are updated
1901 /// incrementally during the search, this function is only used while
1902 /// initializing a new Position object.
1904 Value Position::compute_non_pawn_material(Color c) const {
1906 Value result = Value(0);
1909 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1911 Bitboard b = pieces_of_color_and_type(c, pt);
1914 s = pop_1st_bit(&b);
1915 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1916 result += piece_value_midgame(pt);
1923 /// Position::is_mate() returns true or false depending on whether the
1924 /// side to move is checkmated. Note that this function is currently very
1925 /// slow, and shouldn't be used frequently inside the search.
1927 bool Position::is_mate() const {
1931 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1932 return mp.get_next_move() == MOVE_NONE;
1938 /// Position::is_draw() tests whether the position is drawn by material,
1939 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1940 /// must be done by the search.
1942 bool Position::is_draw() const {
1944 // Draw by material?
1946 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1949 // Draw by the 50 moves rule?
1950 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1953 // Draw by repetition?
1954 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1955 if (history[gamePly - i] == st->key)
1962 /// Position::has_mate_threat() tests whether a given color has a mate in one
1963 /// from the current position. This function is quite slow, but it doesn't
1964 /// matter, because it is currently only called from PV nodes, which are rare.
1966 bool Position::has_mate_threat(Color c) {
1969 Color stm = side_to_move();
1971 // The following lines are useless and silly, but prevents gcc from
1972 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1973 // be used uninitialized.
1974 st1.lastMove = st->lastMove;
1975 st1.epSquare = st->epSquare;
1980 // If the input color is not equal to the side to move, do a null move
1984 MoveStack mlist[120];
1986 bool result = false;
1988 // Generate legal moves
1989 count = generate_legal_moves(*this, mlist);
1991 // Loop through the moves, and see if one of them is mate
1992 for (int i = 0; i < count; i++)
1994 do_move(mlist[i].move, st2);
1998 undo_move(mlist[i].move);
2001 // Undo null move, if necessary
2009 /// Position::init_zobrist() is a static member function which initializes the
2010 /// various arrays used to compute hash keys.
2012 void Position::init_zobrist() {
2014 for (int i = 0; i < 2; i++)
2015 for (int j = 0; j < 8; j++)
2016 for (int k = 0; k < 64; k++)
2017 zobrist[i][j][k] = Key(genrand_int64());
2019 for (int i = 0; i < 64; i++)
2020 zobEp[i] = Key(genrand_int64());
2022 for (int i = 0; i < 16; i++)
2023 zobCastle[i] = genrand_int64();
2025 zobSideToMove = genrand_int64();
2027 for (int i = 0; i < 2; i++)
2028 for (int j = 0; j < 8; j++)
2029 for (int k = 0; k < 16; k++)
2030 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2032 for (int i = 0; i < 16; i++)
2033 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2037 /// Position::init_piece_square_tables() initializes the piece square tables.
2038 /// This is a two-step operation: First, the white halves of the tables are
2039 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2040 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2041 /// Second, the black halves of the tables are initialized by mirroring
2042 /// and changing the sign of the corresponding white scores.
2044 void Position::init_piece_square_tables() {
2046 int r = get_option_value_int("Randomness"), i;
2047 for (Square s = SQ_A1; s <= SQ_H8; s++)
2048 for (Piece p = WP; p <= WK; p++)
2050 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2051 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2052 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2055 for (Square s = SQ_A1; s <= SQ_H8; s++)
2056 for (Piece p = BP; p <= BK; p++)
2058 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2059 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2064 /// Position::flipped_copy() makes a copy of the input position, but with
2065 /// the white and black sides reversed. This is only useful for debugging,
2066 /// especially for finding evaluation symmetry bugs.
2068 void Position::flipped_copy(const Position &pos) {
2070 assert(pos.is_ok());
2075 for (Square s = SQ_A1; s <= SQ_H8; s++)
2076 if (!pos.square_is_empty(s))
2077 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2080 sideToMove = opposite_color(pos.side_to_move());
2083 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2084 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2085 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2086 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2088 initialKFile = pos.initialKFile;
2089 initialKRFile = pos.initialKRFile;
2090 initialQRFile = pos.initialQRFile;
2092 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2093 castleRightsMask[sq] = ALL_CASTLES;
2095 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2096 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2097 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2098 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2099 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2100 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2102 // En passant square
2103 if (pos.st->epSquare != SQ_NONE)
2104 st->epSquare = flip_square(pos.st->epSquare);
2110 st->key = compute_key();
2111 st->pawnKey = compute_pawn_key();
2112 st->materialKey = compute_material_key();
2114 // Incremental scores
2115 st->mgValue = compute_value<MidGame>();
2116 st->egValue = compute_value<EndGame>();
2119 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2120 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2126 /// Position::is_ok() performs some consitency checks for the position object.
2127 /// This is meant to be helpful when debugging.
2129 bool Position::is_ok(int* failedStep) const {
2131 // What features of the position should be verified?
2132 static const bool debugBitboards = false;
2133 static const bool debugKingCount = false;
2134 static const bool debugKingCapture = false;
2135 static const bool debugCheckerCount = false;
2136 static const bool debugKey = false;
2137 static const bool debugMaterialKey = false;
2138 static const bool debugPawnKey = false;
2139 static const bool debugIncrementalEval = false;
2140 static const bool debugNonPawnMaterial = false;
2141 static const bool debugPieceCounts = false;
2142 static const bool debugPieceList = false;
2144 if (failedStep) *failedStep = 1;
2147 if (!color_is_ok(side_to_move()))
2150 // Are the king squares in the position correct?
2151 if (failedStep) (*failedStep)++;
2152 if (piece_on(king_square(WHITE)) != WK)
2155 if (failedStep) (*failedStep)++;
2156 if (piece_on(king_square(BLACK)) != BK)
2160 if (failedStep) (*failedStep)++;
2161 if (!file_is_ok(initialKRFile))
2164 if (!file_is_ok(initialQRFile))
2167 // Do both sides have exactly one king?
2168 if (failedStep) (*failedStep)++;
2171 int kingCount[2] = {0, 0};
2172 for (Square s = SQ_A1; s <= SQ_H8; s++)
2173 if (type_of_piece_on(s) == KING)
2174 kingCount[color_of_piece_on(s)]++;
2176 if (kingCount[0] != 1 || kingCount[1] != 1)
2180 // Can the side to move capture the opponent's king?
2181 if (failedStep) (*failedStep)++;
2182 if (debugKingCapture)
2184 Color us = side_to_move();
2185 Color them = opposite_color(us);
2186 Square ksq = king_square(them);
2187 if (square_is_attacked(ksq, us))
2191 // Is there more than 2 checkers?
2192 if (failedStep) (*failedStep)++;
2193 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2197 if (failedStep) (*failedStep)++;
2200 // The intersection of the white and black pieces must be empty
2201 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2204 // The union of the white and black pieces must be equal to all
2206 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2209 // Separate piece type bitboards must have empty intersections
2210 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2211 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2212 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2216 // En passant square OK?
2217 if (failedStep) (*failedStep)++;
2218 if (ep_square() != SQ_NONE)
2220 // The en passant square must be on rank 6, from the point of view of the
2222 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2227 if (failedStep) (*failedStep)++;
2228 if (debugKey && st->key != compute_key())
2231 // Pawn hash key OK?
2232 if (failedStep) (*failedStep)++;
2233 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2236 // Material hash key OK?
2237 if (failedStep) (*failedStep)++;
2238 if (debugMaterialKey && st->materialKey != compute_material_key())
2241 // Incremental eval OK?
2242 if (failedStep) (*failedStep)++;
2243 if (debugIncrementalEval)
2245 if (st->mgValue != compute_value<MidGame>())
2248 if (st->egValue != compute_value<EndGame>())
2252 // Non-pawn material OK?
2253 if (failedStep) (*failedStep)++;
2254 if (debugNonPawnMaterial)
2256 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2259 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2264 if (failedStep) (*failedStep)++;
2265 if (debugPieceCounts)
2266 for (Color c = WHITE; c <= BLACK; c++)
2267 for (PieceType pt = PAWN; pt <= KING; pt++)
2268 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2271 if (failedStep) (*failedStep)++;
2274 for(Color c = WHITE; c <= BLACK; c++)
2275 for(PieceType pt = PAWN; pt <= KING; pt++)
2276 for(int i = 0; i < pieceCount[c][pt]; i++)
2278 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2281 if (index[piece_list(c, pt, i)] != i)
2285 if (failedStep) *failedStep = 0;