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-2009 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/>.
38 #include "ucioption.h"
47 int Position::castleRightsMask[64];
49 Key Position::zobrist[2][8][64];
50 Key Position::zobEp[64];
51 Key Position::zobCastle[16];
52 Key Position::zobMaterial[2][8][16];
53 Key Position::zobSideToMove;
55 Score Position::PieceSquareTable[16][64];
57 static bool RequestPending = false;
65 Position::Position(const Position& pos) {
69 Position::Position(const string& fen) {
74 /// Position::from_fen() initializes the position object with the given FEN
75 /// string. This function is not very robust - make sure that input FENs are
76 /// correct (this is assumed to be the responsibility of the GUI).
78 void Position::from_fen(const string& fen) {
80 static const string pieceLetters = "KQRBNPkqrbnp";
81 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
89 for ( ; fen[i] != ' '; i++)
93 // Skip the given number of files
94 file += (fen[i] - '1' + 1);
97 else if (fen[i] == '/')
103 size_t idx = pieceLetters.find(fen[i]);
104 if (idx == string::npos)
106 std::cout << "Error in FEN at character " << i << std::endl;
109 Square square = make_square(file, rank);
110 put_piece(pieces[idx], square);
116 if (fen[i] != 'w' && fen[i] != 'b')
118 std::cout << "Error in FEN at character " << i << std::endl;
121 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
127 std::cout << "Error in FEN at character " << i << std::endl;
132 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
138 else if(fen[i] == 'K') allow_oo(WHITE);
139 else if(fen[i] == 'Q') allow_ooo(WHITE);
140 else if(fen[i] == 'k') allow_oo(BLACK);
141 else if(fen[i] == 'q') allow_ooo(BLACK);
142 else if(fen[i] >= 'A' && fen[i] <= 'H') {
143 File rookFile, kingFile = FILE_NONE;
144 for(Square square = SQ_B1; square <= SQ_G1; square++)
145 if(piece_on(square) == WK)
146 kingFile = square_file(square);
147 if(kingFile == FILE_NONE) {
148 std::cout << "Error in FEN at character " << i << std::endl;
151 initialKFile = kingFile;
152 rookFile = File(fen[i] - 'A') + FILE_A;
153 if(rookFile < initialKFile) {
155 initialQRFile = rookFile;
159 initialKRFile = rookFile;
162 else if(fen[i] >= 'a' && fen[i] <= 'h') {
163 File rookFile, kingFile = FILE_NONE;
164 for(Square square = SQ_B8; square <= SQ_G8; square++)
165 if(piece_on(square) == BK)
166 kingFile = square_file(square);
167 if(kingFile == FILE_NONE) {
168 std::cout << "Error in FEN at character " << i << std::endl;
171 initialKFile = kingFile;
172 rookFile = File(fen[i] - 'a') + FILE_A;
173 if(rookFile < initialKFile) {
175 initialQRFile = rookFile;
179 initialKRFile = rookFile;
183 std::cout << "Error in FEN at character " << i << std::endl;
190 while (fen[i] == ' ')
194 if ( i <= fen.length() - 2
195 && (fen[i] >= 'a' && fen[i] <= 'h')
196 && (fen[i+1] == '3' || fen[i+1] == '6'))
197 st->epSquare = square_from_string(fen.substr(i, 2));
199 // Various initialisation
200 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
201 castleRightsMask[sq] = ALL_CASTLES;
203 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
204 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
205 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
206 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
207 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
208 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
212 st->key = compute_key();
213 st->pawnKey = compute_pawn_key();
214 st->materialKey = compute_material_key();
215 st->value = compute_value();
216 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
217 st->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 string Position::to_fen() const {
226 static const 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 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 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));
320 saveState(); // detach and copy state info
324 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
325 /// king) pieces for the given color and for the given pinner type. Or, when
326 /// template parameter FindPinned is false, the pieces of the given color
327 /// candidate for a discovery check against the enemy king.
328 /// Note that checkersBB bitboard must be already updated.
330 template<bool FindPinned>
331 Bitboard Position::hidden_checkers(Color c) const {
333 Bitboard pinners, result = EmptyBoardBB;
335 // Pinned pieces protect our king, dicovery checks attack
337 Square ksq = king_square(FindPinned ? c : opposite_color(c));
339 // Pinners are sliders, not checkers, that give check when
340 // candidate pinned is removed.
341 pinners = (pieces(ROOK, QUEEN, FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
342 | (pieces(BISHOP, QUEEN, FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq]);
344 if (FindPinned && pinners)
345 pinners &= ~st->checkersBB;
349 Square s = pop_1st_bit(&pinners);
350 Bitboard b = squares_between(s, ksq) & occupied_squares();
354 if ( !(b & (b - 1)) // Only one bit set?
355 && (b & pieces_of_color(c))) // Is an our piece?
362 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
363 /// king) pieces for the given color.
365 Bitboard Position::pinned_pieces(Color c) const {
367 return hidden_checkers<true>(c);
371 /// Position:discovered_check_candidates() returns a bitboard containing all
372 /// pieces for the given side which are candidates for giving a discovered
375 Bitboard Position::discovered_check_candidates(Color c) const {
377 return hidden_checkers<false>(c);
380 /// Position::attackers_to() computes a bitboard containing all pieces which
381 /// attacks a given square.
383 Bitboard Position::attackers_to(Square s) const {
385 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
386 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
387 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
388 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
389 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
390 | (attacks_from<KING>(s) & pieces(KING));
393 /// Position::attacks_from() computes a bitboard of all attacks
394 /// of a given piece put in a given square.
396 Bitboard Position::attacks_from(Piece p, Square s) const {
398 assert(square_is_ok(s));
402 case WP: return attacks_from<PAWN>(s, WHITE);
403 case BP: return attacks_from<PAWN>(s, BLACK);
404 case WN: case BN: return attacks_from<KNIGHT>(s);
405 case WB: case BB: return attacks_from<BISHOP>(s);
406 case WR: case BR: return attacks_from<ROOK>(s);
407 case WQ: case BQ: return attacks_from<QUEEN>(s);
408 case WK: case BK: return attacks_from<KING>(s);
415 /// Position::move_attacks_square() tests whether a move from the current
416 /// position attacks a given square.
418 bool Position::move_attacks_square(Move m, Square s) const {
420 assert(move_is_ok(m));
421 assert(square_is_ok(s));
423 Square f = move_from(m), t = move_to(m);
425 assert(square_is_occupied(f));
427 if (bit_is_set(attacks_from(piece_on(f), t), s))
430 // Move the piece and scan for X-ray attacks behind it
431 Bitboard occ = occupied_squares();
432 Color us = color_of_piece_on(f);
435 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
436 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
438 // If we have attacks we need to verify that are caused by our move
439 // and are not already existent ones.
440 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
444 /// Position::find_checkers() computes the checkersBB bitboard, which
445 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
446 /// currently works by calling Position::attackers_to, which is probably
447 /// inefficient. Consider rewriting this function to use the last move
448 /// played, like in non-bitboard versions of Glaurung.
450 void Position::find_checkers() {
452 Color us = side_to_move();
453 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
457 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
459 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
462 assert(move_is_ok(m));
463 assert(pinned == pinned_pieces(side_to_move()));
465 // Castling moves are checked for legality during move generation.
466 if (move_is_castle(m))
469 Color us = side_to_move();
470 Square from = move_from(m);
472 assert(color_of_piece_on(from) == us);
473 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
475 // En passant captures are a tricky special case. Because they are
476 // rather uncommon, we do it simply by testing whether the king is attacked
477 // after the move is made
480 Color them = opposite_color(us);
481 Square to = move_to(m);
482 Square capsq = make_square(square_file(to), square_rank(from));
483 Bitboard b = occupied_squares();
484 Square ksq = king_square(us);
486 assert(to == ep_square());
487 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
488 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
489 assert(piece_on(to) == EMPTY);
492 clear_bit(&b, capsq);
495 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
496 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
499 // If the moving piece is a king, check whether the destination
500 // square is attacked by the opponent.
501 if (type_of_piece_on(from) == KING)
502 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
504 // A non-king move is legal if and only if it is not pinned or it
505 // is moving along the ray towards or away from the king.
507 || !bit_is_set(pinned, from)
508 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
512 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
514 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
518 Color us = side_to_move();
519 Square from = move_from(m);
520 Square to = move_to(m);
522 // King moves and en-passant captures are verified in pl_move_is_legal()
523 if (type_of_piece_on(from) == KING || move_is_ep(m))
524 return pl_move_is_legal(m, pinned);
526 Bitboard target = checkers();
527 Square checksq = pop_1st_bit(&target);
529 if (target) // double check ?
532 // Our move must be a blocking evasion or a capture of the checking piece
533 target = squares_between(checksq, king_square(us)) | checkers();
534 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
538 /// Position::move_is_check() tests whether a pseudo-legal move is a check
540 bool Position::move_is_check(Move m) const {
542 Bitboard dc = discovered_check_candidates(side_to_move());
543 return move_is_check(m, dc);
546 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
549 assert(move_is_ok(m));
550 assert(dcCandidates == discovered_check_candidates(side_to_move()));
552 Color us = side_to_move();
553 Color them = opposite_color(us);
554 Square from = move_from(m);
555 Square to = move_to(m);
556 Square ksq = king_square(them);
558 assert(color_of_piece_on(from) == us);
559 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
561 // Proceed according to the type of the moving piece
562 switch (type_of_piece_on(from))
566 if (bit_is_set(attacks_from<PAWN>(ksq, them), to)) // Normal check?
569 if ( dcCandidates // Discovered check?
570 && bit_is_set(dcCandidates, from)
571 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
574 if (move_is_promotion(m)) // Promotion with check?
576 Bitboard b = occupied_squares();
579 switch (move_promotion_piece(m))
582 return bit_is_set(attacks_from<KNIGHT>(to), ksq);
584 return bit_is_set(bishop_attacks_bb(to, b), ksq);
586 return bit_is_set(rook_attacks_bb(to, b), ksq);
588 return bit_is_set(queen_attacks_bb(to, b), ksq);
593 // En passant capture with check? We have already handled the case
594 // of direct checks and ordinary discovered check, the only case we
595 // need to handle is the unusual case of a discovered check through the
597 else if (move_is_ep(m))
599 Square capsq = make_square(square_file(to), square_rank(from));
600 Bitboard b = occupied_squares();
602 clear_bit(&b, capsq);
604 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
605 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
609 // Test discovered check and normal check according to piece type
611 return (dcCandidates && bit_is_set(dcCandidates, from))
612 || bit_is_set(attacks_from<KNIGHT>(ksq), to);
615 return (dcCandidates && bit_is_set(dcCandidates, from))
616 || (direction_is_diagonal(ksq, to) && bit_is_set(attacks_from<BISHOP>(ksq), to));
619 return (dcCandidates && bit_is_set(dcCandidates, from))
620 || (direction_is_straight(ksq, to) && bit_is_set(attacks_from<ROOK>(ksq), to));
623 // Discovered checks are impossible!
624 assert(!bit_is_set(dcCandidates, from));
625 return ( (direction_is_straight(ksq, to) && bit_is_set(attacks_from<ROOK>(ksq), to))
626 || (direction_is_diagonal(ksq, to) && bit_is_set(attacks_from<BISHOP>(ksq), to)));
630 if ( bit_is_set(dcCandidates, from)
631 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
634 // Castling with check?
635 if (move_is_castle(m))
637 Square kfrom, kto, rfrom, rto;
638 Bitboard b = occupied_squares();
644 kto = relative_square(us, SQ_G1);
645 rto = relative_square(us, SQ_F1);
647 kto = relative_square(us, SQ_C1);
648 rto = relative_square(us, SQ_D1);
650 clear_bit(&b, kfrom);
651 clear_bit(&b, rfrom);
654 return bit_is_set(rook_attacks_bb(rto, b), ksq);
658 default: // NO_PIECE_TYPE
666 /// Position::update_checkers() udpates chekers info given the move. It is called
667 /// in do_move() and is faster then find_checkers().
669 template<PieceType Piece>
670 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
671 Square to, Bitboard dcCandidates) {
673 const bool Bishop = (Piece == QUEEN || Piece == BISHOP);
674 const bool Rook = (Piece == QUEEN || Piece == ROOK);
675 const bool Slider = Bishop || Rook;
678 if ( ( (Bishop && bit_is_set(BishopPseudoAttacks[ksq], to))
679 || (Rook && bit_is_set(RookPseudoAttacks[ksq], to)))
680 && bit_is_set(attacks_from<Piece>(ksq), to)) // slow, try to early skip
681 set_bit(pCheckersBB, to);
683 else if ( Piece != KING
685 && bit_is_set(Piece == PAWN ? attacks_from<PAWN>(ksq, opposite_color(sideToMove))
686 : attacks_from<Piece>(ksq), to))
687 set_bit(pCheckersBB, to);
690 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
693 (*pCheckersBB) |= (attacks_from<ROOK>(ksq) & pieces(ROOK, QUEEN, side_to_move()));
696 (*pCheckersBB) |= (attacks_from<BISHOP>(ksq) & pieces(BISHOP, QUEEN, side_to_move()));
701 /// Position::do_move() makes a move, and saves all information necessary
702 /// to a StateInfo object. The move is assumed to be legal.
703 /// Pseudo-legal moves should be filtered out before this function is called.
705 void Position::do_move(Move m, StateInfo& newSt) {
707 do_move(m, newSt, discovered_check_candidates(side_to_move()));
710 void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
713 assert(move_is_ok(m));
715 Bitboard key = st->key;
717 // Copy some fields of old state to our new StateInfo object except the
718 // ones which are recalculated from scratch anyway, then switch our state
719 // pointer to point to the new, ready to be updated, state.
720 struct ReducedStateInfo {
721 Key key, pawnKey, materialKey;
722 int castleRights, rule50, pliesFromNull;
728 memcpy(&newSt, st, sizeof(ReducedStateInfo));
732 // Save the current key to the history[] array, in order to be able to
733 // detect repetition draws.
734 history[gamePly] = key;
737 // Update side to move
738 key ^= zobSideToMove;
740 // Increment the 50 moves rule draw counter. Resetting it to zero in the
741 // case of non-reversible moves is taken care of later.
745 if (move_is_castle(m))
752 Color us = side_to_move();
753 Color them = opposite_color(us);
754 Square from = move_from(m);
755 Square to = move_to(m);
756 bool ep = move_is_ep(m);
757 bool pm = move_is_promotion(m);
759 Piece piece = piece_on(from);
760 PieceType pt = type_of_piece(piece);
762 assert(color_of_piece_on(from) == us);
763 assert(color_of_piece_on(to) == them || square_is_empty(to));
764 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
765 assert(!pm || relative_rank(us, to) == RANK_8);
767 st->capture = ep ? PAWN : type_of_piece_on(to);
770 do_capture_move(key, st->capture, them, to, ep);
773 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
775 // Reset en passant square
776 if (st->epSquare != SQ_NONE)
778 key ^= zobEp[st->epSquare];
779 st->epSquare = SQ_NONE;
782 // Update castle rights, try to shortcut a common case
783 int cm = castleRightsMask[from] & castleRightsMask[to];
784 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
786 key ^= zobCastle[st->castleRights];
787 st->castleRights &= castleRightsMask[from];
788 st->castleRights &= castleRightsMask[to];
789 key ^= zobCastle[st->castleRights];
792 // Prefetch TT access as soon as we know key is updated
796 Bitboard move_bb = make_move_bb(from, to);
797 do_move_bb(&(byColorBB[us]), move_bb);
798 do_move_bb(&(byTypeBB[pt]), move_bb);
799 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
801 board[to] = board[from];
804 // Update piece lists, note that index[from] is not updated and
805 // becomes stale. This works as long as index[] is accessed just
806 // by known occupied squares.
807 index[to] = index[from];
808 pieceList[us][pt][index[to]] = to;
810 // If the moving piece was a pawn do some special extra work
813 // Reset rule 50 draw counter
816 // Update pawn hash key
817 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
819 // Set en passant square, only if moved pawn can be captured
820 if (abs(int(to) - int(from)) == 16)
822 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
824 st->epSquare = Square((int(from) + int(to)) / 2);
825 key ^= zobEp[st->epSquare];
830 // Update incremental scores
831 st->value += pst_delta(piece, from, to);
833 if (pm) // promotion ?
835 PieceType promotion = move_promotion_piece(m);
837 assert(promotion >= KNIGHT && promotion <= QUEEN);
839 // Insert promoted piece instead of pawn
840 clear_bit(&(byTypeBB[PAWN]), to);
841 set_bit(&(byTypeBB[promotion]), to);
842 board[to] = piece_of_color_and_type(us, promotion);
844 // Update material key
845 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
846 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
848 // Update piece counts
849 pieceCount[us][PAWN]--;
850 pieceCount[us][promotion]++;
852 // Update piece lists, move the last pawn at index[to] position
853 // and shrink the list. Add a new promotion piece to the list.
854 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
855 index[lastPawnSquare] = index[to];
856 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
857 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
858 index[to] = pieceCount[us][promotion] - 1;
859 pieceList[us][promotion][index[to]] = to;
861 // Partially revert hash keys update
862 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
863 st->pawnKey ^= zobrist[us][PAWN][to];
865 // Partially revert and update incremental scores
866 st->value -= pst(us, PAWN, to);
867 st->value += pst(us, promotion, to);
870 st->npMaterial[us] += piece_value_midgame(promotion);
873 // Update the key with the final value
876 // Update checkers bitboard, piece must be already moved
878 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
881 st->checkersBB = EmptyBoardBB;
882 Square ksq = king_square(them);
885 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
886 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
887 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
888 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
889 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
890 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
891 default: assert(false); break;
896 sideToMove = opposite_color(sideToMove);
897 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
903 /// Position::do_capture_move() is a private method used to update captured
904 /// piece info. It is called from the main Position::do_move function.
906 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
908 assert(capture != KING);
912 if (ep) // en passant ?
914 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
916 assert(to == st->epSquare);
917 assert(relative_rank(opposite_color(them), to) == RANK_6);
918 assert(piece_on(to) == EMPTY);
919 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
921 board[capsq] = EMPTY;
924 // Remove captured piece
925 clear_bit(&(byColorBB[them]), capsq);
926 clear_bit(&(byTypeBB[capture]), capsq);
927 clear_bit(&(byTypeBB[0]), capsq);
930 key ^= zobrist[them][capture][capsq];
932 // Update incremental scores
933 st->value -= pst(them, capture, capsq);
935 // If the captured piece was a pawn, update pawn hash key,
936 // otherwise update non-pawn material.
938 st->pawnKey ^= zobrist[them][PAWN][capsq];
940 st->npMaterial[them] -= piece_value_midgame(capture);
942 // Update material hash key
943 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
945 // Update piece count
946 pieceCount[them][capture]--;
948 // Update piece list, move the last piece at index[capsq] position
950 // WARNING: This is a not perfectly revresible operation. When we
951 // will reinsert the captured piece in undo_move() we will put it
952 // at the end of the list and not in its original place, it means
953 // index[] and pieceList[] are not guaranteed to be invariant to a
954 // do_move() + undo_move() sequence.
955 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
956 index[lastPieceSquare] = index[capsq];
957 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
958 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
960 // Reset rule 50 counter
965 /// Position::do_castle_move() is a private method used to make a castling
966 /// move. It is called from the main Position::do_move function. Note that
967 /// castling moves are encoded as "king captures friendly rook" moves, for
968 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
970 void Position::do_castle_move(Move m) {
972 assert(move_is_ok(m));
973 assert(move_is_castle(m));
975 Color us = side_to_move();
976 Color them = opposite_color(us);
978 // Reset capture field
979 st->capture = NO_PIECE_TYPE;
981 // Find source squares for king and rook
982 Square kfrom = move_from(m);
983 Square rfrom = move_to(m); // HACK: See comment at beginning of function
986 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
987 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
989 // Find destination squares for king and rook
990 if (rfrom > kfrom) // O-O
992 kto = relative_square(us, SQ_G1);
993 rto = relative_square(us, SQ_F1);
995 kto = relative_square(us, SQ_C1);
996 rto = relative_square(us, SQ_D1);
999 // Remove pieces from source squares:
1000 clear_bit(&(byColorBB[us]), kfrom);
1001 clear_bit(&(byTypeBB[KING]), kfrom);
1002 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1003 clear_bit(&(byColorBB[us]), rfrom);
1004 clear_bit(&(byTypeBB[ROOK]), rfrom);
1005 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1007 // Put pieces on destination squares:
1008 set_bit(&(byColorBB[us]), kto);
1009 set_bit(&(byTypeBB[KING]), kto);
1010 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1011 set_bit(&(byColorBB[us]), rto);
1012 set_bit(&(byTypeBB[ROOK]), rto);
1013 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1015 // Update board array
1016 Piece king = piece_of_color_and_type(us, KING);
1017 Piece rook = piece_of_color_and_type(us, ROOK);
1018 board[kfrom] = board[rfrom] = EMPTY;
1022 // Update piece lists
1023 pieceList[us][KING][index[kfrom]] = kto;
1024 pieceList[us][ROOK][index[rfrom]] = rto;
1025 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1026 index[kto] = index[kfrom];
1029 // Update incremental scores
1030 st->value += pst_delta(king, kfrom, kto);
1031 st->value += pst_delta(rook, rfrom, rto);
1034 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1035 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1037 // Clear en passant square
1038 if (st->epSquare != SQ_NONE)
1040 st->key ^= zobEp[st->epSquare];
1041 st->epSquare = SQ_NONE;
1044 // Update castling rights
1045 st->key ^= zobCastle[st->castleRights];
1046 st->castleRights &= castleRightsMask[kfrom];
1047 st->key ^= zobCastle[st->castleRights];
1049 // Reset rule 50 counter
1052 // Update checkers BB
1053 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1056 sideToMove = opposite_color(sideToMove);
1057 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1063 /// Position::undo_move() unmakes a move. When it returns, the position should
1064 /// be restored to exactly the same state as before the move was made.
1066 void Position::undo_move(Move m) {
1069 assert(move_is_ok(m));
1072 sideToMove = opposite_color(sideToMove);
1074 if (move_is_castle(m))
1076 undo_castle_move(m);
1080 Color us = side_to_move();
1081 Color them = opposite_color(us);
1082 Square from = move_from(m);
1083 Square to = move_to(m);
1084 bool ep = move_is_ep(m);
1085 bool pm = move_is_promotion(m);
1087 PieceType pt = type_of_piece_on(to);
1089 assert(square_is_empty(from));
1090 assert(color_of_piece_on(to) == us);
1091 assert(!pm || relative_rank(us, to) == RANK_8);
1092 assert(!ep || to == st->previous->epSquare);
1093 assert(!ep || relative_rank(us, to) == RANK_6);
1094 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1096 if (pm) // promotion ?
1098 PieceType promotion = move_promotion_piece(m);
1101 assert(promotion >= KNIGHT && promotion <= QUEEN);
1102 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1104 // Replace promoted piece with a pawn
1105 clear_bit(&(byTypeBB[promotion]), to);
1106 set_bit(&(byTypeBB[PAWN]), to);
1108 // Update piece counts
1109 pieceCount[us][promotion]--;
1110 pieceCount[us][PAWN]++;
1112 // Update piece list replacing promotion piece with a pawn
1113 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1114 index[lastPromotionSquare] = index[to];
1115 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1116 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1117 index[to] = pieceCount[us][PAWN] - 1;
1118 pieceList[us][PAWN][index[to]] = to;
1122 // Put the piece back at the source square
1123 Bitboard move_bb = make_move_bb(to, from);
1124 do_move_bb(&(byColorBB[us]), move_bb);
1125 do_move_bb(&(byTypeBB[pt]), move_bb);
1126 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1128 board[from] = piece_of_color_and_type(us, pt);
1131 // Update piece list
1132 index[from] = index[to];
1133 pieceList[us][pt][index[from]] = from;
1140 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1142 assert(st->capture != KING);
1143 assert(!ep || square_is_empty(capsq));
1145 // Restore the captured piece
1146 set_bit(&(byColorBB[them]), capsq);
1147 set_bit(&(byTypeBB[st->capture]), capsq);
1148 set_bit(&(byTypeBB[0]), capsq);
1150 board[capsq] = piece_of_color_and_type(them, st->capture);
1152 // Update piece count
1153 pieceCount[them][st->capture]++;
1155 // Update piece list, add a new captured piece in capsq square
1156 index[capsq] = pieceCount[them][st->capture] - 1;
1157 pieceList[them][st->capture][index[capsq]] = capsq;
1160 // Finally point our state pointer back to the previous state
1167 /// Position::undo_castle_move() is a private method used to unmake a castling
1168 /// move. It is called from the main Position::undo_move function. Note that
1169 /// castling moves are encoded as "king captures friendly rook" moves, for
1170 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1172 void Position::undo_castle_move(Move m) {
1174 assert(move_is_ok(m));
1175 assert(move_is_castle(m));
1177 // When we have arrived here, some work has already been done by
1178 // Position::undo_move. In particular, the side to move has been switched,
1179 // so the code below is correct.
1180 Color us = side_to_move();
1182 // Find source squares for king and rook
1183 Square kfrom = move_from(m);
1184 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1187 // Find destination squares for king and rook
1188 if (rfrom > kfrom) // O-O
1190 kto = relative_square(us, SQ_G1);
1191 rto = relative_square(us, SQ_F1);
1193 kto = relative_square(us, SQ_C1);
1194 rto = relative_square(us, SQ_D1);
1197 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1198 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1200 // Remove pieces from destination squares:
1201 clear_bit(&(byColorBB[us]), kto);
1202 clear_bit(&(byTypeBB[KING]), kto);
1203 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1204 clear_bit(&(byColorBB[us]), rto);
1205 clear_bit(&(byTypeBB[ROOK]), rto);
1206 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1208 // Put pieces on source squares:
1209 set_bit(&(byColorBB[us]), kfrom);
1210 set_bit(&(byTypeBB[KING]), kfrom);
1211 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1212 set_bit(&(byColorBB[us]), rfrom);
1213 set_bit(&(byTypeBB[ROOK]), rfrom);
1214 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1217 board[rto] = board[kto] = EMPTY;
1218 board[rfrom] = piece_of_color_and_type(us, ROOK);
1219 board[kfrom] = piece_of_color_and_type(us, KING);
1221 // Update piece lists
1222 pieceList[us][KING][index[kto]] = kfrom;
1223 pieceList[us][ROOK][index[rto]] = rfrom;
1224 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1225 index[kfrom] = index[kto];
1228 // Finally point our state pointer back to the previous state
1235 /// Position::do_null_move makes() a "null move": It switches the side to move
1236 /// and updates the hash key without executing any move on the board.
1238 void Position::do_null_move(StateInfo& backupSt) {
1241 assert(!is_check());
1243 // Back up the information necessary to undo the null move to the supplied
1244 // StateInfo object.
1245 // Note that differently from normal case here backupSt is actually used as
1246 // a backup storage not as a new state to be used.
1247 backupSt.key = st->key;
1248 backupSt.epSquare = st->epSquare;
1249 backupSt.value = st->value;
1250 backupSt.previous = st->previous;
1251 backupSt.pliesFromNull = st->pliesFromNull;
1252 st->previous = &backupSt;
1254 // Save the current key to the history[] array, in order to be able to
1255 // detect repetition draws.
1256 history[gamePly] = st->key;
1258 // Update the necessary information
1259 if (st->epSquare != SQ_NONE)
1260 st->key ^= zobEp[st->epSquare];
1262 st->key ^= zobSideToMove;
1263 TT.prefetch(st->key);
1265 sideToMove = opposite_color(sideToMove);
1266 st->epSquare = SQ_NONE;
1268 st->pliesFromNull = 0;
1269 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1274 /// Position::undo_null_move() unmakes a "null move".
1276 void Position::undo_null_move() {
1279 assert(!is_check());
1281 // Restore information from the our backup StateInfo object
1282 StateInfo* backupSt = st->previous;
1283 st->key = backupSt->key;
1284 st->epSquare = backupSt->epSquare;
1285 st->value = backupSt->value;
1286 st->previous = backupSt->previous;
1287 st->pliesFromNull = backupSt->pliesFromNull;
1289 // Update the necessary information
1290 sideToMove = opposite_color(sideToMove);
1296 /// Position::see() is a static exchange evaluator: It tries to estimate the
1297 /// material gain or loss resulting from a move. There are three versions of
1298 /// this function: One which takes a destination square as input, one takes a
1299 /// move, and one which takes a 'from' and a 'to' square. The function does
1300 /// not yet understand promotions captures.
1302 int Position::see(Square to) const {
1304 assert(square_is_ok(to));
1305 return see(SQ_NONE, to);
1308 int Position::see(Move m) const {
1310 assert(move_is_ok(m));
1311 return see(move_from(m), move_to(m));
1314 int Position::see_sign(Move m) const {
1316 assert(move_is_ok(m));
1318 Square from = move_from(m);
1319 Square to = move_to(m);
1321 // Early return if SEE cannot be negative because capturing piece value
1322 // is not bigger then captured one.
1323 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1324 && type_of_piece_on(from) != KING)
1327 return see(from, to);
1330 int Position::see(Square from, Square to) const {
1333 static const int seeValues[18] = {
1334 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1335 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1336 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1337 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1341 Bitboard attackers, stmAttackers, b;
1343 assert(square_is_ok(from) || from == SQ_NONE);
1344 assert(square_is_ok(to));
1346 // Initialize colors
1347 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1348 Color them = opposite_color(us);
1350 // Initialize pieces
1351 Piece piece = piece_on(from);
1352 Piece capture = piece_on(to);
1353 Bitboard occ = occupied_squares();
1355 // King cannot be recaptured
1356 if (type_of_piece(piece) == KING)
1357 return seeValues[capture];
1359 // Handle en passant moves
1360 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1362 assert(capture == EMPTY);
1364 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1365 capture = piece_on(capQq);
1366 assert(type_of_piece_on(capQq) == PAWN);
1368 // Remove the captured pawn
1369 clear_bit(&occ, capQq);
1374 // Find all attackers to the destination square, with the moving piece
1375 // removed, but possibly an X-ray attacker added behind it.
1376 clear_bit(&occ, from);
1377 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1378 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1379 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1380 | (attacks_from<KING>(to) & pieces(KING))
1381 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1382 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1384 if (from != SQ_NONE)
1387 // If we don't have any attacker we are finished
1388 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1391 // Locate the least valuable attacker to the destination square
1392 // and use it to initialize from square.
1393 stmAttackers = attackers & pieces_of_color(us);
1395 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1398 from = first_1(stmAttackers & pieces(pt));
1399 piece = piece_on(from);
1402 // If the opponent has no attackers we are finished
1403 stmAttackers = attackers & pieces_of_color(them);
1405 return seeValues[capture];
1407 attackers &= occ; // Remove the moving piece
1409 // The destination square is defended, which makes things rather more
1410 // difficult to compute. We proceed by building up a "swap list" containing
1411 // the material gain or loss at each stop in a sequence of captures to the
1412 // destination square, where the sides alternately capture, and always
1413 // capture with the least valuable piece. After each capture, we look for
1414 // new X-ray attacks from behind the capturing piece.
1415 int lastCapturingPieceValue = seeValues[piece];
1416 int swapList[32], n = 1;
1420 swapList[0] = seeValues[capture];
1423 // Locate the least valuable attacker for the side to move. The loop
1424 // below looks like it is potentially infinite, but it isn't. We know
1425 // that the side to move still has at least one attacker left.
1426 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1429 // Remove the attacker we just found from the 'attackers' bitboard,
1430 // and scan for new X-ray attacks behind the attacker.
1431 b = stmAttackers & pieces(pt);
1432 occ ^= (b & (~b + 1));
1433 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1434 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1438 // Add the new entry to the swap list
1440 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1443 // Remember the value of the capturing piece, and change the side to move
1444 // before beginning the next iteration
1445 lastCapturingPieceValue = seeValues[pt];
1446 c = opposite_color(c);
1447 stmAttackers = attackers & pieces_of_color(c);
1449 // Stop after a king capture
1450 if (pt == KING && stmAttackers)
1453 swapList[n++] = QueenValueMidgame*10;
1456 } while (stmAttackers);
1458 // Having built the swap list, we negamax through it to find the best
1459 // achievable score from the point of view of the side to move
1461 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1467 /// Position::saveState() copies the content of the current state
1468 /// inside startState and makes st point to it. This is needed
1469 /// when the st pointee could become stale, as example because
1470 /// the caller is about to going out of scope.
1472 void Position::saveState() {
1476 st->previous = NULL; // as a safe guard
1480 /// Position::clear() erases the position object to a pristine state, with an
1481 /// empty board, white to move, and no castling rights.
1483 void Position::clear() {
1486 memset(st, 0, sizeof(StateInfo));
1487 st->epSquare = SQ_NONE;
1489 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1490 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1491 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1492 memset(index, 0, sizeof(int) * 64);
1494 for (int i = 0; i < 64; i++)
1497 for (int i = 0; i < 8; i++)
1498 for (int j = 0; j < 16; j++)
1499 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1503 initialKFile = FILE_E;
1504 initialKRFile = FILE_H;
1505 initialQRFile = FILE_A;
1509 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1510 /// UCI interface code, whenever a non-reversible move is made in a
1511 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1512 /// for the program to handle games of arbitrary length, as long as the GUI
1513 /// handles draws by the 50 move rule correctly.
1515 void Position::reset_game_ply() {
1521 /// Position::put_piece() puts a piece on the given square of the board,
1522 /// updating the board array, bitboards, and piece counts.
1524 void Position::put_piece(Piece p, Square s) {
1526 Color c = color_of_piece(p);
1527 PieceType pt = type_of_piece(p);
1530 index[s] = pieceCount[c][pt];
1531 pieceList[c][pt][index[s]] = s;
1533 set_bit(&(byTypeBB[pt]), s);
1534 set_bit(&(byColorBB[c]), s);
1535 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1537 pieceCount[c][pt]++;
1541 /// Position::allow_oo() gives the given side the right to castle kingside.
1542 /// Used when setting castling rights during parsing of FEN strings.
1544 void Position::allow_oo(Color c) {
1546 st->castleRights |= (1 + int(c));
1550 /// Position::allow_ooo() gives the given side the right to castle queenside.
1551 /// Used when setting castling rights during parsing of FEN strings.
1553 void Position::allow_ooo(Color c) {
1555 st->castleRights |= (4 + 4*int(c));
1559 /// Position::compute_key() computes the hash key of the position. The hash
1560 /// key is usually updated incrementally as moves are made and unmade, the
1561 /// compute_key() function is only used when a new position is set up, and
1562 /// to verify the correctness of the hash key when running in debug mode.
1564 Key Position::compute_key() const {
1566 Key result = Key(0ULL);
1568 for (Square s = SQ_A1; s <= SQ_H8; s++)
1569 if (square_is_occupied(s))
1570 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1572 if (ep_square() != SQ_NONE)
1573 result ^= zobEp[ep_square()];
1575 result ^= zobCastle[st->castleRights];
1576 if (side_to_move() == BLACK)
1577 result ^= zobSideToMove;
1583 /// Position::compute_pawn_key() computes the hash key of the position. The
1584 /// hash key is usually updated incrementally as moves are made and unmade,
1585 /// the compute_pawn_key() function is only used when a new position is set
1586 /// up, and to verify the correctness of the pawn hash key when running in
1589 Key Position::compute_pawn_key() const {
1591 Key result = Key(0ULL);
1595 for (Color c = WHITE; c <= BLACK; c++)
1597 b = pieces(PAWN, c);
1600 s = pop_1st_bit(&b);
1601 result ^= zobrist[c][PAWN][s];
1608 /// Position::compute_material_key() computes the hash key of the position.
1609 /// The hash key is usually updated incrementally as moves are made and unmade,
1610 /// the compute_material_key() function is only used when a new position is set
1611 /// up, and to verify the correctness of the material hash key when running in
1614 Key Position::compute_material_key() const {
1616 Key result = Key(0ULL);
1617 for (Color c = WHITE; c <= BLACK; c++)
1618 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1620 int count = piece_count(c, pt);
1621 for (int i = 0; i <= count; i++)
1622 result ^= zobMaterial[c][pt][i];
1628 /// Position::compute_value() compute the incremental scores for the middle
1629 /// game and the endgame. These functions are used to initialize the incremental
1630 /// scores when a new position is set up, and to verify that the scores are correctly
1631 /// updated by do_move and undo_move when the program is running in debug mode.
1632 Score Position::compute_value() const {
1634 Score result = make_score(0, 0);
1638 for (Color c = WHITE; c <= BLACK; c++)
1639 for (PieceType pt = PAWN; pt <= KING; pt++)
1644 s = pop_1st_bit(&b);
1645 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1646 result += pst(c, pt, s);
1650 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1655 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1656 /// game material score for the given side. Material scores are updated
1657 /// incrementally during the search, this function is only used while
1658 /// initializing a new Position object.
1660 Value Position::compute_non_pawn_material(Color c) const {
1662 Value result = Value(0);
1664 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1666 Bitboard b = pieces(pt, c);
1669 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1671 result += piece_value_midgame(pt);
1678 /// Position::is_draw() tests whether the position is drawn by material,
1679 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1680 /// must be done by the search.
1682 bool Position::is_draw() const {
1684 // Draw by material?
1686 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1689 // Draw by the 50 moves rule?
1690 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1693 // Draw by repetition?
1694 for (int i = 2; i < Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1695 if (history[gamePly - i] == st->key)
1702 /// Position::is_mate() returns true or false depending on whether the
1703 /// side to move is checkmated.
1705 bool Position::is_mate() const {
1707 MoveStack moves[256];
1708 return is_check() && (generate_moves(*this, moves, false) == moves);
1712 /// Position::has_mate_threat() tests whether a given color has a mate in one
1713 /// from the current position.
1715 bool Position::has_mate_threat(Color c) {
1718 Color stm = side_to_move();
1723 // If the input color is not equal to the side to move, do a null move
1727 MoveStack mlist[120];
1728 bool result = false;
1729 Bitboard pinned = pinned_pieces(sideToMove);
1731 // Generate pseudo-legal non-capture and capture check moves
1732 MoveStack* last = generate_non_capture_checks(*this, mlist);
1733 last = generate_captures(*this, last);
1735 // Loop through the moves, and see if one of them is mate
1736 for (MoveStack* cur = mlist; cur != last; cur++)
1738 Move move = cur->move;
1739 if (!pl_move_is_legal(move, pinned))
1749 // Undo null move, if necessary
1757 /// Position::init_zobrist() is a static member function which initializes the
1758 /// various arrays used to compute hash keys.
1760 void Position::init_zobrist() {
1762 for (int i = 0; i < 2; i++)
1763 for (int j = 0; j < 8; j++)
1764 for (int k = 0; k < 64; k++)
1765 zobrist[i][j][k] = Key(genrand_int64());
1767 for (int i = 0; i < 64; i++)
1768 zobEp[i] = Key(genrand_int64());
1770 for (int i = 0; i < 16; i++)
1771 zobCastle[i] = genrand_int64();
1773 zobSideToMove = genrand_int64();
1775 for (int i = 0; i < 2; i++)
1776 for (int j = 0; j < 8; j++)
1777 for (int k = 0; k < 16; k++)
1778 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1780 for (int i = 0; i < 16; i++)
1781 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1785 /// Position::init_piece_square_tables() initializes the piece square tables.
1786 /// This is a two-step operation: First, the white halves of the tables are
1787 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1788 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1789 /// Second, the black halves of the tables are initialized by mirroring
1790 /// and changing the sign of the corresponding white scores.
1792 void Position::init_piece_square_tables() {
1794 int r = get_option_value_int("Randomness"), i;
1795 for (Square s = SQ_A1; s <= SQ_H8; s++)
1796 for (Piece p = WP; p <= WK; p++)
1798 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1799 PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1802 for (Square s = SQ_A1; s <= SQ_H8; s++)
1803 for (Piece p = BP; p <= BK; p++)
1804 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1808 /// Position::flipped_copy() makes a copy of the input position, but with
1809 /// the white and black sides reversed. This is only useful for debugging,
1810 /// especially for finding evaluation symmetry bugs.
1812 void Position::flipped_copy(const Position& pos) {
1814 assert(pos.is_ok());
1819 for (Square s = SQ_A1; s <= SQ_H8; s++)
1820 if (!pos.square_is_empty(s))
1821 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1824 sideToMove = opposite_color(pos.side_to_move());
1827 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1828 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1829 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1830 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1832 initialKFile = pos.initialKFile;
1833 initialKRFile = pos.initialKRFile;
1834 initialQRFile = pos.initialQRFile;
1836 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1837 castleRightsMask[sq] = ALL_CASTLES;
1839 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1840 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1841 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1842 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1843 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1844 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1846 // En passant square
1847 if (pos.st->epSquare != SQ_NONE)
1848 st->epSquare = flip_square(pos.st->epSquare);
1854 st->key = compute_key();
1855 st->pawnKey = compute_pawn_key();
1856 st->materialKey = compute_material_key();
1858 // Incremental scores
1859 st->value = compute_value();
1862 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1863 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1869 /// Position::is_ok() performs some consitency checks for the position object.
1870 /// This is meant to be helpful when debugging.
1872 bool Position::is_ok(int* failedStep) const {
1874 // What features of the position should be verified?
1875 static const bool debugBitboards = false;
1876 static const bool debugKingCount = false;
1877 static const bool debugKingCapture = false;
1878 static const bool debugCheckerCount = false;
1879 static const bool debugKey = false;
1880 static const bool debugMaterialKey = false;
1881 static const bool debugPawnKey = false;
1882 static const bool debugIncrementalEval = false;
1883 static const bool debugNonPawnMaterial = false;
1884 static const bool debugPieceCounts = false;
1885 static const bool debugPieceList = false;
1887 if (failedStep) *failedStep = 1;
1890 if (!color_is_ok(side_to_move()))
1893 // Are the king squares in the position correct?
1894 if (failedStep) (*failedStep)++;
1895 if (piece_on(king_square(WHITE)) != WK)
1898 if (failedStep) (*failedStep)++;
1899 if (piece_on(king_square(BLACK)) != BK)
1903 if (failedStep) (*failedStep)++;
1904 if (!file_is_ok(initialKRFile))
1907 if (!file_is_ok(initialQRFile))
1910 // Do both sides have exactly one king?
1911 if (failedStep) (*failedStep)++;
1914 int kingCount[2] = {0, 0};
1915 for (Square s = SQ_A1; s <= SQ_H8; s++)
1916 if (type_of_piece_on(s) == KING)
1917 kingCount[color_of_piece_on(s)]++;
1919 if (kingCount[0] != 1 || kingCount[1] != 1)
1923 // Can the side to move capture the opponent's king?
1924 if (failedStep) (*failedStep)++;
1925 if (debugKingCapture)
1927 Color us = side_to_move();
1928 Color them = opposite_color(us);
1929 Square ksq = king_square(them);
1930 if (attackers_to(ksq) & pieces_of_color(us))
1934 // Is there more than 2 checkers?
1935 if (failedStep) (*failedStep)++;
1936 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1940 if (failedStep) (*failedStep)++;
1943 // The intersection of the white and black pieces must be empty
1944 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1947 // The union of the white and black pieces must be equal to all
1949 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1952 // Separate piece type bitboards must have empty intersections
1953 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1954 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1955 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1959 // En passant square OK?
1960 if (failedStep) (*failedStep)++;
1961 if (ep_square() != SQ_NONE)
1963 // The en passant square must be on rank 6, from the point of view of the
1965 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1970 if (failedStep) (*failedStep)++;
1971 if (debugKey && st->key != compute_key())
1974 // Pawn hash key OK?
1975 if (failedStep) (*failedStep)++;
1976 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1979 // Material hash key OK?
1980 if (failedStep) (*failedStep)++;
1981 if (debugMaterialKey && st->materialKey != compute_material_key())
1984 // Incremental eval OK?
1985 if (failedStep) (*failedStep)++;
1986 if (debugIncrementalEval && st->value != compute_value())
1989 // Non-pawn material OK?
1990 if (failedStep) (*failedStep)++;
1991 if (debugNonPawnMaterial)
1993 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1996 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2001 if (failedStep) (*failedStep)++;
2002 if (debugPieceCounts)
2003 for (Color c = WHITE; c <= BLACK; c++)
2004 for (PieceType pt = PAWN; pt <= KING; pt++)
2005 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2008 if (failedStep) (*failedStep)++;
2011 for(Color c = WHITE; c <= BLACK; c++)
2012 for(PieceType pt = PAWN; pt <= KING; pt++)
2013 for(int i = 0; i < pieceCount[c][pt]; i++)
2015 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2018 if (index[piece_list(c, pt, i)] != i)
2022 if (failedStep) *failedStep = 0;