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);
418 /// Position::move_attacks_square() tests whether a move from the current
419 /// position attacks a given square. Only attacks by the moving piece are
420 /// considered; the function does not handle X-ray attacks.
422 bool Position::move_attacks_square(Move m, Square s) const {
424 assert(move_is_ok(m));
425 assert(square_is_ok(s));
427 Square f = move_from(m), t = move_to(m);
429 assert(square_is_occupied(f));
433 case WP: return pawn_attacks_square(WHITE, t, s);
434 case BP: return pawn_attacks_square(BLACK, t, s);
435 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
436 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
437 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
438 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
439 case WK: case BK: return piece_attacks_square<KING>(t, s);
445 /// Position::find_checkers() computes the checkersBB bitboard, which
446 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
447 /// currently works by calling Position::attacks_to, which is probably
448 /// inefficient. Consider rewriting this function to use the last move
449 /// played, like in non-bitboard versions of Glaurung.
451 void Position::find_checkers() {
453 Color us = side_to_move();
454 checkersBB = attacks_to(king_square(us), opposite_color(us));
458 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
459 /// There are two versions of this function: One which takes only a
460 /// move as input, and one which takes a move and a bitboard of pinned
461 /// pieces. The latter function is faster, and should always be preferred
462 /// when a pinned piece bitboard has already been computed.
464 bool Position::pl_move_is_legal(Move m) const {
466 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
469 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
472 assert(move_is_ok(m));
473 assert(pinned == pinned_pieces(side_to_move()));
475 // If we're in check, all pseudo-legal moves are legal, because our
476 // check evasion generator only generates true legal moves.
480 // Castling moves are checked for legality during move generation.
481 if (move_is_castle(m))
484 Color us = side_to_move();
485 Color them = opposite_color(us);
486 Square from = move_from(m);
487 Square ksq = king_square(us);
489 assert(color_of_piece_on(from) == us);
490 assert(piece_on(ksq) == king_of_color(us));
492 // En passant captures are a tricky special case. Because they are
493 // rather uncommon, we do it simply by testing whether the king is attacked
494 // after the move is made
497 Square to = move_to(m);
498 Square capsq = make_square(square_file(to), square_rank(from));
499 Bitboard b = occupied_squares();
501 assert(to == ep_square());
502 assert(piece_on(from) == pawn_of_color(us));
503 assert(piece_on(capsq) == pawn_of_color(them));
504 assert(piece_on(to) == EMPTY);
507 clear_bit(&b, capsq);
510 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
511 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
514 // If the moving piece is a king, check whether the destination
515 // square is attacked by the opponent.
517 return !(square_is_attacked(move_to(m), them));
519 // A non-king move is legal if and only if it is not pinned or it
520 // is moving along the ray towards or away from the king.
521 return ( !bit_is_set(pinned, from)
522 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
526 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
527 /// There are two versions of this function: One which takes only a move as
528 /// input, and one which takes a move and a bitboard of discovered check
529 /// candidates. The latter function is faster, and should always be preferred
530 /// when a discovered check candidates bitboard has already been computed.
532 bool Position::move_is_check(Move m) const {
534 Bitboard dc = discovered_check_candidates(side_to_move());
535 return move_is_check(m, dc);
538 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
541 assert(move_is_ok(m));
542 assert(dcCandidates == discovered_check_candidates(side_to_move()));
544 Color us = side_to_move();
545 Color them = opposite_color(us);
546 Square from = move_from(m);
547 Square to = move_to(m);
548 Square ksq = king_square(them);
550 assert(color_of_piece_on(from) == us);
551 assert(piece_on(ksq) == king_of_color(them));
553 // Proceed according to the type of the moving piece
554 switch (type_of_piece_on(from))
558 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
561 if ( bit_is_set(dcCandidates, from) // Discovered check?
562 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
565 if (move_promotion(m)) // Promotion with check?
567 Bitboard b = occupied_squares();
570 switch (move_promotion(m))
573 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
575 return bit_is_set(bishop_attacks_bb(to, b), ksq);
577 return bit_is_set(rook_attacks_bb(to, b), ksq);
579 return bit_is_set(queen_attacks_bb(to, b), ksq);
584 // En passant capture with check? We have already handled the case
585 // of direct checks and ordinary discovered check, the only case we
586 // need to handle is the unusual case of a discovered check through the
588 else if (move_is_ep(m))
590 Square capsq = make_square(square_file(to), square_rank(from));
591 Bitboard b = occupied_squares();
593 clear_bit(&b, capsq);
595 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
596 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
601 return bit_is_set(dcCandidates, from) // Discovered check?
602 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
605 return bit_is_set(dcCandidates, from) // Discovered check?
606 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
609 return bit_is_set(dcCandidates, from) // Discovered check?
610 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
613 // Discovered checks are impossible!
614 assert(!bit_is_set(dcCandidates, from));
615 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
619 if ( bit_is_set(dcCandidates, from)
620 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
623 // Castling with check?
624 if (move_is_castle(m))
626 Square kfrom, kto, rfrom, rto;
627 Bitboard b = occupied_squares();
633 kto = relative_square(us, SQ_G1);
634 rto = relative_square(us, SQ_F1);
636 kto = relative_square(us, SQ_C1);
637 rto = relative_square(us, SQ_D1);
639 clear_bit(&b, kfrom);
640 clear_bit(&b, rfrom);
643 return bit_is_set(rook_attacks_bb(rto, b), ksq);
652 /// Position::move_is_capture() tests whether a move from the current
653 /// position is a capture.
655 bool Position::move_is_capture(Move m) const {
657 return ( !square_is_empty(move_to(m))
658 && (color_of_piece_on(move_to(m)) == opposite_color(side_to_move()))
664 /// Position::backup() is called when making a move. All information
665 /// necessary to restore the position when the move is later unmade
666 /// is saved to an UndoInfo object. The function Position::restore
667 /// does the reverse operation: When one does a backup followed by
668 /// a restore with the same UndoInfo object, the position is restored
669 /// to the state before backup was called.
671 void Position::backup(UndoInfo& u) const {
673 u.castleRights = castleRights;
674 u.epSquare = epSquare;
675 u.checkersBB = checkersBB;
678 u.materialKey = materialKey;
680 u.lastMove = lastMove;
683 u.capture = NO_PIECE_TYPE;
687 /// Position::restore() is called when unmaking a move. It copies back
688 /// the information backed up during a previous call to Position::backup.
690 void Position::restore(const UndoInfo& u) {
692 castleRights = u.castleRights;
693 epSquare = u.epSquare;
694 checkersBB = u.checkersBB;
697 materialKey = u.materialKey;
699 lastMove = u.lastMove;
702 // u.capture is restored in undo_move()
705 /// Position::do_move() makes a move, and backs up all information necessary
706 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
707 /// Pseudo-legal moves should be filtered out before this function is called.
708 /// There are two versions of this function, one which takes only the move and
709 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
710 /// discovered check candidates. The second version is faster, because knowing
711 /// the discovered check candidates makes it easier to update the checkersBB
712 /// member variable in the position object.
714 void Position::do_move(Move m, UndoInfo& u) {
716 do_move(m, u, discovered_check_candidates(side_to_move()));
719 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
722 assert(move_is_ok(m));
724 // Back up the necessary information to our UndoInfo object (except the
725 // captured piece, which is taken care of later.
728 // Save the current key to the history[] array, in order to be able to
729 // detect repetition draws.
730 history[gamePly] = key;
732 // Increment the 50 moves rule draw counter. Resetting it to zero in the
733 // case of non-reversible moves is taken care of later.
736 if (move_is_castle(m))
738 else if (move_promotion(m))
739 do_promotion_move(m, u);
740 else if (move_is_ep(m))
744 Color us = side_to_move();
745 Color them = opposite_color(us);
746 Square from = move_from(m);
747 Square to = move_to(m);
749 assert(color_of_piece_on(from) == us);
750 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
752 PieceType piece = type_of_piece_on(from);
753 PieceType capture = type_of_piece_on(to);
758 do_capture_move(m, capture, them, to);
762 clear_bit(&(byColorBB[us]), from);
763 clear_bit(&(byTypeBB[piece]), from);
764 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
765 set_bit(&(byColorBB[us]), to);
766 set_bit(&(byTypeBB[piece]), to);
767 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
768 board[to] = board[from];
772 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
774 // Update incremental scores
775 mgValue -= mg_pst(us, piece, from);
776 mgValue += mg_pst(us, piece, to);
777 egValue -= eg_pst(us, piece, from);
778 egValue += eg_pst(us, piece, to);
780 // If the moving piece was a king, update the king square
784 // If the move was a double pawn push, set the en passant square.
785 // This code is a bit ugly right now, and should be cleaned up later.
787 if (epSquare != SQ_NONE)
789 key ^= zobEp[epSquare];
794 if (abs(int(to) - int(from)) == 16)
797 && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
799 && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
801 epSquare = Square((int(from) + int(to)) / 2);
802 key ^= zobEp[epSquare];
805 // Reset rule 50 draw counter
808 // Update pawn hash key
809 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
811 // Update piece lists
812 pieceList[us][piece][index[from]] = to;
813 index[to] = index[from];
815 // Update castle rights
816 key ^= zobCastle[castleRights];
817 castleRights &= castleRightsMask[from];
818 castleRights &= castleRightsMask[to];
819 key ^= zobCastle[castleRights];
821 // Update checkers bitboard
822 checkersBB = EmptyBoardBB;
823 Square ksq = king_square(them);
827 if (bit_is_set(pawn_attacks(them, ksq), to))
828 set_bit(&checkersBB, to);
830 if (bit_is_set(dcCandidates, from))
831 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
832 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
836 if (bit_is_set(piece_attacks<KNIGHT>(ksq), to))
837 set_bit(&checkersBB, to);
839 if (bit_is_set(dcCandidates, from))
840 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
841 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
845 if (bit_is_set(piece_attacks<BISHOP>(ksq), to))
846 set_bit(&checkersBB, to);
848 if (bit_is_set(dcCandidates, from))
849 checkersBB |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(us));
853 if (bit_is_set(piece_attacks<ROOK>(ksq), to))
854 set_bit(&checkersBB, to);
856 if (bit_is_set(dcCandidates, from))
857 checkersBB |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us));
861 if (bit_is_set(piece_attacks<QUEEN>(ksq), to))
862 set_bit(&checkersBB, to);
866 if (bit_is_set(dcCandidates, from))
867 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
868 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
878 key ^= zobSideToMove;
879 sideToMove = opposite_color(sideToMove);
882 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
883 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
889 /// Position::do_capture_move() is a private method used to update captured
890 /// piece info. It is called from the main Position::do_move function.
892 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
894 assert(capture != KING);
896 // Remove captured piece
897 clear_bit(&(byColorBB[them]), to);
898 clear_bit(&(byTypeBB[capture]), to);
901 key ^= zobrist[them][capture][to];
903 // If the captured piece was a pawn, update pawn hash key
905 pawnKey ^= zobrist[them][PAWN][to];
907 // Update incremental scores
908 mgValue -= mg_pst(them, capture, to);
909 egValue -= eg_pst(them, capture, to);
911 assert(!move_promotion(m) || capture != PAWN);
915 npMaterial[them] -= piece_value_midgame(capture);
917 // Update material hash key
918 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
920 // Update piece count
921 pieceCount[them][capture]--;
924 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
925 index[pieceList[them][capture][index[to]]] = index[to];
927 // Reset rule 50 counter
932 /// Position::do_castle_move() is a private method used to make a castling
933 /// move. It is called from the main Position::do_move function. Note that
934 /// castling moves are encoded as "king captures friendly rook" moves, for
935 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
937 void Position::do_castle_move(Move m) {
940 assert(move_is_ok(m));
941 assert(move_is_castle(m));
943 Color us = side_to_move();
944 Color them = opposite_color(us);
946 // Find source squares for king and rook
947 Square kfrom = move_from(m);
948 Square rfrom = move_to(m); // HACK: See comment at beginning of function
951 assert(piece_on(kfrom) == king_of_color(us));
952 assert(piece_on(rfrom) == rook_of_color(us));
954 // Find destination squares for king and rook
955 if (rfrom > kfrom) // O-O
957 kto = relative_square(us, SQ_G1);
958 rto = relative_square(us, SQ_F1);
960 kto = relative_square(us, SQ_C1);
961 rto = relative_square(us, SQ_D1);
964 // Remove pieces from source squares
965 clear_bit(&(byColorBB[us]), kfrom);
966 clear_bit(&(byTypeBB[KING]), kfrom);
967 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
968 clear_bit(&(byColorBB[us]), rfrom);
969 clear_bit(&(byTypeBB[ROOK]), rfrom);
970 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
972 // Put pieces on destination squares
973 set_bit(&(byColorBB[us]), kto);
974 set_bit(&(byTypeBB[KING]), kto);
975 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
976 set_bit(&(byColorBB[us]), rto);
977 set_bit(&(byTypeBB[ROOK]), rto);
978 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
980 // Update board array
981 board[kfrom] = board[rfrom] = EMPTY;
982 board[kto] = king_of_color(us);
983 board[rto] = rook_of_color(us);
985 // Update king square
986 kingSquare[us] = kto;
988 // Update piece lists
989 pieceList[us][KING][index[kfrom]] = kto;
990 pieceList[us][ROOK][index[rfrom]] = rto;
991 int tmp = index[rfrom];
992 index[kto] = index[kfrom];
995 // Update incremental scores
996 mgValue -= mg_pst(us, KING, kfrom);
997 mgValue += mg_pst(us, KING, kto);
998 egValue -= eg_pst(us, KING, kfrom);
999 egValue += eg_pst(us, KING, kto);
1000 mgValue -= mg_pst(us, ROOK, rfrom);
1001 mgValue += mg_pst(us, ROOK, rto);
1002 egValue -= eg_pst(us, ROOK, rfrom);
1003 egValue += eg_pst(us, ROOK, rto);
1006 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1007 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1009 // Clear en passant square
1010 if(epSquare != SQ_NONE)
1012 key ^= zobEp[epSquare];
1016 // Update castling rights
1017 key ^= zobCastle[castleRights];
1018 castleRights &= castleRightsMask[kfrom];
1019 key ^= zobCastle[castleRights];
1021 // Reset rule 50 counter
1024 // Update checkers BB
1025 checkersBB = attacks_to(king_square(them), us);
1029 /// Position::do_promotion_move() is a private method used to make a promotion
1030 /// move. It is called from the main Position::do_move function. The
1031 /// UndoInfo object, which has been initialized in Position::do_move, is
1032 /// used to store the captured piece (if any).
1034 void Position::do_promotion_move(Move m, UndoInfo &u) {
1038 PieceType capture, promotion;
1041 assert(move_is_ok(m));
1042 assert(move_promotion(m));
1044 us = side_to_move();
1045 them = opposite_color(us);
1046 from = move_from(m);
1049 assert(relative_rank(us, to) == RANK_8);
1050 assert(piece_on(from) == pawn_of_color(us));
1051 assert(color_of_piece_on(to) == them || square_is_empty(to));
1053 capture = type_of_piece_on(to);
1057 u.capture = capture;
1058 do_capture_move(m, capture, them, to);
1062 clear_bit(&(byColorBB[us]), from);
1063 clear_bit(&(byTypeBB[PAWN]), from);
1064 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1065 board[from] = EMPTY;
1067 // Insert promoted piece
1068 promotion = move_promotion(m);
1069 assert(promotion >= KNIGHT && promotion <= QUEEN);
1070 set_bit(&(byColorBB[us]), to);
1071 set_bit(&(byTypeBB[promotion]), to);
1072 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1073 board[to] = piece_of_color_and_type(us, promotion);
1076 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1078 // Update pawn hash key
1079 pawnKey ^= zobrist[us][PAWN][from];
1081 // Update material key
1082 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1083 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1085 // Update piece counts
1086 pieceCount[us][PAWN]--;
1087 pieceCount[us][promotion]++;
1089 // Update piece lists
1090 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1091 index[pieceList[us][PAWN][index[from]]] = index[from];
1092 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1093 index[to] = pieceCount[us][promotion] - 1;
1095 // Update incremental scores
1096 mgValue -= mg_pst(us, PAWN, from);
1097 mgValue += mg_pst(us, promotion, to);
1098 egValue -= eg_pst(us, PAWN, from);
1099 egValue += eg_pst(us, promotion, to);
1102 npMaterial[us] += piece_value_midgame(promotion);
1104 // Clear the en passant square
1105 if (epSquare != SQ_NONE)
1107 key ^= zobEp[epSquare];
1111 // Update castle rights
1112 key ^= zobCastle[castleRights];
1113 castleRights &= castleRightsMask[to];
1114 key ^= zobCastle[castleRights];
1116 // Reset rule 50 counter
\r
1119 // Update checkers BB
1120 checkersBB = attacks_to(king_square(them), us);
1124 /// Position::do_ep_move() is a private method used to make an en passant
1125 /// capture. It is called from the main Position::do_move function. Because
1126 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1127 /// object in which to store the captured piece.
1129 void Position::do_ep_move(Move m) {
1132 Square from, to, capsq;
1135 assert(move_is_ok(m));
1136 assert(move_is_ep(m));
1138 us = side_to_move();
1139 them = opposite_color(us);
1140 from = move_from(m);
1142 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1144 assert(to == epSquare);
1145 assert(relative_rank(us, to) == RANK_6);
1146 assert(piece_on(to) == EMPTY);
1147 assert(piece_on(from) == pawn_of_color(us));
1148 assert(piece_on(capsq) == pawn_of_color(them));
1150 // Remove captured piece
1151 clear_bit(&(byColorBB[them]), capsq);
1152 clear_bit(&(byTypeBB[PAWN]), capsq);
1153 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1154 board[capsq] = EMPTY;
1156 // Remove moving piece from source square
1157 clear_bit(&(byColorBB[us]), from);
1158 clear_bit(&(byTypeBB[PAWN]), from);
1159 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1161 // Put moving piece on destination square
1162 set_bit(&(byColorBB[us]), to);
1163 set_bit(&(byTypeBB[PAWN]), to);
1164 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1165 board[to] = board[from];
1166 board[from] = EMPTY;
1168 // Update material hash key
1169 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1171 // Update piece count
1172 pieceCount[them][PAWN]--;
1174 // Update piece list
1175 pieceList[us][PAWN][index[from]] = to;
1176 index[to] = index[from];
1177 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1178 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1181 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1182 key ^= zobrist[them][PAWN][capsq];
1183 key ^= zobEp[epSquare];
1185 // Update pawn hash key
1186 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1187 pawnKey ^= zobrist[them][PAWN][capsq];
1189 // Update incremental scores
1190 mgValue -= mg_pst(them, PAWN, capsq);
1191 mgValue -= mg_pst(us, PAWN, from);
1192 mgValue += mg_pst(us, PAWN, to);
1193 egValue -= eg_pst(them, PAWN, capsq);
1194 egValue -= eg_pst(us, PAWN, from);
1195 egValue += eg_pst(us, PAWN, to);
1197 // Reset en passant square
1200 // Reset rule 50 counter
1203 // Update checkers BB
1204 checkersBB = attacks_to(king_square(them), us);
1208 /// Position::undo_move() unmakes a move. When it returns, the position should
1209 /// be restored to exactly the same state as before the move was made. It is
1210 /// important that Position::undo_move is called with the same move and UndoInfo
1211 /// object as the earlier call to Position::do_move.
1213 void Position::undo_move(Move m, const UndoInfo &u) {
1216 assert(move_is_ok(m));
1219 sideToMove = opposite_color(sideToMove);
1221 // Restore information from our UndoInfo object (except the captured piece,
1222 // which is taken care of later)
1225 if (move_is_castle(m))
1226 undo_castle_move(m);
1227 else if (move_promotion(m))
1228 undo_promotion_move(m, u);
1229 else if (move_is_ep(m))
1235 PieceType piece, capture;
1237 us = side_to_move();
1238 them = opposite_color(us);
1239 from = move_from(m);
1242 assert(piece_on(from) == EMPTY);
1243 assert(color_of_piece_on(to) == us);
1245 // Put the piece back at the source square
1246 piece = type_of_piece_on(to);
1247 set_bit(&(byColorBB[us]), from);
1248 set_bit(&(byTypeBB[piece]), from);
1249 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1250 board[from] = piece_of_color_and_type(us, piece);
1252 // Clear the destination square
1253 clear_bit(&(byColorBB[us]), to);
1254 clear_bit(&(byTypeBB[piece]), to);
1255 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1257 // If the moving piece was a king, update the king square
1259 kingSquare[us] = from;
1261 // Update piece list
1262 pieceList[us][piece][index[to]] = from;
1263 index[from] = index[to];
1265 capture = u.capture;
1269 assert(capture != KING);
1271 // Replace the captured piece
1272 set_bit(&(byColorBB[them]), to);
1273 set_bit(&(byTypeBB[capture]), to);
1274 set_bit(&(byTypeBB[0]), to);
1275 board[to] = piece_of_color_and_type(them, capture);
1278 if (capture != PAWN)
1279 npMaterial[them] += piece_value_midgame(capture);
1281 // Update piece list
1282 pieceList[them][capture][pieceCount[them][capture]] = to;
1283 index[to] = pieceCount[them][capture];
1285 // Update piece count
1286 pieceCount[them][capture]++;
1295 /// Position::undo_castle_move() is a private method used to unmake a castling
1296 /// move. It is called from the main Position::undo_move function. Note that
1297 /// castling moves are encoded as "king captures friendly rook" moves, for
1298 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1300 void Position::undo_castle_move(Move m) {
1302 assert(move_is_ok(m));
1303 assert(move_is_castle(m));
1305 // When we have arrived here, some work has already been done by
1306 // Position::undo_move. In particular, the side to move has been switched,
1307 // so the code below is correct.
1308 Color us = side_to_move();
1310 // Find source squares for king and rook
1311 Square kfrom = move_from(m);
1312 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1315 // Find destination squares for king and rook
1316 if (rfrom > kfrom) // O-O
1318 kto = relative_square(us, SQ_G1);
1319 rto = relative_square(us, SQ_F1);
1321 kto = relative_square(us, SQ_C1);
1322 rto = relative_square(us, SQ_D1);
1325 assert(piece_on(kto) == king_of_color(us));
1326 assert(piece_on(rto) == rook_of_color(us));
1328 // Remove pieces from destination squares
1329 clear_bit(&(byColorBB[us]), kto);
1330 clear_bit(&(byTypeBB[KING]), kto);
1331 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1332 clear_bit(&(byColorBB[us]), rto);
1333 clear_bit(&(byTypeBB[ROOK]), rto);
1334 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1336 // Put pieces on source squares
1337 set_bit(&(byColorBB[us]), kfrom);
1338 set_bit(&(byTypeBB[KING]), kfrom);
1339 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1340 set_bit(&(byColorBB[us]), rfrom);
1341 set_bit(&(byTypeBB[ROOK]), rfrom);
1342 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1345 board[rto] = board[kto] = EMPTY;
1346 board[rfrom] = rook_of_color(us);
1347 board[kfrom] = king_of_color(us);
1349 // Update king square
1350 kingSquare[us] = kfrom;
1352 // Update piece lists
1353 pieceList[us][KING][index[kto]] = kfrom;
1354 pieceList[us][ROOK][index[rto]] = rfrom;
1355 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1356 index[kfrom] = index[kto];
1361 /// Position::undo_promotion_move() is a private method used to unmake a
1362 /// promotion move. It is called from the main Position::do_move
1363 /// function. The UndoInfo object, which has been initialized in
1364 /// Position::do_move, is used to put back the captured piece (if any).
1366 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1370 PieceType capture, promotion;
1372 assert(move_is_ok(m));
1373 assert(move_promotion(m));
1375 // When we have arrived here, some work has already been done by
1376 // Position::undo_move. In particular, the side to move has been switched,
1377 // so the code below is correct.
1378 us = side_to_move();
1379 them = opposite_color(us);
1380 from = move_from(m);
1383 assert(relative_rank(us, to) == RANK_8);
1384 assert(piece_on(from) == EMPTY);
1386 // Remove promoted piece
1387 promotion = move_promotion(m);
1388 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1389 assert(promotion >= KNIGHT && promotion <= QUEEN);
1390 clear_bit(&(byColorBB[us]), to);
1391 clear_bit(&(byTypeBB[promotion]), to);
1392 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1394 // Insert pawn at source square
1395 set_bit(&(byColorBB[us]), from);
1396 set_bit(&(byTypeBB[PAWN]), from);
1397 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1398 board[from] = pawn_of_color(us);
1401 npMaterial[us] -= piece_value_midgame(promotion);
1403 // Update piece list
1404 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1405 index[from] = pieceCount[us][PAWN];
1406 pieceList[us][promotion][index[to]] =
1407 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1408 index[pieceList[us][promotion][index[to]]] = index[to];
1410 // Update piece counts
1411 pieceCount[us][promotion]--;
1412 pieceCount[us][PAWN]++;
1414 capture = u.capture;
1418 assert(capture != KING);
1420 // Insert captured piece:
1421 set_bit(&(byColorBB[them]), to);
1422 set_bit(&(byTypeBB[capture]), to);
1423 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1424 board[to] = piece_of_color_and_type(them, capture);
1426 // Update material. Because the move is a promotion move, we know
1427 // that the captured piece cannot be a pawn.
1428 assert(capture != PAWN);
1429 npMaterial[them] += piece_value_midgame(capture);
1431 // Update piece list
1432 pieceList[them][capture][pieceCount[them][capture]] = to;
1433 index[to] = pieceCount[them][capture];
1435 // Update piece count
1436 pieceCount[them][capture]++;
1442 /// Position::undo_ep_move() is a private method used to unmake an en passant
1443 /// capture. It is called from the main Position::undo_move function. Because
1444 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1445 /// object from which to retrieve the captured piece.
1447 void Position::undo_ep_move(Move m) {
1449 assert(move_is_ok(m));
1450 assert(move_is_ep(m));
1452 // When we have arrived here, some work has already been done by
1453 // Position::undo_move. In particular, the side to move has been switched,
1454 // so the code below is correct.
1455 Color us = side_to_move();
1456 Color them = opposite_color(us);
1457 Square from = move_from(m);
1458 Square to = move_to(m);
1459 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1461 assert(to == ep_square());
1462 assert(relative_rank(us, to) == RANK_6);
1463 assert(piece_on(to) == pawn_of_color(us));
1464 assert(piece_on(from) == EMPTY);
1465 assert(piece_on(capsq) == EMPTY);
1467 // Replace captured piece
1468 set_bit(&(byColorBB[them]), capsq);
1469 set_bit(&(byTypeBB[PAWN]), capsq);
1470 set_bit(&(byTypeBB[0]), capsq);
1471 board[capsq] = pawn_of_color(them);
1473 // Remove moving piece from destination square
1474 clear_bit(&(byColorBB[us]), to);
1475 clear_bit(&(byTypeBB[PAWN]), to);
1476 clear_bit(&(byTypeBB[0]), to);
1479 // Replace moving piece at source square
1480 set_bit(&(byColorBB[us]), from);
1481 set_bit(&(byTypeBB[PAWN]), from);
1482 set_bit(&(byTypeBB[0]), from);
1483 board[from] = pawn_of_color(us);
1485 // Update piece list:
1486 pieceList[us][PAWN][index[to]] = from;
1487 index[from] = index[to];
1488 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1489 index[capsq] = pieceCount[them][PAWN];
1491 // Update piece count:
1492 pieceCount[them][PAWN]++;
1496 /// Position::do_null_move makes() a "null move": It switches the side to move
1497 /// and updates the hash key without executing any move on the board.
1499 void Position::do_null_move(UndoInfo &u) {
1502 assert(!is_check());
1504 // Back up the information necessary to undo the null move to the supplied
1505 // UndoInfo object. In the case of a null move, the only thing we need to
1506 // remember is the last move made and the en passant square.
1507 u.lastMove = lastMove;
1508 u.epSquare = epSquare;
1510 // Save the current key to the history[] array, in order to be able to
1511 // detect repetition draws.
1512 history[gamePly] = key;
1514 // Update the necessary information
1515 sideToMove = opposite_color(sideToMove);
1516 if (epSquare != SQ_NONE)
1517 key ^= zobEp[epSquare];
1522 key ^= zobSideToMove;
1524 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1525 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1531 /// Position::undo_null_move() unmakes a "null move".
1533 void Position::undo_null_move(const UndoInfo &u) {
1536 assert(!is_check());
1538 // Restore information from the supplied UndoInfo object:
1539 lastMove = u.lastMove;
1540 epSquare = u.epSquare;
1541 if (epSquare != SQ_NONE)
1542 key ^= zobEp[epSquare];
1544 // Update the necessary information.
1545 sideToMove = opposite_color(sideToMove);
1548 key ^= zobSideToMove;
1550 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1551 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1557 /// Position::see() is a static exchange evaluator: It tries to estimate the
1558 /// material gain or loss resulting from a move. There are two versions of
1559 /// this function: One which takes a move as input, and one which takes a
1560 /// 'from' and a 'to' square. The function does not yet understand promotions
1561 /// or en passant captures.
1563 int Position::see(Move m) const {
1565 assert(move_is_ok(m));
1566 return see(move_from(m), move_to(m));
1569 int Position::see(Square from, Square to) const {
1571 // Approximate material values, with pawn = 1
1572 static const int seeValues[18] = {
1573 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1576 Bitboard attackers, occ, b;
1578 assert(square_is_ok(from));
1579 assert(square_is_ok(to));
1581 // Initialize colors
1582 Color us = color_of_piece_on(from);
1583 Color them = opposite_color(us);
1585 // Initialize pieces
1586 Piece piece = piece_on(from);
1587 Piece capture = piece_on(to);
1589 // Find all attackers to the destination square, with the moving piece
1590 // removed, but possibly an X-ray attacker added behind it.
1591 occ = occupied_squares();
1592 clear_bit(&occ, from);
1593 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1594 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1595 | (piece_attacks<KNIGHT>(to) & knights())
1596 | (piece_attacks<KING>(to) & kings())
1597 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1598 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1600 // If the opponent has no attackers, we are finished
1601 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1602 return seeValues[capture];
1604 attackers &= occ; // Remove the moving piece
1606 // The destination square is defended, which makes things rather more
1607 // difficult to compute. We proceed by building up a "swap list" containing
1608 // the material gain or loss at each stop in a sequence of captures to the
1609 // destination square, where the sides alternately capture, and always
1610 // capture with the least valuable piece. After each capture, we look for
1611 // new X-ray attacks from behind the capturing piece.
1612 int lastCapturingPieceValue = seeValues[piece];
1613 int swapList[32], n = 1;
1617 swapList[0] = seeValues[capture];
1620 // Locate the least valuable attacker for the side to move. The loop
1621 // below looks like it is potentially infinite, but it isn't. We know
1622 // that the side to move still has at least one attacker left.
1623 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1626 // Remove the attacker we just found from the 'attackers' bitboard,
1627 // and scan for new X-ray attacks behind the attacker.
1628 b = attackers & pieces_of_color_and_type(c, pt);
1630 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1631 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1635 // Add the new entry to the swap list
1637 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1640 // Remember the value of the capturing piece, and change the side to move
1641 // before beginning the next iteration
1642 lastCapturingPieceValue = seeValues[pt];
1643 c = opposite_color(c);
1645 // Stop after a king capture
1646 if (pt == KING && (attackers & pieces_of_color(c)))
1649 swapList[n++] = 100;
1652 } while (attackers & pieces_of_color(c));
1654 // Having built the swap list, we negamax through it to find the best
1655 // achievable score from the point of view of the side to move
1657 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1663 /// Position::clear() erases the position object to a pristine state, with an
1664 /// empty board, white to move, and no castling rights.
1666 void Position::clear() {
1668 for (int i = 0; i < 64; i++)
1674 for (int i = 0; i < 2; i++)
1675 byColorBB[i] = EmptyBoardBB;
1677 for (int i = 0; i < 7; i++)
1679 byTypeBB[i] = EmptyBoardBB;
1680 pieceCount[0][i] = pieceCount[1][i] = 0;
1681 for (int j = 0; j < 8; j++)
1682 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1685 checkersBB = EmptyBoardBB;
1687 lastMove = MOVE_NONE;
1690 castleRights = NO_CASTLES;
1691 initialKFile = FILE_E;
1692 initialKRFile = FILE_H;
1693 initialQRFile = FILE_A;
1700 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1701 /// UCI interface code, whenever a non-reversible move is made in a
1702 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1703 /// for the program to handle games of arbitrary length, as long as the GUI
1704 /// handles draws by the 50 move rule correctly.
1706 void Position::reset_game_ply() {
1712 /// Position::put_piece() puts a piece on the given square of the board,
1713 /// updating the board array, bitboards, and piece counts.
1715 void Position::put_piece(Piece p, Square s) {
1717 Color c = color_of_piece(p);
1718 PieceType pt = type_of_piece(p);
1721 index[s] = pieceCount[c][pt];
1722 pieceList[c][pt][index[s]] = s;
1724 set_bit(&(byTypeBB[pt]), s);
1725 set_bit(&(byColorBB[c]), s);
1726 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1728 pieceCount[c][pt]++;
1735 /// Position::allow_oo() gives the given side the right to castle kingside.
1736 /// Used when setting castling rights during parsing of FEN strings.
1738 void Position::allow_oo(Color c) {
1740 castleRights |= (1 + int(c));
1744 /// Position::allow_ooo() gives the given side the right to castle queenside.
1745 /// Used when setting castling rights during parsing of FEN strings.
1747 void Position::allow_ooo(Color c) {
1749 castleRights |= (4 + 4*int(c));
1753 /// Position::compute_key() computes the hash key of the position. The hash
1754 /// key is usually updated incrementally as moves are made and unmade, the
1755 /// compute_key() function is only used when a new position is set up, and
1756 /// to verify the correctness of the hash key when running in debug mode.
1758 Key Position::compute_key() const {
1760 Key result = Key(0ULL);
1762 for (Square s = SQ_A1; s <= SQ_H8; s++)
1763 if (square_is_occupied(s))
1764 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1766 if (ep_square() != SQ_NONE)
1767 result ^= zobEp[ep_square()];
1769 result ^= zobCastle[castleRights];
1770 if (side_to_move() == BLACK)
1771 result ^= zobSideToMove;
1777 /// Position::compute_pawn_key() computes the hash key of the position. The
1778 /// hash key is usually updated incrementally as moves are made and unmade,
1779 /// the compute_pawn_key() function is only used when a new position is set
1780 /// up, and to verify the correctness of the pawn hash key when running in
1783 Key Position::compute_pawn_key() const {
1785 Key result = Key(0ULL);
1789 for (Color c = WHITE; c <= BLACK; c++)
1794 s = pop_1st_bit(&b);
1795 result ^= zobrist[c][PAWN][s];
1802 /// Position::compute_material_key() computes the hash key of the position.
1803 /// The hash key is usually updated incrementally as moves are made and unmade,
1804 /// the compute_material_key() function is only used when a new position is set
1805 /// up, and to verify the correctness of the material hash key when running in
1808 Key Position::compute_material_key() const {
1810 Key result = Key(0ULL);
1811 for (Color c = WHITE; c <= BLACK; c++)
1812 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1814 int count = piece_count(c, pt);
1815 for (int i = 0; i <= count; i++)
1816 result ^= zobMaterial[c][pt][i];
1822 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1823 /// incremental scores for the middle game and the endgame. These functions
1824 /// are used to initialize the incremental scores when a new position is set
1825 /// up, and to verify that the scores are correctly updated by do_move
1826 /// and undo_move when the program is running in debug mode.
1828 Value Position::compute_mg_value() const {
1830 Value result = Value(0);
1834 for (Color c = WHITE; c <= BLACK; c++)
1835 for (PieceType pt = PAWN; pt <= KING; pt++)
1837 b = pieces_of_color_and_type(c, pt);
1840 s = pop_1st_bit(&b);
1841 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1842 result += mg_pst(c, pt, s);
1845 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1849 Value Position::compute_eg_value() const {
1851 Value result = Value(0);
1855 for (Color c = WHITE; c <= BLACK; c++)
1856 for (PieceType pt = PAWN; pt <= KING; pt++)
1858 b = pieces_of_color_and_type(c, pt);
1861 s = pop_1st_bit(&b);
1862 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1863 result += eg_pst(c, pt, s);
1866 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1871 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1872 /// game material score for the given side. Material scores are updated
1873 /// incrementally during the search, this function is only used while
1874 /// initializing a new Position object.
1876 Value Position::compute_non_pawn_material(Color c) const {
1878 Value result = Value(0);
1881 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1883 Bitboard b = pieces_of_color_and_type(c, pt);
1886 s = pop_1st_bit(&b);
1887 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1888 result += piece_value_midgame(pt);
1895 /// Position::is_mate() returns true or false depending on whether the
1896 /// side to move is checkmated. Note that this function is currently very
1897 /// slow, and shouldn't be used frequently inside the search.
1899 bool Position::is_mate() {
1903 MovePicker mp = MovePicker(*this, false, MOVE_NONE, MOVE_NONE,
1904 MOVE_NONE, MOVE_NONE, Depth(0));
1905 return mp.get_next_move() == MOVE_NONE;
1911 /// Position::is_draw() tests whether the position is drawn by material,
1912 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1913 /// must be done by the search.
1915 bool Position::is_draw() const {
1917 // Draw by material?
1919 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1922 // Draw by the 50 moves rule?
1923 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1926 // Draw by repetition?
1927 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1928 if (history[gamePly - i] == key)
1935 /// Position::has_mate_threat() tests whether a given color has a mate in one
1936 /// from the current position. This function is quite slow, but it doesn't
1937 /// matter, because it is currently only called from PV nodes, which are rare.
1939 bool Position::has_mate_threat(Color c) {
1942 Color stm = side_to_move();
1944 // The following lines are useless and silly, but prevents gcc from
1945 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1946 // be used uninitialized.
1947 u1.lastMove = lastMove;
1948 u1.epSquare = epSquare;
1953 // If the input color is not equal to the side to move, do a null move
1957 MoveStack mlist[120];
1959 bool result = false;
1961 // Generate legal moves
1962 count = generate_legal_moves(*this, mlist);
1964 // Loop through the moves, and see if one of them is mate
1965 for (int i = 0; i < count; i++)
1967 do_move(mlist[i].move, u2);
1971 undo_move(mlist[i].move, u2);
1974 // Undo null move, if necessary
1982 /// Position::init_zobrist() is a static member function which initializes the
1983 /// various arrays used to compute hash keys.
1985 void Position::init_zobrist() {
1987 for (int i = 0; i < 2; i++)
1988 for (int j = 0; j < 8; j++)
1989 for (int k = 0; k < 64; k++)
1990 zobrist[i][j][k] = Key(genrand_int64());
1992 for (int i = 0; i < 64; i++)
1993 zobEp[i] = Key(genrand_int64());
1995 for (int i = 0; i < 16; i++)
1996 zobCastle[i] = genrand_int64();
1998 zobSideToMove = genrand_int64();
2000 for (int i = 0; i < 2; i++)
2001 for (int j = 0; j < 8; j++)
2002 for (int k = 0; k < 16; k++)
2003 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2005 for (int i = 0; i < 16; i++)
2006 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2010 /// Position::init_piece_square_tables() initializes the piece square tables.
2011 /// This is a two-step operation: First, the white halves of the tables are
2012 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2013 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2014 /// Second, the black halves of the tables are initialized by mirroring
2015 /// and changing the sign of the corresponding white scores.
2017 void Position::init_piece_square_tables() {
2019 int r = get_option_value_int("Randomness"), i;
2020 for (Square s = SQ_A1; s <= SQ_H8; s++)
2021 for (Piece p = WP; p <= WK; p++)
2023 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2024 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2025 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2028 for (Square s = SQ_A1; s <= SQ_H8; s++)
2029 for (Piece p = BP; p <= BK; p++)
2031 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2032 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2037 /// Position::flipped_copy() makes a copy of the input position, but with
2038 /// the white and black sides reversed. This is only useful for debugging,
2039 /// especially for finding evaluation symmetry bugs.
2041 void Position::flipped_copy(const Position &pos) {
2043 assert(pos.is_ok());
2048 for (Square s = SQ_A1; s <= SQ_H8; s++)
2049 if (!pos.square_is_empty(s))
2050 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2053 sideToMove = opposite_color(pos.side_to_move());
2056 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2057 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2058 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2059 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2061 initialKFile = pos.initialKFile;
2062 initialKRFile = pos.initialKRFile;
2063 initialQRFile = pos.initialQRFile;
2065 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2066 castleRightsMask[sq] = ALL_CASTLES;
2068 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2069 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2070 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2071 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2072 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2073 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2075 // En passant square
2076 if (pos.epSquare != SQ_NONE)
2077 epSquare = flip_square(pos.epSquare);
2083 key = compute_key();
2084 pawnKey = compute_pawn_key();
2085 materialKey = compute_material_key();
2087 // Incremental scores
2088 mgValue = compute_mg_value();
2089 egValue = compute_eg_value();
2092 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2093 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2099 /// Position::is_ok() performs some consitency checks for the position object.
2100 /// This is meant to be helpful when debugging.
2102 bool Position::is_ok(int* failedStep) const {
2104 // What features of the position should be verified?
2105 static const bool debugBitboards = false;
2106 static const bool debugKingCount = false;
2107 static const bool debugKingCapture = false;
2108 static const bool debugCheckerCount = false;
2109 static const bool debugKey = false;
2110 static const bool debugMaterialKey = false;
2111 static const bool debugPawnKey = false;
2112 static const bool debugIncrementalEval = false;
2113 static const bool debugNonPawnMaterial = false;
2114 static const bool debugPieceCounts = false;
2115 static const bool debugPieceList = false;
2117 if (failedStep) *failedStep = 1;
2120 if (!color_is_ok(side_to_move()))
2123 // Are the king squares in the position correct?
2124 if (failedStep) (*failedStep)++;
2125 if (piece_on(king_square(WHITE)) != WK)
2128 if (failedStep) (*failedStep)++;
2129 if (piece_on(king_square(BLACK)) != BK)
2133 if (failedStep) (*failedStep)++;
2134 if (!file_is_ok(initialKRFile))
2137 if (!file_is_ok(initialQRFile))
2140 // Do both sides have exactly one king?
2141 if (failedStep) (*failedStep)++;
2144 int kingCount[2] = {0, 0};
2145 for (Square s = SQ_A1; s <= SQ_H8; s++)
2146 if (type_of_piece_on(s) == KING)
2147 kingCount[color_of_piece_on(s)]++;
2149 if(kingCount[0] != 1 || kingCount[1] != 1)
2153 // Can the side to move capture the opponent's king?
2154 if (failedStep) (*failedStep)++;
2155 if (debugKingCapture)
2157 Color us = side_to_move();
2158 Color them = opposite_color(us);
2159 Square ksq = king_square(them);
2160 if (square_is_attacked(ksq, us))
2164 // Is there more than 2 checkers?
2165 if (failedStep) (*failedStep)++;
2166 if (debugCheckerCount && count_1s(checkersBB) > 2)
2170 if (failedStep) (*failedStep)++;
2173 // The intersection of the white and black pieces must be empty
2174 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2177 // The union of the white and black pieces must be equal to all
2179 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2182 // Separate piece type bitboards must have empty intersections
2183 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2184 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2185 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2189 // En passant square OK?
2190 if (failedStep) (*failedStep)++;
2191 if (ep_square() != SQ_NONE)
2193 // The en passant square must be on rank 6, from the point of view of the
2195 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2200 if (failedStep) (*failedStep)++;
2201 if (debugKey && key != compute_key())
2204 // Pawn hash key OK?
2205 if (failedStep) (*failedStep)++;
2206 if (debugPawnKey && pawnKey != compute_pawn_key())
2209 // Material hash key OK?
2210 if (failedStep) (*failedStep)++;
2211 if (debugMaterialKey && materialKey != compute_material_key())
2214 // Incremental eval OK?
2215 if (failedStep) (*failedStep)++;
2216 if (debugIncrementalEval)
2218 if (mgValue != compute_mg_value())
2221 if (egValue != compute_eg_value())
2225 // Non-pawn material OK?
2226 if (failedStep) (*failedStep)++;
2227 if (debugNonPawnMaterial)
2229 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2232 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2237 if (failedStep) (*failedStep)++;
2238 if (debugPieceCounts)
2239 for (Color c = WHITE; c <= BLACK; c++)
2240 for (PieceType pt = PAWN; pt <= KING; pt++)
2241 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2244 if (failedStep) (*failedStep)++;
2247 for(Color c = WHITE; c <= BLACK; c++)
2248 for(PieceType pt = PAWN; pt <= KING; pt++)
2249 for(int i = 0; i < pieceCount[c][pt]; i++)
2251 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2254 if (index[piece_list(c, pt, i)] != i)
2258 if (failedStep) *failedStep = 0;