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/>.
35 #include "ucioption.h"
42 extern SearchStack EmptySearchStack;
44 int Position::castleRightsMask[64];
46 Key Position::zobrist[2][8][64];
47 Key Position::zobEp[64];
48 Key Position::zobCastle[16];
49 Key Position::zobMaterial[2][8][16];
50 Key Position::zobSideToMove;
52 Value Position::MgPieceSquareTable[16][64];
53 Value Position::EgPieceSquareTable[16][64];
55 static bool RequestPending = false;
63 Position::Position(const Position& pos) {
67 Position::Position(const std::string& fen) {
72 /// Position::from_fen() initializes the position object with the given FEN
73 /// string. This function is not very robust - make sure that input FENs are
74 /// correct (this is assumed to be the responsibility of the GUI).
76 void Position::from_fen(const std::string& fen) {
78 static const std::string pieceLetters = "KQRBNPkqrbnp";
79 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
87 for ( ; fen[i] != ' '; i++)
91 // Skip the given number of files
92 file += (fen[i] - '1' + 1);
95 else if (fen[i] == '/')
101 size_t idx = pieceLetters.find(fen[i]);
102 if (idx == std::string::npos)
104 std::cout << "Error in FEN at character " << i << std::endl;
107 Square square = make_square(file, rank);
108 put_piece(pieces[idx], square);
114 if (fen[i] != 'w' && fen[i] != 'b')
116 std::cout << "Error in FEN at character " << i << std::endl;
119 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
125 std::cout << "Error in FEN at character " << i << std::endl;
130 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
136 else if(fen[i] == 'K') allow_oo(WHITE);
137 else if(fen[i] == 'Q') allow_ooo(WHITE);
138 else if(fen[i] == 'k') allow_oo(BLACK);
139 else if(fen[i] == 'q') allow_ooo(BLACK);
140 else if(fen[i] >= 'A' && fen[i] <= 'H') {
141 File rookFile, kingFile = FILE_NONE;
142 for(Square square = SQ_B1; square <= SQ_G1; square++)
143 if(piece_on(square) == WK)
144 kingFile = square_file(square);
145 if(kingFile == FILE_NONE) {
146 std::cout << "Error in FEN at character " << i << std::endl;
149 initialKFile = kingFile;
150 rookFile = File(fen[i] - 'A') + FILE_A;
151 if(rookFile < initialKFile) {
153 initialQRFile = rookFile;
157 initialKRFile = rookFile;
160 else if(fen[i] >= 'a' && fen[i] <= 'h') {
161 File rookFile, kingFile = FILE_NONE;
162 for(Square square = SQ_B8; square <= SQ_G8; square++)
163 if(piece_on(square) == BK)
164 kingFile = square_file(square);
165 if(kingFile == FILE_NONE) {
166 std::cout << "Error in FEN at character " << i << std::endl;
169 initialKFile = kingFile;
170 rookFile = File(fen[i] - 'a') + FILE_A;
171 if(rookFile < initialKFile) {
173 initialQRFile = rookFile;
177 initialKRFile = rookFile;
181 std::cout << "Error in FEN at character " << i << std::endl;
188 while (fen[i] == ' ')
192 if ( i < fen.length() - 2
193 && (fen[i] >= 'a' && fen[i] <= 'h')
194 && (fen[i+1] == '3' || fen[i+1] == '6'))
195 st->epSquare = square_from_string(fen.substr(i, 2));
197 // Various initialisation
198 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
199 castleRightsMask[sq] = ALL_CASTLES;
201 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
202 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
203 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
204 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
205 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
206 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
211 st->key = compute_key();
212 st->pawnKey = compute_pawn_key();
213 st->materialKey = compute_material_key();
214 st->mgValue = compute_value<MidGame>();
215 st->egValue = compute_value<EndGame>();
216 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
217 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
221 /// Position::to_fen() converts the position object to a FEN string. This is
222 /// probably only useful for debugging.
224 const std::string Position::to_fen() const {
226 static const std::string pieceLetters = " PNBRQK pnbrqk";
230 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
233 for (File file = FILE_A; file <= FILE_H; file++)
235 Square sq = make_square(file, rank);
236 if (!square_is_occupied(sq))
242 fen += (char)skip + '0';
245 fen += pieceLetters[piece_on(sq)];
248 fen += (char)skip + '0';
250 fen += (rank > RANK_1 ? '/' : ' ');
252 fen += (sideToMove == WHITE ? "w " : "b ");
253 if (st->castleRights != NO_CASTLES)
255 if (can_castle_kingside(WHITE)) fen += 'K';
256 if (can_castle_queenside(WHITE)) fen += 'Q';
257 if (can_castle_kingside(BLACK)) fen += 'k';
258 if (can_castle_queenside(BLACK)) fen += 'q';
263 if (ep_square() != SQ_NONE)
264 fen += square_to_string(ep_square());
272 /// Position::print() prints an ASCII representation of the position to
273 /// the standard output. If a move is given then also the san is print.
275 void Position::print(Move m) const {
277 static const std::string pieceLetters = " PNBRQK PNBRQK .";
279 // Check for reentrancy, as example when called from inside
280 // MovePicker that is used also here in move_to_san()
284 RequestPending = true;
286 std::cout << std::endl;
289 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
290 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
292 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
294 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
295 for (File file = FILE_A; file <= FILE_H; file++)
297 Square sq = make_square(file, rank);
298 Piece piece = piece_on(sq);
299 if (piece == EMPTY && square_color(sq) == WHITE)
302 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
303 std::cout << '|' << col << pieceLetters[piece] << col;
305 std::cout << '|' << std::endl;
307 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
308 << "Fen is: " << to_fen() << std::endl
309 << "Key is: " << st->key << std::endl;
311 RequestPending = false;
315 /// Position::copy() creates a copy of the input position.
317 void Position::copy(const Position &pos) {
319 memcpy(this, &pos, sizeof(Position));
323 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
324 /// king) pieces for the given color and for the given pinner type. Or, when
325 /// template parameter FindPinned is false, the pinned pieces of opposite color
326 /// that are, indeed, the pieces candidate for a discovery check.
327 /// Note that checkersBB bitboard must be already updated.
328 template<PieceType Piece, bool FindPinned>
329 Bitboard Position::hidden_checks(Color c, Square ksq, Bitboard& pinners) const {
332 Bitboard sliders, result = EmptyBoardBB;
334 if (Piece == ROOK) // Resolved at compile time
335 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
337 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
339 if (sliders && (!FindPinned || (sliders & ~st->checkersBB)))
341 // King blockers are candidate pinned pieces
342 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
344 // Pinners are sliders, not checkers, that give check when
345 // candidate pinned are removed.
346 pinners = (FindPinned ? sliders & ~st->checkersBB : sliders);
349 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
351 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
353 // Finally for each pinner find the corresponding pinned piece (if same color of king)
354 // or discovery checker (if opposite color) among the candidates.
355 Bitboard p = pinners;
359 result |= (squares_between(s, ksq) & candidate_pinned);
363 pinners = EmptyBoardBB;
369 /// Position::attacks_to() computes a bitboard containing all pieces which
370 /// attacks a given square. There are two versions of this function: One
371 /// which finds attackers of both colors, and one which only finds the
372 /// attackers for one side.
374 Bitboard Position::attacks_to(Square s) const {
376 return (pawn_attacks(BLACK, s) & pawns(WHITE))
377 | (pawn_attacks(WHITE, s) & pawns(BLACK))
378 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
379 | (piece_attacks<ROOK>(s) & rooks_and_queens())
380 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
381 | (piece_attacks<KING>(s) & pieces_of_type(KING));
384 /// Position::piece_attacks_square() tests whether the piece on square f
385 /// attacks square t.
387 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
389 assert(square_is_ok(f));
390 assert(square_is_ok(t));
394 case WP: return pawn_attacks_square(WHITE, f, t);
395 case BP: return pawn_attacks_square(BLACK, f, t);
396 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
397 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
398 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
399 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
400 case WK: case BK: return piece_attacks_square<KING>(f, t);
407 /// Position::move_attacks_square() tests whether a move from the current
408 /// position attacks a given square.
410 bool Position::move_attacks_square(Move m, Square s) const {
412 assert(move_is_ok(m));
413 assert(square_is_ok(s));
415 Square f = move_from(m), t = move_to(m);
417 assert(square_is_occupied(f));
419 if (piece_attacks_square(piece_on(f), t, s))
422 // Move the piece and scan for X-ray attacks behind it
423 Bitboard occ = occupied_squares();
424 Color us = color_of_piece_on(f);
427 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
428 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
430 // If we have attacks we need to verify that are caused by our move
431 // and are not already existent ones.
432 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
436 /// Position::find_checkers() computes the checkersBB bitboard, which
437 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
438 /// currently works by calling Position::attacks_to, which is probably
439 /// inefficient. Consider rewriting this function to use the last move
440 /// played, like in non-bitboard versions of Glaurung.
442 void Position::find_checkers() {
444 Color us = side_to_move();
445 st->checkersBB = attacks_to(king_square(us), opposite_color(us));
449 /// Position:find_pinned() computes the pinned, pinners and dcCandidates
450 /// bitboards for both colors. Bitboard checkersBB must be already updated.
452 void Position::find_pinned() {
457 for (Color c = WHITE; c <= BLACK; c++)
459 ksq = king_square(c);
460 st->pinned[c] = hidden_checks<ROOK, true>(c, ksq, p1) | hidden_checks<BISHOP, true>(c, ksq, p2);
461 st->pinners[c] = p1 | p2;
462 ksq = king_square(opposite_color(c));
463 st->dcCandidates[c] = hidden_checks<ROOK, false>(c, ksq, p1) | hidden_checks<BISHOP, false>(c, ksq, p2);
468 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
470 bool Position::pl_move_is_legal(Move m) const {
473 assert(move_is_ok(m));
475 // If we're in check, all pseudo-legal moves are legal, because our
476 // check evasion generator only generates true legal moves.
480 // Castling moves are checked for legality during move generation.
481 if (move_is_castle(m))
484 Color us = side_to_move();
485 Color them = opposite_color(us);
486 Square from = move_from(m);
487 Square ksq = king_square(us);
489 assert(color_of_piece_on(from) == us);
490 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
492 // En passant captures are a tricky special case. Because they are
493 // rather uncommon, we do it simply by testing whether the king is attacked
494 // after the move is made
497 Square to = move_to(m);
498 Square capsq = make_square(square_file(to), square_rank(from));
499 Bitboard b = occupied_squares();
501 assert(to == ep_square());
502 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
503 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
504 assert(piece_on(to) == EMPTY);
507 clear_bit(&b, capsq);
510 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
511 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
514 // If the moving piece is a king, check whether the destination
515 // square is attacked by the opponent.
517 return !(square_is_attacked(move_to(m), them));
519 // A non-king move is legal if and only if it is not pinned or it
520 // is moving along the ray towards or away from the king.
521 return ( !bit_is_set(pinned_pieces(us), from)
522 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
526 /// Position::move_is_check() tests whether a pseudo-legal move is a check
528 bool Position::move_is_check(Move m) const {
531 assert(move_is_ok(m));
533 Color us = side_to_move();
534 Color them = opposite_color(us);
535 Square from = move_from(m);
536 Square to = move_to(m);
537 Square ksq = king_square(them);
538 Bitboard dcCandidates = discovered_check_candidates(us);
540 assert(color_of_piece_on(from) == us);
541 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
543 // Proceed according to the type of the moving piece
544 switch (type_of_piece_on(from))
548 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
551 if ( bit_is_set(dcCandidates, from) // Discovered check?
552 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
555 if (move_promotion(m)) // Promotion with check?
557 Bitboard b = occupied_squares();
560 switch (move_promotion(m))
563 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
565 return bit_is_set(bishop_attacks_bb(to, b), ksq);
567 return bit_is_set(rook_attacks_bb(to, b), ksq);
569 return bit_is_set(queen_attacks_bb(to, b), ksq);
574 // En passant capture with check? We have already handled the case
575 // of direct checks and ordinary discovered check, the only case we
576 // need to handle is the unusual case of a discovered check through the
578 else if (move_is_ep(m))
580 Square capsq = make_square(square_file(to), square_rank(from));
581 Bitboard b = occupied_squares();
583 clear_bit(&b, capsq);
585 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
586 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
591 return bit_is_set(dcCandidates, from) // Discovered check?
592 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
595 return bit_is_set(dcCandidates, from) // Discovered check?
596 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
599 return bit_is_set(dcCandidates, from) // Discovered check?
600 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
603 // Discovered checks are impossible!
604 assert(!bit_is_set(dcCandidates, from));
605 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
609 if ( bit_is_set(dcCandidates, from)
610 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
613 // Castling with check?
614 if (move_is_castle(m))
616 Square kfrom, kto, rfrom, rto;
617 Bitboard b = occupied_squares();
623 kto = relative_square(us, SQ_G1);
624 rto = relative_square(us, SQ_F1);
626 kto = relative_square(us, SQ_C1);
627 rto = relative_square(us, SQ_D1);
629 clear_bit(&b, kfrom);
630 clear_bit(&b, rfrom);
633 return bit_is_set(rook_attacks_bb(rto, b), ksq);
637 default: // NO_PIECE_TYPE
645 /// Position::move_is_capture() tests whether a move from the current
646 /// position is a capture. Move must not be MOVE_NONE.
648 bool Position::move_is_capture(Move m) const {
650 assert(m != MOVE_NONE);
652 return ( !square_is_empty(move_to(m))
653 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
659 /// Position::update_checkers() is a private method to udpate chekers info
661 template<PieceType Piece>
662 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
663 Square to, Bitboard dcCandidates) {
665 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
666 set_bit(pCheckersBB, to);
668 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
671 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
674 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
679 /// Position::do_move() makes a move, and saves all information necessary
680 /// to a StateInfo object. The move is assumed to be legal.
681 /// Pseudo-legal moves should be filtered out before this function is called.
683 void Position::do_move(Move m, StateInfo& newSt) {
686 assert(move_is_ok(m));
688 // Get now the current (pre-move) dc candidates that we will use
689 // in update_checkers().
690 Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
692 // Copy the old state to our new StateInfo object (except the
693 // captured piece, which is taken care of later.
694 // TODO do not copy pinners and checkersBB because are recalculated
697 newSt.capture = NO_PIECE_TYPE;
701 // Save the current key to the history[] array, in order to be able to
702 // detect repetition draws.
703 history[gamePly] = st->key;
705 // Increment the 50 moves rule draw counter. Resetting it to zero in the
706 // case of non-reversible moves is taken care of later.
709 if (move_is_castle(m))
711 else if (move_promotion(m))
712 do_promotion_move(m);
713 else if (move_is_ep(m))
717 Color us = side_to_move();
718 Color them = opposite_color(us);
719 Square from = move_from(m);
720 Square to = move_to(m);
722 assert(color_of_piece_on(from) == us);
723 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
725 PieceType piece = type_of_piece_on(from);
727 st->capture = type_of_piece_on(to);
730 do_capture_move(m, st->capture, them, to);
733 clear_bit(&(byColorBB[us]), from);
734 clear_bit(&(byTypeBB[piece]), from);
735 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
736 set_bit(&(byColorBB[us]), to);
737 set_bit(&(byTypeBB[piece]), to);
738 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
739 board[to] = board[from];
743 st->key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
745 // Update incremental scores
746 st->mgValue -= pst<MidGame>(us, piece, from);
747 st->mgValue += pst<MidGame>(us, piece, to);
748 st->egValue -= pst<EndGame>(us, piece, from);
749 st->egValue += pst<EndGame>(us, piece, to);
751 // If the moving piece was a king, update the king square
755 // Reset en passant square
756 if (st->epSquare != SQ_NONE)
758 st->key ^= zobEp[st->epSquare];
759 st->epSquare = SQ_NONE;
762 // If the moving piece was a pawn do some special extra work
765 // Reset rule 50 draw counter
768 // Update pawn hash key
769 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
771 // Set en passant square, only if moved pawn can be captured
772 if (abs(int(to) - int(from)) == 16)
774 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
775 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
777 st->epSquare = Square((int(from) + int(to)) / 2);
778 st->key ^= zobEp[st->epSquare];
783 // Update piece lists
784 pieceList[us][piece][index[from]] = to;
785 index[to] = index[from];
787 // Update castle rights
788 st->key ^= zobCastle[st->castleRights];
789 st->castleRights &= castleRightsMask[from];
790 st->castleRights &= castleRightsMask[to];
791 st->key ^= zobCastle[st->castleRights];
793 // Update checkers bitboard, piece must be already moved
794 st->checkersBB = EmptyBoardBB;
795 Square ksq = king_square(them);
798 case PAWN: update_checkers<PAWN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
799 case KNIGHT: update_checkers<KNIGHT>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
800 case BISHOP: update_checkers<BISHOP>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
801 case ROOK: update_checkers<ROOK>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
802 case QUEEN: update_checkers<QUEEN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
803 case KING: update_checkers<KING>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
804 default: assert(false); break;
810 st->key ^= zobSideToMove;
811 sideToMove = opposite_color(sideToMove);
814 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
815 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
821 /// Position::do_capture_move() is a private method used to update captured
822 /// piece info. It is called from the main Position::do_move function.
824 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
826 assert(capture != KING);
828 // Remove captured piece
829 clear_bit(&(byColorBB[them]), to);
830 clear_bit(&(byTypeBB[capture]), to);
833 st->key ^= zobrist[them][capture][to];
835 // If the captured piece was a pawn, update pawn hash key
837 st->pawnKey ^= zobrist[them][PAWN][to];
839 // Update incremental scores
840 st->mgValue -= pst<MidGame>(them, capture, to);
841 st->egValue -= pst<EndGame>(them, capture, to);
843 assert(!move_promotion(m) || capture != PAWN);
847 npMaterial[them] -= piece_value_midgame(capture);
849 // Update material hash key
850 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
852 // Update piece count
853 pieceCount[them][capture]--;
856 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
857 index[pieceList[them][capture][index[to]]] = index[to];
859 // Reset rule 50 counter
864 /// Position::do_castle_move() is a private method used to make a castling
865 /// move. It is called from the main Position::do_move function. Note that
866 /// castling moves are encoded as "king captures friendly rook" moves, for
867 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
869 void Position::do_castle_move(Move m) {
872 assert(move_is_ok(m));
873 assert(move_is_castle(m));
875 Color us = side_to_move();
876 Color them = opposite_color(us);
878 // Find source squares for king and rook
879 Square kfrom = move_from(m);
880 Square rfrom = move_to(m); // HACK: See comment at beginning of function
883 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
884 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
886 // Find destination squares for king and rook
887 if (rfrom > kfrom) // O-O
889 kto = relative_square(us, SQ_G1);
890 rto = relative_square(us, SQ_F1);
892 kto = relative_square(us, SQ_C1);
893 rto = relative_square(us, SQ_D1);
896 // Remove pieces from source squares
897 clear_bit(&(byColorBB[us]), kfrom);
898 clear_bit(&(byTypeBB[KING]), kfrom);
899 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
900 clear_bit(&(byColorBB[us]), rfrom);
901 clear_bit(&(byTypeBB[ROOK]), rfrom);
902 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
904 // Put pieces on destination squares
905 set_bit(&(byColorBB[us]), kto);
906 set_bit(&(byTypeBB[KING]), kto);
907 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
908 set_bit(&(byColorBB[us]), rto);
909 set_bit(&(byTypeBB[ROOK]), rto);
910 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
912 // Update board array
913 board[kfrom] = board[rfrom] = EMPTY;
914 board[kto] = piece_of_color_and_type(us, KING);
915 board[rto] = piece_of_color_and_type(us, ROOK);
917 // Update king square
918 kingSquare[us] = kto;
920 // Update piece lists
921 pieceList[us][KING][index[kfrom]] = kto;
922 pieceList[us][ROOK][index[rfrom]] = rto;
923 int tmp = index[rfrom];
924 index[kto] = index[kfrom];
927 // Update incremental scores
928 st->mgValue -= pst<MidGame>(us, KING, kfrom);
929 st->mgValue += pst<MidGame>(us, KING, kto);
930 st->egValue -= pst<EndGame>(us, KING, kfrom);
931 st->egValue += pst<EndGame>(us, KING, kto);
932 st->mgValue -= pst<MidGame>(us, ROOK, rfrom);
933 st->mgValue += pst<MidGame>(us, ROOK, rto);
934 st->egValue -= pst<EndGame>(us, ROOK, rfrom);
935 st->egValue += pst<EndGame>(us, ROOK, rto);
938 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
939 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
941 // Clear en passant square
942 if (st->epSquare != SQ_NONE)
944 st->key ^= zobEp[st->epSquare];
945 st->epSquare = SQ_NONE;
948 // Update castling rights
949 st->key ^= zobCastle[st->castleRights];
950 st->castleRights &= castleRightsMask[kfrom];
951 st->key ^= zobCastle[st->castleRights];
953 // Reset rule 50 counter
956 // Update checkers BB
957 st->checkersBB = attacks_to(king_square(them), us);
961 /// Position::do_promotion_move() is a private method used to make a promotion
962 /// move. It is called from the main Position::do_move function.
964 void Position::do_promotion_move(Move m) {
971 assert(move_is_ok(m));
972 assert(move_promotion(m));
975 them = opposite_color(us);
979 assert(relative_rank(us, to) == RANK_8);
980 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
981 assert(color_of_piece_on(to) == them || square_is_empty(to));
983 st->capture = type_of_piece_on(to);
986 do_capture_move(m, st->capture, them, to);
989 clear_bit(&(byColorBB[us]), from);
990 clear_bit(&(byTypeBB[PAWN]), from);
991 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
994 // Insert promoted piece
995 promotion = move_promotion(m);
996 assert(promotion >= KNIGHT && promotion <= QUEEN);
997 set_bit(&(byColorBB[us]), to);
998 set_bit(&(byTypeBB[promotion]), to);
999 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1000 board[to] = piece_of_color_and_type(us, promotion);
1003 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1005 // Update pawn hash key
1006 st->pawnKey ^= zobrist[us][PAWN][from];
1008 // Update material key
1009 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1010 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1012 // Update piece counts
1013 pieceCount[us][PAWN]--;
1014 pieceCount[us][promotion]++;
1016 // Update piece lists
1017 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1018 index[pieceList[us][PAWN][index[from]]] = index[from];
1019 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1020 index[to] = pieceCount[us][promotion] - 1;
1022 // Update incremental scores
1023 st->mgValue -= pst<MidGame>(us, PAWN, from);
1024 st->mgValue += pst<MidGame>(us, promotion, to);
1025 st->egValue -= pst<EndGame>(us, PAWN, from);
1026 st->egValue += pst<EndGame>(us, promotion, to);
1029 npMaterial[us] += piece_value_midgame(promotion);
1031 // Clear the en passant square
1032 if (st->epSquare != SQ_NONE)
1034 st->key ^= zobEp[st->epSquare];
1035 st->epSquare = SQ_NONE;
1038 // Update castle rights
1039 st->key ^= zobCastle[st->castleRights];
1040 st->castleRights &= castleRightsMask[to];
1041 st->key ^= zobCastle[st->castleRights];
1043 // Reset rule 50 counter
1046 // Update checkers BB
1047 st->checkersBB = attacks_to(king_square(them), us);
1051 /// Position::do_ep_move() is a private method used to make an en passant
1052 /// capture. It is called from the main Position::do_move function.
1054 void Position::do_ep_move(Move m) {
1057 Square from, to, capsq;
1060 assert(move_is_ok(m));
1061 assert(move_is_ep(m));
1063 us = side_to_move();
1064 them = opposite_color(us);
1065 from = move_from(m);
1067 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1069 assert(to == st->epSquare);
1070 assert(relative_rank(us, to) == RANK_6);
1071 assert(piece_on(to) == EMPTY);
1072 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1073 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1075 // Remove captured piece
1076 clear_bit(&(byColorBB[them]), capsq);
1077 clear_bit(&(byTypeBB[PAWN]), capsq);
1078 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1079 board[capsq] = EMPTY;
1081 // Remove moving piece from source square
1082 clear_bit(&(byColorBB[us]), from);
1083 clear_bit(&(byTypeBB[PAWN]), from);
1084 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1086 // Put moving piece on destination square
1087 set_bit(&(byColorBB[us]), to);
1088 set_bit(&(byTypeBB[PAWN]), to);
1089 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1090 board[to] = board[from];
1091 board[from] = EMPTY;
1093 // Update material hash key
1094 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1096 // Update piece count
1097 pieceCount[them][PAWN]--;
1099 // Update piece list
1100 pieceList[us][PAWN][index[from]] = to;
1101 index[to] = index[from];
1102 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1103 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1106 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1107 st->key ^= zobrist[them][PAWN][capsq];
1108 st->key ^= zobEp[st->epSquare];
1110 // Update pawn hash key
1111 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1112 st->pawnKey ^= zobrist[them][PAWN][capsq];
1114 // Update incremental scores
1115 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1116 st->mgValue -= pst<MidGame>(us, PAWN, from);
1117 st->mgValue += pst<MidGame>(us, PAWN, to);
1118 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1119 st->egValue -= pst<EndGame>(us, PAWN, from);
1120 st->egValue += pst<EndGame>(us, PAWN, to);
1122 // Reset en passant square
1123 st->epSquare = SQ_NONE;
1125 // Reset rule 50 counter
1128 // Update checkers BB
1129 st->checkersBB = attacks_to(king_square(them), us);
1133 /// Position::undo_move() unmakes a move. When it returns, the position should
1134 /// be restored to exactly the same state as before the move was made.
1136 void Position::undo_move(Move m) {
1139 assert(move_is_ok(m));
1142 sideToMove = opposite_color(sideToMove);
1144 if (move_is_castle(m))
1145 undo_castle_move(m);
1146 else if (move_promotion(m))
1147 undo_promotion_move(m);
1148 else if (move_is_ep(m))
1156 us = side_to_move();
1157 them = opposite_color(us);
1158 from = move_from(m);
1161 assert(piece_on(from) == EMPTY);
1162 assert(color_of_piece_on(to) == us);
1164 // Put the piece back at the source square
1165 piece = type_of_piece_on(to);
1166 set_bit(&(byColorBB[us]), from);
1167 set_bit(&(byTypeBB[piece]), from);
1168 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1169 board[from] = piece_of_color_and_type(us, piece);
1171 // Clear the destination square
1172 clear_bit(&(byColorBB[us]), to);
1173 clear_bit(&(byTypeBB[piece]), to);
1174 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1176 // If the moving piece was a king, update the king square
1178 kingSquare[us] = from;
1180 // Update piece list
1181 pieceList[us][piece][index[to]] = from;
1182 index[from] = index[to];
1186 assert(st->capture != KING);
1188 // Replace the captured piece
1189 set_bit(&(byColorBB[them]), to);
1190 set_bit(&(byTypeBB[st->capture]), to);
1191 set_bit(&(byTypeBB[0]), to);
1192 board[to] = piece_of_color_and_type(them, st->capture);
1195 if (st->capture != PAWN)
1196 npMaterial[them] += piece_value_midgame(st->capture);
1198 // Update piece list
1199 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1200 index[to] = pieceCount[them][st->capture];
1202 // Update piece count
1203 pieceCount[them][st->capture]++;
1208 // Finally point out state pointer back to the previous state
1215 /// Position::undo_castle_move() is a private method used to unmake a castling
1216 /// move. It is called from the main Position::undo_move function. Note that
1217 /// castling moves are encoded as "king captures friendly rook" moves, for
1218 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1220 void Position::undo_castle_move(Move m) {
1222 assert(move_is_ok(m));
1223 assert(move_is_castle(m));
1225 // When we have arrived here, some work has already been done by
1226 // Position::undo_move. In particular, the side to move has been switched,
1227 // so the code below is correct.
1228 Color us = side_to_move();
1230 // Find source squares for king and rook
1231 Square kfrom = move_from(m);
1232 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1235 // Find destination squares for king and rook
1236 if (rfrom > kfrom) // O-O
1238 kto = relative_square(us, SQ_G1);
1239 rto = relative_square(us, SQ_F1);
1241 kto = relative_square(us, SQ_C1);
1242 rto = relative_square(us, SQ_D1);
1245 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1246 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1248 // Remove pieces from destination squares
1249 clear_bit(&(byColorBB[us]), kto);
1250 clear_bit(&(byTypeBB[KING]), kto);
1251 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1252 clear_bit(&(byColorBB[us]), rto);
1253 clear_bit(&(byTypeBB[ROOK]), rto);
1254 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1256 // Put pieces on source squares
1257 set_bit(&(byColorBB[us]), kfrom);
1258 set_bit(&(byTypeBB[KING]), kfrom);
1259 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1260 set_bit(&(byColorBB[us]), rfrom);
1261 set_bit(&(byTypeBB[ROOK]), rfrom);
1262 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1265 board[rto] = board[kto] = EMPTY;
1266 board[rfrom] = piece_of_color_and_type(us, ROOK);
1267 board[kfrom] = piece_of_color_and_type(us, KING);
1269 // Update king square
1270 kingSquare[us] = kfrom;
1272 // Update piece lists
1273 pieceList[us][KING][index[kto]] = kfrom;
1274 pieceList[us][ROOK][index[rto]] = rfrom;
1275 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1276 index[kfrom] = index[kto];
1281 /// Position::undo_promotion_move() is a private method used to unmake a
1282 /// promotion move. It is called from the main Position::do_move
1285 void Position::undo_promotion_move(Move m) {
1289 PieceType promotion;
1291 assert(move_is_ok(m));
1292 assert(move_promotion(m));
1294 // When we have arrived here, some work has already been done by
1295 // Position::undo_move. In particular, the side to move has been switched,
1296 // so the code below is correct.
1297 us = side_to_move();
1298 them = opposite_color(us);
1299 from = move_from(m);
1302 assert(relative_rank(us, to) == RANK_8);
1303 assert(piece_on(from) == EMPTY);
1305 // Remove promoted piece
1306 promotion = move_promotion(m);
1307 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1308 assert(promotion >= KNIGHT && promotion <= QUEEN);
1309 clear_bit(&(byColorBB[us]), to);
1310 clear_bit(&(byTypeBB[promotion]), to);
1311 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1313 // Insert pawn at source square
1314 set_bit(&(byColorBB[us]), from);
1315 set_bit(&(byTypeBB[PAWN]), from);
1316 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1317 board[from] = piece_of_color_and_type(us, PAWN);
1320 npMaterial[us] -= piece_value_midgame(promotion);
1322 // Update piece list
1323 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1324 index[from] = pieceCount[us][PAWN];
1325 pieceList[us][promotion][index[to]] =
1326 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1327 index[pieceList[us][promotion][index[to]]] = index[to];
1329 // Update piece counts
1330 pieceCount[us][promotion]--;
1331 pieceCount[us][PAWN]++;
1335 assert(st->capture != KING);
1337 // Insert captured piece:
1338 set_bit(&(byColorBB[them]), to);
1339 set_bit(&(byTypeBB[st->capture]), to);
1340 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1341 board[to] = piece_of_color_and_type(them, st->capture);
1343 // Update material. Because the move is a promotion move, we know
1344 // that the captured piece cannot be a pawn.
1345 assert(st->capture != PAWN);
1346 npMaterial[them] += piece_value_midgame(st->capture);
1348 // Update piece list
1349 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1350 index[to] = pieceCount[them][st->capture];
1352 // Update piece count
1353 pieceCount[them][st->capture]++;
1359 /// Position::undo_ep_move() is a private method used to unmake an en passant
1360 /// capture. It is called from the main Position::undo_move function.
1362 void Position::undo_ep_move(Move m) {
1364 assert(move_is_ok(m));
1365 assert(move_is_ep(m));
1367 // When we have arrived here, some work has already been done by
1368 // Position::undo_move. In particular, the side to move has been switched,
1369 // so the code below is correct.
1370 Color us = side_to_move();
1371 Color them = opposite_color(us);
1372 Square from = move_from(m);
1373 Square to = move_to(m);
1374 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1376 assert(to == st->previous->epSquare);
1377 assert(relative_rank(us, to) == RANK_6);
1378 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1379 assert(piece_on(from) == EMPTY);
1380 assert(piece_on(capsq) == EMPTY);
1382 // Replace captured piece
1383 set_bit(&(byColorBB[them]), capsq);
1384 set_bit(&(byTypeBB[PAWN]), capsq);
1385 set_bit(&(byTypeBB[0]), capsq);
1386 board[capsq] = piece_of_color_and_type(them, PAWN);
1388 // Remove moving piece from destination square
1389 clear_bit(&(byColorBB[us]), to);
1390 clear_bit(&(byTypeBB[PAWN]), to);
1391 clear_bit(&(byTypeBB[0]), to);
1394 // Replace moving piece at source square
1395 set_bit(&(byColorBB[us]), from);
1396 set_bit(&(byTypeBB[PAWN]), from);
1397 set_bit(&(byTypeBB[0]), from);
1398 board[from] = piece_of_color_and_type(us, PAWN);
1400 // Update piece list:
1401 pieceList[us][PAWN][index[to]] = from;
1402 index[from] = index[to];
1403 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1404 index[capsq] = pieceCount[them][PAWN];
1406 // Update piece count:
1407 pieceCount[them][PAWN]++;
1411 /// Position::do_null_move makes() a "null move": It switches the side to move
1412 /// and updates the hash key without executing any move on the board.
1414 void Position::do_null_move(StateInfo& newSt) {
1417 assert(!is_check());
1419 // Back up the information necessary to undo the null move to the supplied
1420 // StateInfo object. In the case of a null move, the only thing we need to
1421 // remember is the last move made and the en passant square.
1422 newSt.lastMove = st->lastMove;
1423 newSt.epSquare = st->epSquare;
1424 newSt.previous = st->previous;
1425 st->previous = &newSt;
1427 // Save the current key to the history[] array, in order to be able to
1428 // detect repetition draws.
1429 history[gamePly] = st->key;
1431 // Update the necessary information
1432 sideToMove = opposite_color(sideToMove);
1433 if (st->epSquare != SQ_NONE)
1434 st->key ^= zobEp[st->epSquare];
1436 st->epSquare = SQ_NONE;
1439 st->key ^= zobSideToMove;
1441 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1442 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1448 /// Position::undo_null_move() unmakes a "null move".
1450 void Position::undo_null_move() {
1453 assert(!is_check());
1455 // Restore information from the our StateInfo object
1456 st->lastMove = st->previous->lastMove;
1457 st->epSquare = st->previous->epSquare;
1458 st->previous = st->previous->previous;
1460 if (st->epSquare != SQ_NONE)
1461 st->key ^= zobEp[st->epSquare];
1463 // Update the necessary information
1464 sideToMove = opposite_color(sideToMove);
1467 st->key ^= zobSideToMove;
1469 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1470 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1476 /// Position::see() is a static exchange evaluator: It tries to estimate the
1477 /// material gain or loss resulting from a move. There are three versions of
1478 /// this function: One which takes a destination square as input, one takes a
1479 /// move, and one which takes a 'from' and a 'to' square. The function does
1480 /// not yet understand promotions captures.
1482 int Position::see(Square to) const {
1484 assert(square_is_ok(to));
1485 return see(SQ_NONE, to);
1488 int Position::see(Move m) const {
1490 assert(move_is_ok(m));
1491 return see(move_from(m), move_to(m));
1494 int Position::see(Square from, Square to) const {
1497 static const int seeValues[18] = {
1498 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1499 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1500 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1501 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1505 Bitboard attackers, occ, b;
1507 assert(square_is_ok(from) || from == SQ_NONE);
1508 assert(square_is_ok(to));
1510 // Initialize colors
1511 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1512 Color them = opposite_color(us);
1514 // Initialize pieces
1515 Piece piece = piece_on(from);
1516 Piece capture = piece_on(to);
1518 // Find all attackers to the destination square, with the moving piece
1519 // removed, but possibly an X-ray attacker added behind it.
1520 occ = occupied_squares();
1522 // Handle en passant moves
1523 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1525 assert(capture == EMPTY);
1527 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1528 capture = piece_on(capQq);
1530 assert(type_of_piece_on(capQq) == PAWN);
1532 // Remove the captured pawn
1533 clear_bit(&occ, capQq);
1538 clear_bit(&occ, from);
1539 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1540 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1541 | (piece_attacks<KNIGHT>(to) & knights())
1542 | (piece_attacks<KING>(to) & kings())
1543 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1544 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1546 if (from != SQ_NONE)
1549 // If we don't have any attacker we are finished
1550 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1553 // Locate the least valuable attacker to the destination square
1554 // and use it to initialize from square.
1556 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1559 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1560 piece = piece_on(from);
1563 // If the opponent has no attackers we are finished
1564 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1565 return seeValues[capture];
1567 attackers &= occ; // Remove the moving piece
1569 // The destination square is defended, which makes things rather more
1570 // difficult to compute. We proceed by building up a "swap list" containing
1571 // the material gain or loss at each stop in a sequence of captures to the
1572 // destination square, where the sides alternately capture, and always
1573 // capture with the least valuable piece. After each capture, we look for
1574 // new X-ray attacks from behind the capturing piece.
1575 int lastCapturingPieceValue = seeValues[piece];
1576 int swapList[32], n = 1;
1580 swapList[0] = seeValues[capture];
1583 // Locate the least valuable attacker for the side to move. The loop
1584 // below looks like it is potentially infinite, but it isn't. We know
1585 // that the side to move still has at least one attacker left.
1586 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1589 // Remove the attacker we just found from the 'attackers' bitboard,
1590 // and scan for new X-ray attacks behind the attacker.
1591 b = attackers & pieces_of_color_and_type(c, pt);
1593 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1594 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1598 // Add the new entry to the swap list
1600 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1603 // Remember the value of the capturing piece, and change the side to move
1604 // before beginning the next iteration
1605 lastCapturingPieceValue = seeValues[pt];
1606 c = opposite_color(c);
1608 // Stop after a king capture
1609 if (pt == KING && (attackers & pieces_of_color(c)))
1612 swapList[n++] = 100;
1615 } while (attackers & pieces_of_color(c));
1617 // Having built the swap list, we negamax through it to find the best
1618 // achievable score from the point of view of the side to move
1620 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1626 /// Position::clear() erases the position object to a pristine state, with an
1627 /// empty board, white to move, and no castling rights.
1629 void Position::clear() {
1632 st->previous = NULL; // We should never dereference this
1634 for (int i = 0; i < 64; i++)
1640 for (int i = 0; i < 2; i++)
1641 byColorBB[i] = EmptyBoardBB;
1643 for (int i = 0; i < 7; i++)
1645 byTypeBB[i] = EmptyBoardBB;
1646 pieceCount[0][i] = pieceCount[1][i] = 0;
1647 for (int j = 0; j < 8; j++)
1648 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1651 st->checkersBB = EmptyBoardBB;
1652 for (Color c = WHITE; c <= BLACK; c++)
1653 st->pinners[c] = st->pinned[c] = st->dcCandidates[c] = ~EmptyBoardBB;
1657 initialKFile = FILE_E;
1658 initialKRFile = FILE_H;
1659 initialQRFile = FILE_A;
1661 st->lastMove = MOVE_NONE;
1662 st->castleRights = NO_CASTLES;
1663 st->epSquare = SQ_NONE;
1665 st->previous = NULL;
1669 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1670 /// UCI interface code, whenever a non-reversible move is made in a
1671 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1672 /// for the program to handle games of arbitrary length, as long as the GUI
1673 /// handles draws by the 50 move rule correctly.
1675 void Position::reset_game_ply() {
1681 /// Position::put_piece() puts a piece on the given square of the board,
1682 /// updating the board array, bitboards, and piece counts.
1684 void Position::put_piece(Piece p, Square s) {
1686 Color c = color_of_piece(p);
1687 PieceType pt = type_of_piece(p);
1690 index[s] = pieceCount[c][pt];
1691 pieceList[c][pt][index[s]] = s;
1693 set_bit(&(byTypeBB[pt]), s);
1694 set_bit(&(byColorBB[c]), s);
1695 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1697 pieceCount[c][pt]++;
1704 /// Position::allow_oo() gives the given side the right to castle kingside.
1705 /// Used when setting castling rights during parsing of FEN strings.
1707 void Position::allow_oo(Color c) {
1709 st->castleRights |= (1 + int(c));
1713 /// Position::allow_ooo() gives the given side the right to castle queenside.
1714 /// Used when setting castling rights during parsing of FEN strings.
1716 void Position::allow_ooo(Color c) {
1718 st->castleRights |= (4 + 4*int(c));
1722 /// Position::compute_key() computes the hash key of the position. The hash
1723 /// key is usually updated incrementally as moves are made and unmade, the
1724 /// compute_key() function is only used when a new position is set up, and
1725 /// to verify the correctness of the hash key when running in debug mode.
1727 Key Position::compute_key() const {
1729 Key result = Key(0ULL);
1731 for (Square s = SQ_A1; s <= SQ_H8; s++)
1732 if (square_is_occupied(s))
1733 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1735 if (ep_square() != SQ_NONE)
1736 result ^= zobEp[ep_square()];
1738 result ^= zobCastle[st->castleRights];
1739 if (side_to_move() == BLACK)
1740 result ^= zobSideToMove;
1746 /// Position::compute_pawn_key() computes the hash key of the position. The
1747 /// hash key is usually updated incrementally as moves are made and unmade,
1748 /// the compute_pawn_key() function is only used when a new position is set
1749 /// up, and to verify the correctness of the pawn hash key when running in
1752 Key Position::compute_pawn_key() const {
1754 Key result = Key(0ULL);
1758 for (Color c = WHITE; c <= BLACK; c++)
1763 s = pop_1st_bit(&b);
1764 result ^= zobrist[c][PAWN][s];
1771 /// Position::compute_material_key() computes the hash key of the position.
1772 /// The hash key is usually updated incrementally as moves are made and unmade,
1773 /// the compute_material_key() function is only used when a new position is set
1774 /// up, and to verify the correctness of the material hash key when running in
1777 Key Position::compute_material_key() const {
1779 Key result = Key(0ULL);
1780 for (Color c = WHITE; c <= BLACK; c++)
1781 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1783 int count = piece_count(c, pt);
1784 for (int i = 0; i <= count; i++)
1785 result ^= zobMaterial[c][pt][i];
1791 /// Position::compute_value() compute the incremental scores for the middle
1792 /// game and the endgame. These functions are used to initialize the incremental
1793 /// scores when a new position is set up, and to verify that the scores are correctly
1794 /// updated by do_move and undo_move when the program is running in debug mode.
1795 template<Position::GamePhase Phase>
1796 Value Position::compute_value() const {
1798 Value result = Value(0);
1802 for (Color c = WHITE; c <= BLACK; c++)
1803 for (PieceType pt = PAWN; pt <= KING; pt++)
1805 b = pieces_of_color_and_type(c, pt);
1808 s = pop_1st_bit(&b);
1809 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1810 result += pst<Phase>(c, pt, s);
1814 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1815 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1820 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1821 /// game material score for the given side. Material scores are updated
1822 /// incrementally during the search, this function is only used while
1823 /// initializing a new Position object.
1825 Value Position::compute_non_pawn_material(Color c) const {
1827 Value result = Value(0);
1830 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1832 Bitboard b = pieces_of_color_and_type(c, pt);
1835 s = pop_1st_bit(&b);
1836 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1837 result += piece_value_midgame(pt);
1844 /// Position::is_mate() returns true or false depending on whether the
1845 /// side to move is checkmated. Note that this function is currently very
1846 /// slow, and shouldn't be used frequently inside the search.
1848 bool Position::is_mate() const {
1852 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1853 return mp.get_next_move() == MOVE_NONE;
1859 /// Position::is_draw() tests whether the position is drawn by material,
1860 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1861 /// must be done by the search.
1863 bool Position::is_draw() const {
1865 // Draw by material?
1867 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1870 // Draw by the 50 moves rule?
1871 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1874 // Draw by repetition?
1875 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1876 if (history[gamePly - i] == st->key)
1883 /// Position::has_mate_threat() tests whether a given color has a mate in one
1884 /// from the current position. This function is quite slow, but it doesn't
1885 /// matter, because it is currently only called from PV nodes, which are rare.
1887 bool Position::has_mate_threat(Color c) {
1890 Color stm = side_to_move();
1892 // The following lines are useless and silly, but prevents gcc from
1893 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1894 // be used uninitialized.
1895 st1.lastMove = st->lastMove;
1896 st1.epSquare = st->epSquare;
1901 // If the input color is not equal to the side to move, do a null move
1905 MoveStack mlist[120];
1907 bool result = false;
1909 // Generate legal moves
1910 count = generate_legal_moves(*this, mlist);
1912 // Loop through the moves, and see if one of them is mate
1913 for (int i = 0; i < count; i++)
1915 do_move(mlist[i].move, st2);
1919 undo_move(mlist[i].move);
1922 // Undo null move, if necessary
1930 /// Position::init_zobrist() is a static member function which initializes the
1931 /// various arrays used to compute hash keys.
1933 void Position::init_zobrist() {
1935 for (int i = 0; i < 2; i++)
1936 for (int j = 0; j < 8; j++)
1937 for (int k = 0; k < 64; k++)
1938 zobrist[i][j][k] = Key(genrand_int64());
1940 for (int i = 0; i < 64; i++)
1941 zobEp[i] = Key(genrand_int64());
1943 for (int i = 0; i < 16; i++)
1944 zobCastle[i] = genrand_int64();
1946 zobSideToMove = genrand_int64();
1948 for (int i = 0; i < 2; i++)
1949 for (int j = 0; j < 8; j++)
1950 for (int k = 0; k < 16; k++)
1951 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1953 for (int i = 0; i < 16; i++)
1954 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1958 /// Position::init_piece_square_tables() initializes the piece square tables.
1959 /// This is a two-step operation: First, the white halves of the tables are
1960 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1961 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1962 /// Second, the black halves of the tables are initialized by mirroring
1963 /// and changing the sign of the corresponding white scores.
1965 void Position::init_piece_square_tables() {
1967 int r = get_option_value_int("Randomness"), i;
1968 for (Square s = SQ_A1; s <= SQ_H8; s++)
1969 for (Piece p = WP; p <= WK; p++)
1971 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1972 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1973 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1976 for (Square s = SQ_A1; s <= SQ_H8; s++)
1977 for (Piece p = BP; p <= BK; p++)
1979 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1980 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
1985 /// Position::flipped_copy() makes a copy of the input position, but with
1986 /// the white and black sides reversed. This is only useful for debugging,
1987 /// especially for finding evaluation symmetry bugs.
1989 void Position::flipped_copy(const Position &pos) {
1991 assert(pos.is_ok());
1996 for (Square s = SQ_A1; s <= SQ_H8; s++)
1997 if (!pos.square_is_empty(s))
1998 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2001 sideToMove = opposite_color(pos.side_to_move());
2004 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2005 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2006 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2007 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2009 initialKFile = pos.initialKFile;
2010 initialKRFile = pos.initialKRFile;
2011 initialQRFile = pos.initialQRFile;
2013 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2014 castleRightsMask[sq] = ALL_CASTLES;
2016 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2017 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2018 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2019 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2020 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2021 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2023 // En passant square
2024 if (pos.st->epSquare != SQ_NONE)
2025 st->epSquare = flip_square(pos.st->epSquare);
2031 st->key = compute_key();
2032 st->pawnKey = compute_pawn_key();
2033 st->materialKey = compute_material_key();
2035 // Incremental scores
2036 st->mgValue = compute_value<MidGame>();
2037 st->egValue = compute_value<EndGame>();
2040 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2041 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2047 /// Position::is_ok() performs some consitency checks for the position object.
2048 /// This is meant to be helpful when debugging.
2050 bool Position::is_ok(int* failedStep) const {
2052 // What features of the position should be verified?
2053 static const bool debugBitboards = false;
2054 static const bool debugKingCount = false;
2055 static const bool debugKingCapture = false;
2056 static const bool debugCheckerCount = false;
2057 static const bool debugKey = false;
2058 static const bool debugMaterialKey = false;
2059 static const bool debugPawnKey = false;
2060 static const bool debugIncrementalEval = false;
2061 static const bool debugNonPawnMaterial = false;
2062 static const bool debugPieceCounts = false;
2063 static const bool debugPieceList = false;
2065 if (failedStep) *failedStep = 1;
2068 if (!color_is_ok(side_to_move()))
2071 // Are the king squares in the position correct?
2072 if (failedStep) (*failedStep)++;
2073 if (piece_on(king_square(WHITE)) != WK)
2076 if (failedStep) (*failedStep)++;
2077 if (piece_on(king_square(BLACK)) != BK)
2081 if (failedStep) (*failedStep)++;
2082 if (!file_is_ok(initialKRFile))
2085 if (!file_is_ok(initialQRFile))
2088 // Do both sides have exactly one king?
2089 if (failedStep) (*failedStep)++;
2092 int kingCount[2] = {0, 0};
2093 for (Square s = SQ_A1; s <= SQ_H8; s++)
2094 if (type_of_piece_on(s) == KING)
2095 kingCount[color_of_piece_on(s)]++;
2097 if (kingCount[0] != 1 || kingCount[1] != 1)
2101 // Can the side to move capture the opponent's king?
2102 if (failedStep) (*failedStep)++;
2103 if (debugKingCapture)
2105 Color us = side_to_move();
2106 Color them = opposite_color(us);
2107 Square ksq = king_square(them);
2108 if (square_is_attacked(ksq, us))
2112 // Is there more than 2 checkers?
2113 if (failedStep) (*failedStep)++;
2114 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2118 if (failedStep) (*failedStep)++;
2121 // The intersection of the white and black pieces must be empty
2122 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2125 // The union of the white and black pieces must be equal to all
2127 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2130 // Separate piece type bitboards must have empty intersections
2131 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2132 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2133 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2137 // En passant square OK?
2138 if (failedStep) (*failedStep)++;
2139 if (ep_square() != SQ_NONE)
2141 // The en passant square must be on rank 6, from the point of view of the
2143 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2148 if (failedStep) (*failedStep)++;
2149 if (debugKey && st->key != compute_key())
2152 // Pawn hash key OK?
2153 if (failedStep) (*failedStep)++;
2154 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2157 // Material hash key OK?
2158 if (failedStep) (*failedStep)++;
2159 if (debugMaterialKey && st->materialKey != compute_material_key())
2162 // Incremental eval OK?
2163 if (failedStep) (*failedStep)++;
2164 if (debugIncrementalEval)
2166 if (st->mgValue != compute_value<MidGame>())
2169 if (st->egValue != compute_value<EndGame>())
2173 // Non-pawn material OK?
2174 if (failedStep) (*failedStep)++;
2175 if (debugNonPawnMaterial)
2177 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2180 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2185 if (failedStep) (*failedStep)++;
2186 if (debugPieceCounts)
2187 for (Color c = WHITE; c <= BLACK; c++)
2188 for (PieceType pt = PAWN; pt <= KING; pt++)
2189 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2192 if (failedStep) (*failedStep)++;
2195 for(Color c = WHITE; c <= BLACK; c++)
2196 for(PieceType pt = PAWN; pt <= KING; pt++)
2197 for(int i = 0; i < pieceCount[c][pt]; i++)
2199 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2202 if (index[piece_list(c, pt, i)] != i)
2206 if (failedStep) *failedStep = 0;