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 int Position::castleRightsMask[64];
44 Key Position::zobrist[2][8][64];
45 Key Position::zobEp[64];
46 Key Position::zobCastle[16];
47 Key Position::zobMaterial[2][8][16];
48 Key Position::zobSideToMove;
50 Value Position::MgPieceSquareTable[16][64];
51 Value Position::EgPieceSquareTable[16][64];
60 Position::Position(const Position &pos) {
64 Position::Position(const std::string &fen) {
69 /// Position::from_fen() initializes the position object with the given FEN
70 /// string. This function is not very robust - make sure that input FENs are
71 /// correct (this is assumed to be the responsibility of the GUI).
73 void Position::from_fen(const std::string &fen) {
75 static const std::string pieceLetters = "KQRBNPkqrbnp";
76 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
84 for ( ; fen[i] != ' '; i++)
88 // Skip the given number of files
89 file += (fen[i] - '1' + 1);
92 else if (fen[i] == '/')
98 size_t idx = pieceLetters.find(fen[i]);
99 if (idx == std::string::npos)
101 std::cout << "Error in FEN at character " << i << std::endl;
104 Square square = make_square(file, rank);
105 put_piece(pieces[idx], square);
111 if (fen[i] != 'w' && fen[i] != 'b')
113 std::cout << "Error in FEN at character " << i << std::endl;
116 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
122 std::cout << "Error in FEN at character " << i << std::endl;
127 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
131 else if(fen[i] == 'K') allow_oo(WHITE);
132 else if(fen[i] == 'Q') allow_ooo(WHITE);
133 else if(fen[i] == 'k') allow_oo(BLACK);
134 else if(fen[i] == 'q') allow_ooo(BLACK);
135 else if(fen[i] >= 'A' && fen[i] <= 'H') {
136 File rookFile, kingFile = FILE_NONE;
137 for(Square square = SQ_B1; square <= SQ_G1; square++)
138 if(piece_on(square) == WK)
139 kingFile = square_file(square);
140 if(kingFile == FILE_NONE) {
141 std::cout << "Error in FEN at character " << i << std::endl;
144 initialKFile = kingFile;
145 rookFile = File(fen[i] - 'A') + FILE_A;
146 if(rookFile < initialKFile) {
148 initialQRFile = rookFile;
152 initialKRFile = rookFile;
155 else if(fen[i] >= 'a' && fen[i] <= 'h') {
156 File rookFile, kingFile = FILE_NONE;
157 for(Square square = SQ_B8; square <= SQ_G8; square++)
158 if(piece_on(square) == BK)
159 kingFile = square_file(square);
160 if(kingFile == FILE_NONE) {
161 std::cout << "Error in FEN at character " << i << std::endl;
164 initialKFile = kingFile;
165 rookFile = File(fen[i] - 'a') + FILE_A;
166 if(rookFile < initialKFile) {
168 initialQRFile = rookFile;
172 initialKRFile = rookFile;
176 std::cout << "Error in FEN at character " << i << std::endl;
183 while (fen[i] == ' ')
187 if ( i < fen.length() - 2
188 && (fen[i] >= 'a' && fen[i] <= 'h')
189 && (fen[i+1] == '3' || fen[i+1] == '6'))
190 epSquare = square_from_string(fen.substr(i, 2));
192 // Various initialisation
193 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
194 castleRightsMask[sq] = ALL_CASTLES;
196 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
197 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
198 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
199 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
200 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
201 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
206 pawnKey = compute_pawn_key();
207 materialKey = compute_material_key();
208 mgValue = compute_mg_value();
209 egValue = compute_eg_value();
210 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
211 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
215 /// Position::to_fen() converts the position object to a FEN string. This is
216 /// probably only useful for debugging.
218 const std::string Position::to_fen() const {
220 static const std::string pieceLetters = " PNBRQK pnbrqk";
224 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
227 for (File file = FILE_A; file <= FILE_H; file++)
229 Square sq = make_square(file, rank);
230 if (!square_is_occupied(sq))
236 fen += (char)skip + '0';
239 fen += pieceLetters[piece_on(sq)];
242 fen += (char)skip + '0';
244 fen += (rank > RANK_1 ? '/' : ' ');
246 fen += (sideToMove == WHITE ? "w " : "b ");
247 if (castleRights != NO_CASTLES)
249 if (can_castle_kingside(WHITE)) fen += 'K';
250 if (can_castle_queenside(WHITE)) fen += 'Q';
251 if (can_castle_kingside(BLACK)) fen += 'k';
252 if (can_castle_queenside(BLACK)) fen += 'q';
257 if (ep_square() != SQ_NONE)
258 fen += square_to_string(ep_square());
266 /// Position::print() prints an ASCII representation of the position to
267 /// the standard output. If a move is given then also the san is print.
269 void Position::print(Move m) const {
271 static const std::string pieceLetters = " PNBRQK PNBRQK .";
273 std::cout << std::endl;
277 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
278 std::cout << "Move is: " << col << move_to_san(p, m) << std::endl;
280 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
282 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
283 for (File file = FILE_A; file <= FILE_H; file++)
285 Square sq = make_square(file, rank);
286 Piece piece = piece_on(sq);
287 if (piece == EMPTY && square_color(sq) == WHITE)
290 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
291 std::cout << '|' << col << pieceLetters[piece] << col;
293 std::cout << '|' << std::endl;
295 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
296 << "Fen is: " << to_fen() << std::endl
297 << "Key is: " << key << std::endl;
301 /// Position::copy() creates a copy of the input position.
303 void Position::copy(const Position &pos) {
305 memcpy(this, &pos, sizeof(Position));
309 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
310 /// king) pieces for the given color.
311 Bitboard Position::pinned_pieces(Color c) const {
313 Square ksq = king_square(c);
314 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
318 /// Position:discovered_check_candidates() returns a bitboard containing all
319 /// pieces for the given side which are candidates for giving a discovered
320 /// check. The code is almost the same as the function for finding pinned
323 Bitboard Position::discovered_check_candidates(Color c) const {
325 Square ksq = king_square(opposite_color(c));
326 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
330 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
331 /// king) pieces for the given color and for the given pinner type. Or, when
332 /// template parameter FindPinned is false, the pinned pieces of opposite color
333 /// that are, indeed, the pieces candidate for a discovery check.
334 template<PieceType Piece, bool FindPinned>
335 Bitboard Position::hidden_checks(Color c, Square ksq) const {
338 Bitboard sliders, result = EmptyBoardBB;
340 if (Piece == ROOK) // Resolved at compile time
341 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
343 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
345 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
347 // King blockers are candidate pinned pieces
348 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
350 // Pinners are sliders, not checkers, that give check when
351 // candidate pinned are removed.
352 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
355 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
357 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
359 // Finally for each pinner find the corresponding pinned piece (if same color of king)
360 // or discovery checker (if opposite color) among the candidates.
363 s = pop_1st_bit(&pinners);
364 result |= (squares_between(s, ksq) & candidate_pinned);
371 /// Position::square_is_attacked() checks whether the given side attacks the
374 bool Position::square_is_attacked(Square s, Color c) const {
376 return (pawn_attacks(opposite_color(c), s) & pawns(c))
377 || (piece_attacks<KNIGHT>(s) & knights(c))
378 || (piece_attacks<KING>(s) & kings(c))
379 || (piece_attacks<ROOK>(s) & rooks_and_queens(c))
380 || (piece_attacks<BISHOP>(s) & bishops_and_queens(c));
384 /// Position::attacks_to() computes a bitboard containing all pieces which
385 /// attacks a given square. There are two versions of this function: One
386 /// which finds attackers of both colors, and one which only finds the
387 /// attackers for one side.
389 Bitboard Position::attacks_to(Square s) const {
391 return (pawn_attacks(BLACK, s) & pawns(WHITE))
392 | (pawn_attacks(WHITE, s) & pawns(BLACK))
393 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
394 | (piece_attacks<ROOK>(s) & rooks_and_queens())
395 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
396 | (piece_attacks<KING>(s) & pieces_of_type(KING));
399 Bitboard Position::attacks_to(Square s, Color c) const {
401 return attacks_to(s) & pieces_of_color(c);
405 /// Position::piece_attacks_square() tests whether the piece on square f
406 /// attacks square t.
408 bool Position::piece_attacks_square(Square f, Square t) const {
410 assert(square_is_ok(f));
411 assert(square_is_ok(t));
415 case WP: return pawn_attacks_square(WHITE, f, t);
416 case BP: return pawn_attacks_square(BLACK, f, t);
417 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
418 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
419 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
420 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
421 case WK: case BK: return piece_attacks_square<KING>(f, t);
428 /// Position::move_attacks_square() tests whether a move from the current
429 /// position attacks a given square. Only attacks by the moving piece are
430 /// considered; the function does not handle X-ray attacks.
432 bool Position::move_attacks_square(Move m, Square s) const {
434 assert(move_is_ok(m));
435 assert(square_is_ok(s));
437 Square f = move_from(m), t = move_to(m);
439 assert(square_is_occupied(f));
443 case WP: return pawn_attacks_square(WHITE, t, s);
444 case BP: return pawn_attacks_square(BLACK, t, s);
445 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
446 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
447 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
448 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
449 case WK: case BK: return piece_attacks_square<KING>(t, s);
456 /// Position::find_checkers() computes the checkersBB bitboard, which
457 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
458 /// currently works by calling Position::attacks_to, which is probably
459 /// inefficient. Consider rewriting this function to use the last move
460 /// played, like in non-bitboard versions of Glaurung.
462 void Position::find_checkers() {
464 Color us = side_to_move();
465 checkersBB = attacks_to(king_square(us), opposite_color(us));
469 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
470 /// There are two versions of this function: One which takes only a
471 /// move as input, and one which takes a move and a bitboard of pinned
472 /// pieces. The latter function is faster, and should always be preferred
473 /// when a pinned piece bitboard has already been computed.
475 bool Position::pl_move_is_legal(Move m) const {
477 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
480 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
483 assert(move_is_ok(m));
484 assert(pinned == pinned_pieces(side_to_move()));
486 // If we're in check, all pseudo-legal moves are legal, because our
487 // check evasion generator only generates true legal moves.
491 // Castling moves are checked for legality during move generation.
492 if (move_is_castle(m))
495 Color us = side_to_move();
496 Color them = opposite_color(us);
497 Square from = move_from(m);
498 Square ksq = king_square(us);
500 assert(color_of_piece_on(from) == us);
501 assert(piece_on(ksq) == king_of_color(us));
503 // En passant captures are a tricky special case. Because they are
504 // rather uncommon, we do it simply by testing whether the king is attacked
505 // after the move is made
508 Square to = move_to(m);
509 Square capsq = make_square(square_file(to), square_rank(from));
510 Bitboard b = occupied_squares();
512 assert(to == ep_square());
513 assert(piece_on(from) == pawn_of_color(us));
514 assert(piece_on(capsq) == pawn_of_color(them));
515 assert(piece_on(to) == EMPTY);
518 clear_bit(&b, capsq);
521 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
522 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
525 // If the moving piece is a king, check whether the destination
526 // square is attacked by the opponent.
528 return !(square_is_attacked(move_to(m), them));
530 // A non-king move is legal if and only if it is not pinned or it
531 // is moving along the ray towards or away from the king.
532 return ( !bit_is_set(pinned, from)
533 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
537 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
538 /// There are two versions of this function: One which takes only a move as
539 /// input, and one which takes a move and a bitboard of discovered check
540 /// candidates. The latter function is faster, and should always be preferred
541 /// when a discovered check candidates bitboard has already been computed.
543 bool Position::move_is_check(Move m) const {
545 Bitboard dc = discovered_check_candidates(side_to_move());
546 return move_is_check(m, dc);
549 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
552 assert(move_is_ok(m));
553 assert(dcCandidates == discovered_check_candidates(side_to_move()));
555 Color us = side_to_move();
556 Color them = opposite_color(us);
557 Square from = move_from(m);
558 Square to = move_to(m);
559 Square ksq = king_square(them);
561 assert(color_of_piece_on(from) == us);
562 assert(piece_on(ksq) == king_of_color(them));
564 // Proceed according to the type of the moving piece
565 switch (type_of_piece_on(from))
569 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
572 if ( bit_is_set(dcCandidates, from) // Discovered check?
573 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
576 if (move_promotion(m)) // Promotion with check?
578 Bitboard b = occupied_squares();
581 switch (move_promotion(m))
584 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
586 return bit_is_set(bishop_attacks_bb(to, b), ksq);
588 return bit_is_set(rook_attacks_bb(to, b), ksq);
590 return bit_is_set(queen_attacks_bb(to, b), ksq);
595 // En passant capture with check? We have already handled the case
596 // of direct checks and ordinary discovered check, the only case we
597 // need to handle is the unusual case of a discovered check through the
599 else if (move_is_ep(m))
601 Square capsq = make_square(square_file(to), square_rank(from));
602 Bitboard b = occupied_squares();
604 clear_bit(&b, capsq);
606 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
607 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
612 return bit_is_set(dcCandidates, from) // Discovered check?
613 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
616 return bit_is_set(dcCandidates, from) // Discovered check?
617 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
620 return bit_is_set(dcCandidates, from) // Discovered check?
621 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
624 // Discovered checks are impossible!
625 assert(!bit_is_set(dcCandidates, from));
626 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
630 if ( bit_is_set(dcCandidates, from)
631 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
634 // Castling with check?
635 if (move_is_castle(m))
637 Square kfrom, kto, rfrom, rto;
638 Bitboard b = occupied_squares();
644 kto = relative_square(us, SQ_G1);
645 rto = relative_square(us, SQ_F1);
647 kto = relative_square(us, SQ_C1);
648 rto = relative_square(us, SQ_D1);
650 clear_bit(&b, kfrom);
651 clear_bit(&b, rfrom);
654 return bit_is_set(rook_attacks_bb(rto, b), ksq);
658 default: // NO_PIECE_TYPE
666 /// Position::move_is_capture() tests whether a move from the current
667 /// position is a capture.
669 bool Position::move_is_capture(Move m) const {
671 return ( !square_is_empty(move_to(m))
672 && (color_of_piece_on(move_to(m)) == opposite_color(side_to_move()))
678 /// Position::backup() is called when making a move. All information
679 /// necessary to restore the position when the move is later unmade
680 /// is saved to an UndoInfo object. The function Position::restore
681 /// does the reverse operation: When one does a backup followed by
682 /// a restore with the same UndoInfo object, the position is restored
683 /// to the state before backup was called.
685 void Position::backup(UndoInfo& u) const {
687 u.castleRights = castleRights;
688 u.epSquare = epSquare;
689 u.checkersBB = checkersBB;
692 u.materialKey = materialKey;
694 u.lastMove = lastMove;
697 u.capture = NO_PIECE_TYPE;
701 /// Position::restore() is called when unmaking a move. It copies back
702 /// the information backed up during a previous call to Position::backup.
704 void Position::restore(const UndoInfo& u) {
706 castleRights = u.castleRights;
707 epSquare = u.epSquare;
708 checkersBB = u.checkersBB;
711 materialKey = u.materialKey;
713 lastMove = u.lastMove;
716 // u.capture is restored in undo_move()
719 /// Position::do_move() makes a move, and backs up all information necessary
720 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
721 /// Pseudo-legal moves should be filtered out before this function is called.
722 /// There are two versions of this function, one which takes only the move and
723 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
724 /// discovered check candidates. The second version is faster, because knowing
725 /// the discovered check candidates makes it easier to update the checkersBB
726 /// member variable in the position object.
728 void Position::do_move(Move m, UndoInfo& u) {
730 do_move(m, u, discovered_check_candidates(side_to_move()));
733 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
736 assert(move_is_ok(m));
738 // Back up the necessary information to our UndoInfo object (except the
739 // captured piece, which is taken care of later.
742 // Save the current key to the history[] array, in order to be able to
743 // detect repetition draws.
744 history[gamePly] = key;
746 // Increment the 50 moves rule draw counter. Resetting it to zero in the
747 // case of non-reversible moves is taken care of later.
750 if (move_is_castle(m))
752 else if (move_promotion(m))
753 do_promotion_move(m, u);
754 else if (move_is_ep(m))
758 Color us = side_to_move();
759 Color them = opposite_color(us);
760 Square from = move_from(m);
761 Square to = move_to(m);
763 assert(color_of_piece_on(from) == us);
764 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
766 PieceType piece = type_of_piece_on(from);
767 PieceType capture = type_of_piece_on(to);
772 do_capture_move(m, capture, them, to);
776 clear_bit(&(byColorBB[us]), from);
777 clear_bit(&(byTypeBB[piece]), from);
778 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
779 set_bit(&(byColorBB[us]), to);
780 set_bit(&(byTypeBB[piece]), to);
781 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
782 board[to] = board[from];
786 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
788 // Update incremental scores
789 mgValue -= mg_pst(us, piece, from);
790 mgValue += mg_pst(us, piece, to);
791 egValue -= eg_pst(us, piece, from);
792 egValue += eg_pst(us, piece, to);
794 // If the moving piece was a king, update the king square
798 // If the move was a double pawn push, set the en passant square.
799 // This code is a bit ugly right now, and should be cleaned up later.
801 if (epSquare != SQ_NONE)
803 key ^= zobEp[epSquare];
808 if (abs(int(to) - int(from)) == 16)
811 && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
813 && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
815 epSquare = Square((int(from) + int(to)) / 2);
816 key ^= zobEp[epSquare];
819 // Reset rule 50 draw counter
822 // Update pawn hash key
823 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
825 // Update piece lists
826 pieceList[us][piece][index[from]] = to;
827 index[to] = index[from];
829 // Update castle rights
830 key ^= zobCastle[castleRights];
831 castleRights &= castleRightsMask[from];
832 castleRights &= castleRightsMask[to];
833 key ^= zobCastle[castleRights];
835 // Update checkers bitboard
836 checkersBB = EmptyBoardBB;
837 Square ksq = king_square(them);
841 if (bit_is_set(pawn_attacks(them, ksq), to))
842 set_bit(&checkersBB, to);
844 if (bit_is_set(dcCandidates, from))
845 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
846 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
850 if (bit_is_set(piece_attacks<KNIGHT>(ksq), to))
851 set_bit(&checkersBB, to);
853 if (bit_is_set(dcCandidates, from))
854 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
855 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
859 if (bit_is_set(piece_attacks<BISHOP>(ksq), to))
860 set_bit(&checkersBB, to);
862 if (bit_is_set(dcCandidates, from))
863 checkersBB |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(us));
867 if (bit_is_set(piece_attacks<ROOK>(ksq), to))
868 set_bit(&checkersBB, to);
870 if (bit_is_set(dcCandidates, from))
871 checkersBB |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us));
875 if (bit_is_set(piece_attacks<QUEEN>(ksq), to))
876 set_bit(&checkersBB, to);
880 if (bit_is_set(dcCandidates, from))
881 checkersBB |= ( (piece_attacks<ROOK>(ksq) & rooks_and_queens(us))
882 |(piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
892 key ^= zobSideToMove;
893 sideToMove = opposite_color(sideToMove);
896 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
897 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
903 /// Position::do_capture_move() is a private method used to update captured
904 /// piece info. It is called from the main Position::do_move function.
906 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
908 assert(capture != KING);
910 // Remove captured piece
911 clear_bit(&(byColorBB[them]), to);
912 clear_bit(&(byTypeBB[capture]), to);
915 key ^= zobrist[them][capture][to];
917 // If the captured piece was a pawn, update pawn hash key
919 pawnKey ^= zobrist[them][PAWN][to];
921 // Update incremental scores
922 mgValue -= mg_pst(them, capture, to);
923 egValue -= eg_pst(them, capture, to);
925 assert(!move_promotion(m) || capture != PAWN);
929 npMaterial[them] -= piece_value_midgame(capture);
931 // Update material hash key
932 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
934 // Update piece count
935 pieceCount[them][capture]--;
938 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
939 index[pieceList[them][capture][index[to]]] = index[to];
941 // Reset rule 50 counter
946 /// Position::do_castle_move() is a private method used to make a castling
947 /// move. It is called from the main Position::do_move function. Note that
948 /// castling moves are encoded as "king captures friendly rook" moves, for
949 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
951 void Position::do_castle_move(Move m) {
954 assert(move_is_ok(m));
955 assert(move_is_castle(m));
957 Color us = side_to_move();
958 Color them = opposite_color(us);
960 // Find source squares for king and rook
961 Square kfrom = move_from(m);
962 Square rfrom = move_to(m); // HACK: See comment at beginning of function
965 assert(piece_on(kfrom) == king_of_color(us));
966 assert(piece_on(rfrom) == rook_of_color(us));
968 // Find destination squares for king and rook
969 if (rfrom > kfrom) // O-O
971 kto = relative_square(us, SQ_G1);
972 rto = relative_square(us, SQ_F1);
974 kto = relative_square(us, SQ_C1);
975 rto = relative_square(us, SQ_D1);
978 // Remove pieces from source squares
979 clear_bit(&(byColorBB[us]), kfrom);
980 clear_bit(&(byTypeBB[KING]), kfrom);
981 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
982 clear_bit(&(byColorBB[us]), rfrom);
983 clear_bit(&(byTypeBB[ROOK]), rfrom);
984 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
986 // Put pieces on destination squares
987 set_bit(&(byColorBB[us]), kto);
988 set_bit(&(byTypeBB[KING]), kto);
989 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
990 set_bit(&(byColorBB[us]), rto);
991 set_bit(&(byTypeBB[ROOK]), rto);
992 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
994 // Update board array
995 board[kfrom] = board[rfrom] = EMPTY;
996 board[kto] = king_of_color(us);
997 board[rto] = rook_of_color(us);
999 // Update king square
1000 kingSquare[us] = kto;
1002 // Update piece lists
1003 pieceList[us][KING][index[kfrom]] = kto;
1004 pieceList[us][ROOK][index[rfrom]] = rto;
1005 int tmp = index[rfrom];
1006 index[kto] = index[kfrom];
1009 // Update incremental scores
1010 mgValue -= mg_pst(us, KING, kfrom);
1011 mgValue += mg_pst(us, KING, kto);
1012 egValue -= eg_pst(us, KING, kfrom);
1013 egValue += eg_pst(us, KING, kto);
1014 mgValue -= mg_pst(us, ROOK, rfrom);
1015 mgValue += mg_pst(us, ROOK, rto);
1016 egValue -= eg_pst(us, ROOK, rfrom);
1017 egValue += eg_pst(us, ROOK, rto);
1020 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1021 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1023 // Clear en passant square
1024 if(epSquare != SQ_NONE)
1026 key ^= zobEp[epSquare];
1030 // Update castling rights
1031 key ^= zobCastle[castleRights];
1032 castleRights &= castleRightsMask[kfrom];
1033 key ^= zobCastle[castleRights];
1035 // Reset rule 50 counter
1038 // Update checkers BB
1039 checkersBB = attacks_to(king_square(them), us);
1043 /// Position::do_promotion_move() is a private method used to make a promotion
1044 /// move. It is called from the main Position::do_move function. The
1045 /// UndoInfo object, which has been initialized in Position::do_move, is
1046 /// used to store the captured piece (if any).
1048 void Position::do_promotion_move(Move m, UndoInfo &u) {
1052 PieceType capture, promotion;
1055 assert(move_is_ok(m));
1056 assert(move_promotion(m));
1058 us = side_to_move();
1059 them = opposite_color(us);
1060 from = move_from(m);
1063 assert(relative_rank(us, to) == RANK_8);
1064 assert(piece_on(from) == pawn_of_color(us));
1065 assert(color_of_piece_on(to) == them || square_is_empty(to));
1067 capture = type_of_piece_on(to);
1071 u.capture = capture;
1072 do_capture_move(m, capture, them, to);
1076 clear_bit(&(byColorBB[us]), from);
1077 clear_bit(&(byTypeBB[PAWN]), from);
1078 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1079 board[from] = EMPTY;
1081 // Insert promoted piece
1082 promotion = move_promotion(m);
1083 assert(promotion >= KNIGHT && promotion <= QUEEN);
1084 set_bit(&(byColorBB[us]), to);
1085 set_bit(&(byTypeBB[promotion]), to);
1086 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1087 board[to] = piece_of_color_and_type(us, promotion);
1090 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1092 // Update pawn hash key
1093 pawnKey ^= zobrist[us][PAWN][from];
1095 // Update material key
1096 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1097 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1099 // Update piece counts
1100 pieceCount[us][PAWN]--;
1101 pieceCount[us][promotion]++;
1103 // Update piece lists
1104 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1105 index[pieceList[us][PAWN][index[from]]] = index[from];
1106 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1107 index[to] = pieceCount[us][promotion] - 1;
1109 // Update incremental scores
1110 mgValue -= mg_pst(us, PAWN, from);
1111 mgValue += mg_pst(us, promotion, to);
1112 egValue -= eg_pst(us, PAWN, from);
1113 egValue += eg_pst(us, promotion, to);
1116 npMaterial[us] += piece_value_midgame(promotion);
1118 // Clear the en passant square
1119 if (epSquare != SQ_NONE)
1121 key ^= zobEp[epSquare];
1125 // Update castle rights
1126 key ^= zobCastle[castleRights];
1127 castleRights &= castleRightsMask[to];
1128 key ^= zobCastle[castleRights];
1130 // Reset rule 50 counter
1133 // Update checkers BB
1134 checkersBB = attacks_to(king_square(them), us);
1138 /// Position::do_ep_move() is a private method used to make an en passant
1139 /// capture. It is called from the main Position::do_move function. Because
1140 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1141 /// object in which to store the captured piece.
1143 void Position::do_ep_move(Move m) {
1146 Square from, to, capsq;
1149 assert(move_is_ok(m));
1150 assert(move_is_ep(m));
1152 us = side_to_move();
1153 them = opposite_color(us);
1154 from = move_from(m);
1156 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1158 assert(to == epSquare);
1159 assert(relative_rank(us, to) == RANK_6);
1160 assert(piece_on(to) == EMPTY);
1161 assert(piece_on(from) == pawn_of_color(us));
1162 assert(piece_on(capsq) == pawn_of_color(them));
1164 // Remove captured piece
1165 clear_bit(&(byColorBB[them]), capsq);
1166 clear_bit(&(byTypeBB[PAWN]), capsq);
1167 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1168 board[capsq] = EMPTY;
1170 // Remove moving piece from source square
1171 clear_bit(&(byColorBB[us]), from);
1172 clear_bit(&(byTypeBB[PAWN]), from);
1173 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1175 // Put moving piece on destination square
1176 set_bit(&(byColorBB[us]), to);
1177 set_bit(&(byTypeBB[PAWN]), to);
1178 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1179 board[to] = board[from];
1180 board[from] = EMPTY;
1182 // Update material hash key
1183 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1185 // Update piece count
1186 pieceCount[them][PAWN]--;
1188 // Update piece list
1189 pieceList[us][PAWN][index[from]] = to;
1190 index[to] = index[from];
1191 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1192 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1195 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1196 key ^= zobrist[them][PAWN][capsq];
1197 key ^= zobEp[epSquare];
1199 // Update pawn hash key
1200 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1201 pawnKey ^= zobrist[them][PAWN][capsq];
1203 // Update incremental scores
1204 mgValue -= mg_pst(them, PAWN, capsq);
1205 mgValue -= mg_pst(us, PAWN, from);
1206 mgValue += mg_pst(us, PAWN, to);
1207 egValue -= eg_pst(them, PAWN, capsq);
1208 egValue -= eg_pst(us, PAWN, from);
1209 egValue += eg_pst(us, PAWN, to);
1211 // Reset en passant square
1214 // Reset rule 50 counter
1217 // Update checkers BB
1218 checkersBB = attacks_to(king_square(them), us);
1222 /// Position::undo_move() unmakes a move. When it returns, the position should
1223 /// be restored to exactly the same state as before the move was made. It is
1224 /// important that Position::undo_move is called with the same move and UndoInfo
1225 /// object as the earlier call to Position::do_move.
1227 void Position::undo_move(Move m, const UndoInfo &u) {
1230 assert(move_is_ok(m));
1233 sideToMove = opposite_color(sideToMove);
1235 // Restore information from our UndoInfo object (except the captured piece,
1236 // which is taken care of later)
1239 if (move_is_castle(m))
1240 undo_castle_move(m);
1241 else if (move_promotion(m))
1242 undo_promotion_move(m, u);
1243 else if (move_is_ep(m))
1249 PieceType piece, capture;
1251 us = side_to_move();
1252 them = opposite_color(us);
1253 from = move_from(m);
1256 assert(piece_on(from) == EMPTY);
1257 assert(color_of_piece_on(to) == us);
1259 // Put the piece back at the source square
1260 piece = type_of_piece_on(to);
1261 set_bit(&(byColorBB[us]), from);
1262 set_bit(&(byTypeBB[piece]), from);
1263 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1264 board[from] = piece_of_color_and_type(us, piece);
1266 // Clear the destination square
1267 clear_bit(&(byColorBB[us]), to);
1268 clear_bit(&(byTypeBB[piece]), to);
1269 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1271 // If the moving piece was a king, update the king square
1273 kingSquare[us] = from;
1275 // Update piece list
1276 pieceList[us][piece][index[to]] = from;
1277 index[from] = index[to];
1279 capture = u.capture;
1283 assert(capture != KING);
1285 // Replace the captured piece
1286 set_bit(&(byColorBB[them]), to);
1287 set_bit(&(byTypeBB[capture]), to);
1288 set_bit(&(byTypeBB[0]), to);
1289 board[to] = piece_of_color_and_type(them, capture);
1292 if (capture != PAWN)
1293 npMaterial[them] += piece_value_midgame(capture);
1295 // Update piece list
1296 pieceList[them][capture][pieceCount[them][capture]] = to;
1297 index[to] = pieceCount[them][capture];
1299 // Update piece count
1300 pieceCount[them][capture]++;
1309 /// Position::undo_castle_move() is a private method used to unmake a castling
1310 /// move. It is called from the main Position::undo_move function. Note that
1311 /// castling moves are encoded as "king captures friendly rook" moves, for
1312 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1314 void Position::undo_castle_move(Move m) {
1316 assert(move_is_ok(m));
1317 assert(move_is_castle(m));
1319 // When we have arrived here, some work has already been done by
1320 // Position::undo_move. In particular, the side to move has been switched,
1321 // so the code below is correct.
1322 Color us = side_to_move();
1324 // Find source squares for king and rook
1325 Square kfrom = move_from(m);
1326 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1329 // Find destination squares for king and rook
1330 if (rfrom > kfrom) // O-O
1332 kto = relative_square(us, SQ_G1);
1333 rto = relative_square(us, SQ_F1);
1335 kto = relative_square(us, SQ_C1);
1336 rto = relative_square(us, SQ_D1);
1339 assert(piece_on(kto) == king_of_color(us));
1340 assert(piece_on(rto) == rook_of_color(us));
1342 // Remove pieces from destination squares
1343 clear_bit(&(byColorBB[us]), kto);
1344 clear_bit(&(byTypeBB[KING]), kto);
1345 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1346 clear_bit(&(byColorBB[us]), rto);
1347 clear_bit(&(byTypeBB[ROOK]), rto);
1348 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1350 // Put pieces on source squares
1351 set_bit(&(byColorBB[us]), kfrom);
1352 set_bit(&(byTypeBB[KING]), kfrom);
1353 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1354 set_bit(&(byColorBB[us]), rfrom);
1355 set_bit(&(byTypeBB[ROOK]), rfrom);
1356 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1359 board[rto] = board[kto] = EMPTY;
1360 board[rfrom] = rook_of_color(us);
1361 board[kfrom] = king_of_color(us);
1363 // Update king square
1364 kingSquare[us] = kfrom;
1366 // Update piece lists
1367 pieceList[us][KING][index[kto]] = kfrom;
1368 pieceList[us][ROOK][index[rto]] = rfrom;
1369 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1370 index[kfrom] = index[kto];
1375 /// Position::undo_promotion_move() is a private method used to unmake a
1376 /// promotion move. It is called from the main Position::do_move
1377 /// function. The UndoInfo object, which has been initialized in
1378 /// Position::do_move, is used to put back the captured piece (if any).
1380 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1384 PieceType capture, promotion;
1386 assert(move_is_ok(m));
1387 assert(move_promotion(m));
1389 // When we have arrived here, some work has already been done by
1390 // Position::undo_move. In particular, the side to move has been switched,
1391 // so the code below is correct.
1392 us = side_to_move();
1393 them = opposite_color(us);
1394 from = move_from(m);
1397 assert(relative_rank(us, to) == RANK_8);
1398 assert(piece_on(from) == EMPTY);
1400 // Remove promoted piece
1401 promotion = move_promotion(m);
1402 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1403 assert(promotion >= KNIGHT && promotion <= QUEEN);
1404 clear_bit(&(byColorBB[us]), to);
1405 clear_bit(&(byTypeBB[promotion]), to);
1406 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1408 // Insert pawn at source square
1409 set_bit(&(byColorBB[us]), from);
1410 set_bit(&(byTypeBB[PAWN]), from);
1411 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1412 board[from] = pawn_of_color(us);
1415 npMaterial[us] -= piece_value_midgame(promotion);
1417 // Update piece list
1418 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1419 index[from] = pieceCount[us][PAWN];
1420 pieceList[us][promotion][index[to]] =
1421 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1422 index[pieceList[us][promotion][index[to]]] = index[to];
1424 // Update piece counts
1425 pieceCount[us][promotion]--;
1426 pieceCount[us][PAWN]++;
1428 capture = u.capture;
1432 assert(capture != KING);
1434 // Insert captured piece:
1435 set_bit(&(byColorBB[them]), to);
1436 set_bit(&(byTypeBB[capture]), to);
1437 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1438 board[to] = piece_of_color_and_type(them, capture);
1440 // Update material. Because the move is a promotion move, we know
1441 // that the captured piece cannot be a pawn.
1442 assert(capture != PAWN);
1443 npMaterial[them] += piece_value_midgame(capture);
1445 // Update piece list
1446 pieceList[them][capture][pieceCount[them][capture]] = to;
1447 index[to] = pieceCount[them][capture];
1449 // Update piece count
1450 pieceCount[them][capture]++;
1456 /// Position::undo_ep_move() is a private method used to unmake an en passant
1457 /// capture. It is called from the main Position::undo_move function. Because
1458 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1459 /// object from which to retrieve the captured piece.
1461 void Position::undo_ep_move(Move m) {
1463 assert(move_is_ok(m));
1464 assert(move_is_ep(m));
1466 // When we have arrived here, some work has already been done by
1467 // Position::undo_move. In particular, the side to move has been switched,
1468 // so the code below is correct.
1469 Color us = side_to_move();
1470 Color them = opposite_color(us);
1471 Square from = move_from(m);
1472 Square to = move_to(m);
1473 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1475 assert(to == ep_square());
1476 assert(relative_rank(us, to) == RANK_6);
1477 assert(piece_on(to) == pawn_of_color(us));
1478 assert(piece_on(from) == EMPTY);
1479 assert(piece_on(capsq) == EMPTY);
1481 // Replace captured piece
1482 set_bit(&(byColorBB[them]), capsq);
1483 set_bit(&(byTypeBB[PAWN]), capsq);
1484 set_bit(&(byTypeBB[0]), capsq);
1485 board[capsq] = pawn_of_color(them);
1487 // Remove moving piece from destination square
1488 clear_bit(&(byColorBB[us]), to);
1489 clear_bit(&(byTypeBB[PAWN]), to);
1490 clear_bit(&(byTypeBB[0]), to);
1493 // Replace moving piece at source square
1494 set_bit(&(byColorBB[us]), from);
1495 set_bit(&(byTypeBB[PAWN]), from);
1496 set_bit(&(byTypeBB[0]), from);
1497 board[from] = pawn_of_color(us);
1499 // Update piece list:
1500 pieceList[us][PAWN][index[to]] = from;
1501 index[from] = index[to];
1502 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1503 index[capsq] = pieceCount[them][PAWN];
1505 // Update piece count:
1506 pieceCount[them][PAWN]++;
1510 /// Position::do_null_move makes() a "null move": It switches the side to move
1511 /// and updates the hash key without executing any move on the board.
1513 void Position::do_null_move(UndoInfo &u) {
1516 assert(!is_check());
1518 // Back up the information necessary to undo the null move to the supplied
1519 // UndoInfo object. In the case of a null move, the only thing we need to
1520 // remember is the last move made and the en passant square.
1521 u.lastMove = lastMove;
1522 u.epSquare = epSquare;
1524 // Save the current key to the history[] array, in order to be able to
1525 // detect repetition draws.
1526 history[gamePly] = key;
1528 // Update the necessary information
1529 sideToMove = opposite_color(sideToMove);
1530 if (epSquare != SQ_NONE)
1531 key ^= zobEp[epSquare];
1536 key ^= zobSideToMove;
1538 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1539 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1545 /// Position::undo_null_move() unmakes a "null move".
1547 void Position::undo_null_move(const UndoInfo &u) {
1550 assert(!is_check());
1552 // Restore information from the supplied UndoInfo object:
1553 lastMove = u.lastMove;
1554 epSquare = u.epSquare;
1555 if (epSquare != SQ_NONE)
1556 key ^= zobEp[epSquare];
1558 // Update the necessary information.
1559 sideToMove = opposite_color(sideToMove);
1562 key ^= zobSideToMove;
1564 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1565 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1571 /// Position::see() is a static exchange evaluator: It tries to estimate the
1572 /// material gain or loss resulting from a move. There are two versions of
1573 /// this function: One which takes a move as input, and one which takes a
1574 /// 'from' and a 'to' square. The function does not yet understand promotions
1575 /// or en passant captures.
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 {
1585 // Approximate material values, with pawn = 1
1586 static const int seeValues[18] = {
1587 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1590 Bitboard attackers, occ, b;
1592 assert(square_is_ok(from));
1593 assert(square_is_ok(to));
1595 // Initialize colors
1596 Color us = color_of_piece_on(from);
1597 Color them = opposite_color(us);
1599 // Initialize pieces
1600 Piece piece = piece_on(from);
1601 Piece capture = piece_on(to);
1603 // Find all attackers to the destination square, with the moving piece
1604 // removed, but possibly an X-ray attacker added behind it.
1605 occ = occupied_squares();
1606 clear_bit(&occ, from);
1607 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1608 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1609 | (piece_attacks<KNIGHT>(to) & knights())
1610 | (piece_attacks<KING>(to) & kings())
1611 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1612 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1614 // If the opponent has no attackers, we are finished
1615 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1616 return seeValues[capture];
1618 attackers &= occ; // Remove the moving piece
1620 // The destination square is defended, which makes things rather more
1621 // difficult to compute. We proceed by building up a "swap list" containing
1622 // the material gain or loss at each stop in a sequence of captures to the
1623 // destination square, where the sides alternately capture, and always
1624 // capture with the least valuable piece. After each capture, we look for
1625 // new X-ray attacks from behind the capturing piece.
1626 int lastCapturingPieceValue = seeValues[piece];
1627 int swapList[32], n = 1;
1631 swapList[0] = seeValues[capture];
1634 // Locate the least valuable attacker for the side to move. The loop
1635 // below looks like it is potentially infinite, but it isn't. We know
1636 // that the side to move still has at least one attacker left.
1637 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1640 // Remove the attacker we just found from the 'attackers' bitboard,
1641 // and scan for new X-ray attacks behind the attacker.
1642 b = attackers & pieces_of_color_and_type(c, pt);
1644 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1645 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1649 // Add the new entry to the swap list
1651 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1654 // Remember the value of the capturing piece, and change the side to move
1655 // before beginning the next iteration
1656 lastCapturingPieceValue = seeValues[pt];
1657 c = opposite_color(c);
1659 // Stop after a king capture
1660 if (pt == KING && (attackers & pieces_of_color(c)))
1663 swapList[n++] = 100;
1666 } while (attackers & pieces_of_color(c));
1668 // Having built the swap list, we negamax through it to find the best
1669 // achievable score from the point of view of the side to move
1671 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1677 /// Position::clear() erases the position object to a pristine state, with an
1678 /// empty board, white to move, and no castling rights.
1680 void Position::clear() {
1682 for (int i = 0; i < 64; i++)
1688 for (int i = 0; i < 2; i++)
1689 byColorBB[i] = EmptyBoardBB;
1691 for (int i = 0; i < 7; i++)
1693 byTypeBB[i] = EmptyBoardBB;
1694 pieceCount[0][i] = pieceCount[1][i] = 0;
1695 for (int j = 0; j < 8; j++)
1696 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1699 checkersBB = EmptyBoardBB;
1701 lastMove = MOVE_NONE;
1704 castleRights = NO_CASTLES;
1705 initialKFile = FILE_E;
1706 initialKRFile = FILE_H;
1707 initialQRFile = FILE_A;
1714 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1715 /// UCI interface code, whenever a non-reversible move is made in a
1716 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1717 /// for the program to handle games of arbitrary length, as long as the GUI
1718 /// handles draws by the 50 move rule correctly.
1720 void Position::reset_game_ply() {
1726 /// Position::put_piece() puts a piece on the given square of the board,
1727 /// updating the board array, bitboards, and piece counts.
1729 void Position::put_piece(Piece p, Square s) {
1731 Color c = color_of_piece(p);
1732 PieceType pt = type_of_piece(p);
1735 index[s] = pieceCount[c][pt];
1736 pieceList[c][pt][index[s]] = s;
1738 set_bit(&(byTypeBB[pt]), s);
1739 set_bit(&(byColorBB[c]), s);
1740 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1742 pieceCount[c][pt]++;
1749 /// Position::allow_oo() gives the given side the right to castle kingside.
1750 /// Used when setting castling rights during parsing of FEN strings.
1752 void Position::allow_oo(Color c) {
1754 castleRights |= (1 + int(c));
1758 /// Position::allow_ooo() gives the given side the right to castle queenside.
1759 /// Used when setting castling rights during parsing of FEN strings.
1761 void Position::allow_ooo(Color c) {
1763 castleRights |= (4 + 4*int(c));
1767 /// Position::compute_key() computes the hash key of the position. The hash
1768 /// key is usually updated incrementally as moves are made and unmade, the
1769 /// compute_key() function is only used when a new position is set up, and
1770 /// to verify the correctness of the hash key when running in debug mode.
1772 Key Position::compute_key() const {
1774 Key result = Key(0ULL);
1776 for (Square s = SQ_A1; s <= SQ_H8; s++)
1777 if (square_is_occupied(s))
1778 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1780 if (ep_square() != SQ_NONE)
1781 result ^= zobEp[ep_square()];
1783 result ^= zobCastle[castleRights];
1784 if (side_to_move() == BLACK)
1785 result ^= zobSideToMove;
1791 /// Position::compute_pawn_key() computes the hash key of the position. The
1792 /// hash key is usually updated incrementally as moves are made and unmade,
1793 /// the compute_pawn_key() function is only used when a new position is set
1794 /// up, and to verify the correctness of the pawn hash key when running in
1797 Key Position::compute_pawn_key() const {
1799 Key result = Key(0ULL);
1803 for (Color c = WHITE; c <= BLACK; c++)
1808 s = pop_1st_bit(&b);
1809 result ^= zobrist[c][PAWN][s];
1816 /// Position::compute_material_key() computes the hash key of the position.
1817 /// The hash key is usually updated incrementally as moves are made and unmade,
1818 /// the compute_material_key() function is only used when a new position is set
1819 /// up, and to verify the correctness of the material hash key when running in
1822 Key Position::compute_material_key() const {
1824 Key result = Key(0ULL);
1825 for (Color c = WHITE; c <= BLACK; c++)
1826 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1828 int count = piece_count(c, pt);
1829 for (int i = 0; i <= count; i++)
1830 result ^= zobMaterial[c][pt][i];
1836 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1837 /// incremental scores for the middle game and the endgame. These functions
1838 /// are used to initialize the incremental scores when a new position is set
1839 /// up, and to verify that the scores are correctly updated by do_move
1840 /// and undo_move when the program is running in debug mode.
1842 Value Position::compute_mg_value() const {
1844 Value result = Value(0);
1848 for (Color c = WHITE; c <= BLACK; c++)
1849 for (PieceType pt = PAWN; pt <= KING; pt++)
1851 b = pieces_of_color_and_type(c, pt);
1854 s = pop_1st_bit(&b);
1855 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1856 result += mg_pst(c, pt, s);
1859 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1863 Value Position::compute_eg_value() const {
1865 Value result = Value(0);
1869 for (Color c = WHITE; c <= BLACK; c++)
1870 for (PieceType pt = PAWN; pt <= KING; pt++)
1872 b = pieces_of_color_and_type(c, pt);
1875 s = pop_1st_bit(&b);
1876 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1877 result += eg_pst(c, pt, s);
1880 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1885 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1886 /// game material score for the given side. Material scores are updated
1887 /// incrementally during the search, this function is only used while
1888 /// initializing a new Position object.
1890 Value Position::compute_non_pawn_material(Color c) const {
1892 Value result = Value(0);
1895 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1897 Bitboard b = pieces_of_color_and_type(c, pt);
1900 s = pop_1st_bit(&b);
1901 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1902 result += piece_value_midgame(pt);
1909 /// Position::is_mate() returns true or false depending on whether the
1910 /// side to move is checkmated. Note that this function is currently very
1911 /// slow, and shouldn't be used frequently inside the search.
1913 bool Position::is_mate() {
1917 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1918 return mp.get_next_move() == MOVE_NONE;
1924 /// Position::is_draw() tests whether the position is drawn by material,
1925 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1926 /// must be done by the search.
1928 bool Position::is_draw() const {
1930 // Draw by material?
1932 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1935 // Draw by the 50 moves rule?
1936 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1939 // Draw by repetition?
1940 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1941 if (history[gamePly - i] == key)
1948 /// Position::has_mate_threat() tests whether a given color has a mate in one
1949 /// from the current position. This function is quite slow, but it doesn't
1950 /// matter, because it is currently only called from PV nodes, which are rare.
1952 bool Position::has_mate_threat(Color c) {
1955 Color stm = side_to_move();
1957 // The following lines are useless and silly, but prevents gcc from
1958 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1959 // be used uninitialized.
1960 u1.lastMove = lastMove;
1961 u1.epSquare = epSquare;
1966 // If the input color is not equal to the side to move, do a null move
1970 MoveStack mlist[120];
1972 bool result = false;
1974 // Generate legal moves
1975 count = generate_legal_moves(*this, mlist);
1977 // Loop through the moves, and see if one of them is mate
1978 for (int i = 0; i < count; i++)
1980 do_move(mlist[i].move, u2);
1984 undo_move(mlist[i].move, u2);
1987 // Undo null move, if necessary
1995 /// Position::init_zobrist() is a static member function which initializes the
1996 /// various arrays used to compute hash keys.
1998 void Position::init_zobrist() {
2000 for (int i = 0; i < 2; i++)
2001 for (int j = 0; j < 8; j++)
2002 for (int k = 0; k < 64; k++)
2003 zobrist[i][j][k] = Key(genrand_int64());
2005 for (int i = 0; i < 64; i++)
2006 zobEp[i] = Key(genrand_int64());
2008 for (int i = 0; i < 16; i++)
2009 zobCastle[i] = genrand_int64();
2011 zobSideToMove = genrand_int64();
2013 for (int i = 0; i < 2; i++)
2014 for (int j = 0; j < 8; j++)
2015 for (int k = 0; k < 16; k++)
2016 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2018 for (int i = 0; i < 16; i++)
2019 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2023 /// Position::init_piece_square_tables() initializes the piece square tables.
2024 /// This is a two-step operation: First, the white halves of the tables are
2025 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2026 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2027 /// Second, the black halves of the tables are initialized by mirroring
2028 /// and changing the sign of the corresponding white scores.
2030 void Position::init_piece_square_tables() {
2032 int r = get_option_value_int("Randomness"), i;
2033 for (Square s = SQ_A1; s <= SQ_H8; s++)
2034 for (Piece p = WP; p <= WK; p++)
2036 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2037 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2038 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2041 for (Square s = SQ_A1; s <= SQ_H8; s++)
2042 for (Piece p = BP; p <= BK; p++)
2044 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2045 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2050 /// Position::flipped_copy() makes a copy of the input position, but with
2051 /// the white and black sides reversed. This is only useful for debugging,
2052 /// especially for finding evaluation symmetry bugs.
2054 void Position::flipped_copy(const Position &pos) {
2056 assert(pos.is_ok());
2061 for (Square s = SQ_A1; s <= SQ_H8; s++)
2062 if (!pos.square_is_empty(s))
2063 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2066 sideToMove = opposite_color(pos.side_to_move());
2069 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2070 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2071 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2072 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2074 initialKFile = pos.initialKFile;
2075 initialKRFile = pos.initialKRFile;
2076 initialQRFile = pos.initialQRFile;
2078 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2079 castleRightsMask[sq] = ALL_CASTLES;
2081 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2082 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2083 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2084 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2085 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2086 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2088 // En passant square
2089 if (pos.epSquare != SQ_NONE)
2090 epSquare = flip_square(pos.epSquare);
2096 key = compute_key();
2097 pawnKey = compute_pawn_key();
2098 materialKey = compute_material_key();
2100 // Incremental scores
2101 mgValue = compute_mg_value();
2102 egValue = compute_eg_value();
2105 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2106 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2112 /// Position::is_ok() performs some consitency checks for the position object.
2113 /// This is meant to be helpful when debugging.
2115 bool Position::is_ok(int* failedStep) const {
2117 // What features of the position should be verified?
2118 static const bool debugBitboards = false;
2119 static const bool debugKingCount = false;
2120 static const bool debugKingCapture = false;
2121 static const bool debugCheckerCount = false;
2122 static const bool debugKey = false;
2123 static const bool debugMaterialKey = false;
2124 static const bool debugPawnKey = false;
2125 static const bool debugIncrementalEval = false;
2126 static const bool debugNonPawnMaterial = false;
2127 static const bool debugPieceCounts = false;
2128 static const bool debugPieceList = false;
2130 if (failedStep) *failedStep = 1;
2133 if (!color_is_ok(side_to_move()))
2136 // Are the king squares in the position correct?
2137 if (failedStep) (*failedStep)++;
2138 if (piece_on(king_square(WHITE)) != WK)
2141 if (failedStep) (*failedStep)++;
2142 if (piece_on(king_square(BLACK)) != BK)
2146 if (failedStep) (*failedStep)++;
2147 if (!file_is_ok(initialKRFile))
2150 if (!file_is_ok(initialQRFile))
2153 // Do both sides have exactly one king?
2154 if (failedStep) (*failedStep)++;
2157 int kingCount[2] = {0, 0};
2158 for (Square s = SQ_A1; s <= SQ_H8; s++)
2159 if (type_of_piece_on(s) == KING)
2160 kingCount[color_of_piece_on(s)]++;
2162 if(kingCount[0] != 1 || kingCount[1] != 1)
2166 // Can the side to move capture the opponent's king?
2167 if (failedStep) (*failedStep)++;
2168 if (debugKingCapture)
2170 Color us = side_to_move();
2171 Color them = opposite_color(us);
2172 Square ksq = king_square(them);
2173 if (square_is_attacked(ksq, us))
2177 // Is there more than 2 checkers?
2178 if (failedStep) (*failedStep)++;
2179 if (debugCheckerCount && count_1s(checkersBB) > 2)
2183 if (failedStep) (*failedStep)++;
2186 // The intersection of the white and black pieces must be empty
2187 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2190 // The union of the white and black pieces must be equal to all
2192 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2195 // Separate piece type bitboards must have empty intersections
2196 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2197 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2198 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2202 // En passant square OK?
2203 if (failedStep) (*failedStep)++;
2204 if (ep_square() != SQ_NONE)
2206 // The en passant square must be on rank 6, from the point of view of the
2208 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2213 if (failedStep) (*failedStep)++;
2214 if (debugKey && key != compute_key())
2217 // Pawn hash key OK?
2218 if (failedStep) (*failedStep)++;
2219 if (debugPawnKey && pawnKey != compute_pawn_key())
2222 // Material hash key OK?
2223 if (failedStep) (*failedStep)++;
2224 if (debugMaterialKey && materialKey != compute_material_key())
2227 // Incremental eval OK?
2228 if (failedStep) (*failedStep)++;
2229 if (debugIncrementalEval)
2231 if (mgValue != compute_mg_value())
2234 if (egValue != compute_eg_value())
2238 // Non-pawn material OK?
2239 if (failedStep) (*failedStep)++;
2240 if (debugNonPawnMaterial)
2242 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2245 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2250 if (failedStep) (*failedStep)++;
2251 if (debugPieceCounts)
2252 for (Color c = WHITE; c <= BLACK; c++)
2253 for (PieceType pt = PAWN; pt <= KING; pt++)
2254 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2257 if (failedStep) (*failedStep)++;
2260 for(Color c = WHITE; c <= BLACK; c++)
2261 for(PieceType pt = PAWN; pt <= KING; pt++)
2262 for(int i = 0; i < pieceCount[c][pt]; i++)
2264 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2267 if (index[piece_list(c, pt, i)] != i)
2271 if (failedStep) *failedStep = 0;