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])) {
134 else if(fen[i] == 'K') allow_oo(WHITE);
135 else if(fen[i] == 'Q') allow_ooo(WHITE);
136 else if(fen[i] == 'k') allow_oo(BLACK);
137 else if(fen[i] == 'q') allow_ooo(BLACK);
138 else if(fen[i] >= 'A' && fen[i] <= 'H') {
139 File rookFile, kingFile = FILE_NONE;
140 for(Square square = SQ_B1; square <= SQ_G1; square++)
141 if(piece_on(square) == WK)
142 kingFile = square_file(square);
143 if(kingFile == FILE_NONE) {
144 std::cout << "Error in FEN at character " << i << std::endl;
147 initialKFile = kingFile;
148 rookFile = File(fen[i] - 'A') + FILE_A;
149 if(rookFile < initialKFile) {
151 initialQRFile = rookFile;
155 initialKRFile = rookFile;
158 else if(fen[i] >= 'a' && fen[i] <= 'h') {
159 File rookFile, kingFile = FILE_NONE;
160 for(Square square = SQ_B8; square <= SQ_G8; square++)
161 if(piece_on(square) == BK)
162 kingFile = square_file(square);
163 if(kingFile == FILE_NONE) {
164 std::cout << "Error in FEN at character " << i << std::endl;
167 initialKFile = kingFile;
168 rookFile = File(fen[i] - 'a') + FILE_A;
169 if(rookFile < initialKFile) {
171 initialQRFile = rookFile;
175 initialKRFile = rookFile;
179 std::cout << "Error in FEN at character " << i << std::endl;
186 while (fen[i] == ' ')
190 if ( i < fen.length() - 2
191 && (fen[i] >= 'a' && fen[i] <= 'h')
192 && (fen[i+1] == '3' || fen[i+1] == '6'))
193 epSquare = square_from_string(fen.substr(i, 2));
195 // Various initialisation
196 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
197 castleRightsMask[sq] = ALL_CASTLES;
199 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
200 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
201 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
202 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
203 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
204 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
209 pawnKey = compute_pawn_key();
210 materialKey = compute_material_key();
211 mgValue = compute_mg_value();
212 egValue = compute_eg_value();
213 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
214 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
218 /// Position::to_fen() converts the position object to a FEN string. This is
219 /// probably only useful for debugging.
221 const std::string Position::to_fen() const {
223 static const std::string pieceLetters = " PNBRQK pnbrqk";
227 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
230 for (File file = FILE_A; file <= FILE_H; file++)
232 Square sq = make_square(file, rank);
233 if (!square_is_occupied(sq))
239 fen += (char)skip + '0';
242 fen += pieceLetters[piece_on(sq)];
245 fen += (char)skip + '0';
247 fen += (rank > RANK_1 ? '/' : ' ');
249 fen += (sideToMove == WHITE ? "w " : "b ");
250 if (castleRights != NO_CASTLES)
252 if (can_castle_kingside(WHITE)) fen += 'K';
253 if (can_castle_queenside(WHITE)) fen += 'Q';
254 if (can_castle_kingside(BLACK)) fen += 'k';
255 if (can_castle_queenside(BLACK)) fen += 'q';
260 if (ep_square() != SQ_NONE)
261 fen += square_to_string(ep_square());
269 /// Position::print() prints an ASCII representation of the position to
270 /// the standard output. If a move is given then also the san is print.
272 void Position::print(Move m) const {
274 static const std::string pieceLetters = " PNBRQK PNBRQK .";
276 // Check for reentrancy, as example when called from inside
277 // MovePicker that is used also here in move_to_san()
281 RequestPending = true;
283 std::cout << std::endl;
286 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
287 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
289 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
291 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
292 for (File file = FILE_A; file <= FILE_H; file++)
294 Square sq = make_square(file, rank);
295 Piece piece = piece_on(sq);
296 if (piece == EMPTY && square_color(sq) == WHITE)
299 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
300 std::cout << '|' << col << pieceLetters[piece] << col;
302 std::cout << '|' << std::endl;
304 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
305 << "Fen is: " << to_fen() << std::endl
306 << "Key is: " << key << std::endl;
308 RequestPending = false;
312 /// Position::copy() creates a copy of the input position.
314 void Position::copy(const Position &pos) {
316 memcpy(this, &pos, sizeof(Position));
320 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
321 /// king) pieces for the given color.
322 Bitboard Position::pinned_pieces(Color c) const {
324 Square ksq = king_square(c);
325 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
329 /// Position:discovered_check_candidates() returns a bitboard containing all
330 /// pieces for the given side which are candidates for giving a discovered
331 /// check. The code is almost the same as the function for finding pinned
334 Bitboard Position::discovered_check_candidates(Color c) const {
336 Square ksq = king_square(opposite_color(c));
337 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
341 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
342 /// king) pieces for the given color and for the given pinner type. Or, when
343 /// template parameter FindPinned is false, the pinned pieces of opposite color
344 /// that are, indeed, the pieces candidate for a discovery check.
345 template<PieceType Piece, bool FindPinned>
346 Bitboard Position::hidden_checks(Color c, Square ksq) const {
349 Bitboard sliders, result = EmptyBoardBB;
351 if (Piece == ROOK) // Resolved at compile time
352 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
354 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
356 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
358 // King blockers are candidate pinned pieces
359 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
361 // Pinners are sliders, not checkers, that give check when
362 // candidate pinned are removed.
363 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
366 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
368 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
370 // Finally for each pinner find the corresponding pinned piece (if same color of king)
371 // or discovery checker (if opposite color) among the candidates.
374 s = pop_1st_bit(&pinners);
375 result |= (squares_between(s, ksq) & candidate_pinned);
382 /// Position::attacks_to() computes a bitboard containing all pieces which
383 /// attacks a given square. There are two versions of this function: One
384 /// which finds attackers of both colors, and one which only finds the
385 /// attackers for one side.
387 Bitboard Position::attacks_to(Square s) const {
389 return (pawn_attacks(BLACK, s) & pawns(WHITE))
390 | (pawn_attacks(WHITE, s) & pawns(BLACK))
391 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
392 | (piece_attacks<ROOK>(s) & rooks_and_queens())
393 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
394 | (piece_attacks<KING>(s) & pieces_of_type(KING));
397 /// Position::piece_attacks_square() tests whether the piece on square f
398 /// attacks square t.
400 bool Position::piece_attacks_square(Square f, Square t) const {
402 assert(square_is_ok(f));
403 assert(square_is_ok(t));
407 case WP: return pawn_attacks_square(WHITE, f, t);
408 case BP: return pawn_attacks_square(BLACK, f, t);
409 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
410 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
411 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
412 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
413 case WK: case BK: return piece_attacks_square<KING>(f, t);
420 /// Position::move_attacks_square() tests whether a move from the current
421 /// position attacks a given square. Only attacks by the moving piece are
422 /// considered; the function does not handle X-ray attacks.
424 bool Position::move_attacks_square(Move m, Square s) const {
426 assert(move_is_ok(m));
427 assert(square_is_ok(s));
429 Square f = move_from(m), t = move_to(m);
431 assert(square_is_occupied(f));
435 case WP: return pawn_attacks_square(WHITE, t, s);
436 case BP: return pawn_attacks_square(BLACK, t, s);
437 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
438 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
439 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
440 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
441 case WK: case BK: return piece_attacks_square<KING>(t, s);
448 /// Position::find_checkers() computes the checkersBB bitboard, which
449 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
450 /// currently works by calling Position::attacks_to, which is probably
451 /// inefficient. Consider rewriting this function to use the last move
452 /// played, like in non-bitboard versions of Glaurung.
454 void Position::find_checkers() {
456 Color us = side_to_move();
457 checkersBB = attacks_to(king_square(us), opposite_color(us));
461 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
462 /// There are two versions of this function: One which takes only a
463 /// move as input, and one which takes a move and a bitboard of pinned
464 /// pieces. The latter function is faster, and should always be preferred
465 /// when a pinned piece bitboard has already been computed.
467 bool Position::pl_move_is_legal(Move m) const {
469 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
472 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
475 assert(move_is_ok(m));
476 assert(pinned == pinned_pieces(side_to_move()));
478 // If we're in check, all pseudo-legal moves are legal, because our
479 // check evasion generator only generates true legal moves.
483 // Castling moves are checked for legality during move generation.
484 if (move_is_castle(m))
487 Color us = side_to_move();
488 Color them = opposite_color(us);
489 Square from = move_from(m);
490 Square ksq = king_square(us);
492 assert(color_of_piece_on(from) == us);
493 assert(piece_on(ksq) == king_of_color(us));
495 // En passant captures are a tricky special case. Because they are
496 // rather uncommon, we do it simply by testing whether the king is attacked
497 // after the move is made
500 Square to = move_to(m);
501 Square capsq = make_square(square_file(to), square_rank(from));
502 Bitboard b = occupied_squares();
504 assert(to == ep_square());
505 assert(piece_on(from) == pawn_of_color(us));
506 assert(piece_on(capsq) == pawn_of_color(them));
507 assert(piece_on(to) == EMPTY);
510 clear_bit(&b, capsq);
513 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
514 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
517 // If the moving piece is a king, check whether the destination
518 // square is attacked by the opponent.
520 return !(square_is_attacked(move_to(m), them));
522 // A non-king move is legal if and only if it is not pinned or it
523 // is moving along the ray towards or away from the king.
524 return ( !bit_is_set(pinned, from)
525 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
529 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
530 /// There are two versions of this function: One which takes only a move as
531 /// input, and one which takes a move and a bitboard of discovered check
532 /// candidates. The latter function is faster, and should always be preferred
533 /// when a discovered check candidates bitboard has already been computed.
535 bool Position::move_is_check(Move m) const {
537 Bitboard dc = discovered_check_candidates(side_to_move());
538 return move_is_check(m, dc);
541 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
544 assert(move_is_ok(m));
545 assert(dcCandidates == discovered_check_candidates(side_to_move()));
547 Color us = side_to_move();
548 Color them = opposite_color(us);
549 Square from = move_from(m);
550 Square to = move_to(m);
551 Square ksq = king_square(them);
553 assert(color_of_piece_on(from) == us);
554 assert(piece_on(ksq) == king_of_color(them));
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)) == opposite_color(side_to_move()))
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;
695 /// Position::restore() is called when unmaking a move. It copies back
696 /// the information backed up during a previous call to Position::backup.
698 void Position::restore(const UndoInfo& u) {
700 castleRights = u.castleRights;
701 epSquare = u.epSquare;
702 checkersBB = u.checkersBB;
705 materialKey = u.materialKey;
707 lastMove = u.lastMove;
710 // u.capture is restored in undo_move()
713 template<PieceType Piece>
714 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from, Square to, Bitboard dcCandidates) {
716 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
717 set_bit(pCheckersBB, to);
719 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
722 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
725 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
729 /// Position::do_move() makes a move, and backs up all information necessary
730 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
731 /// Pseudo-legal moves should be filtered out before this function is called.
732 /// There are two versions of this function, one which takes only the move and
733 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
734 /// discovered check candidates. The second version is faster, because knowing
735 /// the discovered check candidates makes it easier to update the checkersBB
736 /// member variable in the position object.
738 void Position::do_move(Move m, UndoInfo& u) {
740 do_move(m, u, discovered_check_candidates(side_to_move()));
743 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
746 assert(move_is_ok(m));
748 // Back up the necessary information to our UndoInfo object (except the
749 // captured piece, which is taken care of later.
752 // Save the current key to the history[] array, in order to be able to
753 // detect repetition draws.
754 history[gamePly] = key;
756 // Increment the 50 moves rule draw counter. Resetting it to zero in the
757 // case of non-reversible moves is taken care of later.
760 if (move_is_castle(m))
762 else if (move_promotion(m))
763 do_promotion_move(m, u);
764 else if (move_is_ep(m))
768 Color us = side_to_move();
769 Color them = opposite_color(us);
770 Square from = move_from(m);
771 Square to = move_to(m);
773 assert(color_of_piece_on(from) == us);
774 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
776 PieceType piece = type_of_piece_on(from);
777 PieceType capture = type_of_piece_on(to);
782 do_capture_move(m, capture, them, to);
786 clear_bit(&(byColorBB[us]), from);
787 clear_bit(&(byTypeBB[piece]), from);
788 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
789 set_bit(&(byColorBB[us]), to);
790 set_bit(&(byTypeBB[piece]), to);
791 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
792 board[to] = board[from];
796 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
798 // Update incremental scores
799 mgValue -= mg_pst(us, piece, from);
800 mgValue += mg_pst(us, piece, to);
801 egValue -= eg_pst(us, piece, from);
802 egValue += eg_pst(us, piece, to);
804 // If the moving piece was a king, update the king square
808 // Reset en passant square
809 if (epSquare != SQ_NONE)
811 key ^= zobEp[epSquare];
815 // If the moving piece was a pawn do some special extra work
818 // Reset rule 50 draw counter
821 // Update pawn hash key
822 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
824 // Set en passant square, only if moved pawn can be captured
825 if (abs(int(to) - int(from)) == 16)
827 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
828 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
830 epSquare = Square((int(from) + int(to)) / 2);
831 key ^= zobEp[epSquare];
836 // Update piece lists
837 pieceList[us][piece][index[from]] = to;
838 index[to] = index[from];
840 // Update castle rights
841 key ^= zobCastle[castleRights];
842 castleRights &= castleRightsMask[from];
843 castleRights &= castleRightsMask[to];
844 key ^= zobCastle[castleRights];
846 // Update checkers bitboard, piece must be already moved
847 checkersBB = EmptyBoardBB;
848 Square ksq = king_square(them);
852 if (bit_is_set(pawn_attacks(them, ksq), to))
853 set_bit(&checkersBB, to);
855 if (bit_is_set(dcCandidates, from))
856 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
857 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
861 update_checkers<KNIGHT>(&checkersBB, ksq, from, to, dcCandidates);
865 update_checkers<BISHOP>(&checkersBB, ksq, from, to, dcCandidates);
869 update_checkers<ROOK>(&checkersBB, ksq, from, to, dcCandidates);
873 update_checkers<QUEEN>(&checkersBB, ksq, from, to, dcCandidates);
877 update_checkers<KING>(&checkersBB, ksq, from, to, dcCandidates);
887 key ^= zobSideToMove;
888 sideToMove = opposite_color(sideToMove);
891 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
892 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
897 /// Position::do_capture_move() is a private method used to update captured
898 /// piece info. It is called from the main Position::do_move function.
900 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
902 assert(capture != KING);
904 // Remove captured piece
905 clear_bit(&(byColorBB[them]), to);
906 clear_bit(&(byTypeBB[capture]), to);
909 key ^= zobrist[them][capture][to];
911 // If the captured piece was a pawn, update pawn hash key
913 pawnKey ^= zobrist[them][PAWN][to];
915 // Update incremental scores
916 mgValue -= mg_pst(them, capture, to);
917 egValue -= eg_pst(them, capture, to);
919 assert(!move_promotion(m) || capture != PAWN);
923 npMaterial[them] -= piece_value_midgame(capture);
925 // Update material hash key
926 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
928 // Update piece count
929 pieceCount[them][capture]--;
932 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
933 index[pieceList[them][capture][index[to]]] = index[to];
935 // Reset rule 50 counter
940 /// Position::do_castle_move() is a private method used to make a castling
941 /// move. It is called from the main Position::do_move function. Note that
942 /// castling moves are encoded as "king captures friendly rook" moves, for
943 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
945 void Position::do_castle_move(Move m) {
948 assert(move_is_ok(m));
949 assert(move_is_castle(m));
951 Color us = side_to_move();
952 Color them = opposite_color(us);
954 // Find source squares for king and rook
955 Square kfrom = move_from(m);
956 Square rfrom = move_to(m); // HACK: See comment at beginning of function
959 assert(piece_on(kfrom) == king_of_color(us));
960 assert(piece_on(rfrom) == rook_of_color(us));
962 // Find destination squares for king and rook
963 if (rfrom > kfrom) // O-O
965 kto = relative_square(us, SQ_G1);
966 rto = relative_square(us, SQ_F1);
968 kto = relative_square(us, SQ_C1);
969 rto = relative_square(us, SQ_D1);
972 // Remove pieces from source squares
973 clear_bit(&(byColorBB[us]), kfrom);
974 clear_bit(&(byTypeBB[KING]), kfrom);
975 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
976 clear_bit(&(byColorBB[us]), rfrom);
977 clear_bit(&(byTypeBB[ROOK]), rfrom);
978 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
980 // Put pieces on destination squares
981 set_bit(&(byColorBB[us]), kto);
982 set_bit(&(byTypeBB[KING]), kto);
983 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
984 set_bit(&(byColorBB[us]), rto);
985 set_bit(&(byTypeBB[ROOK]), rto);
986 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
988 // Update board array
989 board[kfrom] = board[rfrom] = EMPTY;
990 board[kto] = king_of_color(us);
991 board[rto] = rook_of_color(us);
993 // Update king square
994 kingSquare[us] = kto;
996 // Update piece lists
997 pieceList[us][KING][index[kfrom]] = kto;
998 pieceList[us][ROOK][index[rfrom]] = rto;
999 int tmp = index[rfrom];
1000 index[kto] = index[kfrom];
1003 // Update incremental scores
1004 mgValue -= mg_pst(us, KING, kfrom);
1005 mgValue += mg_pst(us, KING, kto);
1006 egValue -= eg_pst(us, KING, kfrom);
1007 egValue += eg_pst(us, KING, kto);
1008 mgValue -= mg_pst(us, ROOK, rfrom);
1009 mgValue += mg_pst(us, ROOK, rto);
1010 egValue -= eg_pst(us, ROOK, rfrom);
1011 egValue += eg_pst(us, ROOK, rto);
1014 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1015 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1017 // Clear en passant square
1018 if(epSquare != SQ_NONE)
1020 key ^= zobEp[epSquare];
1024 // Update castling rights
1025 key ^= zobCastle[castleRights];
1026 castleRights &= castleRightsMask[kfrom];
1027 key ^= zobCastle[castleRights];
1029 // Reset rule 50 counter
1032 // Update checkers BB
1033 checkersBB = attacks_to(king_square(them), us);
1037 /// Position::do_promotion_move() is a private method used to make a promotion
1038 /// move. It is called from the main Position::do_move function. The
1039 /// UndoInfo object, which has been initialized in Position::do_move, is
1040 /// used to store the captured piece (if any).
1042 void Position::do_promotion_move(Move m, UndoInfo &u) {
1046 PieceType capture, promotion;
1049 assert(move_is_ok(m));
1050 assert(move_promotion(m));
1052 us = side_to_move();
1053 them = opposite_color(us);
1054 from = move_from(m);
1057 assert(relative_rank(us, to) == RANK_8);
1058 assert(piece_on(from) == pawn_of_color(us));
1059 assert(color_of_piece_on(to) == them || square_is_empty(to));
1061 capture = type_of_piece_on(to);
1065 u.capture = capture;
1066 do_capture_move(m, capture, them, to);
1070 clear_bit(&(byColorBB[us]), from);
1071 clear_bit(&(byTypeBB[PAWN]), from);
1072 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1073 board[from] = EMPTY;
1075 // Insert promoted piece
1076 promotion = move_promotion(m);
1077 assert(promotion >= KNIGHT && promotion <= QUEEN);
1078 set_bit(&(byColorBB[us]), to);
1079 set_bit(&(byTypeBB[promotion]), to);
1080 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1081 board[to] = piece_of_color_and_type(us, promotion);
1084 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1086 // Update pawn hash key
1087 pawnKey ^= zobrist[us][PAWN][from];
1089 // Update material key
1090 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1091 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1093 // Update piece counts
1094 pieceCount[us][PAWN]--;
1095 pieceCount[us][promotion]++;
1097 // Update piece lists
1098 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1099 index[pieceList[us][PAWN][index[from]]] = index[from];
1100 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1101 index[to] = pieceCount[us][promotion] - 1;
1103 // Update incremental scores
1104 mgValue -= mg_pst(us, PAWN, from);
1105 mgValue += mg_pst(us, promotion, to);
1106 egValue -= eg_pst(us, PAWN, from);
1107 egValue += eg_pst(us, promotion, to);
1110 npMaterial[us] += piece_value_midgame(promotion);
1112 // Clear the en passant square
1113 if (epSquare != SQ_NONE)
1115 key ^= zobEp[epSquare];
1119 // Update castle rights
1120 key ^= zobCastle[castleRights];
1121 castleRights &= castleRightsMask[to];
1122 key ^= zobCastle[castleRights];
1124 // Reset rule 50 counter
1127 // Update checkers BB
1128 checkersBB = attacks_to(king_square(them), us);
1132 /// Position::do_ep_move() is a private method used to make an en passant
1133 /// capture. It is called from the main Position::do_move function. Because
1134 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1135 /// object in which to store the captured piece.
1137 void Position::do_ep_move(Move m) {
1140 Square from, to, capsq;
1143 assert(move_is_ok(m));
1144 assert(move_is_ep(m));
1146 us = side_to_move();
1147 them = opposite_color(us);
1148 from = move_from(m);
1150 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1152 assert(to == epSquare);
1153 assert(relative_rank(us, to) == RANK_6);
1154 assert(piece_on(to) == EMPTY);
1155 assert(piece_on(from) == pawn_of_color(us));
1156 assert(piece_on(capsq) == pawn_of_color(them));
1158 // Remove captured piece
1159 clear_bit(&(byColorBB[them]), capsq);
1160 clear_bit(&(byTypeBB[PAWN]), capsq);
1161 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1162 board[capsq] = EMPTY;
1164 // Remove moving piece from source square
1165 clear_bit(&(byColorBB[us]), from);
1166 clear_bit(&(byTypeBB[PAWN]), from);
1167 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1169 // Put moving piece on destination square
1170 set_bit(&(byColorBB[us]), to);
1171 set_bit(&(byTypeBB[PAWN]), to);
1172 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1173 board[to] = board[from];
1174 board[from] = EMPTY;
1176 // Update material hash key
1177 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1179 // Update piece count
1180 pieceCount[them][PAWN]--;
1182 // Update piece list
1183 pieceList[us][PAWN][index[from]] = to;
1184 index[to] = index[from];
1185 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1186 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1189 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1190 key ^= zobrist[them][PAWN][capsq];
1191 key ^= zobEp[epSquare];
1193 // Update pawn hash key
1194 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1195 pawnKey ^= zobrist[them][PAWN][capsq];
1197 // Update incremental scores
1198 mgValue -= mg_pst(them, PAWN, capsq);
1199 mgValue -= mg_pst(us, PAWN, from);
1200 mgValue += mg_pst(us, PAWN, to);
1201 egValue -= eg_pst(them, PAWN, capsq);
1202 egValue -= eg_pst(us, PAWN, from);
1203 egValue += eg_pst(us, PAWN, to);
1205 // Reset en passant square
1208 // Reset rule 50 counter
1211 // Update checkers BB
1212 checkersBB = attacks_to(king_square(them), us);
1216 /// Position::undo_move() unmakes a move. When it returns, the position should
1217 /// be restored to exactly the same state as before the move was made. It is
1218 /// important that Position::undo_move is called with the same move and UndoInfo
1219 /// object as the earlier call to Position::do_move.
1221 void Position::undo_move(Move m, const UndoInfo &u) {
1224 assert(move_is_ok(m));
1227 sideToMove = opposite_color(sideToMove);
1229 // Restore information from our UndoInfo object (except the captured piece,
1230 // which is taken care of later)
1233 if (move_is_castle(m))
1234 undo_castle_move(m);
1235 else if (move_promotion(m))
1236 undo_promotion_move(m, u);
1237 else if (move_is_ep(m))
1243 PieceType piece, capture;
1245 us = side_to_move();
1246 them = opposite_color(us);
1247 from = move_from(m);
1250 assert(piece_on(from) == EMPTY);
1251 assert(color_of_piece_on(to) == us);
1253 // Put the piece back at the source square
1254 piece = type_of_piece_on(to);
1255 set_bit(&(byColorBB[us]), from);
1256 set_bit(&(byTypeBB[piece]), from);
1257 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1258 board[from] = piece_of_color_and_type(us, piece);
1260 // Clear the destination square
1261 clear_bit(&(byColorBB[us]), to);
1262 clear_bit(&(byTypeBB[piece]), to);
1263 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1265 // If the moving piece was a king, update the king square
1267 kingSquare[us] = from;
1269 // Update piece list
1270 pieceList[us][piece][index[to]] = from;
1271 index[from] = index[to];
1273 capture = u.capture;
1277 assert(capture != KING);
1279 // Replace the captured piece
1280 set_bit(&(byColorBB[them]), to);
1281 set_bit(&(byTypeBB[capture]), to);
1282 set_bit(&(byTypeBB[0]), to);
1283 board[to] = piece_of_color_and_type(them, capture);
1286 if (capture != PAWN)
1287 npMaterial[them] += piece_value_midgame(capture);
1289 // Update piece list
1290 pieceList[them][capture][pieceCount[them][capture]] = to;
1291 index[to] = pieceCount[them][capture];
1293 // Update piece count
1294 pieceCount[them][capture]++;
1303 /// Position::undo_castle_move() is a private method used to unmake a castling
1304 /// move. It is called from the main Position::undo_move function. Note that
1305 /// castling moves are encoded as "king captures friendly rook" moves, for
1306 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1308 void Position::undo_castle_move(Move m) {
1310 assert(move_is_ok(m));
1311 assert(move_is_castle(m));
1313 // When we have arrived here, some work has already been done by
1314 // Position::undo_move. In particular, the side to move has been switched,
1315 // so the code below is correct.
1316 Color us = side_to_move();
1318 // Find source squares for king and rook
1319 Square kfrom = move_from(m);
1320 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1323 // Find destination squares for king and rook
1324 if (rfrom > kfrom) // O-O
1326 kto = relative_square(us, SQ_G1);
1327 rto = relative_square(us, SQ_F1);
1329 kto = relative_square(us, SQ_C1);
1330 rto = relative_square(us, SQ_D1);
1333 assert(piece_on(kto) == king_of_color(us));
1334 assert(piece_on(rto) == rook_of_color(us));
1336 // Remove pieces from destination squares
1337 clear_bit(&(byColorBB[us]), kto);
1338 clear_bit(&(byTypeBB[KING]), kto);
1339 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1340 clear_bit(&(byColorBB[us]), rto);
1341 clear_bit(&(byTypeBB[ROOK]), rto);
1342 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1344 // Put pieces on source squares
1345 set_bit(&(byColorBB[us]), kfrom);
1346 set_bit(&(byTypeBB[KING]), kfrom);
1347 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1348 set_bit(&(byColorBB[us]), rfrom);
1349 set_bit(&(byTypeBB[ROOK]), rfrom);
1350 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1353 board[rto] = board[kto] = EMPTY;
1354 board[rfrom] = rook_of_color(us);
1355 board[kfrom] = king_of_color(us);
1357 // Update king square
1358 kingSquare[us] = kfrom;
1360 // Update piece lists
1361 pieceList[us][KING][index[kto]] = kfrom;
1362 pieceList[us][ROOK][index[rto]] = rfrom;
1363 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1364 index[kfrom] = index[kto];
1369 /// Position::undo_promotion_move() is a private method used to unmake a
1370 /// promotion move. It is called from the main Position::do_move
1371 /// function. The UndoInfo object, which has been initialized in
1372 /// Position::do_move, is used to put back the captured piece (if any).
1374 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1378 PieceType capture, promotion;
1380 assert(move_is_ok(m));
1381 assert(move_promotion(m));
1383 // When we have arrived here, some work has already been done by
1384 // Position::undo_move. In particular, the side to move has been switched,
1385 // so the code below is correct.
1386 us = side_to_move();
1387 them = opposite_color(us);
1388 from = move_from(m);
1391 assert(relative_rank(us, to) == RANK_8);
1392 assert(piece_on(from) == EMPTY);
1394 // Remove promoted piece
1395 promotion = move_promotion(m);
1396 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1397 assert(promotion >= KNIGHT && promotion <= QUEEN);
1398 clear_bit(&(byColorBB[us]), to);
1399 clear_bit(&(byTypeBB[promotion]), to);
1400 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1402 // Insert pawn at source square
1403 set_bit(&(byColorBB[us]), from);
1404 set_bit(&(byTypeBB[PAWN]), from);
1405 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1406 board[from] = pawn_of_color(us);
1409 npMaterial[us] -= piece_value_midgame(promotion);
1411 // Update piece list
1412 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1413 index[from] = pieceCount[us][PAWN];
1414 pieceList[us][promotion][index[to]] =
1415 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1416 index[pieceList[us][promotion][index[to]]] = index[to];
1418 // Update piece counts
1419 pieceCount[us][promotion]--;
1420 pieceCount[us][PAWN]++;
1422 capture = u.capture;
1426 assert(capture != KING);
1428 // Insert captured piece:
1429 set_bit(&(byColorBB[them]), to);
1430 set_bit(&(byTypeBB[capture]), to);
1431 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1432 board[to] = piece_of_color_and_type(them, capture);
1434 // Update material. Because the move is a promotion move, we know
1435 // that the captured piece cannot be a pawn.
1436 assert(capture != PAWN);
1437 npMaterial[them] += piece_value_midgame(capture);
1439 // Update piece list
1440 pieceList[them][capture][pieceCount[them][capture]] = to;
1441 index[to] = pieceCount[them][capture];
1443 // Update piece count
1444 pieceCount[them][capture]++;
1450 /// Position::undo_ep_move() is a private method used to unmake an en passant
1451 /// capture. It is called from the main Position::undo_move function. Because
1452 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1453 /// object from which to retrieve the captured piece.
1455 void Position::undo_ep_move(Move m) {
1457 assert(move_is_ok(m));
1458 assert(move_is_ep(m));
1460 // When we have arrived here, some work has already been done by
1461 // Position::undo_move. In particular, the side to move has been switched,
1462 // so the code below is correct.
1463 Color us = side_to_move();
1464 Color them = opposite_color(us);
1465 Square from = move_from(m);
1466 Square to = move_to(m);
1467 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1469 assert(to == ep_square());
1470 assert(relative_rank(us, to) == RANK_6);
1471 assert(piece_on(to) == pawn_of_color(us));
1472 assert(piece_on(from) == EMPTY);
1473 assert(piece_on(capsq) == EMPTY);
1475 // Replace captured piece
1476 set_bit(&(byColorBB[them]), capsq);
1477 set_bit(&(byTypeBB[PAWN]), capsq);
1478 set_bit(&(byTypeBB[0]), capsq);
1479 board[capsq] = pawn_of_color(them);
1481 // Remove moving piece from destination square
1482 clear_bit(&(byColorBB[us]), to);
1483 clear_bit(&(byTypeBB[PAWN]), to);
1484 clear_bit(&(byTypeBB[0]), to);
1487 // Replace moving piece at source square
1488 set_bit(&(byColorBB[us]), from);
1489 set_bit(&(byTypeBB[PAWN]), from);
1490 set_bit(&(byTypeBB[0]), from);
1491 board[from] = pawn_of_color(us);
1493 // Update piece list:
1494 pieceList[us][PAWN][index[to]] = from;
1495 index[from] = index[to];
1496 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1497 index[capsq] = pieceCount[them][PAWN];
1499 // Update piece count:
1500 pieceCount[them][PAWN]++;
1504 /// Position::do_null_move makes() a "null move": It switches the side to move
1505 /// and updates the hash key without executing any move on the board.
1507 void Position::do_null_move(UndoInfo &u) {
1510 assert(!is_check());
1512 // Back up the information necessary to undo the null move to the supplied
1513 // UndoInfo object. In the case of a null move, the only thing we need to
1514 // remember is the last move made and the en passant square.
1515 u.lastMove = lastMove;
1516 u.epSquare = epSquare;
1518 // Save the current key to the history[] array, in order to be able to
1519 // detect repetition draws.
1520 history[gamePly] = key;
1522 // Update the necessary information
1523 sideToMove = opposite_color(sideToMove);
1524 if (epSquare != SQ_NONE)
1525 key ^= zobEp[epSquare];
1530 key ^= zobSideToMove;
1532 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1533 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1539 /// Position::undo_null_move() unmakes a "null move".
1541 void Position::undo_null_move(const UndoInfo &u) {
1544 assert(!is_check());
1546 // Restore information from the supplied UndoInfo object:
1547 lastMove = u.lastMove;
1548 epSquare = u.epSquare;
1549 if (epSquare != SQ_NONE)
1550 key ^= zobEp[epSquare];
1552 // Update the necessary information.
1553 sideToMove = opposite_color(sideToMove);
1556 key ^= zobSideToMove;
1558 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1559 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1565 /// Position::see() is a static exchange evaluator: It tries to estimate the
1566 /// material gain or loss resulting from a move. There are three versions of
1567 /// this function: One which takes a destination square as input, one takes a
1568 /// move, and one which takes a 'from' and a 'to' square. The function does
1569 /// not yet understand promotions or en passant captures.
1571 int Position::see(Square to) const {
1573 assert(square_is_ok(to));
1574 return see(SQ_NONE, to);
1577 int Position::see(Move m) const {
1579 assert(move_is_ok(m));
1580 return see(move_from(m), move_to(m));
1583 int Position::see(Square from, Square to) const {
1586 static const int seeValues[18] = {
1587 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1588 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1589 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1590 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1594 Bitboard attackers, occ, b;
1596 assert(square_is_ok(from) || from == SQ_NONE);
1597 assert(square_is_ok(to));
1599 // Initialize colors
1600 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1601 Color them = opposite_color(us);
1603 // Initialize pieces
1604 Piece piece = piece_on(from);
1605 Piece capture = piece_on(to);
1607 // Find all attackers to the destination square, with the moving piece
1608 // removed, but possibly an X-ray attacker added behind it.
1609 occ = occupied_squares();
1611 // Handle enpassant moves
1612 if (ep_square() == to && type_of_piece_on(from) == PAWN)
1614 assert(capture == EMPTY);
1616 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1617 capture = piece_on(capQq);
1619 assert(type_of_piece_on(capQq) == PAWN);
1621 // Remove the captured pawn
1622 clear_bit(&occ, capQq);
1627 clear_bit(&occ, from);
1628 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1629 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1630 | (piece_attacks<KNIGHT>(to) & knights())
1631 | (piece_attacks<KING>(to) & kings())
1632 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1633 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1635 if (from != SQ_NONE)
1638 // If we don't have any attacker we are finished
1639 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1642 // Locate the least valuable attacker to the destination square
1643 // and use it to initialize from square.
1645 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1648 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1649 piece = piece_on(from);
1652 // If the opponent has no attackers we are finished
1653 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1654 return seeValues[capture];
1656 attackers &= occ; // Remove the moving piece
1658 // The destination square is defended, which makes things rather more
1659 // difficult to compute. We proceed by building up a "swap list" containing
1660 // the material gain or loss at each stop in a sequence of captures to the
1661 // destination square, where the sides alternately capture, and always
1662 // capture with the least valuable piece. After each capture, we look for
1663 // new X-ray attacks from behind the capturing piece.
1664 int lastCapturingPieceValue = seeValues[piece];
1665 int swapList[32], n = 1;
1669 swapList[0] = seeValues[capture];
1672 // Locate the least valuable attacker for the side to move. The loop
1673 // below looks like it is potentially infinite, but it isn't. We know
1674 // that the side to move still has at least one attacker left.
1675 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1678 // Remove the attacker we just found from the 'attackers' bitboard,
1679 // and scan for new X-ray attacks behind the attacker.
1680 b = attackers & pieces_of_color_and_type(c, pt);
1682 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1683 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1687 // Add the new entry to the swap list
1689 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1692 // Remember the value of the capturing piece, and change the side to move
1693 // before beginning the next iteration
1694 lastCapturingPieceValue = seeValues[pt];
1695 c = opposite_color(c);
1697 // Stop after a king capture
1698 if (pt == KING && (attackers & pieces_of_color(c)))
1701 swapList[n++] = 100;
1704 } while (attackers & pieces_of_color(c));
1706 // Having built the swap list, we negamax through it to find the best
1707 // achievable score from the point of view of the side to move
1709 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1715 /// Position::clear() erases the position object to a pristine state, with an
1716 /// empty board, white to move, and no castling rights.
1718 void Position::clear() {
1720 for (int i = 0; i < 64; i++)
1726 for (int i = 0; i < 2; i++)
1727 byColorBB[i] = EmptyBoardBB;
1729 for (int i = 0; i < 7; i++)
1731 byTypeBB[i] = EmptyBoardBB;
1732 pieceCount[0][i] = pieceCount[1][i] = 0;
1733 for (int j = 0; j < 8; j++)
1734 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1737 checkersBB = EmptyBoardBB;
1739 lastMove = MOVE_NONE;
1742 castleRights = NO_CASTLES;
1743 initialKFile = FILE_E;
1744 initialKRFile = FILE_H;
1745 initialQRFile = FILE_A;
1752 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1753 /// UCI interface code, whenever a non-reversible move is made in a
1754 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1755 /// for the program to handle games of arbitrary length, as long as the GUI
1756 /// handles draws by the 50 move rule correctly.
1758 void Position::reset_game_ply() {
1764 /// Position::put_piece() puts a piece on the given square of the board,
1765 /// updating the board array, bitboards, and piece counts.
1767 void Position::put_piece(Piece p, Square s) {
1769 Color c = color_of_piece(p);
1770 PieceType pt = type_of_piece(p);
1773 index[s] = pieceCount[c][pt];
1774 pieceList[c][pt][index[s]] = s;
1776 set_bit(&(byTypeBB[pt]), s);
1777 set_bit(&(byColorBB[c]), s);
1778 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1780 pieceCount[c][pt]++;
1787 /// Position::allow_oo() gives the given side the right to castle kingside.
1788 /// Used when setting castling rights during parsing of FEN strings.
1790 void Position::allow_oo(Color c) {
1792 castleRights |= (1 + int(c));
1796 /// Position::allow_ooo() gives the given side the right to castle queenside.
1797 /// Used when setting castling rights during parsing of FEN strings.
1799 void Position::allow_ooo(Color c) {
1801 castleRights |= (4 + 4*int(c));
1805 /// Position::compute_key() computes the hash key of the position. The hash
1806 /// key is usually updated incrementally as moves are made and unmade, the
1807 /// compute_key() function is only used when a new position is set up, and
1808 /// to verify the correctness of the hash key when running in debug mode.
1810 Key Position::compute_key() const {
1812 Key result = Key(0ULL);
1814 for (Square s = SQ_A1; s <= SQ_H8; s++)
1815 if (square_is_occupied(s))
1816 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1818 if (ep_square() != SQ_NONE)
1819 result ^= zobEp[ep_square()];
1821 result ^= zobCastle[castleRights];
1822 if (side_to_move() == BLACK)
1823 result ^= zobSideToMove;
1829 /// Position::compute_pawn_key() computes the hash key of the position. The
1830 /// hash key is usually updated incrementally as moves are made and unmade,
1831 /// the compute_pawn_key() function is only used when a new position is set
1832 /// up, and to verify the correctness of the pawn hash key when running in
1835 Key Position::compute_pawn_key() const {
1837 Key result = Key(0ULL);
1841 for (Color c = WHITE; c <= BLACK; c++)
1846 s = pop_1st_bit(&b);
1847 result ^= zobrist[c][PAWN][s];
1854 /// Position::compute_material_key() computes the hash key of the position.
1855 /// The hash key is usually updated incrementally as moves are made and unmade,
1856 /// the compute_material_key() function is only used when a new position is set
1857 /// up, and to verify the correctness of the material hash key when running in
1860 Key Position::compute_material_key() const {
1862 Key result = Key(0ULL);
1863 for (Color c = WHITE; c <= BLACK; c++)
1864 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1866 int count = piece_count(c, pt);
1867 for (int i = 0; i <= count; i++)
1868 result ^= zobMaterial[c][pt][i];
1874 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1875 /// incremental scores for the middle game and the endgame. These functions
1876 /// are used to initialize the incremental scores when a new position is set
1877 /// up, and to verify that the scores are correctly updated by do_move
1878 /// and undo_move when the program is running in debug mode.
1880 Value Position::compute_mg_value() const {
1882 Value result = Value(0);
1886 for (Color c = WHITE; c <= BLACK; c++)
1887 for (PieceType pt = PAWN; pt <= KING; pt++)
1889 b = pieces_of_color_and_type(c, pt);
1892 s = pop_1st_bit(&b);
1893 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1894 result += mg_pst(c, pt, s);
1897 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1901 Value Position::compute_eg_value() const {
1903 Value result = Value(0);
1907 for (Color c = WHITE; c <= BLACK; c++)
1908 for (PieceType pt = PAWN; pt <= KING; pt++)
1910 b = pieces_of_color_and_type(c, pt);
1913 s = pop_1st_bit(&b);
1914 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1915 result += eg_pst(c, pt, s);
1918 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1923 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1924 /// game material score for the given side. Material scores are updated
1925 /// incrementally during the search, this function is only used while
1926 /// initializing a new Position object.
1928 Value Position::compute_non_pawn_material(Color c) const {
1930 Value result = Value(0);
1933 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1935 Bitboard b = pieces_of_color_and_type(c, pt);
1938 s = pop_1st_bit(&b);
1939 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1940 result += piece_value_midgame(pt);
1947 /// Position::is_mate() returns true or false depending on whether the
1948 /// side to move is checkmated. Note that this function is currently very
1949 /// slow, and shouldn't be used frequently inside the search.
1951 bool Position::is_mate() const {
1955 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1956 return mp.get_next_move() == MOVE_NONE;
1962 /// Position::is_draw() tests whether the position is drawn by material,
1963 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1964 /// must be done by the search.
1966 bool Position::is_draw() const {
1968 // Draw by material?
1970 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1973 // Draw by the 50 moves rule?
1974 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1977 // Draw by repetition?
1978 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1979 if (history[gamePly - i] == key)
1986 /// Position::has_mate_threat() tests whether a given color has a mate in one
1987 /// from the current position. This function is quite slow, but it doesn't
1988 /// matter, because it is currently only called from PV nodes, which are rare.
1990 bool Position::has_mate_threat(Color c) {
1993 Color stm = side_to_move();
1995 // The following lines are useless and silly, but prevents gcc from
1996 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1997 // be used uninitialized.
1998 u1.lastMove = lastMove;
1999 u1.epSquare = epSquare;
2004 // If the input color is not equal to the side to move, do a null move
2008 MoveStack mlist[120];
2010 bool result = false;
2012 // Generate legal moves
2013 count = generate_legal_moves(*this, mlist);
2015 // Loop through the moves, and see if one of them is mate
2016 for (int i = 0; i < count; i++)
2018 do_move(mlist[i].move, u2);
2022 undo_move(mlist[i].move, u2);
2025 // Undo null move, if necessary
2033 /// Position::init_zobrist() is a static member function which initializes the
2034 /// various arrays used to compute hash keys.
2036 void Position::init_zobrist() {
2038 for (int i = 0; i < 2; i++)
2039 for (int j = 0; j < 8; j++)
2040 for (int k = 0; k < 64; k++)
2041 zobrist[i][j][k] = Key(genrand_int64());
2043 for (int i = 0; i < 64; i++)
2044 zobEp[i] = Key(genrand_int64());
2046 for (int i = 0; i < 16; i++)
2047 zobCastle[i] = genrand_int64();
2049 zobSideToMove = genrand_int64();
2051 for (int i = 0; i < 2; i++)
2052 for (int j = 0; j < 8; j++)
2053 for (int k = 0; k < 16; k++)
2054 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2056 for (int i = 0; i < 16; i++)
2057 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2061 /// Position::init_piece_square_tables() initializes the piece square tables.
2062 /// This is a two-step operation: First, the white halves of the tables are
2063 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2064 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2065 /// Second, the black halves of the tables are initialized by mirroring
2066 /// and changing the sign of the corresponding white scores.
2068 void Position::init_piece_square_tables() {
2070 int r = get_option_value_int("Randomness"), i;
2071 for (Square s = SQ_A1; s <= SQ_H8; s++)
2072 for (Piece p = WP; p <= WK; p++)
2074 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2075 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2076 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2079 for (Square s = SQ_A1; s <= SQ_H8; s++)
2080 for (Piece p = BP; p <= BK; p++)
2082 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2083 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2088 /// Position::flipped_copy() makes a copy of the input position, but with
2089 /// the white and black sides reversed. This is only useful for debugging,
2090 /// especially for finding evaluation symmetry bugs.
2092 void Position::flipped_copy(const Position &pos) {
2094 assert(pos.is_ok());
2099 for (Square s = SQ_A1; s <= SQ_H8; s++)
2100 if (!pos.square_is_empty(s))
2101 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2104 sideToMove = opposite_color(pos.side_to_move());
2107 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2108 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2109 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2110 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2112 initialKFile = pos.initialKFile;
2113 initialKRFile = pos.initialKRFile;
2114 initialQRFile = pos.initialQRFile;
2116 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2117 castleRightsMask[sq] = ALL_CASTLES;
2119 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2120 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2121 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2122 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2123 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2124 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2126 // En passant square
2127 if (pos.epSquare != SQ_NONE)
2128 epSquare = flip_square(pos.epSquare);
2134 key = compute_key();
2135 pawnKey = compute_pawn_key();
2136 materialKey = compute_material_key();
2138 // Incremental scores
2139 mgValue = compute_mg_value();
2140 egValue = compute_eg_value();
2143 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2144 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2150 /// Position::is_ok() performs some consitency checks for the position object.
2151 /// This is meant to be helpful when debugging.
2153 bool Position::is_ok(int* failedStep) const {
2155 // What features of the position should be verified?
2156 static const bool debugBitboards = false;
2157 static const bool debugKingCount = false;
2158 static const bool debugKingCapture = false;
2159 static const bool debugCheckerCount = false;
2160 static const bool debugKey = false;
2161 static const bool debugMaterialKey = false;
2162 static const bool debugPawnKey = false;
2163 static const bool debugIncrementalEval = false;
2164 static const bool debugNonPawnMaterial = false;
2165 static const bool debugPieceCounts = false;
2166 static const bool debugPieceList = false;
2168 if (failedStep) *failedStep = 1;
2171 if (!color_is_ok(side_to_move()))
2174 // Are the king squares in the position correct?
2175 if (failedStep) (*failedStep)++;
2176 if (piece_on(king_square(WHITE)) != WK)
2179 if (failedStep) (*failedStep)++;
2180 if (piece_on(king_square(BLACK)) != BK)
2184 if (failedStep) (*failedStep)++;
2185 if (!file_is_ok(initialKRFile))
2188 if (!file_is_ok(initialQRFile))
2191 // Do both sides have exactly one king?
2192 if (failedStep) (*failedStep)++;
2195 int kingCount[2] = {0, 0};
2196 for (Square s = SQ_A1; s <= SQ_H8; s++)
2197 if (type_of_piece_on(s) == KING)
2198 kingCount[color_of_piece_on(s)]++;
2200 if(kingCount[0] != 1 || kingCount[1] != 1)
2204 // Can the side to move capture the opponent's king?
2205 if (failedStep) (*failedStep)++;
2206 if (debugKingCapture)
2208 Color us = side_to_move();
2209 Color them = opposite_color(us);
2210 Square ksq = king_square(them);
2211 if (square_is_attacked(ksq, us))
2215 // Is there more than 2 checkers?
2216 if (failedStep) (*failedStep)++;
2217 if (debugCheckerCount && count_1s(checkersBB) > 2)
2221 if (failedStep) (*failedStep)++;
2224 // The intersection of the white and black pieces must be empty
2225 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2228 // The union of the white and black pieces must be equal to all
2230 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2233 // Separate piece type bitboards must have empty intersections
2234 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2235 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2236 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2240 // En passant square OK?
2241 if (failedStep) (*failedStep)++;
2242 if (ep_square() != SQ_NONE)
2244 // The en passant square must be on rank 6, from the point of view of the
2246 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2251 if (failedStep) (*failedStep)++;
2252 if (debugKey && key != compute_key())
2255 // Pawn hash key OK?
2256 if (failedStep) (*failedStep)++;
2257 if (debugPawnKey && pawnKey != compute_pawn_key())
2260 // Material hash key OK?
2261 if (failedStep) (*failedStep)++;
2262 if (debugMaterialKey && materialKey != compute_material_key())
2265 // Incremental eval OK?
2266 if (failedStep) (*failedStep)++;
2267 if (debugIncrementalEval)
2269 if (mgValue != compute_mg_value())
2272 if (egValue != compute_eg_value())
2276 // Non-pawn material OK?
2277 if (failedStep) (*failedStep)++;
2278 if (debugNonPawnMaterial)
2280 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2283 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2288 if (failedStep) (*failedStep)++;
2289 if (debugPieceCounts)
2290 for (Color c = WHITE; c <= BLACK; c++)
2291 for (PieceType pt = PAWN; pt <= KING; pt++)
2292 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2295 if (failedStep) (*failedStep)++;
2298 for(Color c = WHITE; c <= BLACK; c++)
2299 for(PieceType pt = PAWN; pt <= KING; pt++)
2300 for(int i = 0; i < pieceCount[c][pt]; i++)
2302 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2305 if (index[piece_list(c, pt, i)] != i)
2309 if (failedStep) *failedStep = 0;