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(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. Only attacks by the moving piece are
424 /// considered; the function does not handle X-ray attacks.
426 bool Position::move_attacks_square(Move m, Square s) const {
428 assert(move_is_ok(m));
429 assert(square_is_ok(s));
431 Square f = move_from(m), t = move_to(m);
433 assert(square_is_occupied(f));
437 case WP: return pawn_attacks_square(WHITE, t, s);
438 case BP: return pawn_attacks_square(BLACK, t, s);
439 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
440 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
441 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
442 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
443 case WK: case BK: return piece_attacks_square<KING>(t, s);
450 /// Position::find_checkers() computes the checkersBB bitboard, which
451 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
452 /// currently works by calling Position::attacks_to, which is probably
453 /// inefficient. Consider rewriting this function to use the last move
454 /// played, like in non-bitboard versions of Glaurung.
456 void Position::find_checkers() {
458 Color us = side_to_move();
459 checkersBB = attacks_to(king_square(us), opposite_color(us));
463 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
464 /// There are two versions of this function: One which takes only a
465 /// move as input, and one which takes a move and a bitboard of pinned
466 /// pieces. The latter function is faster, and should always be preferred
467 /// when a pinned piece bitboard has already been computed.
469 bool Position::pl_move_is_legal(Move m) const {
471 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
474 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
477 assert(move_is_ok(m));
478 assert(pinned == pinned_pieces(side_to_move()));
480 // If we're in check, all pseudo-legal moves are legal, because our
481 // check evasion generator only generates true legal moves.
485 // Castling moves are checked for legality during move generation.
486 if (move_is_castle(m))
489 Color us = side_to_move();
490 Color them = opposite_color(us);
491 Square from = move_from(m);
492 Square ksq = king_square(us);
494 assert(color_of_piece_on(from) == us);
495 assert(piece_on(ksq) == king_of_color(us));
497 // En passant captures are a tricky special case. Because they are
498 // rather uncommon, we do it simply by testing whether the king is attacked
499 // after the move is made
502 Square to = move_to(m);
503 Square capsq = make_square(square_file(to), square_rank(from));
504 Bitboard b = occupied_squares();
506 assert(to == ep_square());
507 assert(piece_on(from) == pawn_of_color(us));
508 assert(piece_on(capsq) == pawn_of_color(them));
509 assert(piece_on(to) == EMPTY);
512 clear_bit(&b, capsq);
515 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
516 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
519 // If the moving piece is a king, check whether the destination
520 // square is attacked by the opponent.
522 return !(square_is_attacked(move_to(m), them));
524 // A non-king move is legal if and only if it is not pinned or it
525 // is moving along the ray towards or away from the king.
526 return ( !bit_is_set(pinned, from)
527 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
531 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
532 /// There are two versions of this function: One which takes only a move as
533 /// input, and one which takes a move and a bitboard of discovered check
534 /// candidates. The latter function is faster, and should always be preferred
535 /// when a discovered check candidates bitboard has already been computed.
537 bool Position::move_is_check(Move m) const {
539 Bitboard dc = discovered_check_candidates(side_to_move());
540 return move_is_check(m, dc);
543 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
546 assert(move_is_ok(m));
547 assert(dcCandidates == discovered_check_candidates(side_to_move()));
549 Color us = side_to_move();
550 Color them = opposite_color(us);
551 Square from = move_from(m);
552 Square to = move_to(m);
553 Square ksq = king_square(them);
555 assert(color_of_piece_on(from) == us);
556 assert(piece_on(ksq) == king_of_color(them));
558 // Proceed according to the type of the moving piece
559 switch (type_of_piece_on(from))
563 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
566 if ( bit_is_set(dcCandidates, from) // Discovered check?
567 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
570 if (move_promotion(m)) // Promotion with check?
572 Bitboard b = occupied_squares();
575 switch (move_promotion(m))
578 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
580 return bit_is_set(bishop_attacks_bb(to, b), ksq);
582 return bit_is_set(rook_attacks_bb(to, b), ksq);
584 return bit_is_set(queen_attacks_bb(to, b), ksq);
589 // En passant capture with check? We have already handled the case
590 // of direct checks and ordinary discovered check, the only case we
591 // need to handle is the unusual case of a discovered check through the
593 else if (move_is_ep(m))
595 Square capsq = make_square(square_file(to), square_rank(from));
596 Bitboard b = occupied_squares();
598 clear_bit(&b, capsq);
600 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
601 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
606 return bit_is_set(dcCandidates, from) // Discovered check?
607 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
610 return bit_is_set(dcCandidates, from) // Discovered check?
611 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
614 return bit_is_set(dcCandidates, from) // Discovered check?
615 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
618 // Discovered checks are impossible!
619 assert(!bit_is_set(dcCandidates, from));
620 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
624 if ( bit_is_set(dcCandidates, from)
625 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
628 // Castling with check?
629 if (move_is_castle(m))
631 Square kfrom, kto, rfrom, rto;
632 Bitboard b = occupied_squares();
638 kto = relative_square(us, SQ_G1);
639 rto = relative_square(us, SQ_F1);
641 kto = relative_square(us, SQ_C1);
642 rto = relative_square(us, SQ_D1);
644 clear_bit(&b, kfrom);
645 clear_bit(&b, rfrom);
648 return bit_is_set(rook_attacks_bb(rto, b), ksq);
652 default: // NO_PIECE_TYPE
660 /// Position::move_is_capture() tests whether a move from the current
661 /// position is a capture. Move must not be MOVE_NONE.
663 bool Position::move_is_capture(Move m) const {
665 assert(m != MOVE_NONE);
667 return ( !square_is_empty(move_to(m))
668 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
674 /// Position::backup() is called when making a move. All information
675 /// necessary to restore the position when the move is later unmade
676 /// is saved to an UndoInfo object. The function Position::restore
677 /// does the reverse operation: When one does a backup followed by
678 /// a restore with the same UndoInfo object, the position is restored
679 /// to the state before backup was called.
681 void Position::backup(UndoInfo& u) const {
683 u.castleRights = castleRights;
684 u.epSquare = epSquare;
685 u.checkersBB = checkersBB;
688 u.materialKey = materialKey;
690 u.lastMove = lastMove;
693 u.capture = NO_PIECE_TYPE;
697 /// Position::restore() is called when unmaking a move. It copies back
698 /// the information backed up during a previous call to Position::backup.
700 void Position::restore(const UndoInfo& u) {
702 castleRights = u.castleRights;
703 epSquare = u.epSquare;
704 checkersBB = u.checkersBB;
707 materialKey = u.materialKey;
709 lastMove = u.lastMove;
712 // u.capture is restored in undo_move()
716 /// Position::update_checkers() is a private method to udpate chekers info
718 template<PieceType Piece>
719 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
720 Square to, Bitboard dcCandidates) {
722 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
723 set_bit(pCheckersBB, to);
725 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
728 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
731 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
736 /// Position::do_move() makes a move, and backs up all information necessary
737 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
738 /// Pseudo-legal moves should be filtered out before this function is called.
739 /// There are two versions of this function, one which takes only the move and
740 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
741 /// discovered check candidates. The second version is faster, because knowing
742 /// the discovered check candidates makes it easier to update the checkersBB
743 /// member variable in the position object.
745 void Position::do_move(Move m, UndoInfo& u) {
747 do_move(m, u, discovered_check_candidates(side_to_move()));
750 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
753 assert(move_is_ok(m));
755 // Back up the necessary information to our UndoInfo object (except the
756 // captured piece, which is taken care of later.
759 // Save the current key to the history[] array, in order to be able to
760 // detect repetition draws.
761 history[gamePly] = key;
763 // Increment the 50 moves rule draw counter. Resetting it to zero in the
764 // case of non-reversible moves is taken care of later.
767 if (move_is_castle(m))
769 else if (move_promotion(m))
770 do_promotion_move(m, u);
771 else if (move_is_ep(m))
775 Color us = side_to_move();
776 Color them = opposite_color(us);
777 Square from = move_from(m);
778 Square to = move_to(m);
780 assert(color_of_piece_on(from) == us);
781 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
783 PieceType piece = type_of_piece_on(from);
784 PieceType capture = type_of_piece_on(to);
789 do_capture_move(m, capture, them, to);
793 clear_bit(&(byColorBB[us]), from);
794 clear_bit(&(byTypeBB[piece]), from);
795 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
796 set_bit(&(byColorBB[us]), to);
797 set_bit(&(byTypeBB[piece]), to);
798 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
799 board[to] = board[from];
803 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
805 // Update incremental scores
806 mgValue -= mg_pst(us, piece, from);
807 mgValue += mg_pst(us, piece, to);
808 egValue -= eg_pst(us, piece, from);
809 egValue += eg_pst(us, piece, to);
811 // If the moving piece was a king, update the king square
815 // Reset en passant square
816 if (epSquare != SQ_NONE)
818 key ^= zobEp[epSquare];
822 // If the moving piece was a pawn do some special extra work
825 // Reset rule 50 draw counter
828 // Update pawn hash key
829 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
831 // Set en passant square, only if moved pawn can be captured
832 if (abs(int(to) - int(from)) == 16)
834 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
835 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
837 epSquare = Square((int(from) + int(to)) / 2);
838 key ^= zobEp[epSquare];
843 // Update piece lists
844 pieceList[us][piece][index[from]] = to;
845 index[to] = index[from];
847 // Update castle rights
848 key ^= zobCastle[castleRights];
849 castleRights &= castleRightsMask[from];
850 castleRights &= castleRightsMask[to];
851 key ^= zobCastle[castleRights];
853 // Update checkers bitboard, piece must be already moved
854 checkersBB = EmptyBoardBB;
855 Square ksq = king_square(them);
858 case PAWN: update_checkers<PAWN>(&checkersBB, ksq, from, to, dcCandidates); break;
859 case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, dcCandidates); break;
860 case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, dcCandidates); break;
861 case ROOK: update_checkers<ROOK>(&checkersBB, ksq, from, to, dcCandidates); break;
862 case QUEEN: update_checkers<QUEEN>(&checkersBB, ksq, from, to, dcCandidates); break;
863 case KING: update_checkers<KING>(&checkersBB, ksq, from, to, dcCandidates); break;
864 default: assert(false); break;
869 key ^= zobSideToMove;
870 sideToMove = opposite_color(sideToMove);
873 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
874 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
880 /// Position::do_capture_move() is a private method used to update captured
881 /// piece info. It is called from the main Position::do_move function.
883 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
885 assert(capture != KING);
887 // Remove captured piece
888 clear_bit(&(byColorBB[them]), to);
889 clear_bit(&(byTypeBB[capture]), to);
892 key ^= zobrist[them][capture][to];
894 // If the captured piece was a pawn, update pawn hash key
896 pawnKey ^= zobrist[them][PAWN][to];
898 // Update incremental scores
899 mgValue -= mg_pst(them, capture, to);
900 egValue -= eg_pst(them, capture, to);
902 assert(!move_promotion(m) || capture != PAWN);
906 npMaterial[them] -= piece_value_midgame(capture);
908 // Update material hash key
909 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
911 // Update piece count
912 pieceCount[them][capture]--;
915 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
916 index[pieceList[them][capture][index[to]]] = index[to];
918 // Reset rule 50 counter
923 /// Position::do_castle_move() is a private method used to make a castling
924 /// move. It is called from the main Position::do_move function. Note that
925 /// castling moves are encoded as "king captures friendly rook" moves, for
926 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
928 void Position::do_castle_move(Move m) {
931 assert(move_is_ok(m));
932 assert(move_is_castle(m));
934 Color us = side_to_move();
935 Color them = opposite_color(us);
937 // Find source squares for king and rook
938 Square kfrom = move_from(m);
939 Square rfrom = move_to(m); // HACK: See comment at beginning of function
942 assert(piece_on(kfrom) == king_of_color(us));
943 assert(piece_on(rfrom) == rook_of_color(us));
945 // Find destination squares for king and rook
946 if (rfrom > kfrom) // O-O
948 kto = relative_square(us, SQ_G1);
949 rto = relative_square(us, SQ_F1);
951 kto = relative_square(us, SQ_C1);
952 rto = relative_square(us, SQ_D1);
955 // Remove pieces from source squares
956 clear_bit(&(byColorBB[us]), kfrom);
957 clear_bit(&(byTypeBB[KING]), kfrom);
958 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
959 clear_bit(&(byColorBB[us]), rfrom);
960 clear_bit(&(byTypeBB[ROOK]), rfrom);
961 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
963 // Put pieces on destination squares
964 set_bit(&(byColorBB[us]), kto);
965 set_bit(&(byTypeBB[KING]), kto);
966 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
967 set_bit(&(byColorBB[us]), rto);
968 set_bit(&(byTypeBB[ROOK]), rto);
969 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
971 // Update board array
972 board[kfrom] = board[rfrom] = EMPTY;
973 board[kto] = king_of_color(us);
974 board[rto] = rook_of_color(us);
976 // Update king square
977 kingSquare[us] = kto;
979 // Update piece lists
980 pieceList[us][KING][index[kfrom]] = kto;
981 pieceList[us][ROOK][index[rfrom]] = rto;
982 int tmp = index[rfrom];
983 index[kto] = index[kfrom];
986 // Update incremental scores
987 mgValue -= mg_pst(us, KING, kfrom);
988 mgValue += mg_pst(us, KING, kto);
989 egValue -= eg_pst(us, KING, kfrom);
990 egValue += eg_pst(us, KING, kto);
991 mgValue -= mg_pst(us, ROOK, rfrom);
992 mgValue += mg_pst(us, ROOK, rto);
993 egValue -= eg_pst(us, ROOK, rfrom);
994 egValue += eg_pst(us, ROOK, rto);
997 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
998 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1000 // Clear en passant square
1001 if (epSquare != SQ_NONE)
1003 key ^= zobEp[epSquare];
1007 // Update castling rights
1008 key ^= zobCastle[castleRights];
1009 castleRights &= castleRightsMask[kfrom];
1010 key ^= zobCastle[castleRights];
1012 // Reset rule 50 counter
1015 // Update checkers BB
1016 checkersBB = attacks_to(king_square(them), us);
1020 /// Position::do_promotion_move() is a private method used to make a promotion
1021 /// move. It is called from the main Position::do_move function. The
1022 /// UndoInfo object, which has been initialized in Position::do_move, is
1023 /// used to store the captured piece (if any).
1025 void Position::do_promotion_move(Move m, UndoInfo &u) {
1029 PieceType capture, promotion;
1032 assert(move_is_ok(m));
1033 assert(move_promotion(m));
1035 us = side_to_move();
1036 them = opposite_color(us);
1037 from = move_from(m);
1040 assert(relative_rank(us, to) == RANK_8);
1041 assert(piece_on(from) == pawn_of_color(us));
1042 assert(color_of_piece_on(to) == them || square_is_empty(to));
1044 capture = type_of_piece_on(to);
1048 u.capture = capture;
1049 do_capture_move(m, capture, them, to);
1053 clear_bit(&(byColorBB[us]), from);
1054 clear_bit(&(byTypeBB[PAWN]), from);
1055 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1056 board[from] = EMPTY;
1058 // Insert promoted piece
1059 promotion = move_promotion(m);
1060 assert(promotion >= KNIGHT && promotion <= QUEEN);
1061 set_bit(&(byColorBB[us]), to);
1062 set_bit(&(byTypeBB[promotion]), to);
1063 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1064 board[to] = piece_of_color_and_type(us, promotion);
1067 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1069 // Update pawn hash key
1070 pawnKey ^= zobrist[us][PAWN][from];
1072 // Update material key
1073 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1074 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1076 // Update piece counts
1077 pieceCount[us][PAWN]--;
1078 pieceCount[us][promotion]++;
1080 // Update piece lists
1081 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1082 index[pieceList[us][PAWN][index[from]]] = index[from];
1083 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1084 index[to] = pieceCount[us][promotion] - 1;
1086 // Update incremental scores
1087 mgValue -= mg_pst(us, PAWN, from);
1088 mgValue += mg_pst(us, promotion, to);
1089 egValue -= eg_pst(us, PAWN, from);
1090 egValue += eg_pst(us, promotion, to);
1093 npMaterial[us] += piece_value_midgame(promotion);
1095 // Clear the en passant square
1096 if (epSquare != SQ_NONE)
1098 key ^= zobEp[epSquare];
1102 // Update castle rights
1103 key ^= zobCastle[castleRights];
1104 castleRights &= castleRightsMask[to];
1105 key ^= zobCastle[castleRights];
1107 // Reset rule 50 counter
1110 // Update checkers BB
1111 checkersBB = attacks_to(king_square(them), us);
1115 /// Position::do_ep_move() is a private method used to make an en passant
1116 /// capture. It is called from the main Position::do_move function. Because
1117 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1118 /// object in which to store the captured piece.
1120 void Position::do_ep_move(Move m) {
1123 Square from, to, capsq;
1126 assert(move_is_ok(m));
1127 assert(move_is_ep(m));
1129 us = side_to_move();
1130 them = opposite_color(us);
1131 from = move_from(m);
1133 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1135 assert(to == epSquare);
1136 assert(relative_rank(us, to) == RANK_6);
1137 assert(piece_on(to) == EMPTY);
1138 assert(piece_on(from) == pawn_of_color(us));
1139 assert(piece_on(capsq) == pawn_of_color(them));
1141 // Remove captured piece
1142 clear_bit(&(byColorBB[them]), capsq);
1143 clear_bit(&(byTypeBB[PAWN]), capsq);
1144 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1145 board[capsq] = EMPTY;
1147 // Remove moving piece from source square
1148 clear_bit(&(byColorBB[us]), from);
1149 clear_bit(&(byTypeBB[PAWN]), from);
1150 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1152 // Put moving piece on destination square
1153 set_bit(&(byColorBB[us]), to);
1154 set_bit(&(byTypeBB[PAWN]), to);
1155 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1156 board[to] = board[from];
1157 board[from] = EMPTY;
1159 // Update material hash key
1160 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1162 // Update piece count
1163 pieceCount[them][PAWN]--;
1165 // Update piece list
1166 pieceList[us][PAWN][index[from]] = to;
1167 index[to] = index[from];
1168 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1169 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1172 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1173 key ^= zobrist[them][PAWN][capsq];
1174 key ^= zobEp[epSquare];
1176 // Update pawn hash key
1177 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1178 pawnKey ^= zobrist[them][PAWN][capsq];
1180 // Update incremental scores
1181 mgValue -= mg_pst(them, PAWN, capsq);
1182 mgValue -= mg_pst(us, PAWN, from);
1183 mgValue += mg_pst(us, PAWN, to);
1184 egValue -= eg_pst(them, PAWN, capsq);
1185 egValue -= eg_pst(us, PAWN, from);
1186 egValue += eg_pst(us, PAWN, to);
1188 // Reset en passant square
1191 // Reset rule 50 counter
1194 // Update checkers BB
1195 checkersBB = attacks_to(king_square(them), us);
1199 /// Position::undo_move() unmakes a move. When it returns, the position should
1200 /// be restored to exactly the same state as before the move was made. It is
1201 /// important that Position::undo_move is called with the same move and UndoInfo
1202 /// object as the earlier call to Position::do_move.
1204 void Position::undo_move(Move m, const UndoInfo &u) {
1207 assert(move_is_ok(m));
1210 sideToMove = opposite_color(sideToMove);
1212 // Restore information from our UndoInfo object (except the captured piece,
1213 // which is taken care of later)
1216 if (move_is_castle(m))
1217 undo_castle_move(m);
1218 else if (move_promotion(m))
1219 undo_promotion_move(m, u);
1220 else if (move_is_ep(m))
1226 PieceType piece, capture;
1228 us = side_to_move();
1229 them = opposite_color(us);
1230 from = move_from(m);
1233 assert(piece_on(from) == EMPTY);
1234 assert(color_of_piece_on(to) == us);
1236 // Put the piece back at the source square
1237 piece = type_of_piece_on(to);
1238 set_bit(&(byColorBB[us]), from);
1239 set_bit(&(byTypeBB[piece]), from);
1240 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1241 board[from] = piece_of_color_and_type(us, piece);
1243 // Clear the destination square
1244 clear_bit(&(byColorBB[us]), to);
1245 clear_bit(&(byTypeBB[piece]), to);
1246 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1248 // If the moving piece was a king, update the king square
1250 kingSquare[us] = from;
1252 // Update piece list
1253 pieceList[us][piece][index[to]] = from;
1254 index[from] = index[to];
1256 capture = u.capture;
1260 assert(capture != KING);
1262 // Replace the captured piece
1263 set_bit(&(byColorBB[them]), to);
1264 set_bit(&(byTypeBB[capture]), to);
1265 set_bit(&(byTypeBB[0]), to);
1266 board[to] = piece_of_color_and_type(them, capture);
1269 if (capture != PAWN)
1270 npMaterial[them] += piece_value_midgame(capture);
1272 // Update piece list
1273 pieceList[them][capture][pieceCount[them][capture]] = to;
1274 index[to] = pieceCount[them][capture];
1276 // Update piece count
1277 pieceCount[them][capture]++;
1286 /// Position::undo_castle_move() is a private method used to unmake a castling
1287 /// move. It is called from the main Position::undo_move function. Note that
1288 /// castling moves are encoded as "king captures friendly rook" moves, for
1289 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1291 void Position::undo_castle_move(Move m) {
1293 assert(move_is_ok(m));
1294 assert(move_is_castle(m));
1296 // When we have arrived here, some work has already been done by
1297 // Position::undo_move. In particular, the side to move has been switched,
1298 // so the code below is correct.
1299 Color us = side_to_move();
1301 // Find source squares for king and rook
1302 Square kfrom = move_from(m);
1303 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1306 // Find destination squares for king and rook
1307 if (rfrom > kfrom) // O-O
1309 kto = relative_square(us, SQ_G1);
1310 rto = relative_square(us, SQ_F1);
1312 kto = relative_square(us, SQ_C1);
1313 rto = relative_square(us, SQ_D1);
1316 assert(piece_on(kto) == king_of_color(us));
1317 assert(piece_on(rto) == rook_of_color(us));
1319 // Remove pieces from destination squares
1320 clear_bit(&(byColorBB[us]), kto);
1321 clear_bit(&(byTypeBB[KING]), kto);
1322 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1323 clear_bit(&(byColorBB[us]), rto);
1324 clear_bit(&(byTypeBB[ROOK]), rto);
1325 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1327 // Put pieces on source squares
1328 set_bit(&(byColorBB[us]), kfrom);
1329 set_bit(&(byTypeBB[KING]), kfrom);
1330 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1331 set_bit(&(byColorBB[us]), rfrom);
1332 set_bit(&(byTypeBB[ROOK]), rfrom);
1333 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1336 board[rto] = board[kto] = EMPTY;
1337 board[rfrom] = rook_of_color(us);
1338 board[kfrom] = king_of_color(us);
1340 // Update king square
1341 kingSquare[us] = kfrom;
1343 // Update piece lists
1344 pieceList[us][KING][index[kto]] = kfrom;
1345 pieceList[us][ROOK][index[rto]] = rfrom;
1346 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1347 index[kfrom] = index[kto];
1352 /// Position::undo_promotion_move() is a private method used to unmake a
1353 /// promotion move. It is called from the main Position::do_move
1354 /// function. The UndoInfo object, which has been initialized in
1355 /// Position::do_move, is used to put back the captured piece (if any).
1357 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1361 PieceType capture, promotion;
1363 assert(move_is_ok(m));
1364 assert(move_promotion(m));
1366 // When we have arrived here, some work has already been done by
1367 // Position::undo_move. In particular, the side to move has been switched,
1368 // so the code below is correct.
1369 us = side_to_move();
1370 them = opposite_color(us);
1371 from = move_from(m);
1374 assert(relative_rank(us, to) == RANK_8);
1375 assert(piece_on(from) == EMPTY);
1377 // Remove promoted piece
1378 promotion = move_promotion(m);
1379 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1380 assert(promotion >= KNIGHT && promotion <= QUEEN);
1381 clear_bit(&(byColorBB[us]), to);
1382 clear_bit(&(byTypeBB[promotion]), to);
1383 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1385 // Insert pawn at source square
1386 set_bit(&(byColorBB[us]), from);
1387 set_bit(&(byTypeBB[PAWN]), from);
1388 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1389 board[from] = pawn_of_color(us);
1392 npMaterial[us] -= piece_value_midgame(promotion);
1394 // Update piece list
1395 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1396 index[from] = pieceCount[us][PAWN];
1397 pieceList[us][promotion][index[to]] =
1398 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1399 index[pieceList[us][promotion][index[to]]] = index[to];
1401 // Update piece counts
1402 pieceCount[us][promotion]--;
1403 pieceCount[us][PAWN]++;
1405 capture = u.capture;
1409 assert(capture != KING);
1411 // Insert captured piece:
1412 set_bit(&(byColorBB[them]), to);
1413 set_bit(&(byTypeBB[capture]), to);
1414 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1415 board[to] = piece_of_color_and_type(them, capture);
1417 // Update material. Because the move is a promotion move, we know
1418 // that the captured piece cannot be a pawn.
1419 assert(capture != PAWN);
1420 npMaterial[them] += piece_value_midgame(capture);
1422 // Update piece list
1423 pieceList[them][capture][pieceCount[them][capture]] = to;
1424 index[to] = pieceCount[them][capture];
1426 // Update piece count
1427 pieceCount[them][capture]++;
1433 /// Position::undo_ep_move() is a private method used to unmake an en passant
1434 /// capture. It is called from the main Position::undo_move function. Because
1435 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1436 /// object from which to retrieve the captured piece.
1438 void Position::undo_ep_move(Move m) {
1440 assert(move_is_ok(m));
1441 assert(move_is_ep(m));
1443 // When we have arrived here, some work has already been done by
1444 // Position::undo_move. In particular, the side to move has been switched,
1445 // so the code below is correct.
1446 Color us = side_to_move();
1447 Color them = opposite_color(us);
1448 Square from = move_from(m);
1449 Square to = move_to(m);
1450 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1452 assert(to == ep_square());
1453 assert(relative_rank(us, to) == RANK_6);
1454 assert(piece_on(to) == pawn_of_color(us));
1455 assert(piece_on(from) == EMPTY);
1456 assert(piece_on(capsq) == EMPTY);
1458 // Replace captured piece
1459 set_bit(&(byColorBB[them]), capsq);
1460 set_bit(&(byTypeBB[PAWN]), capsq);
1461 set_bit(&(byTypeBB[0]), capsq);
1462 board[capsq] = pawn_of_color(them);
1464 // Remove moving piece from destination square
1465 clear_bit(&(byColorBB[us]), to);
1466 clear_bit(&(byTypeBB[PAWN]), to);
1467 clear_bit(&(byTypeBB[0]), to);
1470 // Replace moving piece at source square
1471 set_bit(&(byColorBB[us]), from);
1472 set_bit(&(byTypeBB[PAWN]), from);
1473 set_bit(&(byTypeBB[0]), from);
1474 board[from] = pawn_of_color(us);
1476 // Update piece list:
1477 pieceList[us][PAWN][index[to]] = from;
1478 index[from] = index[to];
1479 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1480 index[capsq] = pieceCount[them][PAWN];
1482 // Update piece count:
1483 pieceCount[them][PAWN]++;
1487 /// Position::do_null_move makes() a "null move": It switches the side to move
1488 /// and updates the hash key without executing any move on the board.
1490 void Position::do_null_move(UndoInfo& u) {
1493 assert(!is_check());
1495 // Back up the information necessary to undo the null move to the supplied
1496 // UndoInfo object. In the case of a null move, the only thing we need to
1497 // remember is the last move made and the en passant square.
1498 u.lastMove = lastMove;
1499 u.epSquare = epSquare;
1501 // Save the current key to the history[] array, in order to be able to
1502 // detect repetition draws.
1503 history[gamePly] = key;
1505 // Update the necessary information
1506 sideToMove = opposite_color(sideToMove);
1507 if (epSquare != SQ_NONE)
1508 key ^= zobEp[epSquare];
1513 key ^= zobSideToMove;
1515 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1516 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1522 /// Position::undo_null_move() unmakes a "null move".
1524 void Position::undo_null_move(const UndoInfo &u) {
1527 assert(!is_check());
1529 // Restore information from the supplied UndoInfo object:
1530 lastMove = u.lastMove;
1531 epSquare = u.epSquare;
1532 if (epSquare != SQ_NONE)
1533 key ^= zobEp[epSquare];
1535 // Update the necessary information.
1536 sideToMove = opposite_color(sideToMove);
1539 key ^= zobSideToMove;
1541 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1542 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1548 /// Position::see() is a static exchange evaluator: It tries to estimate the
1549 /// material gain or loss resulting from a move. There are three versions of
1550 /// this function: One which takes a destination square as input, one takes a
1551 /// move, and one which takes a 'from' and a 'to' square. The function does
1552 /// not yet understand promotions captures.
1554 int Position::see(Square to) const {
1556 assert(square_is_ok(to));
1557 return see(SQ_NONE, to);
1560 int Position::see(Move m) const {
1562 assert(move_is_ok(m));
1563 return see(move_from(m), move_to(m));
1566 int Position::see(Square from, Square to) const {
1569 static const int seeValues[18] = {
1570 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1571 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1572 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1573 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1577 Bitboard attackers, occ, b;
1579 assert(square_is_ok(from) || from == SQ_NONE);
1580 assert(square_is_ok(to));
1582 // Initialize colors
1583 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1584 Color them = opposite_color(us);
1586 // Initialize pieces
1587 Piece piece = piece_on(from);
1588 Piece capture = piece_on(to);
1590 // Find all attackers to the destination square, with the moving piece
1591 // removed, but possibly an X-ray attacker added behind it.
1592 occ = occupied_squares();
1594 // Handle en passant moves
1595 if (epSquare == to && type_of_piece_on(from) == PAWN)
1597 assert(capture == EMPTY);
1599 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1600 capture = piece_on(capQq);
1602 assert(type_of_piece_on(capQq) == PAWN);
1604 // Remove the captured pawn
1605 clear_bit(&occ, capQq);
1610 clear_bit(&occ, from);
1611 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1612 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1613 | (piece_attacks<KNIGHT>(to) & knights())
1614 | (piece_attacks<KING>(to) & kings())
1615 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1616 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1618 if (from != SQ_NONE)
1621 // If we don't have any attacker we are finished
1622 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1625 // Locate the least valuable attacker to the destination square
1626 // and use it to initialize from square.
1628 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1631 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1632 piece = piece_on(from);
1635 // If the opponent has no attackers we are finished
1636 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1637 return seeValues[capture];
1639 attackers &= occ; // Remove the moving piece
1641 // The destination square is defended, which makes things rather more
1642 // difficult to compute. We proceed by building up a "swap list" containing
1643 // the material gain or loss at each stop in a sequence of captures to the
1644 // destination square, where the sides alternately capture, and always
1645 // capture with the least valuable piece. After each capture, we look for
1646 // new X-ray attacks from behind the capturing piece.
1647 int lastCapturingPieceValue = seeValues[piece];
1648 int swapList[32], n = 1;
1652 swapList[0] = seeValues[capture];
1655 // Locate the least valuable attacker for the side to move. The loop
1656 // below looks like it is potentially infinite, but it isn't. We know
1657 // that the side to move still has at least one attacker left.
1658 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1661 // Remove the attacker we just found from the 'attackers' bitboard,
1662 // and scan for new X-ray attacks behind the attacker.
1663 b = attackers & pieces_of_color_and_type(c, pt);
1665 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1666 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1670 // Add the new entry to the swap list
1672 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1675 // Remember the value of the capturing piece, and change the side to move
1676 // before beginning the next iteration
1677 lastCapturingPieceValue = seeValues[pt];
1678 c = opposite_color(c);
1680 // Stop after a king capture
1681 if (pt == KING && (attackers & pieces_of_color(c)))
1684 swapList[n++] = 100;
1687 } while (attackers & pieces_of_color(c));
1689 // Having built the swap list, we negamax through it to find the best
1690 // achievable score from the point of view of the side to move
1692 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1698 /// Position::clear() erases the position object to a pristine state, with an
1699 /// empty board, white to move, and no castling rights.
1701 void Position::clear() {
1703 for (int i = 0; i < 64; i++)
1709 for (int i = 0; i < 2; i++)
1710 byColorBB[i] = EmptyBoardBB;
1712 for (int i = 0; i < 7; i++)
1714 byTypeBB[i] = EmptyBoardBB;
1715 pieceCount[0][i] = pieceCount[1][i] = 0;
1716 for (int j = 0; j < 8; j++)
1717 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1720 checkersBB = EmptyBoardBB;
1722 lastMove = MOVE_NONE;
1725 castleRights = NO_CASTLES;
1726 initialKFile = FILE_E;
1727 initialKRFile = FILE_H;
1728 initialQRFile = FILE_A;
1735 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1736 /// UCI interface code, whenever a non-reversible move is made in a
1737 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1738 /// for the program to handle games of arbitrary length, as long as the GUI
1739 /// handles draws by the 50 move rule correctly.
1741 void Position::reset_game_ply() {
1747 /// Position::put_piece() puts a piece on the given square of the board,
1748 /// updating the board array, bitboards, and piece counts.
1750 void Position::put_piece(Piece p, Square s) {
1752 Color c = color_of_piece(p);
1753 PieceType pt = type_of_piece(p);
1756 index[s] = pieceCount[c][pt];
1757 pieceList[c][pt][index[s]] = s;
1759 set_bit(&(byTypeBB[pt]), s);
1760 set_bit(&(byColorBB[c]), s);
1761 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1763 pieceCount[c][pt]++;
1770 /// Position::allow_oo() gives the given side the right to castle kingside.
1771 /// Used when setting castling rights during parsing of FEN strings.
1773 void Position::allow_oo(Color c) {
1775 castleRights |= (1 + int(c));
1779 /// Position::allow_ooo() gives the given side the right to castle queenside.
1780 /// Used when setting castling rights during parsing of FEN strings.
1782 void Position::allow_ooo(Color c) {
1784 castleRights |= (4 + 4*int(c));
1788 /// Position::compute_key() computes the hash key of the position. The hash
1789 /// key is usually updated incrementally as moves are made and unmade, the
1790 /// compute_key() function is only used when a new position is set up, and
1791 /// to verify the correctness of the hash key when running in debug mode.
1793 Key Position::compute_key() const {
1795 Key result = Key(0ULL);
1797 for (Square s = SQ_A1; s <= SQ_H8; s++)
1798 if (square_is_occupied(s))
1799 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1801 if (ep_square() != SQ_NONE)
1802 result ^= zobEp[ep_square()];
1804 result ^= zobCastle[castleRights];
1805 if (side_to_move() == BLACK)
1806 result ^= zobSideToMove;
1812 /// Position::compute_pawn_key() computes the hash key of the position. The
1813 /// hash key is usually updated incrementally as moves are made and unmade,
1814 /// the compute_pawn_key() function is only used when a new position is set
1815 /// up, and to verify the correctness of the pawn hash key when running in
1818 Key Position::compute_pawn_key() const {
1820 Key result = Key(0ULL);
1824 for (Color c = WHITE; c <= BLACK; c++)
1829 s = pop_1st_bit(&b);
1830 result ^= zobrist[c][PAWN][s];
1837 /// Position::compute_material_key() computes the hash key of the position.
1838 /// The hash key is usually updated incrementally as moves are made and unmade,
1839 /// the compute_material_key() function is only used when a new position is set
1840 /// up, and to verify the correctness of the material hash key when running in
1843 Key Position::compute_material_key() const {
1845 Key result = Key(0ULL);
1846 for (Color c = WHITE; c <= BLACK; c++)
1847 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1849 int count = piece_count(c, pt);
1850 for (int i = 0; i <= count; i++)
1851 result ^= zobMaterial[c][pt][i];
1857 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1858 /// incremental scores for the middle game and the endgame. These functions
1859 /// are used to initialize the incremental scores when a new position is set
1860 /// up, and to verify that the scores are correctly updated by do_move
1861 /// and undo_move when the program is running in debug mode.
1863 Value Position::compute_mg_value() const {
1865 Value result = Value(0);
1869 for (Color c = WHITE; c <= BLACK; c++)
1870 for (PieceType pt = PAWN; pt <= KING; pt++)
1872 b = pieces_of_color_and_type(c, pt);
1875 s = pop_1st_bit(&b);
1876 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1877 result += mg_pst(c, pt, s);
1880 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1884 Value Position::compute_eg_value() const {
1886 Value result = Value(0);
1890 for (Color c = WHITE; c <= BLACK; c++)
1891 for (PieceType pt = PAWN; pt <= KING; pt++)
1893 b = pieces_of_color_and_type(c, pt);
1896 s = pop_1st_bit(&b);
1897 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1898 result += eg_pst(c, pt, s);
1901 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1906 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1907 /// game material score for the given side. Material scores are updated
1908 /// incrementally during the search, this function is only used while
1909 /// initializing a new Position object.
1911 Value Position::compute_non_pawn_material(Color c) const {
1913 Value result = Value(0);
1916 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1918 Bitboard b = pieces_of_color_and_type(c, pt);
1921 s = pop_1st_bit(&b);
1922 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1923 result += piece_value_midgame(pt);
1930 /// Position::is_mate() returns true or false depending on whether the
1931 /// side to move is checkmated. Note that this function is currently very
1932 /// slow, and shouldn't be used frequently inside the search.
1934 bool Position::is_mate() const {
1938 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1939 return mp.get_next_move() == MOVE_NONE;
1945 /// Position::is_draw() tests whether the position is drawn by material,
1946 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1947 /// must be done by the search.
1949 bool Position::is_draw() const {
1951 // Draw by material?
1953 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1956 // Draw by the 50 moves rule?
1957 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1960 // Draw by repetition?
1961 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1962 if (history[gamePly - i] == key)
1969 /// Position::has_mate_threat() tests whether a given color has a mate in one
1970 /// from the current position. This function is quite slow, but it doesn't
1971 /// matter, because it is currently only called from PV nodes, which are rare.
1973 bool Position::has_mate_threat(Color c) {
1976 Color stm = side_to_move();
1978 // The following lines are useless and silly, but prevents gcc from
1979 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1980 // be used uninitialized.
1981 u1.lastMove = lastMove;
1982 u1.epSquare = epSquare;
1987 // If the input color is not equal to the side to move, do a null move
1991 MoveStack mlist[120];
1993 bool result = false;
1995 // Generate legal moves
1996 count = generate_legal_moves(*this, mlist);
1998 // Loop through the moves, and see if one of them is mate
1999 for (int i = 0; i < count; i++)
2001 do_move(mlist[i].move, u2);
2005 undo_move(mlist[i].move, u2);
2008 // Undo null move, if necessary
2016 /// Position::init_zobrist() is a static member function which initializes the
2017 /// various arrays used to compute hash keys.
2019 void Position::init_zobrist() {
2021 for (int i = 0; i < 2; i++)
2022 for (int j = 0; j < 8; j++)
2023 for (int k = 0; k < 64; k++)
2024 zobrist[i][j][k] = Key(genrand_int64());
2026 for (int i = 0; i < 64; i++)
2027 zobEp[i] = Key(genrand_int64());
2029 for (int i = 0; i < 16; i++)
2030 zobCastle[i] = genrand_int64();
2032 zobSideToMove = genrand_int64();
2034 for (int i = 0; i < 2; i++)
2035 for (int j = 0; j < 8; j++)
2036 for (int k = 0; k < 16; k++)
2037 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2039 for (int i = 0; i < 16; i++)
2040 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2044 /// Position::init_piece_square_tables() initializes the piece square tables.
2045 /// This is a two-step operation: First, the white halves of the tables are
2046 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2047 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2048 /// Second, the black halves of the tables are initialized by mirroring
2049 /// and changing the sign of the corresponding white scores.
2051 void Position::init_piece_square_tables() {
2053 int r = get_option_value_int("Randomness"), i;
2054 for (Square s = SQ_A1; s <= SQ_H8; s++)
2055 for (Piece p = WP; p <= WK; p++)
2057 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2058 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2059 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2062 for (Square s = SQ_A1; s <= SQ_H8; s++)
2063 for (Piece p = BP; p <= BK; p++)
2065 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2066 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2071 /// Position::flipped_copy() makes a copy of the input position, but with
2072 /// the white and black sides reversed. This is only useful for debugging,
2073 /// especially for finding evaluation symmetry bugs.
2075 void Position::flipped_copy(const Position &pos) {
2077 assert(pos.is_ok());
2082 for (Square s = SQ_A1; s <= SQ_H8; s++)
2083 if (!pos.square_is_empty(s))
2084 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2087 sideToMove = opposite_color(pos.side_to_move());
2090 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2091 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2092 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2093 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2095 initialKFile = pos.initialKFile;
2096 initialKRFile = pos.initialKRFile;
2097 initialQRFile = pos.initialQRFile;
2099 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2100 castleRightsMask[sq] = ALL_CASTLES;
2102 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2103 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2104 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2105 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2106 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2107 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2109 // En passant square
2110 if (pos.epSquare != SQ_NONE)
2111 epSquare = flip_square(pos.epSquare);
2117 key = compute_key();
2118 pawnKey = compute_pawn_key();
2119 materialKey = compute_material_key();
2121 // Incremental scores
2122 mgValue = compute_mg_value();
2123 egValue = compute_eg_value();
2126 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2127 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2133 /// Position::is_ok() performs some consitency checks for the position object.
2134 /// This is meant to be helpful when debugging.
2136 bool Position::is_ok(int* failedStep) const {
2138 // What features of the position should be verified?
2139 static const bool debugBitboards = false;
2140 static const bool debugKingCount = false;
2141 static const bool debugKingCapture = false;
2142 static const bool debugCheckerCount = false;
2143 static const bool debugKey = false;
2144 static const bool debugMaterialKey = false;
2145 static const bool debugPawnKey = false;
2146 static const bool debugIncrementalEval = false;
2147 static const bool debugNonPawnMaterial = false;
2148 static const bool debugPieceCounts = false;
2149 static const bool debugPieceList = false;
2151 if (failedStep) *failedStep = 1;
2154 if (!color_is_ok(side_to_move()))
2157 // Are the king squares in the position correct?
2158 if (failedStep) (*failedStep)++;
2159 if (piece_on(king_square(WHITE)) != WK)
2162 if (failedStep) (*failedStep)++;
2163 if (piece_on(king_square(BLACK)) != BK)
2167 if (failedStep) (*failedStep)++;
2168 if (!file_is_ok(initialKRFile))
2171 if (!file_is_ok(initialQRFile))
2174 // Do both sides have exactly one king?
2175 if (failedStep) (*failedStep)++;
2178 int kingCount[2] = {0, 0};
2179 for (Square s = SQ_A1; s <= SQ_H8; s++)
2180 if (type_of_piece_on(s) == KING)
2181 kingCount[color_of_piece_on(s)]++;
2183 if (kingCount[0] != 1 || kingCount[1] != 1)
2187 // Can the side to move capture the opponent's king?
2188 if (failedStep) (*failedStep)++;
2189 if (debugKingCapture)
2191 Color us = side_to_move();
2192 Color them = opposite_color(us);
2193 Square ksq = king_square(them);
2194 if (square_is_attacked(ksq, us))
2198 // Is there more than 2 checkers?
2199 if (failedStep) (*failedStep)++;
2200 if (debugCheckerCount && count_1s(checkersBB) > 2)
2204 if (failedStep) (*failedStep)++;
2207 // The intersection of the white and black pieces must be empty
2208 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2211 // The union of the white and black pieces must be equal to all
2213 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2216 // Separate piece type bitboards must have empty intersections
2217 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2218 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2219 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2223 // En passant square OK?
2224 if (failedStep) (*failedStep)++;
2225 if (ep_square() != SQ_NONE)
2227 // The en passant square must be on rank 6, from the point of view of the
2229 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2234 if (failedStep) (*failedStep)++;
2235 if (debugKey && key != compute_key())
2238 // Pawn hash key OK?
2239 if (failedStep) (*failedStep)++;
2240 if (debugPawnKey && pawnKey != compute_pawn_key())
2243 // Material hash key OK?
2244 if (failedStep) (*failedStep)++;
2245 if (debugMaterialKey && materialKey != compute_material_key())
2248 // Incremental eval OK?
2249 if (failedStep) (*failedStep)++;
2250 if (debugIncrementalEval)
2252 if (mgValue != compute_mg_value())
2255 if (egValue != compute_eg_value())
2259 // Non-pawn material OK?
2260 if (failedStep) (*failedStep)++;
2261 if (debugNonPawnMaterial)
2263 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2266 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2271 if (failedStep) (*failedStep)++;
2272 if (debugPieceCounts)
2273 for (Color c = WHITE; c <= BLACK; c++)
2274 for (PieceType pt = PAWN; pt <= KING; pt++)
2275 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2278 if (failedStep) (*failedStep)++;
2281 for(Color c = WHITE; c <= BLACK; c++)
2282 for(PieceType pt = PAWN; pt <= KING; pt++)
2283 for(int i = 0; i < pieceCount[c][pt]; i++)
2285 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2288 if (index[piece_list(c, pt, i)] != i)
2292 if (failedStep) *failedStep = 0;