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/>.
34 #include "ucioption.h"
41 int Position::castleRightsMask[64];
43 Key Position::zobrist[2][8][64];
44 Key Position::zobEp[64];
45 Key Position::zobCastle[16];
46 Key Position::zobMaterial[2][8][16];
47 Key Position::zobSideToMove;
49 Value Position::MgPieceSquareTable[16][64];
50 Value Position::EgPieceSquareTable[16][64];
59 Position::Position(const Position &pos) {
63 Position::Position(const std::string &fen) {
68 /// Position::from_fen() initializes the position object with the given FEN
69 /// string. This function is not very robust - make sure that input FENs are
70 /// correct (this is assumed to be the responsibility of the GUI).
72 void Position::from_fen(const std::string &fen) {
74 static const std::string pieceLetters = "KQRBNPkqrbnp";
75 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
83 for ( ; fen[i] != ' '; i++)
87 // Skip the given number of files
88 file += (fen[i] - '1' + 1);
91 else if (fen[i] == '/')
97 size_t idx = pieceLetters.find(fen[i]);
98 if (idx == std::string::npos)
100 std::cout << "Error in FEN at character " << i << std::endl;
103 Square square = make_square(file, rank);
104 put_piece(pieces[idx], square);
110 if (fen[i] != 'w' && fen[i] != 'b')
112 std::cout << "Error in FEN at character " << i << std::endl;
115 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
121 std::cout << "Error in FEN at character " << i << std::endl;
126 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
130 else if(fen[i] == 'K') allow_oo(WHITE);
131 else if(fen[i] == 'Q') allow_ooo(WHITE);
132 else if(fen[i] == 'k') allow_oo(BLACK);
133 else if(fen[i] == 'q') allow_ooo(BLACK);
134 else if(fen[i] >= 'A' && fen[i] <= 'H') {
135 File rookFile, kingFile = FILE_NONE;
136 for(Square square = SQ_B1; square <= SQ_G1; square++)
137 if(piece_on(square) == WK)
138 kingFile = square_file(square);
139 if(kingFile == FILE_NONE) {
140 std::cout << "Error in FEN at character " << i << std::endl;
143 initialKFile = kingFile;
144 rookFile = File(fen[i] - 'A') + FILE_A;
145 if(rookFile < initialKFile) {
147 initialQRFile = rookFile;
151 initialKRFile = rookFile;
154 else if(fen[i] >= 'a' && fen[i] <= 'h') {
155 File rookFile, kingFile = FILE_NONE;
156 for(Square square = SQ_B8; square <= SQ_G8; square++)
157 if(piece_on(square) == BK)
158 kingFile = square_file(square);
159 if(kingFile == FILE_NONE) {
160 std::cout << "Error in FEN at character " << i << std::endl;
163 initialKFile = kingFile;
164 rookFile = File(fen[i] - 'a') + FILE_A;
165 if(rookFile < initialKFile) {
167 initialQRFile = rookFile;
171 initialKRFile = rookFile;
175 std::cout << "Error in FEN at character " << i << std::endl;
182 while (fen[i] == ' ')
186 if ( i < fen.length() - 2
187 && (fen[i] >= 'a' && fen[i] <= 'h')
188 && (fen[i+1] == '3' || fen[i+1] == '6'))
189 epSquare = square_from_string(fen.substr(i, 2));
191 // Various initialisation
192 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
193 castleRightsMask[sq] = ALL_CASTLES;
195 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
196 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
197 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
198 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
199 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
200 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
205 pawnKey = compute_pawn_key();
206 materialKey = compute_material_key();
207 mgValue = compute_mg_value();
208 egValue = compute_eg_value();
209 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
210 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
214 /// Position::to_fen() converts the position object to a FEN string. This is
215 /// probably only useful for debugging.
217 const std::string Position::to_fen() const {
219 static const std::string pieceLetters = " PNBRQK pnbrqk";
223 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
226 for (File file = FILE_A; file <= FILE_H; file++)
228 Square sq = make_square(file, rank);
229 if (!square_is_occupied(sq))
235 fen += (char)skip + '0';
238 fen += pieceLetters[piece_on(sq)];
241 fen += (char)skip + '0';
243 fen += (rank > RANK_1 ? '/' : ' ');
245 fen += (sideToMove == WHITE ? 'w' : 'b') + ' ';
246 if (castleRights != NO_CASTLES)
248 if (can_castle_kingside(WHITE)) fen += 'K';
249 if (can_castle_queenside(WHITE)) fen += 'Q';
250 if (can_castle_kingside(BLACK)) fen += 'k';
251 if (can_castle_queenside(BLACK)) fen += 'q';
256 if (ep_square() != SQ_NONE)
257 fen += square_to_string(ep_square());
265 /// Position::print() prints an ASCII representation of the position to
266 /// the standard output.
268 void Position::print() const {
269 char pieceStrings[][8] =
270 {"| ? ", "| P ", "| N ", "| B ", "| R ", "| Q ", "| K ", "| ? ",
271 "| ? ", "|=P=", "|=N=", "|=B=", "|=R=", "|=Q=", "|=K="
274 for(Rank rank = RANK_8; rank >= RANK_1; rank--) {
275 std::cout << "+---+---+---+---+---+---+---+---+\n";
276 for(File file = FILE_A; file <= FILE_H; file++) {
277 Square sq = make_square(file, rank);
278 Piece piece = piece_on(sq);
280 std::cout << ((square_color(sq) == WHITE)? "| " : "| . ");
282 std::cout << pieceStrings[piece];
286 std::cout << "+---+---+---+---+---+---+---+---+\n";
287 std::cout << to_fen() << std::endl;
288 std::cout << key << std::endl;
292 /// Position::copy() creates a copy of the input position.
294 void Position::copy(const Position &pos) {
296 memcpy(this, &pos, sizeof(Position));
300 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
301 /// king) pieces for the given color.
302 Bitboard Position::pinned_pieces(Color c) const {
304 Square ksq = king_square(c);
305 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
309 /// Position:discovered_check_candidates() returns a bitboard containing all
310 /// pieces for the given side which are candidates for giving a discovered
311 /// check. The code is almost the same as the function for finding pinned
314 Bitboard Position::discovered_check_candidates(Color c) const {
316 Square ksq = king_square(opposite_color(c));
317 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
321 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
322 /// king) pieces for the given color and for the given pinner type. Or, when
323 /// template parameter FindPinned is false, the pinned pieces of opposite color
324 /// that are, indeed, the pieces candidate for a discovery check.
325 template<PieceType Piece, bool FindPinned>
326 Bitboard Position::hidden_checks(Color c, Square ksq) const {
329 Bitboard sliders, result = EmptyBoardBB;
331 if (Piece == ROOK) // Resolved at compile time
332 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
334 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
336 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
338 // King blockers are candidate pinned pieces
339 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
341 // Pinners are sliders, not checkers, that give check when
342 // candidate pinned are removed.
343 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
346 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
348 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
350 // Finally for each pinner find the corresponding pinned piece (if same color of king)
351 // or discovery checker (if opposite color) among the candidates.
354 s = pop_1st_bit(&pinners);
355 result |= (squares_between(s, ksq) & candidate_pinned);
362 /// Position::square_is_attacked() checks whether the given side attacks the
365 bool Position::square_is_attacked(Square s, Color c) const {
367 return (pawn_attacks(opposite_color(c), s) & pawns(c))
368 || (piece_attacks<KNIGHT>(s) & knights(c))
369 || (piece_attacks<KING>(s) & kings(c))
370 || (piece_attacks<ROOK>(s) & rooks_and_queens(c))
371 || (piece_attacks<BISHOP>(s) & bishops_and_queens(c));
375 /// Position::attacks_to() computes a bitboard containing all pieces which
376 /// attacks a given square. There are two versions of this function: One
377 /// which finds attackers of both colors, and one which only finds the
378 /// attackers for one side.
380 Bitboard Position::attacks_to(Square s) const {
382 return (pawn_attacks(BLACK, s) & pawns(WHITE))
383 | (pawn_attacks(WHITE, s) & pawns(BLACK))
384 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
385 | (piece_attacks<ROOK>(s) & rooks_and_queens())
386 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
387 | (piece_attacks<KING>(s) & pieces_of_type(KING));
390 Bitboard Position::attacks_to(Square s, Color c) const {
392 return attacks_to(s) & pieces_of_color(c);
396 /// Position::piece_attacks_square() tests whether the piece on square f
397 /// attacks square t.
399 bool Position::piece_attacks_square(Square f, Square t) const {
401 assert(square_is_ok(f));
402 assert(square_is_ok(t));
406 case WP: return pawn_attacks_square(WHITE, f, t);
407 case BP: return pawn_attacks_square(BLACK, f, t);
408 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
409 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
410 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
411 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
412 case WK: case BK: return piece_attacks_square<KING>(f, t);
413 default: return false;
419 /// Position::move_attacks_square() tests whether a move from the current
420 /// position attacks a given square. Only attacks by the moving piece are
421 /// considered; the function does not handle X-ray attacks.
423 bool Position::move_attacks_square(Move m, Square s) const {
425 assert(move_is_ok(m));
426 assert(square_is_ok(s));
428 Square f = move_from(m), t = move_to(m);
430 assert(square_is_occupied(f));
434 case WP: return pawn_attacks_square(WHITE, t, s);
435 case BP: return pawn_attacks_square(BLACK, t, s);
436 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
437 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
438 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
439 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
440 case WK: case BK: return piece_attacks_square<KING>(t, s);
441 default: assert(false);
447 /// Position::find_checkers() computes the checkersBB bitboard, which
448 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
449 /// currently works by calling Position::attacks_to, which is probably
450 /// inefficient. Consider rewriting this function to use the last move
451 /// played, like in non-bitboard versions of Glaurung.
453 void Position::find_checkers() {
455 checkersBB = attacks_to(king_square(side_to_move()),opposite_color(side_to_move()));
459 /// Position::move_is_legal() tests whether a pseudo-legal move is legal.
460 /// There are two versions of this function: One which takes only a
461 /// move as input, and one which takes a move and a bitboard of pinned
462 /// pieces. The latter function is faster, and should always be preferred
463 /// when a pinned piece bitboard has already been computed.
465 bool Position::move_is_legal(Move m) const {
467 return move_is_legal(m, pinned_pieces(side_to_move()));
470 bool Position::move_is_legal(Move m, Bitboard pinned) const {
476 assert(move_is_ok(m));
477 assert(pinned == pinned_pieces(side_to_move()));
479 // If we're in check, all pseudo-legal moves are legal, because our
480 // check evasion generator only generates true legal moves.
484 // Castling moves are checked for legality during move generation.
485 if (move_is_castle(m))
489 them = opposite_color(us);
491 ksq = king_square(us);
493 assert(color_of_piece_on(from) == us);
494 assert(piece_on(ksq) == king_of_color(us));
496 // En passant captures are a tricky special case. Because they are
497 // rather uncommon, we do it simply by testing whether the king is attacked
498 // after the move is made
501 Square to = move_to(m);
502 Square capsq = make_square(square_file(to), square_rank(from));
503 Bitboard b = occupied_squares();
505 assert(to == ep_square());
506 assert(piece_on(from) == pawn_of_color(us));
507 assert(piece_on(capsq) == pawn_of_color(them));
508 assert(piece_on(to) == EMPTY);
511 clear_bit(&b, capsq);
514 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
515 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
518 // If the moving piece is a king, check whether the destination
519 // square is attacked by the opponent.
521 return !(square_is_attacked(move_to(m), them));
523 // A non-king move is legal if and only if it is not pinned or it
524 // is moving along the ray towards or away from the king.
525 if ( !bit_is_set(pinned, from)
526 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)))
533 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
534 /// There are two versions of this function: One which takes only a move as
535 /// input, and one which takes a move and a bitboard of discovered check
536 /// candidates. The latter function is faster, and should always be preferred
537 /// when a discovered check candidates bitboard has already been computed.
539 bool Position::move_is_check(Move m) const {
541 Bitboard dc = discovered_check_candidates(side_to_move());
542 return move_is_check(m, dc);
545 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
548 Square ksq, from, to;
551 assert(move_is_ok(m));
552 assert(dcCandidates == discovered_check_candidates(side_to_move()));
555 them = opposite_color(us);
558 ksq = king_square(them);
560 assert(color_of_piece_on(from) == us);
561 assert(piece_on(ksq) == king_of_color(them));
563 // Proceed according to the type of the moving piece
564 switch (type_of_piece_on(from))
568 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
571 if ( bit_is_set(dcCandidates, from) // Discovered check?
572 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
575 if (move_promotion(m)) // Promotion with check?
577 Bitboard b = occupied_squares();
580 switch (move_promotion(m))
583 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
585 return bit_is_set(bishop_attacks_bb(to, b), ksq);
587 return bit_is_set(rook_attacks_bb(to, b), ksq);
589 return bit_is_set(queen_attacks_bb(to, b), ksq);
594 // En passant capture with check? We have already handled the case
595 // of direct checks and ordinary discovered check, the only case we
596 // need to handle is the unusual case of a discovered check through the
598 else if (move_is_ep(m))
600 Square capsq = make_square(square_file(to), square_rank(from));
601 Bitboard b = occupied_squares();
603 clear_bit(&b, capsq);
605 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
606 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
611 return bit_is_set(dcCandidates, from) // Discovered check?
612 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
615 return bit_is_set(dcCandidates, from) // Discovered check?
616 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
619 return bit_is_set(dcCandidates, from) // Discovered check?
620 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
623 // Discovered checks are impossible!
624 assert(!bit_is_set(dcCandidates, from));
625 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
629 if ( bit_is_set(dcCandidates, from)
630 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
633 // Castling with check?
634 if (move_is_castle(m))
636 Square kfrom, kto, rfrom, rto;
637 Bitboard b = occupied_squares();
643 kto = relative_square(us, SQ_G1);
644 rto = relative_square(us, SQ_F1);
646 kto = relative_square(us, SQ_C1);
647 rto = relative_square(us, SQ_D1);
649 clear_bit(&b, kfrom);
650 clear_bit(&b, rfrom);
653 return bit_is_set(rook_attacks_bb(rto, b), ksq);
665 /// Position::move_is_capture() tests whether a move from the current
666 /// position is a capture.
668 bool Position::move_is_capture(Move m) const {
670 return color_of_piece_on(move_to(m)) == opposite_color(side_to_move())
675 /// Position::backup() is called when making a move. All information
676 /// necessary to restore the position when the move is later unmade
677 /// is saved to an UndoInfo object. The function Position::restore
678 /// does the reverse operation: When one does a backup followed by
679 /// a restore with the same UndoInfo object, the position is restored
680 /// to the state before backup was called.
682 void Position::backup(UndoInfo& u) const {
684 u.castleRights = castleRights;
685 u.epSquare = epSquare;
686 u.checkersBB = checkersBB;
689 u.materialKey = materialKey;
691 u.lastMove = lastMove;
692 u.capture = NO_PIECE_TYPE;
698 /// Position::restore() is called when unmaking a move. It copies back
699 /// the information backed up during a previous call to Position::backup.
701 void Position::restore(const UndoInfo& u) {
703 castleRights = u.castleRights;
704 epSquare = u.epSquare;
705 checkersBB = u.checkersBB;
708 materialKey = u.materialKey;
710 lastMove = u.lastMove;
711 // u.capture is restored in undo_move()
717 /// Position::do_move() makes a move, and backs up all information necessary
718 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
719 /// Pseudo-legal moves should be filtered out before this function is called.
720 /// There are two versions of this function, one which takes only the move and
721 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
722 /// discovered check candidates. The second version is faster, because knowing
723 /// the discovered check candidates makes it easier to update the checkersBB
724 /// member variable in the position object.
726 void Position::do_move(Move m, UndoInfo& u) {
728 do_move(m, u, discovered_check_candidates(side_to_move()));
731 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
734 assert(move_is_ok(m));
736 // Back up the necessary information to our UndoInfo object (except the
737 // captured piece, which is taken care of later.
740 // Save the current key to the history[] array, in order to be able to
741 // detect repetition draws.
742 history[gamePly] = key;
744 // Increment the 50 moves rule draw counter. Resetting it to zero in the
745 // case of non-reversible moves is taken care of later.
748 if (move_is_castle(m))
750 else if (move_promotion(m))
751 do_promotion_move(m, u);
752 else if (move_is_ep(m))
756 Color us = side_to_move();
757 Color them = opposite_color(us);
758 Square from = move_from(m);
759 Square to = move_to(m);
761 assert(color_of_piece_on(from) == us);
762 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
764 PieceType piece = type_of_piece_on(from);
765 PieceType capture = type_of_piece_on(to);
769 assert(capture != KING);
771 // Remove captured piece
772 clear_bit(&(byColorBB[them]), to);
773 clear_bit(&(byTypeBB[capture]), to);
776 key ^= zobrist[them][capture][to];
778 // If the captured piece was a pawn, update pawn hash key
780 pawnKey ^= zobrist[them][PAWN][to];
782 // Update incremental scores
783 mgValue -= mg_pst(them, capture, to);
784 egValue -= eg_pst(them, capture, to);
788 npMaterial[them] -= piece_value_midgame(capture);
790 // Update material hash key
791 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
793 // Update piece count
794 pieceCount[them][capture]--;
797 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
798 index[pieceList[them][capture][index[to]]] = index[to];
800 // Remember the captured piece, in order to be able to undo the move correctly
803 // Reset rule 50 counter
808 clear_bit(&(byColorBB[us]), from);
809 clear_bit(&(byTypeBB[piece]), from);
810 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
811 set_bit(&(byColorBB[us]), to);
812 set_bit(&(byTypeBB[piece]), to);
813 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
814 board[to] = board[from];
818 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
820 // Update incremental scores
821 mgValue -= mg_pst(us, piece, from);
822 mgValue += mg_pst(us, piece, to);
823 egValue -= eg_pst(us, piece, from);
824 egValue += eg_pst(us, piece, to);
826 // If the moving piece was a king, update the king square
830 // If the move was a double pawn push, set the en passant square.
831 // This code is a bit ugly right now, and should be cleaned up later.
833 if (epSquare != SQ_NONE)
835 key ^= zobEp[epSquare];
840 if (abs(int(to) - int(from)) == 16)
843 && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
845 && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
847 epSquare = Square((int(from) + int(to)) / 2);
848 key ^= zobEp[epSquare];
851 // Reset rule 50 draw counter
854 // Update pawn hash key
855 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
857 // Update piece lists
858 pieceList[us][piece][index[from]] = to;
859 index[to] = index[from];
861 // Update castle rights
862 key ^= zobCastle[castleRights];
863 castleRights &= castleRightsMask[from];
864 castleRights &= castleRightsMask[to];
865 key ^= zobCastle[castleRights];
867 // Update checkers bitboard
868 checkersBB = EmptyBoardBB;
869 Square ksq = king_square(them);
873 if (bit_is_set(pawn_attacks(them, ksq), to))
874 set_bit(&checkersBB, to);
876 if (bit_is_set(dcCandidates, from))
877 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
878 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
882 if (bit_is_set(piece_attacks<KNIGHT>(ksq), to))
883 set_bit(&checkersBB, to);
885 if (bit_is_set(dcCandidates, from))
886 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
887 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
891 if (bit_is_set(piece_attacks<BISHOP>(ksq), to))
892 set_bit(&checkersBB, to);
894 if (bit_is_set(dcCandidates, from))
895 checkersBB |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(us));
899 if (bit_is_set(piece_attacks<ROOK>(ksq), to))
900 set_bit(&checkersBB, to);
902 if (bit_is_set(dcCandidates, from))
903 checkersBB |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us));
907 if (bit_is_set(piece_attacks<QUEEN>(ksq), to))
908 set_bit(&checkersBB, to);
912 if (bit_is_set(dcCandidates, from))
913 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
914 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
924 key ^= zobSideToMove;
925 sideToMove = opposite_color(sideToMove);
928 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
929 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
935 /// Position::do_castle_move() is a private method used to make a castling
936 /// move. It is called from the main Position::do_move function. Note that
937 /// castling moves are encoded as "king captures friendly rook" moves, for
938 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
940 void Position::do_castle_move(Move m) {
943 assert(move_is_ok(m));
944 assert(move_is_castle(m));
946 Color us = side_to_move();
947 Color them = opposite_color(us);
949 // Find source squares for king and rook
950 Square kfrom = move_from(m);
951 Square rfrom = move_to(m); // HACK: See comment at beginning of function
954 assert(piece_on(kfrom) == king_of_color(us));
955 assert(piece_on(rfrom) == rook_of_color(us));
957 // Find destination squares for king and rook
958 if (rfrom > kfrom) // O-O
960 kto = relative_square(us, SQ_G1);
961 rto = relative_square(us, SQ_F1);
963 kto = relative_square(us, SQ_C1);
964 rto = relative_square(us, SQ_D1);
967 // Remove pieces from source squares
968 clear_bit(&(byColorBB[us]), kfrom);
969 clear_bit(&(byTypeBB[KING]), kfrom);
970 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
971 clear_bit(&(byColorBB[us]), rfrom);
972 clear_bit(&(byTypeBB[ROOK]), rfrom);
973 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
975 // Put pieces on destination squares
976 set_bit(&(byColorBB[us]), kto);
977 set_bit(&(byTypeBB[KING]), kto);
978 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
979 set_bit(&(byColorBB[us]), rto);
980 set_bit(&(byTypeBB[ROOK]), rto);
981 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
983 // Update board array
984 board[kfrom] = board[rfrom] = EMPTY;
985 board[kto] = king_of_color(us);
986 board[rto] = rook_of_color(us);
988 // Update king square
989 kingSquare[us] = kto;
991 // Update piece lists
992 pieceList[us][KING][index[kfrom]] = kto;
993 pieceList[us][ROOK][index[rfrom]] = rto;
994 int tmp = index[rfrom];
995 index[kto] = index[kfrom];
998 // Update incremental scores
999 mgValue -= mg_pst(us, KING, kfrom);
1000 mgValue += mg_pst(us, KING, kto);
1001 egValue -= eg_pst(us, KING, kfrom);
1002 egValue += eg_pst(us, KING, kto);
1003 mgValue -= mg_pst(us, ROOK, rfrom);
1004 mgValue += mg_pst(us, ROOK, rto);
1005 egValue -= eg_pst(us, ROOK, rfrom);
1006 egValue += eg_pst(us, ROOK, rto);
1009 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1010 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1012 // Clear en passant square
1013 if(epSquare != SQ_NONE)
1015 key ^= zobEp[epSquare];
1019 // Update castling rights
1020 key ^= zobCastle[castleRights];
1021 castleRights &= castleRightsMask[kfrom];
1022 key ^= zobCastle[castleRights];
1024 // Reset rule 50 counter
1027 // Update checkers BB
1028 checkersBB = attacks_to(king_square(them), us);
1032 /// Position::do_promotion_move() is a private method used to make a promotion
1033 /// move. It is called from the main Position::do_move function. The
1034 /// UndoInfo object, which has been initialized in Position::do_move, is
1035 /// used to store the captured piece (if any).
1037 void Position::do_promotion_move(Move m, UndoInfo &u) {
1040 PieceType capture, promotion;
1043 assert(move_is_ok(m));
1044 assert(move_promotion(m));
1046 us = side_to_move();
1047 them = opposite_color(us);
1049 from = move_from(m);
1052 assert(relative_rank(us, to) == RANK_8);
1053 assert(piece_on(from) == pawn_of_color(us));
1054 assert(color_of_piece_on(to) == them || square_is_empty(to));
1056 capture = type_of_piece_on(to);
1059 assert(capture != KING);
1061 // Remove captured piece:
1062 clear_bit(&(byColorBB[them]), to);
1063 clear_bit(&(byTypeBB[capture]), to);
1066 key ^= zobrist[them][capture][to];
1068 // Update incremental scores:
1069 mgValue -= mg_pst(them, capture, to);
1070 egValue -= eg_pst(them, capture, to);
1072 // Update material. Because our move is a promotion, we know that the
1073 // captured piece is not a pawn.
1074 assert(capture != PAWN);
1075 npMaterial[them] -= piece_value_midgame(capture);
1077 // Update material hash key:
1078 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
1080 // Update piece count:
1081 pieceCount[them][capture]--;
1083 // Update piece list:
1084 pieceList[them][capture][index[to]] =
1085 pieceList[them][capture][pieceCount[them][capture]];
1086 index[pieceList[them][capture][index[to]]] = index[to];
1088 // Remember the captured piece, in order to be able to undo the move
1090 u.capture = capture;
1094 clear_bit(&(byColorBB[us]), from);
1095 clear_bit(&(byTypeBB[PAWN]), from);
1096 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1097 board[from] = EMPTY;
1099 // Insert promoted piece:
1100 promotion = move_promotion(m);
1101 assert(promotion >= KNIGHT && promotion <= QUEEN);
1102 set_bit(&(byColorBB[us]), to);
1103 set_bit(&(byTypeBB[promotion]), to);
1104 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1105 board[to] = piece_of_color_and_type(us, promotion);
1108 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1110 // Update pawn hash key:
1111 pawnKey ^= zobrist[us][PAWN][from];
1113 // Update material key:
1114 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1115 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1117 // Update piece counts:
1118 pieceCount[us][PAWN]--;
1119 pieceCount[us][promotion]++;
1121 // Update piece lists:
1122 pieceList[us][PAWN][index[from]] =
1123 pieceList[us][PAWN][pieceCount[us][PAWN]];
1124 index[pieceList[us][PAWN][index[from]]] = index[from];
1125 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1126 index[to] = pieceCount[us][promotion] - 1;
1128 // Update incremental scores:
1129 mgValue -= mg_pst(us, PAWN, from);
1130 mgValue += mg_pst(us, promotion, to);
1131 egValue -= eg_pst(us, PAWN, from);
1132 egValue += eg_pst(us, promotion, to);
1135 npMaterial[us] += piece_value_midgame(promotion);
1137 // Clear the en passant square:
1138 if(epSquare != SQ_NONE) {
1139 key ^= zobEp[epSquare];
1143 // Update castle rights:
1144 key ^= zobCastle[castleRights];
1145 castleRights &= castleRightsMask[to];
1146 key ^= zobCastle[castleRights];
1148 // Reset rule 50 counter:
1151 // Update checkers BB:
1152 checkersBB = attacks_to(king_square(them), us);
1156 /// Position::do_ep_move() is a private method used to make an en passant
1157 /// capture. It is called from the main Position::do_move function. Because
1158 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1159 /// object in which to store the captured piece.
1161 void Position::do_ep_move(Move m) {
1163 Square from, to, capsq;
1166 assert(move_is_ok(m));
1167 assert(move_is_ep(m));
1169 us = side_to_move();
1170 them = opposite_color(us);
1172 // Find from, to and capture squares:
1173 from = move_from(m);
1175 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1177 assert(to == epSquare);
1178 assert(relative_rank(us, to) == RANK_6);
1179 assert(piece_on(to) == EMPTY);
1180 assert(piece_on(from) == pawn_of_color(us));
1181 assert(piece_on(capsq) == pawn_of_color(them));
1183 // Remove captured piece:
1184 clear_bit(&(byColorBB[them]), capsq);
1185 clear_bit(&(byTypeBB[PAWN]), capsq);
1186 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1187 board[capsq] = EMPTY;
1189 // Remove moving piece from source square:
1190 clear_bit(&(byColorBB[us]), from);
1191 clear_bit(&(byTypeBB[PAWN]), from);
1192 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1194 // Put moving piece on destination square:
1195 set_bit(&(byColorBB[us]), to);
1196 set_bit(&(byTypeBB[PAWN]), to);
1197 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1198 board[to] = board[from];
1199 board[from] = EMPTY;
1201 // Update material hash key:
1202 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1204 // Update piece count:
1205 pieceCount[them][PAWN]--;
1207 // Update piece list:
1208 pieceList[us][PAWN][index[from]] = to;
1209 index[to] = index[from];
1210 pieceList[them][PAWN][index[capsq]] =
1211 pieceList[them][PAWN][pieceCount[them][PAWN]];
1212 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1215 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1216 key ^= zobrist[them][PAWN][capsq];
1217 key ^= zobEp[epSquare];
1219 // Update pawn hash key:
1220 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1221 pawnKey ^= zobrist[them][PAWN][capsq];
1223 // Update incremental scores:
1224 mgValue -= mg_pst(them, PAWN, capsq);
1225 mgValue -= mg_pst(us, PAWN, from);
1226 mgValue += mg_pst(us, PAWN, to);
1227 egValue -= eg_pst(them, PAWN, capsq);
1228 egValue -= eg_pst(us, PAWN, from);
1229 egValue += eg_pst(us, PAWN, to);
1231 // Reset en passant square:
1234 // Reset rule 50 counter:
1237 // Update checkers BB:
1238 checkersBB = attacks_to(king_square(them), us);
1242 /// Position::undo_move() unmakes a move. When it returns, the position should
1243 /// be restored to exactly the same state as before the move was made. It is
1244 /// important that Position::undo_move is called with the same move and UndoInfo
1245 /// object as the earlier call to Position::do_move.
1247 void Position::undo_move(Move m, const UndoInfo &u) {
1249 assert(move_is_ok(m));
1252 sideToMove = opposite_color(sideToMove);
1254 // Restore information from our UndoInfo object (except the captured piece,
1255 // which is taken care of later):
1258 if(move_is_castle(m))
1259 undo_castle_move(m);
1260 else if(move_promotion(m))
1261 undo_promotion_move(m, u);
1262 else if(move_is_ep(m))
1267 PieceType piece, capture;
1269 us = side_to_move();
1270 them = opposite_color(us);
1272 from = move_from(m);
1275 assert(piece_on(from) == EMPTY);
1276 assert(color_of_piece_on(to) == us);
1278 // Put the piece back at the source square:
1279 piece = type_of_piece_on(to);
1280 set_bit(&(byColorBB[us]), from);
1281 set_bit(&(byTypeBB[piece]), from);
1282 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1283 board[from] = piece_of_color_and_type(us, piece);
1285 // Clear the destination square
1286 clear_bit(&(byColorBB[us]), to);
1287 clear_bit(&(byTypeBB[piece]), to);
1288 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1290 // If the moving piece was a king, update the king square:
1292 kingSquare[us] = from;
1294 // Update piece list:
1295 pieceList[us][piece][index[to]] = from;
1296 index[from] = index[to];
1298 capture = u.capture;
1301 assert(capture != KING);
1302 // Replace the captured piece:
1303 set_bit(&(byColorBB[them]), to);
1304 set_bit(&(byTypeBB[capture]), to);
1305 set_bit(&(byTypeBB[0]), to);
1306 board[to] = piece_of_color_and_type(them, capture);
1310 npMaterial[them] += piece_value_midgame(capture);
1312 // Update piece list:
1313 pieceList[them][capture][pieceCount[them][capture]] = to;
1314 index[to] = pieceCount[them][capture];
1316 // Update piece count:
1317 pieceCount[them][capture]++;
1327 /// Position::undo_castle_move() is a private method used to unmake a castling
1328 /// move. It is called from the main Position::undo_move function. Note that
1329 /// castling moves are encoded as "king captures friendly rook" moves, for
1330 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1332 void Position::undo_castle_move(Move m) {
1334 Square kfrom, kto, rfrom, rto;
1336 assert(move_is_ok(m));
1337 assert(move_is_castle(m));
1339 // When we have arrived here, some work has already been done by
1340 // Position::undo_move. In particular, the side to move has been switched,
1341 // so the code below is correct.
1342 us = side_to_move();
1343 them = opposite_color(us);
1345 // Find source squares for king and rook:
1346 kfrom = move_from(m);
1347 rfrom = move_to(m); // HACK: See comment at beginning of function.
1349 // Find destination squares for king and rook:
1350 if(rfrom > kfrom) { // O-O
1351 kto = relative_square(us, SQ_G1);
1352 rto = relative_square(us, SQ_F1);
1355 kto = relative_square(us, SQ_C1);
1356 rto = relative_square(us, SQ_D1);
1359 assert(piece_on(kto) == king_of_color(us));
1360 assert(piece_on(rto) == rook_of_color(us));
1362 // Remove pieces from destination squares:
1363 clear_bit(&(byColorBB[us]), kto);
1364 clear_bit(&(byTypeBB[KING]), kto);
1365 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1366 clear_bit(&(byColorBB[us]), rto);
1367 clear_bit(&(byTypeBB[ROOK]), rto);
1368 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1370 // Put pieces on source squares:
1371 set_bit(&(byColorBB[us]), kfrom);
1372 set_bit(&(byTypeBB[KING]), kfrom);
1373 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1374 set_bit(&(byColorBB[us]), rfrom);
1375 set_bit(&(byTypeBB[ROOK]), rfrom);
1376 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1379 board[rto] = board[kto] = EMPTY;
1380 board[rfrom] = rook_of_color(us);
1381 board[kfrom] = king_of_color(us);
1383 // Update king square:
1384 kingSquare[us] = kfrom;
1386 // Update piece lists:
1387 pieceList[us][KING][index[kto]] = kfrom;
1388 pieceList[us][ROOK][index[rto]] = rfrom;
1389 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1390 index[kfrom] = index[kto];
1395 /// Position::undo_promotion_move() is a private method used to unmake a
1396 /// promotion move. It is called from the main Position::do_move
1397 /// function. The UndoInfo object, which has been initialized in
1398 /// Position::do_move, is used to put back the captured piece (if any).
1400 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1403 PieceType capture, promotion;
1405 assert(move_is_ok(m));
1406 assert(move_promotion(m));
1408 // When we have arrived here, some work has already been done by
1409 // Position::undo_move. In particular, the side to move has been switched,
1410 // so the code below is correct.
1411 us = side_to_move();
1412 them = opposite_color(us);
1414 from = move_from(m);
1417 assert(relative_rank(us, to) == RANK_8);
1418 assert(piece_on(from) == EMPTY);
1420 // Remove promoted piece:
1421 promotion = move_promotion(m);
1422 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1423 assert(promotion >= KNIGHT && promotion <= QUEEN);
1424 clear_bit(&(byColorBB[us]), to);
1425 clear_bit(&(byTypeBB[promotion]), to);
1426 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1428 // Insert pawn at source square:
1429 set_bit(&(byColorBB[us]), from);
1430 set_bit(&(byTypeBB[PAWN]), from);
1431 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1432 board[from] = pawn_of_color(us);
1435 npMaterial[us] -= piece_value_midgame(promotion);
1437 // Update piece list:
1438 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1439 index[from] = pieceCount[us][PAWN];
1440 pieceList[us][promotion][index[to]] =
1441 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1442 index[pieceList[us][promotion][index[to]]] = index[to];
1444 // Update piece counts:
1445 pieceCount[us][promotion]--;
1446 pieceCount[us][PAWN]++;
1448 capture = u.capture;
1450 assert(capture != KING);
1452 // Insert captured piece:
1453 set_bit(&(byColorBB[them]), to);
1454 set_bit(&(byTypeBB[capture]), to);
1455 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1456 board[to] = piece_of_color_and_type(them, capture);
1458 // Update material. Because the move is a promotion move, we know
1459 // that the captured piece cannot be a pawn.
1460 assert(capture != PAWN);
1461 npMaterial[them] += piece_value_midgame(capture);
1463 // Update piece list:
1464 pieceList[them][capture][pieceCount[them][capture]] = to;
1465 index[to] = pieceCount[them][capture];
1467 // Update piece count:
1468 pieceCount[them][capture]++;
1475 /// Position::undo_ep_move() is a private method used to unmake an en passant
1476 /// capture. It is called from the main Position::undo_move function. Because
1477 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1478 /// object from which to retrieve the captured piece.
1480 void Position::undo_ep_move(Move m) {
1482 Square from, to, capsq;
1484 assert(move_is_ok(m));
1485 assert(move_is_ep(m));
1487 // When we have arrived here, some work has already been done by
1488 // Position::undo_move. In particular, the side to move has been switched,
1489 // so the code below is correct.
1490 us = side_to_move();
1491 them = opposite_color(us);
1493 // Find from, to and captures squares:
1494 from = move_from(m);
1496 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1498 assert(to == ep_square());
1499 assert(relative_rank(us, to) == RANK_6);
1500 assert(piece_on(to) == pawn_of_color(us));
1501 assert(piece_on(from) == EMPTY);
1502 assert(piece_on(capsq) == EMPTY);
1504 // Replace captured piece:
1505 set_bit(&(byColorBB[them]), capsq);
1506 set_bit(&(byTypeBB[PAWN]), capsq);
1507 set_bit(&(byTypeBB[0]), capsq);
1508 board[capsq] = pawn_of_color(them);
1510 // Remove moving piece from destination square:
1511 clear_bit(&(byColorBB[us]), to);
1512 clear_bit(&(byTypeBB[PAWN]), to);
1513 clear_bit(&(byTypeBB[0]), to);
1516 // Replace moving piece at source square:
1517 set_bit(&(byColorBB[us]), from);
1518 set_bit(&(byTypeBB[PAWN]), from);
1519 set_bit(&(byTypeBB[0]), from);
1520 board[from] = pawn_of_color(us);
1522 // Update piece list:
1523 pieceList[us][PAWN][index[to]] = from;
1524 index[from] = index[to];
1525 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1526 index[capsq] = pieceCount[them][PAWN];
1528 // Update piece count:
1529 pieceCount[them][PAWN]++;
1533 /// Position::do_null_move makes() a "null move": It switches the side to move
1534 /// and updates the hash key without executing any move on the board.
1536 void Position::do_null_move(UndoInfo &u) {
1538 assert(!is_check());
1540 // Back up the information necessary to undo the null move to the supplied
1541 // UndoInfo object. In the case of a null move, the only thing we need to
1542 // remember is the last move made and the en passant square.
1543 u.lastMove = lastMove;
1544 u.epSquare = epSquare;
1546 // Save the current key to the history[] array, in order to be able to
1547 // detect repetition draws:
1548 history[gamePly] = key;
1550 // Update the necessary information.
1551 sideToMove = opposite_color(sideToMove);
1552 if(epSquare != SQ_NONE)
1553 key ^= zobEp[epSquare];
1557 key ^= zobSideToMove;
1559 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1560 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1566 /// Position::undo_null_move() unmakes a "null move".
1568 void Position::undo_null_move(const UndoInfo &u) {
1570 assert(!is_check());
1572 // Restore information from the supplied UndoInfo object:
1573 lastMove = u.lastMove;
1574 epSquare = u.epSquare;
1575 if(epSquare != SQ_NONE)
1576 key ^= zobEp[epSquare];
1578 // Update the necessary information.
1579 sideToMove = opposite_color(sideToMove);
1582 key ^= zobSideToMove;
1584 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1585 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1591 /// Position::see() is a static exchange evaluator: It tries to estimate the
1592 /// material gain or loss resulting from a move. There are two versions of
1593 /// this function: One which takes a move as input, and one which takes a
1594 /// 'from' and a 'to' square. The function does not yet understand promotions
1595 /// or en passant captures.
1597 int Position::see(Square from, Square to) const {
1598 // Approximate material values, with pawn = 1:
1599 static const int seeValues[18] = {
1600 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1603 Piece piece, capture;
1604 Bitboard attackers, occ, b;
1606 assert(square_is_ok(from));
1607 assert(square_is_ok(to));
1609 // Initialize colors:
1610 us = color_of_piece_on(from);
1611 them = opposite_color(us);
1613 // Initialize pieces:
1614 piece = piece_on(from);
1615 capture = piece_on(to);
1617 // Find all attackers to the destination square, with the moving piece
1618 // removed, but possibly an X-ray attacker added behind it:
1619 occ = occupied_squares();
1620 clear_bit(&occ, from);
1622 (rook_attacks_bb(to, occ) & rooks_and_queens()) |
1623 (bishop_attacks_bb(to, occ) & bishops_and_queens()) |
1624 (piece_attacks<KNIGHT>(to) & knights()) |
1625 (piece_attacks<KING>(to) & kings()) |
1626 (pawn_attacks(WHITE, to) & pawns(BLACK)) |
1627 (pawn_attacks(BLACK, to) & pawns(WHITE));
1630 // If the opponent has no attackers, we are finished:
1631 if((attackers & pieces_of_color(them)) == EmptyBoardBB)
1632 return seeValues[capture];
1634 // The destination square is defended, which makes things rather more
1635 // difficult to compute. We proceed by building up a "swap list" containing
1636 // the material gain or loss at each stop in a sequence of captures to the
1637 // destianation square, where the sides alternately capture, and always
1638 // capture with the least valuable piece. After each capture, we look for
1639 // new X-ray attacks from behind the capturing piece.
1640 int lastCapturingPieceValue = seeValues[piece];
1641 int swapList[32], n = 1;
1645 swapList[0] = seeValues[capture];
1648 // Locate the least valuable attacker for the side to move. The loop
1649 // below looks like it is potentially infinite, but it isn't. We know
1650 // that the side to move still has at least one attacker left.
1651 for(pt = PAWN; !(attackers&pieces_of_color_and_type(c, pt)); pt++)
1654 // Remove the attacker we just found from the 'attackers' bitboard,
1655 // and scan for new X-ray attacks behind the attacker:
1656 b = attackers & pieces_of_color_and_type(c, pt);
1659 (rook_attacks_bb(to, occ) & rooks_and_queens()) |
1660 (bishop_attacks_bb(to, occ) & bishops_and_queens());
1663 // Add the new entry to the swap list:
1665 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1668 // Remember the value of the capturing piece, and change the side to move
1669 // before beginning the next iteration:
1670 lastCapturingPieceValue = seeValues[pt];
1671 c = opposite_color(c);
1673 // Stop after a king capture:
1674 if(pt == KING && (attackers & pieces_of_color(c))) {
1676 swapList[n++] = 100;
1679 } while(attackers & pieces_of_color(c));
1681 // Having built the swap list, we negamax through it to find the best
1682 // achievable score from the point of view of the side to move:
1683 while(--n) swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1689 int Position::see(Move m) const {
1690 assert(move_is_ok(m));
1691 return see(move_from(m), move_to(m));
1695 /// Position::clear() erases the position object to a pristine state, with an
1696 /// empty board, white to move, and no castling rights.
1698 void Position::clear() {
1701 for(i = 0; i < 64; i++) {
1706 for(i = 0; i < 2; i++)
1707 byColorBB[i] = EmptyBoardBB;
1709 for(i = 0; i < 7; i++) {
1710 byTypeBB[i] = EmptyBoardBB;
1711 pieceCount[0][i] = pieceCount[1][i] = 0;
1712 for(j = 0; j < 8; j++)
1713 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1716 checkersBB = EmptyBoardBB;
1718 lastMove = MOVE_NONE;
1721 castleRights = NO_CASTLES;
1722 initialKFile = FILE_E;
1723 initialKRFile = FILE_H;
1724 initialQRFile = FILE_A;
1731 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1732 /// UCI interface code, whenever a non-reversible move is made in a
1733 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1734 /// for the program to handle games of arbitrary length, as long as the GUI
1735 /// handles draws by the 50 move rule correctly.
1737 void Position::reset_game_ply() {
1742 /// Position::put_piece() puts a piece on the given square of the board,
1743 /// updating the board array, bitboards, and piece counts.
1745 void Position::put_piece(Piece p, Square s) {
1746 Color c = color_of_piece(p);
1747 PieceType pt = type_of_piece(p);
1750 index[s] = pieceCount[c][pt];
1751 pieceList[c][pt][index[s]] = s;
1753 set_bit(&(byTypeBB[pt]), s);
1754 set_bit(&(byColorBB[c]), s);
1755 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1757 pieceCount[c][pt]++;
1764 /// Position::allow_oo() gives the given side the right to castle kingside.
1765 /// Used when setting castling rights during parsing of FEN strings.
1767 void Position::allow_oo(Color c) {
1768 castleRights |= (1 + int(c));
1772 /// Position::allow_ooo() gives the given side the right to castle queenside.
1773 /// Used when setting castling rights during parsing of FEN strings.
1775 void Position::allow_ooo(Color c) {
1776 castleRights |= (4 + 4*int(c));
1780 /// Position::compute_key() computes the hash key of the position. The hash
1781 /// key is usually updated incrementally as moves are made and unmade, the
1782 /// compute_key() function is only used when a new position is set up, and
1783 /// to verify the correctness of the hash key when running in debug mode.
1785 Key Position::compute_key() const {
1786 Key result = Key(0ULL);
1788 for(Square s = SQ_A1; s <= SQ_H8; s++)
1789 if(square_is_occupied(s))
1791 zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1793 if(ep_square() != SQ_NONE)
1794 result ^= zobEp[ep_square()];
1795 result ^= zobCastle[castleRights];
1796 if(side_to_move() == BLACK) result ^= zobSideToMove;
1802 /// Position::compute_pawn_key() computes the hash key of the position. The
1803 /// hash key is usually updated incrementally as moves are made and unmade,
1804 /// the compute_pawn_key() function is only used when a new position is set
1805 /// up, and to verify the correctness of the pawn hash key when running in
1808 Key Position::compute_pawn_key() const {
1809 Key result = Key(0ULL);
1813 for(Color c = WHITE; c <= BLACK; c++) {
1816 s = pop_1st_bit(&b);
1817 result ^= zobrist[c][PAWN][s];
1824 /// Position::compute_material_key() computes the hash key of the position.
1825 /// The hash key is usually updated incrementally as moves are made and unmade,
1826 /// the compute_material_key() function is only used when a new position is set
1827 /// up, and to verify the correctness of the material hash key when running in
1830 Key Position::compute_material_key() const {
1831 Key result = Key(0ULL);
1832 for(Color c = WHITE; c <= BLACK; c++)
1833 for(PieceType pt = PAWN; pt <= QUEEN; pt++) {
1834 int count = piece_count(c, pt);
1835 for(int i = 0; i <= count; i++)
1836 result ^= zobMaterial[c][pt][i];
1842 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1843 /// incremental scores for the middle game and the endgame. These functions
1844 /// are used to initialize the incremental scores when a new position is set
1845 /// up, and to verify that the scores are correctly updated by do_move
1846 /// and undo_move when the program is running in debug mode.
1848 Value Position::compute_mg_value() const {
1849 Value result = Value(0);
1853 for(Color c = WHITE; c <= BLACK; c++)
1854 for(PieceType pt = PAWN; pt <= KING; pt++) {
1855 b = pieces_of_color_and_type(c, pt);
1857 s = pop_1st_bit(&b);
1858 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1859 result += mg_pst(c, pt, s);
1862 result += (side_to_move() == WHITE)?
1863 (TempoValueMidgame / 2) : -(TempoValueMidgame / 2);
1867 Value Position::compute_eg_value() const {
1868 Value result = Value(0);
1872 for(Color c = WHITE; c <= BLACK; c++)
1873 for(PieceType pt = PAWN; pt <= KING; pt++) {
1874 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)?
1882 (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 {
1893 Value result = Value(0);
1896 for(PieceType pt = KNIGHT; pt <= QUEEN; pt++) {
1897 Bitboard b = pieces_of_color_and_type(c, pt);
1899 s = pop_1st_bit(&b);
1900 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1901 result += piece_value_midgame(pt);
1908 /// Position::is_mate() returns true or false depending on whether the
1909 /// side to move is checkmated. Note that this function is currently very
1910 /// slow, and shouldn't be used frequently inside the search.
1912 bool Position::is_mate() {
1914 MovePicker mp = MovePicker(*this, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1915 MOVE_NONE, Depth(0));
1916 return mp.get_next_move() == MOVE_NONE;
1923 /// Position::is_draw() tests whether the position is drawn by material,
1924 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1925 /// must be done by the search.
1927 bool Position::is_draw() const {
1928 // Draw by material?
1930 non_pawn_material(WHITE) + non_pawn_material(BLACK)
1931 <= BishopValueMidgame)
1934 // Draw by the 50 moves rule?
1935 if(rule50 > 100 || (rule50 == 100 && !is_check()))
1938 // Draw by repetition?
1939 for(int i = 2; i < Min(gamePly, rule50); i += 2)
1940 if(history[gamePly - i] == key)
1947 /// Position::has_mate_threat() tests whether a given color has a mate in one
1948 /// from the current position. This function is quite slow, but it doesn't
1949 /// matter, because it is currently only called from PV nodes, which are rare.
1951 bool Position::has_mate_threat(Color c) {
1953 Color stm = side_to_move();
1955 // The following lines are useless and silly, but prevents gcc from
1956 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1957 // be used uninitialized.
1958 u1.lastMove = lastMove;
1959 u1.epSquare = epSquare;
1964 // If the input color is not equal to the side to move, do a null move
1965 if(c != stm) do_null_move(u1);
1967 MoveStack mlist[120];
1969 bool result = false;
1971 // Generate legal moves
1972 count = generate_legal_moves(*this, mlist);
1974 // Loop through the moves, and see if one of them is mate.
1975 for(int i = 0; i < count; i++) {
1976 do_move(mlist[i].move, u2);
1977 if(is_mate()) result = true;
1978 undo_move(mlist[i].move, u2);
1981 // Undo null move, if necessary
1982 if(c != stm) undo_null_move(u1);
1988 /// Position::init_zobrist() is a static member function which initializes the
1989 /// various arrays used to compute hash keys.
1991 void Position::init_zobrist() {
1993 for(int i = 0; i < 2; i++)
1994 for(int j = 0; j < 8; j++)
1995 for(int k = 0; k < 64; k++)
1996 zobrist[i][j][k] = Key(genrand_int64());
1998 for(int i = 0; i < 64; i++)
1999 zobEp[i] = Key(genrand_int64());
2001 for(int i = 0; i < 16; i++)
2002 zobCastle[i] = genrand_int64();
2004 zobSideToMove = genrand_int64();
2006 for(int i = 0; i < 2; i++)
2007 for(int j = 0; j < 8; j++)
2008 for(int k = 0; k < 16; k++)
2009 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2011 for(int i = 0; i < 16; i++)
2012 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2016 /// Position::init_piece_square_tables() initializes the piece square tables.
2017 /// This is a two-step operation: First, the white halves of the tables are
2018 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2019 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2020 /// Second, the black halves of the tables are initialized by mirroring
2021 /// and changing the sign of the corresponding white scores.
2023 void Position::init_piece_square_tables() {
2024 int r = get_option_value_int("Randomness"), i;
2025 for(Square s = SQ_A1; s <= SQ_H8; s++) {
2026 for(Piece p = WP; p <= WK; p++) {
2027 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2028 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2029 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2032 for(Square s = SQ_A1; s <= SQ_H8; s++)
2033 for(Piece p = BP; p <= BK; p++) {
2034 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2035 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2040 /// Position::flipped_copy() makes a copy of the input position, but with
2041 /// the white and black sides reversed. This is only useful for debugging,
2042 /// especially for finding evaluation symmetry bugs.
2044 void Position::flipped_copy(const Position &pos) {
2045 assert(pos.is_ok());
2050 for(Square s = SQ_A1; s <= SQ_H8; s++)
2051 if(!pos.square_is_empty(s))
2052 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2055 sideToMove = opposite_color(pos.side_to_move());
2058 if(pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2059 if(pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2060 if(pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2061 if(pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2063 initialKFile = pos.initialKFile;
2064 initialKRFile = pos.initialKRFile;
2065 initialQRFile = pos.initialQRFile;
2067 for(Square sq = SQ_A1; sq <= SQ_H8; sq++)
2068 castleRightsMask[sq] = ALL_CASTLES;
2069 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
2070 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
2071 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2072 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2073 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2074 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2076 // En passant square
2077 if(pos.epSquare != SQ_NONE)
2078 epSquare = flip_square(pos.epSquare);
2084 key = compute_key();
2085 pawnKey = compute_pawn_key();
2086 materialKey = compute_material_key();
2088 // Incremental scores
2089 mgValue = compute_mg_value();
2090 egValue = compute_eg_value();
2093 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2094 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2100 /// Position::is_ok() performs some consitency checks for the position object.
2101 /// This is meant to be helpful when debugging.
2103 bool Position::is_ok(int* failedStep) const {
2105 // What features of the position should be verified?
2106 static const bool debugBitboards = false;
2107 static const bool debugKingCount = false;
2108 static const bool debugKingCapture = false;
2109 static const bool debugCheckerCount = false;
2110 static const bool debugKey = false;
2111 static const bool debugMaterialKey = false;
2112 static const bool debugPawnKey = false;
2113 static const bool debugIncrementalEval = false;
2114 static const bool debugNonPawnMaterial = false;
2115 static const bool debugPieceCounts = false;
2116 static const bool debugPieceList = false;
2118 if (failedStep) *failedStep = 1;
2121 if(!color_is_ok(side_to_move()))
2124 // Are the king squares in the position correct?
2125 if (failedStep) (*failedStep)++;
2126 if(piece_on(king_square(WHITE)) != WK)
2129 if (failedStep) (*failedStep)++;
2130 if(piece_on(king_square(BLACK)) != BK)
2134 if (failedStep) (*failedStep)++;
2135 if(!file_is_ok(initialKRFile))
2137 if(!file_is_ok(initialQRFile))
2140 // Do both sides have exactly one king?
2141 if (failedStep) (*failedStep)++;
2142 if(debugKingCount) {
2143 int kingCount[2] = {0, 0};
2144 for(Square s = SQ_A1; s <= SQ_H8; s++)
2145 if(type_of_piece_on(s) == KING)
2146 kingCount[color_of_piece_on(s)]++;
2147 if(kingCount[0] != 1 || kingCount[1] != 1)
2151 // Can the side to move capture the opponent's king?
2152 if (failedStep) (*failedStep)++;
2153 if(debugKingCapture) {
2154 Color us = side_to_move();
2155 Color them = opposite_color(us);
2156 Square ksq = king_square(them);
2157 if(square_is_attacked(ksq, us))
2161 // Is there more than 2 checkers?
2162 if (failedStep) (*failedStep)++;
2163 if(debugCheckerCount && count_1s(checkersBB) > 2)
2167 if (failedStep) (*failedStep)++;
2168 if(debugBitboards) {
2169 // The intersection of the white and black pieces must be empty:
2170 if((pieces_of_color(WHITE) & pieces_of_color(BLACK))
2174 // The union of the white and black pieces must be equal to all
2175 // occupied squares:
2176 if((pieces_of_color(WHITE) | pieces_of_color(BLACK))
2177 != occupied_squares())
2180 // Separate piece type bitboards must have empty intersections:
2181 for(PieceType p1 = PAWN; p1 <= KING; p1++)
2182 for(PieceType p2 = PAWN; p2 <= KING; p2++)
2183 if(p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2187 // En passant square OK?
2188 if (failedStep) (*failedStep)++;
2189 if(ep_square() != SQ_NONE) {
2190 // The en passant square must be on rank 6, from the point of view of the
2192 if(relative_rank(side_to_move(), ep_square()) != RANK_6)
2197 if (failedStep) (*failedStep)++;
2198 if(debugKey && key != compute_key())
2201 // Pawn hash key OK?
2202 if (failedStep) (*failedStep)++;
2203 if(debugPawnKey && pawnKey != compute_pawn_key())
2206 // Material hash key OK?
2207 if (failedStep) (*failedStep)++;
2208 if(debugMaterialKey && materialKey != compute_material_key())
2211 // Incremental eval OK?
2212 if (failedStep) (*failedStep)++;
2213 if(debugIncrementalEval) {
2214 if(mgValue != compute_mg_value())
2216 if(egValue != compute_eg_value())
2220 // Non-pawn material OK?
2221 if (failedStep) (*failedStep)++;
2222 if(debugNonPawnMaterial) {
2223 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2225 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2230 if (failedStep) (*failedStep)++;
2231 if(debugPieceCounts)
2232 for(Color c = WHITE; c <= BLACK; c++)
2233 for(PieceType pt = PAWN; pt <= KING; pt++)
2234 if(pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2237 if (failedStep) (*failedStep)++;
2238 if(debugPieceList) {
2239 for(Color c = WHITE; c <= BLACK; c++)
2240 for(PieceType pt = PAWN; pt <= KING; pt++)
2241 for(int i = 0; i < pieceCount[c][pt]; i++) {
2242 if(piece_on(piece_list(c, pt, i)) !=
2243 piece_of_color_and_type(c, pt))
2245 if(index[piece_list(c, pt, i)] != i)
2249 if (failedStep) *failedStep = 0;