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, unsigned int types) {
457 Color them = opposite_color(us);
458 Square ksq = king_square(them);
461 st->pinned[them] = hidden_checks<ROOK, true>(them, ksq, p1) | hidden_checks<BISHOP, true>(them, ksq, p2);
462 st->pinners[them] = p1 | p2;
464 if (types & DcCandidates)
465 st->dcCandidates[us] = hidden_checks<ROOK, false>(us, ksq, p1) | hidden_checks<BISHOP, false>(us, ksq, p2);
468 void Position::find_hidden_checks() {
470 for (Color c = WHITE; c <= BLACK; c++)
471 find_hidden_checks(c, Pinned | DcCandidates);
475 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
477 bool Position::pl_move_is_legal(Move m) const {
480 assert(move_is_ok(m));
482 // If we're in check, all pseudo-legal moves are legal, because our
483 // check evasion generator only generates true legal moves.
487 // Castling moves are checked for legality during move generation.
488 if (move_is_castle(m))
491 Color us = side_to_move();
492 Color them = opposite_color(us);
493 Square from = move_from(m);
494 Square ksq = king_square(us);
496 assert(color_of_piece_on(from) == us);
497 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
499 // En passant captures are a tricky special case. Because they are
500 // rather uncommon, we do it simply by testing whether the king is attacked
501 // after the move is made
504 Square to = move_to(m);
505 Square capsq = make_square(square_file(to), square_rank(from));
506 Bitboard b = occupied_squares();
508 assert(to == ep_square());
509 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
510 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
511 assert(piece_on(to) == EMPTY);
514 clear_bit(&b, capsq);
517 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
518 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
521 // If the moving piece is a king, check whether the destination
522 // square is attacked by the opponent.
524 return !(square_is_attacked(move_to(m), them));
526 // A non-king move is legal if and only if it is not pinned or it
527 // is moving along the ray towards or away from the king.
528 return ( !bit_is_set(pinned_pieces(us), from)
529 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
533 /// Position::move_is_check() tests whether a pseudo-legal move is a check
535 bool Position::move_is_check(Move m) const {
538 assert(move_is_ok(m));
540 Color us = side_to_move();
541 Color them = opposite_color(us);
542 Square from = move_from(m);
543 Square to = move_to(m);
544 Square ksq = king_square(them);
545 Bitboard dcCandidates = discovered_check_candidates(us);
547 assert(color_of_piece_on(from) == us);
548 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
550 // Proceed according to the type of the moving piece
551 switch (type_of_piece_on(from))
555 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
558 if ( bit_is_set(dcCandidates, from) // Discovered check?
559 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
562 if (move_promotion(m)) // Promotion with check?
564 Bitboard b = occupied_squares();
567 switch (move_promotion(m))
570 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
572 return bit_is_set(bishop_attacks_bb(to, b), ksq);
574 return bit_is_set(rook_attacks_bb(to, b), ksq);
576 return bit_is_set(queen_attacks_bb(to, b), ksq);
581 // En passant capture with check? We have already handled the case
582 // of direct checks and ordinary discovered check, the only case we
583 // need to handle is the unusual case of a discovered check through the
585 else if (move_is_ep(m))
587 Square capsq = make_square(square_file(to), square_rank(from));
588 Bitboard b = occupied_squares();
590 clear_bit(&b, capsq);
592 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
593 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
598 return bit_is_set(dcCandidates, from) // Discovered check?
599 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
602 return bit_is_set(dcCandidates, from) // Discovered check?
603 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
606 return bit_is_set(dcCandidates, from) // Discovered check?
607 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
610 // Discovered checks are impossible!
611 assert(!bit_is_set(dcCandidates, from));
612 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
616 if ( bit_is_set(dcCandidates, from)
617 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
620 // Castling with check?
621 if (move_is_castle(m))
623 Square kfrom, kto, rfrom, rto;
624 Bitboard b = occupied_squares();
630 kto = relative_square(us, SQ_G1);
631 rto = relative_square(us, SQ_F1);
633 kto = relative_square(us, SQ_C1);
634 rto = relative_square(us, SQ_D1);
636 clear_bit(&b, kfrom);
637 clear_bit(&b, rfrom);
640 return bit_is_set(rook_attacks_bb(rto, b), ksq);
644 default: // NO_PIECE_TYPE
652 /// Position::move_is_capture() tests whether a move from the current
653 /// position is a capture. Move must not be MOVE_NONE.
655 bool Position::move_is_capture(Move m) const {
657 assert(m != MOVE_NONE);
659 return ( !square_is_empty(move_to(m))
660 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
666 /// Position::update_checkers() udpates chekers info given the move. It is called
667 /// in do_move() and is faster then find_checkers().
669 template<PieceType Piece>
670 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
671 Square to, Bitboard dcCandidates) {
673 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
674 set_bit(pCheckersBB, to);
676 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
679 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
682 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
687 /// Position::update_hidden_checks() udpates pinned, pinners and dcCandidates
688 /// bitboards incrementally, given the move. It is called in do_move and is
689 /// faster then find_hidden_checks().
691 void Position::update_hidden_checks(Square from, Square to) {
693 Color us = sideToMove;
694 Color them = opposite_color(us);
695 Square ksq = king_square(opposite_color(us));
697 Bitboard moveSquares = EmptyBoardBB;
698 set_bit(&moveSquares, from);
699 set_bit(&moveSquares, to);
701 // Our moving piece could have been a possible pinner or hidden checker behind a dcCandidates?
702 bool checkerMoved = (st->dcCandidates[us] | st->pinners[them]) && (moveSquares & sliders());
704 // If we are moving from/to an opponent king attack direction and we was a possible hidden checker
705 // or there exsist some possible hidden checker on that line then recalculate the position
706 // otherwise skip because our dcCandidates and opponent pinned pieces are not changed.
707 if ( (moveSquares & RookPseudoAttacks[ksq]) && (checkerMoved || (rooks_and_queens(us) & RookPseudoAttacks[ksq]))
708 || (moveSquares & BishopPseudoAttacks[ksq]) && (checkerMoved || (bishops_and_queens(us) & BishopPseudoAttacks[ksq])))
709 find_hidden_checks(us, Pinned | DcCandidates);
711 ksq = king_square(us);
715 find_hidden_checks(them, Pinned | DcCandidates);
719 // It is possible that we have captured an opponent hidden checker?
720 Bitboard checkerCaptured = st->capture && (st->dcCandidates[them] || bit_is_set(st->pinners[us], to));
722 // If we are moving from/to an our king attack direction and there was/is some possible
723 // opponent hidden checker then calculate the position otherwise skip because opponent
724 // dcCandidates and our pinned pieces are not changed.
725 if ( (moveSquares & RookPseudoAttacks[ksq]) && (checkerCaptured || (rooks_and_queens(them) & RookPseudoAttacks[ksq]))
726 || (moveSquares & BishopPseudoAttacks[ksq]) && (checkerCaptured || (bishops_and_queens(them) & BishopPseudoAttacks[ksq])))
729 // If we don't have opponent dc candidates and we are moving in the
730 // attack line then won't be dc candidates also after the move.
731 if ( st->dcCandidates[them]
732 || bit_is_set(RookPseudoAttacks[ksq], from)
733 || bit_is_set(BishopPseudoAttacks[ksq], from))
735 find_hidden_checks(them, Pinned | DcCandidates);
737 find_hidden_checks(them, Pinned);
742 /// Position::do_move() makes a move, and saves all information necessary
743 /// to a StateInfo object. The move is assumed to be legal.
744 /// Pseudo-legal moves should be filtered out before this function is called.
746 void Position::do_move(Move m, StateInfo& newSt) {
749 assert(move_is_ok(m));
751 // Get now the current (before to move) dc candidates that we will use
752 // in update_checkers().
753 Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
755 // Copy some fields of old state to our new StateInfo object (except the
756 // captured piece, which is taken care of later) and switch state pointer
757 // to point to the new, ready to be updated, state.
759 newSt.capture = NO_PIECE_TYPE;
763 // Save the current key to the history[] array, in order to be able to
764 // detect repetition draws.
765 history[gamePly] = st->key;
767 // Increment the 50 moves rule draw counter. Resetting it to zero in the
768 // case of non-reversible moves is taken care of later.
771 if (move_is_castle(m))
773 else if (move_promotion(m))
774 do_promotion_move(m);
775 else if (move_is_ep(m))
779 Color us = side_to_move();
780 Color them = opposite_color(us);
781 Square from = move_from(m);
782 Square to = move_to(m);
784 assert(color_of_piece_on(from) == us);
785 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
787 PieceType piece = type_of_piece_on(from);
789 st->capture = type_of_piece_on(to);
792 do_capture_move(m, st->capture, them, to);
795 clear_bit(&(byColorBB[us]), from);
796 clear_bit(&(byTypeBB[piece]), from);
797 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
798 set_bit(&(byColorBB[us]), to);
799 set_bit(&(byTypeBB[piece]), to);
800 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
801 board[to] = board[from];
805 st->key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
807 // Update incremental scores
808 st->mgValue -= pst<MidGame>(us, piece, from);
809 st->mgValue += pst<MidGame>(us, piece, to);
810 st->egValue -= pst<EndGame>(us, piece, from);
811 st->egValue += pst<EndGame>(us, piece, to);
813 // If the moving piece was a king, update the king square
817 // Reset en passant square
818 if (st->epSquare != SQ_NONE)
820 st->key ^= zobEp[st->epSquare];
821 st->epSquare = SQ_NONE;
824 // If the moving piece was a pawn do some special extra work
827 // Reset rule 50 draw counter
830 // Update pawn hash key
831 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
833 // Set en passant square, only if moved pawn can be captured
834 if (abs(int(to) - int(from)) == 16)
836 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
837 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
839 st->epSquare = Square((int(from) + int(to)) / 2);
840 st->key ^= zobEp[st->epSquare];
845 // Update piece lists
846 pieceList[us][piece][index[from]] = to;
847 index[to] = index[from];
849 // Update castle rights
850 st->key ^= zobCastle[st->castleRights];
851 st->castleRights &= castleRightsMask[from];
852 st->castleRights &= castleRightsMask[to];
853 st->key ^= zobCastle[st->castleRights];
855 // Update checkers bitboard, piece must be already moved
856 st->checkersBB = EmptyBoardBB;
857 Square ksq = king_square(them);
860 case PAWN: update_checkers<PAWN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
861 case KNIGHT: update_checkers<KNIGHT>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
862 case BISHOP: update_checkers<BISHOP>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
863 case ROOK: update_checkers<ROOK>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
864 case QUEEN: update_checkers<QUEEN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
865 case KING: update_checkers<KING>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
866 default: assert(false); break;
869 update_hidden_checks(from, to);
873 st->key ^= zobSideToMove;
874 sideToMove = opposite_color(sideToMove);
877 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
878 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
884 /// Position::do_capture_move() is a private method used to update captured
885 /// piece info. It is called from the main Position::do_move function.
887 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
889 assert(capture != KING);
891 // Remove captured piece
892 clear_bit(&(byColorBB[them]), to);
893 clear_bit(&(byTypeBB[capture]), to);
896 st->key ^= zobrist[them][capture][to];
898 // If the captured piece was a pawn, update pawn hash key
900 st->pawnKey ^= zobrist[them][PAWN][to];
902 // Update incremental scores
903 st->mgValue -= pst<MidGame>(them, capture, to);
904 st->egValue -= pst<EndGame>(them, capture, to);
906 assert(!move_promotion(m) || capture != PAWN);
910 npMaterial[them] -= piece_value_midgame(capture);
912 // Update material hash key
913 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
915 // Update piece count
916 pieceCount[them][capture]--;
919 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
920 index[pieceList[them][capture][index[to]]] = index[to];
922 // Reset rule 50 counter
927 /// Position::do_castle_move() is a private method used to make a castling
928 /// move. It is called from the main Position::do_move function. Note that
929 /// castling moves are encoded as "king captures friendly rook" moves, for
930 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
932 void Position::do_castle_move(Move m) {
935 assert(move_is_ok(m));
936 assert(move_is_castle(m));
938 Color us = side_to_move();
939 Color them = opposite_color(us);
941 // Find source squares for king and rook
942 Square kfrom = move_from(m);
943 Square rfrom = move_to(m); // HACK: See comment at beginning of function
946 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
947 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
949 // Find destination squares for king and rook
950 if (rfrom > kfrom) // O-O
952 kto = relative_square(us, SQ_G1);
953 rto = relative_square(us, SQ_F1);
955 kto = relative_square(us, SQ_C1);
956 rto = relative_square(us, SQ_D1);
959 // Remove pieces from source squares
960 clear_bit(&(byColorBB[us]), kfrom);
961 clear_bit(&(byTypeBB[KING]), kfrom);
962 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
963 clear_bit(&(byColorBB[us]), rfrom);
964 clear_bit(&(byTypeBB[ROOK]), rfrom);
965 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
967 // Put pieces on destination squares
968 set_bit(&(byColorBB[us]), kto);
969 set_bit(&(byTypeBB[KING]), kto);
970 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
971 set_bit(&(byColorBB[us]), rto);
972 set_bit(&(byTypeBB[ROOK]), rto);
973 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
975 // Update board array
976 board[kfrom] = board[rfrom] = EMPTY;
977 board[kto] = piece_of_color_and_type(us, KING);
978 board[rto] = piece_of_color_and_type(us, ROOK);
980 // Update king square
981 kingSquare[us] = kto;
983 // Update piece lists
984 pieceList[us][KING][index[kfrom]] = kto;
985 pieceList[us][ROOK][index[rfrom]] = rto;
986 int tmp = index[rfrom];
987 index[kto] = index[kfrom];
990 // Update incremental scores
991 st->mgValue -= pst<MidGame>(us, KING, kfrom);
992 st->mgValue += pst<MidGame>(us, KING, kto);
993 st->egValue -= pst<EndGame>(us, KING, kfrom);
994 st->egValue += pst<EndGame>(us, KING, kto);
995 st->mgValue -= pst<MidGame>(us, ROOK, rfrom);
996 st->mgValue += pst<MidGame>(us, ROOK, rto);
997 st->egValue -= pst<EndGame>(us, ROOK, rfrom);
998 st->egValue += pst<EndGame>(us, ROOK, rto);
1001 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1002 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1004 // Clear en passant square
1005 if (st->epSquare != SQ_NONE)
1007 st->key ^= zobEp[st->epSquare];
1008 st->epSquare = SQ_NONE;
1011 // Update castling rights
1012 st->key ^= zobCastle[st->castleRights];
1013 st->castleRights &= castleRightsMask[kfrom];
1014 st->key ^= zobCastle[st->castleRights];
1016 // Reset rule 50 counter
1019 // Update checkers BB
1020 st->checkersBB = attacks_to(king_square(them), us);
1022 // Update hidden checks
1023 find_hidden_checks();
1027 /// Position::do_promotion_move() is a private method used to make a promotion
1028 /// move. It is called from the main Position::do_move function.
1030 void Position::do_promotion_move(Move m) {
1034 PieceType promotion;
1037 assert(move_is_ok(m));
1038 assert(move_promotion(m));
1040 us = side_to_move();
1041 them = opposite_color(us);
1042 from = move_from(m);
1045 assert(relative_rank(us, to) == RANK_8);
1046 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1047 assert(color_of_piece_on(to) == them || square_is_empty(to));
1049 st->capture = type_of_piece_on(to);
1052 do_capture_move(m, st->capture, them, to);
1055 clear_bit(&(byColorBB[us]), from);
1056 clear_bit(&(byTypeBB[PAWN]), from);
1057 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1058 board[from] = EMPTY;
1060 // Insert promoted piece
1061 promotion = move_promotion(m);
1062 assert(promotion >= KNIGHT && promotion <= QUEEN);
1063 set_bit(&(byColorBB[us]), to);
1064 set_bit(&(byTypeBB[promotion]), to);
1065 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1066 board[to] = piece_of_color_and_type(us, promotion);
1069 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1071 // Update pawn hash key
1072 st->pawnKey ^= zobrist[us][PAWN][from];
1074 // Update material key
1075 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1076 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1078 // Update piece counts
1079 pieceCount[us][PAWN]--;
1080 pieceCount[us][promotion]++;
1082 // Update piece lists
1083 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1084 index[pieceList[us][PAWN][index[from]]] = index[from];
1085 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1086 index[to] = pieceCount[us][promotion] - 1;
1088 // Update incremental scores
1089 st->mgValue -= pst<MidGame>(us, PAWN, from);
1090 st->mgValue += pst<MidGame>(us, promotion, to);
1091 st->egValue -= pst<EndGame>(us, PAWN, from);
1092 st->egValue += pst<EndGame>(us, promotion, to);
1095 npMaterial[us] += piece_value_midgame(promotion);
1097 // Clear the en passant square
1098 if (st->epSquare != SQ_NONE)
1100 st->key ^= zobEp[st->epSquare];
1101 st->epSquare = SQ_NONE;
1104 // Update castle rights
1105 st->key ^= zobCastle[st->castleRights];
1106 st->castleRights &= castleRightsMask[to];
1107 st->key ^= zobCastle[st->castleRights];
1109 // Reset rule 50 counter
1112 // Update checkers BB
1113 st->checkersBB = attacks_to(king_square(them), us);
1115 // Update hidden checks
1116 find_hidden_checks();
1120 /// Position::do_ep_move() is a private method used to make an en passant
1121 /// capture. It is called from the main Position::do_move function.
1123 void Position::do_ep_move(Move m) {
1126 Square from, to, capsq;
1129 assert(move_is_ok(m));
1130 assert(move_is_ep(m));
1132 us = side_to_move();
1133 them = opposite_color(us);
1134 from = move_from(m);
1136 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1138 assert(to == st->epSquare);
1139 assert(relative_rank(us, to) == RANK_6);
1140 assert(piece_on(to) == EMPTY);
1141 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1142 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1144 // Remove captured piece
1145 clear_bit(&(byColorBB[them]), capsq);
1146 clear_bit(&(byTypeBB[PAWN]), capsq);
1147 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1148 board[capsq] = EMPTY;
1150 // Remove moving piece from source square
1151 clear_bit(&(byColorBB[us]), from);
1152 clear_bit(&(byTypeBB[PAWN]), from);
1153 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1155 // Put moving piece on destination square
1156 set_bit(&(byColorBB[us]), to);
1157 set_bit(&(byTypeBB[PAWN]), to);
1158 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1159 board[to] = board[from];
1160 board[from] = EMPTY;
1162 // Update material hash key
1163 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1165 // Update piece count
1166 pieceCount[them][PAWN]--;
1168 // Update piece list
1169 pieceList[us][PAWN][index[from]] = to;
1170 index[to] = index[from];
1171 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1172 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1175 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1176 st->key ^= zobrist[them][PAWN][capsq];
1177 st->key ^= zobEp[st->epSquare];
1179 // Update pawn hash key
1180 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1181 st->pawnKey ^= zobrist[them][PAWN][capsq];
1183 // Update incremental scores
1184 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1185 st->mgValue -= pst<MidGame>(us, PAWN, from);
1186 st->mgValue += pst<MidGame>(us, PAWN, to);
1187 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1188 st->egValue -= pst<EndGame>(us, PAWN, from);
1189 st->egValue += pst<EndGame>(us, PAWN, to);
1191 // Reset en passant square
1192 st->epSquare = SQ_NONE;
1194 // Reset rule 50 counter
1197 // Update checkers BB
1198 st->checkersBB = attacks_to(king_square(them), us);
1200 // Update hidden checks
1201 find_hidden_checks();
1205 /// Position::undo_move() unmakes a move. When it returns, the position should
1206 /// be restored to exactly the same state as before the move was made.
1208 void Position::undo_move(Move m) {
1211 assert(move_is_ok(m));
1214 sideToMove = opposite_color(sideToMove);
1216 if (move_is_castle(m))
1217 undo_castle_move(m);
1218 else if (move_promotion(m))
1219 undo_promotion_move(m);
1220 else if (move_is_ep(m))
1228 us = side_to_move();
1229 them = opposite_color(us);
1230 from = move_from(m);
1233 assert(piece_on(from) == EMPTY);
1234 assert(color_of_piece_on(to) == us);
1236 // Put the piece back at the source square
1237 piece = type_of_piece_on(to);
1238 set_bit(&(byColorBB[us]), from);
1239 set_bit(&(byTypeBB[piece]), from);
1240 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1241 board[from] = piece_of_color_and_type(us, piece);
1243 // Clear the destination square
1244 clear_bit(&(byColorBB[us]), to);
1245 clear_bit(&(byTypeBB[piece]), to);
1246 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1248 // If the moving piece was a king, update the king square
1250 kingSquare[us] = from;
1252 // Update piece list
1253 pieceList[us][piece][index[to]] = from;
1254 index[from] = index[to];
1258 assert(st->capture != KING);
1260 // Replace the captured piece
1261 set_bit(&(byColorBB[them]), to);
1262 set_bit(&(byTypeBB[st->capture]), to);
1263 set_bit(&(byTypeBB[0]), to);
1264 board[to] = piece_of_color_and_type(them, st->capture);
1267 if (st->capture != PAWN)
1268 npMaterial[them] += piece_value_midgame(st->capture);
1270 // Update piece list
1271 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1272 index[to] = pieceCount[them][st->capture];
1274 // Update piece count
1275 pieceCount[them][st->capture]++;
1280 // Finally point out state pointer back to the previous state
1287 /// Position::undo_castle_move() is a private method used to unmake a castling
1288 /// move. It is called from the main Position::undo_move function. Note that
1289 /// castling moves are encoded as "king captures friendly rook" moves, for
1290 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1292 void Position::undo_castle_move(Move m) {
1294 assert(move_is_ok(m));
1295 assert(move_is_castle(m));
1297 // When we have arrived here, some work has already been done by
1298 // Position::undo_move. In particular, the side to move has been switched,
1299 // so the code below is correct.
1300 Color us = side_to_move();
1302 // Find source squares for king and rook
1303 Square kfrom = move_from(m);
1304 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1307 // Find destination squares for king and rook
1308 if (rfrom > kfrom) // O-O
1310 kto = relative_square(us, SQ_G1);
1311 rto = relative_square(us, SQ_F1);
1313 kto = relative_square(us, SQ_C1);
1314 rto = relative_square(us, SQ_D1);
1317 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1318 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1320 // Remove pieces from destination squares
1321 clear_bit(&(byColorBB[us]), kto);
1322 clear_bit(&(byTypeBB[KING]), kto);
1323 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1324 clear_bit(&(byColorBB[us]), rto);
1325 clear_bit(&(byTypeBB[ROOK]), rto);
1326 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1328 // Put pieces on source squares
1329 set_bit(&(byColorBB[us]), kfrom);
1330 set_bit(&(byTypeBB[KING]), kfrom);
1331 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1332 set_bit(&(byColorBB[us]), rfrom);
1333 set_bit(&(byTypeBB[ROOK]), rfrom);
1334 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1337 board[rto] = board[kto] = EMPTY;
1338 board[rfrom] = piece_of_color_and_type(us, ROOK);
1339 board[kfrom] = piece_of_color_and_type(us, KING);
1341 // Update king square
1342 kingSquare[us] = kfrom;
1344 // Update piece lists
1345 pieceList[us][KING][index[kto]] = kfrom;
1346 pieceList[us][ROOK][index[rto]] = rfrom;
1347 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1348 index[kfrom] = index[kto];
1353 /// Position::undo_promotion_move() is a private method used to unmake a
1354 /// promotion move. It is called from the main Position::do_move
1357 void Position::undo_promotion_move(Move m) {
1361 PieceType promotion;
1363 assert(move_is_ok(m));
1364 assert(move_promotion(m));
1366 // When we have arrived here, some work has already been done by
1367 // Position::undo_move. In particular, the side to move has been switched,
1368 // so the code below is correct.
1369 us = side_to_move();
1370 them = opposite_color(us);
1371 from = move_from(m);
1374 assert(relative_rank(us, to) == RANK_8);
1375 assert(piece_on(from) == EMPTY);
1377 // Remove promoted piece
1378 promotion = move_promotion(m);
1379 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1380 assert(promotion >= KNIGHT && promotion <= QUEEN);
1381 clear_bit(&(byColorBB[us]), to);
1382 clear_bit(&(byTypeBB[promotion]), to);
1383 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1385 // Insert pawn at source square
1386 set_bit(&(byColorBB[us]), from);
1387 set_bit(&(byTypeBB[PAWN]), from);
1388 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1389 board[from] = piece_of_color_and_type(us, PAWN);
1392 npMaterial[us] -= piece_value_midgame(promotion);
1394 // Update piece list
1395 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1396 index[from] = pieceCount[us][PAWN];
1397 pieceList[us][promotion][index[to]] =
1398 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1399 index[pieceList[us][promotion][index[to]]] = index[to];
1401 // Update piece counts
1402 pieceCount[us][promotion]--;
1403 pieceCount[us][PAWN]++;
1407 assert(st->capture != KING);
1409 // Insert captured piece:
1410 set_bit(&(byColorBB[them]), to);
1411 set_bit(&(byTypeBB[st->capture]), to);
1412 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1413 board[to] = piece_of_color_and_type(them, st->capture);
1415 // Update material. Because the move is a promotion move, we know
1416 // that the captured piece cannot be a pawn.
1417 assert(st->capture != PAWN);
1418 npMaterial[them] += piece_value_midgame(st->capture);
1420 // Update piece list
1421 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1422 index[to] = pieceCount[them][st->capture];
1424 // Update piece count
1425 pieceCount[them][st->capture]++;
1431 /// Position::undo_ep_move() is a private method used to unmake an en passant
1432 /// capture. It is called from the main Position::undo_move function.
1434 void Position::undo_ep_move(Move m) {
1436 assert(move_is_ok(m));
1437 assert(move_is_ep(m));
1439 // When we have arrived here, some work has already been done by
1440 // Position::undo_move. In particular, the side to move has been switched,
1441 // so the code below is correct.
1442 Color us = side_to_move();
1443 Color them = opposite_color(us);
1444 Square from = move_from(m);
1445 Square to = move_to(m);
1446 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1448 assert(to == st->previous->epSquare);
1449 assert(relative_rank(us, to) == RANK_6);
1450 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1451 assert(piece_on(from) == EMPTY);
1452 assert(piece_on(capsq) == EMPTY);
1454 // Replace captured piece
1455 set_bit(&(byColorBB[them]), capsq);
1456 set_bit(&(byTypeBB[PAWN]), capsq);
1457 set_bit(&(byTypeBB[0]), capsq);
1458 board[capsq] = piece_of_color_and_type(them, PAWN);
1460 // Remove moving piece from destination square
1461 clear_bit(&(byColorBB[us]), to);
1462 clear_bit(&(byTypeBB[PAWN]), to);
1463 clear_bit(&(byTypeBB[0]), to);
1466 // Replace moving piece at source square
1467 set_bit(&(byColorBB[us]), from);
1468 set_bit(&(byTypeBB[PAWN]), from);
1469 set_bit(&(byTypeBB[0]), from);
1470 board[from] = piece_of_color_and_type(us, PAWN);
1472 // Update piece list:
1473 pieceList[us][PAWN][index[to]] = from;
1474 index[from] = index[to];
1475 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1476 index[capsq] = pieceCount[them][PAWN];
1478 // Update piece count:
1479 pieceCount[them][PAWN]++;
1483 /// Position::do_null_move makes() a "null move": It switches the side to move
1484 /// and updates the hash key without executing any move on the board.
1486 void Position::do_null_move(StateInfo& newSt) {
1489 assert(!is_check());
1491 // Back up the information necessary to undo the null move to the supplied
1492 // StateInfo object. In the case of a null move, the only thing we need to
1493 // remember is the last move made and the en passant square.
1494 newSt.lastMove = st->lastMove;
1495 newSt.epSquare = st->epSquare;
1496 newSt.previous = st->previous;
1497 st->previous = &newSt;
1499 // Save the current key to the history[] array, in order to be able to
1500 // detect repetition draws.
1501 history[gamePly] = st->key;
1503 // Update the necessary information
1504 sideToMove = opposite_color(sideToMove);
1505 if (st->epSquare != SQ_NONE)
1506 st->key ^= zobEp[st->epSquare];
1508 st->epSquare = SQ_NONE;
1511 st->key ^= zobSideToMove;
1513 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1514 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1520 /// Position::undo_null_move() unmakes a "null move".
1522 void Position::undo_null_move() {
1525 assert(!is_check());
1527 // Restore information from the our StateInfo object
1528 st->lastMove = st->previous->lastMove;
1529 st->epSquare = st->previous->epSquare;
1530 st->previous = st->previous->previous;
1532 if (st->epSquare != SQ_NONE)
1533 st->key ^= zobEp[st->epSquare];
1535 // Update the necessary information
1536 sideToMove = opposite_color(sideToMove);
1539 st->key ^= zobSideToMove;
1541 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1542 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1548 /// Position::see() is a static exchange evaluator: It tries to estimate the
1549 /// material gain or loss resulting from a move. There are three versions of
1550 /// this function: One which takes a destination square as input, one takes a
1551 /// move, and one which takes a 'from' and a 'to' square. The function does
1552 /// not yet understand promotions captures.
1554 int Position::see(Square to) const {
1556 assert(square_is_ok(to));
1557 return see(SQ_NONE, to);
1560 int Position::see(Move m) const {
1562 assert(move_is_ok(m));
1563 return see(move_from(m), move_to(m));
1566 int Position::see(Square from, Square to) const {
1569 static const int seeValues[18] = {
1570 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1571 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1572 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1573 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1577 Bitboard attackers, occ, b;
1579 assert(square_is_ok(from) || from == SQ_NONE);
1580 assert(square_is_ok(to));
1582 // Initialize colors
1583 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1584 Color them = opposite_color(us);
1586 // Initialize pinned and pinners bitboards
1587 Bitboard pinned[2], pinners[2];
1588 pinned[us] = pinned_pieces(us, pinners[us]);
1589 pinned[them] = pinned_pieces(them, pinners[them]);
1591 // Initialize pieces
1592 Piece piece = piece_on(from);
1593 Piece capture = piece_on(to);
1595 // Find all attackers to the destination square, with the moving piece
1596 // removed, but possibly an X-ray attacker added behind it.
1597 occ = occupied_squares();
1599 // Handle en passant moves
1600 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1602 assert(capture == EMPTY);
1604 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1605 capture = piece_on(capQq);
1607 assert(type_of_piece_on(capQq) == PAWN);
1609 // Remove the captured pawn
1610 clear_bit(&occ, capQq);
1615 clear_bit(&occ, from);
1616 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1617 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1618 | (piece_attacks<KNIGHT>(to) & knights())
1619 | (piece_attacks<KING>(to) & kings())
1620 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1621 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1623 // Remove our pinned pieces from attacks if the captured piece is not
1624 // a pinner, otherwise we could remove a valid "capture the pinner" attack.
1625 if (pinned[us] != EmptyBoardBB && !bit_is_set(pinners[us], to))
1626 attackers &= ~pinned[us];
1628 // Remove opponent pinned pieces from attacks if the moving piece is not
1629 // a pinner, otherwise we could remove a piece that is no more pinned
1630 // due to our pinner piece is moving away.
1631 if (pinned[them] != EmptyBoardBB && !bit_is_set(pinners[them], from))
1632 attackers &= ~pinned[them];
1634 if (from != SQ_NONE)
1637 // If we don't have any attacker we are finished
1638 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1641 // Locate the least valuable attacker to the destination square
1642 // and use it to initialize from square.
1644 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1647 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1648 piece = piece_on(from);
1651 // If the opponent has no attackers we are finished
1652 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1653 return seeValues[capture];
1655 attackers &= occ; // Remove the moving piece
1657 // The destination square is defended, which makes things rather more
1658 // difficult to compute. We proceed by building up a "swap list" containing
1659 // the material gain or loss at each stop in a sequence of captures to the
1660 // destination square, where the sides alternately capture, and always
1661 // capture with the least valuable piece. After each capture, we look for
1662 // new X-ray attacks from behind the capturing piece.
1663 int lastCapturingPieceValue = seeValues[piece];
1664 int swapList[32], n = 1;
1668 swapList[0] = seeValues[capture];
1671 // Locate the least valuable attacker for the side to move. The loop
1672 // below looks like it is potentially infinite, but it isn't. We know
1673 // that the side to move still has at least one attacker left.
1674 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1677 // Remove the attacker we just found from the 'attackers' bitboard,
1678 // and scan for new X-ray attacks behind the attacker.
1679 b = attackers & pieces_of_color_and_type(c, pt);
1681 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1682 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1686 // Add the new entry to the swap list
1688 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1691 // Remember the value of the capturing piece, and change the side to move
1692 // before beginning the next iteration
1693 lastCapturingPieceValue = seeValues[pt];
1694 c = opposite_color(c);
1696 // Remove pinned pieces from attackers
1697 if ( pinned[c] != EmptyBoardBB
1698 && !bit_is_set(pinners[c], to)
1699 && !(pinners[c] & attackers))
1700 attackers &= ~pinned[c];
1702 // Stop after a king capture
1703 if (pt == KING && (attackers & pieces_of_color(c)))
1706 swapList[n++] = 100;
1709 } while (attackers & pieces_of_color(c));
1711 // Having built the swap list, we negamax through it to find the best
1712 // achievable score from the point of view of the side to move
1714 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1720 /// Position::setStartState() copies the content of the argument
1721 /// inside startState and makes st point to it. This is needed
1722 /// when the st pointee could become stale, as example because
1723 /// the caller is about to going out of scope.
1725 void Position::setStartState(const StateInfo& s) {
1732 /// Position::clear() erases the position object to a pristine state, with an
1733 /// empty board, white to move, and no castling rights.
1735 void Position::clear() {
1738 memset(st, 0, sizeof(StateInfo));
1739 st->epSquare = SQ_NONE;
1741 memset(index, 0, sizeof(int) * 64);
1742 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1744 for (int i = 0; i < 64; i++)
1747 for (int i = 0; i < 7; i++)
1749 byTypeBB[i] = EmptyBoardBB;
1750 pieceCount[0][i] = pieceCount[1][i] = 0;
1751 for (int j = 0; j < 8; j++)
1752 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1757 initialKFile = FILE_E;
1758 initialKRFile = FILE_H;
1759 initialQRFile = FILE_A;
1763 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1764 /// UCI interface code, whenever a non-reversible move is made in a
1765 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1766 /// for the program to handle games of arbitrary length, as long as the GUI
1767 /// handles draws by the 50 move rule correctly.
1769 void Position::reset_game_ply() {
1775 /// Position::put_piece() puts a piece on the given square of the board,
1776 /// updating the board array, bitboards, and piece counts.
1778 void Position::put_piece(Piece p, Square s) {
1780 Color c = color_of_piece(p);
1781 PieceType pt = type_of_piece(p);
1784 index[s] = pieceCount[c][pt];
1785 pieceList[c][pt][index[s]] = s;
1787 set_bit(&(byTypeBB[pt]), s);
1788 set_bit(&(byColorBB[c]), s);
1789 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1791 pieceCount[c][pt]++;
1798 /// Position::allow_oo() gives the given side the right to castle kingside.
1799 /// Used when setting castling rights during parsing of FEN strings.
1801 void Position::allow_oo(Color c) {
1803 st->castleRights |= (1 + int(c));
1807 /// Position::allow_ooo() gives the given side the right to castle queenside.
1808 /// Used when setting castling rights during parsing of FEN strings.
1810 void Position::allow_ooo(Color c) {
1812 st->castleRights |= (4 + 4*int(c));
1816 /// Position::compute_key() computes the hash key of the position. The hash
1817 /// key is usually updated incrementally as moves are made and unmade, the
1818 /// compute_key() function is only used when a new position is set up, and
1819 /// to verify the correctness of the hash key when running in debug mode.
1821 Key Position::compute_key() const {
1823 Key result = Key(0ULL);
1825 for (Square s = SQ_A1; s <= SQ_H8; s++)
1826 if (square_is_occupied(s))
1827 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1829 if (ep_square() != SQ_NONE)
1830 result ^= zobEp[ep_square()];
1832 result ^= zobCastle[st->castleRights];
1833 if (side_to_move() == BLACK)
1834 result ^= zobSideToMove;
1840 /// Position::compute_pawn_key() computes the hash key of the position. The
1841 /// hash key is usually updated incrementally as moves are made and unmade,
1842 /// the compute_pawn_key() function is only used when a new position is set
1843 /// up, and to verify the correctness of the pawn hash key when running in
1846 Key Position::compute_pawn_key() const {
1848 Key result = Key(0ULL);
1852 for (Color c = WHITE; c <= BLACK; c++)
1857 s = pop_1st_bit(&b);
1858 result ^= zobrist[c][PAWN][s];
1865 /// Position::compute_material_key() computes the hash key of the position.
1866 /// The hash key is usually updated incrementally as moves are made and unmade,
1867 /// the compute_material_key() function is only used when a new position is set
1868 /// up, and to verify the correctness of the material hash key when running in
1871 Key Position::compute_material_key() const {
1873 Key result = Key(0ULL);
1874 for (Color c = WHITE; c <= BLACK; c++)
1875 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1877 int count = piece_count(c, pt);
1878 for (int i = 0; i <= count; i++)
1879 result ^= zobMaterial[c][pt][i];
1885 /// Position::compute_value() compute the incremental scores for the middle
1886 /// game and the endgame. These functions are used to initialize the incremental
1887 /// scores when a new position is set up, and to verify that the scores are correctly
1888 /// updated by do_move and undo_move when the program is running in debug mode.
1889 template<Position::GamePhase Phase>
1890 Value Position::compute_value() const {
1892 Value result = Value(0);
1896 for (Color c = WHITE; c <= BLACK; c++)
1897 for (PieceType pt = PAWN; pt <= KING; pt++)
1899 b = pieces_of_color_and_type(c, pt);
1902 s = pop_1st_bit(&b);
1903 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1904 result += pst<Phase>(c, pt, s);
1908 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1909 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1914 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1915 /// game material score for the given side. Material scores are updated
1916 /// incrementally during the search, this function is only used while
1917 /// initializing a new Position object.
1919 Value Position::compute_non_pawn_material(Color c) const {
1921 Value result = Value(0);
1924 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1926 Bitboard b = pieces_of_color_and_type(c, pt);
1929 s = pop_1st_bit(&b);
1930 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1931 result += piece_value_midgame(pt);
1938 /// Position::is_mate() returns true or false depending on whether the
1939 /// side to move is checkmated. Note that this function is currently very
1940 /// slow, and shouldn't be used frequently inside the search.
1942 bool Position::is_mate() const {
1946 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1947 return mp.get_next_move() == MOVE_NONE;
1953 /// Position::is_draw() tests whether the position is drawn by material,
1954 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1955 /// must be done by the search.
1957 bool Position::is_draw() const {
1959 // Draw by material?
1961 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1964 // Draw by the 50 moves rule?
1965 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1968 // Draw by repetition?
1969 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1970 if (history[gamePly - i] == st->key)
1977 /// Position::has_mate_threat() tests whether a given color has a mate in one
1978 /// from the current position. This function is quite slow, but it doesn't
1979 /// matter, because it is currently only called from PV nodes, which are rare.
1981 bool Position::has_mate_threat(Color c) {
1984 Color stm = side_to_move();
1986 // The following lines are useless and silly, but prevents gcc from
1987 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1988 // be used uninitialized.
1989 st1.lastMove = st->lastMove;
1990 st1.epSquare = st->epSquare;
1995 // If the input color is not equal to the side to move, do a null move
1999 MoveStack mlist[120];
2001 bool result = false;
2003 // Generate legal moves
2004 count = generate_legal_moves(*this, mlist);
2006 // Loop through the moves, and see if one of them is mate
2007 for (int i = 0; i < count; i++)
2009 do_move(mlist[i].move, st2);
2013 undo_move(mlist[i].move);
2016 // Undo null move, if necessary
2024 /// Position::init_zobrist() is a static member function which initializes the
2025 /// various arrays used to compute hash keys.
2027 void Position::init_zobrist() {
2029 for (int i = 0; i < 2; i++)
2030 for (int j = 0; j < 8; j++)
2031 for (int k = 0; k < 64; k++)
2032 zobrist[i][j][k] = Key(genrand_int64());
2034 for (int i = 0; i < 64; i++)
2035 zobEp[i] = Key(genrand_int64());
2037 for (int i = 0; i < 16; i++)
2038 zobCastle[i] = genrand_int64();
2040 zobSideToMove = genrand_int64();
2042 for (int i = 0; i < 2; i++)
2043 for (int j = 0; j < 8; j++)
2044 for (int k = 0; k < 16; k++)
2045 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2047 for (int i = 0; i < 16; i++)
2048 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2052 /// Position::init_piece_square_tables() initializes the piece square tables.
2053 /// This is a two-step operation: First, the white halves of the tables are
2054 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2055 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2056 /// Second, the black halves of the tables are initialized by mirroring
2057 /// and changing the sign of the corresponding white scores.
2059 void Position::init_piece_square_tables() {
2061 int r = get_option_value_int("Randomness"), i;
2062 for (Square s = SQ_A1; s <= SQ_H8; s++)
2063 for (Piece p = WP; p <= WK; p++)
2065 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2066 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2067 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2070 for (Square s = SQ_A1; s <= SQ_H8; s++)
2071 for (Piece p = BP; p <= BK; p++)
2073 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2074 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2079 /// Position::flipped_copy() makes a copy of the input position, but with
2080 /// the white and black sides reversed. This is only useful for debugging,
2081 /// especially for finding evaluation symmetry bugs.
2083 void Position::flipped_copy(const Position &pos) {
2085 assert(pos.is_ok());
2090 for (Square s = SQ_A1; s <= SQ_H8; s++)
2091 if (!pos.square_is_empty(s))
2092 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2095 sideToMove = opposite_color(pos.side_to_move());
2098 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2099 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2100 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2101 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2103 initialKFile = pos.initialKFile;
2104 initialKRFile = pos.initialKRFile;
2105 initialQRFile = pos.initialQRFile;
2107 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2108 castleRightsMask[sq] = ALL_CASTLES;
2110 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2111 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2112 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2113 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2114 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2115 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2117 // En passant square
2118 if (pos.st->epSquare != SQ_NONE)
2119 st->epSquare = flip_square(pos.st->epSquare);
2125 st->key = compute_key();
2126 st->pawnKey = compute_pawn_key();
2127 st->materialKey = compute_material_key();
2129 // Incremental scores
2130 st->mgValue = compute_value<MidGame>();
2131 st->egValue = compute_value<EndGame>();
2134 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2135 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2141 /// Position::is_ok() performs some consitency checks for the position object.
2142 /// This is meant to be helpful when debugging.
2144 bool Position::is_ok(int* failedStep) const {
2146 // What features of the position should be verified?
2147 static const bool debugBitboards = false;
2148 static const bool debugKingCount = false;
2149 static const bool debugKingCapture = false;
2150 static const bool debugCheckerCount = false;
2151 static const bool debugKey = false;
2152 static const bool debugMaterialKey = false;
2153 static const bool debugPawnKey = false;
2154 static const bool debugIncrementalEval = false;
2155 static const bool debugNonPawnMaterial = false;
2156 static const bool debugPieceCounts = false;
2157 static const bool debugPieceList = false;
2159 if (failedStep) *failedStep = 1;
2162 if (!color_is_ok(side_to_move()))
2165 // Are the king squares in the position correct?
2166 if (failedStep) (*failedStep)++;
2167 if (piece_on(king_square(WHITE)) != WK)
2170 if (failedStep) (*failedStep)++;
2171 if (piece_on(king_square(BLACK)) != BK)
2175 if (failedStep) (*failedStep)++;
2176 if (!file_is_ok(initialKRFile))
2179 if (!file_is_ok(initialQRFile))
2182 // Do both sides have exactly one king?
2183 if (failedStep) (*failedStep)++;
2186 int kingCount[2] = {0, 0};
2187 for (Square s = SQ_A1; s <= SQ_H8; s++)
2188 if (type_of_piece_on(s) == KING)
2189 kingCount[color_of_piece_on(s)]++;
2191 if (kingCount[0] != 1 || kingCount[1] != 1)
2195 // Can the side to move capture the opponent's king?
2196 if (failedStep) (*failedStep)++;
2197 if (debugKingCapture)
2199 Color us = side_to_move();
2200 Color them = opposite_color(us);
2201 Square ksq = king_square(them);
2202 if (square_is_attacked(ksq, us))
2206 // Is there more than 2 checkers?
2207 if (failedStep) (*failedStep)++;
2208 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2212 if (failedStep) (*failedStep)++;
2215 // The intersection of the white and black pieces must be empty
2216 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2219 // The union of the white and black pieces must be equal to all
2221 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2224 // Separate piece type bitboards must have empty intersections
2225 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2226 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2227 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2231 // En passant square OK?
2232 if (failedStep) (*failedStep)++;
2233 if (ep_square() != SQ_NONE)
2235 // The en passant square must be on rank 6, from the point of view of the
2237 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2242 if (failedStep) (*failedStep)++;
2243 if (debugKey && st->key != compute_key())
2246 // Pawn hash key OK?
2247 if (failedStep) (*failedStep)++;
2248 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2251 // Material hash key OK?
2252 if (failedStep) (*failedStep)++;
2253 if (debugMaterialKey && st->materialKey != compute_material_key())
2256 // Incremental eval OK?
2257 if (failedStep) (*failedStep)++;
2258 if (debugIncrementalEval)
2260 if (st->mgValue != compute_value<MidGame>())
2263 if (st->egValue != compute_value<EndGame>())
2267 // Non-pawn material OK?
2268 if (failedStep) (*failedStep)++;
2269 if (debugNonPawnMaterial)
2271 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2274 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2279 if (failedStep) (*failedStep)++;
2280 if (debugPieceCounts)
2281 for (Color c = WHITE; c <= BLACK; c++)
2282 for (PieceType pt = PAWN; pt <= KING; pt++)
2283 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2286 if (failedStep) (*failedStep)++;
2289 for(Color c = WHITE; c <= BLACK; c++)
2290 for(PieceType pt = PAWN; pt <= KING; pt++)
2291 for(int i = 0; i < pieceCount[c][pt]; i++)
2293 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2296 if (index[piece_list(c, pt, i)] != i)
2300 if (failedStep) *failedStep = 0;