2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
35 #include "ucioption.h"
42 extern SearchStack EmptySearchStack;
44 int Position::castleRightsMask[64];
46 Key Position::zobrist[2][8][64];
47 Key Position::zobEp[64];
48 Key Position::zobCastle[16];
49 Key Position::zobMaterial[2][8][16];
50 Key Position::zobSideToMove;
52 Value Position::MgPieceSquareTable[16][64];
53 Value Position::EgPieceSquareTable[16][64];
55 static bool RequestPending = false;
63 Position::Position(const Position& pos) {
67 Position::Position(const std::string& fen) {
72 /// Position::from_fen() initializes the position object with the given FEN
73 /// string. This function is not very robust - make sure that input FENs are
74 /// correct (this is assumed to be the responsibility of the GUI).
76 void Position::from_fen(const std::string& fen) {
78 static const std::string pieceLetters = "KQRBNPkqrbnp";
79 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
87 for ( ; fen[i] != ' '; i++)
91 // Skip the given number of files
92 file += (fen[i] - '1' + 1);
95 else if (fen[i] == '/')
101 size_t idx = pieceLetters.find(fen[i]);
102 if (idx == std::string::npos)
104 std::cout << "Error in FEN at character " << i << std::endl;
107 Square square = make_square(file, rank);
108 put_piece(pieces[idx], square);
114 if (fen[i] != 'w' && fen[i] != 'b')
116 std::cout << "Error in FEN at character " << i << std::endl;
119 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
125 std::cout << "Error in FEN at character " << i << std::endl;
130 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
136 else if(fen[i] == 'K') allow_oo(WHITE);
137 else if(fen[i] == 'Q') allow_ooo(WHITE);
138 else if(fen[i] == 'k') allow_oo(BLACK);
139 else if(fen[i] == 'q') allow_ooo(BLACK);
140 else if(fen[i] >= 'A' && fen[i] <= 'H') {
141 File rookFile, kingFile = FILE_NONE;
142 for(Square square = SQ_B1; square <= SQ_G1; square++)
143 if(piece_on(square) == WK)
144 kingFile = square_file(square);
145 if(kingFile == FILE_NONE) {
146 std::cout << "Error in FEN at character " << i << std::endl;
149 initialKFile = kingFile;
150 rookFile = File(fen[i] - 'A') + FILE_A;
151 if(rookFile < initialKFile) {
153 initialQRFile = rookFile;
157 initialKRFile = rookFile;
160 else if(fen[i] >= 'a' && fen[i] <= 'h') {
161 File rookFile, kingFile = FILE_NONE;
162 for(Square square = SQ_B8; square <= SQ_G8; square++)
163 if(piece_on(square) == BK)
164 kingFile = square_file(square);
165 if(kingFile == FILE_NONE) {
166 std::cout << "Error in FEN at character " << i << std::endl;
169 initialKFile = kingFile;
170 rookFile = File(fen[i] - 'a') + FILE_A;
171 if(rookFile < initialKFile) {
173 initialQRFile = rookFile;
177 initialKRFile = rookFile;
181 std::cout << "Error in FEN at character " << i << std::endl;
188 while (fen[i] == ' ')
192 if ( i < fen.length() - 2
193 && (fen[i] >= 'a' && fen[i] <= 'h')
194 && (fen[i+1] == '3' || fen[i+1] == '6'))
195 epSquare = square_from_string(fen.substr(i, 2));
197 // Various initialisation
198 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
199 castleRightsMask[sq] = ALL_CASTLES;
201 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
202 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
203 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
204 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
205 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
206 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
211 pawnKey = compute_pawn_key();
212 materialKey = compute_material_key();
213 mgValue = compute_mg_value();
214 egValue = compute_eg_value();
215 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
216 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
220 /// Position::to_fen() converts the position object to a FEN string. This is
221 /// probably only useful for debugging.
223 const std::string Position::to_fen() const {
225 static const std::string pieceLetters = " PNBRQK pnbrqk";
229 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
232 for (File file = FILE_A; file <= FILE_H; file++)
234 Square sq = make_square(file, rank);
235 if (!square_is_occupied(sq))
241 fen += (char)skip + '0';
244 fen += pieceLetters[piece_on(sq)];
247 fen += (char)skip + '0';
249 fen += (rank > RANK_1 ? '/' : ' ');
251 fen += (sideToMove == WHITE ? "w " : "b ");
252 if (castleRights != NO_CASTLES)
254 if (can_castle_kingside(WHITE)) fen += 'K';
255 if (can_castle_queenside(WHITE)) fen += 'Q';
256 if (can_castle_kingside(BLACK)) fen += 'k';
257 if (can_castle_queenside(BLACK)) fen += 'q';
262 if (ep_square() != SQ_NONE)
263 fen += square_to_string(ep_square());
271 /// Position::print() prints an ASCII representation of the position to
272 /// the standard output. If a move is given then also the san is print.
274 void Position::print(Move m) const {
276 static const std::string pieceLetters = " PNBRQK PNBRQK .";
278 // Check for reentrancy, as example when called from inside
279 // MovePicker that is used also here in move_to_san()
283 RequestPending = true;
285 std::cout << std::endl;
288 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
289 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
291 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
293 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
294 for (File file = FILE_A; file <= FILE_H; file++)
296 Square sq = make_square(file, rank);
297 Piece piece = piece_on(sq);
298 if (piece == EMPTY && square_color(sq) == WHITE)
301 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
302 std::cout << '|' << col << pieceLetters[piece] << col;
304 std::cout << '|' << std::endl;
306 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
307 << "Fen is: " << to_fen() << std::endl
308 << "Key is: " << key << std::endl;
310 RequestPending = false;
314 /// Position::copy() creates a copy of the input position.
316 void Position::copy(const Position &pos) {
318 memcpy(this, &pos, sizeof(Position));
322 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
323 /// king) pieces for the given color.
324 Bitboard Position::pinned_pieces(Color c) const {
326 Square ksq = king_square(c);
327 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
331 /// Position:discovered_check_candidates() returns a bitboard containing all
332 /// pieces for the given side which are candidates for giving a discovered
333 /// check. The code is almost the same as the function for finding pinned
336 Bitboard Position::discovered_check_candidates(Color c) const {
338 Square ksq = king_square(opposite_color(c));
339 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
343 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
344 /// king) pieces for the given color and for the given pinner type. Or, when
345 /// template parameter FindPinned is false, the pinned pieces of opposite color
346 /// that are, indeed, the pieces candidate for a discovery check.
347 template<PieceType Piece, bool FindPinned>
348 Bitboard Position::hidden_checks(Color c, Square ksq) const {
351 Bitboard sliders, result = EmptyBoardBB;
353 if (Piece == ROOK) // Resolved at compile time
354 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
356 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
358 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
360 // King blockers are candidate pinned pieces
361 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
363 // Pinners are sliders, not checkers, that give check when
364 // candidate pinned are removed.
365 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
368 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
370 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
372 // Finally for each pinner find the corresponding pinned piece (if same color of king)
373 // or discovery checker (if opposite color) among the candidates.
376 s = pop_1st_bit(&pinners);
377 result |= (squares_between(s, ksq) & candidate_pinned);
384 /// Position::attacks_to() computes a bitboard containing all pieces which
385 /// attacks a given square. There are two versions of this function: One
386 /// which finds attackers of both colors, and one which only finds the
387 /// attackers for one side.
389 Bitboard Position::attacks_to(Square s) const {
391 return (pawn_attacks(BLACK, s) & pawns(WHITE))
392 | (pawn_attacks(WHITE, s) & pawns(BLACK))
393 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
394 | (piece_attacks<ROOK>(s) & rooks_and_queens())
395 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
396 | (piece_attacks<KING>(s) & pieces_of_type(KING));
399 /// Position::piece_attacks_square() tests whether the piece on square f
400 /// attacks square t.
402 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
404 assert(square_is_ok(f));
405 assert(square_is_ok(t));
409 case WP: return pawn_attacks_square(WHITE, f, t);
410 case BP: return pawn_attacks_square(BLACK, f, t);
411 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
412 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
413 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
414 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
415 case WK: case BK: return piece_attacks_square<KING>(f, t);
422 /// Position::move_attacks_square() tests whether a move from the current
423 /// position attacks a given square.
425 bool Position::move_attacks_square(Move m, Square s) const {
427 assert(move_is_ok(m));
428 assert(square_is_ok(s));
430 Square f = move_from(m), t = move_to(m);
432 assert(square_is_occupied(f));
434 if (piece_attacks_square(piece_on(f), t, s))
437 // Move the piece and scan for X-ray attacks behind it
438 Bitboard occ = occupied_squares();
439 Color us = color_of_piece_on(f);
442 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
443 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
445 // If we have attacks we need to verify that are caused by our move
446 // and are not already existent ones.
447 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
451 /// Position::find_checkers() computes the checkersBB bitboard, which
452 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
453 /// currently works by calling Position::attacks_to, which is probably
454 /// inefficient. Consider rewriting this function to use the last move
455 /// played, like in non-bitboard versions of Glaurung.
457 void Position::find_checkers() {
459 Color us = side_to_move();
460 checkersBB = attacks_to(king_square(us), opposite_color(us));
464 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
465 /// There are two versions of this function: One which takes only a
466 /// move as input, and one which takes a move and a bitboard of pinned
467 /// pieces. The latter function is faster, and should always be preferred
468 /// when a pinned piece bitboard has already been computed.
470 bool Position::pl_move_is_legal(Move m) const {
472 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
475 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
478 assert(move_is_ok(m));
479 assert(pinned == pinned_pieces(side_to_move()));
481 // If we're in check, all pseudo-legal moves are legal, because our
482 // check evasion generator only generates true legal moves.
486 // Castling moves are checked for legality during move generation.
487 if (move_is_castle(m))
490 Color us = side_to_move();
491 Color them = opposite_color(us);
492 Square from = move_from(m);
493 Square ksq = king_square(us);
495 assert(color_of_piece_on(from) == us);
496 assert(piece_on(ksq) == king_of_color(us));
498 // En passant captures are a tricky special case. Because they are
499 // rather uncommon, we do it simply by testing whether the king is attacked
500 // after the move is made
503 Square to = move_to(m);
504 Square capsq = make_square(square_file(to), square_rank(from));
505 Bitboard b = occupied_squares();
507 assert(to == ep_square());
508 assert(piece_on(from) == pawn_of_color(us));
509 assert(piece_on(capsq) == pawn_of_color(them));
510 assert(piece_on(to) == EMPTY);
513 clear_bit(&b, capsq);
516 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
517 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
520 // If the moving piece is a king, check whether the destination
521 // square is attacked by the opponent.
523 return !(square_is_attacked(move_to(m), them));
525 // A non-king move is legal if and only if it is not pinned or it
526 // is moving along the ray towards or away from the king.
527 return ( !bit_is_set(pinned, from)
528 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
532 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
533 /// There are two versions of this function: One which takes only a move as
534 /// input, and one which takes a move and a bitboard of discovered check
535 /// candidates. The latter function is faster, and should always be preferred
536 /// when a discovered check candidates bitboard has already been computed.
538 bool Position::move_is_check(Move m) const {
540 Bitboard dc = discovered_check_candidates(side_to_move());
541 return move_is_check(m, dc);
544 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
547 assert(move_is_ok(m));
548 assert(dcCandidates == discovered_check_candidates(side_to_move()));
550 Color us = side_to_move();
551 Color them = opposite_color(us);
552 Square from = move_from(m);
553 Square to = move_to(m);
554 Square ksq = king_square(them);
556 assert(color_of_piece_on(from) == us);
557 assert(piece_on(ksq) == king_of_color(them));
559 // Proceed according to the type of the moving piece
560 switch (type_of_piece_on(from))
564 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
567 if ( bit_is_set(dcCandidates, from) // Discovered check?
568 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
571 if (move_promotion(m)) // Promotion with check?
573 Bitboard b = occupied_squares();
576 switch (move_promotion(m))
579 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
581 return bit_is_set(bishop_attacks_bb(to, b), ksq);
583 return bit_is_set(rook_attacks_bb(to, b), ksq);
585 return bit_is_set(queen_attacks_bb(to, b), ksq);
590 // En passant capture with check? We have already handled the case
591 // of direct checks and ordinary discovered check, the only case we
592 // need to handle is the unusual case of a discovered check through the
594 else if (move_is_ep(m))
596 Square capsq = make_square(square_file(to), square_rank(from));
597 Bitboard b = occupied_squares();
599 clear_bit(&b, capsq);
601 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
602 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
607 return bit_is_set(dcCandidates, from) // Discovered check?
608 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
611 return bit_is_set(dcCandidates, from) // Discovered check?
612 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
615 return bit_is_set(dcCandidates, from) // Discovered check?
616 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
619 // Discovered checks are impossible!
620 assert(!bit_is_set(dcCandidates, from));
621 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
625 if ( bit_is_set(dcCandidates, from)
626 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
629 // Castling with check?
630 if (move_is_castle(m))
632 Square kfrom, kto, rfrom, rto;
633 Bitboard b = occupied_squares();
639 kto = relative_square(us, SQ_G1);
640 rto = relative_square(us, SQ_F1);
642 kto = relative_square(us, SQ_C1);
643 rto = relative_square(us, SQ_D1);
645 clear_bit(&b, kfrom);
646 clear_bit(&b, rfrom);
649 return bit_is_set(rook_attacks_bb(rto, b), ksq);
653 default: // NO_PIECE_TYPE
661 /// Position::move_is_capture() tests whether a move from the current
662 /// position is a capture. Move must not be MOVE_NONE.
664 bool Position::move_is_capture(Move m) const {
666 assert(m != MOVE_NONE);
668 return ( !square_is_empty(move_to(m))
669 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
675 /// Position::backup() is called when making a move. All information
676 /// necessary to restore the position when the move is later unmade
677 /// is saved to an UndoInfo object. The function Position::restore
678 /// does the reverse operation: When one does a backup followed by
679 /// a restore with the same UndoInfo object, the position is restored
680 /// to the state before backup was called.
682 void Position::backup(UndoInfo& u) const {
684 u.castleRights = castleRights;
685 u.epSquare = epSquare;
686 u.checkersBB = checkersBB;
689 u.materialKey = materialKey;
691 u.lastMove = lastMove;
694 u.capture = NO_PIECE_TYPE;
698 /// Position::restore() is called when unmaking a move. It copies back
699 /// the information backed up during a previous call to Position::backup.
701 void Position::restore(const UndoInfo& u) {
703 castleRights = u.castleRights;
704 epSquare = u.epSquare;
705 checkersBB = u.checkersBB;
708 materialKey = u.materialKey;
710 lastMove = u.lastMove;
713 // u.capture is restored in undo_move()
717 /// Position::update_checkers() is a private method to udpate chekers info
719 template<PieceType Piece>
720 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
721 Square to, Bitboard dcCandidates) {
723 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
724 set_bit(pCheckersBB, to);
726 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
729 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
732 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
737 /// Position::do_move() makes a move, and backs up all information necessary
738 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
739 /// Pseudo-legal moves should be filtered out before this function is called.
740 /// There are two versions of this function, one which takes only the move and
741 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
742 /// discovered check candidates. The second version is faster, because knowing
743 /// the discovered check candidates makes it easier to update the checkersBB
744 /// member variable in the position object.
746 void Position::do_move(Move m, UndoInfo& u) {
748 do_move(m, u, discovered_check_candidates(side_to_move()));
751 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
754 assert(move_is_ok(m));
756 // Back up the necessary information to our UndoInfo object (except the
757 // captured piece, which is taken care of later.
760 // Save the current key to the history[] array, in order to be able to
761 // detect repetition draws.
762 history[gamePly] = key;
764 // Increment the 50 moves rule draw counter. Resetting it to zero in the
765 // case of non-reversible moves is taken care of later.
768 if (move_is_castle(m))
770 else if (move_promotion(m))
771 do_promotion_move(m, u);
772 else if (move_is_ep(m))
776 Color us = side_to_move();
777 Color them = opposite_color(us);
778 Square from = move_from(m);
779 Square to = move_to(m);
781 assert(color_of_piece_on(from) == us);
782 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
784 PieceType piece = type_of_piece_on(from);
785 PieceType capture = type_of_piece_on(to);
790 do_capture_move(m, capture, them, to);
794 clear_bit(&(byColorBB[us]), from);
795 clear_bit(&(byTypeBB[piece]), from);
796 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
797 set_bit(&(byColorBB[us]), to);
798 set_bit(&(byTypeBB[piece]), to);
799 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
800 board[to] = board[from];
804 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
806 // Update incremental scores
807 mgValue -= mg_pst(us, piece, from);
808 mgValue += mg_pst(us, piece, to);
809 egValue -= eg_pst(us, piece, from);
810 egValue += eg_pst(us, piece, to);
812 // If the moving piece was a king, update the king square
816 // Reset en passant square
817 if (epSquare != SQ_NONE)
819 key ^= zobEp[epSquare];
823 // If the moving piece was a pawn do some special extra work
826 // Reset rule 50 draw counter
829 // Update pawn hash key
830 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
832 // Set en passant square, only if moved pawn can be captured
833 if (abs(int(to) - int(from)) == 16)
835 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
836 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
838 epSquare = Square((int(from) + int(to)) / 2);
839 key ^= zobEp[epSquare];
844 // Update piece lists
845 pieceList[us][piece][index[from]] = to;
846 index[to] = index[from];
848 // Update castle rights
849 key ^= zobCastle[castleRights];
850 castleRights &= castleRightsMask[from];
851 castleRights &= castleRightsMask[to];
852 key ^= zobCastle[castleRights];
854 // Update checkers bitboard, piece must be already moved
855 checkersBB = EmptyBoardBB;
856 Square ksq = king_square(them);
859 case PAWN: update_checkers<PAWN>(&checkersBB, ksq, from, to, dcCandidates); break;
860 case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, dcCandidates); break;
861 case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, dcCandidates); break;
862 case ROOK: update_checkers<ROOK>(&checkersBB, ksq, from, to, dcCandidates); break;
863 case QUEEN: update_checkers<QUEEN>(&checkersBB, ksq, from, to, dcCandidates); break;
864 case KING: update_checkers<KING>(&checkersBB, ksq, from, to, dcCandidates); break;
865 default: assert(false); break;
870 key ^= zobSideToMove;
871 sideToMove = opposite_color(sideToMove);
874 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
875 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
881 /// Position::do_capture_move() is a private method used to update captured
882 /// piece info. It is called from the main Position::do_move function.
884 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
886 assert(capture != KING);
888 // Remove captured piece
889 clear_bit(&(byColorBB[them]), to);
890 clear_bit(&(byTypeBB[capture]), to);
893 key ^= zobrist[them][capture][to];
895 // If the captured piece was a pawn, update pawn hash key
897 pawnKey ^= zobrist[them][PAWN][to];
899 // Update incremental scores
900 mgValue -= mg_pst(them, capture, to);
901 egValue -= eg_pst(them, capture, to);
903 assert(!move_promotion(m) || capture != PAWN);
907 npMaterial[them] -= piece_value_midgame(capture);
909 // Update material hash key
910 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
912 // Update piece count
913 pieceCount[them][capture]--;
916 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
917 index[pieceList[them][capture][index[to]]] = index[to];
919 // Reset rule 50 counter
924 /// Position::do_castle_move() is a private method used to make a castling
925 /// move. It is called from the main Position::do_move function. Note that
926 /// castling moves are encoded as "king captures friendly rook" moves, for
927 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
929 void Position::do_castle_move(Move m) {
932 assert(move_is_ok(m));
933 assert(move_is_castle(m));
935 Color us = side_to_move();
936 Color them = opposite_color(us);
938 // Find source squares for king and rook
939 Square kfrom = move_from(m);
940 Square rfrom = move_to(m); // HACK: See comment at beginning of function
943 assert(piece_on(kfrom) == king_of_color(us));
944 assert(piece_on(rfrom) == rook_of_color(us));
946 // Find destination squares for king and rook
947 if (rfrom > kfrom) // O-O
949 kto = relative_square(us, SQ_G1);
950 rto = relative_square(us, SQ_F1);
952 kto = relative_square(us, SQ_C1);
953 rto = relative_square(us, SQ_D1);
956 // Remove pieces from source squares
957 clear_bit(&(byColorBB[us]), kfrom);
958 clear_bit(&(byTypeBB[KING]), kfrom);
959 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
960 clear_bit(&(byColorBB[us]), rfrom);
961 clear_bit(&(byTypeBB[ROOK]), rfrom);
962 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
964 // Put pieces on destination squares
965 set_bit(&(byColorBB[us]), kto);
966 set_bit(&(byTypeBB[KING]), kto);
967 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
968 set_bit(&(byColorBB[us]), rto);
969 set_bit(&(byTypeBB[ROOK]), rto);
970 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
972 // Update board array
973 board[kfrom] = board[rfrom] = EMPTY;
974 board[kto] = piece_of_color_and_type(us, KING);
975 board[rto] = piece_of_color_and_type(us, ROOK);
977 // Update king square
978 kingSquare[us] = kto;
980 // Update piece lists
981 pieceList[us][KING][index[kfrom]] = kto;
982 pieceList[us][ROOK][index[rfrom]] = rto;
983 int tmp = index[rfrom];
984 index[kto] = index[kfrom];
987 // Update incremental scores
988 mgValue -= mg_pst(us, KING, kfrom);
989 mgValue += mg_pst(us, KING, kto);
990 egValue -= eg_pst(us, KING, kfrom);
991 egValue += eg_pst(us, KING, kto);
992 mgValue -= mg_pst(us, ROOK, rfrom);
993 mgValue += mg_pst(us, ROOK, rto);
994 egValue -= eg_pst(us, ROOK, rfrom);
995 egValue += eg_pst(us, ROOK, rto);
998 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
999 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1001 // Clear en passant square
1002 if (epSquare != SQ_NONE)
1004 key ^= zobEp[epSquare];
1008 // Update castling rights
1009 key ^= zobCastle[castleRights];
1010 castleRights &= castleRightsMask[kfrom];
1011 key ^= zobCastle[castleRights];
1013 // Reset rule 50 counter
1016 // Update checkers BB
1017 checkersBB = attacks_to(king_square(them), us);
1021 /// Position::do_promotion_move() is a private method used to make a promotion
1022 /// move. It is called from the main Position::do_move function. The
1023 /// UndoInfo object, which has been initialized in Position::do_move, is
1024 /// used to store the captured piece (if any).
1026 void Position::do_promotion_move(Move m, UndoInfo &u) {
1030 PieceType capture, promotion;
1033 assert(move_is_ok(m));
1034 assert(move_promotion(m));
1036 us = side_to_move();
1037 them = opposite_color(us);
1038 from = move_from(m);
1041 assert(relative_rank(us, to) == RANK_8);
1042 assert(piece_on(from) == pawn_of_color(us));
1043 assert(color_of_piece_on(to) == them || square_is_empty(to));
1045 capture = type_of_piece_on(to);
1049 u.capture = capture;
1050 do_capture_move(m, capture, them, to);
1054 clear_bit(&(byColorBB[us]), from);
1055 clear_bit(&(byTypeBB[PAWN]), from);
1056 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1057 board[from] = EMPTY;
1059 // Insert promoted piece
1060 promotion = move_promotion(m);
1061 assert(promotion >= KNIGHT && promotion <= QUEEN);
1062 set_bit(&(byColorBB[us]), to);
1063 set_bit(&(byTypeBB[promotion]), to);
1064 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1065 board[to] = piece_of_color_and_type(us, promotion);
1068 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1070 // Update pawn hash key
1071 pawnKey ^= zobrist[us][PAWN][from];
1073 // Update material key
1074 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1075 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1077 // Update piece counts
1078 pieceCount[us][PAWN]--;
1079 pieceCount[us][promotion]++;
1081 // Update piece lists
1082 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1083 index[pieceList[us][PAWN][index[from]]] = index[from];
1084 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1085 index[to] = pieceCount[us][promotion] - 1;
1087 // Update incremental scores
1088 mgValue -= mg_pst(us, PAWN, from);
1089 mgValue += mg_pst(us, promotion, to);
1090 egValue -= eg_pst(us, PAWN, from);
1091 egValue += eg_pst(us, promotion, to);
1094 npMaterial[us] += piece_value_midgame(promotion);
1096 // Clear the en passant square
1097 if (epSquare != SQ_NONE)
1099 key ^= zobEp[epSquare];
1103 // Update castle rights
1104 key ^= zobCastle[castleRights];
1105 castleRights &= castleRightsMask[to];
1106 key ^= zobCastle[castleRights];
1108 // Reset rule 50 counter
1111 // Update checkers BB
1112 checkersBB = attacks_to(king_square(them), us);
1116 /// Position::do_ep_move() is a private method used to make an en passant
1117 /// capture. It is called from the main Position::do_move function. Because
1118 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1119 /// object in which to store the captured piece.
1121 void Position::do_ep_move(Move m) {
1124 Square from, to, capsq;
1127 assert(move_is_ok(m));
1128 assert(move_is_ep(m));
1130 us = side_to_move();
1131 them = opposite_color(us);
1132 from = move_from(m);
1134 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1136 assert(to == epSquare);
1137 assert(relative_rank(us, to) == RANK_6);
1138 assert(piece_on(to) == EMPTY);
1139 assert(piece_on(from) == pawn_of_color(us));
1140 assert(piece_on(capsq) == pawn_of_color(them));
1142 // Remove captured piece
1143 clear_bit(&(byColorBB[them]), capsq);
1144 clear_bit(&(byTypeBB[PAWN]), capsq);
1145 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1146 board[capsq] = EMPTY;
1148 // Remove moving piece from source square
1149 clear_bit(&(byColorBB[us]), from);
1150 clear_bit(&(byTypeBB[PAWN]), from);
1151 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1153 // Put moving piece on destination square
1154 set_bit(&(byColorBB[us]), to);
1155 set_bit(&(byTypeBB[PAWN]), to);
1156 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1157 board[to] = board[from];
1158 board[from] = EMPTY;
1160 // Update material hash key
1161 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1163 // Update piece count
1164 pieceCount[them][PAWN]--;
1166 // Update piece list
1167 pieceList[us][PAWN][index[from]] = to;
1168 index[to] = index[from];
1169 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1170 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1173 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1174 key ^= zobrist[them][PAWN][capsq];
1175 key ^= zobEp[epSquare];
1177 // Update pawn hash key
1178 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1179 pawnKey ^= zobrist[them][PAWN][capsq];
1181 // Update incremental scores
1182 mgValue -= mg_pst(them, PAWN, capsq);
1183 mgValue -= mg_pst(us, PAWN, from);
1184 mgValue += mg_pst(us, PAWN, to);
1185 egValue -= eg_pst(them, PAWN, capsq);
1186 egValue -= eg_pst(us, PAWN, from);
1187 egValue += eg_pst(us, PAWN, to);
1189 // Reset en passant square
1192 // Reset rule 50 counter
1195 // Update checkers BB
1196 checkersBB = attacks_to(king_square(them), us);
1200 /// Position::undo_move() unmakes a move. When it returns, the position should
1201 /// be restored to exactly the same state as before the move was made. It is
1202 /// important that Position::undo_move is called with the same move and UndoInfo
1203 /// object as the earlier call to Position::do_move.
1205 void Position::undo_move(Move m, const UndoInfo &u) {
1208 assert(move_is_ok(m));
1211 sideToMove = opposite_color(sideToMove);
1213 // Restore information from our UndoInfo object (except the captured piece,
1214 // which is taken care of later)
1217 if (move_is_castle(m))
1218 undo_castle_move(m);
1219 else if (move_promotion(m))
1220 undo_promotion_move(m, u);
1221 else if (move_is_ep(m))
1227 PieceType piece, capture;
1229 us = side_to_move();
1230 them = opposite_color(us);
1231 from = move_from(m);
1234 assert(piece_on(from) == EMPTY);
1235 assert(color_of_piece_on(to) == us);
1237 // Put the piece back at the source square
1238 piece = type_of_piece_on(to);
1239 set_bit(&(byColorBB[us]), from);
1240 set_bit(&(byTypeBB[piece]), from);
1241 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1242 board[from] = piece_of_color_and_type(us, piece);
1244 // Clear the destination square
1245 clear_bit(&(byColorBB[us]), to);
1246 clear_bit(&(byTypeBB[piece]), to);
1247 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1249 // If the moving piece was a king, update the king square
1251 kingSquare[us] = from;
1253 // Update piece list
1254 pieceList[us][piece][index[to]] = from;
1255 index[from] = index[to];
1257 capture = u.capture;
1261 assert(capture != KING);
1263 // Replace the captured piece
1264 set_bit(&(byColorBB[them]), to);
1265 set_bit(&(byTypeBB[capture]), to);
1266 set_bit(&(byTypeBB[0]), to);
1267 board[to] = piece_of_color_and_type(them, capture);
1270 if (capture != PAWN)
1271 npMaterial[them] += piece_value_midgame(capture);
1273 // Update piece list
1274 pieceList[them][capture][pieceCount[them][capture]] = to;
1275 index[to] = pieceCount[them][capture];
1277 // Update piece count
1278 pieceCount[them][capture]++;
1287 /// Position::undo_castle_move() is a private method used to unmake a castling
1288 /// move. It is called from the main Position::undo_move function. Note that
1289 /// castling moves are encoded as "king captures friendly rook" moves, for
1290 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1292 void Position::undo_castle_move(Move m) {
1294 assert(move_is_ok(m));
1295 assert(move_is_castle(m));
1297 // When we have arrived here, some work has already been done by
1298 // Position::undo_move. In particular, the side to move has been switched,
1299 // so the code below is correct.
1300 Color us = side_to_move();
1302 // Find source squares for king and rook
1303 Square kfrom = move_from(m);
1304 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1307 // Find destination squares for king and rook
1308 if (rfrom > kfrom) // O-O
1310 kto = relative_square(us, SQ_G1);
1311 rto = relative_square(us, SQ_F1);
1313 kto = relative_square(us, SQ_C1);
1314 rto = relative_square(us, SQ_D1);
1317 assert(piece_on(kto) == king_of_color(us));
1318 assert(piece_on(rto) == rook_of_color(us));
1320 // Remove pieces from destination squares
1321 clear_bit(&(byColorBB[us]), kto);
1322 clear_bit(&(byTypeBB[KING]), kto);
1323 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1324 clear_bit(&(byColorBB[us]), rto);
1325 clear_bit(&(byTypeBB[ROOK]), rto);
1326 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1328 // Put pieces on source squares
1329 set_bit(&(byColorBB[us]), kfrom);
1330 set_bit(&(byTypeBB[KING]), kfrom);
1331 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1332 set_bit(&(byColorBB[us]), rfrom);
1333 set_bit(&(byTypeBB[ROOK]), rfrom);
1334 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1337 board[rto] = board[kto] = EMPTY;
1338 board[rfrom] = piece_of_color_and_type(us, ROOK);
1339 board[kfrom] = piece_of_color_and_type(us, KING);
1341 // Update king square
1342 kingSquare[us] = kfrom;
1344 // Update piece lists
1345 pieceList[us][KING][index[kto]] = kfrom;
1346 pieceList[us][ROOK][index[rto]] = rfrom;
1347 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1348 index[kfrom] = index[kto];
1353 /// Position::undo_promotion_move() is a private method used to unmake a
1354 /// promotion move. It is called from the main Position::do_move
1355 /// function. The UndoInfo object, which has been initialized in
1356 /// Position::do_move, is used to put back the captured piece (if any).
1358 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1362 PieceType capture, promotion;
1364 assert(move_is_ok(m));
1365 assert(move_promotion(m));
1367 // When we have arrived here, some work has already been done by
1368 // Position::undo_move. In particular, the side to move has been switched,
1369 // so the code below is correct.
1370 us = side_to_move();
1371 them = opposite_color(us);
1372 from = move_from(m);
1375 assert(relative_rank(us, to) == RANK_8);
1376 assert(piece_on(from) == EMPTY);
1378 // Remove promoted piece
1379 promotion = move_promotion(m);
1380 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1381 assert(promotion >= KNIGHT && promotion <= QUEEN);
1382 clear_bit(&(byColorBB[us]), to);
1383 clear_bit(&(byTypeBB[promotion]), to);
1384 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1386 // Insert pawn at source square
1387 set_bit(&(byColorBB[us]), from);
1388 set_bit(&(byTypeBB[PAWN]), from);
1389 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1390 board[from] = piece_of_color_and_type(us, PAWN);
1393 npMaterial[us] -= piece_value_midgame(promotion);
1395 // Update piece list
1396 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1397 index[from] = pieceCount[us][PAWN];
1398 pieceList[us][promotion][index[to]] =
1399 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1400 index[pieceList[us][promotion][index[to]]] = index[to];
1402 // Update piece counts
1403 pieceCount[us][promotion]--;
1404 pieceCount[us][PAWN]++;
1406 capture = u.capture;
1410 assert(capture != KING);
1412 // Insert captured piece:
1413 set_bit(&(byColorBB[them]), to);
1414 set_bit(&(byTypeBB[capture]), to);
1415 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1416 board[to] = piece_of_color_and_type(them, capture);
1418 // Update material. Because the move is a promotion move, we know
1419 // that the captured piece cannot be a pawn.
1420 assert(capture != PAWN);
1421 npMaterial[them] += piece_value_midgame(capture);
1423 // Update piece list
1424 pieceList[them][capture][pieceCount[them][capture]] = to;
1425 index[to] = pieceCount[them][capture];
1427 // Update piece count
1428 pieceCount[them][capture]++;
1434 /// Position::undo_ep_move() is a private method used to unmake an en passant
1435 /// capture. It is called from the main Position::undo_move function. Because
1436 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1437 /// object from which to retrieve the captured piece.
1439 void Position::undo_ep_move(Move m) {
1441 assert(move_is_ok(m));
1442 assert(move_is_ep(m));
1444 // When we have arrived here, some work has already been done by
1445 // Position::undo_move. In particular, the side to move has been switched,
1446 // so the code below is correct.
1447 Color us = side_to_move();
1448 Color them = opposite_color(us);
1449 Square from = move_from(m);
1450 Square to = move_to(m);
1451 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1453 assert(to == ep_square());
1454 assert(relative_rank(us, to) == RANK_6);
1455 assert(piece_on(to) == pawn_of_color(us));
1456 assert(piece_on(from) == EMPTY);
1457 assert(piece_on(capsq) == EMPTY);
1459 // Replace captured piece
1460 set_bit(&(byColorBB[them]), capsq);
1461 set_bit(&(byTypeBB[PAWN]), capsq);
1462 set_bit(&(byTypeBB[0]), capsq);
1463 board[capsq] = piece_of_color_and_type(them, PAWN);
1465 // Remove moving piece from destination square
1466 clear_bit(&(byColorBB[us]), to);
1467 clear_bit(&(byTypeBB[PAWN]), to);
1468 clear_bit(&(byTypeBB[0]), to);
1471 // Replace moving piece at source square
1472 set_bit(&(byColorBB[us]), from);
1473 set_bit(&(byTypeBB[PAWN]), from);
1474 set_bit(&(byTypeBB[0]), from);
1475 board[from] = piece_of_color_and_type(us, PAWN);
1477 // Update piece list:
1478 pieceList[us][PAWN][index[to]] = from;
1479 index[from] = index[to];
1480 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1481 index[capsq] = pieceCount[them][PAWN];
1483 // Update piece count:
1484 pieceCount[them][PAWN]++;
1488 /// Position::do_null_move makes() a "null move": It switches the side to move
1489 /// and updates the hash key without executing any move on the board.
1491 void Position::do_null_move(UndoInfo& u) {
1494 assert(!is_check());
1496 // Back up the information necessary to undo the null move to the supplied
1497 // UndoInfo object. In the case of a null move, the only thing we need to
1498 // remember is the last move made and the en passant square.
1499 u.lastMove = lastMove;
1500 u.epSquare = epSquare;
1502 // Save the current key to the history[] array, in order to be able to
1503 // detect repetition draws.
1504 history[gamePly] = key;
1506 // Update the necessary information
1507 sideToMove = opposite_color(sideToMove);
1508 if (epSquare != SQ_NONE)
1509 key ^= zobEp[epSquare];
1514 key ^= zobSideToMove;
1516 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1517 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1523 /// Position::undo_null_move() unmakes a "null move".
1525 void Position::undo_null_move(const UndoInfo &u) {
1528 assert(!is_check());
1530 // Restore information from the supplied UndoInfo object:
1531 lastMove = u.lastMove;
1532 epSquare = u.epSquare;
1533 if (epSquare != SQ_NONE)
1534 key ^= zobEp[epSquare];
1536 // Update the necessary information.
1537 sideToMove = opposite_color(sideToMove);
1540 key ^= zobSideToMove;
1542 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1543 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1549 /// Position::see() is a static exchange evaluator: It tries to estimate the
1550 /// material gain or loss resulting from a move. There are three versions of
1551 /// this function: One which takes a destination square as input, one takes a
1552 /// move, and one which takes a 'from' and a 'to' square. The function does
1553 /// not yet understand promotions captures.
1555 int Position::see(Square to) const {
1557 assert(square_is_ok(to));
1558 return see(SQ_NONE, to);
1561 int Position::see(Move m) const {
1563 assert(move_is_ok(m));
1564 return see(move_from(m), move_to(m));
1567 int Position::see(Square from, Square to) const {
1570 static const int seeValues[18] = {
1571 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1572 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1573 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1574 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1578 Bitboard attackers, occ, b;
1580 assert(square_is_ok(from) || from == SQ_NONE);
1581 assert(square_is_ok(to));
1583 // Initialize colors
1584 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1585 Color them = opposite_color(us);
1587 // Initialize pieces
1588 Piece piece = piece_on(from);
1589 Piece capture = piece_on(to);
1591 // Find all attackers to the destination square, with the moving piece
1592 // removed, but possibly an X-ray attacker added behind it.
1593 occ = occupied_squares();
1595 // Handle en passant moves
1596 if (epSquare == to && type_of_piece_on(from) == PAWN)
1598 assert(capture == EMPTY);
1600 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1601 capture = piece_on(capQq);
1603 assert(type_of_piece_on(capQq) == PAWN);
1605 // Remove the captured pawn
1606 clear_bit(&occ, capQq);
1611 clear_bit(&occ, from);
1612 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1613 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1614 | (piece_attacks<KNIGHT>(to) & knights())
1615 | (piece_attacks<KING>(to) & kings())
1616 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1617 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1619 if (from != SQ_NONE)
1622 // If we don't have any attacker we are finished
1623 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1626 // Locate the least valuable attacker to the destination square
1627 // and use it to initialize from square.
1629 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1632 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1633 piece = piece_on(from);
1636 // If the opponent has no attackers we are finished
1637 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1638 return seeValues[capture];
1640 attackers &= occ; // Remove the moving piece
1642 // The destination square is defended, which makes things rather more
1643 // difficult to compute. We proceed by building up a "swap list" containing
1644 // the material gain or loss at each stop in a sequence of captures to the
1645 // destination square, where the sides alternately capture, and always
1646 // capture with the least valuable piece. After each capture, we look for
1647 // new X-ray attacks from behind the capturing piece.
1648 int lastCapturingPieceValue = seeValues[piece];
1649 int swapList[32], n = 1;
1653 swapList[0] = seeValues[capture];
1656 // Locate the least valuable attacker for the side to move. The loop
1657 // below looks like it is potentially infinite, but it isn't. We know
1658 // that the side to move still has at least one attacker left.
1659 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1662 // Remove the attacker we just found from the 'attackers' bitboard,
1663 // and scan for new X-ray attacks behind the attacker.
1664 b = attackers & pieces_of_color_and_type(c, pt);
1666 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1667 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1671 // Add the new entry to the swap list
1673 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1676 // Remember the value of the capturing piece, and change the side to move
1677 // before beginning the next iteration
1678 lastCapturingPieceValue = seeValues[pt];
1679 c = opposite_color(c);
1681 // Stop after a king capture
1682 if (pt == KING && (attackers & pieces_of_color(c)))
1685 swapList[n++] = 100;
1688 } while (attackers & pieces_of_color(c));
1690 // Having built the swap list, we negamax through it to find the best
1691 // achievable score from the point of view of the side to move
1693 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1699 /// Position::clear() erases the position object to a pristine state, with an
1700 /// empty board, white to move, and no castling rights.
1702 void Position::clear() {
1704 for (int i = 0; i < 64; i++)
1710 for (int i = 0; i < 2; i++)
1711 byColorBB[i] = EmptyBoardBB;
1713 for (int i = 0; i < 7; i++)
1715 byTypeBB[i] = EmptyBoardBB;
1716 pieceCount[0][i] = pieceCount[1][i] = 0;
1717 for (int j = 0; j < 8; j++)
1718 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1721 checkersBB = EmptyBoardBB;
1723 lastMove = MOVE_NONE;
1726 castleRights = NO_CASTLES;
1727 initialKFile = FILE_E;
1728 initialKRFile = FILE_H;
1729 initialQRFile = FILE_A;
1736 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1737 /// UCI interface code, whenever a non-reversible move is made in a
1738 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1739 /// for the program to handle games of arbitrary length, as long as the GUI
1740 /// handles draws by the 50 move rule correctly.
1742 void Position::reset_game_ply() {
1748 /// Position::put_piece() puts a piece on the given square of the board,
1749 /// updating the board array, bitboards, and piece counts.
1751 void Position::put_piece(Piece p, Square s) {
1753 Color c = color_of_piece(p);
1754 PieceType pt = type_of_piece(p);
1757 index[s] = pieceCount[c][pt];
1758 pieceList[c][pt][index[s]] = s;
1760 set_bit(&(byTypeBB[pt]), s);
1761 set_bit(&(byColorBB[c]), s);
1762 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1764 pieceCount[c][pt]++;
1771 /// Position::allow_oo() gives the given side the right to castle kingside.
1772 /// Used when setting castling rights during parsing of FEN strings.
1774 void Position::allow_oo(Color c) {
1776 castleRights |= (1 + int(c));
1780 /// Position::allow_ooo() gives the given side the right to castle queenside.
1781 /// Used when setting castling rights during parsing of FEN strings.
1783 void Position::allow_ooo(Color c) {
1785 castleRights |= (4 + 4*int(c));
1789 /// Position::compute_key() computes the hash key of the position. The hash
1790 /// key is usually updated incrementally as moves are made and unmade, the
1791 /// compute_key() function is only used when a new position is set up, and
1792 /// to verify the correctness of the hash key when running in debug mode.
1794 Key Position::compute_key() const {
1796 Key result = Key(0ULL);
1798 for (Square s = SQ_A1; s <= SQ_H8; s++)
1799 if (square_is_occupied(s))
1800 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1802 if (ep_square() != SQ_NONE)
1803 result ^= zobEp[ep_square()];
1805 result ^= zobCastle[castleRights];
1806 if (side_to_move() == BLACK)
1807 result ^= zobSideToMove;
1813 /// Position::compute_pawn_key() computes the hash key of the position. The
1814 /// hash key is usually updated incrementally as moves are made and unmade,
1815 /// the compute_pawn_key() function is only used when a new position is set
1816 /// up, and to verify the correctness of the pawn hash key when running in
1819 Key Position::compute_pawn_key() const {
1821 Key result = Key(0ULL);
1825 for (Color c = WHITE; c <= BLACK; c++)
1830 s = pop_1st_bit(&b);
1831 result ^= zobrist[c][PAWN][s];
1838 /// Position::compute_material_key() computes the hash key of the position.
1839 /// The hash key is usually updated incrementally as moves are made and unmade,
1840 /// the compute_material_key() function is only used when a new position is set
1841 /// up, and to verify the correctness of the material hash key when running in
1844 Key Position::compute_material_key() const {
1846 Key result = Key(0ULL);
1847 for (Color c = WHITE; c <= BLACK; c++)
1848 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1850 int count = piece_count(c, pt);
1851 for (int i = 0; i <= count; i++)
1852 result ^= zobMaterial[c][pt][i];
1858 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1859 /// incremental scores for the middle game and the endgame. These functions
1860 /// are used to initialize the incremental scores when a new position is set
1861 /// up, and to verify that the scores are correctly updated by do_move
1862 /// and undo_move when the program is running in debug mode.
1864 Value Position::compute_mg_value() const {
1866 Value result = Value(0);
1870 for (Color c = WHITE; c <= BLACK; c++)
1871 for (PieceType pt = PAWN; pt <= KING; pt++)
1873 b = pieces_of_color_and_type(c, pt);
1876 s = pop_1st_bit(&b);
1877 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1878 result += mg_pst(c, pt, s);
1881 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1885 Value Position::compute_eg_value() const {
1887 Value result = Value(0);
1891 for (Color c = WHITE; c <= BLACK; c++)
1892 for (PieceType pt = PAWN; pt <= KING; pt++)
1894 b = pieces_of_color_and_type(c, pt);
1897 s = pop_1st_bit(&b);
1898 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1899 result += eg_pst(c, pt, s);
1902 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1907 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1908 /// game material score for the given side. Material scores are updated
1909 /// incrementally during the search, this function is only used while
1910 /// initializing a new Position object.
1912 Value Position::compute_non_pawn_material(Color c) const {
1914 Value result = Value(0);
1917 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1919 Bitboard b = pieces_of_color_and_type(c, pt);
1922 s = pop_1st_bit(&b);
1923 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1924 result += piece_value_midgame(pt);
1931 /// Position::is_mate() returns true or false depending on whether the
1932 /// side to move is checkmated. Note that this function is currently very
1933 /// slow, and shouldn't be used frequently inside the search.
1935 bool Position::is_mate() const {
1939 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1940 return mp.get_next_move() == MOVE_NONE;
1946 /// Position::is_draw() tests whether the position is drawn by material,
1947 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1948 /// must be done by the search.
1950 bool Position::is_draw() const {
1952 // Draw by material?
1954 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1957 // Draw by the 50 moves rule?
1958 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1961 // Draw by repetition?
1962 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1963 if (history[gamePly - i] == key)
1970 /// Position::has_mate_threat() tests whether a given color has a mate in one
1971 /// from the current position. This function is quite slow, but it doesn't
1972 /// matter, because it is currently only called from PV nodes, which are rare.
1974 bool Position::has_mate_threat(Color c) {
1977 Color stm = side_to_move();
1979 // The following lines are useless and silly, but prevents gcc from
1980 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1981 // be used uninitialized.
1982 u1.lastMove = lastMove;
1983 u1.epSquare = epSquare;
1988 // If the input color is not equal to the side to move, do a null move
1992 MoveStack mlist[120];
1994 bool result = false;
1996 // Generate legal moves
1997 count = generate_legal_moves(*this, mlist);
1999 // Loop through the moves, and see if one of them is mate
2000 for (int i = 0; i < count; i++)
2002 do_move(mlist[i].move, u2);
2006 undo_move(mlist[i].move, u2);
2009 // Undo null move, if necessary
2017 /// Position::init_zobrist() is a static member function which initializes the
2018 /// various arrays used to compute hash keys.
2020 void Position::init_zobrist() {
2022 for (int i = 0; i < 2; i++)
2023 for (int j = 0; j < 8; j++)
2024 for (int k = 0; k < 64; k++)
2025 zobrist[i][j][k] = Key(genrand_int64());
2027 for (int i = 0; i < 64; i++)
2028 zobEp[i] = Key(genrand_int64());
2030 for (int i = 0; i < 16; i++)
2031 zobCastle[i] = genrand_int64();
2033 zobSideToMove = genrand_int64();
2035 for (int i = 0; i < 2; i++)
2036 for (int j = 0; j < 8; j++)
2037 for (int k = 0; k < 16; k++)
2038 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2040 for (int i = 0; i < 16; i++)
2041 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2045 /// Position::init_piece_square_tables() initializes the piece square tables.
2046 /// This is a two-step operation: First, the white halves of the tables are
2047 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2048 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2049 /// Second, the black halves of the tables are initialized by mirroring
2050 /// and changing the sign of the corresponding white scores.
2052 void Position::init_piece_square_tables() {
2054 int r = get_option_value_int("Randomness"), i;
2055 for (Square s = SQ_A1; s <= SQ_H8; s++)
2056 for (Piece p = WP; p <= WK; p++)
2058 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2059 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2060 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2063 for (Square s = SQ_A1; s <= SQ_H8; s++)
2064 for (Piece p = BP; p <= BK; p++)
2066 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2067 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2072 /// Position::flipped_copy() makes a copy of the input position, but with
2073 /// the white and black sides reversed. This is only useful for debugging,
2074 /// especially for finding evaluation symmetry bugs.
2076 void Position::flipped_copy(const Position &pos) {
2078 assert(pos.is_ok());
2083 for (Square s = SQ_A1; s <= SQ_H8; s++)
2084 if (!pos.square_is_empty(s))
2085 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2088 sideToMove = opposite_color(pos.side_to_move());
2091 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2092 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2093 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2094 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2096 initialKFile = pos.initialKFile;
2097 initialKRFile = pos.initialKRFile;
2098 initialQRFile = pos.initialQRFile;
2100 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2101 castleRightsMask[sq] = ALL_CASTLES;
2103 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2104 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2105 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2106 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2107 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2108 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2110 // En passant square
2111 if (pos.epSquare != SQ_NONE)
2112 epSquare = flip_square(pos.epSquare);
2118 key = compute_key();
2119 pawnKey = compute_pawn_key();
2120 materialKey = compute_material_key();
2122 // Incremental scores
2123 mgValue = compute_mg_value();
2124 egValue = compute_eg_value();
2127 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2128 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2134 /// Position::is_ok() performs some consitency checks for the position object.
2135 /// This is meant to be helpful when debugging.
2137 bool Position::is_ok(int* failedStep) const {
2139 // What features of the position should be verified?
2140 static const bool debugBitboards = false;
2141 static const bool debugKingCount = false;
2142 static const bool debugKingCapture = false;
2143 static const bool debugCheckerCount = false;
2144 static const bool debugKey = false;
2145 static const bool debugMaterialKey = false;
2146 static const bool debugPawnKey = false;
2147 static const bool debugIncrementalEval = false;
2148 static const bool debugNonPawnMaterial = false;
2149 static const bool debugPieceCounts = false;
2150 static const bool debugPieceList = false;
2152 if (failedStep) *failedStep = 1;
2155 if (!color_is_ok(side_to_move()))
2158 // Are the king squares in the position correct?
2159 if (failedStep) (*failedStep)++;
2160 if (piece_on(king_square(WHITE)) != WK)
2163 if (failedStep) (*failedStep)++;
2164 if (piece_on(king_square(BLACK)) != BK)
2168 if (failedStep) (*failedStep)++;
2169 if (!file_is_ok(initialKRFile))
2172 if (!file_is_ok(initialQRFile))
2175 // Do both sides have exactly one king?
2176 if (failedStep) (*failedStep)++;
2179 int kingCount[2] = {0, 0};
2180 for (Square s = SQ_A1; s <= SQ_H8; s++)
2181 if (type_of_piece_on(s) == KING)
2182 kingCount[color_of_piece_on(s)]++;
2184 if (kingCount[0] != 1 || kingCount[1] != 1)
2188 // Can the side to move capture the opponent's king?
2189 if (failedStep) (*failedStep)++;
2190 if (debugKingCapture)
2192 Color us = side_to_move();
2193 Color them = opposite_color(us);
2194 Square ksq = king_square(them);
2195 if (square_is_attacked(ksq, us))
2199 // Is there more than 2 checkers?
2200 if (failedStep) (*failedStep)++;
2201 if (debugCheckerCount && count_1s(checkersBB) > 2)
2205 if (failedStep) (*failedStep)++;
2208 // The intersection of the white and black pieces must be empty
2209 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2212 // The union of the white and black pieces must be equal to all
2214 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2217 // Separate piece type bitboards must have empty intersections
2218 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2219 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2220 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2224 // En passant square OK?
2225 if (failedStep) (*failedStep)++;
2226 if (ep_square() != SQ_NONE)
2228 // The en passant square must be on rank 6, from the point of view of the
2230 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2235 if (failedStep) (*failedStep)++;
2236 if (debugKey && key != compute_key())
2239 // Pawn hash key OK?
2240 if (failedStep) (*failedStep)++;
2241 if (debugPawnKey && pawnKey != compute_pawn_key())
2244 // Material hash key OK?
2245 if (failedStep) (*failedStep)++;
2246 if (debugMaterialKey && materialKey != compute_material_key())
2249 // Incremental eval OK?
2250 if (failedStep) (*failedStep)++;
2251 if (debugIncrementalEval)
2253 if (mgValue != compute_mg_value())
2256 if (egValue != compute_eg_value())
2260 // Non-pawn material OK?
2261 if (failedStep) (*failedStep)++;
2262 if (debugNonPawnMaterial)
2264 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2267 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2272 if (failedStep) (*failedStep)++;
2273 if (debugPieceCounts)
2274 for (Color c = WHITE; c <= BLACK; c++)
2275 for (PieceType pt = PAWN; pt <= KING; pt++)
2276 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2279 if (failedStep) (*failedStep)++;
2282 for(Color c = WHITE; c <= BLACK; c++)
2283 for(PieceType pt = PAWN; pt <= KING; pt++)
2284 for(int i = 0; i < pieceCount[c][pt]; i++)
2286 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2289 if (index[piece_list(c, pt, i)] != i)
2293 if (failedStep) *failedStep = 0;