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 st.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;
210 st.key = compute_key();
211 st.pawnKey = compute_pawn_key();
212 st.materialKey = compute_material_key();
213 st.mgValue = compute_value<MidGame>();
214 st.egValue = compute_value<EndGame>();
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 (st.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: " << st.key << std::endl;
310 RequestPending = false;
314 /// Position::copy() creates a copy of the input position.
316 void Position::copy(const Position &pos) {
318 memcpy(this, &pos, sizeof(Position));
322 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
323 /// king) pieces for the given color.
324 Bitboard Position::pinned_pieces(Color c) const {
326 if (st.pinned[c] != ~EmptyBoardBB)
330 Square ksq = king_square(c);
331 st.pinned[c] = hidden_checks<ROOK, true>(c, ksq, p1) | hidden_checks<BISHOP, true>(c, ksq, p2);
332 st.pinners[c] = p1 | p2;
336 Bitboard Position::pinned_pieces(Color c, Bitboard& p) const {
338 if (st.pinned[c] == ~EmptyBoardBB)
345 Bitboard Position::discovered_check_candidates(Color c) const {
347 if (st.dcCandidates[c] != ~EmptyBoardBB)
348 return st.dcCandidates[c];
351 Square ksq = king_square(opposite_color(c));
352 st.dcCandidates[c] = hidden_checks<ROOK, false>(c, ksq, dummy) | hidden_checks<BISHOP, false>(c, ksq, dummy);
353 return st.dcCandidates[c];
356 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
357 /// king) pieces for the given color and for the given pinner type. Or, when
358 /// template parameter FindPinned is false, the pinned pieces of opposite color
359 /// that are, indeed, the pieces candidate for a discovery check.
360 template<PieceType Piece, bool FindPinned>
361 Bitboard Position::hidden_checks(Color c, Square ksq, Bitboard& pinners) const {
364 Bitboard sliders, result = EmptyBoardBB;
366 if (Piece == ROOK) // Resolved at compile time
367 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
369 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
371 if (sliders && (!FindPinned || (sliders & ~st.checkersBB)))
373 // King blockers are candidate pinned pieces
374 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
376 // Pinners are sliders, not checkers, that give check when
377 // candidate pinned are removed.
378 pinners = (FindPinned ? sliders & ~st.checkersBB : sliders);
381 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
383 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
385 // Finally for each pinner find the corresponding pinned piece (if same color of king)
386 // or discovery checker (if opposite color) among the candidates.
387 Bitboard p = pinners;
391 result |= (squares_between(s, ksq) & candidate_pinned);
395 pinners = EmptyBoardBB;
401 /// Position::attacks_to() computes a bitboard containing all pieces which
402 /// attacks a given square. There are two versions of this function: One
403 /// which finds attackers of both colors, and one which only finds the
404 /// attackers for one side.
406 Bitboard Position::attacks_to(Square s) const {
408 return (pawn_attacks(BLACK, s) & pawns(WHITE))
409 | (pawn_attacks(WHITE, s) & pawns(BLACK))
410 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
411 | (piece_attacks<ROOK>(s) & rooks_and_queens())
412 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
413 | (piece_attacks<KING>(s) & pieces_of_type(KING));
416 /// Position::piece_attacks_square() tests whether the piece on square f
417 /// attacks square t.
419 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
421 assert(square_is_ok(f));
422 assert(square_is_ok(t));
426 case WP: return pawn_attacks_square(WHITE, f, t);
427 case BP: return pawn_attacks_square(BLACK, f, t);
428 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
429 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
430 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
431 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
432 case WK: case BK: return piece_attacks_square<KING>(f, t);
439 /// Position::move_attacks_square() tests whether a move from the current
440 /// position attacks a given square.
442 bool Position::move_attacks_square(Move m, Square s) const {
444 assert(move_is_ok(m));
445 assert(square_is_ok(s));
447 Square f = move_from(m), t = move_to(m);
449 assert(square_is_occupied(f));
451 if (piece_attacks_square(piece_on(f), t, s))
454 // Move the piece and scan for X-ray attacks behind it
455 Bitboard occ = occupied_squares();
456 Color us = color_of_piece_on(f);
459 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
460 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
462 // If we have attacks we need to verify that are caused by our move
463 // and are not already existent ones.
464 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
468 /// Position::find_checkers() computes the checkersBB bitboard, which
469 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
470 /// currently works by calling Position::attacks_to, which is probably
471 /// inefficient. Consider rewriting this function to use the last move
472 /// played, like in non-bitboard versions of Glaurung.
474 void Position::find_checkers() {
476 Color us = side_to_move();
477 st.checkersBB = attacks_to(king_square(us), opposite_color(us));
481 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
483 bool Position::pl_move_is_legal(Move m) const {
486 assert(move_is_ok(m));
488 // If we're in check, all pseudo-legal moves are legal, because our
489 // check evasion generator only generates true legal moves.
493 // Castling moves are checked for legality during move generation.
494 if (move_is_castle(m))
497 Color us = side_to_move();
498 Color them = opposite_color(us);
499 Square from = move_from(m);
500 Square ksq = king_square(us);
502 assert(color_of_piece_on(from) == us);
503 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
505 // En passant captures are a tricky special case. Because they are
506 // rather uncommon, we do it simply by testing whether the king is attacked
507 // after the move is made
510 Square to = move_to(m);
511 Square capsq = make_square(square_file(to), square_rank(from));
512 Bitboard b = occupied_squares();
514 assert(to == ep_square());
515 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
516 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
517 assert(piece_on(to) == EMPTY);
520 clear_bit(&b, capsq);
523 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
524 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
527 // If the moving piece is a king, check whether the destination
528 // square is attacked by the opponent.
530 return !(square_is_attacked(move_to(m), them));
532 // A non-king move is legal if and only if it is not pinned or it
533 // is moving along the ray towards or away from the king.
534 return ( !bit_is_set(pinned_pieces(us), from)
535 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
539 /// Position::move_is_check() tests whether a pseudo-legal move is a check
541 bool Position::move_is_check(Move m) const {
544 assert(move_is_ok(m));
546 Color us = side_to_move();
547 Color them = opposite_color(us);
548 Square from = move_from(m);
549 Square to = move_to(m);
550 Square ksq = king_square(them);
551 Bitboard dcCandidates = discovered_check_candidates(us);
553 assert(color_of_piece_on(from) == us);
554 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
556 // Proceed according to the type of the moving piece
557 switch (type_of_piece_on(from))
561 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
564 if ( bit_is_set(dcCandidates, from) // Discovered check?
565 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
568 if (move_promotion(m)) // Promotion with check?
570 Bitboard b = occupied_squares();
573 switch (move_promotion(m))
576 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
578 return bit_is_set(bishop_attacks_bb(to, b), ksq);
580 return bit_is_set(rook_attacks_bb(to, b), ksq);
582 return bit_is_set(queen_attacks_bb(to, b), ksq);
587 // En passant capture with check? We have already handled the case
588 // of direct checks and ordinary discovered check, the only case we
589 // need to handle is the unusual case of a discovered check through the
591 else if (move_is_ep(m))
593 Square capsq = make_square(square_file(to), square_rank(from));
594 Bitboard b = occupied_squares();
596 clear_bit(&b, capsq);
598 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
599 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
604 return bit_is_set(dcCandidates, from) // Discovered check?
605 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
608 return bit_is_set(dcCandidates, from) // Discovered check?
609 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
612 return bit_is_set(dcCandidates, from) // Discovered check?
613 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
616 // Discovered checks are impossible!
617 assert(!bit_is_set(dcCandidates, from));
618 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
622 if ( bit_is_set(dcCandidates, from)
623 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
626 // Castling with check?
627 if (move_is_castle(m))
629 Square kfrom, kto, rfrom, rto;
630 Bitboard b = occupied_squares();
636 kto = relative_square(us, SQ_G1);
637 rto = relative_square(us, SQ_F1);
639 kto = relative_square(us, SQ_C1);
640 rto = relative_square(us, SQ_D1);
642 clear_bit(&b, kfrom);
643 clear_bit(&b, rfrom);
646 return bit_is_set(rook_attacks_bb(rto, b), ksq);
650 default: // NO_PIECE_TYPE
658 /// Position::move_is_capture() tests whether a move from the current
659 /// position is a capture. Move must not be MOVE_NONE.
661 bool Position::move_is_capture(Move m) const {
663 assert(m != MOVE_NONE);
665 return ( !square_is_empty(move_to(m))
666 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
672 /// Position::update_checkers() is a private method to udpate chekers info
674 template<PieceType Piece>
675 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
676 Square to, Bitboard dcCandidates) {
678 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
679 set_bit(pCheckersBB, to);
681 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
684 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
687 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
692 /// Position::do_move() makes a move, and backs up all information necessary
693 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
694 /// Pseudo-legal moves should be filtered out before this function is called.
696 void Position::do_move(Move m, UndoInfo& u) {
699 assert(move_is_ok(m));
701 // Get now the current (pre-move) dc candidates that we will use
702 // in update_checkers().
703 Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
705 // Back up the necessary information to our UndoInfo object (except the
706 // captured piece, which is taken care of later.
708 u.capture = NO_PIECE_TYPE;
711 // Save the current key to the history[] array, in order to be able to
712 // detect repetition draws.
713 history[gamePly] = st.key;
715 // Increment the 50 moves rule draw counter. Resetting it to zero in the
716 // case of non-reversible moves is taken care of later.
719 // Reset pinned bitboard and its friends
720 for (Color c = WHITE; c <= BLACK; c++)
721 st.pinners[c] = st.pinned[c] = st.dcCandidates[c] = ~EmptyBoardBB;
723 if (move_is_castle(m))
725 else if (move_promotion(m))
726 do_promotion_move(m);
727 else if (move_is_ep(m))
731 Color us = side_to_move();
732 Color them = opposite_color(us);
733 Square from = move_from(m);
734 Square to = move_to(m);
736 assert(color_of_piece_on(from) == us);
737 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
739 PieceType piece = type_of_piece_on(from);
741 st.capture = type_of_piece_on(to);
745 u.capture = st.capture;
746 do_capture_move(m, st.capture, them, to);
750 clear_bit(&(byColorBB[us]), from);
751 clear_bit(&(byTypeBB[piece]), from);
752 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
753 set_bit(&(byColorBB[us]), to);
754 set_bit(&(byTypeBB[piece]), to);
755 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
756 board[to] = board[from];
760 st.key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
762 // Update incremental scores
763 st.mgValue -= pst<MidGame>(us, piece, from);
764 st.mgValue += pst<MidGame>(us, piece, to);
765 st.egValue -= pst<EndGame>(us, piece, from);
766 st.egValue += pst<EndGame>(us, piece, to);
768 // If the moving piece was a king, update the king square
772 // Reset en passant square
773 if (st.epSquare != SQ_NONE)
775 st.key ^= zobEp[st.epSquare];
776 st.epSquare = SQ_NONE;
779 // If the moving piece was a pawn do some special extra work
782 // Reset rule 50 draw counter
785 // Update pawn hash key
786 st.pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
788 // Set en passant square, only if moved pawn can be captured
789 if (abs(int(to) - int(from)) == 16)
791 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
792 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
794 st.epSquare = Square((int(from) + int(to)) / 2);
795 st.key ^= zobEp[st.epSquare];
800 // Update piece lists
801 pieceList[us][piece][index[from]] = to;
802 index[to] = index[from];
804 // Update castle rights
805 st.key ^= zobCastle[st.castleRights];
806 st.castleRights &= castleRightsMask[from];
807 st.castleRights &= castleRightsMask[to];
808 st.key ^= zobCastle[st.castleRights];
810 // Update checkers bitboard, piece must be already moved
811 st.checkersBB = EmptyBoardBB;
812 Square ksq = king_square(them);
815 case PAWN: update_checkers<PAWN>(&st.checkersBB, ksq, from, to, oldDcCandidates); break;
816 case KNIGHT: update_checkers<KNIGHT>(&st.checkersBB, ksq, from, to, oldDcCandidates); break;
817 case BISHOP: update_checkers<BISHOP>(&st.checkersBB, ksq, from, to, oldDcCandidates); break;
818 case ROOK: update_checkers<ROOK>(&st.checkersBB, ksq, from, to, oldDcCandidates); break;
819 case QUEEN: update_checkers<QUEEN>(&st.checkersBB, ksq, from, to, oldDcCandidates); break;
820 case KING: update_checkers<KING>(&st.checkersBB, ksq, from, to, oldDcCandidates); break;
821 default: assert(false); break;
826 st.key ^= zobSideToMove;
827 sideToMove = opposite_color(sideToMove);
830 st.mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
831 st.egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
837 /// Position::do_capture_move() is a private method used to update captured
838 /// piece info. It is called from the main Position::do_move function.
840 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
842 assert(capture != KING);
844 // Remove captured piece
845 clear_bit(&(byColorBB[them]), to);
846 clear_bit(&(byTypeBB[capture]), to);
849 st.key ^= zobrist[them][capture][to];
851 // If the captured piece was a pawn, update pawn hash key
853 st.pawnKey ^= zobrist[them][PAWN][to];
855 // Update incremental scores
856 st.mgValue -= pst<MidGame>(them, capture, to);
857 st.egValue -= pst<EndGame>(them, capture, to);
859 assert(!move_promotion(m) || capture != PAWN);
863 npMaterial[them] -= piece_value_midgame(capture);
865 // Update material hash key
866 st.materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
868 // Update piece count
869 pieceCount[them][capture]--;
872 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
873 index[pieceList[them][capture][index[to]]] = index[to];
875 // Reset rule 50 counter
880 /// Position::do_castle_move() is a private method used to make a castling
881 /// move. It is called from the main Position::do_move function. Note that
882 /// castling moves are encoded as "king captures friendly rook" moves, for
883 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
885 void Position::do_castle_move(Move m) {
888 assert(move_is_ok(m));
889 assert(move_is_castle(m));
891 Color us = side_to_move();
892 Color them = opposite_color(us);
894 // Find source squares for king and rook
895 Square kfrom = move_from(m);
896 Square rfrom = move_to(m); // HACK: See comment at beginning of function
899 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
900 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
902 // Find destination squares for king and rook
903 if (rfrom > kfrom) // O-O
905 kto = relative_square(us, SQ_G1);
906 rto = relative_square(us, SQ_F1);
908 kto = relative_square(us, SQ_C1);
909 rto = relative_square(us, SQ_D1);
912 // Remove pieces from source squares
913 clear_bit(&(byColorBB[us]), kfrom);
914 clear_bit(&(byTypeBB[KING]), kfrom);
915 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
916 clear_bit(&(byColorBB[us]), rfrom);
917 clear_bit(&(byTypeBB[ROOK]), rfrom);
918 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
920 // Put pieces on destination squares
921 set_bit(&(byColorBB[us]), kto);
922 set_bit(&(byTypeBB[KING]), kto);
923 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
924 set_bit(&(byColorBB[us]), rto);
925 set_bit(&(byTypeBB[ROOK]), rto);
926 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
928 // Update board array
929 board[kfrom] = board[rfrom] = EMPTY;
930 board[kto] = piece_of_color_and_type(us, KING);
931 board[rto] = piece_of_color_and_type(us, ROOK);
933 // Update king square
934 kingSquare[us] = kto;
936 // Update piece lists
937 pieceList[us][KING][index[kfrom]] = kto;
938 pieceList[us][ROOK][index[rfrom]] = rto;
939 int tmp = index[rfrom];
940 index[kto] = index[kfrom];
943 // Update incremental scores
944 st.mgValue -= pst<MidGame>(us, KING, kfrom);
945 st.mgValue += pst<MidGame>(us, KING, kto);
946 st.egValue -= pst<EndGame>(us, KING, kfrom);
947 st.egValue += pst<EndGame>(us, KING, kto);
948 st.mgValue -= pst<MidGame>(us, ROOK, rfrom);
949 st.mgValue += pst<MidGame>(us, ROOK, rto);
950 st.egValue -= pst<EndGame>(us, ROOK, rfrom);
951 st.egValue += pst<EndGame>(us, ROOK, rto);
954 st.key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
955 st.key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
957 // Clear en passant square
958 if (st.epSquare != SQ_NONE)
960 st.key ^= zobEp[st.epSquare];
961 st.epSquare = SQ_NONE;
964 // Update castling rights
965 st.key ^= zobCastle[st.castleRights];
966 st.castleRights &= castleRightsMask[kfrom];
967 st.key ^= zobCastle[st.castleRights];
969 // Reset rule 50 counter
972 // Update checkers BB
973 st.checkersBB = attacks_to(king_square(them), us);
977 /// Position::do_promotion_move() is a private method used to make a promotion
978 /// move. It is called from the main Position::do_move function. The
979 /// UndoInfo object, which has been initialized in Position::do_move, is
980 /// used to store the captured piece (if any).
982 void Position::do_promotion_move(Move m) {
989 assert(move_is_ok(m));
990 assert(move_promotion(m));
993 them = opposite_color(us);
997 assert(relative_rank(us, to) == RANK_8);
998 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
999 assert(color_of_piece_on(to) == them || square_is_empty(to));
1001 st.capture = type_of_piece_on(to);
1005 st.previous->capture = st.capture;
1006 do_capture_move(m, st.capture, them, to);
1010 clear_bit(&(byColorBB[us]), from);
1011 clear_bit(&(byTypeBB[PAWN]), from);
1012 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1013 board[from] = EMPTY;
1015 // Insert promoted piece
1016 promotion = move_promotion(m);
1017 assert(promotion >= KNIGHT && promotion <= QUEEN);
1018 set_bit(&(byColorBB[us]), to);
1019 set_bit(&(byTypeBB[promotion]), to);
1020 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1021 board[to] = piece_of_color_and_type(us, promotion);
1024 st.key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1026 // Update pawn hash key
1027 st.pawnKey ^= zobrist[us][PAWN][from];
1029 // Update material key
1030 st.materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1031 st.materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1033 // Update piece counts
1034 pieceCount[us][PAWN]--;
1035 pieceCount[us][promotion]++;
1037 // Update piece lists
1038 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1039 index[pieceList[us][PAWN][index[from]]] = index[from];
1040 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1041 index[to] = pieceCount[us][promotion] - 1;
1043 // Update incremental scores
1044 st.mgValue -= pst<MidGame>(us, PAWN, from);
1045 st.mgValue += pst<MidGame>(us, promotion, to);
1046 st.egValue -= pst<EndGame>(us, PAWN, from);
1047 st.egValue += pst<EndGame>(us, promotion, to);
1050 npMaterial[us] += piece_value_midgame(promotion);
1052 // Clear the en passant square
1053 if (st.epSquare != SQ_NONE)
1055 st.key ^= zobEp[st.epSquare];
1056 st.epSquare = SQ_NONE;
1059 // Update castle rights
1060 st.key ^= zobCastle[st.castleRights];
1061 st.castleRights &= castleRightsMask[to];
1062 st.key ^= zobCastle[st.castleRights];
1064 // Reset rule 50 counter
1067 // Update checkers BB
1068 st.checkersBB = attacks_to(king_square(them), us);
1072 /// Position::do_ep_move() is a private method used to make an en passant
1073 /// capture. It is called from the main Position::do_move function. Because
1074 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1075 /// object in which to store the captured piece.
1077 void Position::do_ep_move(Move m) {
1080 Square from, to, capsq;
1083 assert(move_is_ok(m));
1084 assert(move_is_ep(m));
1086 us = side_to_move();
1087 them = opposite_color(us);
1088 from = move_from(m);
1090 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1092 assert(to == st.epSquare);
1093 assert(relative_rank(us, to) == RANK_6);
1094 assert(piece_on(to) == EMPTY);
1095 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1096 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1098 // Remove captured piece
1099 clear_bit(&(byColorBB[them]), capsq);
1100 clear_bit(&(byTypeBB[PAWN]), capsq);
1101 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1102 board[capsq] = EMPTY;
1104 // Remove moving piece from source square
1105 clear_bit(&(byColorBB[us]), from);
1106 clear_bit(&(byTypeBB[PAWN]), from);
1107 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1109 // Put moving piece on destination square
1110 set_bit(&(byColorBB[us]), to);
1111 set_bit(&(byTypeBB[PAWN]), to);
1112 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1113 board[to] = board[from];
1114 board[from] = EMPTY;
1116 // Update material hash key
1117 st.materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1119 // Update piece count
1120 pieceCount[them][PAWN]--;
1122 // Update piece list
1123 pieceList[us][PAWN][index[from]] = to;
1124 index[to] = index[from];
1125 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1126 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1129 st.key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1130 st.key ^= zobrist[them][PAWN][capsq];
1131 st.key ^= zobEp[st.epSquare];
1133 // Update pawn hash key
1134 st.pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1135 st.pawnKey ^= zobrist[them][PAWN][capsq];
1137 // Update incremental scores
1138 st.mgValue -= pst<MidGame>(them, PAWN, capsq);
1139 st.mgValue -= pst<MidGame>(us, PAWN, from);
1140 st.mgValue += pst<MidGame>(us, PAWN, to);
1141 st.egValue -= pst<EndGame>(them, PAWN, capsq);
1142 st.egValue -= pst<EndGame>(us, PAWN, from);
1143 st.egValue += pst<EndGame>(us, PAWN, to);
1145 // Reset en passant square
1146 st.epSquare = SQ_NONE;
1148 // Reset rule 50 counter
1151 // Update checkers BB
1152 st.checkersBB = attacks_to(king_square(them), us);
1156 /// Position::undo_move() unmakes a move. When it returns, the position should
1157 /// be restored to exactly the same state as before the move was made. It is
1158 /// important that Position::undo_move is called with the same move and UndoInfo
1159 /// object as the earlier call to Position::do_move.
1161 void Position::undo_move(Move m) {
1164 assert(move_is_ok(m));
1167 sideToMove = opposite_color(sideToMove);
1169 // Restore information from our UndoInfo object (except the captured piece,
1170 // which is taken care of later)
1171 undoInfoUnion = *(st.previous);
1173 if (move_is_castle(m))
1174 undo_castle_move(m);
1175 else if (move_promotion(m))
1176 undo_promotion_move(m);
1177 else if (move_is_ep(m))
1185 us = side_to_move();
1186 them = opposite_color(us);
1187 from = move_from(m);
1190 assert(piece_on(from) == EMPTY);
1191 assert(color_of_piece_on(to) == us);
1193 // Put the piece back at the source square
1194 piece = type_of_piece_on(to);
1195 set_bit(&(byColorBB[us]), from);
1196 set_bit(&(byTypeBB[piece]), from);
1197 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1198 board[from] = piece_of_color_and_type(us, piece);
1200 // Clear the destination square
1201 clear_bit(&(byColorBB[us]), to);
1202 clear_bit(&(byTypeBB[piece]), to);
1203 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1205 // If the moving piece was a king, update the king square
1207 kingSquare[us] = from;
1209 // Update piece list
1210 pieceList[us][piece][index[to]] = from;
1211 index[from] = index[to];
1215 assert(capture != KING);
1217 // Replace the captured piece
1218 set_bit(&(byColorBB[them]), to);
1219 set_bit(&(byTypeBB[st.capture]), to);
1220 set_bit(&(byTypeBB[0]), to);
1221 board[to] = piece_of_color_and_type(them, st.capture);
1224 if (st.capture != PAWN)
1225 npMaterial[them] += piece_value_midgame(st.capture);
1227 // Update piece list
1228 pieceList[them][st.capture][pieceCount[them][st.capture]] = to;
1229 index[to] = pieceCount[them][st.capture];
1231 // Update piece count
1232 pieceCount[them][st.capture]++;
1241 /// Position::undo_castle_move() is a private method used to unmake a castling
1242 /// move. It is called from the main Position::undo_move function. Note that
1243 /// castling moves are encoded as "king captures friendly rook" moves, for
1244 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1246 void Position::undo_castle_move(Move m) {
1248 assert(move_is_ok(m));
1249 assert(move_is_castle(m));
1251 // When we have arrived here, some work has already been done by
1252 // Position::undo_move. In particular, the side to move has been switched,
1253 // so the code below is correct.
1254 Color us = side_to_move();
1256 // Find source squares for king and rook
1257 Square kfrom = move_from(m);
1258 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1261 // Find destination squares for king and rook
1262 if (rfrom > kfrom) // O-O
1264 kto = relative_square(us, SQ_G1);
1265 rto = relative_square(us, SQ_F1);
1267 kto = relative_square(us, SQ_C1);
1268 rto = relative_square(us, SQ_D1);
1271 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1272 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1274 // Remove pieces from destination squares
1275 clear_bit(&(byColorBB[us]), kto);
1276 clear_bit(&(byTypeBB[KING]), kto);
1277 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1278 clear_bit(&(byColorBB[us]), rto);
1279 clear_bit(&(byTypeBB[ROOK]), rto);
1280 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1282 // Put pieces on source squares
1283 set_bit(&(byColorBB[us]), kfrom);
1284 set_bit(&(byTypeBB[KING]), kfrom);
1285 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1286 set_bit(&(byColorBB[us]), rfrom);
1287 set_bit(&(byTypeBB[ROOK]), rfrom);
1288 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1291 board[rto] = board[kto] = EMPTY;
1292 board[rfrom] = piece_of_color_and_type(us, ROOK);
1293 board[kfrom] = piece_of_color_and_type(us, KING);
1295 // Update king square
1296 kingSquare[us] = kfrom;
1298 // Update piece lists
1299 pieceList[us][KING][index[kto]] = kfrom;
1300 pieceList[us][ROOK][index[rto]] = rfrom;
1301 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1302 index[kfrom] = index[kto];
1307 /// Position::undo_promotion_move() is a private method used to unmake a
1308 /// promotion move. It is called from the main Position::do_move
1309 /// function. The UndoInfo object, which has been initialized in
1310 /// Position::do_move, is used to put back the captured piece (if any).
1312 void Position::undo_promotion_move(Move m) {
1316 PieceType promotion;
1318 assert(move_is_ok(m));
1319 assert(move_promotion(m));
1321 // When we have arrived here, some work has already been done by
1322 // Position::undo_move. In particular, the side to move has been switched,
1323 // so the code below is correct.
1324 us = side_to_move();
1325 them = opposite_color(us);
1326 from = move_from(m);
1329 assert(relative_rank(us, to) == RANK_8);
1330 assert(piece_on(from) == EMPTY);
1332 // Remove promoted piece
1333 promotion = move_promotion(m);
1334 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1335 assert(promotion >= KNIGHT && promotion <= QUEEN);
1336 clear_bit(&(byColorBB[us]), to);
1337 clear_bit(&(byTypeBB[promotion]), to);
1338 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1340 // Insert pawn at source square
1341 set_bit(&(byColorBB[us]), from);
1342 set_bit(&(byTypeBB[PAWN]), from);
1343 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1344 board[from] = piece_of_color_and_type(us, PAWN);
1347 npMaterial[us] -= piece_value_midgame(promotion);
1349 // Update piece list
1350 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1351 index[from] = pieceCount[us][PAWN];
1352 pieceList[us][promotion][index[to]] =
1353 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1354 index[pieceList[us][promotion][index[to]]] = index[to];
1356 // Update piece counts
1357 pieceCount[us][promotion]--;
1358 pieceCount[us][PAWN]++;
1362 assert(capture != KING);
1364 // Insert captured piece:
1365 set_bit(&(byColorBB[them]), to);
1366 set_bit(&(byTypeBB[st.capture]), to);
1367 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1368 board[to] = piece_of_color_and_type(them, st.capture);
1370 // Update material. Because the move is a promotion move, we know
1371 // that the captured piece cannot be a pawn.
1372 assert(capture != PAWN);
1373 npMaterial[them] += piece_value_midgame(st.capture);
1375 // Update piece list
1376 pieceList[them][st.capture][pieceCount[them][st.capture]] = to;
1377 index[to] = pieceCount[them][st.capture];
1379 // Update piece count
1380 pieceCount[them][st.capture]++;
1386 /// Position::undo_ep_move() is a private method used to unmake an en passant
1387 /// capture. It is called from the main Position::undo_move function. Because
1388 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1389 /// object from which to retrieve the captured piece.
1391 void Position::undo_ep_move(Move m) {
1393 assert(move_is_ok(m));
1394 assert(move_is_ep(m));
1396 // When we have arrived here, some work has already been done by
1397 // Position::undo_move. In particular, the side to move has been switched,
1398 // so the code below is correct.
1399 Color us = side_to_move();
1400 Color them = opposite_color(us);
1401 Square from = move_from(m);
1402 Square to = move_to(m);
1403 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1405 assert(to == ep_square());
1406 assert(relative_rank(us, to) == RANK_6);
1407 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1408 assert(piece_on(from) == EMPTY);
1409 assert(piece_on(capsq) == EMPTY);
1411 // Replace captured piece
1412 set_bit(&(byColorBB[them]), capsq);
1413 set_bit(&(byTypeBB[PAWN]), capsq);
1414 set_bit(&(byTypeBB[0]), capsq);
1415 board[capsq] = piece_of_color_and_type(them, PAWN);
1417 // Remove moving piece from destination square
1418 clear_bit(&(byColorBB[us]), to);
1419 clear_bit(&(byTypeBB[PAWN]), to);
1420 clear_bit(&(byTypeBB[0]), to);
1423 // Replace moving piece at source square
1424 set_bit(&(byColorBB[us]), from);
1425 set_bit(&(byTypeBB[PAWN]), from);
1426 set_bit(&(byTypeBB[0]), from);
1427 board[from] = piece_of_color_and_type(us, PAWN);
1429 // Update piece list:
1430 pieceList[us][PAWN][index[to]] = from;
1431 index[from] = index[to];
1432 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1433 index[capsq] = pieceCount[them][PAWN];
1435 // Update piece count:
1436 pieceCount[them][PAWN]++;
1440 /// Position::do_null_move makes() a "null move": It switches the side to move
1441 /// and updates the hash key without executing any move on the board.
1443 void Position::do_null_move(UndoInfo& u) {
1446 assert(!is_check());
1448 // Back up the information necessary to undo the null move to the supplied
1449 // UndoInfo object. In the case of a null move, the only thing we need to
1450 // remember is the last move made and the en passant square.
1451 u.lastMove = st.lastMove;
1452 u.epSquare = st.epSquare;
1453 u.previous = st.previous;
1456 // Save the current key to the history[] array, in order to be able to
1457 // detect repetition draws.
1458 history[gamePly] = st.key;
1460 // Update the necessary information
1461 sideToMove = opposite_color(sideToMove);
1462 if (st.epSquare != SQ_NONE)
1463 st.key ^= zobEp[st.epSquare];
1465 st.epSquare = SQ_NONE;
1468 st.key ^= zobSideToMove;
1470 st.mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1471 st.egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1477 /// Position::undo_null_move() unmakes a "null move".
1479 void Position::undo_null_move() {
1482 assert(!is_check());
1484 // Restore information from the our UndoInfo object
1485 st.lastMove = st.previous->lastMove;
1486 st.epSquare = st.previous->epSquare;
1487 st.previous = st.previous->previous;
1489 if (st.epSquare != SQ_NONE)
1490 st.key ^= zobEp[st.epSquare];
1492 // Update the necessary information
1493 sideToMove = opposite_color(sideToMove);
1496 st.key ^= zobSideToMove;
1498 st.mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1499 st.egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1505 /// Position::see() is a static exchange evaluator: It tries to estimate the
1506 /// material gain or loss resulting from a move. There are three versions of
1507 /// this function: One which takes a destination square as input, one takes a
1508 /// move, and one which takes a 'from' and a 'to' square. The function does
1509 /// not yet understand promotions captures.
1511 int Position::see(Square to) const {
1513 assert(square_is_ok(to));
1514 return see(SQ_NONE, to);
1517 int Position::see(Move m) const {
1519 assert(move_is_ok(m));
1520 return see(move_from(m), move_to(m));
1523 int Position::see(Square from, Square to) const {
1526 static const int seeValues[18] = {
1527 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1528 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1529 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1530 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1534 Bitboard attackers, occ, b;
1536 assert(square_is_ok(from) || from == SQ_NONE);
1537 assert(square_is_ok(to));
1539 // Initialize colors
1540 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1541 Color them = opposite_color(us);
1543 // Initialize pieces
1544 Piece piece = piece_on(from);
1545 Piece capture = piece_on(to);
1547 // Find all attackers to the destination square, with the moving piece
1548 // removed, but possibly an X-ray attacker added behind it.
1549 occ = occupied_squares();
1551 // Handle en passant moves
1552 if (st.epSquare == to && type_of_piece_on(from) == PAWN)
1554 assert(capture == EMPTY);
1556 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1557 capture = piece_on(capQq);
1559 assert(type_of_piece_on(capQq) == PAWN);
1561 // Remove the captured pawn
1562 clear_bit(&occ, capQq);
1567 clear_bit(&occ, from);
1568 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1569 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1570 | (piece_attacks<KNIGHT>(to) & knights())
1571 | (piece_attacks<KING>(to) & kings())
1572 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1573 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1575 if (from != SQ_NONE)
1578 // If we don't have any attacker we are finished
1579 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1582 // Locate the least valuable attacker to the destination square
1583 // and use it to initialize from square.
1585 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1588 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1589 piece = piece_on(from);
1592 // If the opponent has no attackers we are finished
1593 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1594 return seeValues[capture];
1596 attackers &= occ; // Remove the moving piece
1598 // The destination square is defended, which makes things rather more
1599 // difficult to compute. We proceed by building up a "swap list" containing
1600 // the material gain or loss at each stop in a sequence of captures to the
1601 // destination square, where the sides alternately capture, and always
1602 // capture with the least valuable piece. After each capture, we look for
1603 // new X-ray attacks from behind the capturing piece.
1604 int lastCapturingPieceValue = seeValues[piece];
1605 int swapList[32], n = 1;
1609 swapList[0] = seeValues[capture];
1612 // Locate the least valuable attacker for the side to move. The loop
1613 // below looks like it is potentially infinite, but it isn't. We know
1614 // that the side to move still has at least one attacker left.
1615 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1618 // Remove the attacker we just found from the 'attackers' bitboard,
1619 // and scan for new X-ray attacks behind the attacker.
1620 b = attackers & pieces_of_color_and_type(c, pt);
1622 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1623 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1627 // Add the new entry to the swap list
1629 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1632 // Remember the value of the capturing piece, and change the side to move
1633 // before beginning the next iteration
1634 lastCapturingPieceValue = seeValues[pt];
1635 c = opposite_color(c);
1637 // Stop after a king capture
1638 if (pt == KING && (attackers & pieces_of_color(c)))
1641 swapList[n++] = 100;
1644 } while (attackers & pieces_of_color(c));
1646 // Having built the swap list, we negamax through it to find the best
1647 // achievable score from the point of view of the side to move
1649 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1655 /// Position::clear() erases the position object to a pristine state, with an
1656 /// empty board, white to move, and no castling rights.
1658 void Position::clear() {
1660 for (int i = 0; i < 64; i++)
1666 for (int i = 0; i < 2; i++)
1667 byColorBB[i] = EmptyBoardBB;
1669 for (int i = 0; i < 7; i++)
1671 byTypeBB[i] = EmptyBoardBB;
1672 pieceCount[0][i] = pieceCount[1][i] = 0;
1673 for (int j = 0; j < 8; j++)
1674 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1677 st.checkersBB = EmptyBoardBB;
1678 for (Color c = WHITE; c <= BLACK; c++)
1679 st.pinners[c] = st.pinned[c] = st.dcCandidates[c] = ~EmptyBoardBB;
1681 st.lastMove = MOVE_NONE;
1684 st.castleRights = NO_CASTLES;
1685 initialKFile = FILE_E;
1686 initialKRFile = FILE_H;
1687 initialQRFile = FILE_A;
1688 st.epSquare = SQ_NONE;
1695 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1696 /// UCI interface code, whenever a non-reversible move is made in a
1697 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1698 /// for the program to handle games of arbitrary length, as long as the GUI
1699 /// handles draws by the 50 move rule correctly.
1701 void Position::reset_game_ply() {
1707 /// Position::put_piece() puts a piece on the given square of the board,
1708 /// updating the board array, bitboards, and piece counts.
1710 void Position::put_piece(Piece p, Square s) {
1712 Color c = color_of_piece(p);
1713 PieceType pt = type_of_piece(p);
1716 index[s] = pieceCount[c][pt];
1717 pieceList[c][pt][index[s]] = s;
1719 set_bit(&(byTypeBB[pt]), s);
1720 set_bit(&(byColorBB[c]), s);
1721 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1723 pieceCount[c][pt]++;
1730 /// Position::allow_oo() gives the given side the right to castle kingside.
1731 /// Used when setting castling rights during parsing of FEN strings.
1733 void Position::allow_oo(Color c) {
1735 st.castleRights |= (1 + int(c));
1739 /// Position::allow_ooo() gives the given side the right to castle queenside.
1740 /// Used when setting castling rights during parsing of FEN strings.
1742 void Position::allow_ooo(Color c) {
1744 st.castleRights |= (4 + 4*int(c));
1748 /// Position::compute_key() computes the hash key of the position. The hash
1749 /// key is usually updated incrementally as moves are made and unmade, the
1750 /// compute_key() function is only used when a new position is set up, and
1751 /// to verify the correctness of the hash key when running in debug mode.
1753 Key Position::compute_key() const {
1755 Key result = Key(0ULL);
1757 for (Square s = SQ_A1; s <= SQ_H8; s++)
1758 if (square_is_occupied(s))
1759 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1761 if (ep_square() != SQ_NONE)
1762 result ^= zobEp[ep_square()];
1764 result ^= zobCastle[st.castleRights];
1765 if (side_to_move() == BLACK)
1766 result ^= zobSideToMove;
1772 /// Position::compute_pawn_key() computes the hash key of the position. The
1773 /// hash key is usually updated incrementally as moves are made and unmade,
1774 /// the compute_pawn_key() function is only used when a new position is set
1775 /// up, and to verify the correctness of the pawn hash key when running in
1778 Key Position::compute_pawn_key() const {
1780 Key result = Key(0ULL);
1784 for (Color c = WHITE; c <= BLACK; c++)
1789 s = pop_1st_bit(&b);
1790 result ^= zobrist[c][PAWN][s];
1797 /// Position::compute_material_key() computes the hash key of the position.
1798 /// The hash key is usually updated incrementally as moves are made and unmade,
1799 /// the compute_material_key() function is only used when a new position is set
1800 /// up, and to verify the correctness of the material hash key when running in
1803 Key Position::compute_material_key() const {
1805 Key result = Key(0ULL);
1806 for (Color c = WHITE; c <= BLACK; c++)
1807 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1809 int count = piece_count(c, pt);
1810 for (int i = 0; i <= count; i++)
1811 result ^= zobMaterial[c][pt][i];
1817 /// Position::compute_value() compute the incremental scores for the middle
1818 /// game and the endgame. These functions are used to initialize the incremental
1819 /// scores when a new position is set up, and to verify that the scores are correctly
1820 /// updated by do_move and undo_move when the program is running in debug mode.
1821 template<Position::GamePhase Phase>
1822 Value Position::compute_value() const {
1824 Value result = Value(0);
1828 for (Color c = WHITE; c <= BLACK; c++)
1829 for (PieceType pt = PAWN; pt <= KING; pt++)
1831 b = pieces_of_color_and_type(c, pt);
1834 s = pop_1st_bit(&b);
1835 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1836 result += pst<Phase>(c, pt, s);
1840 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1841 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1846 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1847 /// game material score for the given side. Material scores are updated
1848 /// incrementally during the search, this function is only used while
1849 /// initializing a new Position object.
1851 Value Position::compute_non_pawn_material(Color c) const {
1853 Value result = Value(0);
1856 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1858 Bitboard b = pieces_of_color_and_type(c, pt);
1861 s = pop_1st_bit(&b);
1862 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1863 result += piece_value_midgame(pt);
1870 /// Position::is_mate() returns true or false depending on whether the
1871 /// side to move is checkmated. Note that this function is currently very
1872 /// slow, and shouldn't be used frequently inside the search.
1874 bool Position::is_mate() const {
1878 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1879 return mp.get_next_move() == MOVE_NONE;
1885 /// Position::is_draw() tests whether the position is drawn by material,
1886 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1887 /// must be done by the search.
1889 bool Position::is_draw() const {
1891 // Draw by material?
1893 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1896 // Draw by the 50 moves rule?
1897 if (st.rule50 > 100 || (st.rule50 == 100 && !is_check()))
1900 // Draw by repetition?
1901 for (int i = 2; i < Min(gamePly, st.rule50); i += 2)
1902 if (history[gamePly - i] == st.key)
1909 /// Position::has_mate_threat() tests whether a given color has a mate in one
1910 /// from the current position. This function is quite slow, but it doesn't
1911 /// matter, because it is currently only called from PV nodes, which are rare.
1913 bool Position::has_mate_threat(Color c) {
1916 Color stm = side_to_move();
1918 // The following lines are useless and silly, but prevents gcc from
1919 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1920 // be used uninitialized.
1921 u1.lastMove = st.lastMove;
1922 u1.epSquare = st.epSquare;
1927 // If the input color is not equal to the side to move, do a null move
1931 MoveStack mlist[120];
1933 bool result = false;
1935 // Generate legal moves
1936 count = generate_legal_moves(*this, mlist);
1938 // Loop through the moves, and see if one of them is mate
1939 for (int i = 0; i < count; i++)
1941 do_move(mlist[i].move, u2);
1945 undo_move(mlist[i].move);
1948 // Undo null move, if necessary
1956 /// Position::init_zobrist() is a static member function which initializes the
1957 /// various arrays used to compute hash keys.
1959 void Position::init_zobrist() {
1961 for (int i = 0; i < 2; i++)
1962 for (int j = 0; j < 8; j++)
1963 for (int k = 0; k < 64; k++)
1964 zobrist[i][j][k] = Key(genrand_int64());
1966 for (int i = 0; i < 64; i++)
1967 zobEp[i] = Key(genrand_int64());
1969 for (int i = 0; i < 16; i++)
1970 zobCastle[i] = genrand_int64();
1972 zobSideToMove = genrand_int64();
1974 for (int i = 0; i < 2; i++)
1975 for (int j = 0; j < 8; j++)
1976 for (int k = 0; k < 16; k++)
1977 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1979 for (int i = 0; i < 16; i++)
1980 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1984 /// Position::init_piece_square_tables() initializes the piece square tables.
1985 /// This is a two-step operation: First, the white halves of the tables are
1986 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1987 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1988 /// Second, the black halves of the tables are initialized by mirroring
1989 /// and changing the sign of the corresponding white scores.
1991 void Position::init_piece_square_tables() {
1993 int r = get_option_value_int("Randomness"), i;
1994 for (Square s = SQ_A1; s <= SQ_H8; s++)
1995 for (Piece p = WP; p <= WK; p++)
1997 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1998 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1999 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2002 for (Square s = SQ_A1; s <= SQ_H8; s++)
2003 for (Piece p = BP; p <= BK; p++)
2005 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2006 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2011 /// Position::flipped_copy() makes a copy of the input position, but with
2012 /// the white and black sides reversed. This is only useful for debugging,
2013 /// especially for finding evaluation symmetry bugs.
2015 void Position::flipped_copy(const Position &pos) {
2017 assert(pos.is_ok());
2022 for (Square s = SQ_A1; s <= SQ_H8; s++)
2023 if (!pos.square_is_empty(s))
2024 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2027 sideToMove = opposite_color(pos.side_to_move());
2030 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2031 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2032 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2033 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2035 initialKFile = pos.initialKFile;
2036 initialKRFile = pos.initialKRFile;
2037 initialQRFile = pos.initialQRFile;
2039 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2040 castleRightsMask[sq] = ALL_CASTLES;
2042 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2043 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2044 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2045 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2046 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2047 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2049 // En passant square
2050 if (pos.st.epSquare != SQ_NONE)
2051 st.epSquare = flip_square(pos.st.epSquare);
2057 st.key = compute_key();
2058 st.pawnKey = compute_pawn_key();
2059 st.materialKey = compute_material_key();
2061 // Incremental scores
2062 st.mgValue = compute_value<MidGame>();
2063 st.egValue = compute_value<EndGame>();
2066 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2067 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2073 /// Position::is_ok() performs some consitency checks for the position object.
2074 /// This is meant to be helpful when debugging.
2076 bool Position::is_ok(int* failedStep) const {
2078 // What features of the position should be verified?
2079 static const bool debugBitboards = false;
2080 static const bool debugKingCount = false;
2081 static const bool debugKingCapture = false;
2082 static const bool debugCheckerCount = false;
2083 static const bool debugKey = false;
2084 static const bool debugMaterialKey = false;
2085 static const bool debugPawnKey = false;
2086 static const bool debugIncrementalEval = false;
2087 static const bool debugNonPawnMaterial = false;
2088 static const bool debugPieceCounts = false;
2089 static const bool debugPieceList = false;
2091 if (failedStep) *failedStep = 1;
2094 if (!color_is_ok(side_to_move()))
2097 // Are the king squares in the position correct?
2098 if (failedStep) (*failedStep)++;
2099 if (piece_on(king_square(WHITE)) != WK)
2102 if (failedStep) (*failedStep)++;
2103 if (piece_on(king_square(BLACK)) != BK)
2107 if (failedStep) (*failedStep)++;
2108 if (!file_is_ok(initialKRFile))
2111 if (!file_is_ok(initialQRFile))
2114 // Do both sides have exactly one king?
2115 if (failedStep) (*failedStep)++;
2118 int kingCount[2] = {0, 0};
2119 for (Square s = SQ_A1; s <= SQ_H8; s++)
2120 if (type_of_piece_on(s) == KING)
2121 kingCount[color_of_piece_on(s)]++;
2123 if (kingCount[0] != 1 || kingCount[1] != 1)
2127 // Can the side to move capture the opponent's king?
2128 if (failedStep) (*failedStep)++;
2129 if (debugKingCapture)
2131 Color us = side_to_move();
2132 Color them = opposite_color(us);
2133 Square ksq = king_square(them);
2134 if (square_is_attacked(ksq, us))
2138 // Is there more than 2 checkers?
2139 if (failedStep) (*failedStep)++;
2140 if (debugCheckerCount && count_1s(st.checkersBB) > 2)
2144 if (failedStep) (*failedStep)++;
2147 // The intersection of the white and black pieces must be empty
2148 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2151 // The union of the white and black pieces must be equal to all
2153 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2156 // Separate piece type bitboards must have empty intersections
2157 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2158 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2159 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2163 // En passant square OK?
2164 if (failedStep) (*failedStep)++;
2165 if (ep_square() != SQ_NONE)
2167 // The en passant square must be on rank 6, from the point of view of the
2169 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2174 if (failedStep) (*failedStep)++;
2175 if (debugKey && st.key != compute_key())
2178 // Pawn hash key OK?
2179 if (failedStep) (*failedStep)++;
2180 if (debugPawnKey && st.pawnKey != compute_pawn_key())
2183 // Material hash key OK?
2184 if (failedStep) (*failedStep)++;
2185 if (debugMaterialKey && st.materialKey != compute_material_key())
2188 // Incremental eval OK?
2189 if (failedStep) (*failedStep)++;
2190 if (debugIncrementalEval)
2192 if (st.mgValue != compute_value<MidGame>())
2195 if (st.egValue != compute_value<EndGame>())
2199 // Non-pawn material OK?
2200 if (failedStep) (*failedStep)++;
2201 if (debugNonPawnMaterial)
2203 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2206 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2211 if (failedStep) (*failedStep)++;
2212 if (debugPieceCounts)
2213 for (Color c = WHITE; c <= BLACK; c++)
2214 for (PieceType pt = PAWN; pt <= KING; pt++)
2215 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2218 if (failedStep) (*failedStep)++;
2221 for(Color c = WHITE; c <= BLACK; c++)
2222 for(PieceType pt = PAWN; pt <= KING; pt++)
2223 for(int i = 0; i < pieceCount[c][pt]; i++)
2225 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2228 if (index[piece_list(c, pt, i)] != i)
2232 if (failedStep) *failedStep = 0;