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 if (pinned[c] != ~EmptyBoardBB)
330 Square ksq = king_square(c);
331 pinned[c] = hidden_checks<ROOK, true>(c, ksq, p1) | hidden_checks<BISHOP, true>(c, ksq, p2);
332 pinners[c] = p1 | p2;
336 Bitboard Position::pinned_pieces(Color c, Bitboard& p) const {
338 if (pinned[c] == ~EmptyBoardBB)
345 Bitboard Position::discovered_check_candidates(Color c) const {
347 if (dcCandidates[c] != ~EmptyBoardBB)
348 return dcCandidates[c];
351 Square ksq = king_square(opposite_color(c));
352 dcCandidates[c] = hidden_checks<ROOK, false>(c, ksq, dummy) | hidden_checks<BISHOP, false>(c, ksq, dummy);
353 return dcCandidates[c];
356 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
357 /// king) pieces for the given color and for the given pinner type. Or, when
358 /// template parameter FindPinned is false, the pinned pieces of opposite color
359 /// that are, indeed, the pieces candidate for a discovery check.
360 template<PieceType Piece, bool FindPinned>
361 Bitboard Position::hidden_checks(Color c, Square ksq, Bitboard& pinners) const {
364 Bitboard sliders, result = EmptyBoardBB;
366 if (Piece == ROOK) // Resolved at compile time
367 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
369 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
371 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
373 // King blockers are candidate pinned pieces
374 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
376 // Pinners are sliders, not checkers, that give check when
377 // candidate pinned are removed.
378 pinners = (FindPinned ? sliders & ~checkersBB : sliders);
381 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
383 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
385 // Finally for each pinner find the corresponding pinned piece (if same color of king)
386 // or discovery checker (if opposite color) among the candidates.
387 Bitboard p = pinners;
391 result |= (squares_between(s, ksq) & candidate_pinned);
395 pinners = EmptyBoardBB;
401 /// Position::attacks_to() computes a bitboard containing all pieces which
402 /// attacks a given square. There are two versions of this function: One
403 /// which finds attackers of both colors, and one which only finds the
404 /// attackers for one side.
406 Bitboard Position::attacks_to(Square s) const {
408 return (pawn_attacks(BLACK, s) & pawns(WHITE))
409 | (pawn_attacks(WHITE, s) & pawns(BLACK))
410 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
411 | (piece_attacks<ROOK>(s) & rooks_and_queens())
412 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
413 | (piece_attacks<KING>(s) & pieces_of_type(KING));
416 /// Position::piece_attacks_square() tests whether the piece on square f
417 /// attacks square t.
419 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
421 assert(square_is_ok(f));
422 assert(square_is_ok(t));
426 case WP: return pawn_attacks_square(WHITE, f, t);
427 case BP: return pawn_attacks_square(BLACK, f, t);
428 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
429 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
430 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
431 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
432 case WK: case BK: return piece_attacks_square<KING>(f, t);
439 /// Position::move_attacks_square() tests whether a move from the current
440 /// position attacks a given square.
442 bool Position::move_attacks_square(Move m, Square s) const {
444 assert(move_is_ok(m));
445 assert(square_is_ok(s));
447 Square f = move_from(m), t = move_to(m);
449 assert(square_is_occupied(f));
451 if (piece_attacks_square(piece_on(f), t, s))
454 // Move the piece and scan for X-ray attacks behind it
455 Bitboard occ = occupied_squares();
456 Color us = color_of_piece_on(f);
459 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
460 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
462 // If we have attacks we need to verify that are caused by our move
463 // and are not already existent ones.
464 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
468 /// Position::find_checkers() computes the checkersBB bitboard, which
469 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
470 /// currently works by calling Position::attacks_to, which is probably
471 /// inefficient. Consider rewriting this function to use the last move
472 /// played, like in non-bitboard versions of Glaurung.
474 void Position::find_checkers() {
476 Color us = side_to_move();
477 checkersBB = attacks_to(king_square(us), opposite_color(us));
481 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
483 bool Position::pl_move_is_legal(Move m) const {
486 assert(move_is_ok(m));
488 // If we're in check, all pseudo-legal moves are legal, because our
489 // check evasion generator only generates true legal moves.
493 // Castling moves are checked for legality during move generation.
494 if (move_is_castle(m))
497 Color us = side_to_move();
498 Color them = opposite_color(us);
499 Square from = move_from(m);
500 Square ksq = king_square(us);
502 assert(color_of_piece_on(from) == us);
503 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
505 // En passant captures are a tricky special case. Because they are
506 // rather uncommon, we do it simply by testing whether the king is attacked
507 // after the move is made
510 Square to = move_to(m);
511 Square capsq = make_square(square_file(to), square_rank(from));
512 Bitboard b = occupied_squares();
514 assert(to == ep_square());
515 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
516 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
517 assert(piece_on(to) == EMPTY);
520 clear_bit(&b, capsq);
523 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
524 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
527 // If the moving piece is a king, check whether the destination
528 // square is attacked by the opponent.
530 return !(square_is_attacked(move_to(m), them));
532 // A non-king move is legal if and only if it is not pinned or it
533 // is moving along the ray towards or away from the king.
534 return ( !bit_is_set(pinned_pieces(us), from)
535 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
539 /// Position::move_is_check() tests whether a pseudo-legal move is a check
541 bool Position::move_is_check(Move m) const {
544 assert(move_is_ok(m));
546 Color us = side_to_move();
547 Color them = opposite_color(us);
548 Square from = move_from(m);
549 Square to = move_to(m);
550 Square ksq = king_square(them);
551 Bitboard dcCandidates = discovered_check_candidates(us);
553 assert(color_of_piece_on(from) == us);
554 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
556 // Proceed according to the type of the moving piece
557 switch (type_of_piece_on(from))
561 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
564 if ( bit_is_set(dcCandidates, from) // Discovered check?
565 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
568 if (move_promotion(m)) // Promotion with check?
570 Bitboard b = occupied_squares();
573 switch (move_promotion(m))
576 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
578 return bit_is_set(bishop_attacks_bb(to, b), ksq);
580 return bit_is_set(rook_attacks_bb(to, b), ksq);
582 return bit_is_set(queen_attacks_bb(to, b), ksq);
587 // En passant capture with check? We have already handled the case
588 // of direct checks and ordinary discovered check, the only case we
589 // need to handle is the unusual case of a discovered check through the
591 else if (move_is_ep(m))
593 Square capsq = make_square(square_file(to), square_rank(from));
594 Bitboard b = occupied_squares();
596 clear_bit(&b, capsq);
598 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
599 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
604 return bit_is_set(dcCandidates, from) // Discovered check?
605 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
608 return bit_is_set(dcCandidates, from) // Discovered check?
609 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
612 return bit_is_set(dcCandidates, from) // Discovered check?
613 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
616 // Discovered checks are impossible!
617 assert(!bit_is_set(dcCandidates, from));
618 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
622 if ( bit_is_set(dcCandidates, from)
623 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
626 // Castling with check?
627 if (move_is_castle(m))
629 Square kfrom, kto, rfrom, rto;
630 Bitboard b = occupied_squares();
636 kto = relative_square(us, SQ_G1);
637 rto = relative_square(us, SQ_F1);
639 kto = relative_square(us, SQ_C1);
640 rto = relative_square(us, SQ_D1);
642 clear_bit(&b, kfrom);
643 clear_bit(&b, rfrom);
646 return bit_is_set(rook_attacks_bb(rto, b), ksq);
650 default: // NO_PIECE_TYPE
658 /// Position::move_is_capture() tests whether a move from the current
659 /// position is a capture. Move must not be MOVE_NONE.
661 bool Position::move_is_capture(Move m) const {
663 assert(m != MOVE_NONE);
665 return ( !square_is_empty(move_to(m))
666 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
672 /// Position::backup() is called when making a move. All information
673 /// necessary to restore the position when the move is later unmade
674 /// is saved to an UndoInfo object. The function Position::restore
675 /// does the reverse operation: When one does a backup followed by
676 /// a restore with the same UndoInfo object, the position is restored
677 /// to the state before backup was called.
679 void Position::backup(UndoInfo& u) const {
681 u.castleRights = castleRights;
682 u.epSquare = epSquare;
683 u.checkersBB = checkersBB;
686 u.materialKey = materialKey;
688 u.lastMove = lastMove;
691 u.capture = NO_PIECE_TYPE;
693 for (Color c = WHITE; c <= BLACK; c++)
695 u.pinners[c] = pinners[c];
696 u.pinned[c] = pinned[c];
697 u.dcCandidates[c] = dcCandidates[c];
702 /// Position::restore() is called when unmaking a move. It copies back
703 /// the information backed up during a previous call to Position::backup.
705 void Position::restore(const UndoInfo& u) {
707 castleRights = u.castleRights;
708 epSquare = u.epSquare;
709 checkersBB = u.checkersBB;
712 materialKey = u.materialKey;
714 lastMove = u.lastMove;
717 // u.capture is restored in undo_move()
719 for (Color c = WHITE; c <= BLACK; c++)
721 pinners[c] = u.pinners[c];
722 pinned[c] = u.pinned[c];
723 dcCandidates[c] = u.dcCandidates[c];
728 /// Position::update_checkers() is a private method to udpate chekers info
730 template<PieceType Piece>
731 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
732 Square to, Bitboard dcCandidates) {
734 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
735 set_bit(pCheckersBB, to);
737 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
740 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
743 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
748 /// Position::do_move() makes a move, and backs up all information necessary
749 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
750 /// Pseudo-legal moves should be filtered out before this function is called.
752 void Position::do_move(Move m, UndoInfo& u) {
755 assert(move_is_ok(m));
757 // Get now the current (pre-move) dc candidates that we will use
758 // in update_checkers().
759 Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
761 // Back up the necessary information to our UndoInfo object (except the
762 // captured piece, which is taken care of later.
765 // Save the current key to the history[] array, in order to be able to
766 // detect repetition draws.
767 history[gamePly] = key;
769 // Increment the 50 moves rule draw counter. Resetting it to zero in the
770 // case of non-reversible moves is taken care of later.
773 // Reset pinned bitboard and its friends
774 for (Color c = WHITE; c <= BLACK; c++)
775 pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
777 if (move_is_castle(m))
779 else if (move_promotion(m))
780 do_promotion_move(m, u);
781 else if (move_is_ep(m))
785 Color us = side_to_move();
786 Color them = opposite_color(us);
787 Square from = move_from(m);
788 Square to = move_to(m);
790 assert(color_of_piece_on(from) == us);
791 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
793 PieceType piece = type_of_piece_on(from);
794 PieceType capture = type_of_piece_on(to);
799 do_capture_move(m, capture, them, to);
803 clear_bit(&(byColorBB[us]), from);
804 clear_bit(&(byTypeBB[piece]), from);
805 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
806 set_bit(&(byColorBB[us]), to);
807 set_bit(&(byTypeBB[piece]), to);
808 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
809 board[to] = board[from];
813 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
815 // Update incremental scores
816 mgValue -= mg_pst(us, piece, from);
817 mgValue += mg_pst(us, piece, to);
818 egValue -= eg_pst(us, piece, from);
819 egValue += eg_pst(us, piece, to);
821 // If the moving piece was a king, update the king square
825 // Reset en passant square
826 if (epSquare != SQ_NONE)
828 key ^= zobEp[epSquare];
832 // If the moving piece was a pawn do some special extra work
835 // Reset rule 50 draw counter
838 // Update pawn hash key
839 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
841 // Set en passant square, only if moved pawn can be captured
842 if (abs(int(to) - int(from)) == 16)
844 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
845 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
847 epSquare = Square((int(from) + int(to)) / 2);
848 key ^= zobEp[epSquare];
853 // Update piece lists
854 pieceList[us][piece][index[from]] = to;
855 index[to] = index[from];
857 // Update castle rights
858 key ^= zobCastle[castleRights];
859 castleRights &= castleRightsMask[from];
860 castleRights &= castleRightsMask[to];
861 key ^= zobCastle[castleRights];
863 // Update checkers bitboard, piece must be already moved
864 checkersBB = EmptyBoardBB;
865 Square ksq = king_square(them);
868 case PAWN: update_checkers<PAWN>(&checkersBB, ksq, from, to, oldDcCandidates); break;
869 case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, oldDcCandidates); break;
870 case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, oldDcCandidates); break;
871 case ROOK: update_checkers<ROOK>(&checkersBB, ksq, from, to, oldDcCandidates); break;
872 case QUEEN: update_checkers<QUEEN>(&checkersBB, ksq, from, to, oldDcCandidates); break;
873 case KING: update_checkers<KING>(&checkersBB, ksq, from, to, oldDcCandidates); break;
874 default: assert(false); break;
879 key ^= zobSideToMove;
880 sideToMove = opposite_color(sideToMove);
883 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
884 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
890 /// Position::do_capture_move() is a private method used to update captured
891 /// piece info. It is called from the main Position::do_move function.
893 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
895 assert(capture != KING);
897 // Remove captured piece
898 clear_bit(&(byColorBB[them]), to);
899 clear_bit(&(byTypeBB[capture]), to);
902 key ^= zobrist[them][capture][to];
904 // If the captured piece was a pawn, update pawn hash key
906 pawnKey ^= zobrist[them][PAWN][to];
908 // Update incremental scores
909 mgValue -= mg_pst(them, capture, to);
910 egValue -= eg_pst(them, capture, to);
912 assert(!move_promotion(m) || capture != PAWN);
916 npMaterial[them] -= piece_value_midgame(capture);
918 // Update material hash key
919 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
921 // Update piece count
922 pieceCount[them][capture]--;
925 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
926 index[pieceList[them][capture][index[to]]] = index[to];
928 // Reset rule 50 counter
933 /// Position::do_castle_move() is a private method used to make a castling
934 /// move. It is called from the main Position::do_move function. Note that
935 /// castling moves are encoded as "king captures friendly rook" moves, for
936 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
938 void Position::do_castle_move(Move m) {
941 assert(move_is_ok(m));
942 assert(move_is_castle(m));
944 Color us = side_to_move();
945 Color them = opposite_color(us);
947 // Find source squares for king and rook
948 Square kfrom = move_from(m);
949 Square rfrom = move_to(m); // HACK: See comment at beginning of function
952 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
953 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
955 // Find destination squares for king and rook
956 if (rfrom > kfrom) // O-O
958 kto = relative_square(us, SQ_G1);
959 rto = relative_square(us, SQ_F1);
961 kto = relative_square(us, SQ_C1);
962 rto = relative_square(us, SQ_D1);
965 // Remove pieces from source squares
966 clear_bit(&(byColorBB[us]), kfrom);
967 clear_bit(&(byTypeBB[KING]), kfrom);
968 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
969 clear_bit(&(byColorBB[us]), rfrom);
970 clear_bit(&(byTypeBB[ROOK]), rfrom);
971 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
973 // Put pieces on destination squares
974 set_bit(&(byColorBB[us]), kto);
975 set_bit(&(byTypeBB[KING]), kto);
976 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
977 set_bit(&(byColorBB[us]), rto);
978 set_bit(&(byTypeBB[ROOK]), rto);
979 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
981 // Update board array
982 board[kfrom] = board[rfrom] = EMPTY;
983 board[kto] = piece_of_color_and_type(us, KING);
984 board[rto] = piece_of_color_and_type(us, ROOK);
986 // Update king square
987 kingSquare[us] = kto;
989 // Update piece lists
990 pieceList[us][KING][index[kfrom]] = kto;
991 pieceList[us][ROOK][index[rfrom]] = rto;
992 int tmp = index[rfrom];
993 index[kto] = index[kfrom];
996 // Update incremental scores
997 mgValue -= mg_pst(us, KING, kfrom);
998 mgValue += mg_pst(us, KING, kto);
999 egValue -= eg_pst(us, KING, kfrom);
1000 egValue += eg_pst(us, KING, kto);
1001 mgValue -= mg_pst(us, ROOK, rfrom);
1002 mgValue += mg_pst(us, ROOK, rto);
1003 egValue -= eg_pst(us, ROOK, rfrom);
1004 egValue += eg_pst(us, ROOK, rto);
1007 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1008 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1010 // Clear en passant square
1011 if (epSquare != SQ_NONE)
1013 key ^= zobEp[epSquare];
1017 // Update castling rights
1018 key ^= zobCastle[castleRights];
1019 castleRights &= castleRightsMask[kfrom];
1020 key ^= zobCastle[castleRights];
1022 // Reset rule 50 counter
1025 // Update checkers BB
1026 checkersBB = attacks_to(king_square(them), us);
1030 /// Position::do_promotion_move() is a private method used to make a promotion
1031 /// move. It is called from the main Position::do_move function. The
1032 /// UndoInfo object, which has been initialized in Position::do_move, is
1033 /// used to store the captured piece (if any).
1035 void Position::do_promotion_move(Move m, UndoInfo &u) {
1039 PieceType capture, promotion;
1042 assert(move_is_ok(m));
1043 assert(move_promotion(m));
1045 us = side_to_move();
1046 them = opposite_color(us);
1047 from = move_from(m);
1050 assert(relative_rank(us, to) == RANK_8);
1051 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1052 assert(color_of_piece_on(to) == them || square_is_empty(to));
1054 capture = type_of_piece_on(to);
1058 u.capture = capture;
1059 do_capture_move(m, capture, them, to);
1063 clear_bit(&(byColorBB[us]), from);
1064 clear_bit(&(byTypeBB[PAWN]), from);
1065 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1066 board[from] = EMPTY;
1068 // Insert promoted piece
1069 promotion = move_promotion(m);
1070 assert(promotion >= KNIGHT && promotion <= QUEEN);
1071 set_bit(&(byColorBB[us]), to);
1072 set_bit(&(byTypeBB[promotion]), to);
1073 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1074 board[to] = piece_of_color_and_type(us, promotion);
1077 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1079 // Update pawn hash key
1080 pawnKey ^= zobrist[us][PAWN][from];
1082 // Update material key
1083 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1084 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1086 // Update piece counts
1087 pieceCount[us][PAWN]--;
1088 pieceCount[us][promotion]++;
1090 // Update piece lists
1091 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1092 index[pieceList[us][PAWN][index[from]]] = index[from];
1093 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1094 index[to] = pieceCount[us][promotion] - 1;
1096 // Update incremental scores
1097 mgValue -= mg_pst(us, PAWN, from);
1098 mgValue += mg_pst(us, promotion, to);
1099 egValue -= eg_pst(us, PAWN, from);
1100 egValue += eg_pst(us, promotion, to);
1103 npMaterial[us] += piece_value_midgame(promotion);
1105 // Clear the en passant square
1106 if (epSquare != SQ_NONE)
1108 key ^= zobEp[epSquare];
1112 // Update castle rights
1113 key ^= zobCastle[castleRights];
1114 castleRights &= castleRightsMask[to];
1115 key ^= zobCastle[castleRights];
1117 // Reset rule 50 counter
1120 // Update checkers BB
1121 checkersBB = attacks_to(king_square(them), us);
1125 /// Position::do_ep_move() is a private method used to make an en passant
1126 /// capture. It is called from the main Position::do_move function. Because
1127 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1128 /// object in which to store the captured piece.
1130 void Position::do_ep_move(Move m) {
1133 Square from, to, capsq;
1136 assert(move_is_ok(m));
1137 assert(move_is_ep(m));
1139 us = side_to_move();
1140 them = opposite_color(us);
1141 from = move_from(m);
1143 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1145 assert(to == epSquare);
1146 assert(relative_rank(us, to) == RANK_6);
1147 assert(piece_on(to) == EMPTY);
1148 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1149 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1151 // Remove captured piece
1152 clear_bit(&(byColorBB[them]), capsq);
1153 clear_bit(&(byTypeBB[PAWN]), capsq);
1154 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1155 board[capsq] = EMPTY;
1157 // Remove moving piece from source square
1158 clear_bit(&(byColorBB[us]), from);
1159 clear_bit(&(byTypeBB[PAWN]), from);
1160 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1162 // Put moving piece on destination square
1163 set_bit(&(byColorBB[us]), to);
1164 set_bit(&(byTypeBB[PAWN]), to);
1165 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1166 board[to] = board[from];
1167 board[from] = EMPTY;
1169 // Update material hash key
1170 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1172 // Update piece count
1173 pieceCount[them][PAWN]--;
1175 // Update piece list
1176 pieceList[us][PAWN][index[from]] = to;
1177 index[to] = index[from];
1178 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1179 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1182 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1183 key ^= zobrist[them][PAWN][capsq];
1184 key ^= zobEp[epSquare];
1186 // Update pawn hash key
1187 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1188 pawnKey ^= zobrist[them][PAWN][capsq];
1190 // Update incremental scores
1191 mgValue -= mg_pst(them, PAWN, capsq);
1192 mgValue -= mg_pst(us, PAWN, from);
1193 mgValue += mg_pst(us, PAWN, to);
1194 egValue -= eg_pst(them, PAWN, capsq);
1195 egValue -= eg_pst(us, PAWN, from);
1196 egValue += eg_pst(us, PAWN, to);
1198 // Reset en passant square
1201 // Reset rule 50 counter
1204 // Update checkers BB
1205 checkersBB = attacks_to(king_square(them), us);
1209 /// Position::undo_move() unmakes a move. When it returns, the position should
1210 /// be restored to exactly the same state as before the move was made. It is
1211 /// important that Position::undo_move is called with the same move and UndoInfo
1212 /// object as the earlier call to Position::do_move.
1214 void Position::undo_move(Move m, const UndoInfo &u) {
1217 assert(move_is_ok(m));
1220 sideToMove = opposite_color(sideToMove);
1222 // Restore information from our UndoInfo object (except the captured piece,
1223 // which is taken care of later)
1226 if (move_is_castle(m))
1227 undo_castle_move(m);
1228 else if (move_promotion(m))
1229 undo_promotion_move(m, u);
1230 else if (move_is_ep(m))
1236 PieceType piece, capture;
1238 us = side_to_move();
1239 them = opposite_color(us);
1240 from = move_from(m);
1243 assert(piece_on(from) == EMPTY);
1244 assert(color_of_piece_on(to) == us);
1246 // Put the piece back at the source square
1247 piece = type_of_piece_on(to);
1248 set_bit(&(byColorBB[us]), from);
1249 set_bit(&(byTypeBB[piece]), from);
1250 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1251 board[from] = piece_of_color_and_type(us, piece);
1253 // Clear the destination square
1254 clear_bit(&(byColorBB[us]), to);
1255 clear_bit(&(byTypeBB[piece]), to);
1256 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1258 // If the moving piece was a king, update the king square
1260 kingSquare[us] = from;
1262 // Update piece list
1263 pieceList[us][piece][index[to]] = from;
1264 index[from] = index[to];
1266 capture = u.capture;
1270 assert(capture != KING);
1272 // Replace the captured piece
1273 set_bit(&(byColorBB[them]), to);
1274 set_bit(&(byTypeBB[capture]), to);
1275 set_bit(&(byTypeBB[0]), to);
1276 board[to] = piece_of_color_and_type(them, capture);
1279 if (capture != PAWN)
1280 npMaterial[them] += piece_value_midgame(capture);
1282 // Update piece list
1283 pieceList[them][capture][pieceCount[them][capture]] = to;
1284 index[to] = pieceCount[them][capture];
1286 // Update piece count
1287 pieceCount[them][capture]++;
1296 /// Position::undo_castle_move() is a private method used to unmake a castling
1297 /// move. It is called from the main Position::undo_move function. Note that
1298 /// castling moves are encoded as "king captures friendly rook" moves, for
1299 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1301 void Position::undo_castle_move(Move m) {
1303 assert(move_is_ok(m));
1304 assert(move_is_castle(m));
1306 // When we have arrived here, some work has already been done by
1307 // Position::undo_move. In particular, the side to move has been switched,
1308 // so the code below is correct.
1309 Color us = side_to_move();
1311 // Find source squares for king and rook
1312 Square kfrom = move_from(m);
1313 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1316 // Find destination squares for king and rook
1317 if (rfrom > kfrom) // O-O
1319 kto = relative_square(us, SQ_G1);
1320 rto = relative_square(us, SQ_F1);
1322 kto = relative_square(us, SQ_C1);
1323 rto = relative_square(us, SQ_D1);
1326 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1327 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1329 // Remove pieces from destination squares
1330 clear_bit(&(byColorBB[us]), kto);
1331 clear_bit(&(byTypeBB[KING]), kto);
1332 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1333 clear_bit(&(byColorBB[us]), rto);
1334 clear_bit(&(byTypeBB[ROOK]), rto);
1335 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1337 // Put pieces on source squares
1338 set_bit(&(byColorBB[us]), kfrom);
1339 set_bit(&(byTypeBB[KING]), kfrom);
1340 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1341 set_bit(&(byColorBB[us]), rfrom);
1342 set_bit(&(byTypeBB[ROOK]), rfrom);
1343 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1346 board[rto] = board[kto] = EMPTY;
1347 board[rfrom] = piece_of_color_and_type(us, ROOK);
1348 board[kfrom] = piece_of_color_and_type(us, KING);
1350 // Update king square
1351 kingSquare[us] = kfrom;
1353 // Update piece lists
1354 pieceList[us][KING][index[kto]] = kfrom;
1355 pieceList[us][ROOK][index[rto]] = rfrom;
1356 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1357 index[kfrom] = index[kto];
1362 /// Position::undo_promotion_move() is a private method used to unmake a
1363 /// promotion move. It is called from the main Position::do_move
1364 /// function. The UndoInfo object, which has been initialized in
1365 /// Position::do_move, is used to put back the captured piece (if any).
1367 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1371 PieceType capture, promotion;
1373 assert(move_is_ok(m));
1374 assert(move_promotion(m));
1376 // When we have arrived here, some work has already been done by
1377 // Position::undo_move. In particular, the side to move has been switched,
1378 // so the code below is correct.
1379 us = side_to_move();
1380 them = opposite_color(us);
1381 from = move_from(m);
1384 assert(relative_rank(us, to) == RANK_8);
1385 assert(piece_on(from) == EMPTY);
1387 // Remove promoted piece
1388 promotion = move_promotion(m);
1389 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1390 assert(promotion >= KNIGHT && promotion <= QUEEN);
1391 clear_bit(&(byColorBB[us]), to);
1392 clear_bit(&(byTypeBB[promotion]), to);
1393 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1395 // Insert pawn at source square
1396 set_bit(&(byColorBB[us]), from);
1397 set_bit(&(byTypeBB[PAWN]), from);
1398 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1399 board[from] = piece_of_color_and_type(us, PAWN);
1402 npMaterial[us] -= piece_value_midgame(promotion);
1404 // Update piece list
1405 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1406 index[from] = pieceCount[us][PAWN];
1407 pieceList[us][promotion][index[to]] =
1408 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1409 index[pieceList[us][promotion][index[to]]] = index[to];
1411 // Update piece counts
1412 pieceCount[us][promotion]--;
1413 pieceCount[us][PAWN]++;
1415 capture = u.capture;
1419 assert(capture != KING);
1421 // Insert captured piece:
1422 set_bit(&(byColorBB[them]), to);
1423 set_bit(&(byTypeBB[capture]), to);
1424 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1425 board[to] = piece_of_color_and_type(them, capture);
1427 // Update material. Because the move is a promotion move, we know
1428 // that the captured piece cannot be a pawn.
1429 assert(capture != PAWN);
1430 npMaterial[them] += piece_value_midgame(capture);
1432 // Update piece list
1433 pieceList[them][capture][pieceCount[them][capture]] = to;
1434 index[to] = pieceCount[them][capture];
1436 // Update piece count
1437 pieceCount[them][capture]++;
1443 /// Position::undo_ep_move() is a private method used to unmake an en passant
1444 /// capture. It is called from the main Position::undo_move function. Because
1445 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1446 /// object from which to retrieve the captured piece.
1448 void Position::undo_ep_move(Move m) {
1450 assert(move_is_ok(m));
1451 assert(move_is_ep(m));
1453 // When we have arrived here, some work has already been done by
1454 // Position::undo_move. In particular, the side to move has been switched,
1455 // so the code below is correct.
1456 Color us = side_to_move();
1457 Color them = opposite_color(us);
1458 Square from = move_from(m);
1459 Square to = move_to(m);
1460 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1462 assert(to == ep_square());
1463 assert(relative_rank(us, to) == RANK_6);
1464 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1465 assert(piece_on(from) == EMPTY);
1466 assert(piece_on(capsq) == EMPTY);
1468 // Replace captured piece
1469 set_bit(&(byColorBB[them]), capsq);
1470 set_bit(&(byTypeBB[PAWN]), capsq);
1471 set_bit(&(byTypeBB[0]), capsq);
1472 board[capsq] = piece_of_color_and_type(them, PAWN);
1474 // Remove moving piece from destination square
1475 clear_bit(&(byColorBB[us]), to);
1476 clear_bit(&(byTypeBB[PAWN]), to);
1477 clear_bit(&(byTypeBB[0]), to);
1480 // Replace moving piece at source square
1481 set_bit(&(byColorBB[us]), from);
1482 set_bit(&(byTypeBB[PAWN]), from);
1483 set_bit(&(byTypeBB[0]), from);
1484 board[from] = piece_of_color_and_type(us, PAWN);
1486 // Update piece list:
1487 pieceList[us][PAWN][index[to]] = from;
1488 index[from] = index[to];
1489 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1490 index[capsq] = pieceCount[them][PAWN];
1492 // Update piece count:
1493 pieceCount[them][PAWN]++;
1497 /// Position::do_null_move makes() a "null move": It switches the side to move
1498 /// and updates the hash key without executing any move on the board.
1500 void Position::do_null_move(UndoInfo& u) {
1503 assert(!is_check());
1505 // Back up the information necessary to undo the null move to the supplied
1506 // UndoInfo object. In the case of a null move, the only thing we need to
1507 // remember is the last move made and the en passant square.
1508 u.lastMove = lastMove;
1509 u.epSquare = epSquare;
1511 // Save the current key to the history[] array, in order to be able to
1512 // detect repetition draws.
1513 history[gamePly] = key;
1515 // Update the necessary information
1516 sideToMove = opposite_color(sideToMove);
1517 if (epSquare != SQ_NONE)
1518 key ^= zobEp[epSquare];
1523 key ^= zobSideToMove;
1525 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1526 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1532 /// Position::undo_null_move() unmakes a "null move".
1534 void Position::undo_null_move(const UndoInfo &u) {
1537 assert(!is_check());
1539 // Restore information from the supplied UndoInfo object:
1540 lastMove = u.lastMove;
1541 epSquare = u.epSquare;
1542 if (epSquare != SQ_NONE)
1543 key ^= zobEp[epSquare];
1545 // Update the necessary information.
1546 sideToMove = opposite_color(sideToMove);
1549 key ^= zobSideToMove;
1551 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1552 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1558 /// Position::see() is a static exchange evaluator: It tries to estimate the
1559 /// material gain or loss resulting from a move. There are three versions of
1560 /// this function: One which takes a destination square as input, one takes a
1561 /// move, and one which takes a 'from' and a 'to' square. The function does
1562 /// not yet understand promotions captures.
1564 int Position::see(Square to) const {
1566 assert(square_is_ok(to));
1567 return see(SQ_NONE, to);
1570 int Position::see(Move m) const {
1572 assert(move_is_ok(m));
1573 return see(move_from(m), move_to(m));
1576 int Position::see(Square from, Square to) const {
1579 static const int seeValues[18] = {
1580 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1581 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1582 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1583 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1587 Bitboard attackers, occ, b;
1589 assert(square_is_ok(from) || from == SQ_NONE);
1590 assert(square_is_ok(to));
1592 // Initialize colors
1593 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1594 Color them = opposite_color(us);
1596 // Initialize pieces
1597 Piece piece = piece_on(from);
1598 Piece capture = piece_on(to);
1600 // Find all attackers to the destination square, with the moving piece
1601 // removed, but possibly an X-ray attacker added behind it.
1602 occ = occupied_squares();
1604 // Handle en passant moves
1605 if (epSquare == to && type_of_piece_on(from) == PAWN)
1607 assert(capture == EMPTY);
1609 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1610 capture = piece_on(capQq);
1612 assert(type_of_piece_on(capQq) == PAWN);
1614 // Remove the captured pawn
1615 clear_bit(&occ, capQq);
1620 clear_bit(&occ, from);
1621 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1622 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1623 | (piece_attacks<KNIGHT>(to) & knights())
1624 | (piece_attacks<KING>(to) & kings())
1625 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1626 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1628 if (from != SQ_NONE)
1631 // If we don't have any attacker we are finished
1632 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1635 // Locate the least valuable attacker to the destination square
1636 // and use it to initialize from square.
1638 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1641 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1642 piece = piece_on(from);
1645 // If the opponent has no attackers we are finished
1646 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1647 return seeValues[capture];
1649 attackers &= occ; // Remove the moving piece
1651 // The destination square is defended, which makes things rather more
1652 // difficult to compute. We proceed by building up a "swap list" containing
1653 // the material gain or loss at each stop in a sequence of captures to the
1654 // destination square, where the sides alternately capture, and always
1655 // capture with the least valuable piece. After each capture, we look for
1656 // new X-ray attacks from behind the capturing piece.
1657 int lastCapturingPieceValue = seeValues[piece];
1658 int swapList[32], n = 1;
1662 swapList[0] = seeValues[capture];
1665 // Locate the least valuable attacker for the side to move. The loop
1666 // below looks like it is potentially infinite, but it isn't. We know
1667 // that the side to move still has at least one attacker left.
1668 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1671 // Remove the attacker we just found from the 'attackers' bitboard,
1672 // and scan for new X-ray attacks behind the attacker.
1673 b = attackers & pieces_of_color_and_type(c, pt);
1675 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1676 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1680 // Add the new entry to the swap list
1682 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1685 // Remember the value of the capturing piece, and change the side to move
1686 // before beginning the next iteration
1687 lastCapturingPieceValue = seeValues[pt];
1688 c = opposite_color(c);
1690 // Stop after a king capture
1691 if (pt == KING && (attackers & pieces_of_color(c)))
1694 swapList[n++] = 100;
1697 } while (attackers & pieces_of_color(c));
1699 // Having built the swap list, we negamax through it to find the best
1700 // achievable score from the point of view of the side to move
1702 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1708 /// Position::clear() erases the position object to a pristine state, with an
1709 /// empty board, white to move, and no castling rights.
1711 void Position::clear() {
1713 for (int i = 0; i < 64; i++)
1719 for (int i = 0; i < 2; i++)
1720 byColorBB[i] = EmptyBoardBB;
1722 for (int i = 0; i < 7; i++)
1724 byTypeBB[i] = EmptyBoardBB;
1725 pieceCount[0][i] = pieceCount[1][i] = 0;
1726 for (int j = 0; j < 8; j++)
1727 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1730 checkersBB = EmptyBoardBB;
1731 for (Color c = WHITE; c <= BLACK; c++)
1732 pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
1734 lastMove = MOVE_NONE;
1737 castleRights = NO_CASTLES;
1738 initialKFile = FILE_E;
1739 initialKRFile = FILE_H;
1740 initialQRFile = FILE_A;
1747 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1748 /// UCI interface code, whenever a non-reversible move is made in a
1749 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1750 /// for the program to handle games of arbitrary length, as long as the GUI
1751 /// handles draws by the 50 move rule correctly.
1753 void Position::reset_game_ply() {
1759 /// Position::put_piece() puts a piece on the given square of the board,
1760 /// updating the board array, bitboards, and piece counts.
1762 void Position::put_piece(Piece p, Square s) {
1764 Color c = color_of_piece(p);
1765 PieceType pt = type_of_piece(p);
1768 index[s] = pieceCount[c][pt];
1769 pieceList[c][pt][index[s]] = s;
1771 set_bit(&(byTypeBB[pt]), s);
1772 set_bit(&(byColorBB[c]), s);
1773 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1775 pieceCount[c][pt]++;
1782 /// Position::allow_oo() gives the given side the right to castle kingside.
1783 /// Used when setting castling rights during parsing of FEN strings.
1785 void Position::allow_oo(Color c) {
1787 castleRights |= (1 + int(c));
1791 /// Position::allow_ooo() gives the given side the right to castle queenside.
1792 /// Used when setting castling rights during parsing of FEN strings.
1794 void Position::allow_ooo(Color c) {
1796 castleRights |= (4 + 4*int(c));
1800 /// Position::compute_key() computes the hash key of the position. The hash
1801 /// key is usually updated incrementally as moves are made and unmade, the
1802 /// compute_key() function is only used when a new position is set up, and
1803 /// to verify the correctness of the hash key when running in debug mode.
1805 Key Position::compute_key() const {
1807 Key result = Key(0ULL);
1809 for (Square s = SQ_A1; s <= SQ_H8; s++)
1810 if (square_is_occupied(s))
1811 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1813 if (ep_square() != SQ_NONE)
1814 result ^= zobEp[ep_square()];
1816 result ^= zobCastle[castleRights];
1817 if (side_to_move() == BLACK)
1818 result ^= zobSideToMove;
1824 /// Position::compute_pawn_key() computes the hash key of the position. The
1825 /// hash key is usually updated incrementally as moves are made and unmade,
1826 /// the compute_pawn_key() function is only used when a new position is set
1827 /// up, and to verify the correctness of the pawn hash key when running in
1830 Key Position::compute_pawn_key() const {
1832 Key result = Key(0ULL);
1836 for (Color c = WHITE; c <= BLACK; c++)
1841 s = pop_1st_bit(&b);
1842 result ^= zobrist[c][PAWN][s];
1849 /// Position::compute_material_key() computes the hash key of the position.
1850 /// The hash key is usually updated incrementally as moves are made and unmade,
1851 /// the compute_material_key() function is only used when a new position is set
1852 /// up, and to verify the correctness of the material hash key when running in
1855 Key Position::compute_material_key() const {
1857 Key result = Key(0ULL);
1858 for (Color c = WHITE; c <= BLACK; c++)
1859 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1861 int count = piece_count(c, pt);
1862 for (int i = 0; i <= count; i++)
1863 result ^= zobMaterial[c][pt][i];
1869 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1870 /// incremental scores for the middle game and the endgame. These functions
1871 /// are used to initialize the incremental scores when a new position is set
1872 /// up, and to verify that the scores are correctly updated by do_move
1873 /// and undo_move when the program is running in debug mode.
1875 Value Position::compute_mg_value() const {
1877 Value result = Value(0);
1881 for (Color c = WHITE; c <= BLACK; c++)
1882 for (PieceType pt = PAWN; pt <= KING; pt++)
1884 b = pieces_of_color_and_type(c, pt);
1887 s = pop_1st_bit(&b);
1888 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1889 result += mg_pst(c, pt, s);
1892 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1896 Value Position::compute_eg_value() const {
1898 Value result = Value(0);
1902 for (Color c = WHITE; c <= BLACK; c++)
1903 for (PieceType pt = PAWN; pt <= KING; pt++)
1905 b = pieces_of_color_and_type(c, pt);
1908 s = pop_1st_bit(&b);
1909 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1910 result += eg_pst(c, pt, s);
1913 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1918 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1919 /// game material score for the given side. Material scores are updated
1920 /// incrementally during the search, this function is only used while
1921 /// initializing a new Position object.
1923 Value Position::compute_non_pawn_material(Color c) const {
1925 Value result = Value(0);
1928 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1930 Bitboard b = pieces_of_color_and_type(c, pt);
1933 s = pop_1st_bit(&b);
1934 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1935 result += piece_value_midgame(pt);
1942 /// Position::is_mate() returns true or false depending on whether the
1943 /// side to move is checkmated. Note that this function is currently very
1944 /// slow, and shouldn't be used frequently inside the search.
1946 bool Position::is_mate() const {
1950 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1951 return mp.get_next_move() == MOVE_NONE;
1957 /// Position::is_draw() tests whether the position is drawn by material,
1958 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1959 /// must be done by the search.
1961 bool Position::is_draw() const {
1963 // Draw by material?
1965 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1968 // Draw by the 50 moves rule?
1969 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1972 // Draw by repetition?
1973 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1974 if (history[gamePly - i] == key)
1981 /// Position::has_mate_threat() tests whether a given color has a mate in one
1982 /// from the current position. This function is quite slow, but it doesn't
1983 /// matter, because it is currently only called from PV nodes, which are rare.
1985 bool Position::has_mate_threat(Color c) {
1988 Color stm = side_to_move();
1990 // The following lines are useless and silly, but prevents gcc from
1991 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1992 // be used uninitialized.
1993 u1.lastMove = lastMove;
1994 u1.epSquare = epSquare;
1999 // If the input color is not equal to the side to move, do a null move
2003 MoveStack mlist[120];
2005 bool result = false;
2007 // Generate legal moves
2008 count = generate_legal_moves(*this, mlist);
2010 // Loop through the moves, and see if one of them is mate
2011 for (int i = 0; i < count; i++)
2013 do_move(mlist[i].move, u2);
2017 undo_move(mlist[i].move, u2);
2020 // Undo null move, if necessary
2028 /// Position::init_zobrist() is a static member function which initializes the
2029 /// various arrays used to compute hash keys.
2031 void Position::init_zobrist() {
2033 for (int i = 0; i < 2; i++)
2034 for (int j = 0; j < 8; j++)
2035 for (int k = 0; k < 64; k++)
2036 zobrist[i][j][k] = Key(genrand_int64());
2038 for (int i = 0; i < 64; i++)
2039 zobEp[i] = Key(genrand_int64());
2041 for (int i = 0; i < 16; i++)
2042 zobCastle[i] = genrand_int64();
2044 zobSideToMove = genrand_int64();
2046 for (int i = 0; i < 2; i++)
2047 for (int j = 0; j < 8; j++)
2048 for (int k = 0; k < 16; k++)
2049 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2051 for (int i = 0; i < 16; i++)
2052 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2056 /// Position::init_piece_square_tables() initializes the piece square tables.
2057 /// This is a two-step operation: First, the white halves of the tables are
2058 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2059 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2060 /// Second, the black halves of the tables are initialized by mirroring
2061 /// and changing the sign of the corresponding white scores.
2063 void Position::init_piece_square_tables() {
2065 int r = get_option_value_int("Randomness"), i;
2066 for (Square s = SQ_A1; s <= SQ_H8; s++)
2067 for (Piece p = WP; p <= WK; p++)
2069 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2070 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2071 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2074 for (Square s = SQ_A1; s <= SQ_H8; s++)
2075 for (Piece p = BP; p <= BK; p++)
2077 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2078 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2083 /// Position::flipped_copy() makes a copy of the input position, but with
2084 /// the white and black sides reversed. This is only useful for debugging,
2085 /// especially for finding evaluation symmetry bugs.
2087 void Position::flipped_copy(const Position &pos) {
2089 assert(pos.is_ok());
2094 for (Square s = SQ_A1; s <= SQ_H8; s++)
2095 if (!pos.square_is_empty(s))
2096 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2099 sideToMove = opposite_color(pos.side_to_move());
2102 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2103 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2104 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2105 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2107 initialKFile = pos.initialKFile;
2108 initialKRFile = pos.initialKRFile;
2109 initialQRFile = pos.initialQRFile;
2111 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2112 castleRightsMask[sq] = ALL_CASTLES;
2114 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2115 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2116 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2117 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2118 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2119 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2121 // En passant square
2122 if (pos.epSquare != SQ_NONE)
2123 epSquare = flip_square(pos.epSquare);
2129 key = compute_key();
2130 pawnKey = compute_pawn_key();
2131 materialKey = compute_material_key();
2133 // Incremental scores
2134 mgValue = compute_mg_value();
2135 egValue = compute_eg_value();
2138 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2139 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2145 /// Position::is_ok() performs some consitency checks for the position object.
2146 /// This is meant to be helpful when debugging.
2148 bool Position::is_ok(int* failedStep) const {
2150 // What features of the position should be verified?
2151 static const bool debugBitboards = false;
2152 static const bool debugKingCount = false;
2153 static const bool debugKingCapture = false;
2154 static const bool debugCheckerCount = false;
2155 static const bool debugKey = false;
2156 static const bool debugMaterialKey = false;
2157 static const bool debugPawnKey = false;
2158 static const bool debugIncrementalEval = false;
2159 static const bool debugNonPawnMaterial = false;
2160 static const bool debugPieceCounts = false;
2161 static const bool debugPieceList = false;
2163 if (failedStep) *failedStep = 1;
2166 if (!color_is_ok(side_to_move()))
2169 // Are the king squares in the position correct?
2170 if (failedStep) (*failedStep)++;
2171 if (piece_on(king_square(WHITE)) != WK)
2174 if (failedStep) (*failedStep)++;
2175 if (piece_on(king_square(BLACK)) != BK)
2179 if (failedStep) (*failedStep)++;
2180 if (!file_is_ok(initialKRFile))
2183 if (!file_is_ok(initialQRFile))
2186 // Do both sides have exactly one king?
2187 if (failedStep) (*failedStep)++;
2190 int kingCount[2] = {0, 0};
2191 for (Square s = SQ_A1; s <= SQ_H8; s++)
2192 if (type_of_piece_on(s) == KING)
2193 kingCount[color_of_piece_on(s)]++;
2195 if (kingCount[0] != 1 || kingCount[1] != 1)
2199 // Can the side to move capture the opponent's king?
2200 if (failedStep) (*failedStep)++;
2201 if (debugKingCapture)
2203 Color us = side_to_move();
2204 Color them = opposite_color(us);
2205 Square ksq = king_square(them);
2206 if (square_is_attacked(ksq, us))
2210 // Is there more than 2 checkers?
2211 if (failedStep) (*failedStep)++;
2212 if (debugCheckerCount && count_1s(checkersBB) > 2)
2216 if (failedStep) (*failedStep)++;
2219 // The intersection of the white and black pieces must be empty
2220 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2223 // The union of the white and black pieces must be equal to all
2225 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2228 // Separate piece type bitboards must have empty intersections
2229 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2230 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2231 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2235 // En passant square OK?
2236 if (failedStep) (*failedStep)++;
2237 if (ep_square() != SQ_NONE)
2239 // The en passant square must be on rank 6, from the point of view of the
2241 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2246 if (failedStep) (*failedStep)++;
2247 if (debugKey && key != compute_key())
2250 // Pawn hash key OK?
2251 if (failedStep) (*failedStep)++;
2252 if (debugPawnKey && pawnKey != compute_pawn_key())
2255 // Material hash key OK?
2256 if (failedStep) (*failedStep)++;
2257 if (debugMaterialKey && materialKey != compute_material_key())
2260 // Incremental eval OK?
2261 if (failedStep) (*failedStep)++;
2262 if (debugIncrementalEval)
2264 if (mgValue != compute_mg_value())
2267 if (egValue != compute_eg_value())
2271 // Non-pawn material OK?
2272 if (failedStep) (*failedStep)++;
2273 if (debugNonPawnMaterial)
2275 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2278 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2283 if (failedStep) (*failedStep)++;
2284 if (debugPieceCounts)
2285 for (Color c = WHITE; c <= BLACK; c++)
2286 for (PieceType pt = PAWN; pt <= KING; pt++)
2287 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2290 if (failedStep) (*failedStep)++;
2293 for(Color c = WHITE; c <= BLACK; c++)
2294 for(PieceType pt = PAWN; pt <= KING; pt++)
2295 for(int i = 0; i < pieceCount[c][pt]; i++)
2297 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2300 if (index[piece_list(c, pt, i)] != i)
2304 if (failedStep) *failedStep = 0;