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/>.
34 #include "ucioption.h"
41 int Position::castleRightsMask[64];
43 Key Position::zobrist[2][8][64];
44 Key Position::zobEp[64];
45 Key Position::zobCastle[16];
46 Key Position::zobMaterial[2][8][16];
47 Key Position::zobSideToMove;
49 Value Position::MgPieceSquareTable[16][64];
50 Value Position::EgPieceSquareTable[16][64];
59 Position::Position(const Position &pos) {
63 Position::Position(const std::string &fen) {
68 /// Position::from_fen() initializes the position object with the given FEN
69 /// string. This function is not very robust - make sure that input FENs are
70 /// correct (this is assumed to be the responsibility of the GUI).
72 void Position::from_fen(const std::string &fen) {
74 static const std::string pieceLetters = "KQRBNPkqrbnp";
75 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
83 for ( ; fen[i] != ' '; i++)
87 // Skip the given number of files
88 file += (fen[i] - '1' + 1);
91 else if (fen[i] == '/')
97 size_t idx = pieceLetters.find(fen[i]);
98 if (idx == std::string::npos)
100 std::cout << "Error in FEN at character " << i << std::endl;
103 Square square = make_square(file, rank);
104 put_piece(pieces[idx], square);
110 if (fen[i] != 'w' && fen[i] != 'b')
112 std::cout << "Error in FEN at character " << i << std::endl;
115 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
121 std::cout << "Error in FEN at character " << i << std::endl;
126 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
130 else if(fen[i] == 'K') allow_oo(WHITE);
131 else if(fen[i] == 'Q') allow_ooo(WHITE);
132 else if(fen[i] == 'k') allow_oo(BLACK);
133 else if(fen[i] == 'q') allow_ooo(BLACK);
134 else if(fen[i] >= 'A' && fen[i] <= 'H') {
135 File rookFile, kingFile = FILE_NONE;
136 for(Square square = SQ_B1; square <= SQ_G1; square++)
137 if(piece_on(square) == WK)
138 kingFile = square_file(square);
139 if(kingFile == FILE_NONE) {
140 std::cout << "Error in FEN at character " << i << std::endl;
143 initialKFile = kingFile;
144 rookFile = File(fen[i] - 'A') + FILE_A;
145 if(rookFile < initialKFile) {
147 initialQRFile = rookFile;
151 initialKRFile = rookFile;
154 else if(fen[i] >= 'a' && fen[i] <= 'h') {
155 File rookFile, kingFile = FILE_NONE;
156 for(Square square = SQ_B8; square <= SQ_G8; square++)
157 if(piece_on(square) == BK)
158 kingFile = square_file(square);
159 if(kingFile == FILE_NONE) {
160 std::cout << "Error in FEN at character " << i << std::endl;
163 initialKFile = kingFile;
164 rookFile = File(fen[i] - 'a') + FILE_A;
165 if(rookFile < initialKFile) {
167 initialQRFile = rookFile;
171 initialKRFile = rookFile;
175 std::cout << "Error in FEN at character " << i << std::endl;
182 while (fen[i] == ' ')
186 if ( i < fen.length() - 2
187 && (fen[i] >= 'a' && fen[i] <= 'h')
188 && (fen[i+1] == '3' || fen[i+1] == '6'))
189 epSquare = square_from_string(fen.substr(i, 2));
191 // Various initialisation
192 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
193 castleRightsMask[sq] = ALL_CASTLES;
195 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
196 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
197 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
198 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
199 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
200 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
205 pawnKey = compute_pawn_key();
206 materialKey = compute_material_key();
207 mgValue = compute_mg_value();
208 egValue = compute_eg_value();
209 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
210 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
214 /// Position::to_fen() converts the position object to a FEN string. This is
215 /// probably only useful for debugging.
217 const std::string Position::to_fen() const {
219 static const std::string pieceLetters = " PNBRQK pnbrqk";
223 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
226 for (File file = FILE_A; file <= FILE_H; file++)
228 Square sq = make_square(file, rank);
229 if (!square_is_occupied(sq))
235 fen += (char)skip + '0';
238 fen += pieceLetters[piece_on(sq)];
241 fen += (char)skip + '0';
243 fen += (rank > RANK_1 ? '/' : ' ');
245 fen += (sideToMove == WHITE ? 'w' : 'b') + ' ';
246 if (castleRights != NO_CASTLES)
248 if (can_castle_kingside(WHITE)) fen += 'K';
249 if (can_castle_queenside(WHITE)) fen += 'Q';
250 if (can_castle_kingside(BLACK)) fen += 'k';
251 if (can_castle_queenside(BLACK)) fen += 'q';
256 if (ep_square() != SQ_NONE)
257 fen += square_to_string(ep_square());
265 /// Position::print() prints an ASCII representation of the position to
266 /// the standard output.
268 void Position::print() const {
269 char pieceStrings[][8] =
270 {"| ? ", "| P ", "| N ", "| B ", "| R ", "| Q ", "| K ", "| ? ",
271 "| ? ", "|=P=", "|=N=", "|=B=", "|=R=", "|=Q=", "|=K="
274 for(Rank rank = RANK_8; rank >= RANK_1; rank--) {
275 std::cout << "+---+---+---+---+---+---+---+---+\n";
276 for(File file = FILE_A; file <= FILE_H; file++) {
277 Square sq = make_square(file, rank);
278 Piece piece = piece_on(sq);
280 std::cout << ((square_color(sq) == WHITE)? "| " : "| . ");
282 std::cout << pieceStrings[piece];
286 std::cout << "+---+---+---+---+---+---+---+---+\n";
287 std::cout << to_fen() << std::endl;
288 std::cout << key << std::endl;
292 /// Position::copy() creates a copy of the input position.
294 void Position::copy(const Position &pos) {
295 memcpy(this, &pos, sizeof(Position));
299 /// Position:pinned_pieces<>() returns a bitboard of all pinned (against the
300 /// king) pieces for the given color and for the given pinner type.
301 template<PieceType Piece>
302 Bitboard Position::pinned_pieces(Color c, Square ksq) const {
305 Bitboard sliders, pinned = EmptyBoardBB;
307 if (Piece == ROOK) // Resolved at compile time
308 sliders = rooks_and_queens(opposite_color(c)) & RookPseudoAttacks[ksq];
310 sliders = bishops_and_queens(opposite_color(c)) & BishopPseudoAttacks[ksq];
312 if (sliders && (sliders & ~checkersBB))
314 // Our king blockers are candidate pinned pieces
315 Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
317 // Pinners are sliders, not checkers, that give check when
318 // candidate pinned are removed.
319 Bitboard pinners = sliders & ~checkersBB;
321 pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
323 pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
325 // Finally for each pinner find the corresponding pinned piece
326 // among the candidates.
329 s = pop_1st_bit(&pinners);
330 pinned |= (squares_between(s, ksq) & candidate_pinned);
337 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
338 /// king) pieces for the given color.
339 Bitboard Position::pinned_pieces(Color c) const {
341 Square ksq = king_square(c);
342 return pinned_pieces<ROOK>(c, ksq) | pinned_pieces<BISHOP>(c, ksq);
346 /// Position:discovered_check_candidates() returns a bitboard containing all
347 /// pieces for the given side which are candidates for giving a discovered
348 /// check. The code is almost the same as the function for finding pinned
351 Bitboard Position::discovered_check_candidates(Color c) const {
352 Bitboard b1, b2, dc, checkers, sliders;
353 Square ksq = king_square(opposite_color(c)), s;
356 b1 = occupied_squares();
358 sliders = rooks_and_queens(c);
359 if(sliders & RookPseudoAttacks[ksq]) {
360 b2 = piece_attacks<ROOK>(ksq) & pieces_of_color(c);
361 checkers = rook_attacks_bb(ksq, b1 ^ b2) & sliders;
363 s = pop_1st_bit(&checkers);
364 dc |= (squares_between(s, ksq) & b2);
368 sliders = bishops_and_queens(c);
369 if(sliders & BishopPseudoAttacks[ksq]) {
370 b2 = piece_attacks<BISHOP>(ksq) & pieces_of_color(c);
371 checkers = bishop_attacks_bb(ksq, b1 ^ b2) & sliders;
373 s = pop_1st_bit(&checkers);
374 dc |= (squares_between(s, ksq) & b2);
382 /// Position::square_is_attacked() checks whether the given side attacks the
385 bool Position::square_is_attacked(Square s, Color c) const {
387 (pawn_attacks(opposite_color(c), s) & pawns(c)) ||
388 (piece_attacks<KNIGHT>(s) & knights(c)) ||
389 (piece_attacks<KING>(s) & kings(c)) ||
390 (piece_attacks<ROOK>(s) & rooks_and_queens(c)) ||
391 (piece_attacks<BISHOP>(s) & bishops_and_queens(c));
395 /// Position::attacks_to() computes a bitboard containing all pieces which
396 /// attacks a given square. There are two versions of this function: One
397 /// which finds attackers of both colors, and one which only finds the
398 /// attackers for one side.
400 Bitboard Position::attacks_to(Square s) const {
402 (pawn_attacks(BLACK, s) & pawns(WHITE)) |
403 (pawn_attacks(WHITE, s) & pawns(BLACK)) |
404 (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT)) |
405 (piece_attacks<ROOK>(s) & rooks_and_queens()) |
406 (piece_attacks<BISHOP>(s) & bishops_and_queens()) |
407 (piece_attacks<KING>(s) & pieces_of_type(KING));
410 Bitboard Position::attacks_to(Square s, Color c) const {
411 return attacks_to(s) & pieces_of_color(c);
415 /// Position::piece_attacks_square() tests whether the piece on square f
416 /// attacks square t.
418 bool Position::piece_attacks_square(Square f, Square t) const {
419 assert(square_is_ok(f));
420 assert(square_is_ok(t));
422 switch(piece_on(f)) {
423 case WP: return pawn_attacks_square(WHITE, f, t);
424 case BP: return pawn_attacks_square(BLACK, f, t);
425 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
426 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
427 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
428 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
429 case WK: case BK: return piece_attacks_square<KING>(f, t);
430 default: return false;
437 /// Position::find_checkers() computes the checkersBB bitboard, which
438 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
439 /// currently works by calling Position::attacks_to, which is probably
440 /// inefficient. Consider rewriting this function to use the last move
441 /// played, like in non-bitboard versions of Glaurung.
443 void Position::find_checkers() {
444 checkersBB = attacks_to(king_square(side_to_move()),
445 opposite_color(side_to_move()));
449 /// Position::move_is_legal() tests whether a pseudo-legal move is legal.
450 /// There are two versions of this function: One which takes only a
451 /// move as input, and one which takes a move and a bitboard of pinned
452 /// pieces. The latter function is faster, and should always be preferred
453 /// when a pinned piece bitboard has already been computed.
455 bool Position::move_is_legal(Move m) const {
456 return move_is_legal(m, pinned_pieces(side_to_move()));
460 bool Position::move_is_legal(Move m, Bitboard pinned) const {
465 assert(move_is_ok(m));
466 assert(pinned == pinned_pieces(side_to_move()));
468 // If we're in check, all pseudo-legal moves are legal, because our
469 // check evasion generator only generates true legal moves.
470 if(is_check()) return true;
472 // Castling moves are checked for legality during move generation.
473 if(move_is_castle(m)) return true;
476 them = opposite_color(us);
479 ksq = king_square(us);
481 assert(color_of_piece_on(from) == us);
482 assert(piece_on(ksq) == king_of_color(us));
484 // En passant captures are a tricky special case. Because they are
485 // rather uncommon, we do it simply by testing whether the king is attacked
486 // after the move is made:
488 Square to = move_to(m);
489 Square capsq = make_square(square_file(to), square_rank(from));
490 Bitboard b = occupied_squares();
492 assert(to == ep_square());
493 assert(piece_on(from) == pawn_of_color(us));
494 assert(piece_on(capsq) == pawn_of_color(them));
495 assert(piece_on(to) == EMPTY);
497 clear_bit(&b, from); clear_bit(&b, capsq); set_bit(&b, to);
499 (!(rook_attacks_bb(ksq, b) & rooks_and_queens(them)) &&
500 !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them)));
503 // If the moving piece is a king, check whether the destination
504 // square is attacked by the opponent.
505 if(from == ksq) return !(square_is_attacked(move_to(m), them));
507 // A non-king move is legal if and only if it is not pinned or it
508 // is moving along the ray towards or away from the king.
509 if(!bit_is_set(pinned, from)) return true;
510 if(direction_between_squares(from, ksq) ==
511 direction_between_squares(move_to(m), ksq))
518 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
519 /// There are two versions of this function: One which takes only a move as
520 /// input, and one which takes a move and a bitboard of discovered check
521 /// candidates. The latter function is faster, and should always be preferred
522 /// when a discovered check candidates bitboard has already been computed.
524 bool Position::move_is_check(Move m) const {
525 Bitboard dc = discovered_check_candidates(side_to_move());
526 return move_is_check(m, dc);
530 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
532 Square ksq, from, to;
535 assert(move_is_ok(m));
536 assert(dcCandidates ==
537 discovered_check_candidates(side_to_move()));
540 them = opposite_color(us);
544 ksq = king_square(them);
545 assert(color_of_piece_on(from) == us);
546 assert(piece_on(ksq) == king_of_color(them));
548 // Proceed according to the type of the moving piece:
549 switch(type_of_piece_on(from)) {
552 if(bit_is_set(pawn_attacks(them, ksq), to))
555 else if(bit_is_set(dcCandidates, from) &&
556 direction_between_squares(from, ksq) !=
557 direction_between_squares(to, ksq))
559 // Promotion with check?
560 else if(move_promotion(m)) {
561 Bitboard b = occupied_squares();
564 switch(move_promotion(m)) {
566 return piece_attacks_square<KNIGHT>(to, ksq);
568 return bit_is_set(bishop_attacks_bb(to, b), ksq);
570 return bit_is_set(rook_attacks_bb(to, b), ksq);
572 return bit_is_set(queen_attacks_bb(to, b), ksq);
577 // En passant capture with check? We have already handled the case
578 // of direct checks and ordinary discovered check, the only case we
579 // need to handle is the unusual case of a discovered check through the
581 else if(move_is_ep(m)) {
582 Square capsq = make_square(square_file(to), square_rank(from));
583 Bitboard b = occupied_squares();
585 clear_bit(&b, from); clear_bit(&b, capsq); set_bit(&b, to);
587 ((rook_attacks_bb(ksq, b) & rooks_and_queens(us)) ||
588 (bishop_attacks_bb(ksq, b) & bishops_and_queens(us)));
594 if(bit_is_set(dcCandidates, from))
598 return bit_is_set(piece_attacks<KNIGHT>(ksq), to);
602 if(bit_is_set(dcCandidates, from))
606 return bit_is_set(piece_attacks<BISHOP>(ksq), to);
610 if(bit_is_set(dcCandidates, from))
614 return bit_is_set(piece_attacks<ROOK>(ksq), to);
617 // Discovered checks are impossible!
618 assert(!bit_is_set(dcCandidates, from));
620 return bit_is_set(piece_attacks<QUEEN>(ksq), to);
624 if(bit_is_set(dcCandidates, from) &&
625 direction_between_squares(from, ksq) !=
626 direction_between_squares(to, ksq))
628 // Castling with check?
629 if(move_is_castle(m)) {
630 Square kfrom, kto, rfrom, rto;
631 Bitboard b = occupied_squares();
636 kto = relative_square(us, SQ_G1);
637 rto = relative_square(us, SQ_F1);
640 kto = relative_square(us, SQ_C1);
641 rto = relative_square(us, SQ_D1);
644 clear_bit(&b, kfrom); clear_bit(&b, rfrom);
645 set_bit(&b, rto); set_bit(&b, kto);
647 return bit_is_set(rook_attacks_bb(rto, b), ksq);
662 /// Position::move_is_capture() tests whether a move from the current
663 /// position is a capture.
665 bool Position::move_is_capture(Move m) const {
667 color_of_piece_on(move_to(m)) == opposite_color(side_to_move())
672 /// Position::move_attacks_square() tests whether a move from the current
673 /// position attacks a given square. Only attacks by the moving piece are
674 /// considered; the function does not handle X-ray attacks.
676 bool Position::move_attacks_square(Move m, Square s) const {
677 assert(move_is_ok(m));
678 assert(square_is_ok(s));
680 Square f = move_from(m), t = move_to(m);
682 assert(square_is_occupied(f));
684 switch(piece_on(f)) {
685 case WP: return pawn_attacks_square(WHITE, t, s);
686 case BP: return pawn_attacks_square(BLACK, t, s);
687 case WN: case BN: return piece_attacks_square<KNIGHT>(t, s);
688 case WB: case BB: return piece_attacks_square<BISHOP>(t, s);
689 case WR: case BR: return piece_attacks_square<ROOK>(t, s);
690 case WQ: case BQ: return piece_attacks_square<QUEEN>(t, s);
691 case WK: case BK: return piece_attacks_square<KING>(t, s);
692 default: assert(false);
700 /// Position::backup() is called when making a move. All information
701 /// necessary to restore the position when the move is later unmade
702 /// is saved to an UndoInfo object. The function Position::restore
703 /// does the reverse operation: When one does a backup followed by
704 /// a restore with the same UndoInfo object, the position is restored
705 /// to the state before backup was called.
707 void Position::backup(UndoInfo &u) const {
708 u.castleRights = castleRights;
709 u.epSquare = epSquare;
710 u.checkersBB = checkersBB;
713 u.materialKey = materialKey;
715 u.lastMove = lastMove;
716 u.capture = NO_PIECE_TYPE;
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) {
726 castleRights = u.castleRights;
727 epSquare = u.epSquare;
728 checkersBB = u.checkersBB;
731 materialKey = u.materialKey;
733 lastMove = u.lastMove;
739 /// Position::do_move() makes a move, and backs up all information necessary
740 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
741 /// Pseudo-legal moves should be filtered out before this function is called.
742 /// There are two versions of this function, one which takes only the move and
743 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
744 /// discovered check candidates. The second version is faster, because knowing
745 /// the discovered check candidates makes it easier to update the checkersBB
746 /// member variable in the position object.
748 void Position::do_move(Move m, UndoInfo &u) {
749 do_move(m, u, discovered_check_candidates(side_to_move()));
752 void Position::do_move(Move m, UndoInfo &u, Bitboard dcCandidates) {
754 assert(move_is_ok(m));
756 // Back up the necessary information to our UndoInfo object (except the
757 // captured piece, which is taken care of later:
760 // Save the current key to the history[] array, in order to be able to
761 // detect repetition draws:
762 history[gamePly] = key;
764 // Increment the 50 moves rule draw counter. Resetting it to zero in the
765 // case of non-reversible moves is taken care of later.
768 if(move_is_castle(m))
770 else if(move_promotion(m))
771 do_promotion_move(m, u);
772 else if(move_is_ep(m))
777 PieceType piece, capture;
780 them = opposite_color(us);
785 assert(color_of_piece_on(from) == us);
786 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
788 piece = type_of_piece_on(from);
789 capture = type_of_piece_on(to);
792 assert(capture != KING);
794 // Remove captured piece:
795 clear_bit(&(byColorBB[them]), to);
796 clear_bit(&(byTypeBB[capture]), to);
799 key ^= zobrist[them][capture][to];
801 // If the captured piece was a pawn, update pawn hash key:
803 pawnKey ^= zobrist[them][PAWN][to];
805 // Update incremental scores:
806 mgValue -= mg_pst(them, capture, to);
807 egValue -= eg_pst(them, capture, to);
811 npMaterial[them] -= piece_value_midgame(capture);
813 // Update material hash key:
814 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
816 // Update piece count:
817 pieceCount[them][capture]--;
819 // Update piece list:
820 pieceList[them][capture][index[to]] =
821 pieceList[them][capture][pieceCount[them][capture]];
822 index[pieceList[them][capture][index[to]]] = index[to];
824 // Remember the captured piece, in order to be able to undo the move
828 // Reset rule 50 counter:
833 clear_bit(&(byColorBB[us]), from);
834 clear_bit(&(byTypeBB[piece]), from);
835 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
836 set_bit(&(byColorBB[us]), to);
837 set_bit(&(byTypeBB[piece]), to);
838 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
839 board[to] = board[from];
843 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
845 // Update incremental scores:
846 mgValue -= mg_pst(us, piece, from);
847 mgValue += mg_pst(us, piece, to);
848 egValue -= eg_pst(us, piece, from);
849 egValue += eg_pst(us, piece, to);
851 // If the moving piece was a king, update the king square:
855 // If the move was a double pawn push, set the en passant square.
856 // This code is a bit ugly right now, and should be cleaned up later.
858 if(epSquare != SQ_NONE) {
859 key ^= zobEp[epSquare];
863 if(abs(int(to) - int(from)) == 16) {
864 if((us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) &
866 (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) &
868 epSquare = Square((int(from) + int(to)) / 2);
869 key ^= zobEp[epSquare];
872 // Reset rule 50 draw counter.
874 // Update pawn hash key:
875 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
878 // Update piece lists:
879 pieceList[us][piece][index[from]] = to;
880 index[to] = index[from];
882 // Update castle rights:
883 key ^= zobCastle[castleRights];
884 castleRights &= castleRightsMask[from];
885 castleRights &= castleRightsMask[to];
886 key ^= zobCastle[castleRights];
888 // Update checkers bitboard:
889 checkersBB = EmptyBoardBB;
890 Square ksq = king_square(them);
895 if(bit_is_set(pawn_attacks(them, ksq), to))
896 set_bit(&checkersBB, to);
897 if(bit_is_set(dcCandidates, from))
899 ((piece_attacks<ROOK>(ksq) & rooks_and_queens(us)) |
900 (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
904 if(bit_is_set(piece_attacks<KNIGHT>(ksq), to))
905 set_bit(&checkersBB, to);
906 if(bit_is_set(dcCandidates, from))
908 ((piece_attacks<ROOK>(ksq) & rooks_and_queens(us)) |
909 (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
913 if(bit_is_set(piece_attacks<BISHOP>(ksq), to))
914 set_bit(&checkersBB, to);
915 if(bit_is_set(dcCandidates, from))
917 (piece_attacks<ROOK>(ksq) & rooks_and_queens(us));
921 if(bit_is_set(piece_attacks<ROOK>(ksq), to))
922 set_bit(&checkersBB, to);
923 if(bit_is_set(dcCandidates, from))
925 (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us));
929 if(bit_is_set(piece_attacks<QUEEN>(ksq), to))
930 set_bit(&checkersBB, to);
934 if(bit_is_set(dcCandidates, from))
936 ((piece_attacks<ROOK>(ksq) & rooks_and_queens(us)) |
937 (piece_attacks<BISHOP>(ksq) & bishops_and_queens(us)));
947 key ^= zobSideToMove;
948 sideToMove = opposite_color(sideToMove);
951 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
952 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
958 /// Position::do_castle_move() is a private method used to make a castling
959 /// move. It is called from the main Position::do_move function. Note that
960 /// castling moves are encoded as "king captures friendly rook" moves, for
961 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
963 void Position::do_castle_move(Move m) {
965 Square kfrom, kto, rfrom, rto;
968 assert(move_is_ok(m));
969 assert(move_is_castle(m));
972 them = opposite_color(us);
974 // Find source squares for king and rook:
975 kfrom = move_from(m);
976 rfrom = move_to(m); // HACK: See comment at beginning of function.
978 assert(piece_on(kfrom) == king_of_color(us));
979 assert(piece_on(rfrom) == rook_of_color(us));
981 // Find destination squares for king and rook:
982 if(rfrom > kfrom) { // O-O
983 kto = relative_square(us, SQ_G1);
984 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] = king_of_color(us);
1010 board[rto] = rook_of_color(us);
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) {
1038 key ^= zobEp[epSquare];
1042 // Update castling rights:
1043 key ^= zobCastle[castleRights];
1044 castleRights &= castleRightsMask[kfrom];
1045 key ^= zobCastle[castleRights];
1047 // Reset rule 50 counter:
1050 // Update checkers BB:
1051 checkersBB = attacks_to(king_square(them), us);
1055 /// Position::do_promotion_move() is a private method used to make a promotion
1056 /// move. It is called from the main Position::do_move function. The
1057 /// UndoInfo object, which has been initialized in Position::do_move, is
1058 /// used to store the captured piece (if any).
1060 void Position::do_promotion_move(Move m, UndoInfo &u) {
1063 PieceType capture, promotion;
1066 assert(move_is_ok(m));
1067 assert(move_promotion(m));
1069 us = side_to_move();
1070 them = opposite_color(us);
1072 from = move_from(m);
1075 assert(relative_rank(us, to) == RANK_8);
1076 assert(piece_on(from) == pawn_of_color(us));
1077 assert(color_of_piece_on(to) == them || square_is_empty(to));
1079 capture = type_of_piece_on(to);
1082 assert(capture != KING);
1084 // Remove captured piece:
1085 clear_bit(&(byColorBB[them]), to);
1086 clear_bit(&(byTypeBB[capture]), to);
1089 key ^= zobrist[them][capture][to];
1091 // Update incremental scores:
1092 mgValue -= mg_pst(them, capture, to);
1093 egValue -= eg_pst(them, capture, to);
1095 // Update material. Because our move is a promotion, we know that the
1096 // captured piece is not a pawn.
1097 assert(capture != PAWN);
1098 npMaterial[them] -= piece_value_midgame(capture);
1100 // Update material hash key:
1101 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
1103 // Update piece count:
1104 pieceCount[them][capture]--;
1106 // Update piece list:
1107 pieceList[them][capture][index[to]] =
1108 pieceList[them][capture][pieceCount[them][capture]];
1109 index[pieceList[them][capture][index[to]]] = index[to];
1111 // Remember the captured piece, in order to be able to undo the move
1113 u.capture = capture;
1117 clear_bit(&(byColorBB[us]), from);
1118 clear_bit(&(byTypeBB[PAWN]), from);
1119 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1120 board[from] = EMPTY;
1122 // Insert promoted piece:
1123 promotion = move_promotion(m);
1124 assert(promotion >= KNIGHT && promotion <= QUEEN);
1125 set_bit(&(byColorBB[us]), to);
1126 set_bit(&(byTypeBB[promotion]), to);
1127 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1128 board[to] = piece_of_color_and_type(us, promotion);
1131 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1133 // Update pawn hash key:
1134 pawnKey ^= zobrist[us][PAWN][from];
1136 // Update material key:
1137 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1138 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1140 // Update piece counts:
1141 pieceCount[us][PAWN]--;
1142 pieceCount[us][promotion]++;
1144 // Update piece lists:
1145 pieceList[us][PAWN][index[from]] =
1146 pieceList[us][PAWN][pieceCount[us][PAWN]];
1147 index[pieceList[us][PAWN][index[from]]] = index[from];
1148 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1149 index[to] = pieceCount[us][promotion] - 1;
1151 // Update incremental scores:
1152 mgValue -= mg_pst(us, PAWN, from);
1153 mgValue += mg_pst(us, promotion, to);
1154 egValue -= eg_pst(us, PAWN, from);
1155 egValue += eg_pst(us, promotion, to);
1158 npMaterial[us] += piece_value_midgame(promotion);
1160 // Clear the en passant square:
1161 if(epSquare != SQ_NONE) {
1162 key ^= zobEp[epSquare];
1166 // Update castle rights:
1167 key ^= zobCastle[castleRights];
1168 castleRights &= castleRightsMask[to];
1169 key ^= zobCastle[castleRights];
1171 // Reset rule 50 counter:
1174 // Update checkers BB:
1175 checkersBB = attacks_to(king_square(them), us);
1179 /// Position::do_ep_move() is a private method used to make an en passant
1180 /// capture. It is called from the main Position::do_move function. Because
1181 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1182 /// object in which to store the captured piece.
1184 void Position::do_ep_move(Move m) {
1186 Square from, to, capsq;
1189 assert(move_is_ok(m));
1190 assert(move_is_ep(m));
1192 us = side_to_move();
1193 them = opposite_color(us);
1195 // Find from, to and capture squares:
1196 from = move_from(m);
1198 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1200 assert(to == epSquare);
1201 assert(relative_rank(us, to) == RANK_6);
1202 assert(piece_on(to) == EMPTY);
1203 assert(piece_on(from) == pawn_of_color(us));
1204 assert(piece_on(capsq) == pawn_of_color(them));
1206 // Remove captured piece:
1207 clear_bit(&(byColorBB[them]), capsq);
1208 clear_bit(&(byTypeBB[PAWN]), capsq);
1209 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1210 board[capsq] = EMPTY;
1212 // Remove moving piece from source square:
1213 clear_bit(&(byColorBB[us]), from);
1214 clear_bit(&(byTypeBB[PAWN]), from);
1215 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1217 // Put moving piece on destination square:
1218 set_bit(&(byColorBB[us]), to);
1219 set_bit(&(byTypeBB[PAWN]), to);
1220 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1221 board[to] = board[from];
1222 board[from] = EMPTY;
1224 // Update material hash key:
1225 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1227 // Update piece count:
1228 pieceCount[them][PAWN]--;
1230 // Update piece list:
1231 pieceList[us][PAWN][index[from]] = to;
1232 index[to] = index[from];
1233 pieceList[them][PAWN][index[capsq]] =
1234 pieceList[them][PAWN][pieceCount[them][PAWN]];
1235 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1238 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1239 key ^= zobrist[them][PAWN][capsq];
1240 key ^= zobEp[epSquare];
1242 // Update pawn hash key:
1243 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1244 pawnKey ^= zobrist[them][PAWN][capsq];
1246 // Update incremental scores:
1247 mgValue -= mg_pst(them, PAWN, capsq);
1248 mgValue -= mg_pst(us, PAWN, from);
1249 mgValue += mg_pst(us, PAWN, to);
1250 egValue -= eg_pst(them, PAWN, capsq);
1251 egValue -= eg_pst(us, PAWN, from);
1252 egValue += eg_pst(us, PAWN, to);
1254 // Reset en passant square:
1257 // Reset rule 50 counter:
1260 // Update checkers BB:
1261 checkersBB = attacks_to(king_square(them), us);
1265 /// Position::undo_move() unmakes a move. When it returns, the position should
1266 /// be restored to exactly the same state as before the move was made. It is
1267 /// important that Position::undo_move is called with the same move and UndoInfo
1268 /// object as the earlier call to Position::do_move.
1270 void Position::undo_move(Move m, const UndoInfo &u) {
1272 assert(move_is_ok(m));
1275 sideToMove = opposite_color(sideToMove);
1277 // Restore information from our UndoInfo object (except the captured piece,
1278 // which is taken care of later):
1281 if(move_is_castle(m))
1282 undo_castle_move(m);
1283 else if(move_promotion(m))
1284 undo_promotion_move(m, u);
1285 else if(move_is_ep(m))
1290 PieceType piece, capture;
1292 us = side_to_move();
1293 them = opposite_color(us);
1295 from = move_from(m);
1298 assert(piece_on(from) == EMPTY);
1299 assert(color_of_piece_on(to) == us);
1301 // Put the piece back at the source square:
1302 piece = type_of_piece_on(to);
1303 set_bit(&(byColorBB[us]), from);
1304 set_bit(&(byTypeBB[piece]), from);
1305 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1306 board[from] = piece_of_color_and_type(us, piece);
1308 // Clear the destination square
1309 clear_bit(&(byColorBB[us]), to);
1310 clear_bit(&(byTypeBB[piece]), to);
1311 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1313 // If the moving piece was a king, update the king square:
1315 kingSquare[us] = from;
1317 // Update piece list:
1318 pieceList[us][piece][index[to]] = from;
1319 index[from] = index[to];
1321 capture = u.capture;
1324 assert(capture != KING);
1325 // Replace the captured piece:
1326 set_bit(&(byColorBB[them]), to);
1327 set_bit(&(byTypeBB[capture]), to);
1328 set_bit(&(byTypeBB[0]), to);
1329 board[to] = piece_of_color_and_type(them, capture);
1333 npMaterial[them] += piece_value_midgame(capture);
1335 // Update piece list:
1336 pieceList[them][capture][pieceCount[them][capture]] = to;
1337 index[to] = pieceCount[them][capture];
1339 // Update piece count:
1340 pieceCount[them][capture]++;
1350 /// Position::undo_castle_move() is a private method used to unmake a castling
1351 /// move. It is called from the main Position::undo_move function. Note that
1352 /// castling moves are encoded as "king captures friendly rook" moves, for
1353 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1355 void Position::undo_castle_move(Move m) {
1357 Square kfrom, kto, rfrom, rto;
1359 assert(move_is_ok(m));
1360 assert(move_is_castle(m));
1362 // When we have arrived here, some work has already been done by
1363 // Position::undo_move. In particular, the side to move has been switched,
1364 // so the code below is correct.
1365 us = side_to_move();
1366 them = opposite_color(us);
1368 // Find source squares for king and rook:
1369 kfrom = move_from(m);
1370 rfrom = move_to(m); // HACK: See comment at beginning of function.
1372 // Find destination squares for king and rook:
1373 if(rfrom > kfrom) { // O-O
1374 kto = relative_square(us, SQ_G1);
1375 rto = relative_square(us, SQ_F1);
1378 kto = relative_square(us, SQ_C1);
1379 rto = relative_square(us, SQ_D1);
1382 assert(piece_on(kto) == king_of_color(us));
1383 assert(piece_on(rto) == rook_of_color(us));
1385 // Remove pieces from destination squares:
1386 clear_bit(&(byColorBB[us]), kto);
1387 clear_bit(&(byTypeBB[KING]), kto);
1388 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1389 clear_bit(&(byColorBB[us]), rto);
1390 clear_bit(&(byTypeBB[ROOK]), rto);
1391 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1393 // Put pieces on source squares:
1394 set_bit(&(byColorBB[us]), kfrom);
1395 set_bit(&(byTypeBB[KING]), kfrom);
1396 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1397 set_bit(&(byColorBB[us]), rfrom);
1398 set_bit(&(byTypeBB[ROOK]), rfrom);
1399 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1402 board[rto] = board[kto] = EMPTY;
1403 board[rfrom] = rook_of_color(us);
1404 board[kfrom] = king_of_color(us);
1406 // Update king square:
1407 kingSquare[us] = kfrom;
1409 // Update piece lists:
1410 pieceList[us][KING][index[kto]] = kfrom;
1411 pieceList[us][ROOK][index[rto]] = rfrom;
1412 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1413 index[kfrom] = index[kto];
1418 /// Position::undo_promotion_move() is a private method used to unmake a
1419 /// promotion move. It is called from the main Position::do_move
1420 /// function. The UndoInfo object, which has been initialized in
1421 /// Position::do_move, is used to put back the captured piece (if any).
1423 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1426 PieceType capture, promotion;
1428 assert(move_is_ok(m));
1429 assert(move_promotion(m));
1431 // When we have arrived here, some work has already been done by
1432 // Position::undo_move. In particular, the side to move has been switched,
1433 // so the code below is correct.
1434 us = side_to_move();
1435 them = opposite_color(us);
1437 from = move_from(m);
1440 assert(relative_rank(us, to) == RANK_8);
1441 assert(piece_on(from) == EMPTY);
1443 // Remove promoted piece:
1444 promotion = move_promotion(m);
1445 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1446 assert(promotion >= KNIGHT && promotion <= QUEEN);
1447 clear_bit(&(byColorBB[us]), to);
1448 clear_bit(&(byTypeBB[promotion]), to);
1449 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1451 // Insert pawn at source square:
1452 set_bit(&(byColorBB[us]), from);
1453 set_bit(&(byTypeBB[PAWN]), from);
1454 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1455 board[from] = pawn_of_color(us);
1458 npMaterial[us] -= piece_value_midgame(promotion);
1460 // Update piece list:
1461 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1462 index[from] = pieceCount[us][PAWN];
1463 pieceList[us][promotion][index[to]] =
1464 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1465 index[pieceList[us][promotion][index[to]]] = index[to];
1467 // Update piece counts:
1468 pieceCount[us][promotion]--;
1469 pieceCount[us][PAWN]++;
1471 capture = u.capture;
1473 assert(capture != KING);
1475 // Insert captured piece:
1476 set_bit(&(byColorBB[them]), to);
1477 set_bit(&(byTypeBB[capture]), to);
1478 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1479 board[to] = piece_of_color_and_type(them, capture);
1481 // Update material. Because the move is a promotion move, we know
1482 // that the captured piece cannot be a pawn.
1483 assert(capture != PAWN);
1484 npMaterial[them] += piece_value_midgame(capture);
1486 // Update piece list:
1487 pieceList[them][capture][pieceCount[them][capture]] = to;
1488 index[to] = pieceCount[them][capture];
1490 // Update piece count:
1491 pieceCount[them][capture]++;
1498 /// Position::undo_ep_move() is a private method used to unmake an en passant
1499 /// capture. It is called from the main Position::undo_move function. Because
1500 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1501 /// object from which to retrieve the captured piece.
1503 void Position::undo_ep_move(Move m) {
1505 Square from, to, capsq;
1507 assert(move_is_ok(m));
1508 assert(move_is_ep(m));
1510 // When we have arrived here, some work has already been done by
1511 // Position::undo_move. In particular, the side to move has been switched,
1512 // so the code below is correct.
1513 us = side_to_move();
1514 them = opposite_color(us);
1516 // Find from, to and captures squares:
1517 from = move_from(m);
1519 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1521 assert(to == ep_square());
1522 assert(relative_rank(us, to) == RANK_6);
1523 assert(piece_on(to) == pawn_of_color(us));
1524 assert(piece_on(from) == EMPTY);
1525 assert(piece_on(capsq) == EMPTY);
1527 // Replace captured piece:
1528 set_bit(&(byColorBB[them]), capsq);
1529 set_bit(&(byTypeBB[PAWN]), capsq);
1530 set_bit(&(byTypeBB[0]), capsq);
1531 board[capsq] = pawn_of_color(them);
1533 // Remove moving piece from destination square:
1534 clear_bit(&(byColorBB[us]), to);
1535 clear_bit(&(byTypeBB[PAWN]), to);
1536 clear_bit(&(byTypeBB[0]), to);
1539 // Replace moving piece at source square:
1540 set_bit(&(byColorBB[us]), from);
1541 set_bit(&(byTypeBB[PAWN]), from);
1542 set_bit(&(byTypeBB[0]), from);
1543 board[from] = pawn_of_color(us);
1545 // Update piece list:
1546 pieceList[us][PAWN][index[to]] = from;
1547 index[from] = index[to];
1548 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1549 index[capsq] = pieceCount[them][PAWN];
1551 // Update piece count:
1552 pieceCount[them][PAWN]++;
1556 /// Position::do_null_move makes() a "null move": It switches the side to move
1557 /// and updates the hash key without executing any move on the board.
1559 void Position::do_null_move(UndoInfo &u) {
1561 assert(!is_check());
1563 // Back up the information necessary to undo the null move to the supplied
1564 // UndoInfo object. In the case of a null move, the only thing we need to
1565 // remember is the last move made and the en passant square.
1566 u.lastMove = lastMove;
1567 u.epSquare = epSquare;
1569 // Save the current key to the history[] array, in order to be able to
1570 // detect repetition draws:
1571 history[gamePly] = key;
1573 // Update the necessary information.
1574 sideToMove = opposite_color(sideToMove);
1575 if(epSquare != SQ_NONE)
1576 key ^= zobEp[epSquare];
1580 key ^= zobSideToMove;
1582 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1583 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1589 /// Position::undo_null_move() unmakes a "null move".
1591 void Position::undo_null_move(const UndoInfo &u) {
1593 assert(!is_check());
1595 // Restore information from the supplied UndoInfo object:
1596 lastMove = u.lastMove;
1597 epSquare = u.epSquare;
1598 if(epSquare != SQ_NONE)
1599 key ^= zobEp[epSquare];
1601 // Update the necessary information.
1602 sideToMove = opposite_color(sideToMove);
1605 key ^= zobSideToMove;
1607 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1608 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1614 /// Position::see() is a static exchange evaluator: It tries to estimate the
1615 /// material gain or loss resulting from a move. There are two versions of
1616 /// this function: One which takes a move as input, and one which takes a
1617 /// 'from' and a 'to' square. The function does not yet understand promotions
1618 /// or en passant captures.
1620 int Position::see(Square from, Square to) const {
1621 // Approximate material values, with pawn = 1:
1622 static const int seeValues[18] = {
1623 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1626 Piece piece, capture;
1627 Bitboard attackers, occ, b;
1629 assert(square_is_ok(from));
1630 assert(square_is_ok(to));
1632 // Initialize colors:
1633 us = color_of_piece_on(from);
1634 them = opposite_color(us);
1636 // Initialize pieces:
1637 piece = piece_on(from);
1638 capture = piece_on(to);
1640 // Find all attackers to the destination square, with the moving piece
1641 // removed, but possibly an X-ray attacker added behind it:
1642 occ = occupied_squares();
1643 clear_bit(&occ, from);
1645 (rook_attacks_bb(to, occ) & rooks_and_queens()) |
1646 (bishop_attacks_bb(to, occ) & bishops_and_queens()) |
1647 (piece_attacks<KNIGHT>(to) & knights()) |
1648 (piece_attacks<KING>(to) & kings()) |
1649 (pawn_attacks(WHITE, to) & pawns(BLACK)) |
1650 (pawn_attacks(BLACK, to) & pawns(WHITE));
1653 // If the opponent has no attackers, we are finished:
1654 if((attackers & pieces_of_color(them)) == EmptyBoardBB)
1655 return seeValues[capture];
1657 // The destination square is defended, which makes things rather more
1658 // difficult to compute. We proceed by building up a "swap list" containing
1659 // the material gain or loss at each stop in a sequence of captures to the
1660 // destianation square, where the sides alternately capture, and always
1661 // capture with the least valuable piece. After each capture, we look for
1662 // new X-ray attacks from behind the capturing piece.
1663 int lastCapturingPieceValue = seeValues[piece];
1664 int swapList[32], n = 1;
1668 swapList[0] = seeValues[capture];
1671 // Locate the least valuable attacker for the side to move. The loop
1672 // below looks like it is potentially infinite, but it isn't. We know
1673 // that the side to move still has at least one attacker left.
1674 for(pt = PAWN; !(attackers&pieces_of_color_and_type(c, pt)); pt++)
1677 // Remove the attacker we just found from the 'attackers' bitboard,
1678 // and scan for new X-ray attacks behind the attacker:
1679 b = attackers & pieces_of_color_and_type(c, pt);
1682 (rook_attacks_bb(to, occ) & rooks_and_queens()) |
1683 (bishop_attacks_bb(to, occ) & bishops_and_queens());
1686 // Add the new entry to the swap list:
1688 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1691 // Remember the value of the capturing piece, and change the side to move
1692 // before beginning the next iteration:
1693 lastCapturingPieceValue = seeValues[pt];
1694 c = opposite_color(c);
1696 // Stop after a king capture:
1697 if(pt == KING && (attackers & pieces_of_color(c))) {
1699 swapList[n++] = 100;
1702 } while(attackers & pieces_of_color(c));
1704 // Having built the swap list, we negamax through it to find the best
1705 // achievable score from the point of view of the side to move:
1706 while(--n) swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1712 int Position::see(Move m) const {
1713 assert(move_is_ok(m));
1714 return see(move_from(m), move_to(m));
1718 /// Position::clear() erases the position object to a pristine state, with an
1719 /// empty board, white to move, and no castling rights.
1721 void Position::clear() {
1724 for(i = 0; i < 64; i++) {
1729 for(i = 0; i < 2; i++)
1730 byColorBB[i] = EmptyBoardBB;
1732 for(i = 0; i < 7; i++) {
1733 byTypeBB[i] = EmptyBoardBB;
1734 pieceCount[0][i] = pieceCount[1][i] = 0;
1735 for(j = 0; j < 8; j++)
1736 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1739 checkersBB = EmptyBoardBB;
1741 lastMove = MOVE_NONE;
1744 castleRights = NO_CASTLES;
1745 initialKFile = FILE_E;
1746 initialKRFile = FILE_H;
1747 initialQRFile = FILE_A;
1754 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1755 /// UCI interface code, whenever a non-reversible move is made in a
1756 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1757 /// for the program to handle games of arbitrary length, as long as the GUI
1758 /// handles draws by the 50 move rule correctly.
1760 void Position::reset_game_ply() {
1765 /// Position::put_piece() puts a piece on the given square of the board,
1766 /// updating the board array, bitboards, and piece counts.
1768 void Position::put_piece(Piece p, Square s) {
1769 Color c = color_of_piece(p);
1770 PieceType pt = type_of_piece(p);
1773 index[s] = pieceCount[c][pt];
1774 pieceList[c][pt][index[s]] = s;
1776 set_bit(&(byTypeBB[pt]), s);
1777 set_bit(&(byColorBB[c]), s);
1778 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1780 pieceCount[c][pt]++;
1787 /// Position::allow_oo() gives the given side the right to castle kingside.
1788 /// Used when setting castling rights during parsing of FEN strings.
1790 void Position::allow_oo(Color c) {
1791 castleRights |= (1 + int(c));
1795 /// Position::allow_ooo() gives the given side the right to castle queenside.
1796 /// Used when setting castling rights during parsing of FEN strings.
1798 void Position::allow_ooo(Color c) {
1799 castleRights |= (4 + 4*int(c));
1803 /// Position::compute_key() computes the hash key of the position. The hash
1804 /// key is usually updated incrementally as moves are made and unmade, the
1805 /// compute_key() function is only used when a new position is set up, and
1806 /// to verify the correctness of the hash key when running in debug mode.
1808 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))
1814 zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1816 if(ep_square() != SQ_NONE)
1817 result ^= zobEp[ep_square()];
1818 result ^= zobCastle[castleRights];
1819 if(side_to_move() == BLACK) result ^= zobSideToMove;
1825 /// Position::compute_pawn_key() computes the hash key of the position. The
1826 /// hash key is usually updated incrementally as moves are made and unmade,
1827 /// the compute_pawn_key() function is only used when a new position is set
1828 /// up, and to verify the correctness of the pawn hash key when running in
1831 Key Position::compute_pawn_key() const {
1832 Key result = Key(0ULL);
1836 for(Color c = WHITE; c <= BLACK; c++) {
1839 s = pop_1st_bit(&b);
1840 result ^= zobrist[c][PAWN][s];
1847 /// Position::compute_material_key() computes the hash key of the position.
1848 /// The hash key is usually updated incrementally as moves are made and unmade,
1849 /// the compute_material_key() function is only used when a new position is set
1850 /// up, and to verify the correctness of the material hash key when running in
1853 Key Position::compute_material_key() const {
1854 Key result = Key(0ULL);
1855 for(Color c = WHITE; c <= BLACK; c++)
1856 for(PieceType pt = PAWN; pt <= QUEEN; pt++) {
1857 int count = piece_count(c, pt);
1858 for(int i = 0; i <= count; i++)
1859 result ^= zobMaterial[c][pt][i];
1865 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1866 /// incremental scores for the middle game and the endgame. These functions
1867 /// are used to initialize the incremental scores when a new position is set
1868 /// up, and to verify that the scores are correctly updated by do_move
1869 /// and undo_move when the program is running in debug mode.
1871 Value Position::compute_mg_value() const {
1872 Value result = Value(0);
1876 for(Color c = WHITE; c <= BLACK; c++)
1877 for(PieceType pt = PAWN; pt <= KING; pt++) {
1878 b = pieces_of_color_and_type(c, pt);
1880 s = pop_1st_bit(&b);
1881 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1882 result += mg_pst(c, pt, s);
1885 result += (side_to_move() == WHITE)?
1886 (TempoValueMidgame / 2) : -(TempoValueMidgame / 2);
1890 Value Position::compute_eg_value() const {
1891 Value result = Value(0);
1895 for(Color c = WHITE; c <= BLACK; c++)
1896 for(PieceType pt = PAWN; pt <= KING; pt++) {
1897 b = pieces_of_color_and_type(c, pt);
1899 s = pop_1st_bit(&b);
1900 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1901 result += eg_pst(c, pt, s);
1904 result += (side_to_move() == WHITE)?
1905 (TempoValueEndgame / 2) : -(TempoValueEndgame / 2);
1910 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1911 /// game material score for the given side. Material scores are updated
1912 /// incrementally during the search, this function is only used while
1913 /// initializing a new Position object.
1915 Value Position::compute_non_pawn_material(Color c) const {
1916 Value result = Value(0);
1919 for(PieceType pt = KNIGHT; pt <= QUEEN; pt++) {
1920 Bitboard b = pieces_of_color_and_type(c, pt);
1922 s = pop_1st_bit(&b);
1923 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1924 result += piece_value_midgame(pt);
1931 /// Position::is_mate() returns true or false depending on whether the
1932 /// side to move is checkmated. Note that this function is currently very
1933 /// slow, and shouldn't be used frequently inside the search.
1935 bool Position::is_mate() {
1937 MovePicker mp = MovePicker(*this, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1938 MOVE_NONE, Depth(0));
1939 return mp.get_next_move() == MOVE_NONE;
1946 /// Position::is_draw() tests whether the position is drawn by material,
1947 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1948 /// must be done by the search.
1950 bool Position::is_draw() const {
1951 // Draw by material?
1953 non_pawn_material(WHITE) + non_pawn_material(BLACK)
1954 <= BishopValueMidgame)
1957 // Draw by the 50 moves rule?
1958 if(rule50 > 100 || (rule50 == 100 && !is_check()))
1961 // Draw by repetition?
1962 for(int i = 2; i < Min(gamePly, rule50); i += 2)
1963 if(history[gamePly - i] == key)
1970 /// Position::has_mate_threat() tests whether a given color has a mate in one
1971 /// from the current position. This function is quite slow, but it doesn't
1972 /// matter, because it is currently only called from PV nodes, which are rare.
1974 bool Position::has_mate_threat(Color c) {
1976 Color stm = side_to_move();
1978 // The following lines are useless and silly, but prevents gcc from
1979 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1980 // be used uninitialized.
1981 u1.lastMove = lastMove;
1982 u1.epSquare = epSquare;
1987 // If the input color is not equal to the side to move, do a null move
1988 if(c != stm) do_null_move(u1);
1990 MoveStack mlist[120];
1992 bool result = false;
1994 // Generate legal moves
1995 count = generate_legal_moves(*this, mlist);
1997 // Loop through the moves, and see if one of them is mate.
1998 for(int i = 0; i < count; i++) {
1999 do_move(mlist[i].move, u2);
2000 if(is_mate()) result = true;
2001 undo_move(mlist[i].move, u2);
2004 // Undo null move, if necessary
2005 if(c != stm) undo_null_move(u1);
2011 /// Position::init_zobrist() is a static member function which initializes the
2012 /// various arrays used to compute hash keys.
2014 void Position::init_zobrist() {
2016 for(int i = 0; i < 2; i++)
2017 for(int j = 0; j < 8; j++)
2018 for(int k = 0; k < 64; k++)
2019 zobrist[i][j][k] = Key(genrand_int64());
2021 for(int i = 0; i < 64; i++)
2022 zobEp[i] = Key(genrand_int64());
2024 for(int i = 0; i < 16; i++)
2025 zobCastle[i] = genrand_int64();
2027 zobSideToMove = genrand_int64();
2029 for(int i = 0; i < 2; i++)
2030 for(int j = 0; j < 8; j++)
2031 for(int k = 0; k < 16; k++)
2032 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2034 for(int i = 0; i < 16; i++)
2035 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2039 /// Position::init_piece_square_tables() initializes the piece square tables.
2040 /// This is a two-step operation: First, the white halves of the tables are
2041 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2042 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2043 /// Second, the black halves of the tables are initialized by mirroring
2044 /// and changing the sign of the corresponding white scores.
2046 void Position::init_piece_square_tables() {
2047 int r = get_option_value_int("Randomness"), i;
2048 for(Square s = SQ_A1; s <= SQ_H8; s++) {
2049 for(Piece p = WP; p <= WK; p++) {
2050 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2051 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2052 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2055 for(Square s = SQ_A1; s <= SQ_H8; s++)
2056 for(Piece p = BP; p <= BK; p++) {
2057 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2058 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2063 /// Position::flipped_copy() makes a copy of the input position, but with
2064 /// the white and black sides reversed. This is only useful for debugging,
2065 /// especially for finding evaluation symmetry bugs.
2067 void Position::flipped_copy(const Position &pos) {
2068 assert(pos.is_ok());
2073 for(Square s = SQ_A1; s <= SQ_H8; s++)
2074 if(!pos.square_is_empty(s))
2075 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2078 sideToMove = opposite_color(pos.side_to_move());
2081 if(pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2082 if(pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2083 if(pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2084 if(pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2086 initialKFile = pos.initialKFile;
2087 initialKRFile = pos.initialKRFile;
2088 initialQRFile = pos.initialQRFile;
2090 for(Square sq = SQ_A1; sq <= SQ_H8; sq++)
2091 castleRightsMask[sq] = ALL_CASTLES;
2092 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
2093 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
2094 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2095 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2096 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2097 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2099 // En passant square
2100 if(pos.epSquare != SQ_NONE)
2101 epSquare = flip_square(pos.epSquare);
2107 key = compute_key();
2108 pawnKey = compute_pawn_key();
2109 materialKey = compute_material_key();
2111 // Incremental scores
2112 mgValue = compute_mg_value();
2113 egValue = compute_eg_value();
2116 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2117 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2123 /// Position::is_ok() performs some consitency checks for the position object.
2124 /// This is meant to be helpful when debugging.
2126 bool Position::is_ok(int* failedStep) const {
2128 // What features of the position should be verified?
2129 static const bool debugBitboards = false;
2130 static const bool debugKingCount = false;
2131 static const bool debugKingCapture = false;
2132 static const bool debugCheckerCount = false;
2133 static const bool debugKey = false;
2134 static const bool debugMaterialKey = false;
2135 static const bool debugPawnKey = false;
2136 static const bool debugIncrementalEval = false;
2137 static const bool debugNonPawnMaterial = false;
2138 static const bool debugPieceCounts = false;
2139 static const bool debugPieceList = false;
2141 if (failedStep) *failedStep = 1;
2144 if(!color_is_ok(side_to_move()))
2147 // Are the king squares in the position correct?
2148 if (failedStep) (*failedStep)++;
2149 if(piece_on(king_square(WHITE)) != WK)
2152 if (failedStep) (*failedStep)++;
2153 if(piece_on(king_square(BLACK)) != BK)
2157 if (failedStep) (*failedStep)++;
2158 if(!file_is_ok(initialKRFile))
2160 if(!file_is_ok(initialQRFile))
2163 // Do both sides have exactly one king?
2164 if (failedStep) (*failedStep)++;
2165 if(debugKingCount) {
2166 int kingCount[2] = {0, 0};
2167 for(Square s = SQ_A1; s <= SQ_H8; s++)
2168 if(type_of_piece_on(s) == KING)
2169 kingCount[color_of_piece_on(s)]++;
2170 if(kingCount[0] != 1 || kingCount[1] != 1)
2174 // Can the side to move capture the opponent's king?
2175 if (failedStep) (*failedStep)++;
2176 if(debugKingCapture) {
2177 Color us = side_to_move();
2178 Color them = opposite_color(us);
2179 Square ksq = king_square(them);
2180 if(square_is_attacked(ksq, us))
2184 // Is there more than 2 checkers?
2185 if (failedStep) (*failedStep)++;
2186 if(debugCheckerCount && count_1s(checkersBB) > 2)
2190 if (failedStep) (*failedStep)++;
2191 if(debugBitboards) {
2192 // The intersection of the white and black pieces must be empty:
2193 if((pieces_of_color(WHITE) & pieces_of_color(BLACK))
2197 // The union of the white and black pieces must be equal to all
2198 // occupied squares:
2199 if((pieces_of_color(WHITE) | pieces_of_color(BLACK))
2200 != occupied_squares())
2203 // Separate piece type bitboards must have empty intersections:
2204 for(PieceType p1 = PAWN; p1 <= KING; p1++)
2205 for(PieceType p2 = PAWN; p2 <= KING; p2++)
2206 if(p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2210 // En passant square OK?
2211 if (failedStep) (*failedStep)++;
2212 if(ep_square() != SQ_NONE) {
2213 // The en passant square must be on rank 6, from the point of view of the
2215 if(relative_rank(side_to_move(), ep_square()) != RANK_6)
2220 if (failedStep) (*failedStep)++;
2221 if(debugKey && key != compute_key())
2224 // Pawn hash key OK?
2225 if (failedStep) (*failedStep)++;
2226 if(debugPawnKey && pawnKey != compute_pawn_key())
2229 // Material hash key OK?
2230 if (failedStep) (*failedStep)++;
2231 if(debugMaterialKey && materialKey != compute_material_key())
2234 // Incremental eval OK?
2235 if (failedStep) (*failedStep)++;
2236 if(debugIncrementalEval) {
2237 if(mgValue != compute_mg_value())
2239 if(egValue != compute_eg_value())
2243 // Non-pawn material OK?
2244 if (failedStep) (*failedStep)++;
2245 if(debugNonPawnMaterial) {
2246 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2248 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2253 if (failedStep) (*failedStep)++;
2254 if(debugPieceCounts)
2255 for(Color c = WHITE; c <= BLACK; c++)
2256 for(PieceType pt = PAWN; pt <= KING; pt++)
2257 if(pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2260 if (failedStep) (*failedStep)++;
2261 if(debugPieceList) {
2262 for(Color c = WHITE; c <= BLACK; c++)
2263 for(PieceType pt = PAWN; pt <= KING; pt++)
2264 for(int i = 0; i < pieceCount[c][pt]; i++) {
2265 if(piece_on(piece_list(c, pt, i)) !=
2266 piece_of_color_and_type(c, pt))
2268 if(index[piece_list(c, pt, i)] != i)
2272 if (failedStep) *failedStep = 0;