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 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 pawnKey = compute_pawn_key();
212 materialKey = compute_material_key();
213 mgValue = compute_mg_value();
214 egValue = compute_eg_value();
215 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
216 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
220 /// Position::to_fen() converts the position object to a FEN string. This is
221 /// probably only useful for debugging.
223 const std::string Position::to_fen() const {
225 static const std::string pieceLetters = " PNBRQK pnbrqk";
229 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
232 for (File file = FILE_A; file <= FILE_H; file++)
234 Square sq = make_square(file, rank);
235 if (!square_is_occupied(sq))
241 fen += (char)skip + '0';
244 fen += pieceLetters[piece_on(sq)];
247 fen += (char)skip + '0';
249 fen += (rank > RANK_1 ? '/' : ' ');
251 fen += (sideToMove == WHITE ? "w " : "b ");
252 if (castleRights != NO_CASTLES)
254 if (can_castle_kingside(WHITE)) fen += 'K';
255 if (can_castle_queenside(WHITE)) fen += 'Q';
256 if (can_castle_kingside(BLACK)) fen += 'k';
257 if (can_castle_queenside(BLACK)) fen += 'q';
262 if (ep_square() != SQ_NONE)
263 fen += square_to_string(ep_square());
271 /// Position::print() prints an ASCII representation of the position to
272 /// the standard output. If a move is given then also the san is print.
274 void Position::print(Move m) const {
276 static const std::string pieceLetters = " PNBRQK PNBRQK .";
278 // Check for reentrancy, as example when called from inside
279 // MovePicker that is used also here in move_to_san()
283 RequestPending = true;
285 std::cout << std::endl;
288 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
289 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
291 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
293 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
294 for (File file = FILE_A; file <= FILE_H; file++)
296 Square sq = make_square(file, rank);
297 Piece piece = piece_on(sq);
298 if (piece == EMPTY && square_color(sq) == WHITE)
301 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
302 std::cout << '|' << col << pieceLetters[piece] << col;
304 std::cout << '|' << std::endl;
306 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
307 << "Fen is: " << to_fen() << std::endl
308 << "Key is: " << key << std::endl;
310 RequestPending = false;
314 /// Position::copy() creates a copy of the input position.
316 void Position::copy(const Position &pos) {
318 memcpy(this, &pos, sizeof(Position));
322 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
323 /// king) pieces for the given color.
324 Bitboard Position::pinned_pieces(Color c) const {
326 if (pinned[c] != ~EmptyBoardBB)
330 Square ksq = king_square(c);
331 pinned[c] = hidden_checks<ROOK, true>(c, ksq, p1) | hidden_checks<BISHOP, true>(c, ksq, p2);
332 pinners[c] = p1 | p2;
336 Bitboard Position::pinned_pieces(Color c, Bitboard& p) const {
338 if (pinned[c] == ~EmptyBoardBB)
345 Bitboard Position::discovered_check_candidates(Color c) const {
347 if (dcCandidates[c] != ~EmptyBoardBB)
348 return dcCandidates[c];
351 Square ksq = king_square(opposite_color(c));
352 dcCandidates[c] = hidden_checks<ROOK, false>(c, ksq, dummy) | hidden_checks<BISHOP, false>(c, ksq, dummy);
353 return dcCandidates[c];
356 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
357 /// king) pieces for the given color and for the given pinner type. Or, when
358 /// template parameter FindPinned is false, the pinned pieces of opposite color
359 /// that are, indeed, the pieces candidate for a discovery check.
360 template<PieceType Piece, bool FindPinned>
361 Bitboard Position::hidden_checks(Color c, Square ksq, Bitboard& pinners) const {
364 Bitboard sliders, result = EmptyBoardBB;
366 if (Piece == ROOK) // Resolved at compile time
367 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
369 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
371 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
373 // King blockers are candidate pinned pieces
374 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
376 // Pinners are sliders, not checkers, that give check when
377 // candidate pinned are removed.
378 pinners = (FindPinned ? sliders & ~checkersBB : sliders);
381 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
383 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
385 // Finally for each pinner find the corresponding pinned piece (if same color of king)
386 // or discovery checker (if opposite color) among the candidates.
387 Bitboard p = pinners;
391 result |= (squares_between(s, ksq) & candidate_pinned);
395 pinners = EmptyBoardBB;
401 /// Position::attacks_to() computes a bitboard containing all pieces which
402 /// attacks a given square. There are two versions of this function: One
403 /// which finds attackers of both colors, and one which only finds the
404 /// attackers for one side.
406 Bitboard Position::attacks_to(Square s) const {
408 return (pawn_attacks(BLACK, s) & pawns(WHITE))
409 | (pawn_attacks(WHITE, s) & pawns(BLACK))
410 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
411 | (piece_attacks<ROOK>(s) & rooks_and_queens())
412 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
413 | (piece_attacks<KING>(s) & pieces_of_type(KING));
416 /// Position::piece_attacks_square() tests whether the piece on square f
417 /// attacks square t.
419 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
421 assert(square_is_ok(f));
422 assert(square_is_ok(t));
426 case WP: return pawn_attacks_square(WHITE, f, t);
427 case BP: return pawn_attacks_square(BLACK, f, t);
428 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
429 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
430 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
431 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
432 case WK: case BK: return piece_attacks_square<KING>(f, t);
439 /// Position::move_attacks_square() tests whether a move from the current
440 /// position attacks a given square.
442 bool Position::move_attacks_square(Move m, Square s) const {
444 assert(move_is_ok(m));
445 assert(square_is_ok(s));
447 Square f = move_from(m), t = move_to(m);
449 assert(square_is_occupied(f));
451 if (piece_attacks_square(piece_on(f), t, s))
454 // Move the piece and scan for X-ray attacks behind it
455 Bitboard occ = occupied_squares();
456 Color us = color_of_piece_on(f);
459 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
460 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
462 // If we have attacks we need to verify that are caused by our move
463 // and are not already existent ones.
464 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
468 /// Position::find_checkers() computes the checkersBB bitboard, which
469 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
470 /// currently works by calling Position::attacks_to, which is probably
471 /// inefficient. Consider rewriting this function to use the last move
472 /// played, like in non-bitboard versions of Glaurung.
474 void Position::find_checkers() {
476 Color us = side_to_move();
477 checkersBB = attacks_to(king_square(us), opposite_color(us));
481 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
483 bool Position::pl_move_is_legal(Move m) const {
486 assert(move_is_ok(m));
488 // If we're in check, all pseudo-legal moves are legal, because our
489 // check evasion generator only generates true legal moves.
493 // Castling moves are checked for legality during move generation.
494 if (move_is_castle(m))
497 Color us = side_to_move();
498 Color them = opposite_color(us);
499 Square from = move_from(m);
500 Square ksq = king_square(us);
502 assert(color_of_piece_on(from) == us);
503 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
505 // En passant captures are a tricky special case. Because they are
506 // rather uncommon, we do it simply by testing whether the king is attacked
507 // after the move is made
510 Square to = move_to(m);
511 Square capsq = make_square(square_file(to), square_rank(from));
512 Bitboard b = occupied_squares();
514 assert(to == ep_square());
515 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
516 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
517 assert(piece_on(to) == EMPTY);
520 clear_bit(&b, capsq);
523 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
524 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
527 // If the moving piece is a king, check whether the destination
528 // square is attacked by the opponent.
530 return !(square_is_attacked(move_to(m), them));
532 // A non-king move is legal if and only if it is not pinned or it
533 // is moving along the ray towards or away from the king.
534 return ( !bit_is_set(pinned_pieces(us), from)
535 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
539 /// Position::move_is_check() tests whether a pseudo-legal move is a check
541 bool Position::move_is_check(Move m) const {
544 assert(move_is_ok(m));
546 Color us = side_to_move();
547 Color them = opposite_color(us);
548 Square from = move_from(m);
549 Square to = move_to(m);
550 Square ksq = king_square(them);
551 Bitboard dcCandidates = discovered_check_candidates(us);
553 assert(color_of_piece_on(from) == us);
554 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
556 // Proceed according to the type of the moving piece
557 switch (type_of_piece_on(from))
561 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
564 if ( bit_is_set(dcCandidates, from) // Discovered check?
565 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
568 if (move_promotion(m)) // Promotion with check?
570 Bitboard b = occupied_squares();
573 switch (move_promotion(m))
576 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
578 return bit_is_set(bishop_attacks_bb(to, b), ksq);
580 return bit_is_set(rook_attacks_bb(to, b), ksq);
582 return bit_is_set(queen_attacks_bb(to, b), ksq);
587 // En passant capture with check? We have already handled the case
588 // of direct checks and ordinary discovered check, the only case we
589 // need to handle is the unusual case of a discovered check through the
591 else if (move_is_ep(m))
593 Square capsq = make_square(square_file(to), square_rank(from));
594 Bitboard b = occupied_squares();
596 clear_bit(&b, capsq);
598 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
599 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
604 return bit_is_set(dcCandidates, from) // Discovered check?
605 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
608 return bit_is_set(dcCandidates, from) // Discovered check?
609 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
612 return bit_is_set(dcCandidates, from) // Discovered check?
613 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
616 // Discovered checks are impossible!
617 assert(!bit_is_set(dcCandidates, from));
618 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
622 if ( bit_is_set(dcCandidates, from)
623 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
626 // Castling with check?
627 if (move_is_castle(m))
629 Square kfrom, kto, rfrom, rto;
630 Bitboard b = occupied_squares();
636 kto = relative_square(us, SQ_G1);
637 rto = relative_square(us, SQ_F1);
639 kto = relative_square(us, SQ_C1);
640 rto = relative_square(us, SQ_D1);
642 clear_bit(&b, kfrom);
643 clear_bit(&b, rfrom);
646 return bit_is_set(rook_attacks_bb(rto, b), ksq);
650 default: // NO_PIECE_TYPE
658 /// Position::move_is_capture() tests whether a move from the current
659 /// position is a capture. Move must not be MOVE_NONE.
661 bool Position::move_is_capture(Move m) const {
663 assert(m != MOVE_NONE);
665 return ( !square_is_empty(move_to(m))
666 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
672 /// Position::update_checkers() is a private method to udpate chekers info
674 template<PieceType Piece>
675 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
676 Square to, Bitboard dcCandidates) {
678 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
679 set_bit(pCheckersBB, to);
681 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
684 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
687 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
692 /// Position::do_move() makes a move, and backs up all information necessary
693 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
694 /// Pseudo-legal moves should be filtered out before this function is called.
696 void Position::do_move(Move m, UndoInfo& u) {
699 assert(move_is_ok(m));
701 // Get now the current (pre-move) dc candidates that we will use
702 // in update_checkers().
703 Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
705 // Back up the necessary information to our UndoInfo object (except the
706 // captured piece, which is taken care of later.
708 u.capture = NO_PIECE_TYPE;
710 // Save the current key to the history[] array, in order to be able to
711 // detect repetition draws.
712 history[gamePly] = key;
714 // Increment the 50 moves rule draw counter. Resetting it to zero in the
715 // case of non-reversible moves is taken care of later.
718 // Reset pinned bitboard and its friends
719 for (Color c = WHITE; c <= BLACK; c++)
720 pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
722 if (move_is_castle(m))
724 else if (move_promotion(m))
725 do_promotion_move(m, u);
726 else if (move_is_ep(m))
730 Color us = side_to_move();
731 Color them = opposite_color(us);
732 Square from = move_from(m);
733 Square to = move_to(m);
735 assert(color_of_piece_on(from) == us);
736 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
738 PieceType piece = type_of_piece_on(from);
739 PieceType capture = type_of_piece_on(to);
744 do_capture_move(m, capture, them, to);
748 clear_bit(&(byColorBB[us]), from);
749 clear_bit(&(byTypeBB[piece]), from);
750 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
751 set_bit(&(byColorBB[us]), to);
752 set_bit(&(byTypeBB[piece]), to);
753 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
754 board[to] = board[from];
758 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
760 // Update incremental scores
761 mgValue -= mg_pst(us, piece, from);
762 mgValue += mg_pst(us, piece, to);
763 egValue -= eg_pst(us, piece, from);
764 egValue += eg_pst(us, piece, to);
766 // If the moving piece was a king, update the king square
770 // Reset en passant square
771 if (epSquare != SQ_NONE)
773 key ^= zobEp[epSquare];
777 // If the moving piece was a pawn do some special extra work
780 // Reset rule 50 draw counter
783 // Update pawn hash key
784 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
786 // Set en passant square, only if moved pawn can be captured
787 if (abs(int(to) - int(from)) == 16)
789 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
790 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
792 epSquare = Square((int(from) + int(to)) / 2);
793 key ^= zobEp[epSquare];
798 // Update piece lists
799 pieceList[us][piece][index[from]] = to;
800 index[to] = index[from];
802 // Update castle rights
803 key ^= zobCastle[castleRights];
804 castleRights &= castleRightsMask[from];
805 castleRights &= castleRightsMask[to];
806 key ^= zobCastle[castleRights];
808 // Update checkers bitboard, piece must be already moved
809 checkersBB = EmptyBoardBB;
810 Square ksq = king_square(them);
813 case PAWN: update_checkers<PAWN>(&checkersBB, ksq, from, to, oldDcCandidates); break;
814 case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, oldDcCandidates); break;
815 case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, oldDcCandidates); break;
816 case ROOK: update_checkers<ROOK>(&checkersBB, ksq, from, to, oldDcCandidates); break;
817 case QUEEN: update_checkers<QUEEN>(&checkersBB, ksq, from, to, oldDcCandidates); break;
818 case KING: update_checkers<KING>(&checkersBB, ksq, from, to, oldDcCandidates); break;
819 default: assert(false); break;
824 key ^= zobSideToMove;
825 sideToMove = opposite_color(sideToMove);
828 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
829 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
835 /// Position::do_capture_move() is a private method used to update captured
836 /// piece info. It is called from the main Position::do_move function.
838 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
840 assert(capture != KING);
842 // Remove captured piece
843 clear_bit(&(byColorBB[them]), to);
844 clear_bit(&(byTypeBB[capture]), to);
847 key ^= zobrist[them][capture][to];
849 // If the captured piece was a pawn, update pawn hash key
851 pawnKey ^= zobrist[them][PAWN][to];
853 // Update incremental scores
854 mgValue -= mg_pst(them, capture, to);
855 egValue -= eg_pst(them, capture, to);
857 assert(!move_promotion(m) || capture != PAWN);
861 npMaterial[them] -= piece_value_midgame(capture);
863 // Update material hash key
864 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
866 // Update piece count
867 pieceCount[them][capture]--;
870 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
871 index[pieceList[them][capture][index[to]]] = index[to];
873 // Reset rule 50 counter
878 /// Position::do_castle_move() is a private method used to make a castling
879 /// move. It is called from the main Position::do_move function. Note that
880 /// castling moves are encoded as "king captures friendly rook" moves, for
881 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
883 void Position::do_castle_move(Move m) {
886 assert(move_is_ok(m));
887 assert(move_is_castle(m));
889 Color us = side_to_move();
890 Color them = opposite_color(us);
892 // Find source squares for king and rook
893 Square kfrom = move_from(m);
894 Square rfrom = move_to(m); // HACK: See comment at beginning of function
897 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
898 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
900 // Find destination squares for king and rook
901 if (rfrom > kfrom) // O-O
903 kto = relative_square(us, SQ_G1);
904 rto = relative_square(us, SQ_F1);
906 kto = relative_square(us, SQ_C1);
907 rto = relative_square(us, SQ_D1);
910 // Remove pieces from source squares
911 clear_bit(&(byColorBB[us]), kfrom);
912 clear_bit(&(byTypeBB[KING]), kfrom);
913 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
914 clear_bit(&(byColorBB[us]), rfrom);
915 clear_bit(&(byTypeBB[ROOK]), rfrom);
916 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
918 // Put pieces on destination squares
919 set_bit(&(byColorBB[us]), kto);
920 set_bit(&(byTypeBB[KING]), kto);
921 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
922 set_bit(&(byColorBB[us]), rto);
923 set_bit(&(byTypeBB[ROOK]), rto);
924 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
926 // Update board array
927 board[kfrom] = board[rfrom] = EMPTY;
928 board[kto] = piece_of_color_and_type(us, KING);
929 board[rto] = piece_of_color_and_type(us, ROOK);
931 // Update king square
932 kingSquare[us] = kto;
934 // Update piece lists
935 pieceList[us][KING][index[kfrom]] = kto;
936 pieceList[us][ROOK][index[rfrom]] = rto;
937 int tmp = index[rfrom];
938 index[kto] = index[kfrom];
941 // Update incremental scores
942 mgValue -= mg_pst(us, KING, kfrom);
943 mgValue += mg_pst(us, KING, kto);
944 egValue -= eg_pst(us, KING, kfrom);
945 egValue += eg_pst(us, KING, kto);
946 mgValue -= mg_pst(us, ROOK, rfrom);
947 mgValue += mg_pst(us, ROOK, rto);
948 egValue -= eg_pst(us, ROOK, rfrom);
949 egValue += eg_pst(us, ROOK, rto);
952 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
953 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
955 // Clear en passant square
956 if (epSquare != SQ_NONE)
958 key ^= zobEp[epSquare];
962 // Update castling rights
963 key ^= zobCastle[castleRights];
964 castleRights &= castleRightsMask[kfrom];
965 key ^= zobCastle[castleRights];
967 // Reset rule 50 counter
970 // Update checkers BB
971 checkersBB = attacks_to(king_square(them), us);
975 /// Position::do_promotion_move() is a private method used to make a promotion
976 /// move. It is called from the main Position::do_move function. The
977 /// UndoInfo object, which has been initialized in Position::do_move, is
978 /// used to store the captured piece (if any).
980 void Position::do_promotion_move(Move m, UndoInfo &u) {
984 PieceType capture, promotion;
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 capture = type_of_piece_on(to);
1003 u.capture = capture;
1004 do_capture_move(m, capture, them, to);
1008 clear_bit(&(byColorBB[us]), from);
1009 clear_bit(&(byTypeBB[PAWN]), from);
1010 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1011 board[from] = EMPTY;
1013 // Insert promoted piece
1014 promotion = move_promotion(m);
1015 assert(promotion >= KNIGHT && promotion <= QUEEN);
1016 set_bit(&(byColorBB[us]), to);
1017 set_bit(&(byTypeBB[promotion]), to);
1018 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1019 board[to] = piece_of_color_and_type(us, promotion);
1022 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1024 // Update pawn hash key
1025 pawnKey ^= zobrist[us][PAWN][from];
1027 // Update material key
1028 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1029 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1031 // Update piece counts
1032 pieceCount[us][PAWN]--;
1033 pieceCount[us][promotion]++;
1035 // Update piece lists
1036 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1037 index[pieceList[us][PAWN][index[from]]] = index[from];
1038 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1039 index[to] = pieceCount[us][promotion] - 1;
1041 // Update incremental scores
1042 mgValue -= mg_pst(us, PAWN, from);
1043 mgValue += mg_pst(us, promotion, to);
1044 egValue -= eg_pst(us, PAWN, from);
1045 egValue += eg_pst(us, promotion, to);
1048 npMaterial[us] += piece_value_midgame(promotion);
1050 // Clear the en passant square
1051 if (epSquare != SQ_NONE)
1053 key ^= zobEp[epSquare];
1057 // Update castle rights
1058 key ^= zobCastle[castleRights];
1059 castleRights &= castleRightsMask[to];
1060 key ^= zobCastle[castleRights];
1062 // Reset rule 50 counter
1065 // Update checkers BB
1066 checkersBB = attacks_to(king_square(them), us);
1070 /// Position::do_ep_move() is a private method used to make an en passant
1071 /// capture. It is called from the main Position::do_move function. Because
1072 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1073 /// object in which to store the captured piece.
1075 void Position::do_ep_move(Move m) {
1078 Square from, to, capsq;
1081 assert(move_is_ok(m));
1082 assert(move_is_ep(m));
1084 us = side_to_move();
1085 them = opposite_color(us);
1086 from = move_from(m);
1088 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1090 assert(to == epSquare);
1091 assert(relative_rank(us, to) == RANK_6);
1092 assert(piece_on(to) == EMPTY);
1093 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1094 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1096 // Remove captured piece
1097 clear_bit(&(byColorBB[them]), capsq);
1098 clear_bit(&(byTypeBB[PAWN]), capsq);
1099 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1100 board[capsq] = EMPTY;
1102 // Remove moving piece from source square
1103 clear_bit(&(byColorBB[us]), from);
1104 clear_bit(&(byTypeBB[PAWN]), from);
1105 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1107 // Put moving piece on destination square
1108 set_bit(&(byColorBB[us]), to);
1109 set_bit(&(byTypeBB[PAWN]), to);
1110 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1111 board[to] = board[from];
1112 board[from] = EMPTY;
1114 // Update material hash key
1115 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1117 // Update piece count
1118 pieceCount[them][PAWN]--;
1120 // Update piece list
1121 pieceList[us][PAWN][index[from]] = to;
1122 index[to] = index[from];
1123 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1124 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1127 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1128 key ^= zobrist[them][PAWN][capsq];
1129 key ^= zobEp[epSquare];
1131 // Update pawn hash key
1132 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1133 pawnKey ^= zobrist[them][PAWN][capsq];
1135 // Update incremental scores
1136 mgValue -= mg_pst(them, PAWN, capsq);
1137 mgValue -= mg_pst(us, PAWN, from);
1138 mgValue += mg_pst(us, PAWN, to);
1139 egValue -= eg_pst(them, PAWN, capsq);
1140 egValue -= eg_pst(us, PAWN, from);
1141 egValue += eg_pst(us, PAWN, to);
1143 // Reset en passant square
1146 // Reset rule 50 counter
1149 // Update checkers BB
1150 checkersBB = attacks_to(king_square(them), us);
1154 /// Position::undo_move() unmakes a move. When it returns, the position should
1155 /// be restored to exactly the same state as before the move was made. It is
1156 /// important that Position::undo_move is called with the same move and UndoInfo
1157 /// object as the earlier call to Position::do_move.
1159 void Position::undo_move(Move m, const UndoInfo &u) {
1162 assert(move_is_ok(m));
1165 sideToMove = opposite_color(sideToMove);
1167 // Restore information from our UndoInfo object (except the captured piece,
1168 // which is taken care of later)
1171 if (move_is_castle(m))
1172 undo_castle_move(m);
1173 else if (move_promotion(m))
1174 undo_promotion_move(m, u);
1175 else if (move_is_ep(m))
1181 PieceType piece, capture;
1183 us = side_to_move();
1184 them = opposite_color(us);
1185 from = move_from(m);
1188 assert(piece_on(from) == EMPTY);
1189 assert(color_of_piece_on(to) == us);
1191 // Put the piece back at the source square
1192 piece = type_of_piece_on(to);
1193 set_bit(&(byColorBB[us]), from);
1194 set_bit(&(byTypeBB[piece]), from);
1195 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1196 board[from] = piece_of_color_and_type(us, piece);
1198 // Clear the destination square
1199 clear_bit(&(byColorBB[us]), to);
1200 clear_bit(&(byTypeBB[piece]), to);
1201 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1203 // If the moving piece was a king, update the king square
1205 kingSquare[us] = from;
1207 // Update piece list
1208 pieceList[us][piece][index[to]] = from;
1209 index[from] = index[to];
1211 capture = u.capture;
1215 assert(capture != KING);
1217 // Replace the captured piece
1218 set_bit(&(byColorBB[them]), to);
1219 set_bit(&(byTypeBB[capture]), to);
1220 set_bit(&(byTypeBB[0]), to);
1221 board[to] = piece_of_color_and_type(them, capture);
1224 if (capture != PAWN)
1225 npMaterial[them] += piece_value_midgame(capture);
1227 // Update piece list
1228 pieceList[them][capture][pieceCount[them][capture]] = to;
1229 index[to] = pieceCount[them][capture];
1231 // Update piece count
1232 pieceCount[them][capture]++;
1241 /// Position::undo_castle_move() is a private method used to unmake a castling
1242 /// move. It is called from the main Position::undo_move function. Note that
1243 /// castling moves are encoded as "king captures friendly rook" moves, for
1244 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1246 void Position::undo_castle_move(Move m) {
1248 assert(move_is_ok(m));
1249 assert(move_is_castle(m));
1251 // When we have arrived here, some work has already been done by
1252 // Position::undo_move. In particular, the side to move has been switched,
1253 // so the code below is correct.
1254 Color us = side_to_move();
1256 // Find source squares for king and rook
1257 Square kfrom = move_from(m);
1258 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1261 // Find destination squares for king and rook
1262 if (rfrom > kfrom) // O-O
1264 kto = relative_square(us, SQ_G1);
1265 rto = relative_square(us, SQ_F1);
1267 kto = relative_square(us, SQ_C1);
1268 rto = relative_square(us, SQ_D1);
1271 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1272 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1274 // Remove pieces from destination squares
1275 clear_bit(&(byColorBB[us]), kto);
1276 clear_bit(&(byTypeBB[KING]), kto);
1277 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1278 clear_bit(&(byColorBB[us]), rto);
1279 clear_bit(&(byTypeBB[ROOK]), rto);
1280 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1282 // Put pieces on source squares
1283 set_bit(&(byColorBB[us]), kfrom);
1284 set_bit(&(byTypeBB[KING]), kfrom);
1285 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1286 set_bit(&(byColorBB[us]), rfrom);
1287 set_bit(&(byTypeBB[ROOK]), rfrom);
1288 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1291 board[rto] = board[kto] = EMPTY;
1292 board[rfrom] = piece_of_color_and_type(us, ROOK);
1293 board[kfrom] = piece_of_color_and_type(us, KING);
1295 // Update king square
1296 kingSquare[us] = kfrom;
1298 // Update piece lists
1299 pieceList[us][KING][index[kto]] = kfrom;
1300 pieceList[us][ROOK][index[rto]] = rfrom;
1301 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1302 index[kfrom] = index[kto];
1307 /// Position::undo_promotion_move() is a private method used to unmake a
1308 /// promotion move. It is called from the main Position::do_move
1309 /// function. The UndoInfo object, which has been initialized in
1310 /// Position::do_move, is used to put back the captured piece (if any).
1312 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1316 PieceType capture, promotion;
1318 assert(move_is_ok(m));
1319 assert(move_promotion(m));
1321 // When we have arrived here, some work has already been done by
1322 // Position::undo_move. In particular, the side to move has been switched,
1323 // so the code below is correct.
1324 us = side_to_move();
1325 them = opposite_color(us);
1326 from = move_from(m);
1329 assert(relative_rank(us, to) == RANK_8);
1330 assert(piece_on(from) == EMPTY);
1332 // Remove promoted piece
1333 promotion = move_promotion(m);
1334 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1335 assert(promotion >= KNIGHT && promotion <= QUEEN);
1336 clear_bit(&(byColorBB[us]), to);
1337 clear_bit(&(byTypeBB[promotion]), to);
1338 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1340 // Insert pawn at source square
1341 set_bit(&(byColorBB[us]), from);
1342 set_bit(&(byTypeBB[PAWN]), from);
1343 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1344 board[from] = piece_of_color_and_type(us, PAWN);
1347 npMaterial[us] -= piece_value_midgame(promotion);
1349 // Update piece list
1350 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1351 index[from] = pieceCount[us][PAWN];
1352 pieceList[us][promotion][index[to]] =
1353 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1354 index[pieceList[us][promotion][index[to]]] = index[to];
1356 // Update piece counts
1357 pieceCount[us][promotion]--;
1358 pieceCount[us][PAWN]++;
1360 capture = u.capture;
1364 assert(capture != KING);
1366 // Insert captured piece:
1367 set_bit(&(byColorBB[them]), to);
1368 set_bit(&(byTypeBB[capture]), to);
1369 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1370 board[to] = piece_of_color_and_type(them, capture);
1372 // Update material. Because the move is a promotion move, we know
1373 // that the captured piece cannot be a pawn.
1374 assert(capture != PAWN);
1375 npMaterial[them] += piece_value_midgame(capture);
1377 // Update piece list
1378 pieceList[them][capture][pieceCount[them][capture]] = to;
1379 index[to] = pieceCount[them][capture];
1381 // Update piece count
1382 pieceCount[them][capture]++;
1388 /// Position::undo_ep_move() is a private method used to unmake an en passant
1389 /// capture. It is called from the main Position::undo_move function. Because
1390 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1391 /// object from which to retrieve the captured piece.
1393 void Position::undo_ep_move(Move m) {
1395 assert(move_is_ok(m));
1396 assert(move_is_ep(m));
1398 // When we have arrived here, some work has already been done by
1399 // Position::undo_move. In particular, the side to move has been switched,
1400 // so the code below is correct.
1401 Color us = side_to_move();
1402 Color them = opposite_color(us);
1403 Square from = move_from(m);
1404 Square to = move_to(m);
1405 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1407 assert(to == ep_square());
1408 assert(relative_rank(us, to) == RANK_6);
1409 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1410 assert(piece_on(from) == EMPTY);
1411 assert(piece_on(capsq) == EMPTY);
1413 // Replace captured piece
1414 set_bit(&(byColorBB[them]), capsq);
1415 set_bit(&(byTypeBB[PAWN]), capsq);
1416 set_bit(&(byTypeBB[0]), capsq);
1417 board[capsq] = piece_of_color_and_type(them, PAWN);
1419 // Remove moving piece from destination square
1420 clear_bit(&(byColorBB[us]), to);
1421 clear_bit(&(byTypeBB[PAWN]), to);
1422 clear_bit(&(byTypeBB[0]), to);
1425 // Replace moving piece at source square
1426 set_bit(&(byColorBB[us]), from);
1427 set_bit(&(byTypeBB[PAWN]), from);
1428 set_bit(&(byTypeBB[0]), from);
1429 board[from] = piece_of_color_and_type(us, PAWN);
1431 // Update piece list:
1432 pieceList[us][PAWN][index[to]] = from;
1433 index[from] = index[to];
1434 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1435 index[capsq] = pieceCount[them][PAWN];
1437 // Update piece count:
1438 pieceCount[them][PAWN]++;
1442 /// Position::do_null_move makes() a "null move": It switches the side to move
1443 /// and updates the hash key without executing any move on the board.
1445 void Position::do_null_move(UndoInfo& u) {
1448 assert(!is_check());
1450 // Back up the information necessary to undo the null move to the supplied
1451 // UndoInfo object. In the case of a null move, the only thing we need to
1452 // remember is the last move made and the en passant square.
1453 u.lastMove = lastMove;
1454 u.epSquare = epSquare;
1456 // Save the current key to the history[] array, in order to be able to
1457 // detect repetition draws.
1458 history[gamePly] = key;
1460 // Update the necessary information
1461 sideToMove = opposite_color(sideToMove);
1462 if (epSquare != SQ_NONE)
1463 key ^= zobEp[epSquare];
1468 key ^= zobSideToMove;
1470 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1471 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1477 /// Position::undo_null_move() unmakes a "null move".
1479 void Position::undo_null_move(const UndoInfo &u) {
1482 assert(!is_check());
1484 // Restore information from the supplied UndoInfo object:
1485 lastMove = u.lastMove;
1486 epSquare = u.epSquare;
1487 if (epSquare != SQ_NONE)
1488 key ^= zobEp[epSquare];
1490 // Update the necessary information.
1491 sideToMove = opposite_color(sideToMove);
1494 key ^= zobSideToMove;
1496 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1497 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1503 /// Position::see() is a static exchange evaluator: It tries to estimate the
1504 /// material gain or loss resulting from a move. There are three versions of
1505 /// this function: One which takes a destination square as input, one takes a
1506 /// move, and one which takes a 'from' and a 'to' square. The function does
1507 /// not yet understand promotions captures.
1509 int Position::see(Square to) const {
1511 assert(square_is_ok(to));
1512 return see(SQ_NONE, to);
1515 int Position::see(Move m) const {
1517 assert(move_is_ok(m));
1518 return see(move_from(m), move_to(m));
1521 int Position::see(Square from, Square to) const {
1524 static const int seeValues[18] = {
1525 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1526 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1527 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1528 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1532 Bitboard attackers, occ, b;
1534 assert(square_is_ok(from) || from == SQ_NONE);
1535 assert(square_is_ok(to));
1537 // Initialize colors
1538 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1539 Color them = opposite_color(us);
1541 // Initialize pieces
1542 Piece piece = piece_on(from);
1543 Piece capture = piece_on(to);
1545 // Find all attackers to the destination square, with the moving piece
1546 // removed, but possibly an X-ray attacker added behind it.
1547 occ = occupied_squares();
1549 // Handle en passant moves
1550 if (epSquare == to && type_of_piece_on(from) == PAWN)
1552 assert(capture == EMPTY);
1554 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1555 capture = piece_on(capQq);
1557 assert(type_of_piece_on(capQq) == PAWN);
1559 // Remove the captured pawn
1560 clear_bit(&occ, capQq);
1565 clear_bit(&occ, from);
1566 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1567 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1568 | (piece_attacks<KNIGHT>(to) & knights())
1569 | (piece_attacks<KING>(to) & kings())
1570 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1571 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1573 if (from != SQ_NONE)
1576 // If we don't have any attacker we are finished
1577 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1580 // Locate the least valuable attacker to the destination square
1581 // and use it to initialize from square.
1583 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1586 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1587 piece = piece_on(from);
1590 // If the opponent has no attackers we are finished
1591 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1592 return seeValues[capture];
1594 attackers &= occ; // Remove the moving piece
1596 // The destination square is defended, which makes things rather more
1597 // difficult to compute. We proceed by building up a "swap list" containing
1598 // the material gain or loss at each stop in a sequence of captures to the
1599 // destination square, where the sides alternately capture, and always
1600 // capture with the least valuable piece. After each capture, we look for
1601 // new X-ray attacks from behind the capturing piece.
1602 int lastCapturingPieceValue = seeValues[piece];
1603 int swapList[32], n = 1;
1607 swapList[0] = seeValues[capture];
1610 // Locate the least valuable attacker for the side to move. The loop
1611 // below looks like it is potentially infinite, but it isn't. We know
1612 // that the side to move still has at least one attacker left.
1613 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1616 // Remove the attacker we just found from the 'attackers' bitboard,
1617 // and scan for new X-ray attacks behind the attacker.
1618 b = attackers & pieces_of_color_and_type(c, pt);
1620 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1621 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1625 // Add the new entry to the swap list
1627 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1630 // Remember the value of the capturing piece, and change the side to move
1631 // before beginning the next iteration
1632 lastCapturingPieceValue = seeValues[pt];
1633 c = opposite_color(c);
1635 // Stop after a king capture
1636 if (pt == KING && (attackers & pieces_of_color(c)))
1639 swapList[n++] = 100;
1642 } while (attackers & pieces_of_color(c));
1644 // Having built the swap list, we negamax through it to find the best
1645 // achievable score from the point of view of the side to move
1647 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1653 /// Position::clear() erases the position object to a pristine state, with an
1654 /// empty board, white to move, and no castling rights.
1656 void Position::clear() {
1658 for (int i = 0; i < 64; i++)
1664 for (int i = 0; i < 2; i++)
1665 byColorBB[i] = EmptyBoardBB;
1667 for (int i = 0; i < 7; i++)
1669 byTypeBB[i] = EmptyBoardBB;
1670 pieceCount[0][i] = pieceCount[1][i] = 0;
1671 for (int j = 0; j < 8; j++)
1672 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1675 checkersBB = EmptyBoardBB;
1676 for (Color c = WHITE; c <= BLACK; c++)
1677 pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
1679 lastMove = MOVE_NONE;
1682 castleRights = NO_CASTLES;
1683 initialKFile = FILE_E;
1684 initialKRFile = FILE_H;
1685 initialQRFile = FILE_A;
1692 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1693 /// UCI interface code, whenever a non-reversible move is made in a
1694 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1695 /// for the program to handle games of arbitrary length, as long as the GUI
1696 /// handles draws by the 50 move rule correctly.
1698 void Position::reset_game_ply() {
1704 /// Position::put_piece() puts a piece on the given square of the board,
1705 /// updating the board array, bitboards, and piece counts.
1707 void Position::put_piece(Piece p, Square s) {
1709 Color c = color_of_piece(p);
1710 PieceType pt = type_of_piece(p);
1713 index[s] = pieceCount[c][pt];
1714 pieceList[c][pt][index[s]] = s;
1716 set_bit(&(byTypeBB[pt]), s);
1717 set_bit(&(byColorBB[c]), s);
1718 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1720 pieceCount[c][pt]++;
1727 /// Position::allow_oo() gives the given side the right to castle kingside.
1728 /// Used when setting castling rights during parsing of FEN strings.
1730 void Position::allow_oo(Color c) {
1732 castleRights |= (1 + int(c));
1736 /// Position::allow_ooo() gives the given side the right to castle queenside.
1737 /// Used when setting castling rights during parsing of FEN strings.
1739 void Position::allow_ooo(Color c) {
1741 castleRights |= (4 + 4*int(c));
1745 /// Position::compute_key() computes the hash key of the position. The hash
1746 /// key is usually updated incrementally as moves are made and unmade, the
1747 /// compute_key() function is only used when a new position is set up, and
1748 /// to verify the correctness of the hash key when running in debug mode.
1750 Key Position::compute_key() const {
1752 Key result = Key(0ULL);
1754 for (Square s = SQ_A1; s <= SQ_H8; s++)
1755 if (square_is_occupied(s))
1756 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1758 if (ep_square() != SQ_NONE)
1759 result ^= zobEp[ep_square()];
1761 result ^= zobCastle[castleRights];
1762 if (side_to_move() == BLACK)
1763 result ^= zobSideToMove;
1769 /// Position::compute_pawn_key() computes the hash key of the position. The
1770 /// hash key is usually updated incrementally as moves are made and unmade,
1771 /// the compute_pawn_key() function is only used when a new position is set
1772 /// up, and to verify the correctness of the pawn hash key when running in
1775 Key Position::compute_pawn_key() const {
1777 Key result = Key(0ULL);
1781 for (Color c = WHITE; c <= BLACK; c++)
1786 s = pop_1st_bit(&b);
1787 result ^= zobrist[c][PAWN][s];
1794 /// Position::compute_material_key() computes the hash key of the position.
1795 /// The hash key is usually updated incrementally as moves are made and unmade,
1796 /// the compute_material_key() function is only used when a new position is set
1797 /// up, and to verify the correctness of the material hash key when running in
1800 Key Position::compute_material_key() const {
1802 Key result = Key(0ULL);
1803 for (Color c = WHITE; c <= BLACK; c++)
1804 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1806 int count = piece_count(c, pt);
1807 for (int i = 0; i <= count; i++)
1808 result ^= zobMaterial[c][pt][i];
1814 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1815 /// incremental scores for the middle game and the endgame. These functions
1816 /// are used to initialize the incremental scores when a new position is set
1817 /// up, and to verify that the scores are correctly updated by do_move
1818 /// and undo_move when the program is running in debug mode.
1820 Value Position::compute_mg_value() const {
1822 Value result = Value(0);
1826 for (Color c = WHITE; c <= BLACK; c++)
1827 for (PieceType pt = PAWN; pt <= KING; pt++)
1829 b = pieces_of_color_and_type(c, pt);
1832 s = pop_1st_bit(&b);
1833 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1834 result += mg_pst(c, pt, s);
1837 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1841 Value Position::compute_eg_value() const {
1843 Value result = Value(0);
1847 for (Color c = WHITE; c <= BLACK; c++)
1848 for (PieceType pt = PAWN; pt <= KING; pt++)
1850 b = pieces_of_color_and_type(c, pt);
1853 s = pop_1st_bit(&b);
1854 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1855 result += eg_pst(c, pt, s);
1858 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1863 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1864 /// game material score for the given side. Material scores are updated
1865 /// incrementally during the search, this function is only used while
1866 /// initializing a new Position object.
1868 Value Position::compute_non_pawn_material(Color c) const {
1870 Value result = Value(0);
1873 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1875 Bitboard b = pieces_of_color_and_type(c, pt);
1878 s = pop_1st_bit(&b);
1879 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1880 result += piece_value_midgame(pt);
1887 /// Position::is_mate() returns true or false depending on whether the
1888 /// side to move is checkmated. Note that this function is currently very
1889 /// slow, and shouldn't be used frequently inside the search.
1891 bool Position::is_mate() const {
1895 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1896 return mp.get_next_move() == MOVE_NONE;
1902 /// Position::is_draw() tests whether the position is drawn by material,
1903 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1904 /// must be done by the search.
1906 bool Position::is_draw() const {
1908 // Draw by material?
1910 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1913 // Draw by the 50 moves rule?
1914 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1917 // Draw by repetition?
1918 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1919 if (history[gamePly - i] == key)
1926 /// Position::has_mate_threat() tests whether a given color has a mate in one
1927 /// from the current position. This function is quite slow, but it doesn't
1928 /// matter, because it is currently only called from PV nodes, which are rare.
1930 bool Position::has_mate_threat(Color c) {
1933 Color stm = side_to_move();
1935 // The following lines are useless and silly, but prevents gcc from
1936 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1937 // be used uninitialized.
1938 u1.lastMove = lastMove;
1939 u1.epSquare = epSquare;
1944 // If the input color is not equal to the side to move, do a null move
1948 MoveStack mlist[120];
1950 bool result = false;
1952 // Generate legal moves
1953 count = generate_legal_moves(*this, mlist);
1955 // Loop through the moves, and see if one of them is mate
1956 for (int i = 0; i < count; i++)
1958 do_move(mlist[i].move, u2);
1962 undo_move(mlist[i].move, u2);
1965 // Undo null move, if necessary
1973 /// Position::init_zobrist() is a static member function which initializes the
1974 /// various arrays used to compute hash keys.
1976 void Position::init_zobrist() {
1978 for (int i = 0; i < 2; i++)
1979 for (int j = 0; j < 8; j++)
1980 for (int k = 0; k < 64; k++)
1981 zobrist[i][j][k] = Key(genrand_int64());
1983 for (int i = 0; i < 64; i++)
1984 zobEp[i] = Key(genrand_int64());
1986 for (int i = 0; i < 16; i++)
1987 zobCastle[i] = genrand_int64();
1989 zobSideToMove = genrand_int64();
1991 for (int i = 0; i < 2; i++)
1992 for (int j = 0; j < 8; j++)
1993 for (int k = 0; k < 16; k++)
1994 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1996 for (int i = 0; i < 16; i++)
1997 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2001 /// Position::init_piece_square_tables() initializes the piece square tables.
2002 /// This is a two-step operation: First, the white halves of the tables are
2003 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2004 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2005 /// Second, the black halves of the tables are initialized by mirroring
2006 /// and changing the sign of the corresponding white scores.
2008 void Position::init_piece_square_tables() {
2010 int r = get_option_value_int("Randomness"), i;
2011 for (Square s = SQ_A1; s <= SQ_H8; s++)
2012 for (Piece p = WP; p <= WK; p++)
2014 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2015 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2016 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2019 for (Square s = SQ_A1; s <= SQ_H8; s++)
2020 for (Piece p = BP; p <= BK; p++)
2022 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2023 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2028 /// Position::flipped_copy() makes a copy of the input position, but with
2029 /// the white and black sides reversed. This is only useful for debugging,
2030 /// especially for finding evaluation symmetry bugs.
2032 void Position::flipped_copy(const Position &pos) {
2034 assert(pos.is_ok());
2039 for (Square s = SQ_A1; s <= SQ_H8; s++)
2040 if (!pos.square_is_empty(s))
2041 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2044 sideToMove = opposite_color(pos.side_to_move());
2047 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2048 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2049 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2050 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2052 initialKFile = pos.initialKFile;
2053 initialKRFile = pos.initialKRFile;
2054 initialQRFile = pos.initialQRFile;
2056 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2057 castleRightsMask[sq] = ALL_CASTLES;
2059 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2060 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2061 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2062 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2063 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2064 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2066 // En passant square
2067 if (pos.epSquare != SQ_NONE)
2068 epSquare = flip_square(pos.epSquare);
2074 key = compute_key();
2075 pawnKey = compute_pawn_key();
2076 materialKey = compute_material_key();
2078 // Incremental scores
2079 mgValue = compute_mg_value();
2080 egValue = compute_eg_value();
2083 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2084 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2090 /// Position::is_ok() performs some consitency checks for the position object.
2091 /// This is meant to be helpful when debugging.
2093 bool Position::is_ok(int* failedStep) const {
2095 // What features of the position should be verified?
2096 static const bool debugBitboards = false;
2097 static const bool debugKingCount = false;
2098 static const bool debugKingCapture = false;
2099 static const bool debugCheckerCount = false;
2100 static const bool debugKey = false;
2101 static const bool debugMaterialKey = false;
2102 static const bool debugPawnKey = false;
2103 static const bool debugIncrementalEval = false;
2104 static const bool debugNonPawnMaterial = false;
2105 static const bool debugPieceCounts = false;
2106 static const bool debugPieceList = false;
2108 if (failedStep) *failedStep = 1;
2111 if (!color_is_ok(side_to_move()))
2114 // Are the king squares in the position correct?
2115 if (failedStep) (*failedStep)++;
2116 if (piece_on(king_square(WHITE)) != WK)
2119 if (failedStep) (*failedStep)++;
2120 if (piece_on(king_square(BLACK)) != BK)
2124 if (failedStep) (*failedStep)++;
2125 if (!file_is_ok(initialKRFile))
2128 if (!file_is_ok(initialQRFile))
2131 // Do both sides have exactly one king?
2132 if (failedStep) (*failedStep)++;
2135 int kingCount[2] = {0, 0};
2136 for (Square s = SQ_A1; s <= SQ_H8; s++)
2137 if (type_of_piece_on(s) == KING)
2138 kingCount[color_of_piece_on(s)]++;
2140 if (kingCount[0] != 1 || kingCount[1] != 1)
2144 // Can the side to move capture the opponent's king?
2145 if (failedStep) (*failedStep)++;
2146 if (debugKingCapture)
2148 Color us = side_to_move();
2149 Color them = opposite_color(us);
2150 Square ksq = king_square(them);
2151 if (square_is_attacked(ksq, us))
2155 // Is there more than 2 checkers?
2156 if (failedStep) (*failedStep)++;
2157 if (debugCheckerCount && count_1s(checkersBB) > 2)
2161 if (failedStep) (*failedStep)++;
2164 // The intersection of the white and black pieces must be empty
2165 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2168 // The union of the white and black pieces must be equal to all
2170 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2173 // Separate piece type bitboards must have empty intersections
2174 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2175 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2176 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2180 // En passant square OK?
2181 if (failedStep) (*failedStep)++;
2182 if (ep_square() != SQ_NONE)
2184 // The en passant square must be on rank 6, from the point of view of the
2186 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2191 if (failedStep) (*failedStep)++;
2192 if (debugKey && key != compute_key())
2195 // Pawn hash key OK?
2196 if (failedStep) (*failedStep)++;
2197 if (debugPawnKey && pawnKey != compute_pawn_key())
2200 // Material hash key OK?
2201 if (failedStep) (*failedStep)++;
2202 if (debugMaterialKey && materialKey != compute_material_key())
2205 // Incremental eval OK?
2206 if (failedStep) (*failedStep)++;
2207 if (debugIncrementalEval)
2209 if (mgValue != compute_mg_value())
2212 if (egValue != compute_eg_value())
2216 // Non-pawn material OK?
2217 if (failedStep) (*failedStep)++;
2218 if (debugNonPawnMaterial)
2220 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2223 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2228 if (failedStep) (*failedStep)++;
2229 if (debugPieceCounts)
2230 for (Color c = WHITE; c <= BLACK; c++)
2231 for (PieceType pt = PAWN; pt <= KING; pt++)
2232 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2235 if (failedStep) (*failedStep)++;
2238 for(Color c = WHITE; c <= BLACK; c++)
2239 for(PieceType pt = PAWN; pt <= KING; pt++)
2240 for(int i = 0; i < pieceCount[c][pt]; i++)
2242 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2245 if (index[piece_list(c, pt, i)] != i)
2249 if (failedStep) *failedStep = 0;