2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
35 #include "ucioption.h"
42 extern SearchStack EmptySearchStack;
44 int Position::castleRightsMask[64];
46 Key Position::zobrist[2][8][64];
47 Key Position::zobEp[64];
48 Key Position::zobCastle[16];
49 Key Position::zobMaterial[2][8][16];
50 Key Position::zobSideToMove;
52 Value Position::MgPieceSquareTable[16][64];
53 Value Position::EgPieceSquareTable[16][64];
55 static bool RequestPending = false;
63 Position::Position(const Position& pos) {
67 Position::Position(const std::string& fen) {
72 /// Position::from_fen() initializes the position object with the given FEN
73 /// string. This function is not very robust - make sure that input FENs are
74 /// correct (this is assumed to be the responsibility of the GUI).
76 void Position::from_fen(const std::string& fen) {
78 static const std::string pieceLetters = "KQRBNPkqrbnp";
79 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
87 for ( ; fen[i] != ' '; i++)
91 // Skip the given number of files
92 file += (fen[i] - '1' + 1);
95 else if (fen[i] == '/')
101 size_t idx = pieceLetters.find(fen[i]);
102 if (idx == std::string::npos)
104 std::cout << "Error in FEN at character " << i << std::endl;
107 Square square = make_square(file, rank);
108 put_piece(pieces[idx], square);
114 if (fen[i] != 'w' && fen[i] != 'b')
116 std::cout << "Error in FEN at character " << i << std::endl;
119 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
125 std::cout << "Error in FEN at character " << i << std::endl;
130 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
136 else if(fen[i] == 'K') allow_oo(WHITE);
137 else if(fen[i] == 'Q') allow_ooo(WHITE);
138 else if(fen[i] == 'k') allow_oo(BLACK);
139 else if(fen[i] == 'q') allow_ooo(BLACK);
140 else if(fen[i] >= 'A' && fen[i] <= 'H') {
141 File rookFile, kingFile = FILE_NONE;
142 for(Square square = SQ_B1; square <= SQ_G1; square++)
143 if(piece_on(square) == WK)
144 kingFile = square_file(square);
145 if(kingFile == FILE_NONE) {
146 std::cout << "Error in FEN at character " << i << std::endl;
149 initialKFile = kingFile;
150 rookFile = File(fen[i] - 'A') + FILE_A;
151 if(rookFile < initialKFile) {
153 initialQRFile = rookFile;
157 initialKRFile = rookFile;
160 else if(fen[i] >= 'a' && fen[i] <= 'h') {
161 File rookFile, kingFile = FILE_NONE;
162 for(Square square = SQ_B8; square <= SQ_G8; square++)
163 if(piece_on(square) == BK)
164 kingFile = square_file(square);
165 if(kingFile == FILE_NONE) {
166 std::cout << "Error in FEN at character " << i << std::endl;
169 initialKFile = kingFile;
170 rookFile = File(fen[i] - 'a') + FILE_A;
171 if(rookFile < initialKFile) {
173 initialQRFile = rookFile;
177 initialKRFile = rookFile;
181 std::cout << "Error in FEN at character " << i << std::endl;
188 while (fen[i] == ' ')
192 if ( i < fen.length() - 2
193 && (fen[i] >= 'a' && fen[i] <= 'h')
194 && (fen[i+1] == '3' || fen[i+1] == '6'))
195 epSquare = square_from_string(fen.substr(i, 2));
197 // Various initialisation
198 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
199 castleRightsMask[sq] = ALL_CASTLES;
201 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
202 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
203 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
204 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
205 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
206 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
211 pawnKey = compute_pawn_key();
212 materialKey = compute_material_key();
213 mgValue = compute_mg_value();
214 egValue = compute_eg_value();
215 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
216 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
220 /// Position::to_fen() converts the position object to a FEN string. This is
221 /// probably only useful for debugging.
223 const std::string Position::to_fen() const {
225 static const std::string pieceLetters = " PNBRQK pnbrqk";
229 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
232 for (File file = FILE_A; file <= FILE_H; file++)
234 Square sq = make_square(file, rank);
235 if (!square_is_occupied(sq))
241 fen += (char)skip + '0';
244 fen += pieceLetters[piece_on(sq)];
247 fen += (char)skip + '0';
249 fen += (rank > RANK_1 ? '/' : ' ');
251 fen += (sideToMove == WHITE ? "w " : "b ");
252 if (castleRights != NO_CASTLES)
254 if (can_castle_kingside(WHITE)) fen += 'K';
255 if (can_castle_queenside(WHITE)) fen += 'Q';
256 if (can_castle_kingside(BLACK)) fen += 'k';
257 if (can_castle_queenside(BLACK)) fen += 'q';
262 if (ep_square() != SQ_NONE)
263 fen += square_to_string(ep_square());
271 /// Position::print() prints an ASCII representation of the position to
272 /// the standard output. If a move is given then also the san is print.
274 void Position::print(Move m) const {
276 static const std::string pieceLetters = " PNBRQK PNBRQK .";
278 // Check for reentrancy, as example when called from inside
279 // MovePicker that is used also here in move_to_san()
283 RequestPending = true;
285 std::cout << std::endl;
288 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
289 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
291 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
293 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
294 for (File file = FILE_A; file <= FILE_H; file++)
296 Square sq = make_square(file, rank);
297 Piece piece = piece_on(sq);
298 if (piece == EMPTY && square_color(sq) == WHITE)
301 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
302 std::cout << '|' << col << pieceLetters[piece] << col;
304 std::cout << '|' << std::endl;
306 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
307 << "Fen is: " << to_fen() << std::endl
308 << "Key is: " << key << std::endl;
310 RequestPending = false;
314 /// Position::copy() creates a copy of the input position.
316 void Position::copy(const Position &pos) {
318 memcpy(this, &pos, sizeof(Position));
322 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
323 /// king) pieces for the given color.
324 Bitboard Position::pinned_pieces(Color c) const {
326 Square ksq = king_square(c);
327 return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
331 /// Position:discovered_check_candidates() returns a bitboard containing all
332 /// pieces for the given side which are candidates for giving a discovered
333 /// check. The code is almost the same as the function for finding pinned
336 Bitboard Position::discovered_check_candidates(Color c) const {
338 Square ksq = king_square(opposite_color(c));
339 return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
343 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
344 /// king) pieces for the given color and for the given pinner type. Or, when
345 /// template parameter FindPinned is false, the pinned pieces of opposite color
346 /// that are, indeed, the pieces candidate for a discovery check.
347 template<PieceType Piece, bool FindPinned>
348 Bitboard Position::hidden_checks(Color c, Square ksq) const {
351 Bitboard sliders, result = EmptyBoardBB;
353 if (Piece == ROOK) // Resolved at compile time
354 sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
356 sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
358 if (sliders && (!FindPinned || (sliders & ~checkersBB)))
360 // King blockers are candidate pinned pieces
361 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
363 // Pinners are sliders, not checkers, that give check when
364 // candidate pinned are removed.
365 Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
368 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
370 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
372 // Finally for each pinner find the corresponding pinned piece (if same color of king)
373 // or discovery checker (if opposite color) among the candidates.
376 s = pop_1st_bit(&pinners);
377 result |= (squares_between(s, ksq) & candidate_pinned);
384 /// Position::attacks_to() computes a bitboard containing all pieces which
385 /// attacks a given square. There are two versions of this function: One
386 /// which finds attackers of both colors, and one which only finds the
387 /// attackers for one side.
389 Bitboard Position::attacks_to(Square s) const {
391 return (pawn_attacks(BLACK, s) & pawns(WHITE))
392 | (pawn_attacks(WHITE, s) & pawns(BLACK))
393 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
394 | (piece_attacks<ROOK>(s) & rooks_and_queens())
395 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
396 | (piece_attacks<KING>(s) & pieces_of_type(KING));
399 /// Position::piece_attacks_square() tests whether the piece on square f
400 /// attacks square t.
402 bool Position::piece_attacks_square(Square f, Square t) const {
404 assert(square_is_ok(f));
405 assert(square_is_ok(t));
409 case WP: return pawn_attacks_square(WHITE, f, t);
410 case BP: return pawn_attacks_square(BLACK, f, t);
411 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
412 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
413 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
414 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
415 case WK: case BK: return piece_attacks_square<KING>(f, t);
422 /// Position::move_attacks_square() tests whether a move from the current
423 /// position attacks a given square.
425 bool Position::move_attacks_square(Move m, Square s) const {
427 assert(move_is_ok(m));
428 assert(square_is_ok(s));
431 Square f = move_from(m), t = move_to(m);
433 assert(square_is_occupied(f));
437 case WP: is_attack = pawn_attacks_square(WHITE, t, s); break;
438 case BP: is_attack = pawn_attacks_square(BLACK, t, s); break;
439 case WN: case BN: is_attack = piece_attacks_square<KNIGHT>(t, s); break;
440 case WB: case BB: is_attack = piece_attacks_square<BISHOP>(t, s); break;
441 case WR: case BR: is_attack = piece_attacks_square<ROOK>(t, s); break;
442 case WQ: case BQ: is_attack = piece_attacks_square<QUEEN>(t, s); break;
443 case WK: case BK: is_attack = piece_attacks_square<KING>(t, s); break;
450 // Move the piece and scan for X-ray attacks behind it
451 Bitboard occ = occupied_squares();
452 Color us = color_of_piece_on(f);
455 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
456 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
458 // If we have attacks we need to verify that are caused by our move
459 // and are not already existent ones.
460 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
464 /// Position::find_checkers() computes the checkersBB bitboard, which
465 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
466 /// currently works by calling Position::attacks_to, which is probably
467 /// inefficient. Consider rewriting this function to use the last move
468 /// played, like in non-bitboard versions of Glaurung.
470 void Position::find_checkers() {
472 Color us = side_to_move();
473 checkersBB = attacks_to(king_square(us), opposite_color(us));
477 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal.
478 /// There are two versions of this function: One which takes only a
479 /// move as input, and one which takes a move and a bitboard of pinned
480 /// pieces. The latter function is faster, and should always be preferred
481 /// when a pinned piece bitboard has already been computed.
483 bool Position::pl_move_is_legal(Move m) const {
485 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
488 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
491 assert(move_is_ok(m));
492 assert(pinned == pinned_pieces(side_to_move()));
494 // If we're in check, all pseudo-legal moves are legal, because our
495 // check evasion generator only generates true legal moves.
499 // Castling moves are checked for legality during move generation.
500 if (move_is_castle(m))
503 Color us = side_to_move();
504 Color them = opposite_color(us);
505 Square from = move_from(m);
506 Square ksq = king_square(us);
508 assert(color_of_piece_on(from) == us);
509 assert(piece_on(ksq) == king_of_color(us));
511 // En passant captures are a tricky special case. Because they are
512 // rather uncommon, we do it simply by testing whether the king is attacked
513 // after the move is made
516 Square to = move_to(m);
517 Square capsq = make_square(square_file(to), square_rank(from));
518 Bitboard b = occupied_squares();
520 assert(to == ep_square());
521 assert(piece_on(from) == pawn_of_color(us));
522 assert(piece_on(capsq) == pawn_of_color(them));
523 assert(piece_on(to) == EMPTY);
526 clear_bit(&b, capsq);
529 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
530 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
533 // If the moving piece is a king, check whether the destination
534 // square is attacked by the opponent.
536 return !(square_is_attacked(move_to(m), them));
538 // A non-king move is legal if and only if it is not pinned or it
539 // is moving along the ray towards or away from the king.
540 return ( !bit_is_set(pinned, from)
541 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
545 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
546 /// There are two versions of this function: One which takes only a move as
547 /// input, and one which takes a move and a bitboard of discovered check
548 /// candidates. The latter function is faster, and should always be preferred
549 /// when a discovered check candidates bitboard has already been computed.
551 bool Position::move_is_check(Move m) const {
553 Bitboard dc = discovered_check_candidates(side_to_move());
554 return move_is_check(m, dc);
557 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
560 assert(move_is_ok(m));
561 assert(dcCandidates == discovered_check_candidates(side_to_move()));
563 Color us = side_to_move();
564 Color them = opposite_color(us);
565 Square from = move_from(m);
566 Square to = move_to(m);
567 Square ksq = king_square(them);
569 assert(color_of_piece_on(from) == us);
570 assert(piece_on(ksq) == king_of_color(them));
572 // Proceed according to the type of the moving piece
573 switch (type_of_piece_on(from))
577 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
580 if ( bit_is_set(dcCandidates, from) // Discovered check?
581 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
584 if (move_promotion(m)) // Promotion with check?
586 Bitboard b = occupied_squares();
589 switch (move_promotion(m))
592 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
594 return bit_is_set(bishop_attacks_bb(to, b), ksq);
596 return bit_is_set(rook_attacks_bb(to, b), ksq);
598 return bit_is_set(queen_attacks_bb(to, b), ksq);
603 // En passant capture with check? We have already handled the case
604 // of direct checks and ordinary discovered check, the only case we
605 // need to handle is the unusual case of a discovered check through the
607 else if (move_is_ep(m))
609 Square capsq = make_square(square_file(to), square_rank(from));
610 Bitboard b = occupied_squares();
612 clear_bit(&b, capsq);
614 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
615 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
620 return bit_is_set(dcCandidates, from) // Discovered check?
621 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
624 return bit_is_set(dcCandidates, from) // Discovered check?
625 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
628 return bit_is_set(dcCandidates, from) // Discovered check?
629 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
632 // Discovered checks are impossible!
633 assert(!bit_is_set(dcCandidates, from));
634 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
638 if ( bit_is_set(dcCandidates, from)
639 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
642 // Castling with check?
643 if (move_is_castle(m))
645 Square kfrom, kto, rfrom, rto;
646 Bitboard b = occupied_squares();
652 kto = relative_square(us, SQ_G1);
653 rto = relative_square(us, SQ_F1);
655 kto = relative_square(us, SQ_C1);
656 rto = relative_square(us, SQ_D1);
658 clear_bit(&b, kfrom);
659 clear_bit(&b, rfrom);
662 return bit_is_set(rook_attacks_bb(rto, b), ksq);
666 default: // NO_PIECE_TYPE
674 /// Position::move_is_capture() tests whether a move from the current
675 /// position is a capture. Move must not be MOVE_NONE.
677 bool Position::move_is_capture(Move m) const {
679 assert(m != MOVE_NONE);
681 return ( !square_is_empty(move_to(m))
682 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
688 /// Position::backup() is called when making a move. All information
689 /// necessary to restore the position when the move is later unmade
690 /// is saved to an UndoInfo object. The function Position::restore
691 /// does the reverse operation: When one does a backup followed by
692 /// a restore with the same UndoInfo object, the position is restored
693 /// to the state before backup was called.
695 void Position::backup(UndoInfo& u) const {
697 u.castleRights = castleRights;
698 u.epSquare = epSquare;
699 u.checkersBB = checkersBB;
702 u.materialKey = materialKey;
704 u.lastMove = lastMove;
707 u.capture = NO_PIECE_TYPE;
711 /// Position::restore() is called when unmaking a move. It copies back
712 /// the information backed up during a previous call to Position::backup.
714 void Position::restore(const UndoInfo& u) {
716 castleRights = u.castleRights;
717 epSquare = u.epSquare;
718 checkersBB = u.checkersBB;
721 materialKey = u.materialKey;
723 lastMove = u.lastMove;
726 // u.capture is restored in undo_move()
730 /// Position::update_checkers() is a private method to udpate chekers info
732 template<PieceType Piece>
733 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
734 Square to, Bitboard dcCandidates) {
736 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
737 set_bit(pCheckersBB, to);
739 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
742 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
745 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
750 /// Position::do_move() makes a move, and backs up all information necessary
751 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
752 /// Pseudo-legal moves should be filtered out before this function is called.
753 /// There are two versions of this function, one which takes only the move and
754 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
755 /// discovered check candidates. The second version is faster, because knowing
756 /// the discovered check candidates makes it easier to update the checkersBB
757 /// member variable in the position object.
759 void Position::do_move(Move m, UndoInfo& u) {
761 do_move(m, u, discovered_check_candidates(side_to_move()));
764 void Position::do_move(Move m, UndoInfo& u, Bitboard dcCandidates) {
767 assert(move_is_ok(m));
769 // Back up the necessary information to our UndoInfo object (except the
770 // captured piece, which is taken care of later.
773 // Save the current key to the history[] array, in order to be able to
774 // detect repetition draws.
775 history[gamePly] = key;
777 // Increment the 50 moves rule draw counter. Resetting it to zero in the
778 // case of non-reversible moves is taken care of later.
781 if (move_is_castle(m))
783 else if (move_promotion(m))
784 do_promotion_move(m, u);
785 else if (move_is_ep(m))
789 Color us = side_to_move();
790 Color them = opposite_color(us);
791 Square from = move_from(m);
792 Square to = move_to(m);
794 assert(color_of_piece_on(from) == us);
795 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
797 PieceType piece = type_of_piece_on(from);
798 PieceType capture = type_of_piece_on(to);
803 do_capture_move(m, capture, them, to);
807 clear_bit(&(byColorBB[us]), from);
808 clear_bit(&(byTypeBB[piece]), from);
809 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
810 set_bit(&(byColorBB[us]), to);
811 set_bit(&(byTypeBB[piece]), to);
812 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
813 board[to] = board[from];
817 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
819 // Update incremental scores
820 mgValue -= mg_pst(us, piece, from);
821 mgValue += mg_pst(us, piece, to);
822 egValue -= eg_pst(us, piece, from);
823 egValue += eg_pst(us, piece, to);
825 // If the moving piece was a king, update the king square
829 // Reset en passant square
830 if (epSquare != SQ_NONE)
832 key ^= zobEp[epSquare];
836 // If the moving piece was a pawn do some special extra work
839 // Reset rule 50 draw counter
842 // Update pawn hash key
843 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
845 // Set en passant square, only if moved pawn can be captured
846 if (abs(int(to) - int(from)) == 16)
848 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
849 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
851 epSquare = Square((int(from) + int(to)) / 2);
852 key ^= zobEp[epSquare];
857 // Update piece lists
858 pieceList[us][piece][index[from]] = to;
859 index[to] = index[from];
861 // Update castle rights
862 key ^= zobCastle[castleRights];
863 castleRights &= castleRightsMask[from];
864 castleRights &= castleRightsMask[to];
865 key ^= zobCastle[castleRights];
867 // Update checkers bitboard, piece must be already moved
868 checkersBB = EmptyBoardBB;
869 Square ksq = king_square(them);
872 case PAWN: update_checkers<PAWN>(&checkersBB, ksq, from, to, dcCandidates); break;
873 case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, dcCandidates); break;
874 case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, dcCandidates); break;
875 case ROOK: update_checkers<ROOK>(&checkersBB, ksq, from, to, dcCandidates); break;
876 case QUEEN: update_checkers<QUEEN>(&checkersBB, ksq, from, to, dcCandidates); break;
877 case KING: update_checkers<KING>(&checkersBB, ksq, from, to, dcCandidates); break;
878 default: assert(false); break;
883 key ^= zobSideToMove;
884 sideToMove = opposite_color(sideToMove);
887 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
888 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
894 /// Position::do_capture_move() is a private method used to update captured
895 /// piece info. It is called from the main Position::do_move function.
897 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
899 assert(capture != KING);
901 // Remove captured piece
902 clear_bit(&(byColorBB[them]), to);
903 clear_bit(&(byTypeBB[capture]), to);
906 key ^= zobrist[them][capture][to];
908 // If the captured piece was a pawn, update pawn hash key
910 pawnKey ^= zobrist[them][PAWN][to];
912 // Update incremental scores
913 mgValue -= mg_pst(them, capture, to);
914 egValue -= eg_pst(them, capture, to);
916 assert(!move_promotion(m) || capture != PAWN);
920 npMaterial[them] -= piece_value_midgame(capture);
922 // Update material hash key
923 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
925 // Update piece count
926 pieceCount[them][capture]--;
929 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
930 index[pieceList[them][capture][index[to]]] = index[to];
932 // Reset rule 50 counter
937 /// Position::do_castle_move() is a private method used to make a castling
938 /// move. It is called from the main Position::do_move function. Note that
939 /// castling moves are encoded as "king captures friendly rook" moves, for
940 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
942 void Position::do_castle_move(Move m) {
945 assert(move_is_ok(m));
946 assert(move_is_castle(m));
948 Color us = side_to_move();
949 Color them = opposite_color(us);
951 // Find source squares for king and rook
952 Square kfrom = move_from(m);
953 Square rfrom = move_to(m); // HACK: See comment at beginning of function
956 assert(piece_on(kfrom) == king_of_color(us));
957 assert(piece_on(rfrom) == rook_of_color(us));
959 // Find destination squares for king and rook
960 if (rfrom > kfrom) // O-O
962 kto = relative_square(us, SQ_G1);
963 rto = relative_square(us, SQ_F1);
965 kto = relative_square(us, SQ_C1);
966 rto = relative_square(us, SQ_D1);
969 // Remove pieces from source squares
970 clear_bit(&(byColorBB[us]), kfrom);
971 clear_bit(&(byTypeBB[KING]), kfrom);
972 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
973 clear_bit(&(byColorBB[us]), rfrom);
974 clear_bit(&(byTypeBB[ROOK]), rfrom);
975 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
977 // Put pieces on destination squares
978 set_bit(&(byColorBB[us]), kto);
979 set_bit(&(byTypeBB[KING]), kto);
980 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
981 set_bit(&(byColorBB[us]), rto);
982 set_bit(&(byTypeBB[ROOK]), rto);
983 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
985 // Update board array
986 board[kfrom] = board[rfrom] = EMPTY;
987 board[kto] = piece_of_color_and_type(us, KING);
988 board[rto] = piece_of_color_and_type(us, ROOK);
990 // Update king square
991 kingSquare[us] = kto;
993 // Update piece lists
994 pieceList[us][KING][index[kfrom]] = kto;
995 pieceList[us][ROOK][index[rfrom]] = rto;
996 int tmp = index[rfrom];
997 index[kto] = index[kfrom];
1000 // Update incremental scores
1001 mgValue -= mg_pst(us, KING, kfrom);
1002 mgValue += mg_pst(us, KING, kto);
1003 egValue -= eg_pst(us, KING, kfrom);
1004 egValue += eg_pst(us, KING, kto);
1005 mgValue -= mg_pst(us, ROOK, rfrom);
1006 mgValue += mg_pst(us, ROOK, rto);
1007 egValue -= eg_pst(us, ROOK, rfrom);
1008 egValue += eg_pst(us, ROOK, rto);
1011 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1012 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1014 // Clear en passant square
1015 if (epSquare != SQ_NONE)
1017 key ^= zobEp[epSquare];
1021 // Update castling rights
1022 key ^= zobCastle[castleRights];
1023 castleRights &= castleRightsMask[kfrom];
1024 key ^= zobCastle[castleRights];
1026 // Reset rule 50 counter
1029 // Update checkers BB
1030 checkersBB = attacks_to(king_square(them), us);
1034 /// Position::do_promotion_move() is a private method used to make a promotion
1035 /// move. It is called from the main Position::do_move function. The
1036 /// UndoInfo object, which has been initialized in Position::do_move, is
1037 /// used to store the captured piece (if any).
1039 void Position::do_promotion_move(Move m, UndoInfo &u) {
1043 PieceType capture, promotion;
1046 assert(move_is_ok(m));
1047 assert(move_promotion(m));
1049 us = side_to_move();
1050 them = opposite_color(us);
1051 from = move_from(m);
1054 assert(relative_rank(us, to) == RANK_8);
1055 assert(piece_on(from) == pawn_of_color(us));
1056 assert(color_of_piece_on(to) == them || square_is_empty(to));
1058 capture = type_of_piece_on(to);
1062 u.capture = capture;
1063 do_capture_move(m, capture, them, to);
1067 clear_bit(&(byColorBB[us]), from);
1068 clear_bit(&(byTypeBB[PAWN]), from);
1069 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1070 board[from] = EMPTY;
1072 // Insert promoted piece
1073 promotion = move_promotion(m);
1074 assert(promotion >= KNIGHT && promotion <= QUEEN);
1075 set_bit(&(byColorBB[us]), to);
1076 set_bit(&(byTypeBB[promotion]), to);
1077 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1078 board[to] = piece_of_color_and_type(us, promotion);
1081 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1083 // Update pawn hash key
1084 pawnKey ^= zobrist[us][PAWN][from];
1086 // Update material key
1087 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1088 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1090 // Update piece counts
1091 pieceCount[us][PAWN]--;
1092 pieceCount[us][promotion]++;
1094 // Update piece lists
1095 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1096 index[pieceList[us][PAWN][index[from]]] = index[from];
1097 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1098 index[to] = pieceCount[us][promotion] - 1;
1100 // Update incremental scores
1101 mgValue -= mg_pst(us, PAWN, from);
1102 mgValue += mg_pst(us, promotion, to);
1103 egValue -= eg_pst(us, PAWN, from);
1104 egValue += eg_pst(us, promotion, to);
1107 npMaterial[us] += piece_value_midgame(promotion);
1109 // Clear the en passant square
1110 if (epSquare != SQ_NONE)
1112 key ^= zobEp[epSquare];
1116 // Update castle rights
1117 key ^= zobCastle[castleRights];
1118 castleRights &= castleRightsMask[to];
1119 key ^= zobCastle[castleRights];
1121 // Reset rule 50 counter
1124 // Update checkers BB
1125 checkersBB = attacks_to(king_square(them), us);
1129 /// Position::do_ep_move() is a private method used to make an en passant
1130 /// capture. It is called from the main Position::do_move function. Because
1131 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1132 /// object in which to store the captured piece.
1134 void Position::do_ep_move(Move m) {
1137 Square from, to, capsq;
1140 assert(move_is_ok(m));
1141 assert(move_is_ep(m));
1143 us = side_to_move();
1144 them = opposite_color(us);
1145 from = move_from(m);
1147 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1149 assert(to == epSquare);
1150 assert(relative_rank(us, to) == RANK_6);
1151 assert(piece_on(to) == EMPTY);
1152 assert(piece_on(from) == pawn_of_color(us));
1153 assert(piece_on(capsq) == pawn_of_color(them));
1155 // Remove captured piece
1156 clear_bit(&(byColorBB[them]), capsq);
1157 clear_bit(&(byTypeBB[PAWN]), capsq);
1158 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1159 board[capsq] = EMPTY;
1161 // Remove moving piece from source square
1162 clear_bit(&(byColorBB[us]), from);
1163 clear_bit(&(byTypeBB[PAWN]), from);
1164 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1166 // Put moving piece on destination square
1167 set_bit(&(byColorBB[us]), to);
1168 set_bit(&(byTypeBB[PAWN]), to);
1169 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1170 board[to] = board[from];
1171 board[from] = EMPTY;
1173 // Update material hash key
1174 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1176 // Update piece count
1177 pieceCount[them][PAWN]--;
1179 // Update piece list
1180 pieceList[us][PAWN][index[from]] = to;
1181 index[to] = index[from];
1182 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1183 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1186 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1187 key ^= zobrist[them][PAWN][capsq];
1188 key ^= zobEp[epSquare];
1190 // Update pawn hash key
1191 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1192 pawnKey ^= zobrist[them][PAWN][capsq];
1194 // Update incremental scores
1195 mgValue -= mg_pst(them, PAWN, capsq);
1196 mgValue -= mg_pst(us, PAWN, from);
1197 mgValue += mg_pst(us, PAWN, to);
1198 egValue -= eg_pst(them, PAWN, capsq);
1199 egValue -= eg_pst(us, PAWN, from);
1200 egValue += eg_pst(us, PAWN, to);
1202 // Reset en passant square
1205 // Reset rule 50 counter
1208 // Update checkers BB
1209 checkersBB = attacks_to(king_square(them), us);
1213 /// Position::undo_move() unmakes a move. When it returns, the position should
1214 /// be restored to exactly the same state as before the move was made. It is
1215 /// important that Position::undo_move is called with the same move and UndoInfo
1216 /// object as the earlier call to Position::do_move.
1218 void Position::undo_move(Move m, const UndoInfo &u) {
1221 assert(move_is_ok(m));
1224 sideToMove = opposite_color(sideToMove);
1226 // Restore information from our UndoInfo object (except the captured piece,
1227 // which is taken care of later)
1230 if (move_is_castle(m))
1231 undo_castle_move(m);
1232 else if (move_promotion(m))
1233 undo_promotion_move(m, u);
1234 else if (move_is_ep(m))
1240 PieceType piece, capture;
1242 us = side_to_move();
1243 them = opposite_color(us);
1244 from = move_from(m);
1247 assert(piece_on(from) == EMPTY);
1248 assert(color_of_piece_on(to) == us);
1250 // Put the piece back at the source square
1251 piece = type_of_piece_on(to);
1252 set_bit(&(byColorBB[us]), from);
1253 set_bit(&(byTypeBB[piece]), from);
1254 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1255 board[from] = piece_of_color_and_type(us, piece);
1257 // Clear the destination square
1258 clear_bit(&(byColorBB[us]), to);
1259 clear_bit(&(byTypeBB[piece]), to);
1260 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1262 // If the moving piece was a king, update the king square
1264 kingSquare[us] = from;
1266 // Update piece list
1267 pieceList[us][piece][index[to]] = from;
1268 index[from] = index[to];
1270 capture = u.capture;
1274 assert(capture != KING);
1276 // Replace the captured piece
1277 set_bit(&(byColorBB[them]), to);
1278 set_bit(&(byTypeBB[capture]), to);
1279 set_bit(&(byTypeBB[0]), to);
1280 board[to] = piece_of_color_and_type(them, capture);
1283 if (capture != PAWN)
1284 npMaterial[them] += piece_value_midgame(capture);
1286 // Update piece list
1287 pieceList[them][capture][pieceCount[them][capture]] = to;
1288 index[to] = pieceCount[them][capture];
1290 // Update piece count
1291 pieceCount[them][capture]++;
1300 /// Position::undo_castle_move() is a private method used to unmake a castling
1301 /// move. It is called from the main Position::undo_move function. Note that
1302 /// castling moves are encoded as "king captures friendly rook" moves, for
1303 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1305 void Position::undo_castle_move(Move m) {
1307 assert(move_is_ok(m));
1308 assert(move_is_castle(m));
1310 // When we have arrived here, some work has already been done by
1311 // Position::undo_move. In particular, the side to move has been switched,
1312 // so the code below is correct.
1313 Color us = side_to_move();
1315 // Find source squares for king and rook
1316 Square kfrom = move_from(m);
1317 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1320 // Find destination squares for king and rook
1321 if (rfrom > kfrom) // O-O
1323 kto = relative_square(us, SQ_G1);
1324 rto = relative_square(us, SQ_F1);
1326 kto = relative_square(us, SQ_C1);
1327 rto = relative_square(us, SQ_D1);
1330 assert(piece_on(kto) == king_of_color(us));
1331 assert(piece_on(rto) == rook_of_color(us));
1333 // Remove pieces from destination squares
1334 clear_bit(&(byColorBB[us]), kto);
1335 clear_bit(&(byTypeBB[KING]), kto);
1336 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1337 clear_bit(&(byColorBB[us]), rto);
1338 clear_bit(&(byTypeBB[ROOK]), rto);
1339 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1341 // Put pieces on source squares
1342 set_bit(&(byColorBB[us]), kfrom);
1343 set_bit(&(byTypeBB[KING]), kfrom);
1344 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1345 set_bit(&(byColorBB[us]), rfrom);
1346 set_bit(&(byTypeBB[ROOK]), rfrom);
1347 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1350 board[rto] = board[kto] = EMPTY;
1351 board[rfrom] = piece_of_color_and_type(us, ROOK);
1352 board[kfrom] = piece_of_color_and_type(us, KING);
1354 // Update king square
1355 kingSquare[us] = kfrom;
1357 // Update piece lists
1358 pieceList[us][KING][index[kto]] = kfrom;
1359 pieceList[us][ROOK][index[rto]] = rfrom;
1360 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1361 index[kfrom] = index[kto];
1366 /// Position::undo_promotion_move() is a private method used to unmake a
1367 /// promotion move. It is called from the main Position::do_move
1368 /// function. The UndoInfo object, which has been initialized in
1369 /// Position::do_move, is used to put back the captured piece (if any).
1371 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1375 PieceType capture, promotion;
1377 assert(move_is_ok(m));
1378 assert(move_promotion(m));
1380 // When we have arrived here, some work has already been done by
1381 // Position::undo_move. In particular, the side to move has been switched,
1382 // so the code below is correct.
1383 us = side_to_move();
1384 them = opposite_color(us);
1385 from = move_from(m);
1388 assert(relative_rank(us, to) == RANK_8);
1389 assert(piece_on(from) == EMPTY);
1391 // Remove promoted piece
1392 promotion = move_promotion(m);
1393 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1394 assert(promotion >= KNIGHT && promotion <= QUEEN);
1395 clear_bit(&(byColorBB[us]), to);
1396 clear_bit(&(byTypeBB[promotion]), to);
1397 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1399 // Insert pawn at source square
1400 set_bit(&(byColorBB[us]), from);
1401 set_bit(&(byTypeBB[PAWN]), from);
1402 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1403 board[from] = piece_of_color_and_type(us, PAWN);
1406 npMaterial[us] -= piece_value_midgame(promotion);
1408 // Update piece list
1409 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1410 index[from] = pieceCount[us][PAWN];
1411 pieceList[us][promotion][index[to]] =
1412 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1413 index[pieceList[us][promotion][index[to]]] = index[to];
1415 // Update piece counts
1416 pieceCount[us][promotion]--;
1417 pieceCount[us][PAWN]++;
1419 capture = u.capture;
1423 assert(capture != KING);
1425 // Insert captured piece:
1426 set_bit(&(byColorBB[them]), to);
1427 set_bit(&(byTypeBB[capture]), to);
1428 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1429 board[to] = piece_of_color_and_type(them, capture);
1431 // Update material. Because the move is a promotion move, we know
1432 // that the captured piece cannot be a pawn.
1433 assert(capture != PAWN);
1434 npMaterial[them] += piece_value_midgame(capture);
1436 // Update piece list
1437 pieceList[them][capture][pieceCount[them][capture]] = to;
1438 index[to] = pieceCount[them][capture];
1440 // Update piece count
1441 pieceCount[them][capture]++;
1447 /// Position::undo_ep_move() is a private method used to unmake an en passant
1448 /// capture. It is called from the main Position::undo_move function. Because
1449 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1450 /// object from which to retrieve the captured piece.
1452 void Position::undo_ep_move(Move m) {
1454 assert(move_is_ok(m));
1455 assert(move_is_ep(m));
1457 // When we have arrived here, some work has already been done by
1458 // Position::undo_move. In particular, the side to move has been switched,
1459 // so the code below is correct.
1460 Color us = side_to_move();
1461 Color them = opposite_color(us);
1462 Square from = move_from(m);
1463 Square to = move_to(m);
1464 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1466 assert(to == ep_square());
1467 assert(relative_rank(us, to) == RANK_6);
1468 assert(piece_on(to) == pawn_of_color(us));
1469 assert(piece_on(from) == EMPTY);
1470 assert(piece_on(capsq) == EMPTY);
1472 // Replace captured piece
1473 set_bit(&(byColorBB[them]), capsq);
1474 set_bit(&(byTypeBB[PAWN]), capsq);
1475 set_bit(&(byTypeBB[0]), capsq);
1476 board[capsq] = piece_of_color_and_type(them, PAWN);
1478 // Remove moving piece from destination square
1479 clear_bit(&(byColorBB[us]), to);
1480 clear_bit(&(byTypeBB[PAWN]), to);
1481 clear_bit(&(byTypeBB[0]), to);
1484 // Replace moving piece at source square
1485 set_bit(&(byColorBB[us]), from);
1486 set_bit(&(byTypeBB[PAWN]), from);
1487 set_bit(&(byTypeBB[0]), from);
1488 board[from] = piece_of_color_and_type(us, PAWN);
1490 // Update piece list:
1491 pieceList[us][PAWN][index[to]] = from;
1492 index[from] = index[to];
1493 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1494 index[capsq] = pieceCount[them][PAWN];
1496 // Update piece count:
1497 pieceCount[them][PAWN]++;
1501 /// Position::do_null_move makes() a "null move": It switches the side to move
1502 /// and updates the hash key without executing any move on the board.
1504 void Position::do_null_move(UndoInfo& u) {
1507 assert(!is_check());
1509 // Back up the information necessary to undo the null move to the supplied
1510 // UndoInfo object. In the case of a null move, the only thing we need to
1511 // remember is the last move made and the en passant square.
1512 u.lastMove = lastMove;
1513 u.epSquare = epSquare;
1515 // Save the current key to the history[] array, in order to be able to
1516 // detect repetition draws.
1517 history[gamePly] = key;
1519 // Update the necessary information
1520 sideToMove = opposite_color(sideToMove);
1521 if (epSquare != SQ_NONE)
1522 key ^= zobEp[epSquare];
1527 key ^= zobSideToMove;
1529 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1530 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1536 /// Position::undo_null_move() unmakes a "null move".
1538 void Position::undo_null_move(const UndoInfo &u) {
1541 assert(!is_check());
1543 // Restore information from the supplied UndoInfo object:
1544 lastMove = u.lastMove;
1545 epSquare = u.epSquare;
1546 if (epSquare != SQ_NONE)
1547 key ^= zobEp[epSquare];
1549 // Update the necessary information.
1550 sideToMove = opposite_color(sideToMove);
1553 key ^= zobSideToMove;
1555 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1556 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1562 /// Position::see() is a static exchange evaluator: It tries to estimate the
1563 /// material gain or loss resulting from a move. There are three versions of
1564 /// this function: One which takes a destination square as input, one takes a
1565 /// move, and one which takes a 'from' and a 'to' square. The function does
1566 /// not yet understand promotions captures.
1568 int Position::see(Square to) const {
1570 assert(square_is_ok(to));
1571 return see(SQ_NONE, to);
1574 int Position::see(Move m) const {
1576 assert(move_is_ok(m));
1577 return see(move_from(m), move_to(m));
1580 int Position::see(Square from, Square to) const {
1583 static const int seeValues[18] = {
1584 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1585 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1586 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1587 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1591 Bitboard attackers, occ, b;
1593 assert(square_is_ok(from) || from == SQ_NONE);
1594 assert(square_is_ok(to));
1596 // Initialize colors
1597 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1598 Color them = opposite_color(us);
1600 // Initialize pieces
1601 Piece piece = piece_on(from);
1602 Piece capture = piece_on(to);
1604 // Find all attackers to the destination square, with the moving piece
1605 // removed, but possibly an X-ray attacker added behind it.
1606 occ = occupied_squares();
1608 // Handle en passant moves
1609 if (epSquare == to && type_of_piece_on(from) == PAWN)
1611 assert(capture == EMPTY);
1613 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1614 capture = piece_on(capQq);
1616 assert(type_of_piece_on(capQq) == PAWN);
1618 // Remove the captured pawn
1619 clear_bit(&occ, capQq);
1624 clear_bit(&occ, from);
1625 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1626 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1627 | (piece_attacks<KNIGHT>(to) & knights())
1628 | (piece_attacks<KING>(to) & kings())
1629 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1630 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1632 if (from != SQ_NONE)
1635 // If we don't have any attacker we are finished
1636 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1639 // Locate the least valuable attacker to the destination square
1640 // and use it to initialize from square.
1642 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1645 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1646 piece = piece_on(from);
1649 // If the opponent has no attackers we are finished
1650 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1651 return seeValues[capture];
1653 attackers &= occ; // Remove the moving piece
1655 // The destination square is defended, which makes things rather more
1656 // difficult to compute. We proceed by building up a "swap list" containing
1657 // the material gain or loss at each stop in a sequence of captures to the
1658 // destination square, where the sides alternately capture, and always
1659 // capture with the least valuable piece. After each capture, we look for
1660 // new X-ray attacks from behind the capturing piece.
1661 int lastCapturingPieceValue = seeValues[piece];
1662 int swapList[32], n = 1;
1666 swapList[0] = seeValues[capture];
1669 // Locate the least valuable attacker for the side to move. The loop
1670 // below looks like it is potentially infinite, but it isn't. We know
1671 // that the side to move still has at least one attacker left.
1672 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1675 // Remove the attacker we just found from the 'attackers' bitboard,
1676 // and scan for new X-ray attacks behind the attacker.
1677 b = attackers & pieces_of_color_and_type(c, pt);
1679 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1680 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1684 // Add the new entry to the swap list
1686 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1689 // Remember the value of the capturing piece, and change the side to move
1690 // before beginning the next iteration
1691 lastCapturingPieceValue = seeValues[pt];
1692 c = opposite_color(c);
1694 // Stop after a king capture
1695 if (pt == KING && (attackers & pieces_of_color(c)))
1698 swapList[n++] = 100;
1701 } while (attackers & pieces_of_color(c));
1703 // Having built the swap list, we negamax through it to find the best
1704 // achievable score from the point of view of the side to move
1706 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1712 /// Position::clear() erases the position object to a pristine state, with an
1713 /// empty board, white to move, and no castling rights.
1715 void Position::clear() {
1717 for (int i = 0; i < 64; i++)
1723 for (int i = 0; i < 2; i++)
1724 byColorBB[i] = EmptyBoardBB;
1726 for (int i = 0; i < 7; i++)
1728 byTypeBB[i] = EmptyBoardBB;
1729 pieceCount[0][i] = pieceCount[1][i] = 0;
1730 for (int j = 0; j < 8; j++)
1731 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1734 checkersBB = EmptyBoardBB;
1736 lastMove = MOVE_NONE;
1739 castleRights = NO_CASTLES;
1740 initialKFile = FILE_E;
1741 initialKRFile = FILE_H;
1742 initialQRFile = FILE_A;
1749 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1750 /// UCI interface code, whenever a non-reversible move is made in a
1751 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1752 /// for the program to handle games of arbitrary length, as long as the GUI
1753 /// handles draws by the 50 move rule correctly.
1755 void Position::reset_game_ply() {
1761 /// Position::put_piece() puts a piece on the given square of the board,
1762 /// updating the board array, bitboards, and piece counts.
1764 void Position::put_piece(Piece p, Square s) {
1766 Color c = color_of_piece(p);
1767 PieceType pt = type_of_piece(p);
1770 index[s] = pieceCount[c][pt];
1771 pieceList[c][pt][index[s]] = s;
1773 set_bit(&(byTypeBB[pt]), s);
1774 set_bit(&(byColorBB[c]), s);
1775 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1777 pieceCount[c][pt]++;
1784 /// Position::allow_oo() gives the given side the right to castle kingside.
1785 /// Used when setting castling rights during parsing of FEN strings.
1787 void Position::allow_oo(Color c) {
1789 castleRights |= (1 + int(c));
1793 /// Position::allow_ooo() gives the given side the right to castle queenside.
1794 /// Used when setting castling rights during parsing of FEN strings.
1796 void Position::allow_ooo(Color c) {
1798 castleRights |= (4 + 4*int(c));
1802 /// Position::compute_key() computes the hash key of the position. The hash
1803 /// key is usually updated incrementally as moves are made and unmade, the
1804 /// compute_key() function is only used when a new position is set up, and
1805 /// to verify the correctness of the hash key when running in debug mode.
1807 Key Position::compute_key() const {
1809 Key result = Key(0ULL);
1811 for (Square s = SQ_A1; s <= SQ_H8; s++)
1812 if (square_is_occupied(s))
1813 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1815 if (ep_square() != SQ_NONE)
1816 result ^= zobEp[ep_square()];
1818 result ^= zobCastle[castleRights];
1819 if (side_to_move() == BLACK)
1820 result ^= zobSideToMove;
1826 /// Position::compute_pawn_key() computes the hash key of the position. The
1827 /// hash key is usually updated incrementally as moves are made and unmade,
1828 /// the compute_pawn_key() function is only used when a new position is set
1829 /// up, and to verify the correctness of the pawn hash key when running in
1832 Key Position::compute_pawn_key() const {
1834 Key result = Key(0ULL);
1838 for (Color c = WHITE; c <= BLACK; c++)
1843 s = pop_1st_bit(&b);
1844 result ^= zobrist[c][PAWN][s];
1851 /// Position::compute_material_key() computes the hash key of the position.
1852 /// The hash key is usually updated incrementally as moves are made and unmade,
1853 /// the compute_material_key() function is only used when a new position is set
1854 /// up, and to verify the correctness of the material hash key when running in
1857 Key Position::compute_material_key() const {
1859 Key result = Key(0ULL);
1860 for (Color c = WHITE; c <= BLACK; c++)
1861 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1863 int count = piece_count(c, pt);
1864 for (int i = 0; i <= count; i++)
1865 result ^= zobMaterial[c][pt][i];
1871 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1872 /// incremental scores for the middle game and the endgame. These functions
1873 /// are used to initialize the incremental scores when a new position is set
1874 /// up, and to verify that the scores are correctly updated by do_move
1875 /// and undo_move when the program is running in debug mode.
1877 Value Position::compute_mg_value() const {
1879 Value result = Value(0);
1883 for (Color c = WHITE; c <= BLACK; c++)
1884 for (PieceType pt = PAWN; pt <= KING; pt++)
1886 b = pieces_of_color_and_type(c, pt);
1889 s = pop_1st_bit(&b);
1890 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1891 result += mg_pst(c, pt, s);
1894 result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1898 Value Position::compute_eg_value() const {
1900 Value result = Value(0);
1904 for (Color c = WHITE; c <= BLACK; c++)
1905 for (PieceType pt = PAWN; pt <= KING; pt++)
1907 b = pieces_of_color_and_type(c, pt);
1910 s = pop_1st_bit(&b);
1911 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1912 result += eg_pst(c, pt, s);
1915 result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1920 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1921 /// game material score for the given side. Material scores are updated
1922 /// incrementally during the search, this function is only used while
1923 /// initializing a new Position object.
1925 Value Position::compute_non_pawn_material(Color c) const {
1927 Value result = Value(0);
1930 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1932 Bitboard b = pieces_of_color_and_type(c, pt);
1935 s = pop_1st_bit(&b);
1936 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1937 result += piece_value_midgame(pt);
1944 /// Position::is_mate() returns true or false depending on whether the
1945 /// side to move is checkmated. Note that this function is currently very
1946 /// slow, and shouldn't be used frequently inside the search.
1948 bool Position::is_mate() const {
1952 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1953 return mp.get_next_move() == MOVE_NONE;
1959 /// Position::is_draw() tests whether the position is drawn by material,
1960 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1961 /// must be done by the search.
1963 bool Position::is_draw() const {
1965 // Draw by material?
1967 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1970 // Draw by the 50 moves rule?
1971 if (rule50 > 100 || (rule50 == 100 && !is_check()))
1974 // Draw by repetition?
1975 for (int i = 2; i < Min(gamePly, rule50); i += 2)
1976 if (history[gamePly - i] == key)
1983 /// Position::has_mate_threat() tests whether a given color has a mate in one
1984 /// from the current position. This function is quite slow, but it doesn't
1985 /// matter, because it is currently only called from PV nodes, which are rare.
1987 bool Position::has_mate_threat(Color c) {
1990 Color stm = side_to_move();
1992 // The following lines are useless and silly, but prevents gcc from
1993 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1994 // be used uninitialized.
1995 u1.lastMove = lastMove;
1996 u1.epSquare = epSquare;
2001 // If the input color is not equal to the side to move, do a null move
2005 MoveStack mlist[120];
2007 bool result = false;
2009 // Generate legal moves
2010 count = generate_legal_moves(*this, mlist);
2012 // Loop through the moves, and see if one of them is mate
2013 for (int i = 0; i < count; i++)
2015 do_move(mlist[i].move, u2);
2019 undo_move(mlist[i].move, u2);
2022 // Undo null move, if necessary
2030 /// Position::init_zobrist() is a static member function which initializes the
2031 /// various arrays used to compute hash keys.
2033 void Position::init_zobrist() {
2035 for (int i = 0; i < 2; i++)
2036 for (int j = 0; j < 8; j++)
2037 for (int k = 0; k < 64; k++)
2038 zobrist[i][j][k] = Key(genrand_int64());
2040 for (int i = 0; i < 64; i++)
2041 zobEp[i] = Key(genrand_int64());
2043 for (int i = 0; i < 16; i++)
2044 zobCastle[i] = genrand_int64();
2046 zobSideToMove = genrand_int64();
2048 for (int i = 0; i < 2; i++)
2049 for (int j = 0; j < 8; j++)
2050 for (int k = 0; k < 16; k++)
2051 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2053 for (int i = 0; i < 16; i++)
2054 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2058 /// Position::init_piece_square_tables() initializes the piece square tables.
2059 /// This is a two-step operation: First, the white halves of the tables are
2060 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2061 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2062 /// Second, the black halves of the tables are initialized by mirroring
2063 /// and changing the sign of the corresponding white scores.
2065 void Position::init_piece_square_tables() {
2067 int r = get_option_value_int("Randomness"), i;
2068 for (Square s = SQ_A1; s <= SQ_H8; s++)
2069 for (Piece p = WP; p <= WK; p++)
2071 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2072 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2073 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2076 for (Square s = SQ_A1; s <= SQ_H8; s++)
2077 for (Piece p = BP; p <= BK; p++)
2079 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2080 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2085 /// Position::flipped_copy() makes a copy of the input position, but with
2086 /// the white and black sides reversed. This is only useful for debugging,
2087 /// especially for finding evaluation symmetry bugs.
2089 void Position::flipped_copy(const Position &pos) {
2091 assert(pos.is_ok());
2096 for (Square s = SQ_A1; s <= SQ_H8; s++)
2097 if (!pos.square_is_empty(s))
2098 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2101 sideToMove = opposite_color(pos.side_to_move());
2104 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2105 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2106 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2107 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2109 initialKFile = pos.initialKFile;
2110 initialKRFile = pos.initialKRFile;
2111 initialQRFile = pos.initialQRFile;
2113 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2114 castleRightsMask[sq] = ALL_CASTLES;
2116 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2117 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2118 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2119 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2120 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2121 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2123 // En passant square
2124 if (pos.epSquare != SQ_NONE)
2125 epSquare = flip_square(pos.epSquare);
2131 key = compute_key();
2132 pawnKey = compute_pawn_key();
2133 materialKey = compute_material_key();
2135 // Incremental scores
2136 mgValue = compute_mg_value();
2137 egValue = compute_eg_value();
2140 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2141 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2147 /// Position::is_ok() performs some consitency checks for the position object.
2148 /// This is meant to be helpful when debugging.
2150 bool Position::is_ok(int* failedStep) const {
2152 // What features of the position should be verified?
2153 static const bool debugBitboards = false;
2154 static const bool debugKingCount = false;
2155 static const bool debugKingCapture = false;
2156 static const bool debugCheckerCount = false;
2157 static const bool debugKey = false;
2158 static const bool debugMaterialKey = false;
2159 static const bool debugPawnKey = false;
2160 static const bool debugIncrementalEval = false;
2161 static const bool debugNonPawnMaterial = false;
2162 static const bool debugPieceCounts = false;
2163 static const bool debugPieceList = false;
2165 if (failedStep) *failedStep = 1;
2168 if (!color_is_ok(side_to_move()))
2171 // Are the king squares in the position correct?
2172 if (failedStep) (*failedStep)++;
2173 if (piece_on(king_square(WHITE)) != WK)
2176 if (failedStep) (*failedStep)++;
2177 if (piece_on(king_square(BLACK)) != BK)
2181 if (failedStep) (*failedStep)++;
2182 if (!file_is_ok(initialKRFile))
2185 if (!file_is_ok(initialQRFile))
2188 // Do both sides have exactly one king?
2189 if (failedStep) (*failedStep)++;
2192 int kingCount[2] = {0, 0};
2193 for (Square s = SQ_A1; s <= SQ_H8; s++)
2194 if (type_of_piece_on(s) == KING)
2195 kingCount[color_of_piece_on(s)]++;
2197 if (kingCount[0] != 1 || kingCount[1] != 1)
2201 // Can the side to move capture the opponent's king?
2202 if (failedStep) (*failedStep)++;
2203 if (debugKingCapture)
2205 Color us = side_to_move();
2206 Color them = opposite_color(us);
2207 Square ksq = king_square(them);
2208 if (square_is_attacked(ksq, us))
2212 // Is there more than 2 checkers?
2213 if (failedStep) (*failedStep)++;
2214 if (debugCheckerCount && count_1s(checkersBB) > 2)
2218 if (failedStep) (*failedStep)++;
2221 // The intersection of the white and black pieces must be empty
2222 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2225 // The union of the white and black pieces must be equal to all
2227 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2230 // Separate piece type bitboards must have empty intersections
2231 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2232 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2233 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2237 // En passant square OK?
2238 if (failedStep) (*failedStep)++;
2239 if (ep_square() != SQ_NONE)
2241 // The en passant square must be on rank 6, from the point of view of the
2243 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2248 if (failedStep) (*failedStep)++;
2249 if (debugKey && key != compute_key())
2252 // Pawn hash key OK?
2253 if (failedStep) (*failedStep)++;
2254 if (debugPawnKey && pawnKey != compute_pawn_key())
2257 // Material hash key OK?
2258 if (failedStep) (*failedStep)++;
2259 if (debugMaterialKey && materialKey != compute_material_key())
2262 // Incremental eval OK?
2263 if (failedStep) (*failedStep)++;
2264 if (debugIncrementalEval)
2266 if (mgValue != compute_mg_value())
2269 if (egValue != compute_eg_value())
2273 // Non-pawn material OK?
2274 if (failedStep) (*failedStep)++;
2275 if (debugNonPawnMaterial)
2277 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2280 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2285 if (failedStep) (*failedStep)++;
2286 if (debugPieceCounts)
2287 for (Color c = WHITE; c <= BLACK; c++)
2288 for (PieceType pt = PAWN; pt <= KING; pt++)
2289 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2292 if (failedStep) (*failedStep)++;
2295 for(Color c = WHITE; c <= BLACK; c++)
2296 for(PieceType pt = PAWN; pt <= KING; pt++)
2297 for(int i = 0; i < pieceCount[c][pt]; i++)
2299 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2302 if (index[piece_list(c, pt, i)] != i)
2306 if (failedStep) *failedStep = 0;