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 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);
761 PieceType capture = ep ? PAWN : type_of_piece_on(to);
763 assert(color_of_piece_on(from) == us);
764 assert(color_of_piece_on(to) == them || square_is_empty(to));
765 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
766 assert(!pm || relative_rank(us, to) == RANK_8);
769 do_capture_move(key, capture, them, to, ep);
772 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
774 // Reset en passant square
775 if (st->epSquare != SQ_NONE)
777 key ^= zobEp[st->epSquare];
778 st->epSquare = SQ_NONE;
781 // Update castle rights, try to shortcut a common case
782 int cm = castleRightsMask[from] & castleRightsMask[to];
783 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
785 key ^= zobCastle[st->castleRights];
786 st->castleRights &= castleRightsMask[from];
787 st->castleRights &= castleRightsMask[to];
788 key ^= zobCastle[st->castleRights];
791 // Prefetch TT access as soon as we know key is updated
795 Bitboard move_bb = make_move_bb(from, to);
796 do_move_bb(&(byColorBB[us]), move_bb);
797 do_move_bb(&(byTypeBB[pt]), move_bb);
798 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
800 board[to] = board[from];
803 // Update piece lists, note that index[from] is not updated and
804 // becomes stale. This works as long as index[] is accessed just
805 // by known occupied squares.
806 index[to] = index[from];
807 pieceList[us][pt][index[to]] = to;
809 // If the moving piece was a pawn do some special extra work
812 // Reset rule 50 draw counter
815 // Update pawn hash key
816 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
818 // Set en passant square, only if moved pawn can be captured
819 if ((to ^ from) == 16)
821 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
823 st->epSquare = Square((int(from) + int(to)) / 2);
824 key ^= zobEp[st->epSquare];
829 // Update incremental scores
830 st->value += pst_delta(piece, from, to);
833 st->capture = capture;
835 if (pm) // promotion ?
837 PieceType promotion = move_promotion_piece(m);
839 assert(promotion >= KNIGHT && promotion <= QUEEN);
841 // Insert promoted piece instead of pawn
842 clear_bit(&(byTypeBB[PAWN]), to);
843 set_bit(&(byTypeBB[promotion]), to);
844 board[to] = piece_of_color_and_type(us, promotion);
846 // Update material key
847 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
848 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
850 // Update piece counts
851 pieceCount[us][PAWN]--;
852 pieceCount[us][promotion]++;
854 // Update piece lists, move the last pawn at index[to] position
855 // and shrink the list. Add a new promotion piece to the list.
856 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
857 index[lastPawnSquare] = index[to];
858 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
859 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
860 index[to] = pieceCount[us][promotion] - 1;
861 pieceList[us][promotion][index[to]] = to;
863 // Partially revert hash keys update
864 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
865 st->pawnKey ^= zobrist[us][PAWN][to];
867 // Partially revert and update incremental scores
868 st->value -= pst(us, PAWN, to);
869 st->value += pst(us, promotion, to);
872 st->npMaterial[us] += piece_value_midgame(promotion);
875 // Update the key with the final value
878 // Update checkers bitboard, piece must be already moved
880 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
883 st->checkersBB = EmptyBoardBB;
884 Square ksq = king_square(them);
887 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
888 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
889 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
890 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
891 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
892 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
893 default: assert(false); break;
898 sideToMove = opposite_color(sideToMove);
899 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
905 /// Position::do_capture_move() is a private method used to update captured
906 /// piece info. It is called from the main Position::do_move function.
908 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
910 assert(capture != KING);
914 if (ep) // en passant ?
916 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
918 assert(to == st->epSquare);
919 assert(relative_rank(opposite_color(them), to) == RANK_6);
920 assert(piece_on(to) == EMPTY);
921 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
923 board[capsq] = EMPTY;
926 // Remove captured piece
927 clear_bit(&(byColorBB[them]), capsq);
928 clear_bit(&(byTypeBB[capture]), capsq);
929 clear_bit(&(byTypeBB[0]), capsq);
932 key ^= zobrist[them][capture][capsq];
934 // Update incremental scores
935 st->value -= pst(them, capture, capsq);
937 // If the captured piece was a pawn, update pawn hash key,
938 // otherwise update non-pawn material.
940 st->pawnKey ^= zobrist[them][PAWN][capsq];
942 st->npMaterial[them] -= piece_value_midgame(capture);
944 // Update material hash key
945 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
947 // Update piece count
948 pieceCount[them][capture]--;
950 // Update piece list, move the last piece at index[capsq] position
952 // WARNING: This is a not perfectly revresible operation. When we
953 // will reinsert the captured piece in undo_move() we will put it
954 // at the end of the list and not in its original place, it means
955 // index[] and pieceList[] are not guaranteed to be invariant to a
956 // do_move() + undo_move() sequence.
957 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
958 index[lastPieceSquare] = index[capsq];
959 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
960 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
962 // Reset rule 50 counter
967 /// Position::do_castle_move() is a private method used to make a castling
968 /// move. It is called from the main Position::do_move function. Note that
969 /// castling moves are encoded as "king captures friendly rook" moves, for
970 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
972 void Position::do_castle_move(Move m) {
974 assert(move_is_ok(m));
975 assert(move_is_castle(m));
977 Color us = side_to_move();
978 Color them = opposite_color(us);
980 // Reset capture field
981 st->capture = NO_PIECE_TYPE;
983 // Find source squares for king and rook
984 Square kfrom = move_from(m);
985 Square rfrom = move_to(m); // HACK: See comment at beginning of function
988 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
989 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
991 // Find destination squares for king and rook
992 if (rfrom > kfrom) // O-O
994 kto = relative_square(us, SQ_G1);
995 rto = relative_square(us, SQ_F1);
997 kto = relative_square(us, SQ_C1);
998 rto = relative_square(us, SQ_D1);
1001 // Remove pieces from source squares:
1002 clear_bit(&(byColorBB[us]), kfrom);
1003 clear_bit(&(byTypeBB[KING]), kfrom);
1004 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1005 clear_bit(&(byColorBB[us]), rfrom);
1006 clear_bit(&(byTypeBB[ROOK]), rfrom);
1007 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1009 // Put pieces on destination squares:
1010 set_bit(&(byColorBB[us]), kto);
1011 set_bit(&(byTypeBB[KING]), kto);
1012 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1013 set_bit(&(byColorBB[us]), rto);
1014 set_bit(&(byTypeBB[ROOK]), rto);
1015 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1017 // Update board array
1018 Piece king = piece_of_color_and_type(us, KING);
1019 Piece rook = piece_of_color_and_type(us, ROOK);
1020 board[kfrom] = board[rfrom] = EMPTY;
1024 // Update piece lists
1025 pieceList[us][KING][index[kfrom]] = kto;
1026 pieceList[us][ROOK][index[rfrom]] = rto;
1027 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1028 index[kto] = index[kfrom];
1031 // Update incremental scores
1032 st->value += pst_delta(king, kfrom, kto);
1033 st->value += pst_delta(rook, rfrom, rto);
1036 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1037 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1039 // Clear en passant square
1040 if (st->epSquare != SQ_NONE)
1042 st->key ^= zobEp[st->epSquare];
1043 st->epSquare = SQ_NONE;
1046 // Update castling rights
1047 st->key ^= zobCastle[st->castleRights];
1048 st->castleRights &= castleRightsMask[kfrom];
1049 st->key ^= zobCastle[st->castleRights];
1051 // Reset rule 50 counter
1054 // Update checkers BB
1055 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1058 sideToMove = opposite_color(sideToMove);
1059 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1065 /// Position::undo_move() unmakes a move. When it returns, the position should
1066 /// be restored to exactly the same state as before the move was made.
1068 void Position::undo_move(Move m) {
1071 assert(move_is_ok(m));
1074 sideToMove = opposite_color(sideToMove);
1076 if (move_is_castle(m))
1078 undo_castle_move(m);
1082 Color us = side_to_move();
1083 Color them = opposite_color(us);
1084 Square from = move_from(m);
1085 Square to = move_to(m);
1086 bool ep = move_is_ep(m);
1087 bool pm = move_is_promotion(m);
1089 PieceType pt = type_of_piece_on(to);
1091 assert(square_is_empty(from));
1092 assert(color_of_piece_on(to) == us);
1093 assert(!pm || relative_rank(us, to) == RANK_8);
1094 assert(!ep || to == st->previous->epSquare);
1095 assert(!ep || relative_rank(us, to) == RANK_6);
1096 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1098 if (pm) // promotion ?
1100 PieceType promotion = move_promotion_piece(m);
1103 assert(promotion >= KNIGHT && promotion <= QUEEN);
1104 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1106 // Replace promoted piece with a pawn
1107 clear_bit(&(byTypeBB[promotion]), to);
1108 set_bit(&(byTypeBB[PAWN]), to);
1110 // Update piece counts
1111 pieceCount[us][promotion]--;
1112 pieceCount[us][PAWN]++;
1114 // Update piece list replacing promotion piece with a pawn
1115 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1116 index[lastPromotionSquare] = index[to];
1117 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1118 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1119 index[to] = pieceCount[us][PAWN] - 1;
1120 pieceList[us][PAWN][index[to]] = to;
1124 // Put the piece back at the source square
1125 Bitboard move_bb = make_move_bb(to, from);
1126 do_move_bb(&(byColorBB[us]), move_bb);
1127 do_move_bb(&(byTypeBB[pt]), move_bb);
1128 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1130 board[from] = piece_of_color_and_type(us, pt);
1133 // Update piece list
1134 index[from] = index[to];
1135 pieceList[us][pt][index[from]] = from;
1142 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1144 assert(st->capture != KING);
1145 assert(!ep || square_is_empty(capsq));
1147 // Restore the captured piece
1148 set_bit(&(byColorBB[them]), capsq);
1149 set_bit(&(byTypeBB[st->capture]), capsq);
1150 set_bit(&(byTypeBB[0]), capsq);
1152 board[capsq] = piece_of_color_and_type(them, st->capture);
1154 // Update piece count
1155 pieceCount[them][st->capture]++;
1157 // Update piece list, add a new captured piece in capsq square
1158 index[capsq] = pieceCount[them][st->capture] - 1;
1159 pieceList[them][st->capture][index[capsq]] = capsq;
1162 // Finally point our state pointer back to the previous state
1169 /// Position::undo_castle_move() is a private method used to unmake a castling
1170 /// move. It is called from the main Position::undo_move function. Note that
1171 /// castling moves are encoded as "king captures friendly rook" moves, for
1172 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1174 void Position::undo_castle_move(Move m) {
1176 assert(move_is_ok(m));
1177 assert(move_is_castle(m));
1179 // When we have arrived here, some work has already been done by
1180 // Position::undo_move. In particular, the side to move has been switched,
1181 // so the code below is correct.
1182 Color us = side_to_move();
1184 // Find source squares for king and rook
1185 Square kfrom = move_from(m);
1186 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1189 // Find destination squares for king and rook
1190 if (rfrom > kfrom) // O-O
1192 kto = relative_square(us, SQ_G1);
1193 rto = relative_square(us, SQ_F1);
1195 kto = relative_square(us, SQ_C1);
1196 rto = relative_square(us, SQ_D1);
1199 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1200 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1202 // Remove pieces from destination squares:
1203 clear_bit(&(byColorBB[us]), kto);
1204 clear_bit(&(byTypeBB[KING]), kto);
1205 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1206 clear_bit(&(byColorBB[us]), rto);
1207 clear_bit(&(byTypeBB[ROOK]), rto);
1208 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1210 // Put pieces on source squares:
1211 set_bit(&(byColorBB[us]), kfrom);
1212 set_bit(&(byTypeBB[KING]), kfrom);
1213 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1214 set_bit(&(byColorBB[us]), rfrom);
1215 set_bit(&(byTypeBB[ROOK]), rfrom);
1216 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1219 board[rto] = board[kto] = EMPTY;
1220 board[rfrom] = piece_of_color_and_type(us, ROOK);
1221 board[kfrom] = piece_of_color_and_type(us, KING);
1223 // Update piece lists
1224 pieceList[us][KING][index[kto]] = kfrom;
1225 pieceList[us][ROOK][index[rto]] = rfrom;
1226 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1227 index[kfrom] = index[kto];
1230 // Finally point our state pointer back to the previous state
1237 /// Position::do_null_move makes() a "null move": It switches the side to move
1238 /// and updates the hash key without executing any move on the board.
1240 void Position::do_null_move(StateInfo& backupSt) {
1243 assert(!is_check());
1245 // Back up the information necessary to undo the null move to the supplied
1246 // StateInfo object.
1247 // Note that differently from normal case here backupSt is actually used as
1248 // a backup storage not as a new state to be used.
1249 backupSt.key = st->key;
1250 backupSt.epSquare = st->epSquare;
1251 backupSt.value = st->value;
1252 backupSt.previous = st->previous;
1253 backupSt.pliesFromNull = st->pliesFromNull;
1254 st->previous = &backupSt;
1256 // Save the current key to the history[] array, in order to be able to
1257 // detect repetition draws.
1258 history[gamePly] = st->key;
1260 // Update the necessary information
1261 if (st->epSquare != SQ_NONE)
1262 st->key ^= zobEp[st->epSquare];
1264 st->key ^= zobSideToMove;
1265 TT.prefetch(st->key);
1267 sideToMove = opposite_color(sideToMove);
1268 st->epSquare = SQ_NONE;
1270 st->pliesFromNull = 0;
1271 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1276 /// Position::undo_null_move() unmakes a "null move".
1278 void Position::undo_null_move() {
1281 assert(!is_check());
1283 // Restore information from the our backup StateInfo object
1284 StateInfo* backupSt = st->previous;
1285 st->key = backupSt->key;
1286 st->epSquare = backupSt->epSquare;
1287 st->value = backupSt->value;
1288 st->previous = backupSt->previous;
1289 st->pliesFromNull = backupSt->pliesFromNull;
1291 // Update the necessary information
1292 sideToMove = opposite_color(sideToMove);
1298 /// Position::see() is a static exchange evaluator: It tries to estimate the
1299 /// material gain or loss resulting from a move. There are three versions of
1300 /// this function: One which takes a destination square as input, one takes a
1301 /// move, and one which takes a 'from' and a 'to' square. The function does
1302 /// not yet understand promotions captures.
1304 int Position::see(Square to) const {
1306 assert(square_is_ok(to));
1307 return see(SQ_NONE, to);
1310 int Position::see(Move m) const {
1312 assert(move_is_ok(m));
1313 return see(move_from(m), move_to(m));
1316 int Position::see_sign(Move m) const {
1318 assert(move_is_ok(m));
1320 Square from = move_from(m);
1321 Square to = move_to(m);
1323 // Early return if SEE cannot be negative because capturing piece value
1324 // is not bigger then captured one.
1325 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1326 && type_of_piece_on(from) != KING)
1329 return see(from, to);
1332 int Position::see(Square from, Square to) const {
1335 static const int seeValues[18] = {
1336 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1337 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1338 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1339 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1343 Bitboard attackers, stmAttackers, b;
1345 assert(square_is_ok(from) || from == SQ_NONE);
1346 assert(square_is_ok(to));
1348 // Initialize colors
1349 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1350 Color them = opposite_color(us);
1352 // Initialize pieces
1353 Piece piece = piece_on(from);
1354 Piece capture = piece_on(to);
1355 Bitboard occ = occupied_squares();
1357 // King cannot be recaptured
1358 if (type_of_piece(piece) == KING)
1359 return seeValues[capture];
1361 // Handle en passant moves
1362 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1364 assert(capture == EMPTY);
1366 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1367 capture = piece_on(capQq);
1368 assert(type_of_piece_on(capQq) == PAWN);
1370 // Remove the captured pawn
1371 clear_bit(&occ, capQq);
1376 // Find all attackers to the destination square, with the moving piece
1377 // removed, but possibly an X-ray attacker added behind it.
1378 clear_bit(&occ, from);
1379 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1380 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1381 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1382 | (attacks_from<KING>(to) & pieces(KING))
1383 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1384 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1386 if (from != SQ_NONE)
1389 // If we don't have any attacker we are finished
1390 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1393 // Locate the least valuable attacker to the destination square
1394 // and use it to initialize from square.
1395 stmAttackers = attackers & pieces_of_color(us);
1397 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1400 from = first_1(stmAttackers & pieces(pt));
1401 piece = piece_on(from);
1404 // If the opponent has no attackers we are finished
1405 stmAttackers = attackers & pieces_of_color(them);
1407 return seeValues[capture];
1409 attackers &= occ; // Remove the moving piece
1411 // The destination square is defended, which makes things rather more
1412 // difficult to compute. We proceed by building up a "swap list" containing
1413 // the material gain or loss at each stop in a sequence of captures to the
1414 // destination square, where the sides alternately capture, and always
1415 // capture with the least valuable piece. After each capture, we look for
1416 // new X-ray attacks from behind the capturing piece.
1417 int lastCapturingPieceValue = seeValues[piece];
1418 int swapList[32], n = 1;
1422 swapList[0] = seeValues[capture];
1425 // Locate the least valuable attacker for the side to move. The loop
1426 // below looks like it is potentially infinite, but it isn't. We know
1427 // that the side to move still has at least one attacker left.
1428 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1431 // Remove the attacker we just found from the 'attackers' bitboard,
1432 // and scan for new X-ray attacks behind the attacker.
1433 b = stmAttackers & pieces(pt);
1434 occ ^= (b & (~b + 1));
1435 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1436 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1440 // Add the new entry to the swap list
1442 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1445 // Remember the value of the capturing piece, and change the side to move
1446 // before beginning the next iteration
1447 lastCapturingPieceValue = seeValues[pt];
1448 c = opposite_color(c);
1449 stmAttackers = attackers & pieces_of_color(c);
1451 // Stop after a king capture
1452 if (pt == KING && stmAttackers)
1455 swapList[n++] = QueenValueMidgame*10;
1458 } while (stmAttackers);
1460 // Having built the swap list, we negamax through it to find the best
1461 // achievable score from the point of view of the side to move
1463 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1469 /// Position::saveState() copies the content of the current state
1470 /// inside startState and makes st point to it. This is needed
1471 /// when the st pointee could become stale, as example because
1472 /// the caller is about to going out of scope.
1474 void Position::saveState() {
1478 st->previous = NULL; // as a safe guard
1482 /// Position::clear() erases the position object to a pristine state, with an
1483 /// empty board, white to move, and no castling rights.
1485 void Position::clear() {
1488 memset(st, 0, sizeof(StateInfo));
1489 st->epSquare = SQ_NONE;
1491 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1492 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1493 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1494 memset(index, 0, sizeof(int) * 64);
1496 for (int i = 0; i < 64; i++)
1499 for (int i = 0; i < 8; i++)
1500 for (int j = 0; j < 16; j++)
1501 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1505 initialKFile = FILE_E;
1506 initialKRFile = FILE_H;
1507 initialQRFile = FILE_A;
1511 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1512 /// UCI interface code, whenever a non-reversible move is made in a
1513 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1514 /// for the program to handle games of arbitrary length, as long as the GUI
1515 /// handles draws by the 50 move rule correctly.
1517 void Position::reset_game_ply() {
1523 /// Position::put_piece() puts a piece on the given square of the board,
1524 /// updating the board array, bitboards, and piece counts.
1526 void Position::put_piece(Piece p, Square s) {
1528 Color c = color_of_piece(p);
1529 PieceType pt = type_of_piece(p);
1532 index[s] = pieceCount[c][pt];
1533 pieceList[c][pt][index[s]] = s;
1535 set_bit(&(byTypeBB[pt]), s);
1536 set_bit(&(byColorBB[c]), s);
1537 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1539 pieceCount[c][pt]++;
1543 /// Position::allow_oo() gives the given side the right to castle kingside.
1544 /// Used when setting castling rights during parsing of FEN strings.
1546 void Position::allow_oo(Color c) {
1548 st->castleRights |= (1 + int(c));
1552 /// Position::allow_ooo() gives the given side the right to castle queenside.
1553 /// Used when setting castling rights during parsing of FEN strings.
1555 void Position::allow_ooo(Color c) {
1557 st->castleRights |= (4 + 4*int(c));
1561 /// Position::compute_key() computes the hash key of the position. The hash
1562 /// key is usually updated incrementally as moves are made and unmade, the
1563 /// compute_key() function is only used when a new position is set up, and
1564 /// to verify the correctness of the hash key when running in debug mode.
1566 Key Position::compute_key() const {
1568 Key result = Key(0ULL);
1570 for (Square s = SQ_A1; s <= SQ_H8; s++)
1571 if (square_is_occupied(s))
1572 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1574 if (ep_square() != SQ_NONE)
1575 result ^= zobEp[ep_square()];
1577 result ^= zobCastle[st->castleRights];
1578 if (side_to_move() == BLACK)
1579 result ^= zobSideToMove;
1585 /// Position::compute_pawn_key() computes the hash key of the position. The
1586 /// hash key is usually updated incrementally as moves are made and unmade,
1587 /// the compute_pawn_key() function is only used when a new position is set
1588 /// up, and to verify the correctness of the pawn hash key when running in
1591 Key Position::compute_pawn_key() const {
1593 Key result = Key(0ULL);
1597 for (Color c = WHITE; c <= BLACK; c++)
1599 b = pieces(PAWN, c);
1602 s = pop_1st_bit(&b);
1603 result ^= zobrist[c][PAWN][s];
1610 /// Position::compute_material_key() computes the hash key of the position.
1611 /// The hash key is usually updated incrementally as moves are made and unmade,
1612 /// the compute_material_key() function is only used when a new position is set
1613 /// up, and to verify the correctness of the material hash key when running in
1616 Key Position::compute_material_key() const {
1618 Key result = Key(0ULL);
1619 for (Color c = WHITE; c <= BLACK; c++)
1620 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1622 int count = piece_count(c, pt);
1623 for (int i = 0; i <= count; i++)
1624 result ^= zobMaterial[c][pt][i];
1630 /// Position::compute_value() compute the incremental scores for the middle
1631 /// game and the endgame. These functions are used to initialize the incremental
1632 /// scores when a new position is set up, and to verify that the scores are correctly
1633 /// updated by do_move and undo_move when the program is running in debug mode.
1634 Score Position::compute_value() const {
1636 Score result = make_score(0, 0);
1640 for (Color c = WHITE; c <= BLACK; c++)
1641 for (PieceType pt = PAWN; pt <= KING; pt++)
1646 s = pop_1st_bit(&b);
1647 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1648 result += pst(c, pt, s);
1652 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1657 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1658 /// game material score for the given side. Material scores are updated
1659 /// incrementally during the search, this function is only used while
1660 /// initializing a new Position object.
1662 Value Position::compute_non_pawn_material(Color c) const {
1664 Value result = Value(0);
1666 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1668 Bitboard b = pieces(pt, c);
1671 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1673 result += piece_value_midgame(pt);
1680 /// Position::is_draw() tests whether the position is drawn by material,
1681 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1682 /// must be done by the search.
1684 bool Position::is_draw() const {
1686 // Draw by material?
1688 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1691 // Draw by the 50 moves rule?
1692 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1695 // Draw by repetition?
1696 for (int i = 2; i < Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1697 if (history[gamePly - i] == st->key)
1704 /// Position::is_mate() returns true or false depending on whether the
1705 /// side to move is checkmated.
1707 bool Position::is_mate() const {
1709 MoveStack moves[256];
1710 return is_check() && (generate_moves(*this, moves, false) == moves);
1714 /// Position::has_mate_threat() tests whether a given color has a mate in one
1715 /// from the current position.
1717 bool Position::has_mate_threat(Color c) {
1720 Color stm = side_to_move();
1725 // If the input color is not equal to the side to move, do a null move
1729 MoveStack mlist[120];
1730 bool result = false;
1731 Bitboard pinned = pinned_pieces(sideToMove);
1733 // Generate pseudo-legal non-capture and capture check moves
1734 MoveStack* last = generate_non_capture_checks(*this, mlist);
1735 last = generate_captures(*this, last);
1737 // Loop through the moves, and see if one of them is mate
1738 for (MoveStack* cur = mlist; cur != last; cur++)
1740 Move move = cur->move;
1741 if (!pl_move_is_legal(move, pinned))
1751 // Undo null move, if necessary
1759 /// Position::init_zobrist() is a static member function which initializes the
1760 /// various arrays used to compute hash keys.
1762 void Position::init_zobrist() {
1764 for (int i = 0; i < 2; i++)
1765 for (int j = 0; j < 8; j++)
1766 for (int k = 0; k < 64; k++)
1767 zobrist[i][j][k] = Key(genrand_int64());
1769 for (int i = 0; i < 64; i++)
1770 zobEp[i] = Key(genrand_int64());
1772 for (int i = 0; i < 16; i++)
1773 zobCastle[i] = genrand_int64();
1775 zobSideToMove = genrand_int64();
1777 for (int i = 0; i < 2; i++)
1778 for (int j = 0; j < 8; j++)
1779 for (int k = 0; k < 16; k++)
1780 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1782 for (int i = 0; i < 16; i++)
1783 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1787 /// Position::init_piece_square_tables() initializes the piece square tables.
1788 /// This is a two-step operation: First, the white halves of the tables are
1789 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1790 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1791 /// Second, the black halves of the tables are initialized by mirroring
1792 /// and changing the sign of the corresponding white scores.
1794 void Position::init_piece_square_tables() {
1796 int r = get_option_value_int("Randomness"), i;
1797 for (Square s = SQ_A1; s <= SQ_H8; s++)
1798 for (Piece p = WP; p <= WK; p++)
1800 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1801 PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1804 for (Square s = SQ_A1; s <= SQ_H8; s++)
1805 for (Piece p = BP; p <= BK; p++)
1806 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1810 /// Position::flipped_copy() makes a copy of the input position, but with
1811 /// the white and black sides reversed. This is only useful for debugging,
1812 /// especially for finding evaluation symmetry bugs.
1814 void Position::flipped_copy(const Position& pos) {
1816 assert(pos.is_ok());
1821 for (Square s = SQ_A1; s <= SQ_H8; s++)
1822 if (!pos.square_is_empty(s))
1823 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1826 sideToMove = opposite_color(pos.side_to_move());
1829 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1830 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1831 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1832 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1834 initialKFile = pos.initialKFile;
1835 initialKRFile = pos.initialKRFile;
1836 initialQRFile = pos.initialQRFile;
1838 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1839 castleRightsMask[sq] = ALL_CASTLES;
1841 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1842 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1843 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1844 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1845 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1846 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1848 // En passant square
1849 if (pos.st->epSquare != SQ_NONE)
1850 st->epSquare = flip_square(pos.st->epSquare);
1856 st->key = compute_key();
1857 st->pawnKey = compute_pawn_key();
1858 st->materialKey = compute_material_key();
1860 // Incremental scores
1861 st->value = compute_value();
1864 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1865 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1871 /// Position::is_ok() performs some consitency checks for the position object.
1872 /// This is meant to be helpful when debugging.
1874 bool Position::is_ok(int* failedStep) const {
1876 // What features of the position should be verified?
1877 static const bool debugBitboards = false;
1878 static const bool debugKingCount = false;
1879 static const bool debugKingCapture = false;
1880 static const bool debugCheckerCount = false;
1881 static const bool debugKey = false;
1882 static const bool debugMaterialKey = false;
1883 static const bool debugPawnKey = false;
1884 static const bool debugIncrementalEval = false;
1885 static const bool debugNonPawnMaterial = false;
1886 static const bool debugPieceCounts = false;
1887 static const bool debugPieceList = false;
1889 if (failedStep) *failedStep = 1;
1892 if (!color_is_ok(side_to_move()))
1895 // Are the king squares in the position correct?
1896 if (failedStep) (*failedStep)++;
1897 if (piece_on(king_square(WHITE)) != WK)
1900 if (failedStep) (*failedStep)++;
1901 if (piece_on(king_square(BLACK)) != BK)
1905 if (failedStep) (*failedStep)++;
1906 if (!file_is_ok(initialKRFile))
1909 if (!file_is_ok(initialQRFile))
1912 // Do both sides have exactly one king?
1913 if (failedStep) (*failedStep)++;
1916 int kingCount[2] = {0, 0};
1917 for (Square s = SQ_A1; s <= SQ_H8; s++)
1918 if (type_of_piece_on(s) == KING)
1919 kingCount[color_of_piece_on(s)]++;
1921 if (kingCount[0] != 1 || kingCount[1] != 1)
1925 // Can the side to move capture the opponent's king?
1926 if (failedStep) (*failedStep)++;
1927 if (debugKingCapture)
1929 Color us = side_to_move();
1930 Color them = opposite_color(us);
1931 Square ksq = king_square(them);
1932 if (attackers_to(ksq) & pieces_of_color(us))
1936 // Is there more than 2 checkers?
1937 if (failedStep) (*failedStep)++;
1938 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1942 if (failedStep) (*failedStep)++;
1945 // The intersection of the white and black pieces must be empty
1946 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1949 // The union of the white and black pieces must be equal to all
1951 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1954 // Separate piece type bitboards must have empty intersections
1955 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1956 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1957 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1961 // En passant square OK?
1962 if (failedStep) (*failedStep)++;
1963 if (ep_square() != SQ_NONE)
1965 // The en passant square must be on rank 6, from the point of view of the
1967 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1972 if (failedStep) (*failedStep)++;
1973 if (debugKey && st->key != compute_key())
1976 // Pawn hash key OK?
1977 if (failedStep) (*failedStep)++;
1978 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1981 // Material hash key OK?
1982 if (failedStep) (*failedStep)++;
1983 if (debugMaterialKey && st->materialKey != compute_material_key())
1986 // Incremental eval OK?
1987 if (failedStep) (*failedStep)++;
1988 if (debugIncrementalEval && st->value != compute_value())
1991 // Non-pawn material OK?
1992 if (failedStep) (*failedStep)++;
1993 if (debugNonPawnMaterial)
1995 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1998 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2003 if (failedStep) (*failedStep)++;
2004 if (debugPieceCounts)
2005 for (Color c = WHITE; c <= BLACK; c++)
2006 for (PieceType pt = PAWN; pt <= KING; pt++)
2007 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2010 if (failedStep) (*failedStep)++;
2013 for(Color c = WHITE; c <= BLACK; c++)
2014 for(PieceType pt = PAWN; pt <= KING; pt++)
2015 for(int i = 0; i < pieceCount[c][pt]; i++)
2017 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2020 if (index[piece_list(c, pt, i)] != i)
2024 if (failedStep) *failedStep = 0;