2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
35 #include "ucioption.h"
42 extern SearchStack EmptySearchStack;
44 int Position::castleRightsMask[64];
46 Key Position::zobrist[2][8][64];
47 Key Position::zobEp[64];
48 Key Position::zobCastle[16];
49 Key Position::zobMaterial[2][8][16];
50 Key Position::zobSideToMove;
52 Value Position::MgPieceSquareTable[16][64];
53 Value Position::EgPieceSquareTable[16][64];
55 static bool RequestPending = false;
63 Position::Position(const Position& pos) {
67 Position::Position(const std::string& fen) {
72 /// Position::from_fen() initializes the position object with the given FEN
73 /// string. This function is not very robust - make sure that input FENs are
74 /// correct (this is assumed to be the responsibility of the GUI).
76 void Position::from_fen(const std::string& fen) {
78 static const std::string pieceLetters = "KQRBNPkqrbnp";
79 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
87 for ( ; fen[i] != ' '; i++)
91 // Skip the given number of files
92 file += (fen[i] - '1' + 1);
95 else if (fen[i] == '/')
101 size_t idx = pieceLetters.find(fen[i]);
102 if (idx == std::string::npos)
104 std::cout << "Error in FEN at character " << i << std::endl;
107 Square square = make_square(file, rank);
108 put_piece(pieces[idx], square);
114 if (fen[i] != 'w' && fen[i] != 'b')
116 std::cout << "Error in FEN at character " << i << std::endl;
119 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
125 std::cout << "Error in FEN at character " << i << std::endl;
130 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
136 else if(fen[i] == 'K') allow_oo(WHITE);
137 else if(fen[i] == 'Q') allow_ooo(WHITE);
138 else if(fen[i] == 'k') allow_oo(BLACK);
139 else if(fen[i] == 'q') allow_ooo(BLACK);
140 else if(fen[i] >= 'A' && fen[i] <= 'H') {
141 File rookFile, kingFile = FILE_NONE;
142 for(Square square = SQ_B1; square <= SQ_G1; square++)
143 if(piece_on(square) == WK)
144 kingFile = square_file(square);
145 if(kingFile == FILE_NONE) {
146 std::cout << "Error in FEN at character " << i << std::endl;
149 initialKFile = kingFile;
150 rookFile = File(fen[i] - 'A') + FILE_A;
151 if(rookFile < initialKFile) {
153 initialQRFile = rookFile;
157 initialKRFile = rookFile;
160 else if(fen[i] >= 'a' && fen[i] <= 'h') {
161 File rookFile, kingFile = FILE_NONE;
162 for(Square square = SQ_B8; square <= SQ_G8; square++)
163 if(piece_on(square) == BK)
164 kingFile = square_file(square);
165 if(kingFile == FILE_NONE) {
166 std::cout << "Error in FEN at character " << i << std::endl;
169 initialKFile = kingFile;
170 rookFile = File(fen[i] - 'a') + FILE_A;
171 if(rookFile < initialKFile) {
173 initialQRFile = rookFile;
177 initialKRFile = rookFile;
181 std::cout << "Error in FEN at character " << i << std::endl;
188 while (fen[i] == ' ')
192 if ( i < fen.length() - 2
193 && (fen[i] >= 'a' && fen[i] <= 'h')
194 && (fen[i+1] == '3' || fen[i+1] == '6'))
195 epSquare = square_from_string(fen.substr(i, 2));
197 // Various initialisation
198 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
199 castleRightsMask[sq] = ALL_CASTLES;
201 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
202 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
203 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
204 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
205 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
206 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
211 pawnKey = compute_pawn_key();
212 materialKey = compute_material_key();
213 mgValue = compute_mg_value();
214 egValue = compute_eg_value();
215 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
216 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
220 /// Position::to_fen() converts the position object to a FEN string. This is
221 /// probably only useful for debugging.
223 const std::string Position::to_fen() const {
225 static const std::string pieceLetters = " PNBRQK pnbrqk";
229 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
232 for (File file = FILE_A; file <= FILE_H; file++)
234 Square sq = make_square(file, rank);
235 if (!square_is_occupied(sq))
241 fen += (char)skip + '0';
244 fen += pieceLetters[piece_on(sq)];
247 fen += (char)skip + '0';
249 fen += (rank > RANK_1 ? '/' : ' ');
251 fen += (sideToMove == WHITE ? "w " : "b ");
252 if (castleRights != NO_CASTLES)
254 if (can_castle_kingside(WHITE)) fen += 'K';
255 if (can_castle_queenside(WHITE)) fen += 'Q';
256 if (can_castle_kingside(BLACK)) fen += 'k';
257 if (can_castle_queenside(BLACK)) fen += 'q';
262 if (ep_square() != SQ_NONE)
263 fen += square_to_string(ep_square());
271 /// Position::print() prints an ASCII representation of the position to
272 /// the standard output. If a move is given then also the san is print.
274 void Position::print(Move m) const {
276 static const std::string pieceLetters = " PNBRQK PNBRQK .";
278 // Check for reentrancy, as example when called from inside
279 // MovePicker that is used also here in move_to_san()
283 RequestPending = true;
285 std::cout << std::endl;
288 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
289 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
291 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
293 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
294 for (File file = FILE_A; file <= FILE_H; file++)
296 Square sq = make_square(file, rank);
297 Piece piece = piece_on(sq);
298 if (piece == EMPTY && square_color(sq) == WHITE)
301 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
302 std::cout << '|' << col << pieceLetters[piece] << col;
304 std::cout << '|' << std::endl;
306 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
307 << "Fen is: " << to_fen() << std::endl
308 << "Key is: " << key << std::endl;
310 RequestPending = false;
314 /// Position::copy() creates a copy of the input position.
316 void Position::copy(const Position &pos) {
318 memcpy(this, &pos, sizeof(Position));
322 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
323 /// king) pieces for the given color.
324 Bitboard Position::pinned_pieces(Color c) const {
326 if (pinned[c] != ~EmptyBoardBB)
330 Square ksq = king_square(c);
331 pinned[c] = hidden_checks<ROOK, true>(c, ksq, p1) | hidden_checks<BISHOP, true>(c, ksq, p2);
332 pinners[c] = p1 | p2;
336 Bitboard Position::pinned_pieces(Color c, Bitboard& p) const {
338 if (pinned[c] == ~EmptyBoardBB)
345 Bitboard Position::discovered_check_candidates(Color c) const {
347 if (dcCandidates[c] != ~EmptyBoardBB)
348 return dcCandidates[c];
351 Square ksq = king_square(opposite_color(c));
352 dcCandidates[c] = hidden_checks<ROOK, false>(c, ksq, dummy) | hidden_checks<BISHOP, false>(c, ksq, dummy);
353 return dcCandidates[c];
356 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
357 /// king) pieces for the given color and for the given pinner type. Or, when
358 /// template parameter FindPinned is false, the pinned pieces of opposite color
359 /// that are, indeed, the pieces candidate for a discovery check.
360 template<PieceType Piece, bool FindPinned>
361 Bitboard Position::hidden_checks(Color c, Square ksq, Bitboard& pinners) const {
364 Bitboard sliders, result = EmptyBoardBB;
366 if (Piece == ROOK) // Resolved at compile time
367 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
369 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
371 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
373 // King blockers are candidate pinned pieces
374 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
376 // Pinners are sliders, not checkers, that give check when
377 // candidate pinned are removed.
378 pinners = (FindPinned ? sliders & ~checkersBB : sliders);
381 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
383 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
385 // Finally for each pinner find the corresponding pinned piece (if same color of king)
386 // or discovery checker (if opposite color) among the candidates.
387 Bitboard p = pinners;
391 result |= (squares_between(s, ksq) & candidate_pinned);
395 pinners = EmptyBoardBB;
401 /// Position::attacks_to() computes a bitboard containing all pieces which
402 /// attacks a given square. There are two versions of this function: One
403 /// which finds attackers of both colors, and one which only finds the
404 /// attackers for one side.
406 Bitboard Position::attacks_to(Square s) const {
408 return (pawn_attacks(BLACK, s) & pawns(WHITE))
409 | (pawn_attacks(WHITE, s) & pawns(BLACK))
410 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
411 | (piece_attacks<ROOK>(s) & rooks_and_queens())
412 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
413 | (piece_attacks<KING>(s) & pieces_of_type(KING));
416 /// Position::piece_attacks_square() tests whether the piece on square f
417 /// attacks square t.
419 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
421 assert(square_is_ok(f));
422 assert(square_is_ok(t));
426 case WP: return pawn_attacks_square(WHITE, f, t);
427 case BP: return pawn_attacks_square(BLACK, f, t);
428 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
429 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
430 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
431 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
432 case WK: case BK: return piece_attacks_square<KING>(f, t);
439 /// Position::move_attacks_square() tests whether a move from the current
440 /// position attacks a given square.
442 bool Position::move_attacks_square(Move m, Square s) const {
444 assert(move_is_ok(m));
445 assert(square_is_ok(s));
447 Square f = move_from(m), t = move_to(m);
449 assert(square_is_occupied(f));
451 if (piece_attacks_square(piece_on(f), t, s))
454 // Move the piece and scan for X-ray attacks behind it
455 Bitboard occ = occupied_squares();
456 Color us = color_of_piece_on(f);
459 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
460 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
462 // If we have attacks we need to verify that are caused by our move
463 // and are not already existent ones.
464 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
468 /// Position::find_checkers() computes the checkersBB bitboard, which
469 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
470 /// currently works by calling Position::attacks_to, which is probably
471 /// inefficient. Consider rewriting this function to use the last move
472 /// played, like in non-bitboard versions of Glaurung.
474 void Position::find_checkers() {
476 Color us = side_to_move();
477 checkersBB = attacks_to(king_square(us), opposite_color(us));
481 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
482 /// There are two versions of this function: One which takes only a
483 /// move as input, and one which takes a move and a bitboard of pinned
484 /// pieces. The latter function is faster, and should always be preferred
485 /// when a pinned piece bitboard has already been computed.
487 bool Position::pl_move_is_legal(Move m) const {
489 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
492 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
495 assert(move_is_ok(m));
496 assert(pinned == pinned_pieces(side_to_move()));
498 // If we're in check, all pseudo-legal moves are legal, because our
499 // check evasion generator only generates true legal moves.
503 // Castling moves are checked for legality during move generation.
504 if (move_is_castle(m))
507 Color us = side_to_move();
508 Color them = opposite_color(us);
509 Square from = move_from(m);
510 Square ksq = king_square(us);
512 assert(color_of_piece_on(from) == us);
513 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
515 // En passant captures are a tricky special case. Because they are
516 // rather uncommon, we do it simply by testing whether the king is attacked
517 // after the move is made
520 Square to = move_to(m);
521 Square capsq = make_square(square_file(to), square_rank(from));
522 Bitboard b = occupied_squares();
524 assert(to == ep_square());
525 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
526 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
527 assert(piece_on(to) == EMPTY);
530 clear_bit(&b, capsq);
533 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
534 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
537 // If the moving piece is a king, check whether the destination
538 // square is attacked by the opponent.
540 return !(square_is_attacked(move_to(m), them));
542 // A non-king move is legal if and only if it is not pinned or it
543 // is moving along the ray towards or away from the king.
544 return ( !bit_is_set(pinned, from)
545 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
549 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
550 /// There are two versions of this function: One which takes only a move as
551 /// input, and one which takes a move and a bitboard of discovered check
552 /// candidates. The latter function is faster, and should always be preferred
553 /// when a discovered check candidates bitboard has already been computed.
555 bool Position::move_is_check(Move m) const {
557 Bitboard dc = discovered_check_candidates(side_to_move());
558 return move_is_check(m, dc);
561 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
564 assert(move_is_ok(m));
565 assert(dcCandidates == discovered_check_candidates(side_to_move()));
567 Color us = side_to_move();
568 Color them = opposite_color(us);
569 Square from = move_from(m);
570 Square to = move_to(m);
571 Square ksq = king_square(them);
573 assert(color_of_piece_on(from) == us);
574 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
576 // Proceed according to the type of the moving piece
577 switch (type_of_piece_on(from))
581 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
584 if ( bit_is_set(dcCandidates, from) // Discovered check?
585 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
588 if (move_promotion(m)) // Promotion with check?
590 Bitboard b = occupied_squares();
593 switch (move_promotion(m))
596 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
598 return bit_is_set(bishop_attacks_bb(to, b), ksq);
600 return bit_is_set(rook_attacks_bb(to, b), ksq);
602 return bit_is_set(queen_attacks_bb(to, b), ksq);
607 // En passant capture with check? We have already handled the case
608 // of direct checks and ordinary discovered check, the only case we
609 // need to handle is the unusual case of a discovered check through the
611 else if (move_is_ep(m))
613 Square capsq = make_square(square_file(to), square_rank(from));
614 Bitboard b = occupied_squares();
616 clear_bit(&b, capsq);
618 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
619 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
624 return bit_is_set(dcCandidates, from) // Discovered check?
625 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
628 return bit_is_set(dcCandidates, from) // Discovered check?
629 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
632 return bit_is_set(dcCandidates, from) // Discovered check?
633 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
636 // Discovered checks are impossible!
637 assert(!bit_is_set(dcCandidates, from));
638 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
642 if ( bit_is_set(dcCandidates, from)
643 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
646 // Castling with check?
647 if (move_is_castle(m))
649 Square kfrom, kto, rfrom, rto;
650 Bitboard b = occupied_squares();
656 kto = relative_square(us, SQ_G1);
657 rto = relative_square(us, SQ_F1);
659 kto = relative_square(us, SQ_C1);
660 rto = relative_square(us, SQ_D1);
662 clear_bit(&b, kfrom);
663 clear_bit(&b, rfrom);
666 return bit_is_set(rook_attacks_bb(rto, b), ksq);
670 default: // NO_PIECE_TYPE
678 /// Position::move_is_capture() tests whether a move from the current
679 /// position is a capture. Move must not be MOVE_NONE.
681 bool Position::move_is_capture(Move m) const {
683 assert(m != MOVE_NONE);
685 return ( !square_is_empty(move_to(m))
686 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
692 /// Position::backup() is called when making a move. All information
693 /// necessary to restore the position when the move is later unmade
694 /// is saved to an UndoInfo object. The function Position::restore
695 /// does the reverse operation: When one does a backup followed by
696 /// a restore with the same UndoInfo object, the position is restored
697 /// to the state before backup was called.
699 void Position::backup(UndoInfo& u) const {
701 u.castleRights = castleRights;
702 u.epSquare = epSquare;
703 u.checkersBB = checkersBB;
706 u.materialKey = materialKey;
708 u.lastMove = lastMove;
711 u.capture = NO_PIECE_TYPE;
713 for (Color c = WHITE; c <= BLACK; c++)
715 u.pinners[c] = pinners[c];
716 u.pinned[c] = pinned[c];
717 u.dcCandidates[c] = dcCandidates[c];
722 /// Position::restore() is called when unmaking a move. It copies back
723 /// the information backed up during a previous call to Position::backup.
725 void Position::restore(const UndoInfo& u) {
727 castleRights = u.castleRights;
728 epSquare = u.epSquare;
729 checkersBB = u.checkersBB;
732 materialKey = u.materialKey;
734 lastMove = u.lastMove;
737 // u.capture is restored in undo_move()
739 for (Color c = WHITE; c <= BLACK; c++)
741 pinners[c] = u.pinners[c];
742 pinned[c] = u.pinned[c];
743 dcCandidates[c] = u.dcCandidates[c];
748 /// Position::update_checkers() is a private method to udpate chekers info
750 template<PieceType Piece>
751 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
752 Square to, Bitboard dcCandidates) {
754 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
755 set_bit(pCheckersBB, to);
757 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
760 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
763 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
768 /// Position::do_move() makes a move, and backs up all information necessary
769 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
770 /// Pseudo-legal moves should be filtered out before this function is called.
771 /// There are two versions of this function, one which takes only the move and
772 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
773 /// discovered check candidates. The second version is faster, because knowing
774 /// the discovered check candidates makes it easier to update the checkersBB
775 /// member variable in the position object.
777 void Position::do_move(Move m, UndoInfo& u) {
779 do_move(m, u, discovered_check_candidates(side_to_move()));
782 void Position::do_move(Move m, UndoInfo& u, Bitboard dc) {
785 assert(move_is_ok(m));
787 // Back up the necessary information to our UndoInfo object (except the
788 // captured piece, which is taken care of later.
791 // Save the current key to the history[] array, in order to be able to
792 // detect repetition draws.
793 history[gamePly] = key;
795 // Increment the 50 moves rule draw counter. Resetting it to zero in the
796 // case of non-reversible moves is taken care of later.
799 // Reset pinned bitboard and its friends
800 for (Color c = WHITE; c <= BLACK; c++)
801 pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
803 if (move_is_castle(m))
805 else if (move_promotion(m))
806 do_promotion_move(m, u);
807 else if (move_is_ep(m))
811 Color us = side_to_move();
812 Color them = opposite_color(us);
813 Square from = move_from(m);
814 Square to = move_to(m);
816 assert(color_of_piece_on(from) == us);
817 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
819 PieceType piece = type_of_piece_on(from);
820 PieceType capture = type_of_piece_on(to);
825 do_capture_move(m, capture, them, to);
829 clear_bit(&(byColorBB[us]), from);
830 clear_bit(&(byTypeBB[piece]), from);
831 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
832 set_bit(&(byColorBB[us]), to);
833 set_bit(&(byTypeBB[piece]), to);
834 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
835 board[to] = board[from];
839 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
841 // Update incremental scores
842 mgValue -= mg_pst(us, piece, from);
843 mgValue += mg_pst(us, piece, to);
844 egValue -= eg_pst(us, piece, from);
845 egValue += eg_pst(us, piece, to);
847 // If the moving piece was a king, update the king square
851 // Reset en passant square
852 if (epSquare != SQ_NONE)
854 key ^= zobEp[epSquare];
858 // If the moving piece was a pawn do some special extra work
861 // Reset rule 50 draw counter
864 // Update pawn hash key
865 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
867 // Set en passant square, only if moved pawn can be captured
868 if (abs(int(to) - int(from)) == 16)
870 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
871 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
873 epSquare = Square((int(from) + int(to)) / 2);
874 key ^= zobEp[epSquare];
879 // Update piece lists
880 pieceList[us][piece][index[from]] = to;
881 index[to] = index[from];
883 // Update castle rights
884 key ^= zobCastle[castleRights];
885 castleRights &= castleRightsMask[from];
886 castleRights &= castleRightsMask[to];
887 key ^= zobCastle[castleRights];
889 // Update checkers bitboard, piece must be already moved
890 checkersBB = EmptyBoardBB;
891 Square ksq = king_square(them);
894 case PAWN: update_checkers<PAWN>(&checkersBB, ksq, from, to, dc); break;
895 case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, dc); break;
896 case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, dc); break;
897 case ROOK: update_checkers<ROOK>(&checkersBB, ksq, from, to, dc); break;
898 case QUEEN: update_checkers<QUEEN>(&checkersBB, ksq, from, to, dc); break;
899 case KING: update_checkers<KING>(&checkersBB, ksq, from, to, dc); break;
900 default: assert(false); break;
905 key ^= zobSideToMove;
906 sideToMove = opposite_color(sideToMove);
909 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
910 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
916 /// Position::do_capture_move() is a private method used to update captured
917 /// piece info. It is called from the main Position::do_move function.
919 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
921 assert(capture != KING);
923 // Remove captured piece
924 clear_bit(&(byColorBB[them]), to);
925 clear_bit(&(byTypeBB[capture]), to);
928 key ^= zobrist[them][capture][to];
930 // If the captured piece was a pawn, update pawn hash key
932 pawnKey ^= zobrist[them][PAWN][to];
934 // Update incremental scores
935 mgValue -= mg_pst(them, capture, to);
936 egValue -= eg_pst(them, capture, to);
938 assert(!move_promotion(m) || capture != PAWN);
942 npMaterial[them] -= piece_value_midgame(capture);
944 // Update material hash key
945 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
947 // Update piece count
948 pieceCount[them][capture]--;
951 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
952 index[pieceList[them][capture][index[to]]] = index[to];
954 // Reset rule 50 counter
959 /// Position::do_castle_move() is a private method used to make a castling
960 /// move. It is called from the main Position::do_move function. Note that
961 /// castling moves are encoded as "king captures friendly rook" moves, for
962 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
964 void Position::do_castle_move(Move m) {
967 assert(move_is_ok(m));
968 assert(move_is_castle(m));
970 Color us = side_to_move();
971 Color them = opposite_color(us);
973 // Find source squares for king and rook
974 Square kfrom = move_from(m);
975 Square rfrom = move_to(m); // HACK: See comment at beginning of function
978 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
979 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
981 // Find destination squares for king and rook
982 if (rfrom > kfrom) // O-O
984 kto = relative_square(us, SQ_G1);
985 rto = relative_square(us, SQ_F1);
987 kto = relative_square(us, SQ_C1);
988 rto = relative_square(us, SQ_D1);
991 // Remove pieces from source squares
992 clear_bit(&(byColorBB[us]), kfrom);
993 clear_bit(&(byTypeBB[KING]), kfrom);
994 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
995 clear_bit(&(byColorBB[us]), rfrom);
996 clear_bit(&(byTypeBB[ROOK]), rfrom);
997 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
999 // Put pieces on destination squares
1000 set_bit(&(byColorBB[us]), kto);
1001 set_bit(&(byTypeBB[KING]), kto);
1002 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1003 set_bit(&(byColorBB[us]), rto);
1004 set_bit(&(byTypeBB[ROOK]), rto);
1005 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1007 // Update board array
1008 board[kfrom] = board[rfrom] = EMPTY;
1009 board[kto] = piece_of_color_and_type(us, KING);
1010 board[rto] = piece_of_color_and_type(us, ROOK);
1012 // Update king square
1013 kingSquare[us] = kto;
1015 // Update piece lists
1016 pieceList[us][KING][index[kfrom]] = kto;
1017 pieceList[us][ROOK][index[rfrom]] = rto;
1018 int tmp = index[rfrom];
1019 index[kto] = index[kfrom];
1022 // Update incremental scores
1023 mgValue -= mg_pst(us, KING, kfrom);
1024 mgValue += mg_pst(us, KING, kto);
1025 egValue -= eg_pst(us, KING, kfrom);
1026 egValue += eg_pst(us, KING, kto);
1027 mgValue -= mg_pst(us, ROOK, rfrom);
1028 mgValue += mg_pst(us, ROOK, rto);
1029 egValue -= eg_pst(us, ROOK, rfrom);
1030 egValue += eg_pst(us, ROOK, rto);
1033 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1034 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1036 // Clear en passant square
1037 if (epSquare != SQ_NONE)
1039 key ^= zobEp[epSquare];
1043 // Update castling rights
1044 key ^= zobCastle[castleRights];
1045 castleRights &= castleRightsMask[kfrom];
1046 key ^= zobCastle[castleRights];
1048 // Reset rule 50 counter
1051 // Update checkers BB
1052 checkersBB = attacks_to(king_square(them), us);
1056 /// Position::do_promotion_move() is a private method used to make a promotion
1057 /// move. It is called from the main Position::do_move function. The
1058 /// UndoInfo object, which has been initialized in Position::do_move, is
1059 /// used to store the captured piece (if any).
1061 void Position::do_promotion_move(Move m, UndoInfo &u) {
1065 PieceType capture, promotion;
1068 assert(move_is_ok(m));
1069 assert(move_promotion(m));
1071 us = side_to_move();
1072 them = opposite_color(us);
1073 from = move_from(m);
1076 assert(relative_rank(us, to) == RANK_8);
1077 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1078 assert(color_of_piece_on(to) == them || square_is_empty(to));
1080 capture = type_of_piece_on(to);
1084 u.capture = capture;
1085 do_capture_move(m, capture, them, to);
1089 clear_bit(&(byColorBB[us]), from);
1090 clear_bit(&(byTypeBB[PAWN]), from);
1091 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1092 board[from] = EMPTY;
1094 // Insert promoted piece
1095 promotion = move_promotion(m);
1096 assert(promotion >= KNIGHT && promotion <= QUEEN);
1097 set_bit(&(byColorBB[us]), to);
1098 set_bit(&(byTypeBB[promotion]), to);
1099 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1100 board[to] = piece_of_color_and_type(us, promotion);
1103 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1105 // Update pawn hash key
1106 pawnKey ^= zobrist[us][PAWN][from];
1108 // Update material key
1109 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1110 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1112 // Update piece counts
1113 pieceCount[us][PAWN]--;
1114 pieceCount[us][promotion]++;
1116 // Update piece lists
1117 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1118 index[pieceList[us][PAWN][index[from]]] = index[from];
1119 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1120 index[to] = pieceCount[us][promotion] - 1;
1122 // Update incremental scores
1123 mgValue -= mg_pst(us, PAWN, from);
1124 mgValue += mg_pst(us, promotion, to);
1125 egValue -= eg_pst(us, PAWN, from);
1126 egValue += eg_pst(us, promotion, to);
1129 npMaterial[us] += piece_value_midgame(promotion);
1131 // Clear the en passant square
1132 if (epSquare != SQ_NONE)
1134 key ^= zobEp[epSquare];
1138 // Update castle rights
1139 key ^= zobCastle[castleRights];
1140 castleRights &= castleRightsMask[to];
1141 key ^= zobCastle[castleRights];
1143 // Reset rule 50 counter
1146 // Update checkers BB
1147 checkersBB = attacks_to(king_square(them), us);
1151 /// Position::do_ep_move() is a private method used to make an en passant
1152 /// capture. It is called from the main Position::do_move function. Because
1153 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1154 /// object in which to store the captured piece.
1156 void Position::do_ep_move(Move m) {
1159 Square from, to, capsq;
1162 assert(move_is_ok(m));
1163 assert(move_is_ep(m));
1165 us = side_to_move();
1166 them = opposite_color(us);
1167 from = move_from(m);
1169 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1171 assert(to == epSquare);
1172 assert(relative_rank(us, to) == RANK_6);
1173 assert(piece_on(to) == EMPTY);
1174 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1175 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1177 // Remove captured piece
1178 clear_bit(&(byColorBB[them]), capsq);
1179 clear_bit(&(byTypeBB[PAWN]), capsq);
1180 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1181 board[capsq] = EMPTY;
1183 // Remove moving piece from source square
1184 clear_bit(&(byColorBB[us]), from);
1185 clear_bit(&(byTypeBB[PAWN]), from);
1186 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1188 // Put moving piece on destination square
1189 set_bit(&(byColorBB[us]), to);
1190 set_bit(&(byTypeBB[PAWN]), to);
1191 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1192 board[to] = board[from];
1193 board[from] = EMPTY;
1195 // Update material hash key
1196 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1198 // Update piece count
1199 pieceCount[them][PAWN]--;
1201 // Update piece list
1202 pieceList[us][PAWN][index[from]] = to;
1203 index[to] = index[from];
1204 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1205 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1208 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1209 key ^= zobrist[them][PAWN][capsq];
1210 key ^= zobEp[epSquare];
1212 // Update pawn hash key
1213 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1214 pawnKey ^= zobrist[them][PAWN][capsq];
1216 // Update incremental scores
1217 mgValue -= mg_pst(them, PAWN, capsq);
1218 mgValue -= mg_pst(us, PAWN, from);
1219 mgValue += mg_pst(us, PAWN, to);
1220 egValue -= eg_pst(them, PAWN, capsq);
1221 egValue -= eg_pst(us, PAWN, from);
1222 egValue += eg_pst(us, PAWN, to);
1224 // Reset en passant square
1227 // Reset rule 50 counter
1230 // Update checkers BB
1231 checkersBB = attacks_to(king_square(them), us);
1235 /// Position::undo_move() unmakes a move. When it returns, the position should
1236 /// be restored to exactly the same state as before the move was made. It is
1237 /// important that Position::undo_move is called with the same move and UndoInfo
1238 /// object as the earlier call to Position::do_move.
1240 void Position::undo_move(Move m, const UndoInfo &u) {
1243 assert(move_is_ok(m));
1246 sideToMove = opposite_color(sideToMove);
1248 // Restore information from our UndoInfo object (except the captured piece,
1249 // which is taken care of later)
1252 if (move_is_castle(m))
1253 undo_castle_move(m);
1254 else if (move_promotion(m))
1255 undo_promotion_move(m, u);
1256 else if (move_is_ep(m))
1262 PieceType piece, capture;
1264 us = side_to_move();
1265 them = opposite_color(us);
1266 from = move_from(m);
1269 assert(piece_on(from) == EMPTY);
1270 assert(color_of_piece_on(to) == us);
1272 // Put the piece back at the source square
1273 piece = type_of_piece_on(to);
1274 set_bit(&(byColorBB[us]), from);
1275 set_bit(&(byTypeBB[piece]), from);
1276 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1277 board[from] = piece_of_color_and_type(us, piece);
1279 // Clear the destination square
1280 clear_bit(&(byColorBB[us]), to);
1281 clear_bit(&(byTypeBB[piece]), to);
1282 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1284 // If the moving piece was a king, update the king square
1286 kingSquare[us] = from;
1288 // Update piece list
1289 pieceList[us][piece][index[to]] = from;
1290 index[from] = index[to];
1292 capture = u.capture;
1296 assert(capture != KING);
1298 // Replace the captured piece
1299 set_bit(&(byColorBB[them]), to);
1300 set_bit(&(byTypeBB[capture]), to);
1301 set_bit(&(byTypeBB[0]), to);
1302 board[to] = piece_of_color_and_type(them, capture);
1305 if (capture != PAWN)
1306 npMaterial[them] += piece_value_midgame(capture);
1308 // Update piece list
1309 pieceList[them][capture][pieceCount[them][capture]] = to;
1310 index[to] = pieceCount[them][capture];
1312 // Update piece count
1313 pieceCount[them][capture]++;
1322 /// Position::undo_castle_move() is a private method used to unmake a castling
1323 /// move. It is called from the main Position::undo_move function. Note that
1324 /// castling moves are encoded as "king captures friendly rook" moves, for
1325 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1327 void Position::undo_castle_move(Move m) {
1329 assert(move_is_ok(m));
1330 assert(move_is_castle(m));
1332 // When we have arrived here, some work has already been done by
1333 // Position::undo_move. In particular, the side to move has been switched,
1334 // so the code below is correct.
1335 Color us = side_to_move();
1337 // Find source squares for king and rook
1338 Square kfrom = move_from(m);
1339 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1342 // Find destination squares for king and rook
1343 if (rfrom > kfrom) // O-O
1345 kto = relative_square(us, SQ_G1);
1346 rto = relative_square(us, SQ_F1);
1348 kto = relative_square(us, SQ_C1);
1349 rto = relative_square(us, SQ_D1);
1352 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1353 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1355 // Remove pieces from destination squares
1356 clear_bit(&(byColorBB[us]), kto);
1357 clear_bit(&(byTypeBB[KING]), kto);
1358 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1359 clear_bit(&(byColorBB[us]), rto);
1360 clear_bit(&(byTypeBB[ROOK]), rto);
1361 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1363 // Put pieces on source squares
1364 set_bit(&(byColorBB[us]), kfrom);
1365 set_bit(&(byTypeBB[KING]), kfrom);
1366 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1367 set_bit(&(byColorBB[us]), rfrom);
1368 set_bit(&(byTypeBB[ROOK]), rfrom);
1369 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1372 board[rto] = board[kto] = EMPTY;
1373 board[rfrom] = piece_of_color_and_type(us, ROOK);
1374 board[kfrom] = piece_of_color_and_type(us, KING);
1376 // Update king square
1377 kingSquare[us] = kfrom;
1379 // Update piece lists
1380 pieceList[us][KING][index[kto]] = kfrom;
1381 pieceList[us][ROOK][index[rto]] = rfrom;
1382 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1383 index[kfrom] = index[kto];
1388 /// Position::undo_promotion_move() is a private method used to unmake a
1389 /// promotion move. It is called from the main Position::do_move
1390 /// function. The UndoInfo object, which has been initialized in
1391 /// Position::do_move, is used to put back the captured piece (if any).
1393 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1397 PieceType capture, promotion;
1399 assert(move_is_ok(m));
1400 assert(move_promotion(m));
1402 // When we have arrived here, some work has already been done by
1403 // Position::undo_move. In particular, the side to move has been switched,
1404 // so the code below is correct.
1405 us = side_to_move();
1406 them = opposite_color(us);
1407 from = move_from(m);
1410 assert(relative_rank(us, to) == RANK_8);
1411 assert(piece_on(from) == EMPTY);
1413 // Remove promoted piece
1414 promotion = move_promotion(m);
1415 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1416 assert(promotion >= KNIGHT && promotion <= QUEEN);
1417 clear_bit(&(byColorBB[us]), to);
1418 clear_bit(&(byTypeBB[promotion]), to);
1419 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1421 // Insert pawn at source square
1422 set_bit(&(byColorBB[us]), from);
1423 set_bit(&(byTypeBB[PAWN]), from);
1424 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1425 board[from] = piece_of_color_and_type(us, PAWN);
1428 npMaterial[us] -= piece_value_midgame(promotion);
1430 // Update piece list
1431 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1432 index[from] = pieceCount[us][PAWN];
1433 pieceList[us][promotion][index[to]] =
1434 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1435 index[pieceList[us][promotion][index[to]]] = index[to];
1437 // Update piece counts
1438 pieceCount[us][promotion]--;
1439 pieceCount[us][PAWN]++;
1441 capture = u.capture;
1445 assert(capture != KING);
1447 // Insert captured piece:
1448 set_bit(&(byColorBB[them]), to);
1449 set_bit(&(byTypeBB[capture]), to);
1450 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1451 board[to] = piece_of_color_and_type(them, capture);
1453 // Update material. Because the move is a promotion move, we know
1454 // that the captured piece cannot be a pawn.
1455 assert(capture != PAWN);
1456 npMaterial[them] += piece_value_midgame(capture);
1458 // Update piece list
1459 pieceList[them][capture][pieceCount[them][capture]] = to;
1460 index[to] = pieceCount[them][capture];
1462 // Update piece count
1463 pieceCount[them][capture]++;
1469 /// Position::undo_ep_move() is a private method used to unmake an en passant
1470 /// capture. It is called from the main Position::undo_move function. Because
1471 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1472 /// object from which to retrieve the captured piece.
1474 void Position::undo_ep_move(Move m) {
1476 assert(move_is_ok(m));
1477 assert(move_is_ep(m));
1479 // When we have arrived here, some work has already been done by
1480 // Position::undo_move. In particular, the side to move has been switched,
1481 // so the code below is correct.
1482 Color us = side_to_move();
1483 Color them = opposite_color(us);
1484 Square from = move_from(m);
1485 Square to = move_to(m);
1486 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1488 assert(to == ep_square());
1489 assert(relative_rank(us, to) == RANK_6);
1490 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1491 assert(piece_on(from) == EMPTY);
1492 assert(piece_on(capsq) == EMPTY);
1494 // Replace captured piece
1495 set_bit(&(byColorBB[them]), capsq);
1496 set_bit(&(byTypeBB[PAWN]), capsq);
1497 set_bit(&(byTypeBB[0]), capsq);
1498 board[capsq] = piece_of_color_and_type(them, PAWN);
1500 // Remove moving piece from destination square
1501 clear_bit(&(byColorBB[us]), to);
1502 clear_bit(&(byTypeBB[PAWN]), to);
1503 clear_bit(&(byTypeBB[0]), to);
1506 // Replace moving piece at source square
1507 set_bit(&(byColorBB[us]), from);
1508 set_bit(&(byTypeBB[PAWN]), from);
1509 set_bit(&(byTypeBB[0]), from);
1510 board[from] = piece_of_color_and_type(us, PAWN);
1512 // Update piece list:
1513 pieceList[us][PAWN][index[to]] = from;
1514 index[from] = index[to];
1515 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1516 index[capsq] = pieceCount[them][PAWN];
1518 // Update piece count:
1519 pieceCount[them][PAWN]++;
1523 /// Position::do_null_move makes() a "null move": It switches the side to move
1524 /// and updates the hash key without executing any move on the board.
1526 void Position::do_null_move(UndoInfo& u) {
1529 assert(!is_check());
1531 // Back up the information necessary to undo the null move to the supplied
1532 // UndoInfo object. In the case of a null move, the only thing we need to
1533 // remember is the last move made and the en passant square.
1534 u.lastMove = lastMove;
1535 u.epSquare = epSquare;
1537 // Save the current key to the history[] array, in order to be able to
1538 // detect repetition draws.
1539 history[gamePly] = key;
1541 // Update the necessary information
1542 sideToMove = opposite_color(sideToMove);
1543 if (epSquare != SQ_NONE)
1544 key ^= zobEp[epSquare];
1549 key ^= zobSideToMove;
1551 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1552 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1558 /// Position::undo_null_move() unmakes a "null move".
1560 void Position::undo_null_move(const UndoInfo &u) {
1563 assert(!is_check());
1565 // Restore information from the supplied UndoInfo object:
1566 lastMove = u.lastMove;
1567 epSquare = u.epSquare;
1568 if (epSquare != SQ_NONE)
1569 key ^= zobEp[epSquare];
1571 // Update the necessary information.
1572 sideToMove = opposite_color(sideToMove);
1575 key ^= zobSideToMove;
1577 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1578 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1584 /// Position::see() is a static exchange evaluator: It tries to estimate the
1585 /// material gain or loss resulting from a move. There are three versions of
1586 /// this function: One which takes a destination square as input, one takes a
1587 /// move, and one which takes a 'from' and a 'to' square. The function does
1588 /// not yet understand promotions captures.
1590 int Position::see(Square to) const {
1592 assert(square_is_ok(to));
1593 return see(SQ_NONE, to);
1596 int Position::see(Move m) const {
1598 assert(move_is_ok(m));
1599 return see(move_from(m), move_to(m));
1602 int Position::see(Square from, Square to) const {
1605 static const int seeValues[18] = {
1606 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1607 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1608 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1609 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1613 Bitboard attackers, occ, b;
1615 assert(square_is_ok(from) || from == SQ_NONE);
1616 assert(square_is_ok(to));
1618 // Initialize colors
1619 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1620 Color them = opposite_color(us);
1622 // Initialize pieces
1623 Piece piece = piece_on(from);
1624 Piece capture = piece_on(to);
1626 // Find all attackers to the destination square, with the moving piece
1627 // removed, but possibly an X-ray attacker added behind it.
1628 occ = occupied_squares();
1630 // Handle en passant moves
1631 if (epSquare == to && type_of_piece_on(from) == PAWN)
1633 assert(capture == EMPTY);
1635 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1636 capture = piece_on(capQq);
1638 assert(type_of_piece_on(capQq) == PAWN);
1640 // Remove the captured pawn
1641 clear_bit(&occ, capQq);
1646 clear_bit(&occ, from);
1647 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1648 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1649 | (piece_attacks<KNIGHT>(to) & knights())
1650 | (piece_attacks<KING>(to) & kings())
1651 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1652 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1654 if (from != SQ_NONE)
1657 // If we don't have any attacker we are finished
1658 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1661 // Locate the least valuable attacker to the destination square
1662 // and use it to initialize from square.
1664 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1667 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1668 piece = piece_on(from);
1671 // If the opponent has no attackers we are finished
1672 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1673 return seeValues[capture];
1675 attackers &= occ; // Remove the moving piece
1677 // The destination square is defended, which makes things rather more
1678 // difficult to compute. We proceed by building up a "swap list" containing
1679 // the material gain or loss at each stop in a sequence of captures to the
1680 // destination square, where the sides alternately capture, and always
1681 // capture with the least valuable piece. After each capture, we look for
1682 // new X-ray attacks from behind the capturing piece.
1683 int lastCapturingPieceValue = seeValues[piece];
1684 int swapList[32], n = 1;
1688 swapList[0] = seeValues[capture];
1691 // Locate the least valuable attacker for the side to move. The loop
1692 // below looks like it is potentially infinite, but it isn't. We know
1693 // that the side to move still has at least one attacker left.
1694 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1697 // Remove the attacker we just found from the 'attackers' bitboard,
1698 // and scan for new X-ray attacks behind the attacker.
1699 b = attackers & pieces_of_color_and_type(c, pt);
1701 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1702 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1706 // Add the new entry to the swap list
1708 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1711 // Remember the value of the capturing piece, and change the side to move
1712 // before beginning the next iteration
1713 lastCapturingPieceValue = seeValues[pt];
1714 c = opposite_color(c);
1716 // Stop after a king capture
1717 if (pt == KING && (attackers & pieces_of_color(c)))
1720 swapList[n++] = 100;
1723 } while (attackers & pieces_of_color(c));
1725 // Having built the swap list, we negamax through it to find the best
1726 // achievable score from the point of view of the side to move
1728 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1734 /// Position::clear() erases the position object to a pristine state, with an
1735 /// empty board, white to move, and no castling rights.
1737 void Position::clear() {
1739 for (int i = 0; i < 64; i++)
1745 for (int i = 0; i < 2; i++)
1746 byColorBB[i] = EmptyBoardBB;
1748 for (int i = 0; i < 7; i++)
1750 byTypeBB[i] = EmptyBoardBB;
1751 pieceCount[0][i] = pieceCount[1][i] = 0;
1752 for (int j = 0; j < 8; j++)
1753 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1756 checkersBB = EmptyBoardBB;
1757 for (Color c = WHITE; c <= BLACK; c++)
1758 pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
1760 lastMove = MOVE_NONE;
1763 castleRights = NO_CASTLES;
1764 initialKFile = FILE_E;
1765 initialKRFile = FILE_H;
1766 initialQRFile = FILE_A;
1773 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1774 /// UCI interface code, whenever a non-reversible move is made in a
1775 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1776 /// for the program to handle games of arbitrary length, as long as the GUI
1777 /// handles draws by the 50 move rule correctly.
1779 void Position::reset_game_ply() {
1785 /// Position::put_piece() puts a piece on the given square of the board,
1786 /// updating the board array, bitboards, and piece counts.
1788 void Position::put_piece(Piece p, Square s) {
1790 Color c = color_of_piece(p);
1791 PieceType pt = type_of_piece(p);
1794 index[s] = pieceCount[c][pt];
1795 pieceList[c][pt][index[s]] = s;
1797 set_bit(&(byTypeBB[pt]), s);
1798 set_bit(&(byColorBB[c]), s);
1799 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1801 pieceCount[c][pt]++;
1808 /// Position::allow_oo() gives the given side the right to castle kingside.
1809 /// Used when setting castling rights during parsing of FEN strings.
1811 void Position::allow_oo(Color c) {
1813 castleRights |= (1 + int(c));
1817 /// Position::allow_ooo() gives the given side the right to castle queenside.
1818 /// Used when setting castling rights during parsing of FEN strings.
1820 void Position::allow_ooo(Color c) {
1822 castleRights |= (4 + 4*int(c));
1826 /// Position::compute_key() computes the hash key of the position. The hash
1827 /// key is usually updated incrementally as moves are made and unmade, the
1828 /// compute_key() function is only used when a new position is set up, and
1829 /// to verify the correctness of the hash key when running in debug mode.
1831 Key Position::compute_key() const {
1833 Key result = Key(0ULL);
1835 for (Square s = SQ_A1; s <= SQ_H8; s++)
1836 if (square_is_occupied(s))
1837 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1839 if (ep_square() != SQ_NONE)
1840 result ^= zobEp[ep_square()];
1842 result ^= zobCastle[castleRights];
1843 if (side_to_move() == BLACK)
1844 result ^= zobSideToMove;
1850 /// Position::compute_pawn_key() computes the hash key of the position. The
1851 /// hash key is usually updated incrementally as moves are made and unmade,
1852 /// the compute_pawn_key() function is only used when a new position is set
1853 /// up, and to verify the correctness of the pawn hash key when running in
1856 Key Position::compute_pawn_key() const {
1858 Key result = Key(0ULL);
1862 for (Color c = WHITE; c <= BLACK; c++)
1867 s = pop_1st_bit(&b);
1868 result ^= zobrist[c][PAWN][s];
1875 /// Position::compute_material_key() computes the hash key of the position.
1876 /// The hash key is usually updated incrementally as moves are made and unmade,
1877 /// the compute_material_key() function is only used when a new position is set
1878 /// up, and to verify the correctness of the material hash key when running in
1881 Key Position::compute_material_key() const {
1883 Key result = Key(0ULL);
1884 for (Color c = WHITE; c <= BLACK; c++)
1885 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1887 int count = piece_count(c, pt);
1888 for (int i = 0; i <= count; i++)
1889 result ^= zobMaterial[c][pt][i];
1895 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1896 /// incremental scores for the middle game and the endgame. These functions
1897 /// are used to initialize the incremental scores when a new position is set
1898 /// up, and to verify that the scores are correctly updated by do_move
1899 /// and undo_move when the program is running in debug mode.
1901 Value Position::compute_mg_value() const {
1903 Value result = Value(0);
1907 for (Color c = WHITE; c <= BLACK; c++)
1908 for (PieceType pt = PAWN; pt <= KING; pt++)
1910 b = pieces_of_color_and_type(c, pt);
1913 s = pop_1st_bit(&b);
1914 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1915 result += mg_pst(c, pt, s);
1918 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1922 Value Position::compute_eg_value() const {
1924 Value result = Value(0);
1928 for (Color c = WHITE; c <= BLACK; c++)
1929 for (PieceType pt = PAWN; pt <= KING; pt++)
1931 b = pieces_of_color_and_type(c, pt);
1934 s = pop_1st_bit(&b);
1935 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1936 result += eg_pst(c, pt, s);
1939 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1944 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1945 /// game material score for the given side. Material scores are updated
1946 /// incrementally during the search, this function is only used while
1947 /// initializing a new Position object.
1949 Value Position::compute_non_pawn_material(Color c) const {
1951 Value result = Value(0);
1954 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1956 Bitboard b = pieces_of_color_and_type(c, pt);
1959 s = pop_1st_bit(&b);
1960 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1961 result += piece_value_midgame(pt);
1968 /// Position::is_mate() returns true or false depending on whether the
1969 /// side to move is checkmated. Note that this function is currently very
1970 /// slow, and shouldn't be used frequently inside the search.
1972 bool Position::is_mate() const {
1976 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1977 return mp.get_next_move() == MOVE_NONE;
1983 /// Position::is_draw() tests whether the position is drawn by material,
1984 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1985 /// must be done by the search.
1987 bool Position::is_draw() const {
1989 // Draw by material?
1991 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1994 // Draw by the 50 moves rule?
1995 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1998 // Draw by repetition?
1999 for (int i = 2; i < Min(gamePly, rule50); i += 2)
2000 if (history[gamePly - i] == key)
2007 /// Position::has_mate_threat() tests whether a given color has a mate in one
2008 /// from the current position. This function is quite slow, but it doesn't
2009 /// matter, because it is currently only called from PV nodes, which are rare.
2011 bool Position::has_mate_threat(Color c) {
2014 Color stm = side_to_move();
2016 // The following lines are useless and silly, but prevents gcc from
2017 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
2018 // be used uninitialized.
2019 u1.lastMove = lastMove;
2020 u1.epSquare = epSquare;
2025 // If the input color is not equal to the side to move, do a null move
2029 MoveStack mlist[120];
2031 bool result = false;
2033 // Generate legal moves
2034 count = generate_legal_moves(*this, mlist);
2036 // Loop through the moves, and see if one of them is mate
2037 for (int i = 0; i < count; i++)
2039 do_move(mlist[i].move, u2);
2043 undo_move(mlist[i].move, u2);
2046 // Undo null move, if necessary
2054 /// Position::init_zobrist() is a static member function which initializes the
2055 /// various arrays used to compute hash keys.
2057 void Position::init_zobrist() {
2059 for (int i = 0; i < 2; i++)
2060 for (int j = 0; j < 8; j++)
2061 for (int k = 0; k < 64; k++)
2062 zobrist[i][j][k] = Key(genrand_int64());
2064 for (int i = 0; i < 64; i++)
2065 zobEp[i] = Key(genrand_int64());
2067 for (int i = 0; i < 16; i++)
2068 zobCastle[i] = genrand_int64();
2070 zobSideToMove = genrand_int64();
2072 for (int i = 0; i < 2; i++)
2073 for (int j = 0; j < 8; j++)
2074 for (int k = 0; k < 16; k++)
2075 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2077 for (int i = 0; i < 16; i++)
2078 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2082 /// Position::init_piece_square_tables() initializes the piece square tables.
2083 /// This is a two-step operation: First, the white halves of the tables are
2084 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2085 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2086 /// Second, the black halves of the tables are initialized by mirroring
2087 /// and changing the sign of the corresponding white scores.
2089 void Position::init_piece_square_tables() {
2091 int r = get_option_value_int("Randomness"), i;
2092 for (Square s = SQ_A1; s <= SQ_H8; s++)
2093 for (Piece p = WP; p <= WK; p++)
2095 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2096 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2097 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2100 for (Square s = SQ_A1; s <= SQ_H8; s++)
2101 for (Piece p = BP; p <= BK; p++)
2103 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2104 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2109 /// Position::flipped_copy() makes a copy of the input position, but with
2110 /// the white and black sides reversed. This is only useful for debugging,
2111 /// especially for finding evaluation symmetry bugs.
2113 void Position::flipped_copy(const Position &pos) {
2115 assert(pos.is_ok());
2120 for (Square s = SQ_A1; s <= SQ_H8; s++)
2121 if (!pos.square_is_empty(s))
2122 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2125 sideToMove = opposite_color(pos.side_to_move());
2128 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2129 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2130 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2131 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2133 initialKFile = pos.initialKFile;
2134 initialKRFile = pos.initialKRFile;
2135 initialQRFile = pos.initialQRFile;
2137 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2138 castleRightsMask[sq] = ALL_CASTLES;
2140 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2141 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2142 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2143 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2144 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2145 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2147 // En passant square
2148 if (pos.epSquare != SQ_NONE)
2149 epSquare = flip_square(pos.epSquare);
2155 key = compute_key();
2156 pawnKey = compute_pawn_key();
2157 materialKey = compute_material_key();
2159 // Incremental scores
2160 mgValue = compute_mg_value();
2161 egValue = compute_eg_value();
2164 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2165 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2171 /// Position::is_ok() performs some consitency checks for the position object.
2172 /// This is meant to be helpful when debugging.
2174 bool Position::is_ok(int* failedStep) const {
2176 // What features of the position should be verified?
2177 static const bool debugBitboards = false;
2178 static const bool debugKingCount = false;
2179 static const bool debugKingCapture = false;
2180 static const bool debugCheckerCount = false;
2181 static const bool debugKey = false;
2182 static const bool debugMaterialKey = false;
2183 static const bool debugPawnKey = false;
2184 static const bool debugIncrementalEval = false;
2185 static const bool debugNonPawnMaterial = false;
2186 static const bool debugPieceCounts = false;
2187 static const bool debugPieceList = false;
2189 if (failedStep) *failedStep = 1;
2192 if (!color_is_ok(side_to_move()))
2195 // Are the king squares in the position correct?
2196 if (failedStep) (*failedStep)++;
2197 if (piece_on(king_square(WHITE)) != WK)
2200 if (failedStep) (*failedStep)++;
2201 if (piece_on(king_square(BLACK)) != BK)
2205 if (failedStep) (*failedStep)++;
2206 if (!file_is_ok(initialKRFile))
2209 if (!file_is_ok(initialQRFile))
2212 // Do both sides have exactly one king?
2213 if (failedStep) (*failedStep)++;
2216 int kingCount[2] = {0, 0};
2217 for (Square s = SQ_A1; s <= SQ_H8; s++)
2218 if (type_of_piece_on(s) == KING)
2219 kingCount[color_of_piece_on(s)]++;
2221 if (kingCount[0] != 1 || kingCount[1] != 1)
2225 // Can the side to move capture the opponent's king?
2226 if (failedStep) (*failedStep)++;
2227 if (debugKingCapture)
2229 Color us = side_to_move();
2230 Color them = opposite_color(us);
2231 Square ksq = king_square(them);
2232 if (square_is_attacked(ksq, us))
2236 // Is there more than 2 checkers?
2237 if (failedStep) (*failedStep)++;
2238 if (debugCheckerCount && count_1s(checkersBB) > 2)
2242 if (failedStep) (*failedStep)++;
2245 // The intersection of the white and black pieces must be empty
2246 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2249 // The union of the white and black pieces must be equal to all
2251 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2254 // Separate piece type bitboards must have empty intersections
2255 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2256 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2257 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2261 // En passant square OK?
2262 if (failedStep) (*failedStep)++;
2263 if (ep_square() != SQ_NONE)
2265 // The en passant square must be on rank 6, from the point of view of the
2267 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2272 if (failedStep) (*failedStep)++;
2273 if (debugKey && key != compute_key())
2276 // Pawn hash key OK?
2277 if (failedStep) (*failedStep)++;
2278 if (debugPawnKey && pawnKey != compute_pawn_key())
2281 // Material hash key OK?
2282 if (failedStep) (*failedStep)++;
2283 if (debugMaterialKey && materialKey != compute_material_key())
2286 // Incremental eval OK?
2287 if (failedStep) (*failedStep)++;
2288 if (debugIncrementalEval)
2290 if (mgValue != compute_mg_value())
2293 if (egValue != compute_eg_value())
2297 // Non-pawn material OK?
2298 if (failedStep) (*failedStep)++;
2299 if (debugNonPawnMaterial)
2301 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2304 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2309 if (failedStep) (*failedStep)++;
2310 if (debugPieceCounts)
2311 for (Color c = WHITE; c <= BLACK; c++)
2312 for (PieceType pt = PAWN; pt <= KING; pt++)
2313 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2316 if (failedStep) (*failedStep)++;
2319 for(Color c = WHITE; c <= BLACK; c++)
2320 for(PieceType pt = PAWN; pt <= KING; pt++)
2321 for(int i = 0; i < pieceCount[c][pt]; i++)
2323 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2326 if (index[piece_list(c, pt, i)] != i)
2330 if (failedStep) *failedStep = 0;