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/>.
36 #include "ucioption.h"
43 extern SearchStack EmptySearchStack;
45 int Position::castleRightsMask[64];
47 Key Position::zobrist[2][8][64];
48 Key Position::zobEp[64];
49 Key Position::zobCastle[16];
50 Key Position::zobMaterial[2][8][16];
51 Key Position::zobSideToMove;
53 Value Position::MgPieceSquareTable[16][64];
54 Value Position::EgPieceSquareTable[16][64];
56 static bool RequestPending = false;
64 Position::Position(const Position& pos) {
68 Position::Position(const std::string& fen) {
73 /// Position::from_fen() initializes the position object with the given FEN
74 /// string. This function is not very robust - make sure that input FENs are
75 /// correct (this is assumed to be the responsibility of the GUI).
77 void Position::from_fen(const std::string& fen) {
79 static const std::string pieceLetters = "KQRBNPkqrbnp";
80 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
88 for ( ; fen[i] != ' '; i++)
92 // Skip the given number of files
93 file += (fen[i] - '1' + 1);
96 else if (fen[i] == '/')
102 size_t idx = pieceLetters.find(fen[i]);
103 if (idx == std::string::npos)
105 std::cout << "Error in FEN at character " << i << std::endl;
108 Square square = make_square(file, rank);
109 put_piece(pieces[idx], square);
115 if (fen[i] != 'w' && fen[i] != 'b')
117 std::cout << "Error in FEN at character " << i << std::endl;
120 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
126 std::cout << "Error in FEN at character " << i << std::endl;
131 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
137 else if(fen[i] == 'K') allow_oo(WHITE);
138 else if(fen[i] == 'Q') allow_ooo(WHITE);
139 else if(fen[i] == 'k') allow_oo(BLACK);
140 else if(fen[i] == 'q') allow_ooo(BLACK);
141 else if(fen[i] >= 'A' && fen[i] <= 'H') {
142 File rookFile, kingFile = FILE_NONE;
143 for(Square square = SQ_B1; square <= SQ_G1; square++)
144 if(piece_on(square) == WK)
145 kingFile = square_file(square);
146 if(kingFile == FILE_NONE) {
147 std::cout << "Error in FEN at character " << i << std::endl;
150 initialKFile = kingFile;
151 rookFile = File(fen[i] - 'A') + FILE_A;
152 if(rookFile < initialKFile) {
154 initialQRFile = rookFile;
158 initialKRFile = rookFile;
161 else if(fen[i] >= 'a' && fen[i] <= 'h') {
162 File rookFile, kingFile = FILE_NONE;
163 for(Square square = SQ_B8; square <= SQ_G8; square++)
164 if(piece_on(square) == BK)
165 kingFile = square_file(square);
166 if(kingFile == FILE_NONE) {
167 std::cout << "Error in FEN at character " << i << std::endl;
170 initialKFile = kingFile;
171 rookFile = File(fen[i] - 'a') + FILE_A;
172 if(rookFile < initialKFile) {
174 initialQRFile = rookFile;
178 initialKRFile = rookFile;
182 std::cout << "Error in FEN at character " << i << std::endl;
189 while (fen[i] == ' ')
193 if ( i < fen.length() - 2
194 && (fen[i] >= 'a' && fen[i] <= 'h')
195 && (fen[i+1] == '3' || fen[i+1] == '6'))
196 st->epSquare = square_from_string(fen.substr(i, 2));
198 // Various initialisation
199 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
200 castleRightsMask[sq] = ALL_CASTLES;
202 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
203 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
204 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
205 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
206 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
207 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
211 st->key = compute_key();
212 st->pawnKey = compute_pawn_key();
213 st->materialKey = compute_material_key();
214 st->mgValue = compute_value<MidGame>();
215 st->egValue = compute_value<EndGame>();
216 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
217 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
221 /// Position::to_fen() converts the position object to a FEN string. This is
222 /// probably only useful for debugging.
224 const std::string Position::to_fen() const {
226 static const std::string pieceLetters = " PNBRQK pnbrqk";
230 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
233 for (File file = FILE_A; file <= FILE_H; file++)
235 Square sq = make_square(file, rank);
236 if (!square_is_occupied(sq))
242 fen += (char)skip + '0';
245 fen += pieceLetters[piece_on(sq)];
248 fen += (char)skip + '0';
250 fen += (rank > RANK_1 ? '/' : ' ');
252 fen += (sideToMove == WHITE ? "w " : "b ");
253 if (st->castleRights != NO_CASTLES)
255 if (can_castle_kingside(WHITE)) fen += 'K';
256 if (can_castle_queenside(WHITE)) fen += 'Q';
257 if (can_castle_kingside(BLACK)) fen += 'k';
258 if (can_castle_queenside(BLACK)) fen += 'q';
263 if (ep_square() != SQ_NONE)
264 fen += square_to_string(ep_square());
272 /// Position::print() prints an ASCII representation of the position to
273 /// the standard output. If a move is given then also the san is print.
275 void Position::print(Move m) const {
277 static const std::string pieceLetters = " PNBRQK PNBRQK .";
279 // Check for reentrancy, as example when called from inside
280 // MovePicker that is used also here in move_to_san()
284 RequestPending = true;
286 std::cout << std::endl;
289 std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
290 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
292 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
294 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
295 for (File file = FILE_A; file <= FILE_H; file++)
297 Square sq = make_square(file, rank);
298 Piece piece = piece_on(sq);
299 if (piece == EMPTY && square_color(sq) == WHITE)
302 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
303 std::cout << '|' << col << pieceLetters[piece] << col;
305 std::cout << '|' << std::endl;
307 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
308 << "Fen is: " << to_fen() << std::endl
309 << "Key is: " << st->key << std::endl;
311 RequestPending = false;
315 /// Position::copy() creates a copy of the input position.
317 void Position::copy(const Position &pos) {
319 memcpy(this, &pos, sizeof(Position));
323 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
324 /// king) pieces for the given color and for the given pinner type. Or, when
325 /// template parameter FindPinned is false, the pieces of the given color
326 /// candidate for a discovery check against the enemy king.
327 /// Note that checkersBB bitboard must be already updated.
329 template<bool FindPinned>
330 Bitboard Position::hidden_checkers(Color c) const {
332 Bitboard pinners, result = EmptyBoardBB;
334 // Pinned pieces protect our king, dicovery checks attack
336 Square ksq = king_square(FindPinned ? c : opposite_color(c));
338 // Pinners are sliders, not checkers, that give check when
339 // candidate pinned is removed.
340 pinners = (rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
341 | (bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq]);
343 if (FindPinned && pinners)
344 pinners &= ~st->checkersBB;
348 Square s = pop_1st_bit(&pinners);
349 Bitboard b = squares_between(s, ksq) & occupied_squares();
353 if ( !(b & (b - 1)) // Only one bit set?
354 && (b & pieces_of_color(c))) // Is an our piece?
361 /// Position::attacks_to() computes a bitboard containing all pieces which
362 /// attacks a given square. There are two versions of this function: One
363 /// which finds attackers of both colors, and one which only finds the
364 /// attackers for one side.
366 Bitboard Position::attacks_to(Square s) const {
368 return (pawn_attacks(BLACK, s) & pawns(WHITE))
369 | (pawn_attacks(WHITE, s) & pawns(BLACK))
370 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
371 | (piece_attacks<ROOK>(s) & rooks_and_queens())
372 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
373 | (piece_attacks<KING>(s) & pieces_of_type(KING));
376 /// Position::piece_attacks_square() tests whether the piece on square f
377 /// attacks square t.
379 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
381 assert(square_is_ok(f));
382 assert(square_is_ok(t));
386 case WP: return pawn_attacks_square(WHITE, f, t);
387 case BP: return pawn_attacks_square(BLACK, f, t);
388 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
389 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
390 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
391 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
392 case WK: case BK: return piece_attacks_square<KING>(f, t);
399 /// Position::move_attacks_square() tests whether a move from the current
400 /// position attacks a given square.
402 bool Position::move_attacks_square(Move m, Square s) const {
404 assert(move_is_ok(m));
405 assert(square_is_ok(s));
407 Square f = move_from(m), t = move_to(m);
409 assert(square_is_occupied(f));
411 if (piece_attacks_square(piece_on(f), t, s))
414 // Move the piece and scan for X-ray attacks behind it
415 Bitboard occ = occupied_squares();
416 Color us = color_of_piece_on(f);
419 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
420 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
422 // If we have attacks we need to verify that are caused by our move
423 // and are not already existent ones.
424 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
428 /// Position::find_checkers() computes the checkersBB bitboard, which
429 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
430 /// currently works by calling Position::attacks_to, which is probably
431 /// inefficient. Consider rewriting this function to use the last move
432 /// played, like in non-bitboard versions of Glaurung.
434 void Position::find_checkers() {
436 Color us = side_to_move();
437 st->checkersBB = attacks_to(king_square(us), opposite_color(us));
441 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
443 bool Position::pl_move_is_legal(Move m) const {
445 return pl_move_is_legal(m, pinned_pieces(side_to_move()));
448 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
451 assert(move_is_ok(m));
452 assert(pinned == pinned_pieces(side_to_move()));
454 // If we're in check, all pseudo-legal moves are legal, because our
455 // check evasion generator only generates true legal moves.
459 // Castling moves are checked for legality during move generation.
460 if (move_is_castle(m))
463 Color us = side_to_move();
464 Color them = opposite_color(us);
465 Square from = move_from(m);
466 Square ksq = king_square(us);
468 assert(color_of_piece_on(from) == us);
469 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
471 // En passant captures are a tricky special case. Because they are
472 // rather uncommon, we do it simply by testing whether the king is attacked
473 // after the move is made
476 Square to = move_to(m);
477 Square capsq = make_square(square_file(to), square_rank(from));
478 Bitboard b = occupied_squares();
480 assert(to == ep_square());
481 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
482 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
483 assert(piece_on(to) == EMPTY);
486 clear_bit(&b, capsq);
489 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
490 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
493 // If the moving piece is a king, check whether the destination
494 // square is attacked by the opponent.
496 return !(square_is_attacked(move_to(m), them));
498 // A non-king move is legal if and only if it is not pinned or it
499 // is moving along the ray towards or away from the king.
500 return ( !bit_is_set(pinned, from)
501 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
505 /// Position::move_is_check() tests whether a pseudo-legal move is a check
507 bool Position::move_is_check(Move m) const {
509 Bitboard dc = discovered_check_candidates(side_to_move());
510 return move_is_check(m, dc);
513 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
516 assert(move_is_ok(m));
517 assert(dcCandidates == discovered_check_candidates(side_to_move()));
519 Color us = side_to_move();
520 Color them = opposite_color(us);
521 Square from = move_from(m);
522 Square to = move_to(m);
523 Square ksq = king_square(them);
525 assert(color_of_piece_on(from) == us);
526 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
528 // Proceed according to the type of the moving piece
529 switch (type_of_piece_on(from))
533 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
536 if ( bit_is_set(dcCandidates, from) // Discovered check?
537 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
540 if (move_promotion(m)) // Promotion with check?
542 Bitboard b = occupied_squares();
545 switch (move_promotion(m))
548 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
550 return bit_is_set(bishop_attacks_bb(to, b), ksq);
552 return bit_is_set(rook_attacks_bb(to, b), ksq);
554 return bit_is_set(queen_attacks_bb(to, b), ksq);
559 // En passant capture with check? We have already handled the case
560 // of direct checks and ordinary discovered check, the only case we
561 // need to handle is the unusual case of a discovered check through the
563 else if (move_is_ep(m))
565 Square capsq = make_square(square_file(to), square_rank(from));
566 Bitboard b = occupied_squares();
568 clear_bit(&b, capsq);
570 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
571 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
576 return bit_is_set(dcCandidates, from) // Discovered check?
577 || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
580 return bit_is_set(dcCandidates, from) // Discovered check?
581 || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
584 return bit_is_set(dcCandidates, from) // Discovered check?
585 || bit_is_set(piece_attacks<ROOK>(ksq), to); // Normal check?
588 // Discovered checks are impossible!
589 assert(!bit_is_set(dcCandidates, from));
590 return bit_is_set(piece_attacks<QUEEN>(ksq), to); // Normal check?
594 if ( bit_is_set(dcCandidates, from)
595 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
598 // Castling with check?
599 if (move_is_castle(m))
601 Square kfrom, kto, rfrom, rto;
602 Bitboard b = occupied_squares();
608 kto = relative_square(us, SQ_G1);
609 rto = relative_square(us, SQ_F1);
611 kto = relative_square(us, SQ_C1);
612 rto = relative_square(us, SQ_D1);
614 clear_bit(&b, kfrom);
615 clear_bit(&b, rfrom);
618 return bit_is_set(rook_attacks_bb(rto, b), ksq);
622 default: // NO_PIECE_TYPE
630 /// Position::move_is_capture() tests whether a move from the current
631 /// position is a capture. Move must not be MOVE_NONE.
633 bool Position::move_is_capture(Move m) const {
635 assert(m != MOVE_NONE);
637 return ( !square_is_empty(move_to(m))
638 && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
644 /// Position::update_checkers() udpates chekers info given the move. It is called
645 /// in do_move() and is faster then find_checkers().
647 template<PieceType Piece>
648 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
649 Square to, Bitboard dcCandidates) {
651 if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
652 set_bit(pCheckersBB, to);
654 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
657 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
660 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
665 /// Position::do_move() makes a move, and saves all information necessary
666 /// to a StateInfo object. The move is assumed to be legal.
667 /// Pseudo-legal moves should be filtered out before this function is called.
669 void Position::do_move(Move m, StateInfo& newSt) {
671 do_move(m, newSt, discovered_check_candidates(side_to_move()));
674 void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
677 assert(move_is_ok(m));
679 // Copy some fields of old state to our new StateInfo object except the
680 // ones which are recalculated from scratch anyway, then switch our state
681 // pointer to point to the new, ready to be updated, state.
682 struct ReducedStateInfo {
683 Key key, pawnKey, materialKey;
684 int castleRights, rule50;
686 Value mgValue, egValue;
689 memcpy(&newSt, st, sizeof(ReducedStateInfo));
690 newSt.capture = NO_PIECE_TYPE;
694 // Save the current key to the history[] array, in order to be able to
695 // detect repetition draws.
696 history[gamePly] = st->key;
698 // Increment the 50 moves rule draw counter. Resetting it to zero in the
699 // case of non-reversible moves is taken care of later.
702 if (move_is_castle(m))
704 else if (move_promotion(m))
705 do_promotion_move(m);
706 else if (move_is_ep(m))
710 Color us = side_to_move();
711 Color them = opposite_color(us);
712 Square from = move_from(m);
713 Square to = move_to(m);
715 assert(color_of_piece_on(from) == us);
716 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
718 PieceType piece = type_of_piece_on(from);
720 st->capture = type_of_piece_on(to);
723 do_capture_move(m, st->capture, them, to);
726 clear_bit(&(byColorBB[us]), from);
727 clear_bit(&(byTypeBB[piece]), from);
728 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
729 set_bit(&(byColorBB[us]), to);
730 set_bit(&(byTypeBB[piece]), to);
731 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
732 board[to] = board[from];
736 st->key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
738 // Update incremental scores
739 st->mgValue -= pst<MidGame>(us, piece, from);
740 st->mgValue += pst<MidGame>(us, piece, to);
741 st->egValue -= pst<EndGame>(us, piece, from);
742 st->egValue += pst<EndGame>(us, piece, to);
744 // If the moving piece was a king, update the king square
748 // Reset en passant square
749 if (st->epSquare != SQ_NONE)
751 st->key ^= zobEp[st->epSquare];
752 st->epSquare = SQ_NONE;
755 // If the moving piece was a pawn do some special extra work
758 // Reset rule 50 draw counter
761 // Update pawn hash key
762 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
764 // Set en passant square, only if moved pawn can be captured
765 if (abs(int(to) - int(from)) == 16)
767 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
768 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
770 st->epSquare = Square((int(from) + int(to)) / 2);
771 st->key ^= zobEp[st->epSquare];
776 // Update piece lists
777 pieceList[us][piece][index[from]] = to;
778 index[to] = index[from];
780 // Update castle rights
781 st->key ^= zobCastle[st->castleRights];
782 st->castleRights &= castleRightsMask[from];
783 st->castleRights &= castleRightsMask[to];
784 st->key ^= zobCastle[st->castleRights];
786 // Update checkers bitboard, piece must be already moved
787 st->checkersBB = EmptyBoardBB;
788 Square ksq = king_square(them);
791 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
792 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
793 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
794 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
795 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
796 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
797 default: assert(false); break;
802 st->key ^= zobSideToMove;
803 sideToMove = opposite_color(sideToMove);
806 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
807 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
813 /// Position::do_capture_move() is a private method used to update captured
814 /// piece info. It is called from the main Position::do_move function.
816 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
818 assert(capture != KING);
820 // Remove captured piece
821 clear_bit(&(byColorBB[them]), to);
822 clear_bit(&(byTypeBB[capture]), to);
825 st->key ^= zobrist[them][capture][to];
827 // If the captured piece was a pawn, update pawn hash key
829 st->pawnKey ^= zobrist[them][PAWN][to];
831 // Update incremental scores
832 st->mgValue -= pst<MidGame>(them, capture, to);
833 st->egValue -= pst<EndGame>(them, capture, to);
835 assert(!move_promotion(m) || capture != PAWN);
839 npMaterial[them] -= piece_value_midgame(capture);
841 // Update material hash key
842 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
844 // Update piece count
845 pieceCount[them][capture]--;
848 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
849 index[pieceList[them][capture][index[to]]] = index[to];
851 // Reset rule 50 counter
856 /// Position::do_castle_move() is a private method used to make a castling
857 /// move. It is called from the main Position::do_move function. Note that
858 /// castling moves are encoded as "king captures friendly rook" moves, for
859 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
861 void Position::do_castle_move(Move m) {
864 assert(move_is_ok(m));
865 assert(move_is_castle(m));
867 Color us = side_to_move();
868 Color them = opposite_color(us);
870 // Find source squares for king and rook
871 Square kfrom = move_from(m);
872 Square rfrom = move_to(m); // HACK: See comment at beginning of function
875 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
876 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
878 // Find destination squares for king and rook
879 if (rfrom > kfrom) // O-O
881 kto = relative_square(us, SQ_G1);
882 rto = relative_square(us, SQ_F1);
884 kto = relative_square(us, SQ_C1);
885 rto = relative_square(us, SQ_D1);
888 // Remove pieces from source squares
889 clear_bit(&(byColorBB[us]), kfrom);
890 clear_bit(&(byTypeBB[KING]), kfrom);
891 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
892 clear_bit(&(byColorBB[us]), rfrom);
893 clear_bit(&(byTypeBB[ROOK]), rfrom);
894 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
896 // Put pieces on destination squares
897 set_bit(&(byColorBB[us]), kto);
898 set_bit(&(byTypeBB[KING]), kto);
899 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
900 set_bit(&(byColorBB[us]), rto);
901 set_bit(&(byTypeBB[ROOK]), rto);
902 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
904 // Update board array
905 board[kfrom] = board[rfrom] = EMPTY;
906 board[kto] = piece_of_color_and_type(us, KING);
907 board[rto] = piece_of_color_and_type(us, ROOK);
909 // Update king square
910 kingSquare[us] = kto;
912 // Update piece lists
913 pieceList[us][KING][index[kfrom]] = kto;
914 pieceList[us][ROOK][index[rfrom]] = rto;
915 int tmp = index[rfrom];
916 index[kto] = index[kfrom];
919 // Update incremental scores
920 st->mgValue -= pst<MidGame>(us, KING, kfrom);
921 st->mgValue += pst<MidGame>(us, KING, kto);
922 st->egValue -= pst<EndGame>(us, KING, kfrom);
923 st->egValue += pst<EndGame>(us, KING, kto);
924 st->mgValue -= pst<MidGame>(us, ROOK, rfrom);
925 st->mgValue += pst<MidGame>(us, ROOK, rto);
926 st->egValue -= pst<EndGame>(us, ROOK, rfrom);
927 st->egValue += pst<EndGame>(us, ROOK, rto);
930 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
931 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
933 // Clear en passant square
934 if (st->epSquare != SQ_NONE)
936 st->key ^= zobEp[st->epSquare];
937 st->epSquare = SQ_NONE;
940 // Update castling rights
941 st->key ^= zobCastle[st->castleRights];
942 st->castleRights &= castleRightsMask[kfrom];
943 st->key ^= zobCastle[st->castleRights];
945 // Reset rule 50 counter
948 // Update checkers BB
949 st->checkersBB = attacks_to(king_square(them), us);
953 /// Position::do_promotion_move() is a private method used to make a promotion
954 /// move. It is called from the main Position::do_move function.
956 void Position::do_promotion_move(Move m) {
963 assert(move_is_ok(m));
964 assert(move_promotion(m));
967 them = opposite_color(us);
971 assert(relative_rank(us, to) == RANK_8);
972 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
973 assert(color_of_piece_on(to) == them || square_is_empty(to));
975 st->capture = type_of_piece_on(to);
978 do_capture_move(m, st->capture, them, to);
981 clear_bit(&(byColorBB[us]), from);
982 clear_bit(&(byTypeBB[PAWN]), from);
983 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
986 // Insert promoted piece
987 promotion = move_promotion(m);
988 assert(promotion >= KNIGHT && promotion <= QUEEN);
989 set_bit(&(byColorBB[us]), to);
990 set_bit(&(byTypeBB[promotion]), to);
991 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
992 board[to] = piece_of_color_and_type(us, promotion);
995 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
997 // Update pawn hash key
998 st->pawnKey ^= zobrist[us][PAWN][from];
1000 // Update material key
1001 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1002 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1004 // Update piece counts
1005 pieceCount[us][PAWN]--;
1006 pieceCount[us][promotion]++;
1008 // Update piece lists
1009 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1010 index[pieceList[us][PAWN][index[from]]] = index[from];
1011 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1012 index[to] = pieceCount[us][promotion] - 1;
1014 // Update incremental scores
1015 st->mgValue -= pst<MidGame>(us, PAWN, from);
1016 st->mgValue += pst<MidGame>(us, promotion, to);
1017 st->egValue -= pst<EndGame>(us, PAWN, from);
1018 st->egValue += pst<EndGame>(us, promotion, to);
1021 npMaterial[us] += piece_value_midgame(promotion);
1023 // Clear the en passant square
1024 if (st->epSquare != SQ_NONE)
1026 st->key ^= zobEp[st->epSquare];
1027 st->epSquare = SQ_NONE;
1030 // Update castle rights
1031 st->key ^= zobCastle[st->castleRights];
1032 st->castleRights &= castleRightsMask[to];
1033 st->key ^= zobCastle[st->castleRights];
1035 // Reset rule 50 counter
1038 // Update checkers BB
1039 st->checkersBB = attacks_to(king_square(them), us);
1043 /// Position::do_ep_move() is a private method used to make an en passant
1044 /// capture. It is called from the main Position::do_move function.
1046 void Position::do_ep_move(Move m) {
1049 Square from, to, capsq;
1052 assert(move_is_ok(m));
1053 assert(move_is_ep(m));
1055 us = side_to_move();
1056 them = opposite_color(us);
1057 from = move_from(m);
1059 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1061 assert(to == st->epSquare);
1062 assert(relative_rank(us, to) == RANK_6);
1063 assert(piece_on(to) == EMPTY);
1064 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1065 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1067 // Remove captured piece
1068 clear_bit(&(byColorBB[them]), capsq);
1069 clear_bit(&(byTypeBB[PAWN]), capsq);
1070 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1071 board[capsq] = EMPTY;
1073 // Remove moving piece from source square
1074 clear_bit(&(byColorBB[us]), from);
1075 clear_bit(&(byTypeBB[PAWN]), from);
1076 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1078 // Put moving piece on destination square
1079 set_bit(&(byColorBB[us]), to);
1080 set_bit(&(byTypeBB[PAWN]), to);
1081 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1082 board[to] = board[from];
1083 board[from] = EMPTY;
1085 // Update material hash key
1086 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1088 // Update piece count
1089 pieceCount[them][PAWN]--;
1091 // Update piece list
1092 pieceList[us][PAWN][index[from]] = to;
1093 index[to] = index[from];
1094 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1095 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1098 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1099 st->key ^= zobrist[them][PAWN][capsq];
1100 st->key ^= zobEp[st->epSquare];
1102 // Update pawn hash key
1103 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1104 st->pawnKey ^= zobrist[them][PAWN][capsq];
1106 // Update incremental scores
1107 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1108 st->mgValue -= pst<MidGame>(us, PAWN, from);
1109 st->mgValue += pst<MidGame>(us, PAWN, to);
1110 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1111 st->egValue -= pst<EndGame>(us, PAWN, from);
1112 st->egValue += pst<EndGame>(us, PAWN, to);
1114 // Reset en passant square
1115 st->epSquare = SQ_NONE;
1117 // Reset rule 50 counter
1120 // Update checkers BB
1121 st->checkersBB = attacks_to(king_square(them), us);
1125 /// Position::undo_move() unmakes a move. When it returns, the position should
1126 /// be restored to exactly the same state as before the move was made.
1128 void Position::undo_move(Move m) {
1131 assert(move_is_ok(m));
1134 sideToMove = opposite_color(sideToMove);
1136 if (move_is_castle(m))
1137 undo_castle_move(m);
1138 else if (move_promotion(m))
1139 undo_promotion_move(m);
1140 else if (move_is_ep(m))
1148 us = side_to_move();
1149 them = opposite_color(us);
1150 from = move_from(m);
1153 assert(piece_on(from) == EMPTY);
1154 assert(color_of_piece_on(to) == us);
1156 // Put the piece back at the source square
1157 piece = type_of_piece_on(to);
1158 set_bit(&(byColorBB[us]), from);
1159 set_bit(&(byTypeBB[piece]), from);
1160 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1161 board[from] = piece_of_color_and_type(us, piece);
1163 // Clear the destination square
1164 clear_bit(&(byColorBB[us]), to);
1165 clear_bit(&(byTypeBB[piece]), to);
1166 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1168 // If the moving piece was a king, update the king square
1170 kingSquare[us] = from;
1172 // Update piece list
1173 pieceList[us][piece][index[to]] = from;
1174 index[from] = index[to];
1178 assert(st->capture != KING);
1180 // Replace the captured piece
1181 set_bit(&(byColorBB[them]), to);
1182 set_bit(&(byTypeBB[st->capture]), to);
1183 set_bit(&(byTypeBB[0]), to);
1184 board[to] = piece_of_color_and_type(them, st->capture);
1187 if (st->capture != PAWN)
1188 npMaterial[them] += piece_value_midgame(st->capture);
1190 // Update piece list
1191 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1192 index[to] = pieceCount[them][st->capture];
1194 // Update piece count
1195 pieceCount[them][st->capture]++;
1200 // Finally point out state pointer back to the previous state
1207 /// Position::undo_castle_move() is a private method used to unmake a castling
1208 /// move. It is called from the main Position::undo_move function. Note that
1209 /// castling moves are encoded as "king captures friendly rook" moves, for
1210 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1212 void Position::undo_castle_move(Move m) {
1214 assert(move_is_ok(m));
1215 assert(move_is_castle(m));
1217 // When we have arrived here, some work has already been done by
1218 // Position::undo_move. In particular, the side to move has been switched,
1219 // so the code below is correct.
1220 Color us = side_to_move();
1222 // Find source squares for king and rook
1223 Square kfrom = move_from(m);
1224 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1227 // Find destination squares for king and rook
1228 if (rfrom > kfrom) // O-O
1230 kto = relative_square(us, SQ_G1);
1231 rto = relative_square(us, SQ_F1);
1233 kto = relative_square(us, SQ_C1);
1234 rto = relative_square(us, SQ_D1);
1237 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1238 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1240 // Remove pieces from destination squares
1241 clear_bit(&(byColorBB[us]), kto);
1242 clear_bit(&(byTypeBB[KING]), kto);
1243 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1244 clear_bit(&(byColorBB[us]), rto);
1245 clear_bit(&(byTypeBB[ROOK]), rto);
1246 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1248 // Put pieces on source squares
1249 set_bit(&(byColorBB[us]), kfrom);
1250 set_bit(&(byTypeBB[KING]), kfrom);
1251 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1252 set_bit(&(byColorBB[us]), rfrom);
1253 set_bit(&(byTypeBB[ROOK]), rfrom);
1254 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1257 board[rto] = board[kto] = EMPTY;
1258 board[rfrom] = piece_of_color_and_type(us, ROOK);
1259 board[kfrom] = piece_of_color_and_type(us, KING);
1261 // Update king square
1262 kingSquare[us] = kfrom;
1264 // Update piece lists
1265 pieceList[us][KING][index[kto]] = kfrom;
1266 pieceList[us][ROOK][index[rto]] = rfrom;
1267 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1268 index[kfrom] = index[kto];
1273 /// Position::undo_promotion_move() is a private method used to unmake a
1274 /// promotion move. It is called from the main Position::do_move
1277 void Position::undo_promotion_move(Move m) {
1281 PieceType promotion;
1283 assert(move_is_ok(m));
1284 assert(move_promotion(m));
1286 // When we have arrived here, some work has already been done by
1287 // Position::undo_move. In particular, the side to move has been switched,
1288 // so the code below is correct.
1289 us = side_to_move();
1290 them = opposite_color(us);
1291 from = move_from(m);
1294 assert(relative_rank(us, to) == RANK_8);
1295 assert(piece_on(from) == EMPTY);
1297 // Remove promoted piece
1298 promotion = move_promotion(m);
1299 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1300 assert(promotion >= KNIGHT && promotion <= QUEEN);
1301 clear_bit(&(byColorBB[us]), to);
1302 clear_bit(&(byTypeBB[promotion]), to);
1303 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1305 // Insert pawn at source square
1306 set_bit(&(byColorBB[us]), from);
1307 set_bit(&(byTypeBB[PAWN]), from);
1308 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1309 board[from] = piece_of_color_and_type(us, PAWN);
1312 npMaterial[us] -= piece_value_midgame(promotion);
1314 // Update piece list
1315 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1316 index[from] = pieceCount[us][PAWN];
1317 pieceList[us][promotion][index[to]] =
1318 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1319 index[pieceList[us][promotion][index[to]]] = index[to];
1321 // Update piece counts
1322 pieceCount[us][promotion]--;
1323 pieceCount[us][PAWN]++;
1327 assert(st->capture != KING);
1329 // Insert captured piece:
1330 set_bit(&(byColorBB[them]), to);
1331 set_bit(&(byTypeBB[st->capture]), to);
1332 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1333 board[to] = piece_of_color_and_type(them, st->capture);
1335 // Update material. Because the move is a promotion move, we know
1336 // that the captured piece cannot be a pawn.
1337 assert(st->capture != PAWN);
1338 npMaterial[them] += piece_value_midgame(st->capture);
1340 // Update piece list
1341 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1342 index[to] = pieceCount[them][st->capture];
1344 // Update piece count
1345 pieceCount[them][st->capture]++;
1351 /// Position::undo_ep_move() is a private method used to unmake an en passant
1352 /// capture. It is called from the main Position::undo_move function.
1354 void Position::undo_ep_move(Move m) {
1356 assert(move_is_ok(m));
1357 assert(move_is_ep(m));
1359 // When we have arrived here, some work has already been done by
1360 // Position::undo_move. In particular, the side to move has been switched,
1361 // so the code below is correct.
1362 Color us = side_to_move();
1363 Color them = opposite_color(us);
1364 Square from = move_from(m);
1365 Square to = move_to(m);
1366 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1368 assert(to == st->previous->epSquare);
1369 assert(relative_rank(us, to) == RANK_6);
1370 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1371 assert(piece_on(from) == EMPTY);
1372 assert(piece_on(capsq) == EMPTY);
1374 // Replace captured piece
1375 set_bit(&(byColorBB[them]), capsq);
1376 set_bit(&(byTypeBB[PAWN]), capsq);
1377 set_bit(&(byTypeBB[0]), capsq);
1378 board[capsq] = piece_of_color_and_type(them, PAWN);
1380 // Remove moving piece from destination square
1381 clear_bit(&(byColorBB[us]), to);
1382 clear_bit(&(byTypeBB[PAWN]), to);
1383 clear_bit(&(byTypeBB[0]), to);
1386 // Replace moving piece at source square
1387 set_bit(&(byColorBB[us]), from);
1388 set_bit(&(byTypeBB[PAWN]), from);
1389 set_bit(&(byTypeBB[0]), from);
1390 board[from] = piece_of_color_and_type(us, PAWN);
1392 // Update piece list:
1393 pieceList[us][PAWN][index[to]] = from;
1394 index[from] = index[to];
1395 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1396 index[capsq] = pieceCount[them][PAWN];
1398 // Update piece count:
1399 pieceCount[them][PAWN]++;
1403 /// Position::do_null_move makes() a "null move": It switches the side to move
1404 /// and updates the hash key without executing any move on the board.
1406 void Position::do_null_move(StateInfo& newSt) {
1409 assert(!is_check());
1411 // Back up the information necessary to undo the null move to the supplied
1412 // StateInfo object. In the case of a null move, the only thing we need to
1413 // remember is the last move made and the en passant square.
1414 newSt.lastMove = st->lastMove;
1415 newSt.epSquare = st->epSquare;
1416 newSt.previous = st->previous;
1417 st->previous = &newSt;
1419 // Save the current key to the history[] array, in order to be able to
1420 // detect repetition draws.
1421 history[gamePly] = st->key;
1423 // Update the necessary information
1424 sideToMove = opposite_color(sideToMove);
1425 if (st->epSquare != SQ_NONE)
1426 st->key ^= zobEp[st->epSquare];
1428 st->epSquare = SQ_NONE;
1431 st->key ^= zobSideToMove;
1433 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1434 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1440 /// Position::undo_null_move() unmakes a "null move".
1442 void Position::undo_null_move() {
1445 assert(!is_check());
1447 // Restore information from the our StateInfo object
1448 st->lastMove = st->previous->lastMove;
1449 st->epSquare = st->previous->epSquare;
1450 st->previous = st->previous->previous;
1452 if (st->epSquare != SQ_NONE)
1453 st->key ^= zobEp[st->epSquare];
1455 // Update the necessary information
1456 sideToMove = opposite_color(sideToMove);
1459 st->key ^= zobSideToMove;
1461 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1462 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1468 /// Position::see() is a static exchange evaluator: It tries to estimate the
1469 /// material gain or loss resulting from a move. There are three versions of
1470 /// this function: One which takes a destination square as input, one takes a
1471 /// move, and one which takes a 'from' and a 'to' square. The function does
1472 /// not yet understand promotions captures.
1474 int Position::see(Square to) const {
1476 assert(square_is_ok(to));
1477 return see(SQ_NONE, to);
1480 int Position::see(Move m) const {
1482 assert(move_is_ok(m));
1483 return see(move_from(m), move_to(m));
1486 int Position::see(Square from, Square to) const {
1489 static const int seeValues[18] = {
1490 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1491 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1492 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1493 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1497 Bitboard attackers, occ, b;
1499 assert(square_is_ok(from) || from == SQ_NONE);
1500 assert(square_is_ok(to));
1502 // Initialize colors
1503 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1504 Color them = opposite_color(us);
1506 // Initialize pieces
1507 Piece piece = piece_on(from);
1508 Piece capture = piece_on(to);
1510 // Find all attackers to the destination square, with the moving piece
1511 // removed, but possibly an X-ray attacker added behind it.
1512 occ = occupied_squares();
1514 // Handle en passant moves
1515 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1517 assert(capture == EMPTY);
1519 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1520 capture = piece_on(capQq);
1522 assert(type_of_piece_on(capQq) == PAWN);
1524 // Remove the captured pawn
1525 clear_bit(&occ, capQq);
1530 clear_bit(&occ, from);
1531 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1532 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1533 | (piece_attacks<KNIGHT>(to) & knights())
1534 | (piece_attacks<KING>(to) & kings())
1535 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1536 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1538 if (from != SQ_NONE)
1541 // If we don't have any attacker we are finished
1542 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1545 // Locate the least valuable attacker to the destination square
1546 // and use it to initialize from square.
1548 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1551 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1552 piece = piece_on(from);
1555 // If the opponent has no attackers we are finished
1556 if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1557 return seeValues[capture];
1559 attackers &= occ; // Remove the moving piece
1561 // The destination square is defended, which makes things rather more
1562 // difficult to compute. We proceed by building up a "swap list" containing
1563 // the material gain or loss at each stop in a sequence of captures to the
1564 // destination square, where the sides alternately capture, and always
1565 // capture with the least valuable piece. After each capture, we look for
1566 // new X-ray attacks from behind the capturing piece.
1567 int lastCapturingPieceValue = seeValues[piece];
1568 int swapList[32], n = 1;
1572 swapList[0] = seeValues[capture];
1575 // Locate the least valuable attacker for the side to move. The loop
1576 // below looks like it is potentially infinite, but it isn't. We know
1577 // that the side to move still has at least one attacker left.
1578 for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1581 // Remove the attacker we just found from the 'attackers' bitboard,
1582 // and scan for new X-ray attacks behind the attacker.
1583 b = attackers & pieces_of_color_and_type(c, pt);
1585 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1586 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1590 // Add the new entry to the swap list
1592 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1595 // Remember the value of the capturing piece, and change the side to move
1596 // before beginning the next iteration
1597 lastCapturingPieceValue = seeValues[pt];
1598 c = opposite_color(c);
1600 // Stop after a king capture
1601 if (pt == KING && (attackers & pieces_of_color(c)))
1604 swapList[n++] = 100;
1607 } while (attackers & pieces_of_color(c));
1609 // Having built the swap list, we negamax through it to find the best
1610 // achievable score from the point of view of the side to move
1612 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1618 /// Position::setStartState() copies the content of the argument
1619 /// inside startState and makes st point to it. This is needed
1620 /// when the st pointee could become stale, as example because
1621 /// the caller is about to going out of scope.
1623 void Position::setStartState(const StateInfo& s) {
1630 /// Position::clear() erases the position object to a pristine state, with an
1631 /// empty board, white to move, and no castling rights.
1633 void Position::clear() {
1636 memset(st, 0, sizeof(StateInfo));
1637 st->epSquare = SQ_NONE;
1639 memset(index, 0, sizeof(int) * 64);
1640 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1642 for (int i = 0; i < 64; i++)
1645 for (int i = 0; i < 7; i++)
1647 byTypeBB[i] = EmptyBoardBB;
1648 pieceCount[0][i] = pieceCount[1][i] = 0;
1649 for (int j = 0; j < 8; j++)
1650 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1655 initialKFile = FILE_E;
1656 initialKRFile = FILE_H;
1657 initialQRFile = FILE_A;
1661 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1662 /// UCI interface code, whenever a non-reversible move is made in a
1663 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1664 /// for the program to handle games of arbitrary length, as long as the GUI
1665 /// handles draws by the 50 move rule correctly.
1667 void Position::reset_game_ply() {
1673 /// Position::put_piece() puts a piece on the given square of the board,
1674 /// updating the board array, bitboards, and piece counts.
1676 void Position::put_piece(Piece p, Square s) {
1678 Color c = color_of_piece(p);
1679 PieceType pt = type_of_piece(p);
1682 index[s] = pieceCount[c][pt];
1683 pieceList[c][pt][index[s]] = s;
1685 set_bit(&(byTypeBB[pt]), s);
1686 set_bit(&(byColorBB[c]), s);
1687 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1689 pieceCount[c][pt]++;
1696 /// Position::allow_oo() gives the given side the right to castle kingside.
1697 /// Used when setting castling rights during parsing of FEN strings.
1699 void Position::allow_oo(Color c) {
1701 st->castleRights |= (1 + int(c));
1705 /// Position::allow_ooo() gives the given side the right to castle queenside.
1706 /// Used when setting castling rights during parsing of FEN strings.
1708 void Position::allow_ooo(Color c) {
1710 st->castleRights |= (4 + 4*int(c));
1714 /// Position::compute_key() computes the hash key of the position. The hash
1715 /// key is usually updated incrementally as moves are made and unmade, the
1716 /// compute_key() function is only used when a new position is set up, and
1717 /// to verify the correctness of the hash key when running in debug mode.
1719 Key Position::compute_key() const {
1721 Key result = Key(0ULL);
1723 for (Square s = SQ_A1; s <= SQ_H8; s++)
1724 if (square_is_occupied(s))
1725 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1727 if (ep_square() != SQ_NONE)
1728 result ^= zobEp[ep_square()];
1730 result ^= zobCastle[st->castleRights];
1731 if (side_to_move() == BLACK)
1732 result ^= zobSideToMove;
1738 /// Position::compute_pawn_key() computes the hash key of the position. The
1739 /// hash key is usually updated incrementally as moves are made and unmade,
1740 /// the compute_pawn_key() function is only used when a new position is set
1741 /// up, and to verify the correctness of the pawn hash key when running in
1744 Key Position::compute_pawn_key() const {
1746 Key result = Key(0ULL);
1750 for (Color c = WHITE; c <= BLACK; c++)
1755 s = pop_1st_bit(&b);
1756 result ^= zobrist[c][PAWN][s];
1763 /// Position::compute_material_key() computes the hash key of the position.
1764 /// The hash key is usually updated incrementally as moves are made and unmade,
1765 /// the compute_material_key() function is only used when a new position is set
1766 /// up, and to verify the correctness of the material hash key when running in
1769 Key Position::compute_material_key() const {
1771 Key result = Key(0ULL);
1772 for (Color c = WHITE; c <= BLACK; c++)
1773 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1775 int count = piece_count(c, pt);
1776 for (int i = 0; i <= count; i++)
1777 result ^= zobMaterial[c][pt][i];
1783 /// Position::compute_value() compute the incremental scores for the middle
1784 /// game and the endgame. These functions are used to initialize the incremental
1785 /// scores when a new position is set up, and to verify that the scores are correctly
1786 /// updated by do_move and undo_move when the program is running in debug mode.
1787 template<Position::GamePhase Phase>
1788 Value Position::compute_value() const {
1790 Value result = Value(0);
1794 for (Color c = WHITE; c <= BLACK; c++)
1795 for (PieceType pt = PAWN; pt <= KING; pt++)
1797 b = pieces_of_color_and_type(c, pt);
1800 s = pop_1st_bit(&b);
1801 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1802 result += pst<Phase>(c, pt, s);
1806 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1807 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1812 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1813 /// game material score for the given side. Material scores are updated
1814 /// incrementally during the search, this function is only used while
1815 /// initializing a new Position object.
1817 Value Position::compute_non_pawn_material(Color c) const {
1819 Value result = Value(0);
1822 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1824 Bitboard b = pieces_of_color_and_type(c, pt);
1827 s = pop_1st_bit(&b);
1828 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1829 result += piece_value_midgame(pt);
1836 /// Position::is_mate() returns true or false depending on whether the
1837 /// side to move is checkmated. Note that this function is currently very
1838 /// slow, and shouldn't be used frequently inside the search.
1840 bool Position::is_mate() const {
1844 MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1845 return mp.get_next_move() == MOVE_NONE;
1851 /// Position::is_draw() tests whether the position is drawn by material,
1852 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1853 /// must be done by the search.
1855 bool Position::is_draw() const {
1857 // Draw by material?
1859 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1862 // Draw by the 50 moves rule?
1863 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1866 // Draw by repetition?
1867 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1868 if (history[gamePly - i] == st->key)
1875 /// Position::has_mate_threat() tests whether a given color has a mate in one
1876 /// from the current position. This function is quite slow, but it doesn't
1877 /// matter, because it is currently only called from PV nodes, which are rare.
1879 bool Position::has_mate_threat(Color c) {
1882 Color stm = side_to_move();
1884 // The following lines are useless and silly, but prevents gcc from
1885 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1886 // be used uninitialized.
1887 st1.lastMove = st->lastMove;
1888 st1.epSquare = st->epSquare;
1893 // If the input color is not equal to the side to move, do a null move
1897 MoveStack mlist[120];
1899 bool result = false;
1901 // Generate legal moves
1902 count = generate_legal_moves(*this, mlist);
1904 // Loop through the moves, and see if one of them is mate
1905 for (int i = 0; i < count; i++)
1907 do_move(mlist[i].move, st2);
1911 undo_move(mlist[i].move);
1914 // Undo null move, if necessary
1922 /// Position::init_zobrist() is a static member function which initializes the
1923 /// various arrays used to compute hash keys.
1925 void Position::init_zobrist() {
1927 for (int i = 0; i < 2; i++)
1928 for (int j = 0; j < 8; j++)
1929 for (int k = 0; k < 64; k++)
1930 zobrist[i][j][k] = Key(genrand_int64());
1932 for (int i = 0; i < 64; i++)
1933 zobEp[i] = Key(genrand_int64());
1935 for (int i = 0; i < 16; i++)
1936 zobCastle[i] = genrand_int64();
1938 zobSideToMove = genrand_int64();
1940 for (int i = 0; i < 2; i++)
1941 for (int j = 0; j < 8; j++)
1942 for (int k = 0; k < 16; k++)
1943 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1945 for (int i = 0; i < 16; i++)
1946 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1950 /// Position::init_piece_square_tables() initializes the piece square tables.
1951 /// This is a two-step operation: First, the white halves of the tables are
1952 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1953 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1954 /// Second, the black halves of the tables are initialized by mirroring
1955 /// and changing the sign of the corresponding white scores.
1957 void Position::init_piece_square_tables() {
1959 int r = get_option_value_int("Randomness"), i;
1960 for (Square s = SQ_A1; s <= SQ_H8; s++)
1961 for (Piece p = WP; p <= WK; p++)
1963 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1964 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1965 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1968 for (Square s = SQ_A1; s <= SQ_H8; s++)
1969 for (Piece p = BP; p <= BK; p++)
1971 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1972 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
1977 /// Position::flipped_copy() makes a copy of the input position, but with
1978 /// the white and black sides reversed. This is only useful for debugging,
1979 /// especially for finding evaluation symmetry bugs.
1981 void Position::flipped_copy(const Position &pos) {
1983 assert(pos.is_ok());
1988 for (Square s = SQ_A1; s <= SQ_H8; s++)
1989 if (!pos.square_is_empty(s))
1990 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1993 sideToMove = opposite_color(pos.side_to_move());
1996 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1997 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1998 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1999 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2001 initialKFile = pos.initialKFile;
2002 initialKRFile = pos.initialKRFile;
2003 initialQRFile = pos.initialQRFile;
2005 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2006 castleRightsMask[sq] = ALL_CASTLES;
2008 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2009 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2010 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2011 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2012 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2013 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2015 // En passant square
2016 if (pos.st->epSquare != SQ_NONE)
2017 st->epSquare = flip_square(pos.st->epSquare);
2023 st->key = compute_key();
2024 st->pawnKey = compute_pawn_key();
2025 st->materialKey = compute_material_key();
2027 // Incremental scores
2028 st->mgValue = compute_value<MidGame>();
2029 st->egValue = compute_value<EndGame>();
2032 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2033 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2039 /// Position::is_ok() performs some consitency checks for the position object.
2040 /// This is meant to be helpful when debugging.
2042 bool Position::is_ok(int* failedStep) const {
2044 // What features of the position should be verified?
2045 static const bool debugBitboards = false;
2046 static const bool debugKingCount = false;
2047 static const bool debugKingCapture = false;
2048 static const bool debugCheckerCount = false;
2049 static const bool debugKey = false;
2050 static const bool debugMaterialKey = false;
2051 static const bool debugPawnKey = false;
2052 static const bool debugIncrementalEval = false;
2053 static const bool debugNonPawnMaterial = false;
2054 static const bool debugPieceCounts = false;
2055 static const bool debugPieceList = false;
2057 if (failedStep) *failedStep = 1;
2060 if (!color_is_ok(side_to_move()))
2063 // Are the king squares in the position correct?
2064 if (failedStep) (*failedStep)++;
2065 if (piece_on(king_square(WHITE)) != WK)
2068 if (failedStep) (*failedStep)++;
2069 if (piece_on(king_square(BLACK)) != BK)
2073 if (failedStep) (*failedStep)++;
2074 if (!file_is_ok(initialKRFile))
2077 if (!file_is_ok(initialQRFile))
2080 // Do both sides have exactly one king?
2081 if (failedStep) (*failedStep)++;
2084 int kingCount[2] = {0, 0};
2085 for (Square s = SQ_A1; s <= SQ_H8; s++)
2086 if (type_of_piece_on(s) == KING)
2087 kingCount[color_of_piece_on(s)]++;
2089 if (kingCount[0] != 1 || kingCount[1] != 1)
2093 // Can the side to move capture the opponent's king?
2094 if (failedStep) (*failedStep)++;
2095 if (debugKingCapture)
2097 Color us = side_to_move();
2098 Color them = opposite_color(us);
2099 Square ksq = king_square(them);
2100 if (square_is_attacked(ksq, us))
2104 // Is there more than 2 checkers?
2105 if (failedStep) (*failedStep)++;
2106 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2110 if (failedStep) (*failedStep)++;
2113 // The intersection of the white and black pieces must be empty
2114 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2117 // The union of the white and black pieces must be equal to all
2119 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2122 // Separate piece type bitboards must have empty intersections
2123 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2124 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2125 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2129 // En passant square OK?
2130 if (failedStep) (*failedStep)++;
2131 if (ep_square() != SQ_NONE)
2133 // The en passant square must be on rank 6, from the point of view of the
2135 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2140 if (failedStep) (*failedStep)++;
2141 if (debugKey && st->key != compute_key())
2144 // Pawn hash key OK?
2145 if (failedStep) (*failedStep)++;
2146 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2149 // Material hash key OK?
2150 if (failedStep) (*failedStep)++;
2151 if (debugMaterialKey && st->materialKey != compute_material_key())
2154 // Incremental eval OK?
2155 if (failedStep) (*failedStep)++;
2156 if (debugIncrementalEval)
2158 if (st->mgValue != compute_value<MidGame>())
2161 if (st->egValue != compute_value<EndGame>())
2165 // Non-pawn material OK?
2166 if (failedStep) (*failedStep)++;
2167 if (debugNonPawnMaterial)
2169 if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2172 if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2177 if (failedStep) (*failedStep)++;
2178 if (debugPieceCounts)
2179 for (Color c = WHITE; c <= BLACK; c++)
2180 for (PieceType pt = PAWN; pt <= KING; pt++)
2181 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2184 if (failedStep) (*failedStep)++;
2187 for(Color c = WHITE; c <= BLACK; c++)
2188 for(PieceType pt = PAWN; pt <= KING; pt++)
2189 for(int i = 0; i < pieceCount[c][pt]; i++)
2191 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2194 if (index[piece_list(c, pt, i)] != i)
2198 if (failedStep) *failedStep = 0;