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;
279 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
280 std::cout << "Move is: " << col << move_to_san(p, m) << std::endl;
282 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
284 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
285 for (File file = FILE_A; file <= FILE_H; file++)
287 Square sq = make_square(file, rank);
288 Piece piece = piece_on(sq);
289 if (piece == EMPTY && square_color(sq) == WHITE)
292 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
293 std::cout << '|' << col << pieceLetters[piece] << col;
295 std::cout << '|' << std::endl;
297 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
298 << "Fen is: " << to_fen() << std::endl
299 << "Key is: " << key << std::endl;
303 /// Position::copy() creates a copy of the input position.
305 void Position::copy(const Position &pos) {
307 memcpy(this, &pos, sizeof(Position));
311 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
312 /// king) pieces for the given color.
313 Bitboard Position::pinned_pieces(Color c) const {
315 Square ksq = king_square(c);
316 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
320 /// Position:discovered_check_candidates() returns a bitboard containing all
321 /// pieces for the given side which are candidates for giving a discovered
322 /// check. The code is almost the same as the function for finding pinned
325 Bitboard Position::discovered_check_candidates(Color c) const {
327 Square ksq = king_square(opposite_color(c));
328 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
332 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
333 /// king) pieces for the given color and for the given pinner type. Or, when
334 /// template parameter FindPinned is false, the pinned pieces of opposite color
335 /// that are, indeed, the pieces candidate for a discovery check.
336 template<PieceType Piece, bool FindPinned>
337 Bitboard Position::hidden_checks(Color c, Square ksq) const {
340 Bitboard sliders, result = EmptyBoardBB;
342 if (Piece == ROOK) // Resolved at compile time
343 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
345 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
347 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
349 // King blockers are candidate pinned pieces
350 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
352 // Pinners are sliders, not checkers, that give check when
353 // candidate pinned are removed.
354 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
357 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
359 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
361 // Finally for each pinner find the corresponding pinned piece (if same color of king)
362 // or discovery checker (if opposite color) among the candidates.
365 s = pop_1st_bit(&pinners);
366 result |= (squares_between(s, ksq) & candidate_pinned);
373 /// Position::square_is_attacked() checks whether the given side attacks the
376 bool Position::square_is_attacked(Square s, Color c) const {
378 return (pawn_attacks(opposite_color(c), s) & pawns(c))
379 || (piece_attacks<KNIGHT>(s) & knights(c))
380 || (piece_attacks<KING>(s) & kings(c))
381 || (piece_attacks<ROOK>(s) & rooks_and_queens(c))
382 || (piece_attacks<BISHOP>(s) & bishops_and_queens(c));
386 /// Position::attacks_to() computes a bitboard containing all pieces which
387 /// attacks a given square. There are two versions of this function: One
388 /// which finds attackers of both colors, and one which only finds the
389 /// attackers for one side.
391 Bitboard Position::attacks_to(Square s) const {
393 return (pawn_attacks(BLACK, s) & pawns(WHITE))
394 | (pawn_attacks(WHITE, s) & pawns(BLACK))
395 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
396 | (piece_attacks<ROOK>(s) & rooks_and_queens())
397 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
398 | (piece_attacks<KING>(s) & pieces_of_type(KING));
401 Bitboard Position::attacks_to(Square s, Color c) const {
403 return attacks_to(s) & pieces_of_color(c);
407 /// Position::piece_attacks_square() tests whether the piece on square f
408 /// attacks square t.
410 bool Position::piece_attacks_square(Square f, Square t) const {
412 assert(square_is_ok(f));
413 assert(square_is_ok(t));
417 case WP: return pawn_attacks_square(WHITE, f, t);
418 case BP: return pawn_attacks_square(BLACK, f, t);
419 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
420 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
421 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
422 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
423 case WK: case BK: return piece_attacks_square<KING>(f, t);
430 /// Position::move_attacks_square() tests whether a move from the current
431 /// position attacks a given square. Only attacks by the moving piece are
432 /// considered; the function does not handle X-ray attacks.
434 bool Position::move_attacks_square(Move m, Square s) const {
436 assert(move_is_ok(m));
437 assert(square_is_ok(s));
439 Square f = move_from(m), t = move_to(m);
441 assert(square_is_occupied(f));
445 case WP: return pawn_attacks_square(WHITE, t, s);
446 case BP: return pawn_attacks_square(BLACK, t, s);
447 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
448 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
449 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
450 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
451 case WK: case BK: return piece_attacks_square<KING>(t, s);
458 /// Position::find_checkers() computes the checkersBB bitboard, which
459 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
460 /// currently works by calling Position::attacks_to, which is probably
461 /// inefficient. Consider rewriting this function to use the last move
462 /// played, like in non-bitboard versions of Glaurung.
464 void Position::find_checkers() {
466 Color us = side_to_move();
467 checkersBB = attacks_to(king_square(us), opposite_color(us));
471 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
472 /// There are two versions of this function: One which takes only a
473 /// move as input, and one which takes a move and a bitboard of pinned
474 /// pieces. The latter function is faster, and should always be preferred
475 /// when a pinned piece bitboard has already been computed.
477 bool Position::pl_move_is_legal(Move m) const {
479 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
482 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
485 assert(move_is_ok(m));
486 assert(pinned == pinned_pieces(side_to_move()));
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) == king_of_color(us));
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) == pawn_of_color(us));
516 assert(piece_on(capsq) == pawn_of_color(them));
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, 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.
540 /// There are two versions of this function: One which takes only a move as
541 /// input, and one which takes a move and a bitboard of discovered check
542 /// candidates. The latter function is faster, and should always be preferred
543 /// when a discovered check candidates bitboard has already been computed.
545 bool Position::move_is_check(Move m) const {
547 Bitboard dc = discovered_check_candidates(side_to_move());
548 return move_is_check(m, dc);
551 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
554 assert(move_is_ok(m));
555 assert(dcCandidates == discovered_check_candidates(side_to_move()));
557 Color us = side_to_move();
558 Color them = opposite_color(us);
559 Square from = move_from(m);
560 Square to = move_to(m);
561 Square ksq = king_square(them);
563 assert(color_of_piece_on(from) == us);
564 assert(piece_on(ksq) == king_of_color(them));
566 // Proceed according to the type of the moving piece
567 switch (type_of_piece_on(from))
571 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
574 if ( bit_is_set(dcCandidates, from) // Discovered check?
575 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
578 if (move_promotion(m)) // Promotion with check?
580 Bitboard b = occupied_squares();
583 switch (move_promotion(m))
586 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
588 return bit_is_set(bishop_attacks_bb(to, b), ksq);
590 return bit_is_set(rook_attacks_bb(to, b), ksq);
592 return bit_is_set(queen_attacks_bb(to, b), ksq);
597 // En passant capture with check? We have already handled the case
598 // of direct checks and ordinary discovered check, the only case we
599 // need to handle is the unusual case of a discovered check through the
601 else if (move_is_ep(m))
603 Square capsq = make_square(square_file(to), square_rank(from));
604 Bitboard b = occupied_squares();
606 clear_bit(&b, capsq);
608 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
609 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
614 return bit_is_set(dcCandidates, from) // Discovered check?
615 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
618 return bit_is_set(dcCandidates, from) // Discovered check?
619 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
622 return bit_is_set(dcCandidates, from) // Discovered check?
623 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
626 // Discovered checks are impossible!
627 assert(!bit_is_set(dcCandidates, from));
628 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
632 if ( bit_is_set(dcCandidates, from)
633 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
636 // Castling with check?
637 if (move_is_castle(m))
639 Square kfrom, kto, rfrom, rto;
640 Bitboard b = occupied_squares();
646 kto = relative_square(us, SQ_G1);
647 rto = relative_square(us, SQ_F1);
649 kto = relative_square(us, SQ_C1);
650 rto = relative_square(us, SQ_D1);
652 clear_bit(&b, kfrom);
653 clear_bit(&b, rfrom);
656 return bit_is_set(rook_attacks_bb(rto, b), ksq);
660 default: // NO_PIECE_TYPE
668 /// Position::move_is_capture() tests whether a move from the current
669 /// position is a capture.
671 bool Position::move_is_capture(Move m) const {
673 return ( !square_is_empty(move_to(m))
674 && (color_of_piece_on(move_to(m)) == opposite_color(side_to_move()))
680 /// Position::backup() is called when making a move. All information
681 /// necessary to restore the position when the move is later unmade
682 /// is saved to an UndoInfo object. The function Position::restore
683 /// does the reverse operation: When one does a backup followed by
684 /// a restore with the same UndoInfo object, the position is restored
685 /// to the state before backup was called.
687 void Position::backup(UndoInfo& u) const {
689 u.castleRights = castleRights;
690 u.epSquare = epSquare;
691 u.checkersBB = checkersBB;
694 u.materialKey = materialKey;
696 u.lastMove = lastMove;
699 u.capture = NO_PIECE_TYPE;
703 /// Position::restore() is called when unmaking a move. It copies back
704 /// the information backed up during a previous call to Position::backup.
706 void Position::restore(const UndoInfo& u) {
708 castleRights = u.castleRights;
709 epSquare = u.epSquare;
710 checkersBB = u.checkersBB;
713 materialKey = u.materialKey;
715 lastMove = u.lastMove;
718 // u.capture is restored in undo_move()
721 /// Position::do_move() makes a move, and backs up all information necessary
722 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
723 /// Pseudo-legal moves should be filtered out before this function is called.
724 /// There are two versions of this function, one which takes only the move and
725 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
726 /// discovered check candidates. The second version is faster, because knowing
727 /// the discovered check candidates makes it easier to update the checkersBB
728 /// member variable in the position object.
730 void Position::do_move(Move m, UndoInfo& u) {
732 do_move(m, u, discovered_check_candidates(side_to_move()));
735 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
738 assert(move_is_ok(m));
740 // Back up the necessary information to our UndoInfo object (except the
741 // captured piece, which is taken care of later.
744 // Save the current key to the history[] array, in order to be able to
745 // detect repetition draws.
746 history[gamePly] = key;
748 // Increment the 50 moves rule draw counter. Resetting it to zero in the
749 // case of non-reversible moves is taken care of later.
752 if (move_is_castle(m))
754 else if (move_promotion(m))
755 do_promotion_move(m, u);
756 else if (move_is_ep(m))
760 Color us = side_to_move();
761 Color them = opposite_color(us);
762 Square from = move_from(m);
763 Square to = move_to(m);
765 assert(color_of_piece_on(from) == us);
766 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
768 PieceType piece = type_of_piece_on(from);
769 PieceType capture = type_of_piece_on(to);
774 do_capture_move(m, capture, them, to);
778 clear_bit(&(byColorBB[us]), from);
779 clear_bit(&(byTypeBB[piece]), from);
780 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
781 set_bit(&(byColorBB[us]), to);
782 set_bit(&(byTypeBB[piece]), to);
783 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
784 board[to] = board[from];
788 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
790 // Update incremental scores
791 mgValue -= mg_pst(us, piece, from);
792 mgValue += mg_pst(us, piece, to);
793 egValue -= eg_pst(us, piece, from);
794 egValue += eg_pst(us, piece, to);
796 // If the moving piece was a king, update the king square
800 // If the move was a double pawn push, set the en passant square.
801 // This code is a bit ugly right now, and should be cleaned up later.
803 if (epSquare != SQ_NONE)
805 key ^= zobEp[epSquare];
810 if (abs(int(to) - int(from)) == 16)
813 && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
815 && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
817 epSquare = Square((int(from) + int(to)) / 2);
818 key ^= zobEp[epSquare];
821 // Reset rule 50 draw counter
824 // Update pawn hash key
825 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
827 // Update piece lists
828 pieceList[us][piece][index[from]] = to;
829 index[to] = index[from];
831 // Update castle rights
832 key ^= zobCastle[castleRights];
833 castleRights &= castleRightsMask[from];
834 castleRights &= castleRightsMask[to];
835 key ^= zobCastle[castleRights];
837 // Update checkers bitboard
838 checkersBB = EmptyBoardBB;
839 Square ksq = king_square(them);
843 if (bit_is_set(pawn_attacks(them, ksq), to))
844 set_bit(&checkersBB, to);
846 if (bit_is_set(dcCandidates, from))
847 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
848 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
852 if (bit_is_set(piece_attacks<KNIGHT>(ksq), to))
853 set_bit(&checkersBB, to);
855 if (bit_is_set(dcCandidates, from))
856 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
857 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
861 if (bit_is_set(piece_attacks<BISHOP>(ksq), to))
862 set_bit(&checkersBB, to);
864 if (bit_is_set(dcCandidates, from))
865 checkersBB |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(us));
869 if (bit_is_set(piece_attacks<ROOK>(ksq), to))
870 set_bit(&checkersBB, to);
872 if (bit_is_set(dcCandidates, from))
873 checkersBB |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us));
877 if (bit_is_set(piece_attacks<QUEEN>(ksq), to))
878 set_bit(&checkersBB, to);
882 if (bit_is_set(dcCandidates, from))
883 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
884 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
894 key ^= zobSideToMove;
895 sideToMove = opposite_color(sideToMove);
898 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
899 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
905 /// Position::do_capture_move() is a private method used to update captured
906 /// piece info. It is called from the main Position::do_move function.
908 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
910 assert(capture != KING);
912 // Remove captured piece
913 clear_bit(&(byColorBB[them]), to);
914 clear_bit(&(byTypeBB[capture]), to);
917 key ^= zobrist[them][capture][to];
919 // If the captured piece was a pawn, update pawn hash key
921 pawnKey ^= zobrist[them][PAWN][to];
923 // Update incremental scores
924 mgValue -= mg_pst(them, capture, to);
925 egValue -= eg_pst(them, capture, to);
927 assert(!move_promotion(m) || capture != PAWN);
931 npMaterial[them] -= piece_value_midgame(capture);
933 // Update material hash key
934 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
936 // Update piece count
937 pieceCount[them][capture]--;
940 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
941 index[pieceList[them][capture][index[to]]] = index[to];
943 // Reset rule 50 counter
948 /// Position::do_castle_move() is a private method used to make a castling
949 /// move. It is called from the main Position::do_move function. Note that
950 /// castling moves are encoded as "king captures friendly rook" moves, for
951 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
953 void Position::do_castle_move(Move m) {
956 assert(move_is_ok(m));
957 assert(move_is_castle(m));
959 Color us = side_to_move();
960 Color them = opposite_color(us);
962 // Find source squares for king and rook
963 Square kfrom = move_from(m);
964 Square rfrom = move_to(m); // HACK: See comment at beginning of function
967 assert(piece_on(kfrom) == king_of_color(us));
968 assert(piece_on(rfrom) == rook_of_color(us));
970 // Find destination squares for king and rook
971 if (rfrom > kfrom) // O-O
973 kto = relative_square(us, SQ_G1);
974 rto = relative_square(us, SQ_F1);
976 kto = relative_square(us, SQ_C1);
977 rto = relative_square(us, SQ_D1);
980 // Remove pieces from source squares
981 clear_bit(&(byColorBB[us]), kfrom);
982 clear_bit(&(byTypeBB[KING]), kfrom);
983 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
984 clear_bit(&(byColorBB[us]), rfrom);
985 clear_bit(&(byTypeBB[ROOK]), rfrom);
986 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
988 // Put pieces on destination squares
989 set_bit(&(byColorBB[us]), kto);
990 set_bit(&(byTypeBB[KING]), kto);
991 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
992 set_bit(&(byColorBB[us]), rto);
993 set_bit(&(byTypeBB[ROOK]), rto);
994 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
996 // Update board array
997 board[kfrom] = board[rfrom] = EMPTY;
998 board[kto] = king_of_color(us);
999 board[rto] = rook_of_color(us);
1001 // Update king square
1002 kingSquare[us] = kto;
1004 // Update piece lists
1005 pieceList[us][KING][index[kfrom]] = kto;
1006 pieceList[us][ROOK][index[rfrom]] = rto;
1007 int tmp = index[rfrom];
1008 index[kto] = index[kfrom];
1011 // Update incremental scores
1012 mgValue -= mg_pst(us, KING, kfrom);
1013 mgValue += mg_pst(us, KING, kto);
1014 egValue -= eg_pst(us, KING, kfrom);
1015 egValue += eg_pst(us, KING, kto);
1016 mgValue -= mg_pst(us, ROOK, rfrom);
1017 mgValue += mg_pst(us, ROOK, rto);
1018 egValue -= eg_pst(us, ROOK, rfrom);
1019 egValue += eg_pst(us, ROOK, rto);
1022 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1023 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1025 // Clear en passant square
1026 if(epSquare != SQ_NONE)
1028 key ^= zobEp[epSquare];
1032 // Update castling rights
1033 key ^= zobCastle[castleRights];
1034 castleRights &= castleRightsMask[kfrom];
1035 key ^= zobCastle[castleRights];
1037 // Reset rule 50 counter
1040 // Update checkers BB
1041 checkersBB = attacks_to(king_square(them), us);
1045 /// Position::do_promotion_move() is a private method used to make a promotion
1046 /// move. It is called from the main Position::do_move function. The
1047 /// UndoInfo object, which has been initialized in Position::do_move, is
1048 /// used to store the captured piece (if any).
1050 void Position::do_promotion_move(Move m, UndoInfo &u) {
1054 PieceType capture, promotion;
1057 assert(move_is_ok(m));
1058 assert(move_promotion(m));
1060 us = side_to_move();
1061 them = opposite_color(us);
1062 from = move_from(m);
1065 assert(relative_rank(us, to) == RANK_8);
1066 assert(piece_on(from) == pawn_of_color(us));
1067 assert(color_of_piece_on(to) == them || square_is_empty(to));
1069 capture = type_of_piece_on(to);
1073 u.capture = capture;
1074 do_capture_move(m, capture, them, to);
1078 clear_bit(&(byColorBB[us]), from);
1079 clear_bit(&(byTypeBB[PAWN]), from);
1080 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1081 board[from] = EMPTY;
1083 // Insert promoted piece
1084 promotion = move_promotion(m);
1085 assert(promotion >= KNIGHT && promotion <= QUEEN);
1086 set_bit(&(byColorBB[us]), to);
1087 set_bit(&(byTypeBB[promotion]), to);
1088 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1089 board[to] = piece_of_color_and_type(us, promotion);
1092 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1094 // Update pawn hash key
1095 pawnKey ^= zobrist[us][PAWN][from];
1097 // Update material key
1098 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1099 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1101 // Update piece counts
1102 pieceCount[us][PAWN]--;
1103 pieceCount[us][promotion]++;
1105 // Update piece lists
1106 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1107 index[pieceList[us][PAWN][index[from]]] = index[from];
1108 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1109 index[to] = pieceCount[us][promotion] - 1;
1111 // Update incremental scores
1112 mgValue -= mg_pst(us, PAWN, from);
1113 mgValue += mg_pst(us, promotion, to);
1114 egValue -= eg_pst(us, PAWN, from);
1115 egValue += eg_pst(us, promotion, to);
1118 npMaterial[us] += piece_value_midgame(promotion);
1120 // Clear the en passant square
1121 if (epSquare != SQ_NONE)
1123 key ^= zobEp[epSquare];
1127 // Update castle rights
1128 key ^= zobCastle[castleRights];
1129 castleRights &= castleRightsMask[to];
1130 key ^= zobCastle[castleRights];
1132 // Reset rule 50 counter
1135 // Update checkers BB
1136 checkersBB = attacks_to(king_square(them), us);
1140 /// Position::do_ep_move() is a private method used to make an en passant
1141 /// capture. It is called from the main Position::do_move function. Because
1142 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1143 /// object in which to store the captured piece.
1145 void Position::do_ep_move(Move m) {
1148 Square from, to, capsq;
1151 assert(move_is_ok(m));
1152 assert(move_is_ep(m));
1154 us = side_to_move();
1155 them = opposite_color(us);
1156 from = move_from(m);
1158 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1160 assert(to == epSquare);
1161 assert(relative_rank(us, to) == RANK_6);
1162 assert(piece_on(to) == EMPTY);
1163 assert(piece_on(from) == pawn_of_color(us));
1164 assert(piece_on(capsq) == pawn_of_color(them));
1166 // Remove captured piece
1167 clear_bit(&(byColorBB[them]), capsq);
1168 clear_bit(&(byTypeBB[PAWN]), capsq);
1169 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1170 board[capsq] = EMPTY;
1172 // Remove moving piece from source square
1173 clear_bit(&(byColorBB[us]), from);
1174 clear_bit(&(byTypeBB[PAWN]), from);
1175 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1177 // Put moving piece on destination square
1178 set_bit(&(byColorBB[us]), to);
1179 set_bit(&(byTypeBB[PAWN]), to);
1180 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1181 board[to] = board[from];
1182 board[from] = EMPTY;
1184 // Update material hash key
1185 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1187 // Update piece count
1188 pieceCount[them][PAWN]--;
1190 // Update piece list
1191 pieceList[us][PAWN][index[from]] = to;
1192 index[to] = index[from];
1193 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1194 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1197 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1198 key ^= zobrist[them][PAWN][capsq];
1199 key ^= zobEp[epSquare];
1201 // Update pawn hash key
1202 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1203 pawnKey ^= zobrist[them][PAWN][capsq];
1205 // Update incremental scores
1206 mgValue -= mg_pst(them, PAWN, capsq);
1207 mgValue -= mg_pst(us, PAWN, from);
1208 mgValue += mg_pst(us, PAWN, to);
1209 egValue -= eg_pst(them, PAWN, capsq);
1210 egValue -= eg_pst(us, PAWN, from);
1211 egValue += eg_pst(us, PAWN, to);
1213 // Reset en passant square
1216 // Reset rule 50 counter
1219 // Update checkers BB
1220 checkersBB = attacks_to(king_square(them), us);
1224 /// Position::undo_move() unmakes a move. When it returns, the position should
1225 /// be restored to exactly the same state as before the move was made. It is
1226 /// important that Position::undo_move is called with the same move and UndoInfo
1227 /// object as the earlier call to Position::do_move.
1229 void Position::undo_move(Move m, const UndoInfo &u) {
1232 assert(move_is_ok(m));
1235 sideToMove = opposite_color(sideToMove);
1237 // Restore information from our UndoInfo object (except the captured piece,
1238 // which is taken care of later)
1241 if (move_is_castle(m))
1242 undo_castle_move(m);
1243 else if (move_promotion(m))
1244 undo_promotion_move(m, u);
1245 else if (move_is_ep(m))
1251 PieceType piece, capture;
1253 us = side_to_move();
1254 them = opposite_color(us);
1255 from = move_from(m);
1258 assert(piece_on(from) == EMPTY);
1259 assert(color_of_piece_on(to) == us);
1261 // Put the piece back at the source square
1262 piece = type_of_piece_on(to);
1263 set_bit(&(byColorBB[us]), from);
1264 set_bit(&(byTypeBB[piece]), from);
1265 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1266 board[from] = piece_of_color_and_type(us, piece);
1268 // Clear the destination square
1269 clear_bit(&(byColorBB[us]), to);
1270 clear_bit(&(byTypeBB[piece]), to);
1271 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1273 // If the moving piece was a king, update the king square
1275 kingSquare[us] = from;
1277 // Update piece list
1278 pieceList[us][piece][index[to]] = from;
1279 index[from] = index[to];
1281 capture = u.capture;
1285 assert(capture != KING);
1287 // Replace the captured piece
1288 set_bit(&(byColorBB[them]), to);
1289 set_bit(&(byTypeBB[capture]), to);
1290 set_bit(&(byTypeBB[0]), to);
1291 board[to] = piece_of_color_and_type(them, capture);
1294 if (capture != PAWN)
1295 npMaterial[them] += piece_value_midgame(capture);
1297 // Update piece list
1298 pieceList[them][capture][pieceCount[them][capture]] = to;
1299 index[to] = pieceCount[them][capture];
1301 // Update piece count
1302 pieceCount[them][capture]++;
1311 /// Position::undo_castle_move() is a private method used to unmake a castling
1312 /// move. It is called from the main Position::undo_move function. Note that
1313 /// castling moves are encoded as "king captures friendly rook" moves, for
1314 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1316 void Position::undo_castle_move(Move m) {
1318 assert(move_is_ok(m));
1319 assert(move_is_castle(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 Color us = side_to_move();
1326 // Find source squares for king and rook
1327 Square kfrom = move_from(m);
1328 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1331 // Find destination squares for king and rook
1332 if (rfrom > kfrom) // O-O
1334 kto = relative_square(us, SQ_G1);
1335 rto = relative_square(us, SQ_F1);
1337 kto = relative_square(us, SQ_C1);
1338 rto = relative_square(us, SQ_D1);
1341 assert(piece_on(kto) == king_of_color(us));
1342 assert(piece_on(rto) == rook_of_color(us));
1344 // Remove pieces from destination squares
1345 clear_bit(&(byColorBB[us]), kto);
1346 clear_bit(&(byTypeBB[KING]), kto);
1347 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1348 clear_bit(&(byColorBB[us]), rto);
1349 clear_bit(&(byTypeBB[ROOK]), rto);
1350 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1352 // Put pieces on source squares
1353 set_bit(&(byColorBB[us]), kfrom);
1354 set_bit(&(byTypeBB[KING]), kfrom);
1355 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1356 set_bit(&(byColorBB[us]), rfrom);
1357 set_bit(&(byTypeBB[ROOK]), rfrom);
1358 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1361 board[rto] = board[kto] = EMPTY;
1362 board[rfrom] = rook_of_color(us);
1363 board[kfrom] = king_of_color(us);
1365 // Update king square
1366 kingSquare[us] = kfrom;
1368 // Update piece lists
1369 pieceList[us][KING][index[kto]] = kfrom;
1370 pieceList[us][ROOK][index[rto]] = rfrom;
1371 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1372 index[kfrom] = index[kto];
1377 /// Position::undo_promotion_move() is a private method used to unmake a
1378 /// promotion move. It is called from the main Position::do_move
1379 /// function. The UndoInfo object, which has been initialized in
1380 /// Position::do_move, is used to put back the captured piece (if any).
1382 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1386 PieceType capture, promotion;
1388 assert(move_is_ok(m));
1389 assert(move_promotion(m));
1391 // When we have arrived here, some work has already been done by
1392 // Position::undo_move. In particular, the side to move has been switched,
1393 // so the code below is correct.
1394 us = side_to_move();
1395 them = opposite_color(us);
1396 from = move_from(m);
1399 assert(relative_rank(us, to) == RANK_8);
1400 assert(piece_on(from) == EMPTY);
1402 // Remove promoted piece
1403 promotion = move_promotion(m);
1404 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1405 assert(promotion >= KNIGHT && promotion <= QUEEN);
1406 clear_bit(&(byColorBB[us]), to);
1407 clear_bit(&(byTypeBB[promotion]), to);
1408 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1410 // Insert pawn at source square
1411 set_bit(&(byColorBB[us]), from);
1412 set_bit(&(byTypeBB[PAWN]), from);
1413 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1414 board[from] = pawn_of_color(us);
1417 npMaterial[us] -= piece_value_midgame(promotion);
1419 // Update piece list
1420 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1421 index[from] = pieceCount[us][PAWN];
1422 pieceList[us][promotion][index[to]] =
1423 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1424 index[pieceList[us][promotion][index[to]]] = index[to];
1426 // Update piece counts
1427 pieceCount[us][promotion]--;
1428 pieceCount[us][PAWN]++;
1430 capture = u.capture;
1434 assert(capture != KING);
1436 // Insert captured piece:
1437 set_bit(&(byColorBB[them]), to);
1438 set_bit(&(byTypeBB[capture]), to);
1439 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1440 board[to] = piece_of_color_and_type(them, capture);
1442 // Update material. Because the move is a promotion move, we know
1443 // that the captured piece cannot be a pawn.
1444 assert(capture != PAWN);
1445 npMaterial[them] += piece_value_midgame(capture);
1447 // Update piece list
1448 pieceList[them][capture][pieceCount[them][capture]] = to;
1449 index[to] = pieceCount[them][capture];
1451 // Update piece count
1452 pieceCount[them][capture]++;
1458 /// Position::undo_ep_move() is a private method used to unmake an en passant
1459 /// capture. It is called from the main Position::undo_move function. Because
1460 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1461 /// object from which to retrieve the captured piece.
1463 void Position::undo_ep_move(Move m) {
1465 assert(move_is_ok(m));
1466 assert(move_is_ep(m));
1468 // When we have arrived here, some work has already been done by
1469 // Position::undo_move. In particular, the side to move has been switched,
1470 // so the code below is correct.
1471 Color us = side_to_move();
1472 Color them = opposite_color(us);
1473 Square from = move_from(m);
1474 Square to = move_to(m);
1475 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1477 assert(to == ep_square());
1478 assert(relative_rank(us, to) == RANK_6);
1479 assert(piece_on(to) == pawn_of_color(us));
1480 assert(piece_on(from) == EMPTY);
1481 assert(piece_on(capsq) == EMPTY);
1483 // Replace captured piece
1484 set_bit(&(byColorBB[them]), capsq);
1485 set_bit(&(byTypeBB[PAWN]), capsq);
1486 set_bit(&(byTypeBB[0]), capsq);
1487 board[capsq] = pawn_of_color(them);
1489 // Remove moving piece from destination square
1490 clear_bit(&(byColorBB[us]), to);
1491 clear_bit(&(byTypeBB[PAWN]), to);
1492 clear_bit(&(byTypeBB[0]), to);
1495 // Replace moving piece at source square
1496 set_bit(&(byColorBB[us]), from);
1497 set_bit(&(byTypeBB[PAWN]), from);
1498 set_bit(&(byTypeBB[0]), from);
1499 board[from] = pawn_of_color(us);
1501 // Update piece list:
1502 pieceList[us][PAWN][index[to]] = from;
1503 index[from] = index[to];
1504 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1505 index[capsq] = pieceCount[them][PAWN];
1507 // Update piece count:
1508 pieceCount[them][PAWN]++;
1512 /// Position::do_null_move makes() a "null move": It switches the side to move
1513 /// and updates the hash key without executing any move on the board.
1515 void Position::do_null_move(UndoInfo &u) {
1518 assert(!is_check());
1520 // Back up the information necessary to undo the null move to the supplied
1521 // UndoInfo object. In the case of a null move, the only thing we need to
1522 // remember is the last move made and the en passant square.
1523 u.lastMove = lastMove;
1524 u.epSquare = epSquare;
1526 // Save the current key to the history[] array, in order to be able to
1527 // detect repetition draws.
1528 history[gamePly] = key;
1530 // Update the necessary information
1531 sideToMove = opposite_color(sideToMove);
1532 if (epSquare != SQ_NONE)
1533 key ^= zobEp[epSquare];
1538 key ^= zobSideToMove;
1540 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1541 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1547 /// Position::undo_null_move() unmakes a "null move".
1549 void Position::undo_null_move(const UndoInfo &u) {
1552 assert(!is_check());
1554 // Restore information from the supplied UndoInfo object:
1555 lastMove = u.lastMove;
1556 epSquare = u.epSquare;
1557 if (epSquare != SQ_NONE)
1558 key ^= zobEp[epSquare];
1560 // Update the necessary information.
1561 sideToMove = opposite_color(sideToMove);
1564 key ^= zobSideToMove;
1566 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1567 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1573 /// Position::see() is a static exchange evaluator: It tries to estimate the
1574 /// material gain or loss resulting from a move. There are two versions of
1575 /// this function: One which takes a move as input, and one which takes a
1576 /// 'from' and a 'to' square. The function does not yet understand promotions
1577 /// or en passant captures.
1579 int Position::see(Move m) const {
1581 assert(move_is_ok(m));
1582 return see(move_from(m), move_to(m));
1585 int Position::see(Square from, Square to) const {
1587 // Approximate material values, with pawn = 1
1588 static const int seeValues[18] = {
1589 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1592 Bitboard attackers, occ, b;
1594 assert(square_is_ok(from));
1595 assert(square_is_ok(to));
1597 // Initialize colors
1598 Color us = color_of_piece_on(from);
1599 Color them = opposite_color(us);
1601 // Initialize pieces
1602 Piece piece = piece_on(from);
1603 Piece capture = piece_on(to);
1605 // Find all attackers to the destination square, with the moving piece
1606 // removed, but possibly an X-ray attacker added behind it.
1607 occ = occupied_squares();
1608 clear_bit(&occ, from);
1609 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1610 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1611 | (piece_attacks<KNIGHT>(to) & knights())
1612 | (piece_attacks<KING>(to) & kings())
1613 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1614 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1616 // If the opponent has no attackers, we are finished
1617 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1618 return seeValues[capture];
1620 attackers &= occ; // Remove the moving piece
1622 // The destination square is defended, which makes things rather more
1623 // difficult to compute. We proceed by building up a "swap list" containing
1624 // the material gain or loss at each stop in a sequence of captures to the
1625 // destination square, where the sides alternately capture, and always
1626 // capture with the least valuable piece. After each capture, we look for
1627 // new X-ray attacks from behind the capturing piece.
1628 int lastCapturingPieceValue = seeValues[piece];
1629 int swapList[32], n = 1;
1633 swapList[0] = seeValues[capture];
1636 // Locate the least valuable attacker for the side to move. The loop
1637 // below looks like it is potentially infinite, but it isn't. We know
1638 // that the side to move still has at least one attacker left.
1639 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1642 // Remove the attacker we just found from the 'attackers' bitboard,
1643 // and scan for new X-ray attacks behind the attacker.
1644 b = attackers & pieces_of_color_and_type(c, pt);
1646 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1647 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1651 // Add the new entry to the swap list
1653 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1656 // Remember the value of the capturing piece, and change the side to move
1657 // before beginning the next iteration
1658 lastCapturingPieceValue = seeValues[pt];
1659 c = opposite_color(c);
1661 // Stop after a king capture
1662 if (pt == KING && (attackers & pieces_of_color(c)))
1665 swapList[n++] = 100;
1668 } while (attackers & pieces_of_color(c));
1670 // Having built the swap list, we negamax through it to find the best
1671 // achievable score from the point of view of the side to move
1673 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1679 /// Position::clear() erases the position object to a pristine state, with an
1680 /// empty board, white to move, and no castling rights.
1682 void Position::clear() {
1684 for (int i = 0; i < 64; i++)
1690 for (int i = 0; i < 2; i++)
1691 byColorBB[i] = EmptyBoardBB;
1693 for (int i = 0; i < 7; i++)
1695 byTypeBB[i] = EmptyBoardBB;
1696 pieceCount[0][i] = pieceCount[1][i] = 0;
1697 for (int j = 0; j < 8; j++)
1698 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1701 checkersBB = EmptyBoardBB;
1703 lastMove = MOVE_NONE;
1706 castleRights = NO_CASTLES;
1707 initialKFile = FILE_E;
1708 initialKRFile = FILE_H;
1709 initialQRFile = FILE_A;
1716 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1717 /// UCI interface code, whenever a non-reversible move is made in a
1718 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1719 /// for the program to handle games of arbitrary length, as long as the GUI
1720 /// handles draws by the 50 move rule correctly.
1722 void Position::reset_game_ply() {
1728 /// Position::put_piece() puts a piece on the given square of the board,
1729 /// updating the board array, bitboards, and piece counts.
1731 void Position::put_piece(Piece p, Square s) {
1733 Color c = color_of_piece(p);
1734 PieceType pt = type_of_piece(p);
1737 index[s] = pieceCount[c][pt];
1738 pieceList[c][pt][index[s]] = s;
1740 set_bit(&(byTypeBB[pt]), s);
1741 set_bit(&(byColorBB[c]), s);
1742 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1744 pieceCount[c][pt]++;
1751 /// Position::allow_oo() gives the given side the right to castle kingside.
1752 /// Used when setting castling rights during parsing of FEN strings.
1754 void Position::allow_oo(Color c) {
1756 castleRights |= (1 + int(c));
1760 /// Position::allow_ooo() gives the given side the right to castle queenside.
1761 /// Used when setting castling rights during parsing of FEN strings.
1763 void Position::allow_ooo(Color c) {
1765 castleRights |= (4 + 4*int(c));
1769 /// Position::compute_key() computes the hash key of the position. The hash
1770 /// key is usually updated incrementally as moves are made and unmade, the
1771 /// compute_key() function is only used when a new position is set up, and
1772 /// to verify the correctness of the hash key when running in debug mode.
1774 Key Position::compute_key() const {
1776 Key result = Key(0ULL);
1778 for (Square s = SQ_A1; s <= SQ_H8; s++)
1779 if (square_is_occupied(s))
1780 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1782 if (ep_square() != SQ_NONE)
1783 result ^= zobEp[ep_square()];
1785 result ^= zobCastle[castleRights];
1786 if (side_to_move() == BLACK)
1787 result ^= zobSideToMove;
1793 /// Position::compute_pawn_key() computes the hash key of the position. The
1794 /// hash key is usually updated incrementally as moves are made and unmade,
1795 /// the compute_pawn_key() function is only used when a new position is set
1796 /// up, and to verify the correctness of the pawn hash key when running in
1799 Key Position::compute_pawn_key() const {
1801 Key result = Key(0ULL);
1805 for (Color c = WHITE; c <= BLACK; c++)
1810 s = pop_1st_bit(&b);
1811 result ^= zobrist[c][PAWN][s];
1818 /// Position::compute_material_key() computes the hash key of the position.
1819 /// The hash key is usually updated incrementally as moves are made and unmade,
1820 /// the compute_material_key() function is only used when a new position is set
1821 /// up, and to verify the correctness of the material hash key when running in
1824 Key Position::compute_material_key() const {
1826 Key result = Key(0ULL);
1827 for (Color c = WHITE; c <= BLACK; c++)
1828 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1830 int count = piece_count(c, pt);
1831 for (int i = 0; i <= count; i++)
1832 result ^= zobMaterial[c][pt][i];
1838 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1839 /// incremental scores for the middle game and the endgame. These functions
1840 /// are used to initialize the incremental scores when a new position is set
1841 /// up, and to verify that the scores are correctly updated by do_move
1842 /// and undo_move when the program is running in debug mode.
1844 Value Position::compute_mg_value() const {
1846 Value result = Value(0);
1850 for (Color c = WHITE; c <= BLACK; c++)
1851 for (PieceType pt = PAWN; pt <= KING; pt++)
1853 b = pieces_of_color_and_type(c, pt);
1856 s = pop_1st_bit(&b);
1857 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1858 result += mg_pst(c, pt, s);
1861 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1865 Value Position::compute_eg_value() const {
1867 Value result = Value(0);
1871 for (Color c = WHITE; c <= BLACK; c++)
1872 for (PieceType pt = PAWN; pt <= KING; pt++)
1874 b = pieces_of_color_and_type(c, pt);
1877 s = pop_1st_bit(&b);
1878 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1879 result += eg_pst(c, pt, s);
1882 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1887 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1888 /// game material score for the given side. Material scores are updated
1889 /// incrementally during the search, this function is only used while
1890 /// initializing a new Position object.
1892 Value Position::compute_non_pawn_material(Color c) const {
1894 Value result = Value(0);
1897 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1899 Bitboard b = pieces_of_color_and_type(c, pt);
1902 s = pop_1st_bit(&b);
1903 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1904 result += piece_value_midgame(pt);
1911 /// Position::is_mate() returns true or false depending on whether the
1912 /// side to move is checkmated. Note that this function is currently very
1913 /// slow, and shouldn't be used frequently inside the search.
1915 bool Position::is_mate() {
1919 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1920 return mp.get_next_move() == MOVE_NONE;
1926 /// Position::is_draw() tests whether the position is drawn by material,
1927 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1928 /// must be done by the search.
1930 bool Position::is_draw() const {
1932 // Draw by material?
1934 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1937 // Draw by the 50 moves rule?
1938 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1941 // Draw by repetition?
1942 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1943 if (history[gamePly - i] == key)
1950 /// Position::has_mate_threat() tests whether a given color has a mate in one
1951 /// from the current position. This function is quite slow, but it doesn't
1952 /// matter, because it is currently only called from PV nodes, which are rare.
1954 bool Position::has_mate_threat(Color c) {
1957 Color stm = side_to_move();
1959 // The following lines are useless and silly, but prevents gcc from
1960 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1961 // be used uninitialized.
1962 u1.lastMove = lastMove;
1963 u1.epSquare = epSquare;
1968 // If the input color is not equal to the side to move, do a null move
1972 MoveStack mlist[120];
1974 bool result = false;
1976 // Generate legal moves
1977 count = generate_legal_moves(*this, mlist);
1979 // Loop through the moves, and see if one of them is mate
1980 for (int i = 0; i < count; i++)
1982 do_move(mlist[i].move, u2);
1986 undo_move(mlist[i].move, u2);
1989 // Undo null move, if necessary
1997 /// Position::init_zobrist() is a static member function which initializes the
1998 /// various arrays used to compute hash keys.
2000 void Position::init_zobrist() {
2002 for (int i = 0; i < 2; i++)
2003 for (int j = 0; j < 8; j++)
2004 for (int k = 0; k < 64; k++)
2005 zobrist[i][j][k] = Key(genrand_int64());
2007 for (int i = 0; i < 64; i++)
2008 zobEp[i] = Key(genrand_int64());
2010 for (int i = 0; i < 16; i++)
2011 zobCastle[i] = genrand_int64();
2013 zobSideToMove = genrand_int64();
2015 for (int i = 0; i < 2; i++)
2016 for (int j = 0; j < 8; j++)
2017 for (int k = 0; k < 16; k++)
2018 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2020 for (int i = 0; i < 16; i++)
2021 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2025 /// Position::init_piece_square_tables() initializes the piece square tables.
2026 /// This is a two-step operation: First, the white halves of the tables are
2027 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2028 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2029 /// Second, the black halves of the tables are initialized by mirroring
2030 /// and changing the sign of the corresponding white scores.
2032 void Position::init_piece_square_tables() {
2034 int r = get_option_value_int("Randomness"), i;
2035 for (Square s = SQ_A1; s <= SQ_H8; s++)
2036 for (Piece p = WP; p <= WK; p++)
2038 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2039 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2040 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2043 for (Square s = SQ_A1; s <= SQ_H8; s++)
2044 for (Piece p = BP; p <= BK; p++)
2046 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2047 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2052 /// Position::flipped_copy() makes a copy of the input position, but with
2053 /// the white and black sides reversed. This is only useful for debugging,
2054 /// especially for finding evaluation symmetry bugs.
2056 void Position::flipped_copy(const Position &pos) {
2058 assert(pos.is_ok());
2063 for (Square s = SQ_A1; s <= SQ_H8; s++)
2064 if (!pos.square_is_empty(s))
2065 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2068 sideToMove = opposite_color(pos.side_to_move());
2071 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2072 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2073 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2074 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2076 initialKFile = pos.initialKFile;
2077 initialKRFile = pos.initialKRFile;
2078 initialQRFile = pos.initialQRFile;
2080 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2081 castleRightsMask[sq] = ALL_CASTLES;
2083 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2084 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2085 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2086 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2087 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2088 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2090 // En passant square
2091 if (pos.epSquare != SQ_NONE)
2092 epSquare = flip_square(pos.epSquare);
2098 key = compute_key();
2099 pawnKey = compute_pawn_key();
2100 materialKey = compute_material_key();
2102 // Incremental scores
2103 mgValue = compute_mg_value();
2104 egValue = compute_eg_value();
2107 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2108 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2114 /// Position::is_ok() performs some consitency checks for the position object.
2115 /// This is meant to be helpful when debugging.
2117 bool Position::is_ok(int* failedStep) const {
2119 // What features of the position should be verified?
2120 static const bool debugBitboards = false;
2121 static const bool debugKingCount = false;
2122 static const bool debugKingCapture = false;
2123 static const bool debugCheckerCount = false;
2124 static const bool debugKey = false;
2125 static const bool debugMaterialKey = false;
2126 static const bool debugPawnKey = false;
2127 static const bool debugIncrementalEval = false;
2128 static const bool debugNonPawnMaterial = false;
2129 static const bool debugPieceCounts = false;
2130 static const bool debugPieceList = false;
2132 if (failedStep) *failedStep = 1;
2135 if (!color_is_ok(side_to_move()))
2138 // Are the king squares in the position correct?
2139 if (failedStep) (*failedStep)++;
2140 if (piece_on(king_square(WHITE)) != WK)
2143 if (failedStep) (*failedStep)++;
2144 if (piece_on(king_square(BLACK)) != BK)
2148 if (failedStep) (*failedStep)++;
2149 if (!file_is_ok(initialKRFile))
2152 if (!file_is_ok(initialQRFile))
2155 // Do both sides have exactly one king?
2156 if (failedStep) (*failedStep)++;
2159 int kingCount[2] = {0, 0};
2160 for (Square s = SQ_A1; s <= SQ_H8; s++)
2161 if (type_of_piece_on(s) == KING)
2162 kingCount[color_of_piece_on(s)]++;
2164 if(kingCount[0] != 1 || kingCount[1] != 1)
2168 // Can the side to move capture the opponent's king?
2169 if (failedStep) (*failedStep)++;
2170 if (debugKingCapture)
2172 Color us = side_to_move();
2173 Color them = opposite_color(us);
2174 Square ksq = king_square(them);
2175 if (square_is_attacked(ksq, us))
2179 // Is there more than 2 checkers?
2180 if (failedStep) (*failedStep)++;
2181 if (debugCheckerCount && count_1s(checkersBB) > 2)
2185 if (failedStep) (*failedStep)++;
2188 // The intersection of the white and black pieces must be empty
2189 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2192 // The union of the white and black pieces must be equal to all
2194 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2197 // Separate piece type bitboards must have empty intersections
2198 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2199 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2200 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2204 // En passant square OK?
2205 if (failedStep) (*failedStep)++;
2206 if (ep_square() != SQ_NONE)
2208 // The en passant square must be on rank 6, from the point of view of the
2210 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2215 if (failedStep) (*failedStep)++;
2216 if (debugKey && key != compute_key())
2219 // Pawn hash key OK?
2220 if (failedStep) (*failedStep)++;
2221 if (debugPawnKey && pawnKey != compute_pawn_key())
2224 // Material hash key OK?
2225 if (failedStep) (*failedStep)++;
2226 if (debugMaterialKey && materialKey != compute_material_key())
2229 // Incremental eval OK?
2230 if (failedStep) (*failedStep)++;
2231 if (debugIncrementalEval)
2233 if (mgValue != compute_mg_value())
2236 if (egValue != compute_eg_value())
2240 // Non-pawn material OK?
2241 if (failedStep) (*failedStep)++;
2242 if (debugNonPawnMaterial)
2244 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2247 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2252 if (failedStep) (*failedStep)++;
2253 if (debugPieceCounts)
2254 for (Color c = WHITE; c <= BLACK; c++)
2255 for (PieceType pt = PAWN; pt <= KING; pt++)
2256 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2259 if (failedStep) (*failedStep)++;
2262 for(Color c = WHITE; c <= BLACK; c++)
2263 for(PieceType pt = PAWN; pt <= KING; pt++)
2264 for(int i = 0; i < pieceCount[c][pt]; i++)
2266 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2269 if (index[piece_list(c, pt, i)] != i)
2273 if (failedStep) *failedStep = 0;