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];
62 Position::Position(const Position &pos) {
66 Position::Position(const std::string &fen) {
71 /// Position::from_fen() initializes the position object with the given FEN
72 /// string. This function is not very robust - make sure that input FENs are
73 /// correct (this is assumed to be the responsibility of the GUI).
75 void Position::from_fen(const std::string &fen) {
77 static const std::string pieceLetters = "KQRBNPkqrbnp";
78 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
86 for ( ; fen[i] != ' '; i++)
90 // Skip the given number of files
91 file += (fen[i] - '1' + 1);
94 else if (fen[i] == '/')
100 size_t idx = pieceLetters.find(fen[i]);
101 if (idx == std::string::npos)
103 std::cout << "Error in FEN at character " << i << std::endl;
106 Square square = make_square(file, rank);
107 put_piece(pieces[idx], square);
113 if (fen[i] != 'w' && fen[i] != 'b')
115 std::cout << "Error in FEN at character " << i << std::endl;
118 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
124 std::cout << "Error in FEN at character " << i << std::endl;
129 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
133 else if(fen[i] == 'K') allow_oo(WHITE);
134 else if(fen[i] == 'Q') allow_ooo(WHITE);
135 else if(fen[i] == 'k') allow_oo(BLACK);
136 else if(fen[i] == 'q') allow_ooo(BLACK);
137 else if(fen[i] >= 'A' && fen[i] <= 'H') {
138 File rookFile, kingFile = FILE_NONE;
139 for(Square square = SQ_B1; square <= SQ_G1; square++)
140 if(piece_on(square) == WK)
141 kingFile = square_file(square);
142 if(kingFile == FILE_NONE) {
143 std::cout << "Error in FEN at character " << i << std::endl;
146 initialKFile = kingFile;
147 rookFile = File(fen[i] - 'A') + FILE_A;
148 if(rookFile < initialKFile) {
150 initialQRFile = rookFile;
154 initialKRFile = rookFile;
157 else if(fen[i] >= 'a' && fen[i] <= 'h') {
158 File rookFile, kingFile = FILE_NONE;
159 for(Square square = SQ_B8; square <= SQ_G8; square++)
160 if(piece_on(square) == BK)
161 kingFile = square_file(square);
162 if(kingFile == FILE_NONE) {
163 std::cout << "Error in FEN at character " << i << std::endl;
166 initialKFile = kingFile;
167 rookFile = File(fen[i] - 'a') + FILE_A;
168 if(rookFile < initialKFile) {
170 initialQRFile = rookFile;
174 initialKRFile = rookFile;
178 std::cout << "Error in FEN at character " << i << std::endl;
185 while (fen[i] == ' ')
189 if ( i < fen.length() - 2
190 && (fen[i] >= 'a' && fen[i] <= 'h')
191 && (fen[i+1] == '3' || fen[i+1] == '6'))
192 epSquare = square_from_string(fen.substr(i, 2));
194 // Various initialisation
195 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
196 castleRightsMask[sq] = ALL_CASTLES;
198 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
199 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
200 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
201 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
202 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
203 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
208 pawnKey = compute_pawn_key();
209 materialKey = compute_material_key();
210 mgValue = compute_mg_value();
211 egValue = compute_eg_value();
212 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
213 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
217 /// Position::to_fen() converts the position object to a FEN string. This is
218 /// probably only useful for debugging.
220 const std::string Position::to_fen() const {
222 static const std::string pieceLetters = " PNBRQK pnbrqk";
226 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
229 for (File file = FILE_A; file <= FILE_H; file++)
231 Square sq = make_square(file, rank);
232 if (!square_is_occupied(sq))
238 fen += (char)skip + '0';
241 fen += pieceLetters[piece_on(sq)];
244 fen += (char)skip + '0';
246 fen += (rank > RANK_1 ? '/' : ' ');
248 fen += (sideToMove == WHITE ? "w " : "b ");
249 if (castleRights != NO_CASTLES)
251 if (can_castle_kingside(WHITE)) fen += 'K';
252 if (can_castle_queenside(WHITE)) fen += 'Q';
253 if (can_castle_kingside(BLACK)) fen += 'k';
254 if (can_castle_queenside(BLACK)) fen += 'q';
259 if (ep_square() != SQ_NONE)
260 fen += square_to_string(ep_square());
268 /// Position::print() prints an ASCII representation of the position to
269 /// the standard output. If a move is given then also the san is print.
271 void Position::print(Move m) const {
273 static const std::string pieceLetters = " PNBRQK PNBRQK .";
275 std::cout << std::endl;
278 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
279 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
281 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
283 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
284 for (File file = FILE_A; file <= FILE_H; file++)
286 Square sq = make_square(file, rank);
287 Piece piece = piece_on(sq);
288 if (piece == EMPTY && square_color(sq) == WHITE)
291 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
292 std::cout << '|' << col << pieceLetters[piece] << col;
294 std::cout << '|' << std::endl;
296 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
297 << "Fen is: " << to_fen() << std::endl
298 << "Key is: " << key << std::endl;
302 /// Position::copy() creates a copy of the input position.
304 void Position::copy(const Position &pos) {
306 memcpy(this, &pos, sizeof(Position));
310 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
311 /// king) pieces for the given color.
312 Bitboard Position::pinned_pieces(Color c) const {
314 Square ksq = king_square(c);
315 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
319 /// Position:discovered_check_candidates() returns a bitboard containing all
320 /// pieces for the given side which are candidates for giving a discovered
321 /// check. The code is almost the same as the function for finding pinned
324 Bitboard Position::discovered_check_candidates(Color c) const {
326 Square ksq = king_square(opposite_color(c));
327 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
331 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
332 /// king) pieces for the given color and for the given pinner type. Or, when
333 /// template parameter FindPinned is false, the pinned pieces of opposite color
334 /// that are, indeed, the pieces candidate for a discovery check.
335 template<PieceType Piece, bool FindPinned>
336 Bitboard Position::hidden_checks(Color c, Square ksq) const {
339 Bitboard sliders, result = EmptyBoardBB;
341 if (Piece == ROOK) // Resolved at compile time
342 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
344 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
346 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
348 // King blockers are candidate pinned pieces
349 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
351 // Pinners are sliders, not checkers, that give check when
352 // candidate pinned are removed.
353 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
356 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
358 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
360 // Finally for each pinner find the corresponding pinned piece (if same color of king)
361 // or discovery checker (if opposite color) among the candidates.
364 s = pop_1st_bit(&pinners);
365 result |= (squares_between(s, ksq) & candidate_pinned);
372 /// Position::square_is_attacked() checks whether the given side attacks the
375 bool Position::square_is_attacked(Square s, Color c) const {
377 return (pawn_attacks(opposite_color(c), s) & pawns(c))
378 || (piece_attacks<KNIGHT>(s) & knights(c))
379 || (piece_attacks<KING>(s) & kings(c))
380 || (piece_attacks<ROOK>(s) & rooks_and_queens(c))
381 || (piece_attacks<BISHOP>(s) & bishops_and_queens(c));
385 /// Position::attacks_to() computes a bitboard containing all pieces which
386 /// attacks a given square. There are two versions of this function: One
387 /// which finds attackers of both colors, and one which only finds the
388 /// attackers for one side.
390 Bitboard Position::attacks_to(Square s) const {
392 return (pawn_attacks(BLACK, s) & pawns(WHITE))
393 | (pawn_attacks(WHITE, s) & pawns(BLACK))
394 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
395 | (piece_attacks<ROOK>(s) & rooks_and_queens())
396 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
397 | (piece_attacks<KING>(s) & pieces_of_type(KING));
400 Bitboard Position::attacks_to(Square s, Color c) const {
402 return attacks_to(s) & pieces_of_color(c);
406 /// Position::piece_attacks_square() tests whether the piece on square f
407 /// attacks square t.
409 bool Position::piece_attacks_square(Square f, Square t) const {
411 assert(square_is_ok(f));
412 assert(square_is_ok(t));
416 case WP: return pawn_attacks_square(WHITE, f, t);
417 case BP: return pawn_attacks_square(BLACK, f, t);
418 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
419 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
420 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
421 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
422 case WK: case BK: return piece_attacks_square<KING>(f, t);
429 /// Position::move_attacks_square() tests whether a move from the current
430 /// position attacks a given square. Only attacks by the moving piece are
431 /// considered; the function does not handle X-ray attacks.
433 bool Position::move_attacks_square(Move m, Square s) const {
435 assert(move_is_ok(m));
436 assert(square_is_ok(s));
438 Square f = move_from(m), t = move_to(m);
440 assert(square_is_occupied(f));
444 case WP: return pawn_attacks_square(WHITE, t, s);
445 case BP: return pawn_attacks_square(BLACK, t, s);
446 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
447 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
448 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
449 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
450 case WK: case BK: return piece_attacks_square<KING>(t, s);
457 /// Position::find_checkers() computes the checkersBB bitboard, which
458 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
459 /// currently works by calling Position::attacks_to, which is probably
460 /// inefficient. Consider rewriting this function to use the last move
461 /// played, like in non-bitboard versions of Glaurung.
463 void Position::find_checkers() {
465 Color us = side_to_move();
466 checkersBB = attacks_to(king_square(us), opposite_color(us));
470 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
471 /// There are two versions of this function: One which takes only a
472 /// move as input, and one which takes a move and a bitboard of pinned
473 /// pieces. The latter function is faster, and should always be preferred
474 /// when a pinned piece bitboard has already been computed.
476 bool Position::pl_move_is_legal(Move m) const {
478 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
481 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
484 assert(move_is_ok(m));
485 assert(pinned == pinned_pieces(side_to_move()));
487 // If we're in check, all pseudo-legal moves are legal, because our
488 // check evasion generator only generates true legal moves.
492 // Castling moves are checked for legality during move generation.
493 if (move_is_castle(m))
496 Color us = side_to_move();
497 Color them = opposite_color(us);
498 Square from = move_from(m);
499 Square ksq = king_square(us);
501 assert(color_of_piece_on(from) == us);
502 assert(piece_on(ksq) == king_of_color(us));
504 // En passant captures are a tricky special case. Because they are
505 // rather uncommon, we do it simply by testing whether the king is attacked
506 // after the move is made
509 Square to = move_to(m);
510 Square capsq = make_square(square_file(to), square_rank(from));
511 Bitboard b = occupied_squares();
513 assert(to == ep_square());
514 assert(piece_on(from) == pawn_of_color(us));
515 assert(piece_on(capsq) == pawn_of_color(them));
516 assert(piece_on(to) == EMPTY);
519 clear_bit(&b, capsq);
522 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
523 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
526 // If the moving piece is a king, check whether the destination
527 // square is attacked by the opponent.
529 return !(square_is_attacked(move_to(m), them));
531 // A non-king move is legal if and only if it is not pinned or it
532 // is moving along the ray towards or away from the king.
533 return ( !bit_is_set(pinned, from)
534 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
538 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
539 /// There are two versions of this function: One which takes only a move as
540 /// input, and one which takes a move and a bitboard of discovered check
541 /// candidates. The latter function is faster, and should always be preferred
542 /// when a discovered check candidates bitboard has already been computed.
544 bool Position::move_is_check(Move m) const {
546 Bitboard dc = discovered_check_candidates(side_to_move());
547 return move_is_check(m, dc);
550 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
553 assert(move_is_ok(m));
554 assert(dcCandidates == discovered_check_candidates(side_to_move()));
556 Color us = side_to_move();
557 Color them = opposite_color(us);
558 Square from = move_from(m);
559 Square to = move_to(m);
560 Square ksq = king_square(them);
562 assert(color_of_piece_on(from) == us);
563 assert(piece_on(ksq) == king_of_color(them));
565 // Proceed according to the type of the moving piece
566 switch (type_of_piece_on(from))
570 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
573 if ( bit_is_set(dcCandidates, from) // Discovered check?
574 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
577 if (move_promotion(m)) // Promotion with check?
579 Bitboard b = occupied_squares();
582 switch (move_promotion(m))
585 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
587 return bit_is_set(bishop_attacks_bb(to, b), ksq);
589 return bit_is_set(rook_attacks_bb(to, b), ksq);
591 return bit_is_set(queen_attacks_bb(to, b), ksq);
596 // En passant capture with check? We have already handled the case
597 // of direct checks and ordinary discovered check, the only case we
598 // need to handle is the unusual case of a discovered check through the
600 else if (move_is_ep(m))
602 Square capsq = make_square(square_file(to), square_rank(from));
603 Bitboard b = occupied_squares();
605 clear_bit(&b, capsq);
607 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
608 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
613 return bit_is_set(dcCandidates, from) // Discovered check?
614 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
617 return bit_is_set(dcCandidates, from) // Discovered check?
618 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
621 return bit_is_set(dcCandidates, from) // Discovered check?
622 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
625 // Discovered checks are impossible!
626 assert(!bit_is_set(dcCandidates, from));
627 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
631 if ( bit_is_set(dcCandidates, from)
632 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
635 // Castling with check?
636 if (move_is_castle(m))
638 Square kfrom, kto, rfrom, rto;
639 Bitboard b = occupied_squares();
645 kto = relative_square(us, SQ_G1);
646 rto = relative_square(us, SQ_F1);
648 kto = relative_square(us, SQ_C1);
649 rto = relative_square(us, SQ_D1);
651 clear_bit(&b, kfrom);
652 clear_bit(&b, rfrom);
655 return bit_is_set(rook_attacks_bb(rto, b), ksq);
659 default: // NO_PIECE_TYPE
667 /// Position::move_is_capture() tests whether a move from the current
668 /// position is a capture.
670 bool Position::move_is_capture(Move m) const {
672 return ( !square_is_empty(move_to(m))
673 && (color_of_piece_on(move_to(m)) == opposite_color(side_to_move()))
679 /// Position::backup() is called when making a move. All information
680 /// necessary to restore the position when the move is later unmade
681 /// is saved to an UndoInfo object. The function Position::restore
682 /// does the reverse operation: When one does a backup followed by
683 /// a restore with the same UndoInfo object, the position is restored
684 /// to the state before backup was called.
686 void Position::backup(UndoInfo& u) const {
688 u.castleRights = castleRights;
689 u.epSquare = epSquare;
690 u.checkersBB = checkersBB;
693 u.materialKey = materialKey;
695 u.lastMove = lastMove;
698 u.capture = NO_PIECE_TYPE;
702 /// Position::restore() is called when unmaking a move. It copies back
703 /// the information backed up during a previous call to Position::backup.
705 void Position::restore(const UndoInfo& u) {
707 castleRights = u.castleRights;
708 epSquare = u.epSquare;
709 checkersBB = u.checkersBB;
712 materialKey = u.materialKey;
714 lastMove = u.lastMove;
717 // u.capture is restored in undo_move()
720 /// Position::do_move() makes a move, and backs up all information necessary
721 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
722 /// Pseudo-legal moves should be filtered out before this function is called.
723 /// There are two versions of this function, one which takes only the move and
724 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
725 /// discovered check candidates. The second version is faster, because knowing
726 /// the discovered check candidates makes it easier to update the checkersBB
727 /// member variable in the position object.
729 void Position::do_move(Move m, UndoInfo& u) {
731 do_move(m, u, discovered_check_candidates(side_to_move()));
734 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
737 assert(move_is_ok(m));
739 // Back up the necessary information to our UndoInfo object (except the
740 // captured piece, which is taken care of later.
743 // Save the current key to the history[] array, in order to be able to
744 // detect repetition draws.
745 history[gamePly] = key;
747 // Increment the 50 moves rule draw counter. Resetting it to zero in the
748 // case of non-reversible moves is taken care of later.
751 if (move_is_castle(m))
753 else if (move_promotion(m))
754 do_promotion_move(m, u);
755 else if (move_is_ep(m))
759 Color us = side_to_move();
760 Color them = opposite_color(us);
761 Square from = move_from(m);
762 Square to = move_to(m);
764 assert(color_of_piece_on(from) == us);
765 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
767 PieceType piece = type_of_piece_on(from);
768 PieceType capture = type_of_piece_on(to);
773 do_capture_move(m, capture, them, to);
777 clear_bit(&(byColorBB[us]), from);
778 clear_bit(&(byTypeBB[piece]), from);
779 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
780 set_bit(&(byColorBB[us]), to);
781 set_bit(&(byTypeBB[piece]), to);
782 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
783 board[to] = board[from];
787 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
789 // Update incremental scores
790 mgValue -= mg_pst(us, piece, from);
791 mgValue += mg_pst(us, piece, to);
792 egValue -= eg_pst(us, piece, from);
793 egValue += eg_pst(us, piece, to);
795 // If the moving piece was a king, update the king square
799 // If the move was a double pawn push, set the en passant square.
800 // This code is a bit ugly right now, and should be cleaned up later.
802 if (epSquare != SQ_NONE)
804 key ^= zobEp[epSquare];
809 if (abs(int(to) - int(from)) == 16)
812 && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
814 && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
816 epSquare = Square((int(from) + int(to)) / 2);
817 key ^= zobEp[epSquare];
820 // Reset rule 50 draw counter
823 // Update pawn hash key
824 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
826 // Update piece lists
827 pieceList[us][piece][index[from]] = to;
828 index[to] = index[from];
830 // Update castle rights
831 key ^= zobCastle[castleRights];
832 castleRights &= castleRightsMask[from];
833 castleRights &= castleRightsMask[to];
834 key ^= zobCastle[castleRights];
836 // Update checkers bitboard
837 checkersBB = EmptyBoardBB;
838 Square ksq = king_square(them);
842 if (bit_is_set(pawn_attacks(them, ksq), to))
843 set_bit(&checkersBB, to);
845 if (bit_is_set(dcCandidates, from))
846 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
847 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
851 if (bit_is_set(piece_attacks<KNIGHT>(ksq), to))
852 set_bit(&checkersBB, to);
854 if (bit_is_set(dcCandidates, from))
855 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
856 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
860 if (bit_is_set(piece_attacks<BISHOP>(ksq), to))
861 set_bit(&checkersBB, to);
863 if (bit_is_set(dcCandidates, from))
864 checkersBB |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(us));
868 if (bit_is_set(piece_attacks<ROOK>(ksq), to))
869 set_bit(&checkersBB, to);
871 if (bit_is_set(dcCandidates, from))
872 checkersBB |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us));
876 if (bit_is_set(piece_attacks<QUEEN>(ksq), to))
877 set_bit(&checkersBB, to);
881 if (bit_is_set(dcCandidates, from))
882 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
883 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
893 key ^= zobSideToMove;
894 sideToMove = opposite_color(sideToMove);
897 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
898 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
904 /// Position::do_capture_move() is a private method used to update captured
905 /// piece info. It is called from the main Position::do_move function.
907 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
909 assert(capture != KING);
911 // Remove captured piece
912 clear_bit(&(byColorBB[them]), to);
913 clear_bit(&(byTypeBB[capture]), to);
916 key ^= zobrist[them][capture][to];
918 // If the captured piece was a pawn, update pawn hash key
920 pawnKey ^= zobrist[them][PAWN][to];
922 // Update incremental scores
923 mgValue -= mg_pst(them, capture, to);
924 egValue -= eg_pst(them, capture, to);
926 assert(!move_promotion(m) || capture != PAWN);
930 npMaterial[them] -= piece_value_midgame(capture);
932 // Update material hash key
933 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
935 // Update piece count
936 pieceCount[them][capture]--;
939 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
940 index[pieceList[them][capture][index[to]]] = index[to];
942 // Reset rule 50 counter
947 /// Position::do_castle_move() is a private method used to make a castling
948 /// move. It is called from the main Position::do_move function. Note that
949 /// castling moves are encoded as "king captures friendly rook" moves, for
950 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
952 void Position::do_castle_move(Move m) {
955 assert(move_is_ok(m));
956 assert(move_is_castle(m));
958 Color us = side_to_move();
959 Color them = opposite_color(us);
961 // Find source squares for king and rook
962 Square kfrom = move_from(m);
963 Square rfrom = move_to(m); // HACK: See comment at beginning of function
966 assert(piece_on(kfrom) == king_of_color(us));
967 assert(piece_on(rfrom) == rook_of_color(us));
969 // Find destination squares for king and rook
970 if (rfrom > kfrom) // O-O
972 kto = relative_square(us, SQ_G1);
973 rto = relative_square(us, SQ_F1);
975 kto = relative_square(us, SQ_C1);
976 rto = relative_square(us, SQ_D1);
979 // Remove pieces from source squares
980 clear_bit(&(byColorBB[us]), kfrom);
981 clear_bit(&(byTypeBB[KING]), kfrom);
982 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
983 clear_bit(&(byColorBB[us]), rfrom);
984 clear_bit(&(byTypeBB[ROOK]), rfrom);
985 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
987 // Put pieces on destination squares
988 set_bit(&(byColorBB[us]), kto);
989 set_bit(&(byTypeBB[KING]), kto);
990 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
991 set_bit(&(byColorBB[us]), rto);
992 set_bit(&(byTypeBB[ROOK]), rto);
993 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
995 // Update board array
996 board[kfrom] = board[rfrom] = EMPTY;
997 board[kto] = king_of_color(us);
998 board[rto] = rook_of_color(us);
1000 // Update king square
1001 kingSquare[us] = kto;
1003 // Update piece lists
1004 pieceList[us][KING][index[kfrom]] = kto;
1005 pieceList[us][ROOK][index[rfrom]] = rto;
1006 int tmp = index[rfrom];
1007 index[kto] = index[kfrom];
1010 // Update incremental scores
1011 mgValue -= mg_pst(us, KING, kfrom);
1012 mgValue += mg_pst(us, KING, kto);
1013 egValue -= eg_pst(us, KING, kfrom);
1014 egValue += eg_pst(us, KING, kto);
1015 mgValue -= mg_pst(us, ROOK, rfrom);
1016 mgValue += mg_pst(us, ROOK, rto);
1017 egValue -= eg_pst(us, ROOK, rfrom);
1018 egValue += eg_pst(us, ROOK, rto);
1021 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1022 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1024 // Clear en passant square
1025 if(epSquare != SQ_NONE)
1027 key ^= zobEp[epSquare];
1031 // Update castling rights
1032 key ^= zobCastle[castleRights];
1033 castleRights &= castleRightsMask[kfrom];
1034 key ^= zobCastle[castleRights];
1036 // Reset rule 50 counter
1039 // Update checkers BB
1040 checkersBB = attacks_to(king_square(them), us);
1044 /// Position::do_promotion_move() is a private method used to make a promotion
1045 /// move. It is called from the main Position::do_move function. The
1046 /// UndoInfo object, which has been initialized in Position::do_move, is
1047 /// used to store the captured piece (if any).
1049 void Position::do_promotion_move(Move m, UndoInfo &u) {
1053 PieceType capture, promotion;
1056 assert(move_is_ok(m));
1057 assert(move_promotion(m));
1059 us = side_to_move();
1060 them = opposite_color(us);
1061 from = move_from(m);
1064 assert(relative_rank(us, to) == RANK_8);
1065 assert(piece_on(from) == pawn_of_color(us));
1066 assert(color_of_piece_on(to) == them || square_is_empty(to));
1068 capture = type_of_piece_on(to);
1072 u.capture = capture;
1073 do_capture_move(m, capture, them, to);
1077 clear_bit(&(byColorBB[us]), from);
1078 clear_bit(&(byTypeBB[PAWN]), from);
1079 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1080 board[from] = EMPTY;
1082 // Insert promoted piece
1083 promotion = move_promotion(m);
1084 assert(promotion >= KNIGHT && promotion <= QUEEN);
1085 set_bit(&(byColorBB[us]), to);
1086 set_bit(&(byTypeBB[promotion]), to);
1087 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1088 board[to] = piece_of_color_and_type(us, promotion);
1091 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1093 // Update pawn hash key
1094 pawnKey ^= zobrist[us][PAWN][from];
1096 // Update material key
1097 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1098 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1100 // Update piece counts
1101 pieceCount[us][PAWN]--;
1102 pieceCount[us][promotion]++;
1104 // Update piece lists
1105 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1106 index[pieceList[us][PAWN][index[from]]] = index[from];
1107 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1108 index[to] = pieceCount[us][promotion] - 1;
1110 // Update incremental scores
1111 mgValue -= mg_pst(us, PAWN, from);
1112 mgValue += mg_pst(us, promotion, to);
1113 egValue -= eg_pst(us, PAWN, from);
1114 egValue += eg_pst(us, promotion, to);
1117 npMaterial[us] += piece_value_midgame(promotion);
1119 // Clear the en passant square
1120 if (epSquare != SQ_NONE)
1122 key ^= zobEp[epSquare];
1126 // Update castle rights
1127 key ^= zobCastle[castleRights];
1128 castleRights &= castleRightsMask[to];
1129 key ^= zobCastle[castleRights];
1131 // Reset rule 50 counter
1134 // Update checkers BB
1135 checkersBB = attacks_to(king_square(them), us);
1139 /// Position::do_ep_move() is a private method used to make an en passant
1140 /// capture. It is called from the main Position::do_move function. Because
1141 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1142 /// object in which to store the captured piece.
1144 void Position::do_ep_move(Move m) {
1147 Square from, to, capsq;
1150 assert(move_is_ok(m));
1151 assert(move_is_ep(m));
1153 us = side_to_move();
1154 them = opposite_color(us);
1155 from = move_from(m);
1157 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1159 assert(to == epSquare);
1160 assert(relative_rank(us, to) == RANK_6);
1161 assert(piece_on(to) == EMPTY);
1162 assert(piece_on(from) == pawn_of_color(us));
1163 assert(piece_on(capsq) == pawn_of_color(them));
1165 // Remove captured piece
1166 clear_bit(&(byColorBB[them]), capsq);
1167 clear_bit(&(byTypeBB[PAWN]), capsq);
1168 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1169 board[capsq] = EMPTY;
1171 // Remove moving piece from source square
1172 clear_bit(&(byColorBB[us]), from);
1173 clear_bit(&(byTypeBB[PAWN]), from);
1174 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1176 // Put moving piece on destination square
1177 set_bit(&(byColorBB[us]), to);
1178 set_bit(&(byTypeBB[PAWN]), to);
1179 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1180 board[to] = board[from];
1181 board[from] = EMPTY;
1183 // Update material hash key
1184 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1186 // Update piece count
1187 pieceCount[them][PAWN]--;
1189 // Update piece list
1190 pieceList[us][PAWN][index[from]] = to;
1191 index[to] = index[from];
1192 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1193 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1196 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1197 key ^= zobrist[them][PAWN][capsq];
1198 key ^= zobEp[epSquare];
1200 // Update pawn hash key
1201 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1202 pawnKey ^= zobrist[them][PAWN][capsq];
1204 // Update incremental scores
1205 mgValue -= mg_pst(them, PAWN, capsq);
1206 mgValue -= mg_pst(us, PAWN, from);
1207 mgValue += mg_pst(us, PAWN, to);
1208 egValue -= eg_pst(them, PAWN, capsq);
1209 egValue -= eg_pst(us, PAWN, from);
1210 egValue += eg_pst(us, PAWN, to);
1212 // Reset en passant square
1215 // Reset rule 50 counter
1218 // Update checkers BB
1219 checkersBB = attacks_to(king_square(them), us);
1223 /// Position::undo_move() unmakes a move. When it returns, the position should
1224 /// be restored to exactly the same state as before the move was made. It is
1225 /// important that Position::undo_move is called with the same move and UndoInfo
1226 /// object as the earlier call to Position::do_move.
1228 void Position::undo_move(Move m, const UndoInfo &u) {
1231 assert(move_is_ok(m));
1234 sideToMove = opposite_color(sideToMove);
1236 // Restore information from our UndoInfo object (except the captured piece,
1237 // which is taken care of later)
1240 if (move_is_castle(m))
1241 undo_castle_move(m);
1242 else if (move_promotion(m))
1243 undo_promotion_move(m, u);
1244 else if (move_is_ep(m))
1250 PieceType piece, capture;
1252 us = side_to_move();
1253 them = opposite_color(us);
1254 from = move_from(m);
1257 assert(piece_on(from) == EMPTY);
1258 assert(color_of_piece_on(to) == us);
1260 // Put the piece back at the source square
1261 piece = type_of_piece_on(to);
1262 set_bit(&(byColorBB[us]), from);
1263 set_bit(&(byTypeBB[piece]), from);
1264 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1265 board[from] = piece_of_color_and_type(us, piece);
1267 // Clear the destination square
1268 clear_bit(&(byColorBB[us]), to);
1269 clear_bit(&(byTypeBB[piece]), to);
1270 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1272 // If the moving piece was a king, update the king square
1274 kingSquare[us] = from;
1276 // Update piece list
1277 pieceList[us][piece][index[to]] = from;
1278 index[from] = index[to];
1280 capture = u.capture;
1284 assert(capture != KING);
1286 // Replace the captured piece
1287 set_bit(&(byColorBB[them]), to);
1288 set_bit(&(byTypeBB[capture]), to);
1289 set_bit(&(byTypeBB[0]), to);
1290 board[to] = piece_of_color_and_type(them, capture);
1293 if (capture != PAWN)
1294 npMaterial[them] += piece_value_midgame(capture);
1296 // Update piece list
1297 pieceList[them][capture][pieceCount[them][capture]] = to;
1298 index[to] = pieceCount[them][capture];
1300 // Update piece count
1301 pieceCount[them][capture]++;
1310 /// Position::undo_castle_move() is a private method used to unmake a castling
1311 /// move. It is called from the main Position::undo_move function. Note that
1312 /// castling moves are encoded as "king captures friendly rook" moves, for
1313 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1315 void Position::undo_castle_move(Move m) {
1317 assert(move_is_ok(m));
1318 assert(move_is_castle(m));
1320 // When we have arrived here, some work has already been done by
1321 // Position::undo_move. In particular, the side to move has been switched,
1322 // so the code below is correct.
1323 Color us = side_to_move();
1325 // Find source squares for king and rook
1326 Square kfrom = move_from(m);
1327 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1330 // Find destination squares for king and rook
1331 if (rfrom > kfrom) // O-O
1333 kto = relative_square(us, SQ_G1);
1334 rto = relative_square(us, SQ_F1);
1336 kto = relative_square(us, SQ_C1);
1337 rto = relative_square(us, SQ_D1);
1340 assert(piece_on(kto) == king_of_color(us));
1341 assert(piece_on(rto) == rook_of_color(us));
1343 // Remove pieces from destination squares
1344 clear_bit(&(byColorBB[us]), kto);
1345 clear_bit(&(byTypeBB[KING]), kto);
1346 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1347 clear_bit(&(byColorBB[us]), rto);
1348 clear_bit(&(byTypeBB[ROOK]), rto);
1349 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1351 // Put pieces on source squares
1352 set_bit(&(byColorBB[us]), kfrom);
1353 set_bit(&(byTypeBB[KING]), kfrom);
1354 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1355 set_bit(&(byColorBB[us]), rfrom);
1356 set_bit(&(byTypeBB[ROOK]), rfrom);
1357 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1360 board[rto] = board[kto] = EMPTY;
1361 board[rfrom] = rook_of_color(us);
1362 board[kfrom] = king_of_color(us);
1364 // Update king square
1365 kingSquare[us] = kfrom;
1367 // Update piece lists
1368 pieceList[us][KING][index[kto]] = kfrom;
1369 pieceList[us][ROOK][index[rto]] = rfrom;
1370 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1371 index[kfrom] = index[kto];
1376 /// Position::undo_promotion_move() is a private method used to unmake a
1377 /// promotion move. It is called from the main Position::do_move
1378 /// function. The UndoInfo object, which has been initialized in
1379 /// Position::do_move, is used to put back the captured piece (if any).
1381 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1385 PieceType capture, promotion;
1387 assert(move_is_ok(m));
1388 assert(move_promotion(m));
1390 // When we have arrived here, some work has already been done by
1391 // Position::undo_move. In particular, the side to move has been switched,
1392 // so the code below is correct.
1393 us = side_to_move();
1394 them = opposite_color(us);
1395 from = move_from(m);
1398 assert(relative_rank(us, to) == RANK_8);
1399 assert(piece_on(from) == EMPTY);
1401 // Remove promoted piece
1402 promotion = move_promotion(m);
1403 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1404 assert(promotion >= KNIGHT && promotion <= QUEEN);
1405 clear_bit(&(byColorBB[us]), to);
1406 clear_bit(&(byTypeBB[promotion]), to);
1407 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1409 // Insert pawn at source square
1410 set_bit(&(byColorBB[us]), from);
1411 set_bit(&(byTypeBB[PAWN]), from);
1412 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1413 board[from] = pawn_of_color(us);
1416 npMaterial[us] -= piece_value_midgame(promotion);
1418 // Update piece list
1419 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1420 index[from] = pieceCount[us][PAWN];
1421 pieceList[us][promotion][index[to]] =
1422 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1423 index[pieceList[us][promotion][index[to]]] = index[to];
1425 // Update piece counts
1426 pieceCount[us][promotion]--;
1427 pieceCount[us][PAWN]++;
1429 capture = u.capture;
1433 assert(capture != KING);
1435 // Insert captured piece:
1436 set_bit(&(byColorBB[them]), to);
1437 set_bit(&(byTypeBB[capture]), to);
1438 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1439 board[to] = piece_of_color_and_type(them, capture);
1441 // Update material. Because the move is a promotion move, we know
1442 // that the captured piece cannot be a pawn.
1443 assert(capture != PAWN);
1444 npMaterial[them] += piece_value_midgame(capture);
1446 // Update piece list
1447 pieceList[them][capture][pieceCount[them][capture]] = to;
1448 index[to] = pieceCount[them][capture];
1450 // Update piece count
1451 pieceCount[them][capture]++;
1457 /// Position::undo_ep_move() is a private method used to unmake an en passant
1458 /// capture. It is called from the main Position::undo_move function. Because
1459 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1460 /// object from which to retrieve the captured piece.
1462 void Position::undo_ep_move(Move m) {
1464 assert(move_is_ok(m));
1465 assert(move_is_ep(m));
1467 // When we have arrived here, some work has already been done by
1468 // Position::undo_move. In particular, the side to move has been switched,
1469 // so the code below is correct.
1470 Color us = side_to_move();
1471 Color them = opposite_color(us);
1472 Square from = move_from(m);
1473 Square to = move_to(m);
1474 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1476 assert(to == ep_square());
1477 assert(relative_rank(us, to) == RANK_6);
1478 assert(piece_on(to) == pawn_of_color(us));
1479 assert(piece_on(from) == EMPTY);
1480 assert(piece_on(capsq) == EMPTY);
1482 // Replace captured piece
1483 set_bit(&(byColorBB[them]), capsq);
1484 set_bit(&(byTypeBB[PAWN]), capsq);
1485 set_bit(&(byTypeBB[0]), capsq);
1486 board[capsq] = pawn_of_color(them);
1488 // Remove moving piece from destination square
1489 clear_bit(&(byColorBB[us]), to);
1490 clear_bit(&(byTypeBB[PAWN]), to);
1491 clear_bit(&(byTypeBB[0]), to);
1494 // Replace moving piece at source square
1495 set_bit(&(byColorBB[us]), from);
1496 set_bit(&(byTypeBB[PAWN]), from);
1497 set_bit(&(byTypeBB[0]), from);
1498 board[from] = pawn_of_color(us);
1500 // Update piece list:
1501 pieceList[us][PAWN][index[to]] = from;
1502 index[from] = index[to];
1503 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1504 index[capsq] = pieceCount[them][PAWN];
1506 // Update piece count:
1507 pieceCount[them][PAWN]++;
1511 /// Position::do_null_move makes() a "null move": It switches the side to move
1512 /// and updates the hash key without executing any move on the board.
1514 void Position::do_null_move(UndoInfo &u) {
1517 assert(!is_check());
1519 // Back up the information necessary to undo the null move to the supplied
1520 // UndoInfo object. In the case of a null move, the only thing we need to
1521 // remember is the last move made and the en passant square.
1522 u.lastMove = lastMove;
1523 u.epSquare = epSquare;
1525 // Save the current key to the history[] array, in order to be able to
1526 // detect repetition draws.
1527 history[gamePly] = key;
1529 // Update the necessary information
1530 sideToMove = opposite_color(sideToMove);
1531 if (epSquare != SQ_NONE)
1532 key ^= zobEp[epSquare];
1537 key ^= zobSideToMove;
1539 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1540 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1546 /// Position::undo_null_move() unmakes a "null move".
1548 void Position::undo_null_move(const UndoInfo &u) {
1551 assert(!is_check());
1553 // Restore information from the supplied UndoInfo object:
1554 lastMove = u.lastMove;
1555 epSquare = u.epSquare;
1556 if (epSquare != SQ_NONE)
1557 key ^= zobEp[epSquare];
1559 // Update the necessary information.
1560 sideToMove = opposite_color(sideToMove);
1563 key ^= zobSideToMove;
1565 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1566 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1572 /// Position::see() is a static exchange evaluator: It tries to estimate the
1573 /// material gain or loss resulting from a move. There are two versions of
1574 /// this function: One which takes a move as input, and one which takes a
1575 /// 'from' and a 'to' square. The function does not yet understand promotions
1576 /// or en passant captures.
1578 int Position::see(Move m) const {
1580 assert(move_is_ok(m));
1581 return see(move_from(m), move_to(m));
1584 int Position::see(Square from, Square to) const {
1586 // Approximate material values, with pawn = 1
1587 static const int seeValues[18] = {
1588 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1591 Bitboard attackers, occ, b;
1593 assert(square_is_ok(from));
1594 assert(square_is_ok(to));
1596 // Initialize colors
1597 Color us = color_of_piece_on(from);
1598 Color them = opposite_color(us);
1600 // Initialize pieces
1601 Piece piece = piece_on(from);
1602 Piece capture = piece_on(to);
1604 // Find all attackers to the destination square, with the moving piece
1605 // removed, but possibly an X-ray attacker added behind it.
1606 occ = occupied_squares();
1607 clear_bit(&occ, from);
1608 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1609 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1610 | (piece_attacks<KNIGHT>(to) & knights())
1611 | (piece_attacks<KING>(to) & kings())
1612 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1613 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1615 // If the opponent has no attackers, we are finished
1616 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1617 return seeValues[capture];
1619 attackers &= occ; // Remove the moving piece
1621 // The destination square is defended, which makes things rather more
1622 // difficult to compute. We proceed by building up a "swap list" containing
1623 // the material gain or loss at each stop in a sequence of captures to the
1624 // destination square, where the sides alternately capture, and always
1625 // capture with the least valuable piece. After each capture, we look for
1626 // new X-ray attacks from behind the capturing piece.
1627 int lastCapturingPieceValue = seeValues[piece];
1628 int swapList[32], n = 1;
1632 swapList[0] = seeValues[capture];
1635 // Locate the least valuable attacker for the side to move. The loop
1636 // below looks like it is potentially infinite, but it isn't. We know
1637 // that the side to move still has at least one attacker left.
1638 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1641 // Remove the attacker we just found from the 'attackers' bitboard,
1642 // and scan for new X-ray attacks behind the attacker.
1643 b = attackers & pieces_of_color_and_type(c, pt);
1645 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1646 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1650 // Add the new entry to the swap list
1652 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1655 // Remember the value of the capturing piece, and change the side to move
1656 // before beginning the next iteration
1657 lastCapturingPieceValue = seeValues[pt];
1658 c = opposite_color(c);
1660 // Stop after a king capture
1661 if (pt == KING && (attackers & pieces_of_color(c)))
1664 swapList[n++] = 100;
1667 } while (attackers & pieces_of_color(c));
1669 // Having built the swap list, we negamax through it to find the best
1670 // achievable score from the point of view of the side to move
1672 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1678 /// Position::clear() erases the position object to a pristine state, with an
1679 /// empty board, white to move, and no castling rights.
1681 void Position::clear() {
1683 for (int i = 0; i < 64; i++)
1689 for (int i = 0; i < 2; i++)
1690 byColorBB[i] = EmptyBoardBB;
1692 for (int i = 0; i < 7; i++)
1694 byTypeBB[i] = EmptyBoardBB;
1695 pieceCount[0][i] = pieceCount[1][i] = 0;
1696 for (int j = 0; j < 8; j++)
1697 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1700 checkersBB = EmptyBoardBB;
1702 lastMove = MOVE_NONE;
1705 castleRights = NO_CASTLES;
1706 initialKFile = FILE_E;
1707 initialKRFile = FILE_H;
1708 initialQRFile = FILE_A;
1715 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1716 /// UCI interface code, whenever a non-reversible move is made in a
1717 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1718 /// for the program to handle games of arbitrary length, as long as the GUI
1719 /// handles draws by the 50 move rule correctly.
1721 void Position::reset_game_ply() {
1727 /// Position::put_piece() puts a piece on the given square of the board,
1728 /// updating the board array, bitboards, and piece counts.
1730 void Position::put_piece(Piece p, Square s) {
1732 Color c = color_of_piece(p);
1733 PieceType pt = type_of_piece(p);
1736 index[s] = pieceCount[c][pt];
1737 pieceList[c][pt][index[s]] = s;
1739 set_bit(&(byTypeBB[pt]), s);
1740 set_bit(&(byColorBB[c]), s);
1741 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1743 pieceCount[c][pt]++;
1750 /// Position::allow_oo() gives the given side the right to castle kingside.
1751 /// Used when setting castling rights during parsing of FEN strings.
1753 void Position::allow_oo(Color c) {
1755 castleRights |= (1 + int(c));
1759 /// Position::allow_ooo() gives the given side the right to castle queenside.
1760 /// Used when setting castling rights during parsing of FEN strings.
1762 void Position::allow_ooo(Color c) {
1764 castleRights |= (4 + 4*int(c));
1768 /// Position::compute_key() computes the hash key of the position. The hash
1769 /// key is usually updated incrementally as moves are made and unmade, the
1770 /// compute_key() function is only used when a new position is set up, and
1771 /// to verify the correctness of the hash key when running in debug mode.
1773 Key Position::compute_key() const {
1775 Key result = Key(0ULL);
1777 for (Square s = SQ_A1; s <= SQ_H8; s++)
1778 if (square_is_occupied(s))
1779 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1781 if (ep_square() != SQ_NONE)
1782 result ^= zobEp[ep_square()];
1784 result ^= zobCastle[castleRights];
1785 if (side_to_move() == BLACK)
1786 result ^= zobSideToMove;
1792 /// Position::compute_pawn_key() computes the hash key of the position. The
1793 /// hash key is usually updated incrementally as moves are made and unmade,
1794 /// the compute_pawn_key() function is only used when a new position is set
1795 /// up, and to verify the correctness of the pawn hash key when running in
1798 Key Position::compute_pawn_key() const {
1800 Key result = Key(0ULL);
1804 for (Color c = WHITE; c <= BLACK; c++)
1809 s = pop_1st_bit(&b);
1810 result ^= zobrist[c][PAWN][s];
1817 /// Position::compute_material_key() computes the hash key of the position.
1818 /// The hash key is usually updated incrementally as moves are made and unmade,
1819 /// the compute_material_key() function is only used when a new position is set
1820 /// up, and to verify the correctness of the material hash key when running in
1823 Key Position::compute_material_key() const {
1825 Key result = Key(0ULL);
1826 for (Color c = WHITE; c <= BLACK; c++)
1827 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1829 int count = piece_count(c, pt);
1830 for (int i = 0; i <= count; i++)
1831 result ^= zobMaterial[c][pt][i];
1837 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1838 /// incremental scores for the middle game and the endgame. These functions
1839 /// are used to initialize the incremental scores when a new position is set
1840 /// up, and to verify that the scores are correctly updated by do_move
1841 /// and undo_move when the program is running in debug mode.
1843 Value Position::compute_mg_value() const {
1845 Value result = Value(0);
1849 for (Color c = WHITE; c <= BLACK; c++)
1850 for (PieceType pt = PAWN; pt <= KING; pt++)
1852 b = pieces_of_color_and_type(c, pt);
1855 s = pop_1st_bit(&b);
1856 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1857 result += mg_pst(c, pt, s);
1860 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1864 Value Position::compute_eg_value() const {
1866 Value result = Value(0);
1870 for (Color c = WHITE; c <= BLACK; c++)
1871 for (PieceType pt = PAWN; pt <= KING; pt++)
1873 b = pieces_of_color_and_type(c, pt);
1876 s = pop_1st_bit(&b);
1877 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1878 result += eg_pst(c, pt, s);
1881 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1886 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1887 /// game material score for the given side. Material scores are updated
1888 /// incrementally during the search, this function is only used while
1889 /// initializing a new Position object.
1891 Value Position::compute_non_pawn_material(Color c) const {
1893 Value result = Value(0);
1896 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1898 Bitboard b = pieces_of_color_and_type(c, pt);
1901 s = pop_1st_bit(&b);
1902 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1903 result += piece_value_midgame(pt);
1910 /// Position::is_mate() returns true or false depending on whether the
1911 /// side to move is checkmated. Note that this function is currently very
1912 /// slow, and shouldn't be used frequently inside the search.
1914 bool Position::is_mate() {
1918 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1919 return mp.get_next_move() == MOVE_NONE;
1925 /// Position::is_draw() tests whether the position is drawn by material,
1926 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1927 /// must be done by the search.
1929 bool Position::is_draw() const {
1931 // Draw by material?
1933 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1936 // Draw by the 50 moves rule?
1937 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1940 // Draw by repetition?
1941 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1942 if (history[gamePly - i] == key)
1949 /// Position::has_mate_threat() tests whether a given color has a mate in one
1950 /// from the current position. This function is quite slow, but it doesn't
1951 /// matter, because it is currently only called from PV nodes, which are rare.
1953 bool Position::has_mate_threat(Color c) {
1956 Color stm = side_to_move();
1958 // The following lines are useless and silly, but prevents gcc from
1959 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1960 // be used uninitialized.
1961 u1.lastMove = lastMove;
1962 u1.epSquare = epSquare;
1967 // If the input color is not equal to the side to move, do a null move
1971 MoveStack mlist[120];
1973 bool result = false;
1975 // Generate legal moves
1976 count = generate_legal_moves(*this, mlist);
1978 // Loop through the moves, and see if one of them is mate
1979 for (int i = 0; i < count; i++)
1981 do_move(mlist[i].move, u2);
1985 undo_move(mlist[i].move, u2);
1988 // Undo null move, if necessary
1996 /// Position::init_zobrist() is a static member function which initializes the
1997 /// various arrays used to compute hash keys.
1999 void Position::init_zobrist() {
2001 for (int i = 0; i < 2; i++)
2002 for (int j = 0; j < 8; j++)
2003 for (int k = 0; k < 64; k++)
2004 zobrist[i][j][k] = Key(genrand_int64());
2006 for (int i = 0; i < 64; i++)
2007 zobEp[i] = Key(genrand_int64());
2009 for (int i = 0; i < 16; i++)
2010 zobCastle[i] = genrand_int64();
2012 zobSideToMove = genrand_int64();
2014 for (int i = 0; i < 2; i++)
2015 for (int j = 0; j < 8; j++)
2016 for (int k = 0; k < 16; k++)
2017 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2019 for (int i = 0; i < 16; i++)
2020 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2024 /// Position::init_piece_square_tables() initializes the piece square tables.
2025 /// This is a two-step operation: First, the white halves of the tables are
2026 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2027 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2028 /// Second, the black halves of the tables are initialized by mirroring
2029 /// and changing the sign of the corresponding white scores.
2031 void Position::init_piece_square_tables() {
2033 int r = get_option_value_int("Randomness"), i;
2034 for (Square s = SQ_A1; s <= SQ_H8; s++)
2035 for (Piece p = WP; p <= WK; p++)
2037 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2038 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2039 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2042 for (Square s = SQ_A1; s <= SQ_H8; s++)
2043 for (Piece p = BP; p <= BK; p++)
2045 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2046 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2051 /// Position::flipped_copy() makes a copy of the input position, but with
2052 /// the white and black sides reversed. This is only useful for debugging,
2053 /// especially for finding evaluation symmetry bugs.
2055 void Position::flipped_copy(const Position &pos) {
2057 assert(pos.is_ok());
2062 for (Square s = SQ_A1; s <= SQ_H8; s++)
2063 if (!pos.square_is_empty(s))
2064 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2067 sideToMove = opposite_color(pos.side_to_move());
2070 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2071 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2072 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2073 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2075 initialKFile = pos.initialKFile;
2076 initialKRFile = pos.initialKRFile;
2077 initialQRFile = pos.initialQRFile;
2079 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2080 castleRightsMask[sq] = ALL_CASTLES;
2082 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2083 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2084 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2085 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2086 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2087 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2089 // En passant square
2090 if (pos.epSquare != SQ_NONE)
2091 epSquare = flip_square(pos.epSquare);
2097 key = compute_key();
2098 pawnKey = compute_pawn_key();
2099 materialKey = compute_material_key();
2101 // Incremental scores
2102 mgValue = compute_mg_value();
2103 egValue = compute_eg_value();
2106 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2107 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2113 /// Position::is_ok() performs some consitency checks for the position object.
2114 /// This is meant to be helpful when debugging.
2116 bool Position::is_ok(int* failedStep) const {
2118 // What features of the position should be verified?
2119 static const bool debugBitboards = false;
2120 static const bool debugKingCount = false;
2121 static const bool debugKingCapture = false;
2122 static const bool debugCheckerCount = false;
2123 static const bool debugKey = false;
2124 static const bool debugMaterialKey = false;
2125 static const bool debugPawnKey = false;
2126 static const bool debugIncrementalEval = false;
2127 static const bool debugNonPawnMaterial = false;
2128 static const bool debugPieceCounts = false;
2129 static const bool debugPieceList = false;
2131 if (failedStep) *failedStep = 1;
2134 if (!color_is_ok(side_to_move()))
2137 // Are the king squares in the position correct?
2138 if (failedStep) (*failedStep)++;
2139 if (piece_on(king_square(WHITE)) != WK)
2142 if (failedStep) (*failedStep)++;
2143 if (piece_on(king_square(BLACK)) != BK)
2147 if (failedStep) (*failedStep)++;
2148 if (!file_is_ok(initialKRFile))
2151 if (!file_is_ok(initialQRFile))
2154 // Do both sides have exactly one king?
2155 if (failedStep) (*failedStep)++;
2158 int kingCount[2] = {0, 0};
2159 for (Square s = SQ_A1; s <= SQ_H8; s++)
2160 if (type_of_piece_on(s) == KING)
2161 kingCount[color_of_piece_on(s)]++;
2163 if(kingCount[0] != 1 || kingCount[1] != 1)
2167 // Can the side to move capture the opponent's king?
2168 if (failedStep) (*failedStep)++;
2169 if (debugKingCapture)
2171 Color us = side_to_move();
2172 Color them = opposite_color(us);
2173 Square ksq = king_square(them);
2174 if (square_is_attacked(ksq, us))
2178 // Is there more than 2 checkers?
2179 if (failedStep) (*failedStep)++;
2180 if (debugCheckerCount && count_1s(checkersBB) > 2)
2184 if (failedStep) (*failedStep)++;
2187 // The intersection of the white and black pieces must be empty
2188 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2191 // The union of the white and black pieces must be equal to all
2193 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2196 // Separate piece type bitboards must have empty intersections
2197 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2198 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2199 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2203 // En passant square OK?
2204 if (failedStep) (*failedStep)++;
2205 if (ep_square() != SQ_NONE)
2207 // The en passant square must be on rank 6, from the point of view of the
2209 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2214 if (failedStep) (*failedStep)++;
2215 if (debugKey && key != compute_key())
2218 // Pawn hash key OK?
2219 if (failedStep) (*failedStep)++;
2220 if (debugPawnKey && pawnKey != compute_pawn_key())
2223 // Material hash key OK?
2224 if (failedStep) (*failedStep)++;
2225 if (debugMaterialKey && materialKey != compute_material_key())
2228 // Incremental eval OK?
2229 if (failedStep) (*failedStep)++;
2230 if (debugIncrementalEval)
2232 if (mgValue != compute_mg_value())
2235 if (egValue != compute_eg_value())
2239 // Non-pawn material OK?
2240 if (failedStep) (*failedStep)++;
2241 if (debugNonPawnMaterial)
2243 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2246 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2251 if (failedStep) (*failedStep)++;
2252 if (debugPieceCounts)
2253 for (Color c = WHITE; c <= BLACK; c++)
2254 for (PieceType pt = PAWN; pt <= KING; pt++)
2255 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2258 if (failedStep) (*failedStep)++;
2261 for(Color c = WHITE; c <= BLACK; c++)
2262 for(PieceType pt = PAWN; pt <= KING; pt++)
2263 for(int i = 0; i < pieceCount[c][pt]; i++)
2265 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2268 if (index[piece_list(c, pt, i)] != i)
2272 if (failedStep) *failedStep = 0;