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 int Position::castleRightsMask[64];
44 Key Position::zobrist[2][8][64];
45 Key Position::zobEp[64];
46 Key Position::zobCastle[16];
47 Key Position::zobMaterial[2][8][16];
48 Key Position::zobSideToMove;
50 Value Position::MgPieceSquareTable[16][64];
51 Value Position::EgPieceSquareTable[16][64];
60 Position::Position(const Position &pos) {
64 Position::Position(const std::string &fen) {
69 /// Position::from_fen() initializes the position object with the given FEN
70 /// string. This function is not very robust - make sure that input FENs are
71 /// correct (this is assumed to be the responsibility of the GUI).
73 void Position::from_fen(const std::string &fen) {
75 static const std::string pieceLetters = "KQRBNPkqrbnp";
76 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
84 for ( ; fen[i] != ' '; i++)
88 // Skip the given number of files
89 file += (fen[i] - '1' + 1);
92 else if (fen[i] == '/')
98 size_t idx = pieceLetters.find(fen[i]);
99 if (idx == std::string::npos)
101 std::cout << "Error in FEN at character " << i << std::endl;
104 Square square = make_square(file, rank);
105 put_piece(pieces[idx], square);
111 if (fen[i] != 'w' && fen[i] != 'b')
113 std::cout << "Error in FEN at character " << i << std::endl;
116 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
122 std::cout << "Error in FEN at character " << i << std::endl;
127 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
131 else if(fen[i] == 'K') allow_oo(WHITE);
132 else if(fen[i] == 'Q') allow_ooo(WHITE);
133 else if(fen[i] == 'k') allow_oo(BLACK);
134 else if(fen[i] == 'q') allow_ooo(BLACK);
135 else if(fen[i] >= 'A' && fen[i] <= 'H') {
136 File rookFile, kingFile = FILE_NONE;
137 for(Square square = SQ_B1; square <= SQ_G1; square++)
138 if(piece_on(square) == WK)
139 kingFile = square_file(square);
140 if(kingFile == FILE_NONE) {
141 std::cout << "Error in FEN at character " << i << std::endl;
144 initialKFile = kingFile;
145 rookFile = File(fen[i] - 'A') + FILE_A;
146 if(rookFile < initialKFile) {
148 initialQRFile = rookFile;
152 initialKRFile = rookFile;
155 else if(fen[i] >= 'a' && fen[i] <= 'h') {
156 File rookFile, kingFile = FILE_NONE;
157 for(Square square = SQ_B8; square <= SQ_G8; square++)
158 if(piece_on(square) == BK)
159 kingFile = square_file(square);
160 if(kingFile == FILE_NONE) {
161 std::cout << "Error in FEN at character " << i << std::endl;
164 initialKFile = kingFile;
165 rookFile = File(fen[i] - 'a') + FILE_A;
166 if(rookFile < initialKFile) {
168 initialQRFile = rookFile;
172 initialKRFile = rookFile;
176 std::cout << "Error in FEN at character " << i << std::endl;
183 while (fen[i] == ' ')
187 if ( i < fen.length() - 2
188 && (fen[i] >= 'a' && fen[i] <= 'h')
189 && (fen[i+1] == '3' || fen[i+1] == '6'))
190 epSquare = square_from_string(fen.substr(i, 2));
192 // Various initialisation
193 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
194 castleRightsMask[sq] = ALL_CASTLES;
196 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
197 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
198 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
199 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
200 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
201 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
206 pawnKey = compute_pawn_key();
207 materialKey = compute_material_key();
208 mgValue = compute_mg_value();
209 egValue = compute_eg_value();
210 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
211 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
215 /// Position::to_fen() converts the position object to a FEN string. This is
216 /// probably only useful for debugging.
218 const std::string Position::to_fen() const {
220 static const std::string pieceLetters = " PNBRQK pnbrqk";
224 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
227 for (File file = FILE_A; file <= FILE_H; file++)
229 Square sq = make_square(file, rank);
230 if (!square_is_occupied(sq))
236 fen += (char)skip + '0';
239 fen += pieceLetters[piece_on(sq)];
242 fen += (char)skip + '0';
244 fen += (rank > RANK_1 ? '/' : ' ');
246 fen += (sideToMove == WHITE ? 'w' : 'b') + ' ';
247 if (castleRights != NO_CASTLES)
249 if (can_castle_kingside(WHITE)) fen += 'K';
250 if (can_castle_queenside(WHITE)) fen += 'Q';
251 if (can_castle_kingside(BLACK)) fen += 'k';
252 if (can_castle_queenside(BLACK)) fen += 'q';
257 if (ep_square() != SQ_NONE)
258 fen += square_to_string(ep_square());
266 /// Position::print() prints an ASCII representation of the position to
267 /// the standard output. If a move is given then also the san is print.
269 void Position::print(Move m) const {
271 static const std::string pieceLetters = " PNBRQK PNBRQK .";
273 std::cout << std::endl;
277 std::cout << "Move is: " << move_to_san(p, m) << std::endl;
279 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
281 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
282 for (File file = FILE_A; file <= FILE_H; file++)
284 Square sq = make_square(file, rank);
285 Piece piece = piece_on(sq);
286 if (piece == EMPTY && square_color(sq) == WHITE)
289 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
290 std::cout << '|' << col << pieceLetters[piece] << col;
292 std::cout << '|' << std::endl;
294 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
295 std::cout << "Fen is: " << to_fen() << std::endl;
296 std::cout << key << std::endl;
300 /// Position::copy() creates a copy of the input position.
302 void Position::copy(const Position &pos) {
304 memcpy(this, &pos, sizeof(Position));
308 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
309 /// king) pieces for the given color.
310 Bitboard Position::pinned_pieces(Color c) const {
312 Square ksq = king_square(c);
313 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
317 /// Position:discovered_check_candidates() returns a bitboard containing all
318 /// pieces for the given side which are candidates for giving a discovered
319 /// check. The code is almost the same as the function for finding pinned
322 Bitboard Position::discovered_check_candidates(Color c) const {
324 Square ksq = king_square(opposite_color(c));
325 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
329 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
330 /// king) pieces for the given color and for the given pinner type. Or, when
331 /// template parameter FindPinned is false, the pinned pieces of opposite color
332 /// that are, indeed, the pieces candidate for a discovery check.
333 template<PieceType Piece, bool FindPinned>
334 Bitboard Position::hidden_checks(Color c, Square ksq) const {
337 Bitboard sliders, result = EmptyBoardBB;
339 if (Piece == ROOK) // Resolved at compile time
340 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
342 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
344 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
346 // King blockers are candidate pinned pieces
347 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
349 // Pinners are sliders, not checkers, that give check when
350 // candidate pinned are removed.
351 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
354 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
356 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
358 // Finally for each pinner find the corresponding pinned piece (if same color of king)
359 // or discovery checker (if opposite color) among the candidates.
362 s = pop_1st_bit(&pinners);
363 result |= (squares_between(s, ksq) & candidate_pinned);
370 /// Position::square_is_attacked() checks whether the given side attacks the
373 bool Position::square_is_attacked(Square s, Color c) const {
375 return (pawn_attacks(opposite_color(c), s) & pawns(c))
376 || (piece_attacks<KNIGHT>(s) & knights(c))
377 || (piece_attacks<KING>(s) & kings(c))
378 || (piece_attacks<ROOK>(s) & rooks_and_queens(c))
379 || (piece_attacks<BISHOP>(s) & bishops_and_queens(c));
383 /// Position::attacks_to() computes a bitboard containing all pieces which
384 /// attacks a given square. There are two versions of this function: One
385 /// which finds attackers of both colors, and one which only finds the
386 /// attackers for one side.
388 Bitboard Position::attacks_to(Square s) const {
390 return (pawn_attacks(BLACK, s) & pawns(WHITE))
391 | (pawn_attacks(WHITE, s) & pawns(BLACK))
392 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
393 | (piece_attacks<ROOK>(s) & rooks_and_queens())
394 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
395 | (piece_attacks<KING>(s) & pieces_of_type(KING));
398 Bitboard Position::attacks_to(Square s, Color c) const {
400 return attacks_to(s) & pieces_of_color(c);
404 /// Position::piece_attacks_square() tests whether the piece on square f
405 /// attacks square t.
407 bool Position::piece_attacks_square(Square f, Square t) const {
409 assert(square_is_ok(f));
410 assert(square_is_ok(t));
414 case WP: return pawn_attacks_square(WHITE, f, t);
415 case BP: return pawn_attacks_square(BLACK, f, t);
416 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
417 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
418 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
419 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
420 case WK: case BK: return piece_attacks_square<KING>(f, t);
427 /// Position::move_attacks_square() tests whether a move from the current
428 /// position attacks a given square. Only attacks by the moving piece are
429 /// considered; the function does not handle X-ray attacks.
431 bool Position::move_attacks_square(Move m, Square s) const {
433 assert(move_is_ok(m));
434 assert(square_is_ok(s));
436 Square f = move_from(m), t = move_to(m);
438 assert(square_is_occupied(f));
442 case WP: return pawn_attacks_square(WHITE, t, s);
443 case BP: return pawn_attacks_square(BLACK, t, s);
444 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
445 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
446 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
447 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
448 case WK: case BK: return piece_attacks_square<KING>(t, s);
455 /// Position::find_checkers() computes the checkersBB bitboard, which
456 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
457 /// currently works by calling Position::attacks_to, which is probably
458 /// inefficient. Consider rewriting this function to use the last move
459 /// played, like in non-bitboard versions of Glaurung.
461 void Position::find_checkers() {
463 Color us = side_to_move();
464 checkersBB = attacks_to(king_square(us), opposite_color(us));
468 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
469 /// There are two versions of this function: One which takes only a
470 /// move as input, and one which takes a move and a bitboard of pinned
471 /// pieces. The latter function is faster, and should always be preferred
472 /// when a pinned piece bitboard has already been computed.
474 bool Position::pl_move_is_legal(Move m) const {
476 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
479 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
482 assert(move_is_ok(m));
483 assert(pinned == pinned_pieces(side_to_move()));
485 // If we're in check, all pseudo-legal moves are legal, because our
486 // check evasion generator only generates true legal moves.
490 // Castling moves are checked for legality during move generation.
491 if (move_is_castle(m))
494 Color us = side_to_move();
495 Color them = opposite_color(us);
496 Square from = move_from(m);
497 Square ksq = king_square(us);
499 assert(color_of_piece_on(from) == us);
500 assert(piece_on(ksq) == king_of_color(us));
502 // En passant captures are a tricky special case. Because they are
503 // rather uncommon, we do it simply by testing whether the king is attacked
504 // after the move is made
507 Square to = move_to(m);
508 Square capsq = make_square(square_file(to), square_rank(from));
509 Bitboard b = occupied_squares();
511 assert(to == ep_square());
512 assert(piece_on(from) == pawn_of_color(us));
513 assert(piece_on(capsq) == pawn_of_color(them));
514 assert(piece_on(to) == EMPTY);
517 clear_bit(&b, capsq);
520 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
521 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
524 // If the moving piece is a king, check whether the destination
525 // square is attacked by the opponent.
527 return !(square_is_attacked(move_to(m), them));
529 // A non-king move is legal if and only if it is not pinned or it
530 // is moving along the ray towards or away from the king.
531 return ( !bit_is_set(pinned, from)
532 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
536 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
537 /// There are two versions of this function: One which takes only a move as
538 /// input, and one which takes a move and a bitboard of discovered check
539 /// candidates. The latter function is faster, and should always be preferred
540 /// when a discovered check candidates bitboard has already been computed.
542 bool Position::move_is_check(Move m) const {
544 Bitboard dc = discovered_check_candidates(side_to_move());
545 return move_is_check(m, dc);
548 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
551 assert(move_is_ok(m));
552 assert(dcCandidates == discovered_check_candidates(side_to_move()));
554 Color us = side_to_move();
555 Color them = opposite_color(us);
556 Square from = move_from(m);
557 Square to = move_to(m);
558 Square 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);
657 default: // NO_PIECE_TYPE
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 ( !square_is_empty(move_to(m))
671 && (color_of_piece_on(move_to(m)) == opposite_color(side_to_move()))
677 /// Position::backup() is called when making a move. All information
678 /// necessary to restore the position when the move is later unmade
679 /// is saved to an UndoInfo object. The function Position::restore
680 /// does the reverse operation: When one does a backup followed by
681 /// a restore with the same UndoInfo object, the position is restored
682 /// to the state before backup was called.
684 void Position::backup(UndoInfo& u) const {
686 u.castleRights = castleRights;
687 u.epSquare = epSquare;
688 u.checkersBB = checkersBB;
691 u.materialKey = materialKey;
693 u.lastMove = lastMove;
696 u.capture = NO_PIECE_TYPE;
700 /// Position::restore() is called when unmaking a move. It copies back
701 /// the information backed up during a previous call to Position::backup.
703 void Position::restore(const UndoInfo& u) {
705 castleRights = u.castleRights;
706 epSquare = u.epSquare;
707 checkersBB = u.checkersBB;
710 materialKey = u.materialKey;
712 lastMove = u.lastMove;
715 // u.capture is restored in undo_move()
718 /// Position::do_move() makes a move, and backs up all information necessary
719 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
720 /// Pseudo-legal moves should be filtered out before this function is called.
721 /// There are two versions of this function, one which takes only the move and
722 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
723 /// discovered check candidates. The second version is faster, because knowing
724 /// the discovered check candidates makes it easier to update the checkersBB
725 /// member variable in the position object.
727 void Position::do_move(Move m, UndoInfo& u) {
729 do_move(m, u, discovered_check_candidates(side_to_move()));
732 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
735 assert(move_is_ok(m));
737 // Back up the necessary information to our UndoInfo object (except the
738 // captured piece, which is taken care of later.
741 // Save the current key to the history[] array, in order to be able to
742 // detect repetition draws.
743 history[gamePly] = key;
745 // Increment the 50 moves rule draw counter. Resetting it to zero in the
746 // case of non-reversible moves is taken care of later.
749 if (move_is_castle(m))
751 else if (move_promotion(m))
752 do_promotion_move(m, u);
753 else if (move_is_ep(m))
757 Color us = side_to_move();
758 Color them = opposite_color(us);
759 Square from = move_from(m);
760 Square to = move_to(m);
762 assert(color_of_piece_on(from) == us);
763 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
765 PieceType piece = type_of_piece_on(from);
766 PieceType capture = type_of_piece_on(to);
771 do_capture_move(m, capture, them, to);
775 clear_bit(&(byColorBB[us]), from);
776 clear_bit(&(byTypeBB[piece]), from);
777 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
778 set_bit(&(byColorBB[us]), to);
779 set_bit(&(byTypeBB[piece]), to);
780 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
781 board[to] = board[from];
785 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
787 // Update incremental scores
788 mgValue -= mg_pst(us, piece, from);
789 mgValue += mg_pst(us, piece, to);
790 egValue -= eg_pst(us, piece, from);
791 egValue += eg_pst(us, piece, to);
793 // If the moving piece was a king, update the king square
797 // If the move was a double pawn push, set the en passant square.
798 // This code is a bit ugly right now, and should be cleaned up later.
800 if (epSquare != SQ_NONE)
802 key ^= zobEp[epSquare];
807 if (abs(int(to) - int(from)) == 16)
810 && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
812 && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
814 epSquare = Square((int(from) + int(to)) / 2);
815 key ^= zobEp[epSquare];
818 // Reset rule 50 draw counter
821 // Update pawn hash key
822 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
824 // Update piece lists
825 pieceList[us][piece][index[from]] = to;
826 index[to] = index[from];
828 // Update castle rights
829 key ^= zobCastle[castleRights];
830 castleRights &= castleRightsMask[from];
831 castleRights &= castleRightsMask[to];
832 key ^= zobCastle[castleRights];
834 // Update checkers bitboard
835 checkersBB = EmptyBoardBB;
836 Square ksq = king_square(them);
840 if (bit_is_set(pawn_attacks(them, ksq), to))
841 set_bit(&checkersBB, to);
843 if (bit_is_set(dcCandidates, from))
844 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
845 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
849 if (bit_is_set(piece_attacks<KNIGHT>(ksq), to))
850 set_bit(&checkersBB, to);
852 if (bit_is_set(dcCandidates, from))
853 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
854 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
858 if (bit_is_set(piece_attacks<BISHOP>(ksq), to))
859 set_bit(&checkersBB, to);
861 if (bit_is_set(dcCandidates, from))
862 checkersBB |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(us));
866 if (bit_is_set(piece_attacks<ROOK>(ksq), to))
867 set_bit(&checkersBB, to);
869 if (bit_is_set(dcCandidates, from))
870 checkersBB |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us));
874 if (bit_is_set(piece_attacks<QUEEN>(ksq), to))
875 set_bit(&checkersBB, to);
879 if (bit_is_set(dcCandidates, from))
880 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
881 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
891 key ^= zobSideToMove;
892 sideToMove = opposite_color(sideToMove);
895 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
896 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
902 /// Position::do_capture_move() is a private method used to update captured
903 /// piece info. It is called from the main Position::do_move function.
905 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
907 assert(capture != KING);
909 // Remove captured piece
910 clear_bit(&(byColorBB[them]), to);
911 clear_bit(&(byTypeBB[capture]), to);
914 key ^= zobrist[them][capture][to];
916 // If the captured piece was a pawn, update pawn hash key
918 pawnKey ^= zobrist[them][PAWN][to];
920 // Update incremental scores
921 mgValue -= mg_pst(them, capture, to);
922 egValue -= eg_pst(them, capture, to);
924 assert(!move_promotion(m) || capture != PAWN);
928 npMaterial[them] -= piece_value_midgame(capture);
930 // Update material hash key
931 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
933 // Update piece count
934 pieceCount[them][capture]--;
937 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
938 index[pieceList[them][capture][index[to]]] = index[to];
940 // Reset rule 50 counter
945 /// Position::do_castle_move() is a private method used to make a castling
946 /// move. It is called from the main Position::do_move function. Note that
947 /// castling moves are encoded as "king captures friendly rook" moves, for
948 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
950 void Position::do_castle_move(Move m) {
953 assert(move_is_ok(m));
954 assert(move_is_castle(m));
956 Color us = side_to_move();
957 Color them = opposite_color(us);
959 // Find source squares for king and rook
960 Square kfrom = move_from(m);
961 Square rfrom = move_to(m); // HACK: See comment at beginning of function
964 assert(piece_on(kfrom) == king_of_color(us));
965 assert(piece_on(rfrom) == rook_of_color(us));
967 // Find destination squares for king and rook
968 if (rfrom > kfrom) // O-O
970 kto = relative_square(us, SQ_G1);
971 rto = relative_square(us, SQ_F1);
973 kto = relative_square(us, SQ_C1);
974 rto = relative_square(us, SQ_D1);
977 // Remove pieces from source squares
978 clear_bit(&(byColorBB[us]), kfrom);
979 clear_bit(&(byTypeBB[KING]), kfrom);
980 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
981 clear_bit(&(byColorBB[us]), rfrom);
982 clear_bit(&(byTypeBB[ROOK]), rfrom);
983 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
985 // Put pieces on destination squares
986 set_bit(&(byColorBB[us]), kto);
987 set_bit(&(byTypeBB[KING]), kto);
988 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
989 set_bit(&(byColorBB[us]), rto);
990 set_bit(&(byTypeBB[ROOK]), rto);
991 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
993 // Update board array
994 board[kfrom] = board[rfrom] = EMPTY;
995 board[kto] = king_of_color(us);
996 board[rto] = rook_of_color(us);
998 // Update king square
999 kingSquare[us] = kto;
1001 // Update piece lists
1002 pieceList[us][KING][index[kfrom]] = kto;
1003 pieceList[us][ROOK][index[rfrom]] = rto;
1004 int tmp = index[rfrom];
1005 index[kto] = index[kfrom];
1008 // Update incremental scores
1009 mgValue -= mg_pst(us, KING, kfrom);
1010 mgValue += mg_pst(us, KING, kto);
1011 egValue -= eg_pst(us, KING, kfrom);
1012 egValue += eg_pst(us, KING, kto);
1013 mgValue -= mg_pst(us, ROOK, rfrom);
1014 mgValue += mg_pst(us, ROOK, rto);
1015 egValue -= eg_pst(us, ROOK, rfrom);
1016 egValue += eg_pst(us, ROOK, rto);
1019 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1020 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1022 // Clear en passant square
1023 if(epSquare != SQ_NONE)
1025 key ^= zobEp[epSquare];
1029 // Update castling rights
1030 key ^= zobCastle[castleRights];
1031 castleRights &= castleRightsMask[kfrom];
1032 key ^= zobCastle[castleRights];
1034 // Reset rule 50 counter
1037 // Update checkers BB
1038 checkersBB = attacks_to(king_square(them), us);
1042 /// Position::do_promotion_move() is a private method used to make a promotion
1043 /// move. It is called from the main Position::do_move function. The
1044 /// UndoInfo object, which has been initialized in Position::do_move, is
1045 /// used to store the captured piece (if any).
1047 void Position::do_promotion_move(Move m, UndoInfo &u) {
1051 PieceType capture, promotion;
1054 assert(move_is_ok(m));
1055 assert(move_promotion(m));
1057 us = side_to_move();
1058 them = opposite_color(us);
1059 from = move_from(m);
1062 assert(relative_rank(us, to) == RANK_8);
1063 assert(piece_on(from) == pawn_of_color(us));
1064 assert(color_of_piece_on(to) == them || square_is_empty(to));
1066 capture = type_of_piece_on(to);
1070 u.capture = capture;
1071 do_capture_move(m, capture, them, to);
1075 clear_bit(&(byColorBB[us]), from);
1076 clear_bit(&(byTypeBB[PAWN]), from);
1077 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1078 board[from] = EMPTY;
1080 // Insert promoted piece
1081 promotion = move_promotion(m);
1082 assert(promotion >= KNIGHT && promotion <= QUEEN);
1083 set_bit(&(byColorBB[us]), to);
1084 set_bit(&(byTypeBB[promotion]), to);
1085 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1086 board[to] = piece_of_color_and_type(us, promotion);
1089 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1091 // Update pawn hash key
1092 pawnKey ^= zobrist[us][PAWN][from];
1094 // Update material key
1095 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1096 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1098 // Update piece counts
1099 pieceCount[us][PAWN]--;
1100 pieceCount[us][promotion]++;
1102 // Update piece lists
1103 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1104 index[pieceList[us][PAWN][index[from]]] = index[from];
1105 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1106 index[to] = pieceCount[us][promotion] - 1;
1108 // Update incremental scores
1109 mgValue -= mg_pst(us, PAWN, from);
1110 mgValue += mg_pst(us, promotion, to);
1111 egValue -= eg_pst(us, PAWN, from);
1112 egValue += eg_pst(us, promotion, to);
1115 npMaterial[us] += piece_value_midgame(promotion);
1117 // Clear the en passant square
1118 if (epSquare != SQ_NONE)
1120 key ^= zobEp[epSquare];
1124 // Update castle rights
1125 key ^= zobCastle[castleRights];
1126 castleRights &= castleRightsMask[to];
1127 key ^= zobCastle[castleRights];
1129 // Reset rule 50 counter
1132 // Update checkers BB
1133 checkersBB = attacks_to(king_square(them), us);
1137 /// Position::do_ep_move() is a private method used to make an en passant
1138 /// capture. It is called from the main Position::do_move function. Because
1139 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1140 /// object in which to store the captured piece.
1142 void Position::do_ep_move(Move m) {
1145 Square from, to, capsq;
1148 assert(move_is_ok(m));
1149 assert(move_is_ep(m));
1151 us = side_to_move();
1152 them = opposite_color(us);
1153 from = move_from(m);
1155 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1157 assert(to == epSquare);
1158 assert(relative_rank(us, to) == RANK_6);
1159 assert(piece_on(to) == EMPTY);
1160 assert(piece_on(from) == pawn_of_color(us));
1161 assert(piece_on(capsq) == pawn_of_color(them));
1163 // Remove captured piece
1164 clear_bit(&(byColorBB[them]), capsq);
1165 clear_bit(&(byTypeBB[PAWN]), capsq);
1166 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1167 board[capsq] = EMPTY;
1169 // Remove moving piece from source square
1170 clear_bit(&(byColorBB[us]), from);
1171 clear_bit(&(byTypeBB[PAWN]), from);
1172 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1174 // Put moving piece on destination square
1175 set_bit(&(byColorBB[us]), to);
1176 set_bit(&(byTypeBB[PAWN]), to);
1177 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1178 board[to] = board[from];
1179 board[from] = EMPTY;
1181 // Update material hash key
1182 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1184 // Update piece count
1185 pieceCount[them][PAWN]--;
1187 // Update piece list
1188 pieceList[us][PAWN][index[from]] = to;
1189 index[to] = index[from];
1190 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1191 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1194 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1195 key ^= zobrist[them][PAWN][capsq];
1196 key ^= zobEp[epSquare];
1198 // Update pawn hash key
1199 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1200 pawnKey ^= zobrist[them][PAWN][capsq];
1202 // Update incremental scores
1203 mgValue -= mg_pst(them, PAWN, capsq);
1204 mgValue -= mg_pst(us, PAWN, from);
1205 mgValue += mg_pst(us, PAWN, to);
1206 egValue -= eg_pst(them, PAWN, capsq);
1207 egValue -= eg_pst(us, PAWN, from);
1208 egValue += eg_pst(us, PAWN, to);
1210 // Reset en passant square
1213 // Reset rule 50 counter
1216 // Update checkers BB
1217 checkersBB = attacks_to(king_square(them), us);
1221 /// Position::undo_move() unmakes a move. When it returns, the position should
1222 /// be restored to exactly the same state as before the move was made. It is
1223 /// important that Position::undo_move is called with the same move and UndoInfo
1224 /// object as the earlier call to Position::do_move.
1226 void Position::undo_move(Move m, const UndoInfo &u) {
1229 assert(move_is_ok(m));
1232 sideToMove = opposite_color(sideToMove);
1234 // Restore information from our UndoInfo object (except the captured piece,
1235 // which is taken care of later)
1238 if (move_is_castle(m))
1239 undo_castle_move(m);
1240 else if (move_promotion(m))
1241 undo_promotion_move(m, u);
1242 else if (move_is_ep(m))
1248 PieceType piece, capture;
1250 us = side_to_move();
1251 them = opposite_color(us);
1252 from = move_from(m);
1255 assert(piece_on(from) == EMPTY);
1256 assert(color_of_piece_on(to) == us);
1258 // Put the piece back at the source square
1259 piece = type_of_piece_on(to);
1260 set_bit(&(byColorBB[us]), from);
1261 set_bit(&(byTypeBB[piece]), from);
1262 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1263 board[from] = piece_of_color_and_type(us, piece);
1265 // Clear the destination square
1266 clear_bit(&(byColorBB[us]), to);
1267 clear_bit(&(byTypeBB[piece]), to);
1268 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1270 // If the moving piece was a king, update the king square
1272 kingSquare[us] = from;
1274 // Update piece list
1275 pieceList[us][piece][index[to]] = from;
1276 index[from] = index[to];
1278 capture = u.capture;
1282 assert(capture != KING);
1284 // Replace the captured piece
1285 set_bit(&(byColorBB[them]), to);
1286 set_bit(&(byTypeBB[capture]), to);
1287 set_bit(&(byTypeBB[0]), to);
1288 board[to] = piece_of_color_and_type(them, capture);
1291 if (capture != PAWN)
1292 npMaterial[them] += piece_value_midgame(capture);
1294 // Update piece list
1295 pieceList[them][capture][pieceCount[them][capture]] = to;
1296 index[to] = pieceCount[them][capture];
1298 // Update piece count
1299 pieceCount[them][capture]++;
1308 /// Position::undo_castle_move() is a private method used to unmake a castling
1309 /// move. It is called from the main Position::undo_move function. Note that
1310 /// castling moves are encoded as "king captures friendly rook" moves, for
1311 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1313 void Position::undo_castle_move(Move m) {
1315 assert(move_is_ok(m));
1316 assert(move_is_castle(m));
1318 // When we have arrived here, some work has already been done by
1319 // Position::undo_move. In particular, the side to move has been switched,
1320 // so the code below is correct.
1321 Color us = side_to_move();
1323 // Find source squares for king and rook
1324 Square kfrom = move_from(m);
1325 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1328 // Find destination squares for king and rook
1329 if (rfrom > kfrom) // O-O
1331 kto = relative_square(us, SQ_G1);
1332 rto = relative_square(us, SQ_F1);
1334 kto = relative_square(us, SQ_C1);
1335 rto = relative_square(us, SQ_D1);
1338 assert(piece_on(kto) == king_of_color(us));
1339 assert(piece_on(rto) == rook_of_color(us));
1341 // Remove pieces from destination squares
1342 clear_bit(&(byColorBB[us]), kto);
1343 clear_bit(&(byTypeBB[KING]), kto);
1344 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1345 clear_bit(&(byColorBB[us]), rto);
1346 clear_bit(&(byTypeBB[ROOK]), rto);
1347 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1349 // Put pieces on source squares
1350 set_bit(&(byColorBB[us]), kfrom);
1351 set_bit(&(byTypeBB[KING]), kfrom);
1352 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1353 set_bit(&(byColorBB[us]), rfrom);
1354 set_bit(&(byTypeBB[ROOK]), rfrom);
1355 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1358 board[rto] = board[kto] = EMPTY;
1359 board[rfrom] = rook_of_color(us);
1360 board[kfrom] = king_of_color(us);
1362 // Update king square
1363 kingSquare[us] = kfrom;
1365 // Update piece lists
1366 pieceList[us][KING][index[kto]] = kfrom;
1367 pieceList[us][ROOK][index[rto]] = rfrom;
1368 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1369 index[kfrom] = index[kto];
1374 /// Position::undo_promotion_move() is a private method used to unmake a
1375 /// promotion move. It is called from the main Position::do_move
1376 /// function. The UndoInfo object, which has been initialized in
1377 /// Position::do_move, is used to put back the captured piece (if any).
1379 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1383 PieceType capture, promotion;
1385 assert(move_is_ok(m));
1386 assert(move_promotion(m));
1388 // When we have arrived here, some work has already been done by
1389 // Position::undo_move. In particular, the side to move has been switched,
1390 // so the code below is correct.
1391 us = side_to_move();
1392 them = opposite_color(us);
1393 from = move_from(m);
1396 assert(relative_rank(us, to) == RANK_8);
1397 assert(piece_on(from) == EMPTY);
1399 // Remove promoted piece
1400 promotion = move_promotion(m);
1401 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1402 assert(promotion >= KNIGHT && promotion <= QUEEN);
1403 clear_bit(&(byColorBB[us]), to);
1404 clear_bit(&(byTypeBB[promotion]), to);
1405 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1407 // Insert pawn at source square
1408 set_bit(&(byColorBB[us]), from);
1409 set_bit(&(byTypeBB[PAWN]), from);
1410 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1411 board[from] = pawn_of_color(us);
1414 npMaterial[us] -= piece_value_midgame(promotion);
1416 // Update piece list
1417 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1418 index[from] = pieceCount[us][PAWN];
1419 pieceList[us][promotion][index[to]] =
1420 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1421 index[pieceList[us][promotion][index[to]]] = index[to];
1423 // Update piece counts
1424 pieceCount[us][promotion]--;
1425 pieceCount[us][PAWN]++;
1427 capture = u.capture;
1431 assert(capture != KING);
1433 // Insert captured piece:
1434 set_bit(&(byColorBB[them]), to);
1435 set_bit(&(byTypeBB[capture]), to);
1436 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1437 board[to] = piece_of_color_and_type(them, capture);
1439 // Update material. Because the move is a promotion move, we know
1440 // that the captured piece cannot be a pawn.
1441 assert(capture != PAWN);
1442 npMaterial[them] += piece_value_midgame(capture);
1444 // Update piece list
1445 pieceList[them][capture][pieceCount[them][capture]] = to;
1446 index[to] = pieceCount[them][capture];
1448 // Update piece count
1449 pieceCount[them][capture]++;
1455 /// Position::undo_ep_move() is a private method used to unmake an en passant
1456 /// capture. It is called from the main Position::undo_move function. Because
1457 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1458 /// object from which to retrieve the captured piece.
1460 void Position::undo_ep_move(Move m) {
1462 assert(move_is_ok(m));
1463 assert(move_is_ep(m));
1465 // When we have arrived here, some work has already been done by
1466 // Position::undo_move. In particular, the side to move has been switched,
1467 // so the code below is correct.
1468 Color us = side_to_move();
1469 Color them = opposite_color(us);
1470 Square from = move_from(m);
1471 Square to = move_to(m);
1472 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1474 assert(to == ep_square());
1475 assert(relative_rank(us, to) == RANK_6);
1476 assert(piece_on(to) == pawn_of_color(us));
1477 assert(piece_on(from) == EMPTY);
1478 assert(piece_on(capsq) == EMPTY);
1480 // Replace captured piece
1481 set_bit(&(byColorBB[them]), capsq);
1482 set_bit(&(byTypeBB[PAWN]), capsq);
1483 set_bit(&(byTypeBB[0]), capsq);
1484 board[capsq] = pawn_of_color(them);
1486 // Remove moving piece from destination square
1487 clear_bit(&(byColorBB[us]), to);
1488 clear_bit(&(byTypeBB[PAWN]), to);
1489 clear_bit(&(byTypeBB[0]), to);
1492 // Replace moving piece at source square
1493 set_bit(&(byColorBB[us]), from);
1494 set_bit(&(byTypeBB[PAWN]), from);
1495 set_bit(&(byTypeBB[0]), from);
1496 board[from] = pawn_of_color(us);
1498 // Update piece list:
1499 pieceList[us][PAWN][index[to]] = from;
1500 index[from] = index[to];
1501 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1502 index[capsq] = pieceCount[them][PAWN];
1504 // Update piece count:
1505 pieceCount[them][PAWN]++;
1509 /// Position::do_null_move makes() a "null move": It switches the side to move
1510 /// and updates the hash key without executing any move on the board.
1512 void Position::do_null_move(UndoInfo &u) {
1515 assert(!is_check());
1517 // Back up the information necessary to undo the null move to the supplied
1518 // UndoInfo object. In the case of a null move, the only thing we need to
1519 // remember is the last move made and the en passant square.
1520 u.lastMove = lastMove;
1521 u.epSquare = epSquare;
1523 // Save the current key to the history[] array, in order to be able to
1524 // detect repetition draws.
1525 history[gamePly] = key;
1527 // Update the necessary information
1528 sideToMove = opposite_color(sideToMove);
1529 if (epSquare != SQ_NONE)
1530 key ^= zobEp[epSquare];
1535 key ^= zobSideToMove;
1537 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1538 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1544 /// Position::undo_null_move() unmakes a "null move".
1546 void Position::undo_null_move(const UndoInfo &u) {
1549 assert(!is_check());
1551 // Restore information from the supplied UndoInfo object:
1552 lastMove = u.lastMove;
1553 epSquare = u.epSquare;
1554 if (epSquare != SQ_NONE)
1555 key ^= zobEp[epSquare];
1557 // Update the necessary information.
1558 sideToMove = opposite_color(sideToMove);
1561 key ^= zobSideToMove;
1563 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1564 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1570 /// Position::see() is a static exchange evaluator: It tries to estimate the
1571 /// material gain or loss resulting from a move. There are two versions of
1572 /// this function: One which takes a move as input, and one which takes a
1573 /// 'from' and a 'to' square. The function does not yet understand promotions
1574 /// or en passant captures.
1576 int Position::see(Move m) const {
1578 assert(move_is_ok(m));
1579 return see(move_from(m), move_to(m));
1582 int Position::see(Square from, Square to) const {
1584 // Approximate material values, with pawn = 1
1585 static const int seeValues[18] = {
1586 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1589 Bitboard attackers, occ, b;
1591 assert(square_is_ok(from));
1592 assert(square_is_ok(to));
1594 // Initialize colors
1595 Color us = color_of_piece_on(from);
1596 Color them = opposite_color(us);
1598 // Initialize pieces
1599 Piece piece = piece_on(from);
1600 Piece capture = piece_on(to);
1602 // Find all attackers to the destination square, with the moving piece
1603 // removed, but possibly an X-ray attacker added behind it.
1604 occ = occupied_squares();
1605 clear_bit(&occ, from);
1606 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1607 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1608 | (piece_attacks<KNIGHT>(to) & knights())
1609 | (piece_attacks<KING>(to) & kings())
1610 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1611 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1613 // If the opponent has no attackers, we are finished
1614 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1615 return seeValues[capture];
1617 attackers &= occ; // Remove the moving piece
1619 // The destination square is defended, which makes things rather more
1620 // difficult to compute. We proceed by building up a "swap list" containing
1621 // the material gain or loss at each stop in a sequence of captures to the
1622 // destination square, where the sides alternately capture, and always
1623 // capture with the least valuable piece. After each capture, we look for
1624 // new X-ray attacks from behind the capturing piece.
1625 int lastCapturingPieceValue = seeValues[piece];
1626 int swapList[32], n = 1;
1630 swapList[0] = seeValues[capture];
1633 // Locate the least valuable attacker for the side to move. The loop
1634 // below looks like it is potentially infinite, but it isn't. We know
1635 // that the side to move still has at least one attacker left.
1636 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1639 // Remove the attacker we just found from the 'attackers' bitboard,
1640 // and scan for new X-ray attacks behind the attacker.
1641 b = attackers & pieces_of_color_and_type(c, pt);
1643 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1644 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1648 // Add the new entry to the swap list
1650 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1653 // Remember the value of the capturing piece, and change the side to move
1654 // before beginning the next iteration
1655 lastCapturingPieceValue = seeValues[pt];
1656 c = opposite_color(c);
1658 // Stop after a king capture
1659 if (pt == KING && (attackers & pieces_of_color(c)))
1662 swapList[n++] = 100;
1665 } while (attackers & pieces_of_color(c));
1667 // Having built the swap list, we negamax through it to find the best
1668 // achievable score from the point of view of the side to move
1670 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1676 /// Position::clear() erases the position object to a pristine state, with an
1677 /// empty board, white to move, and no castling rights.
1679 void Position::clear() {
1681 for (int i = 0; i < 64; i++)
1687 for (int i = 0; i < 2; i++)
1688 byColorBB[i] = EmptyBoardBB;
1690 for (int i = 0; i < 7; i++)
1692 byTypeBB[i] = EmptyBoardBB;
1693 pieceCount[0][i] = pieceCount[1][i] = 0;
1694 for (int j = 0; j < 8; j++)
1695 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1698 checkersBB = EmptyBoardBB;
1700 lastMove = MOVE_NONE;
1703 castleRights = NO_CASTLES;
1704 initialKFile = FILE_E;
1705 initialKRFile = FILE_H;
1706 initialQRFile = FILE_A;
1713 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1714 /// UCI interface code, whenever a non-reversible move is made in a
1715 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1716 /// for the program to handle games of arbitrary length, as long as the GUI
1717 /// handles draws by the 50 move rule correctly.
1719 void Position::reset_game_ply() {
1725 /// Position::put_piece() puts a piece on the given square of the board,
1726 /// updating the board array, bitboards, and piece counts.
1728 void Position::put_piece(Piece p, Square s) {
1730 Color c = color_of_piece(p);
1731 PieceType pt = type_of_piece(p);
1734 index[s] = pieceCount[c][pt];
1735 pieceList[c][pt][index[s]] = s;
1737 set_bit(&(byTypeBB[pt]), s);
1738 set_bit(&(byColorBB[c]), s);
1739 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1741 pieceCount[c][pt]++;
1748 /// Position::allow_oo() gives the given side the right to castle kingside.
1749 /// Used when setting castling rights during parsing of FEN strings.
1751 void Position::allow_oo(Color c) {
1753 castleRights |= (1 + int(c));
1757 /// Position::allow_ooo() gives the given side the right to castle queenside.
1758 /// Used when setting castling rights during parsing of FEN strings.
1760 void Position::allow_ooo(Color c) {
1762 castleRights |= (4 + 4*int(c));
1766 /// Position::compute_key() computes the hash key of the position. The hash
1767 /// key is usually updated incrementally as moves are made and unmade, the
1768 /// compute_key() function is only used when a new position is set up, and
1769 /// to verify the correctness of the hash key when running in debug mode.
1771 Key Position::compute_key() const {
1773 Key result = Key(0ULL);
1775 for (Square s = SQ_A1; s <= SQ_H8; s++)
1776 if (square_is_occupied(s))
1777 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1779 if (ep_square() != SQ_NONE)
1780 result ^= zobEp[ep_square()];
1782 result ^= zobCastle[castleRights];
1783 if (side_to_move() == BLACK)
1784 result ^= zobSideToMove;
1790 /// Position::compute_pawn_key() computes the hash key of the position. The
1791 /// hash key is usually updated incrementally as moves are made and unmade,
1792 /// the compute_pawn_key() function is only used when a new position is set
1793 /// up, and to verify the correctness of the pawn hash key when running in
1796 Key Position::compute_pawn_key() const {
1798 Key result = Key(0ULL);
1802 for (Color c = WHITE; c <= BLACK; c++)
1807 s = pop_1st_bit(&b);
1808 result ^= zobrist[c][PAWN][s];
1815 /// Position::compute_material_key() computes the hash key of the position.
1816 /// The hash key is usually updated incrementally as moves are made and unmade,
1817 /// the compute_material_key() function is only used when a new position is set
1818 /// up, and to verify the correctness of the material hash key when running in
1821 Key Position::compute_material_key() const {
1823 Key result = Key(0ULL);
1824 for (Color c = WHITE; c <= BLACK; c++)
1825 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1827 int count = piece_count(c, pt);
1828 for (int i = 0; i <= count; i++)
1829 result ^= zobMaterial[c][pt][i];
1835 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1836 /// incremental scores for the middle game and the endgame. These functions
1837 /// are used to initialize the incremental scores when a new position is set
1838 /// up, and to verify that the scores are correctly updated by do_move
1839 /// and undo_move when the program is running in debug mode.
1841 Value Position::compute_mg_value() const {
1843 Value result = Value(0);
1847 for (Color c = WHITE; c <= BLACK; c++)
1848 for (PieceType pt = PAWN; pt <= KING; pt++)
1850 b = pieces_of_color_and_type(c, pt);
1853 s = pop_1st_bit(&b);
1854 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1855 result += mg_pst(c, pt, s);
1858 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1862 Value Position::compute_eg_value() const {
1864 Value result = Value(0);
1868 for (Color c = WHITE; c <= BLACK; c++)
1869 for (PieceType pt = PAWN; pt <= KING; pt++)
1871 b = pieces_of_color_and_type(c, pt);
1874 s = pop_1st_bit(&b);
1875 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1876 result += eg_pst(c, pt, s);
1879 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1884 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1885 /// game material score for the given side. Material scores are updated
1886 /// incrementally during the search, this function is only used while
1887 /// initializing a new Position object.
1889 Value Position::compute_non_pawn_material(Color c) const {
1891 Value result = Value(0);
1894 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1896 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() {
1916 MovePicker mp = MovePicker(*this, false, MOVE_NONE, MOVE_NONE,
1917 MOVE_NONE, MOVE_NONE, Depth(0));
1918 return mp.get_next_move() == MOVE_NONE;
1924 /// Position::is_draw() tests whether the position is drawn by material,
1925 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1926 /// must be done by the search.
1928 bool Position::is_draw() const {
1930 // Draw by material?
1932 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1935 // Draw by the 50 moves rule?
1936 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1939 // Draw by repetition?
1940 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1941 if (history[gamePly - i] == key)
1948 /// Position::has_mate_threat() tests whether a given color has a mate in one
1949 /// from the current position. This function is quite slow, but it doesn't
1950 /// matter, because it is currently only called from PV nodes, which are rare.
1952 bool Position::has_mate_threat(Color c) {
1955 Color stm = side_to_move();
1957 // The following lines are useless and silly, but prevents gcc from
1958 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1959 // be used uninitialized.
1960 u1.lastMove = lastMove;
1961 u1.epSquare = epSquare;
1966 // If the input color is not equal to the side to move, do a null move
1970 MoveStack mlist[120];
1972 bool result = false;
1974 // Generate legal moves
1975 count = generate_legal_moves(*this, mlist);
1977 // Loop through the moves, and see if one of them is mate
1978 for (int i = 0; i < count; i++)
1980 do_move(mlist[i].move, u2);
1984 undo_move(mlist[i].move, u2);
1987 // Undo null move, if necessary
1995 /// Position::init_zobrist() is a static member function which initializes the
1996 /// various arrays used to compute hash keys.
1998 void Position::init_zobrist() {
2000 for (int i = 0; i < 2; i++)
2001 for (int j = 0; j < 8; j++)
2002 for (int k = 0; k < 64; k++)
2003 zobrist[i][j][k] = Key(genrand_int64());
2005 for (int i = 0; i < 64; i++)
2006 zobEp[i] = Key(genrand_int64());
2008 for (int i = 0; i < 16; i++)
2009 zobCastle[i] = genrand_int64();
2011 zobSideToMove = genrand_int64();
2013 for (int i = 0; i < 2; i++)
2014 for (int j = 0; j < 8; j++)
2015 for (int k = 0; k < 16; k++)
2016 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2018 for (int i = 0; i < 16; i++)
2019 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2023 /// Position::init_piece_square_tables() initializes the piece square tables.
2024 /// This is a two-step operation: First, the white halves of the tables are
2025 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2026 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2027 /// Second, the black halves of the tables are initialized by mirroring
2028 /// and changing the sign of the corresponding white scores.
2030 void Position::init_piece_square_tables() {
2032 int r = get_option_value_int("Randomness"), i;
2033 for (Square s = SQ_A1; s <= SQ_H8; s++)
2034 for (Piece p = WP; p <= WK; p++)
2036 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2037 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2038 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2041 for (Square s = SQ_A1; s <= SQ_H8; s++)
2042 for (Piece p = BP; p <= BK; p++)
2044 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2045 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2050 /// Position::flipped_copy() makes a copy of the input position, but with
2051 /// the white and black sides reversed. This is only useful for debugging,
2052 /// especially for finding evaluation symmetry bugs.
2054 void Position::flipped_copy(const Position &pos) {
2056 assert(pos.is_ok());
2061 for (Square s = SQ_A1; s <= SQ_H8; s++)
2062 if (!pos.square_is_empty(s))
2063 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2066 sideToMove = opposite_color(pos.side_to_move());
2069 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2070 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2071 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2072 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2074 initialKFile = pos.initialKFile;
2075 initialKRFile = pos.initialKRFile;
2076 initialQRFile = pos.initialQRFile;
2078 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2079 castleRightsMask[sq] = ALL_CASTLES;
2081 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2082 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2083 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2084 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2085 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2086 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2088 // En passant square
2089 if (pos.epSquare != SQ_NONE)
2090 epSquare = flip_square(pos.epSquare);
2096 key = compute_key();
2097 pawnKey = compute_pawn_key();
2098 materialKey = compute_material_key();
2100 // Incremental scores
2101 mgValue = compute_mg_value();
2102 egValue = compute_eg_value();
2105 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2106 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2112 /// Position::is_ok() performs some consitency checks for the position object.
2113 /// This is meant to be helpful when debugging.
2115 bool Position::is_ok(int* failedStep) const {
2117 // What features of the position should be verified?
2118 static const bool debugBitboards = false;
2119 static const bool debugKingCount = false;
2120 static const bool debugKingCapture = false;
2121 static const bool debugCheckerCount = false;
2122 static const bool debugKey = false;
2123 static const bool debugMaterialKey = false;
2124 static const bool debugPawnKey = false;
2125 static const bool debugIncrementalEval = false;
2126 static const bool debugNonPawnMaterial = false;
2127 static const bool debugPieceCounts = false;
2128 static const bool debugPieceList = false;
2130 if (failedStep) *failedStep = 1;
2133 if (!color_is_ok(side_to_move()))
2136 // Are the king squares in the position correct?
2137 if (failedStep) (*failedStep)++;
2138 if (piece_on(king_square(WHITE)) != WK)
2141 if (failedStep) (*failedStep)++;
2142 if (piece_on(king_square(BLACK)) != BK)
2146 if (failedStep) (*failedStep)++;
2147 if (!file_is_ok(initialKRFile))
2150 if (!file_is_ok(initialQRFile))
2153 // Do both sides have exactly one king?
2154 if (failedStep) (*failedStep)++;
2157 int kingCount[2] = {0, 0};
2158 for (Square s = SQ_A1; s <= SQ_H8; s++)
2159 if (type_of_piece_on(s) == KING)
2160 kingCount[color_of_piece_on(s)]++;
2162 if(kingCount[0] != 1 || kingCount[1] != 1)
2166 // Can the side to move capture the opponent's king?
2167 if (failedStep) (*failedStep)++;
2168 if (debugKingCapture)
2170 Color us = side_to_move();
2171 Color them = opposite_color(us);
2172 Square ksq = king_square(them);
2173 if (square_is_attacked(ksq, us))
2177 // Is there more than 2 checkers?
2178 if (failedStep) (*failedStep)++;
2179 if (debugCheckerCount && count_1s(checkersBB) > 2)
2183 if (failedStep) (*failedStep)++;
2186 // The intersection of the white and black pieces must be empty
2187 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2190 // The union of the white and black pieces must be equal to all
2192 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2195 // Separate piece type bitboards must have empty intersections
2196 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2197 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2198 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2202 // En passant square OK?
2203 if (failedStep) (*failedStep)++;
2204 if (ep_square() != SQ_NONE)
2206 // The en passant square must be on rank 6, from the point of view of the
2208 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2213 if (failedStep) (*failedStep)++;
2214 if (debugKey && key != compute_key())
2217 // Pawn hash key OK?
2218 if (failedStep) (*failedStep)++;
2219 if (debugPawnKey && pawnKey != compute_pawn_key())
2222 // Material hash key OK?
2223 if (failedStep) (*failedStep)++;
2224 if (debugMaterialKey && materialKey != compute_material_key())
2227 // Incremental eval OK?
2228 if (failedStep) (*failedStep)++;
2229 if (debugIncrementalEval)
2231 if (mgValue != compute_mg_value())
2234 if (egValue != compute_eg_value())
2238 // Non-pawn material OK?
2239 if (failedStep) (*failedStep)++;
2240 if (debugNonPawnMaterial)
2242 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2245 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2250 if (failedStep) (*failedStep)++;
2251 if (debugPieceCounts)
2252 for (Color c = WHITE; c <= BLACK; c++)
2253 for (PieceType pt = PAWN; pt <= KING; pt++)
2254 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2257 if (failedStep) (*failedStep)++;
2260 for(Color c = WHITE; c <= BLACK; c++)
2261 for(PieceType pt = PAWN; pt <= KING; pt++)
2262 for(int i = 0; i < pieceCount[c][pt]; i++)
2264 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2267 if (index[piece_list(c, pt, i)] != i)
2271 if (failedStep) *failedStep = 0;