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::init_new_state() copies from the current state the fields
680 /// that will be updated incrementally, skips the fields, like bitboards
681 /// that will be recalculated form scratch anyway.
683 void Position::init_new_state(StateInfo& newSt) {
686 newSt.pawnKey = st->pawnKey;
687 newSt.materialKey = st->materialKey;
688 newSt.castleRights = st->castleRights;
689 newSt.rule50 = st->rule50;
690 newSt.epSquare = st->epSquare;
691 newSt.mgValue = st->mgValue;
692 newSt.egValue = st->egValue;
693 newSt.capture = NO_PIECE_TYPE;
698 /// Position::do_move() makes a move, and saves all information necessary
699 /// to a StateInfo object. The move is assumed to be legal.
700 /// Pseudo-legal moves should be filtered out before this function is called.
702 void Position::do_move(Move m, StateInfo& newSt) {
705 assert(move_is_ok(m));
707 // Get now the current (before to move) dc candidates that we will use
708 // in update_checkers().
709 Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
711 // Copy some fields of old state to our new StateInfo object (except the
712 // captured piece, which is taken care of later) and switch state pointer
713 // to point to the new, ready to be updated, state.
714 init_new_state(newSt);
717 // Save the current key to the history[] array, in order to be able to
718 // detect repetition draws.
719 history[gamePly] = st->key;
721 // Increment the 50 moves rule draw counter. Resetting it to zero in the
722 // case of non-reversible moves is taken care of later.
725 if (move_is_castle(m))
727 else if (move_promotion(m))
728 do_promotion_move(m);
729 else if (move_is_ep(m))
733 Color us = side_to_move();
734 Color them = opposite_color(us);
735 Square from = move_from(m);
736 Square to = move_to(m);
738 assert(color_of_piece_on(from) == us);
739 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
741 PieceType piece = type_of_piece_on(from);
743 st->capture = type_of_piece_on(to);
746 do_capture_move(m, st->capture, them, to);
749 clear_bit(&(byColorBB[us]), from);
750 clear_bit(&(byTypeBB[piece]), from);
751 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
752 set_bit(&(byColorBB[us]), to);
753 set_bit(&(byTypeBB[piece]), to);
754 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
755 board[to] = board[from];
759 st->key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
761 // Update incremental scores
762 st->mgValue -= pst<MidGame>(us, piece, from);
763 st->mgValue += pst<MidGame>(us, piece, to);
764 st->egValue -= pst<EndGame>(us, piece, from);
765 st->egValue += pst<EndGame>(us, piece, to);
767 // If the moving piece was a king, update the king square
771 // Reset en passant square
772 if (st->epSquare != SQ_NONE)
774 st->key ^= zobEp[st->epSquare];
775 st->epSquare = SQ_NONE;
778 // If the moving piece was a pawn do some special extra work
781 // Reset rule 50 draw counter
784 // Update pawn hash key
785 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
787 // Set en passant square, only if moved pawn can be captured
788 if (abs(int(to) - int(from)) == 16)
790 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
791 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
793 st->epSquare = Square((int(from) + int(to)) / 2);
794 st->key ^= zobEp[st->epSquare];
799 // Update piece lists
800 pieceList[us][piece][index[from]] = to;
801 index[to] = index[from];
803 // Update castle rights
804 st->key ^= zobCastle[st->castleRights];
805 st->castleRights &= castleRightsMask[from];
806 st->castleRights &= castleRightsMask[to];
807 st->key ^= zobCastle[st->castleRights];
809 // Update checkers bitboard, piece must be already moved
810 st->checkersBB = EmptyBoardBB;
811 Square ksq = king_square(them);
814 case PAWN: update_checkers<PAWN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
815 case KNIGHT: update_checkers<KNIGHT>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
816 case BISHOP: update_checkers<BISHOP>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
817 case ROOK: update_checkers<ROOK>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
818 case QUEEN: update_checkers<QUEEN>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
819 case KING: update_checkers<KING>(&st->checkersBB, ksq, from, to, oldDcCandidates); break;
820 default: assert(false); break;
826 st->key ^= zobSideToMove;
827 sideToMove = opposite_color(sideToMove);
830 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
831 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
837 /// Position::do_capture_move() is a private method used to update captured
838 /// piece info. It is called from the main Position::do_move function.
840 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
842 assert(capture != KING);
844 // Remove captured piece
845 clear_bit(&(byColorBB[them]), to);
846 clear_bit(&(byTypeBB[capture]), to);
849 st->key ^= zobrist[them][capture][to];
851 // If the captured piece was a pawn, update pawn hash key
853 st->pawnKey ^= zobrist[them][PAWN][to];
855 // Update incremental scores
856 st->mgValue -= pst<MidGame>(them, capture, to);
857 st->egValue -= pst<EndGame>(them, capture, to);
859 assert(!move_promotion(m) || capture != PAWN);
863 npMaterial[them] -= piece_value_midgame(capture);
865 // Update material hash key
866 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
868 // Update piece count
869 pieceCount[them][capture]--;
872 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
873 index[pieceList[them][capture][index[to]]] = index[to];
875 // Reset rule 50 counter
880 /// Position::do_castle_move() is a private method used to make a castling
881 /// move. It is called from the main Position::do_move function. Note that
882 /// castling moves are encoded as "king captures friendly rook" moves, for
883 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
885 void Position::do_castle_move(Move m) {
888 assert(move_is_ok(m));
889 assert(move_is_castle(m));
891 Color us = side_to_move();
892 Color them = opposite_color(us);
894 // Find source squares for king and rook
895 Square kfrom = move_from(m);
896 Square rfrom = move_to(m); // HACK: See comment at beginning of function
899 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
900 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
902 // Find destination squares for king and rook
903 if (rfrom > kfrom) // O-O
905 kto = relative_square(us, SQ_G1);
906 rto = relative_square(us, SQ_F1);
908 kto = relative_square(us, SQ_C1);
909 rto = relative_square(us, SQ_D1);
912 // Remove pieces from source squares
913 clear_bit(&(byColorBB[us]), kfrom);
914 clear_bit(&(byTypeBB[KING]), kfrom);
915 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
916 clear_bit(&(byColorBB[us]), rfrom);
917 clear_bit(&(byTypeBB[ROOK]), rfrom);
918 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
920 // Put pieces on destination squares
921 set_bit(&(byColorBB[us]), kto);
922 set_bit(&(byTypeBB[KING]), kto);
923 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
924 set_bit(&(byColorBB[us]), rto);
925 set_bit(&(byTypeBB[ROOK]), rto);
926 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
928 // Update board array
929 board[kfrom] = board[rfrom] = EMPTY;
930 board[kto] = piece_of_color_and_type(us, KING);
931 board[rto] = piece_of_color_and_type(us, ROOK);
933 // Update king square
934 kingSquare[us] = kto;
936 // Update piece lists
937 pieceList[us][KING][index[kfrom]] = kto;
938 pieceList[us][ROOK][index[rfrom]] = rto;
939 int tmp = index[rfrom];
940 index[kto] = index[kfrom];
943 // Update incremental scores
944 st->mgValue -= pst<MidGame>(us, KING, kfrom);
945 st->mgValue += pst<MidGame>(us, KING, kto);
946 st->egValue -= pst<EndGame>(us, KING, kfrom);
947 st->egValue += pst<EndGame>(us, KING, kto);
948 st->mgValue -= pst<MidGame>(us, ROOK, rfrom);
949 st->mgValue += pst<MidGame>(us, ROOK, rto);
950 st->egValue -= pst<EndGame>(us, ROOK, rfrom);
951 st->egValue += pst<EndGame>(us, ROOK, rto);
954 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
955 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
957 // Clear en passant square
958 if (st->epSquare != SQ_NONE)
960 st->key ^= zobEp[st->epSquare];
961 st->epSquare = SQ_NONE;
964 // Update castling rights
965 st->key ^= zobCastle[st->castleRights];
966 st->castleRights &= castleRightsMask[kfrom];
967 st->key ^= zobCastle[st->castleRights];
969 // Reset rule 50 counter
972 // Update checkers BB
973 st->checkersBB = attacks_to(king_square(them), us);
977 /// Position::do_promotion_move() is a private method used to make a promotion
978 /// move. It is called from the main Position::do_move function.
980 void Position::do_promotion_move(Move m) {
987 assert(move_is_ok(m));
988 assert(move_promotion(m));
991 them = opposite_color(us);
995 assert(relative_rank(us, to) == RANK_8);
996 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
997 assert(color_of_piece_on(to) == them || square_is_empty(to));
999 st->capture = type_of_piece_on(to);
1002 do_capture_move(m, st->capture, them, to);
1005 clear_bit(&(byColorBB[us]), from);
1006 clear_bit(&(byTypeBB[PAWN]), from);
1007 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1008 board[from] = EMPTY;
1010 // Insert promoted piece
1011 promotion = move_promotion(m);
1012 assert(promotion >= KNIGHT && promotion <= QUEEN);
1013 set_bit(&(byColorBB[us]), to);
1014 set_bit(&(byTypeBB[promotion]), to);
1015 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1016 board[to] = piece_of_color_and_type(us, promotion);
1019 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1021 // Update pawn hash key
1022 st->pawnKey ^= zobrist[us][PAWN][from];
1024 // Update material key
1025 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1026 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1028 // Update piece counts
1029 pieceCount[us][PAWN]--;
1030 pieceCount[us][promotion]++;
1032 // Update piece lists
1033 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1034 index[pieceList[us][PAWN][index[from]]] = index[from];
1035 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1036 index[to] = pieceCount[us][promotion] - 1;
1038 // Update incremental scores
1039 st->mgValue -= pst<MidGame>(us, PAWN, from);
1040 st->mgValue += pst<MidGame>(us, promotion, to);
1041 st->egValue -= pst<EndGame>(us, PAWN, from);
1042 st->egValue += pst<EndGame>(us, promotion, to);
1045 npMaterial[us] += piece_value_midgame(promotion);
1047 // Clear the en passant square
1048 if (st->epSquare != SQ_NONE)
1050 st->key ^= zobEp[st->epSquare];
1051 st->epSquare = SQ_NONE;
1054 // Update castle rights
1055 st->key ^= zobCastle[st->castleRights];
1056 st->castleRights &= castleRightsMask[to];
1057 st->key ^= zobCastle[st->castleRights];
1059 // Reset rule 50 counter
1062 // Update checkers BB
1063 st->checkersBB = attacks_to(king_square(them), us);
1067 /// Position::do_ep_move() is a private method used to make an en passant
1068 /// capture. It is called from the main Position::do_move function.
1070 void Position::do_ep_move(Move m) {
1073 Square from, to, capsq;
1076 assert(move_is_ok(m));
1077 assert(move_is_ep(m));
1079 us = side_to_move();
1080 them = opposite_color(us);
1081 from = move_from(m);
1083 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1085 assert(to == st->epSquare);
1086 assert(relative_rank(us, to) == RANK_6);
1087 assert(piece_on(to) == EMPTY);
1088 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1089 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1091 // Remove captured piece
1092 clear_bit(&(byColorBB[them]), capsq);
1093 clear_bit(&(byTypeBB[PAWN]), capsq);
1094 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1095 board[capsq] = EMPTY;
1097 // Remove moving piece from source square
1098 clear_bit(&(byColorBB[us]), from);
1099 clear_bit(&(byTypeBB[PAWN]), from);
1100 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1102 // Put moving piece on destination square
1103 set_bit(&(byColorBB[us]), to);
1104 set_bit(&(byTypeBB[PAWN]), to);
1105 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1106 board[to] = board[from];
1107 board[from] = EMPTY;
1109 // Update material hash key
1110 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1112 // Update piece count
1113 pieceCount[them][PAWN]--;
1115 // Update piece list
1116 pieceList[us][PAWN][index[from]] = to;
1117 index[to] = index[from];
1118 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1119 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1122 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1123 st->key ^= zobrist[them][PAWN][capsq];
1124 st->key ^= zobEp[st->epSquare];
1126 // Update pawn hash key
1127 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1128 st->pawnKey ^= zobrist[them][PAWN][capsq];
1130 // Update incremental scores
1131 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1132 st->mgValue -= pst<MidGame>(us, PAWN, from);
1133 st->mgValue += pst<MidGame>(us, PAWN, to);
1134 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1135 st->egValue -= pst<EndGame>(us, PAWN, from);
1136 st->egValue += pst<EndGame>(us, PAWN, to);
1138 // Reset en passant square
1139 st->epSquare = SQ_NONE;
1141 // Reset rule 50 counter
1144 // Update checkers BB
1145 st->checkersBB = attacks_to(king_square(them), us);
1149 /// Position::undo_move() unmakes a move. When it returns, the position should
1150 /// be restored to exactly the same state as before the move was made.
1152 void Position::undo_move(Move m) {
1155 assert(move_is_ok(m));
1158 sideToMove = opposite_color(sideToMove);
1160 if (move_is_castle(m))
1161 undo_castle_move(m);
1162 else if (move_promotion(m))
1163 undo_promotion_move(m);
1164 else if (move_is_ep(m))
1172 us = side_to_move();
1173 them = opposite_color(us);
1174 from = move_from(m);
1177 assert(piece_on(from) == EMPTY);
1178 assert(color_of_piece_on(to) == us);
1180 // Put the piece back at the source square
1181 piece = type_of_piece_on(to);
1182 set_bit(&(byColorBB[us]), from);
1183 set_bit(&(byTypeBB[piece]), from);
1184 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1185 board[from] = piece_of_color_and_type(us, piece);
1187 // Clear the destination square
1188 clear_bit(&(byColorBB[us]), to);
1189 clear_bit(&(byTypeBB[piece]), to);
1190 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1192 // If the moving piece was a king, update the king square
1194 kingSquare[us] = from;
1196 // Update piece list
1197 pieceList[us][piece][index[to]] = from;
1198 index[from] = index[to];
1202 assert(st->capture != KING);
1204 // Replace the captured piece
1205 set_bit(&(byColorBB[them]), to);
1206 set_bit(&(byTypeBB[st->capture]), to);
1207 set_bit(&(byTypeBB[0]), to);
1208 board[to] = piece_of_color_and_type(them, st->capture);
1211 if (st->capture != PAWN)
1212 npMaterial[them] += piece_value_midgame(st->capture);
1214 // Update piece list
1215 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1216 index[to] = pieceCount[them][st->capture];
1218 // Update piece count
1219 pieceCount[them][st->capture]++;
1224 // Finally point out state pointer back to the previous state
1231 /// Position::undo_castle_move() is a private method used to unmake a castling
1232 /// move. It is called from the main Position::undo_move function. Note that
1233 /// castling moves are encoded as "king captures friendly rook" moves, for
1234 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1236 void Position::undo_castle_move(Move m) {
1238 assert(move_is_ok(m));
1239 assert(move_is_castle(m));
1241 // When we have arrived here, some work has already been done by
1242 // Position::undo_move. In particular, the side to move has been switched,
1243 // so the code below is correct.
1244 Color us = side_to_move();
1246 // Find source squares for king and rook
1247 Square kfrom = move_from(m);
1248 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1251 // Find destination squares for king and rook
1252 if (rfrom > kfrom) // O-O
1254 kto = relative_square(us, SQ_G1);
1255 rto = relative_square(us, SQ_F1);
1257 kto = relative_square(us, SQ_C1);
1258 rto = relative_square(us, SQ_D1);
1261 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1262 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1264 // Remove pieces from destination squares
1265 clear_bit(&(byColorBB[us]), kto);
1266 clear_bit(&(byTypeBB[KING]), kto);
1267 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1268 clear_bit(&(byColorBB[us]), rto);
1269 clear_bit(&(byTypeBB[ROOK]), rto);
1270 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1272 // Put pieces on source squares
1273 set_bit(&(byColorBB[us]), kfrom);
1274 set_bit(&(byTypeBB[KING]), kfrom);
1275 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1276 set_bit(&(byColorBB[us]), rfrom);
1277 set_bit(&(byTypeBB[ROOK]), rfrom);
1278 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1281 board[rto] = board[kto] = EMPTY;
1282 board[rfrom] = piece_of_color_and_type(us, ROOK);
1283 board[kfrom] = piece_of_color_and_type(us, KING);
1285 // Update king square
1286 kingSquare[us] = kfrom;
1288 // Update piece lists
1289 pieceList[us][KING][index[kto]] = kfrom;
1290 pieceList[us][ROOK][index[rto]] = rfrom;
1291 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1292 index[kfrom] = index[kto];
1297 /// Position::undo_promotion_move() is a private method used to unmake a
1298 /// promotion move. It is called from the main Position::do_move
1301 void Position::undo_promotion_move(Move m) {
1305 PieceType promotion;
1307 assert(move_is_ok(m));
1308 assert(move_promotion(m));
1310 // When we have arrived here, some work has already been done by
1311 // Position::undo_move. In particular, the side to move has been switched,
1312 // so the code below is correct.
1313 us = side_to_move();
1314 them = opposite_color(us);
1315 from = move_from(m);
1318 assert(relative_rank(us, to) == RANK_8);
1319 assert(piece_on(from) == EMPTY);
1321 // Remove promoted piece
1322 promotion = move_promotion(m);
1323 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1324 assert(promotion >= KNIGHT && promotion <= QUEEN);
1325 clear_bit(&(byColorBB[us]), to);
1326 clear_bit(&(byTypeBB[promotion]), to);
1327 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1329 // Insert pawn at source square
1330 set_bit(&(byColorBB[us]), from);
1331 set_bit(&(byTypeBB[PAWN]), from);
1332 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1333 board[from] = piece_of_color_and_type(us, PAWN);
1336 npMaterial[us] -= piece_value_midgame(promotion);
1338 // Update piece list
1339 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1340 index[from] = pieceCount[us][PAWN];
1341 pieceList[us][promotion][index[to]] =
1342 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1343 index[pieceList[us][promotion][index[to]]] = index[to];
1345 // Update piece counts
1346 pieceCount[us][promotion]--;
1347 pieceCount[us][PAWN]++;
1351 assert(st->capture != KING);
1353 // Insert captured piece:
1354 set_bit(&(byColorBB[them]), to);
1355 set_bit(&(byTypeBB[st->capture]), to);
1356 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1357 board[to] = piece_of_color_and_type(them, st->capture);
1359 // Update material. Because the move is a promotion move, we know
1360 // that the captured piece cannot be a pawn.
1361 assert(st->capture != PAWN);
1362 npMaterial[them] += piece_value_midgame(st->capture);
1364 // Update piece list
1365 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1366 index[to] = pieceCount[them][st->capture];
1368 // Update piece count
1369 pieceCount[them][st->capture]++;
1375 /// Position::undo_ep_move() is a private method used to unmake an en passant
1376 /// capture. It is called from the main Position::undo_move function.
1378 void Position::undo_ep_move(Move m) {
1380 assert(move_is_ok(m));
1381 assert(move_is_ep(m));
1383 // When we have arrived here, some work has already been done by
1384 // Position::undo_move. In particular, the side to move has been switched,
1385 // so the code below is correct.
1386 Color us = side_to_move();
1387 Color them = opposite_color(us);
1388 Square from = move_from(m);
1389 Square to = move_to(m);
1390 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1392 assert(to == st->previous->epSquare);
1393 assert(relative_rank(us, to) == RANK_6);
1394 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1395 assert(piece_on(from) == EMPTY);
1396 assert(piece_on(capsq) == EMPTY);
1398 // Replace captured piece
1399 set_bit(&(byColorBB[them]), capsq);
1400 set_bit(&(byTypeBB[PAWN]), capsq);
1401 set_bit(&(byTypeBB[0]), capsq);
1402 board[capsq] = piece_of_color_and_type(them, PAWN);
1404 // Remove moving piece from destination square
1405 clear_bit(&(byColorBB[us]), to);
1406 clear_bit(&(byTypeBB[PAWN]), to);
1407 clear_bit(&(byTypeBB[0]), to);
1410 // Replace moving piece at source square
1411 set_bit(&(byColorBB[us]), from);
1412 set_bit(&(byTypeBB[PAWN]), from);
1413 set_bit(&(byTypeBB[0]), from);
1414 board[from] = piece_of_color_and_type(us, PAWN);
1416 // Update piece list:
1417 pieceList[us][PAWN][index[to]] = from;
1418 index[from] = index[to];
1419 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1420 index[capsq] = pieceCount[them][PAWN];
1422 // Update piece count:
1423 pieceCount[them][PAWN]++;
1427 /// Position::do_null_move makes() a "null move": It switches the side to move
1428 /// and updates the hash key without executing any move on the board.
1430 void Position::do_null_move(StateInfo& newSt) {
1433 assert(!is_check());
1435 // Back up the information necessary to undo the null move to the supplied
1436 // StateInfo object. In the case of a null move, the only thing we need to
1437 // remember is the last move made and the en passant square.
1438 newSt.lastMove = st->lastMove;
1439 newSt.epSquare = st->epSquare;
1440 newSt.previous = st->previous;
1441 st->previous = &newSt;
1443 // Save the current key to the history[] array, in order to be able to
1444 // detect repetition draws.
1445 history[gamePly] = st->key;
1447 // Update the necessary information
1448 sideToMove = opposite_color(sideToMove);
1449 if (st->epSquare != SQ_NONE)
1450 st->key ^= zobEp[st->epSquare];
1452 st->epSquare = SQ_NONE;
1455 st->key ^= zobSideToMove;
1457 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1458 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1464 /// Position::undo_null_move() unmakes a "null move".
1466 void Position::undo_null_move() {
1469 assert(!is_check());
1471 // Restore information from the our StateInfo object
1472 st->lastMove = st->previous->lastMove;
1473 st->epSquare = st->previous->epSquare;
1474 st->previous = st->previous->previous;
1476 if (st->epSquare != SQ_NONE)
1477 st->key ^= zobEp[st->epSquare];
1479 // Update the necessary information
1480 sideToMove = opposite_color(sideToMove);
1483 st->key ^= zobSideToMove;
1485 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1486 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1492 /// Position::see() is a static exchange evaluator: It tries to estimate the
1493 /// material gain or loss resulting from a move. There are three versions of
1494 /// this function: One which takes a destination square as input, one takes a
1495 /// move, and one which takes a 'from' and a 'to' square. The function does
1496 /// not yet understand promotions captures.
1498 int Position::see(Square to) const {
1500 assert(square_is_ok(to));
1501 return see(SQ_NONE, to);
1504 int Position::see(Move m) const {
1506 assert(move_is_ok(m));
1507 return see(move_from(m), move_to(m));
1510 int Position::see(Square from, Square to) const {
1513 static const int seeValues[18] = {
1514 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1515 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1516 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1517 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1521 Bitboard attackers, occ, b;
1523 assert(square_is_ok(from) || from == SQ_NONE);
1524 assert(square_is_ok(to));
1526 // Initialize colors
1527 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1528 Color them = opposite_color(us);
1530 // Initialize pieces
1531 Piece piece = piece_on(from);
1532 Piece capture = piece_on(to);
1534 // Find all attackers to the destination square, with the moving piece
1535 // removed, but possibly an X-ray attacker added behind it.
1536 occ = occupied_squares();
1538 // Handle en passant moves
1539 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1541 assert(capture == EMPTY);
1543 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1544 capture = piece_on(capQq);
1546 assert(type_of_piece_on(capQq) == PAWN);
1548 // Remove the captured pawn
1549 clear_bit(&occ, capQq);
1554 clear_bit(&occ, from);
1555 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1556 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1557 | (piece_attacks<KNIGHT>(to) & knights())
1558 | (piece_attacks<KING>(to) & kings())
1559 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1560 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1562 if (from != SQ_NONE)
1565 // If we don't have any attacker we are finished
1566 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1569 // Locate the least valuable attacker to the destination square
1570 // and use it to initialize from square.
1572 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1575 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1576 piece = piece_on(from);
1579 // If the opponent has no attackers we are finished
1580 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1581 return seeValues[capture];
1583 attackers &= occ; // Remove the moving piece
1585 // The destination square is defended, which makes things rather more
1586 // difficult to compute. We proceed by building up a "swap list" containing
1587 // the material gain or loss at each stop in a sequence of captures to the
1588 // destination square, where the sides alternately capture, and always
1589 // capture with the least valuable piece. After each capture, we look for
1590 // new X-ray attacks from behind the capturing piece.
1591 int lastCapturingPieceValue = seeValues[piece];
1592 int swapList[32], n = 1;
1596 swapList[0] = seeValues[capture];
1599 // Locate the least valuable attacker for the side to move. The loop
1600 // below looks like it is potentially infinite, but it isn't. We know
1601 // that the side to move still has at least one attacker left.
1602 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1605 // Remove the attacker we just found from the 'attackers' bitboard,
1606 // and scan for new X-ray attacks behind the attacker.
1607 b = attackers & pieces_of_color_and_type(c, pt);
1609 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1610 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1614 // Add the new entry to the swap list
1616 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1619 // Remember the value of the capturing piece, and change the side to move
1620 // before beginning the next iteration
1621 lastCapturingPieceValue = seeValues[pt];
1622 c = opposite_color(c);
1624 // Stop after a king capture
1625 if (pt == KING && (attackers & pieces_of_color(c)))
1628 swapList[n++] = 100;
1631 } while (attackers & pieces_of_color(c));
1633 // Having built the swap list, we negamax through it to find the best
1634 // achievable score from the point of view of the side to move
1636 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1642 /// Position::clear() erases the position object to a pristine state, with an
1643 /// empty board, white to move, and no castling rights.
1645 void Position::clear() {
1648 st->previous = NULL; // We should never dereference this
1650 for (int i = 0; i < 64; i++)
1656 for (int i = 0; i < 2; i++)
1657 byColorBB[i] = EmptyBoardBB;
1659 for (int i = 0; i < 7; i++)
1661 byTypeBB[i] = EmptyBoardBB;
1662 pieceCount[0][i] = pieceCount[1][i] = 0;
1663 for (int j = 0; j < 8; j++)
1664 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1667 st->checkersBB = EmptyBoardBB;
1668 for (Color c = WHITE; c <= BLACK; c++)
1669 st->pinners[c] = st->pinned[c] = st->dcCandidates[c] = ~EmptyBoardBB;
1673 initialKFile = FILE_E;
1674 initialKRFile = FILE_H;
1675 initialQRFile = FILE_A;
1677 st->lastMove = MOVE_NONE;
1678 st->castleRights = NO_CASTLES;
1679 st->epSquare = SQ_NONE;
1681 st->previous = NULL;
1685 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1686 /// UCI interface code, whenever a non-reversible move is made in a
1687 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1688 /// for the program to handle games of arbitrary length, as long as the GUI
1689 /// handles draws by the 50 move rule correctly.
1691 void Position::reset_game_ply() {
1697 /// Position::put_piece() puts a piece on the given square of the board,
1698 /// updating the board array, bitboards, and piece counts.
1700 void Position::put_piece(Piece p, Square s) {
1702 Color c = color_of_piece(p);
1703 PieceType pt = type_of_piece(p);
1706 index[s] = pieceCount[c][pt];
1707 pieceList[c][pt][index[s]] = s;
1709 set_bit(&(byTypeBB[pt]), s);
1710 set_bit(&(byColorBB[c]), s);
1711 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1713 pieceCount[c][pt]++;
1720 /// Position::allow_oo() gives the given side the right to castle kingside.
1721 /// Used when setting castling rights during parsing of FEN strings.
1723 void Position::allow_oo(Color c) {
1725 st->castleRights |= (1 + int(c));
1729 /// Position::allow_ooo() gives the given side the right to castle queenside.
1730 /// Used when setting castling rights during parsing of FEN strings.
1732 void Position::allow_ooo(Color c) {
1734 st->castleRights |= (4 + 4*int(c));
1738 /// Position::compute_key() computes the hash key of the position. The hash
1739 /// key is usually updated incrementally as moves are made and unmade, the
1740 /// compute_key() function is only used when a new position is set up, and
1741 /// to verify the correctness of the hash key when running in debug mode.
1743 Key Position::compute_key() const {
1745 Key result = Key(0ULL);
1747 for (Square s = SQ_A1; s <= SQ_H8; s++)
1748 if (square_is_occupied(s))
1749 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1751 if (ep_square() != SQ_NONE)
1752 result ^= zobEp[ep_square()];
1754 result ^= zobCastle[st->castleRights];
1755 if (side_to_move() == BLACK)
1756 result ^= zobSideToMove;
1762 /// Position::compute_pawn_key() computes the hash key of the position. The
1763 /// hash key is usually updated incrementally as moves are made and unmade,
1764 /// the compute_pawn_key() function is only used when a new position is set
1765 /// up, and to verify the correctness of the pawn hash key when running in
1768 Key Position::compute_pawn_key() const {
1770 Key result = Key(0ULL);
1774 for (Color c = WHITE; c <= BLACK; c++)
1779 s = pop_1st_bit(&b);
1780 result ^= zobrist[c][PAWN][s];
1787 /// Position::compute_material_key() computes the hash key of the position.
1788 /// The hash key is usually updated incrementally as moves are made and unmade,
1789 /// the compute_material_key() function is only used when a new position is set
1790 /// up, and to verify the correctness of the material hash key when running in
1793 Key Position::compute_material_key() const {
1795 Key result = Key(0ULL);
1796 for (Color c = WHITE; c <= BLACK; c++)
1797 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1799 int count = piece_count(c, pt);
1800 for (int i = 0; i <= count; i++)
1801 result ^= zobMaterial[c][pt][i];
1807 /// Position::compute_value() compute the incremental scores for the middle
1808 /// game and the endgame. These functions are used to initialize the incremental
1809 /// scores when a new position is set up, and to verify that the scores are correctly
1810 /// updated by do_move and undo_move when the program is running in debug mode.
1811 template<Position::GamePhase Phase>
1812 Value Position::compute_value() const {
1814 Value result = Value(0);
1818 for (Color c = WHITE; c <= BLACK; c++)
1819 for (PieceType pt = PAWN; pt <= KING; pt++)
1821 b = pieces_of_color_and_type(c, pt);
1824 s = pop_1st_bit(&b);
1825 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1826 result += pst<Phase>(c, pt, s);
1830 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1831 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1836 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1837 /// game material score for the given side. Material scores are updated
1838 /// incrementally during the search, this function is only used while
1839 /// initializing a new Position object.
1841 Value Position::compute_non_pawn_material(Color c) const {
1843 Value result = Value(0);
1846 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1848 Bitboard b = pieces_of_color_and_type(c, pt);
1851 s = pop_1st_bit(&b);
1852 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1853 result += piece_value_midgame(pt);
1860 /// Position::is_mate() returns true or false depending on whether the
1861 /// side to move is checkmated. Note that this function is currently very
1862 /// slow, and shouldn't be used frequently inside the search.
1864 bool Position::is_mate() const {
1868 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1869 return mp.get_next_move() == MOVE_NONE;
1875 /// Position::is_draw() tests whether the position is drawn by material,
1876 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1877 /// must be done by the search.
1879 bool Position::is_draw() const {
1881 // Draw by material?
1883 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1886 // Draw by the 50 moves rule?
1887 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1890 // Draw by repetition?
1891 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1892 if (history[gamePly - i] == st->key)
1899 /// Position::has_mate_threat() tests whether a given color has a mate in one
1900 /// from the current position. This function is quite slow, but it doesn't
1901 /// matter, because it is currently only called from PV nodes, which are rare.
1903 bool Position::has_mate_threat(Color c) {
1906 Color stm = side_to_move();
1908 // The following lines are useless and silly, but prevents gcc from
1909 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1910 // be used uninitialized.
1911 st1.lastMove = st->lastMove;
1912 st1.epSquare = st->epSquare;
1917 // If the input color is not equal to the side to move, do a null move
1921 MoveStack mlist[120];
1923 bool result = false;
1925 // Generate legal moves
1926 count = generate_legal_moves(*this, mlist);
1928 // Loop through the moves, and see if one of them is mate
1929 for (int i = 0; i < count; i++)
1931 do_move(mlist[i].move, st2);
1935 undo_move(mlist[i].move);
1938 // Undo null move, if necessary
1946 /// Position::init_zobrist() is a static member function which initializes the
1947 /// various arrays used to compute hash keys.
1949 void Position::init_zobrist() {
1951 for (int i = 0; i < 2; i++)
1952 for (int j = 0; j < 8; j++)
1953 for (int k = 0; k < 64; k++)
1954 zobrist[i][j][k] = Key(genrand_int64());
1956 for (int i = 0; i < 64; i++)
1957 zobEp[i] = Key(genrand_int64());
1959 for (int i = 0; i < 16; i++)
1960 zobCastle[i] = genrand_int64();
1962 zobSideToMove = genrand_int64();
1964 for (int i = 0; i < 2; i++)
1965 for (int j = 0; j < 8; j++)
1966 for (int k = 0; k < 16; k++)
1967 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1969 for (int i = 0; i < 16; i++)
1970 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1974 /// Position::init_piece_square_tables() initializes the piece square tables.
1975 /// This is a two-step operation: First, the white halves of the tables are
1976 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1977 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1978 /// Second, the black halves of the tables are initialized by mirroring
1979 /// and changing the sign of the corresponding white scores.
1981 void Position::init_piece_square_tables() {
1983 int r = get_option_value_int("Randomness"), i;
1984 for (Square s = SQ_A1; s <= SQ_H8; s++)
1985 for (Piece p = WP; p <= WK; p++)
1987 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1988 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1989 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1992 for (Square s = SQ_A1; s <= SQ_H8; s++)
1993 for (Piece p = BP; p <= BK; p++)
1995 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1996 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2001 /// Position::flipped_copy() makes a copy of the input position, but with
2002 /// the white and black sides reversed. This is only useful for debugging,
2003 /// especially for finding evaluation symmetry bugs.
2005 void Position::flipped_copy(const Position &pos) {
2007 assert(pos.is_ok());
2012 for (Square s = SQ_A1; s <= SQ_H8; s++)
2013 if (!pos.square_is_empty(s))
2014 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2017 sideToMove = opposite_color(pos.side_to_move());
2020 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2021 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2022 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2023 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2025 initialKFile = pos.initialKFile;
2026 initialKRFile = pos.initialKRFile;
2027 initialQRFile = pos.initialQRFile;
2029 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2030 castleRightsMask[sq] = ALL_CASTLES;
2032 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2033 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2034 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2035 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2036 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2037 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2039 // En passant square
2040 if (pos.st->epSquare != SQ_NONE)
2041 st->epSquare = flip_square(pos.st->epSquare);
2047 st->key = compute_key();
2048 st->pawnKey = compute_pawn_key();
2049 st->materialKey = compute_material_key();
2051 // Incremental scores
2052 st->mgValue = compute_value<MidGame>();
2053 st->egValue = compute_value<EndGame>();
2056 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2057 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2063 /// Position::is_ok() performs some consitency checks for the position object.
2064 /// This is meant to be helpful when debugging.
2066 bool Position::is_ok(int* failedStep) const {
2068 // What features of the position should be verified?
2069 static const bool debugBitboards = false;
2070 static const bool debugKingCount = false;
2071 static const bool debugKingCapture = false;
2072 static const bool debugCheckerCount = false;
2073 static const bool debugKey = false;
2074 static const bool debugMaterialKey = false;
2075 static const bool debugPawnKey = false;
2076 static const bool debugIncrementalEval = false;
2077 static const bool debugNonPawnMaterial = false;
2078 static const bool debugPieceCounts = false;
2079 static const bool debugPieceList = false;
2081 if (failedStep) *failedStep = 1;
2084 if (!color_is_ok(side_to_move()))
2087 // Are the king squares in the position correct?
2088 if (failedStep) (*failedStep)++;
2089 if (piece_on(king_square(WHITE)) != WK)
2092 if (failedStep) (*failedStep)++;
2093 if (piece_on(king_square(BLACK)) != BK)
2097 if (failedStep) (*failedStep)++;
2098 if (!file_is_ok(initialKRFile))
2101 if (!file_is_ok(initialQRFile))
2104 // Do both sides have exactly one king?
2105 if (failedStep) (*failedStep)++;
2108 int kingCount[2] = {0, 0};
2109 for (Square s = SQ_A1; s <= SQ_H8; s++)
2110 if (type_of_piece_on(s) == KING)
2111 kingCount[color_of_piece_on(s)]++;
2113 if (kingCount[0] != 1 || kingCount[1] != 1)
2117 // Can the side to move capture the opponent's king?
2118 if (failedStep) (*failedStep)++;
2119 if (debugKingCapture)
2121 Color us = side_to_move();
2122 Color them = opposite_color(us);
2123 Square ksq = king_square(them);
2124 if (square_is_attacked(ksq, us))
2128 // Is there more than 2 checkers?
2129 if (failedStep) (*failedStep)++;
2130 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2134 if (failedStep) (*failedStep)++;
2137 // The intersection of the white and black pieces must be empty
2138 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2141 // The union of the white and black pieces must be equal to all
2143 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2146 // Separate piece type bitboards must have empty intersections
2147 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2148 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2149 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2153 // En passant square OK?
2154 if (failedStep) (*failedStep)++;
2155 if (ep_square() != SQ_NONE)
2157 // The en passant square must be on rank 6, from the point of view of the
2159 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2164 if (failedStep) (*failedStep)++;
2165 if (debugKey && st->key != compute_key())
2168 // Pawn hash key OK?
2169 if (failedStep) (*failedStep)++;
2170 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2173 // Material hash key OK?
2174 if (failedStep) (*failedStep)++;
2175 if (debugMaterialKey && st->materialKey != compute_material_key())
2178 // Incremental eval OK?
2179 if (failedStep) (*failedStep)++;
2180 if (debugIncrementalEval)
2182 if (st->mgValue != compute_value<MidGame>())
2185 if (st->egValue != compute_value<EndGame>())
2189 // Non-pawn material OK?
2190 if (failedStep) (*failedStep)++;
2191 if (debugNonPawnMaterial)
2193 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2196 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2201 if (failedStep) (*failedStep)++;
2202 if (debugPieceCounts)
2203 for (Color c = WHITE; c <= BLACK; c++)
2204 for (PieceType pt = PAWN; pt <= KING; pt++)
2205 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2208 if (failedStep) (*failedStep)++;
2211 for(Color c = WHITE; c <= BLACK; c++)
2212 for(PieceType pt = PAWN; pt <= KING; pt++)
2213 for(int i = 0; i < pieceCount[c][pt]; i++)
2215 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2218 if (index[piece_list(c, pt, i)] != i)
2222 if (failedStep) *failedStep = 0;