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 Value Position::MgPieceSquareTable[16][64];
56 Value Position::EgPieceSquareTable[16][64];
58 static bool RequestPending = false;
66 Position::Position(const Position& pos) {
70 Position::Position(const string& fen) {
75 /// Position::from_fen() initializes the position object with the given FEN
76 /// string. This function is not very robust - make sure that input FENs are
77 /// correct (this is assumed to be the responsibility of the GUI).
79 void Position::from_fen(const string& fen) {
81 static const string pieceLetters = "KQRBNPkqrbnp";
82 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
90 for ( ; fen[i] != ' '; i++)
94 // Skip the given number of files
95 file += (fen[i] - '1' + 1);
98 else if (fen[i] == '/')
104 size_t idx = pieceLetters.find(fen[i]);
105 if (idx == string::npos)
107 std::cout << "Error in FEN at character " << i << std::endl;
110 Square square = make_square(file, rank);
111 put_piece(pieces[idx], square);
117 if (fen[i] != 'w' && fen[i] != 'b')
119 std::cout << "Error in FEN at character " << i << std::endl;
122 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
128 std::cout << "Error in FEN at character " << i << std::endl;
133 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
139 else if(fen[i] == 'K') allow_oo(WHITE);
140 else if(fen[i] == 'Q') allow_ooo(WHITE);
141 else if(fen[i] == 'k') allow_oo(BLACK);
142 else if(fen[i] == 'q') allow_ooo(BLACK);
143 else if(fen[i] >= 'A' && fen[i] <= 'H') {
144 File rookFile, kingFile = FILE_NONE;
145 for(Square square = SQ_B1; square <= SQ_G1; square++)
146 if(piece_on(square) == WK)
147 kingFile = square_file(square);
148 if(kingFile == FILE_NONE) {
149 std::cout << "Error in FEN at character " << i << std::endl;
152 initialKFile = kingFile;
153 rookFile = File(fen[i] - 'A') + FILE_A;
154 if(rookFile < initialKFile) {
156 initialQRFile = rookFile;
160 initialKRFile = rookFile;
163 else if(fen[i] >= 'a' && fen[i] <= 'h') {
164 File rookFile, kingFile = FILE_NONE;
165 for(Square square = SQ_B8; square <= SQ_G8; square++)
166 if(piece_on(square) == BK)
167 kingFile = square_file(square);
168 if(kingFile == FILE_NONE) {
169 std::cout << "Error in FEN at character " << i << std::endl;
172 initialKFile = kingFile;
173 rookFile = File(fen[i] - 'a') + FILE_A;
174 if(rookFile < initialKFile) {
176 initialQRFile = rookFile;
180 initialKRFile = rookFile;
184 std::cout << "Error in FEN at character " << i << std::endl;
191 while (fen[i] == ' ')
195 if ( i <= fen.length() - 2
196 && (fen[i] >= 'a' && fen[i] <= 'h')
197 && (fen[i+1] == '3' || fen[i+1] == '6'))
198 st->epSquare = square_from_string(fen.substr(i, 2));
200 // Various initialisation
201 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
202 castleRightsMask[sq] = ALL_CASTLES;
204 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
205 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
206 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
207 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
208 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
209 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
213 st->key = compute_key();
214 st->pawnKey = compute_pawn_key();
215 st->materialKey = compute_material_key();
216 st->mgValue = compute_value<MidGame>();
217 st->egValue = compute_value<EndGame>();
218 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
219 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
223 /// Position::to_fen() converts the position object to a FEN string. This is
224 /// probably only useful for debugging.
226 const string Position::to_fen() const {
228 static const string pieceLetters = " PNBRQK pnbrqk";
232 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
235 for (File file = FILE_A; file <= FILE_H; file++)
237 Square sq = make_square(file, rank);
238 if (!square_is_occupied(sq))
244 fen += (char)skip + '0';
247 fen += pieceLetters[piece_on(sq)];
250 fen += (char)skip + '0';
252 fen += (rank > RANK_1 ? '/' : ' ');
254 fen += (sideToMove == WHITE ? "w " : "b ");
255 if (st->castleRights != NO_CASTLES)
257 if (can_castle_kingside(WHITE)) fen += 'K';
258 if (can_castle_queenside(WHITE)) fen += 'Q';
259 if (can_castle_kingside(BLACK)) fen += 'k';
260 if (can_castle_queenside(BLACK)) fen += 'q';
265 if (ep_square() != SQ_NONE)
266 fen += square_to_string(ep_square());
274 /// Position::print() prints an ASCII representation of the position to
275 /// the standard output. If a move is given then also the san is print.
277 void Position::print(Move m) const {
279 static const string pieceLetters = " PNBRQK PNBRQK .";
281 // Check for reentrancy, as example when called from inside
282 // MovePicker that is used also here in move_to_san()
286 RequestPending = true;
288 std::cout << std::endl;
291 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
292 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
294 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
296 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
297 for (File file = FILE_A; file <= FILE_H; file++)
299 Square sq = make_square(file, rank);
300 Piece piece = piece_on(sq);
301 if (piece == EMPTY && square_color(sq) == WHITE)
304 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
305 std::cout << '|' << col << pieceLetters[piece] << col;
307 std::cout << '|' << std::endl;
309 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
310 << "Fen is: " << to_fen() << std::endl
311 << "Key is: " << st->key << std::endl;
313 RequestPending = false;
317 /// Position::copy() creates a copy of the input position.
319 void Position::copy(const Position& pos) {
321 memcpy(this, &pos, sizeof(Position));
322 saveState(); // detach and copy state info
326 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
327 /// king) pieces for the given color and for the given pinner type. Or, when
328 /// template parameter FindPinned is false, the pieces of the given color
329 /// candidate for a discovery check against the enemy king.
330 /// Note that checkersBB bitboard must be already updated.
332 template<bool FindPinned>
333 Bitboard Position::hidden_checkers(Color c) const {
335 Bitboard pinners, result = EmptyBoardBB;
337 // Pinned pieces protect our king, dicovery checks attack
339 Square ksq = king_square(FindPinned ? c : opposite_color(c));
341 // Pinners are sliders, not checkers, that give check when
342 // candidate pinned is removed.
343 pinners = (rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
344 | (bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq]);
346 if (FindPinned && pinners)
347 pinners &= ~st->checkersBB;
351 Square s = pop_1st_bit(&pinners);
352 Bitboard b = squares_between(s, ksq) & occupied_squares();
356 if ( !(b & (b - 1)) // Only one bit set?
357 && (b & pieces_of_color(c))) // Is an our piece?
364 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
365 /// king) pieces for the given color.
367 Bitboard Position::pinned_pieces(Color c) const {
369 return hidden_checkers<true>(c);
373 /// Position:discovered_check_candidates() returns a bitboard containing all
374 /// pieces for the given side which are candidates for giving a discovered
377 Bitboard Position::discovered_check_candidates(Color c) const {
379 return hidden_checkers<false>(c);
382 /// Position::attacks_to() computes a bitboard containing all pieces which
383 /// attacks a given square.
385 Bitboard Position::attacks_to(Square s) const {
387 return (pawn_attacks(BLACK, s) & pawns(WHITE))
388 | (pawn_attacks(WHITE, s) & pawns(BLACK))
389 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
390 | (piece_attacks<ROOK>(s) & rooks_and_queens())
391 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
392 | (piece_attacks<KING>(s) & pieces_of_type(KING));
395 /// Position::piece_attacks_square() tests whether the piece on square f
396 /// attacks square t.
398 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
400 assert(square_is_ok(f));
401 assert(square_is_ok(t));
405 case WP: return pawn_attacks_square(WHITE, f, t);
406 case BP: return pawn_attacks_square(BLACK, f, t);
407 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
408 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
409 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
410 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
411 case WK: case BK: return piece_attacks_square<KING>(f, t);
418 /// Position::move_attacks_square() tests whether a move from the current
419 /// position attacks a given square.
421 bool Position::move_attacks_square(Move m, Square s) const {
423 assert(move_is_ok(m));
424 assert(square_is_ok(s));
426 Square f = move_from(m), t = move_to(m);
428 assert(square_is_occupied(f));
430 if (piece_attacks_square(piece_on(f), t, s))
433 // Move the piece and scan for X-ray attacks behind it
434 Bitboard occ = occupied_squares();
435 Color us = color_of_piece_on(f);
438 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
439 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
441 // If we have attacks we need to verify that are caused by our move
442 // and are not already existent ones.
443 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
447 /// Position::find_checkers() computes the checkersBB bitboard, which
448 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
449 /// currently works by calling Position::attacks_to, which is probably
450 /// inefficient. Consider rewriting this function to use the last move
451 /// played, like in non-bitboard versions of Glaurung.
453 void Position::find_checkers() {
455 Color us = side_to_move();
456 st->checkersBB = attacks_to(king_square(us), opposite_color(us));
460 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
462 bool Position::pl_move_is_legal(Move m) const {
464 // If we're in check, all pseudo-legal moves are legal, because our
465 // check evasion generator only generates true legal moves.
466 return is_check() || pl_move_is_legal(m, pinned_pieces(side_to_move()));
469 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
472 assert(move_is_ok(m));
473 assert(pinned == pinned_pieces(side_to_move()));
476 // Castling moves are checked for legality during move generation.
477 if (move_is_castle(m))
480 Color us = side_to_move();
481 Square from = move_from(m);
482 Square ksq = king_square(us);
484 assert(color_of_piece_on(from) == us);
485 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
487 // En passant captures are a tricky special case. Because they are
488 // rather uncommon, we do it simply by testing whether the king is attacked
489 // after the move is made
492 Color them = opposite_color(us);
493 Square to = move_to(m);
494 Square capsq = make_square(square_file(to), square_rank(from));
495 Bitboard b = occupied_squares();
497 assert(to == ep_square());
498 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
499 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
500 assert(piece_on(to) == EMPTY);
503 clear_bit(&b, capsq);
506 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
507 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
510 // If the moving piece is a king, check whether the destination
511 // square is attacked by the opponent.
513 return !(square_is_attacked(move_to(m), opposite_color(us)));
515 // A non-king move is legal if and only if it is not pinned or it
516 // is moving along the ray towards or away from the king.
518 || !bit_is_set(pinned, from)
519 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
523 /// Position::move_is_check() tests whether a pseudo-legal move is a check
525 bool Position::move_is_check(Move m) const {
527 Bitboard dc = discovered_check_candidates(side_to_move());
528 return move_is_check(m, dc);
531 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
534 assert(move_is_ok(m));
535 assert(dcCandidates == discovered_check_candidates(side_to_move()));
537 Color us = side_to_move();
538 Color them = opposite_color(us);
539 Square from = move_from(m);
540 Square to = move_to(m);
541 Square ksq = king_square(them);
543 assert(color_of_piece_on(from) == us);
544 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
546 // Proceed according to the type of the moving piece
547 switch (type_of_piece_on(from))
551 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
554 if ( dcCandidates // Discovered check?
555 && bit_is_set(dcCandidates, from)
556 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
559 if (move_is_promotion(m)) // Promotion with check?
561 Bitboard b = occupied_squares();
564 switch (move_promotion_piece(m))
567 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
569 return bit_is_set(bishop_attacks_bb(to, b), ksq);
571 return bit_is_set(rook_attacks_bb(to, b), ksq);
573 return bit_is_set(queen_attacks_bb(to, b), ksq);
578 // En passant capture with check? We have already handled the case
579 // of direct checks and ordinary discovered check, the only case we
580 // need to handle is the unusual case of a discovered check through the
582 else if (move_is_ep(m))
584 Square capsq = make_square(square_file(to), square_rank(from));
585 Bitboard b = occupied_squares();
587 clear_bit(&b, capsq);
589 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
590 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
594 // Test discovered check and normal check according to piece type
596 return (dcCandidates && bit_is_set(dcCandidates, from))
597 || bit_is_set(piece_attacks<KNIGHT>(ksq), to);
600 return (dcCandidates && bit_is_set(dcCandidates, from))
601 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to));
604 return (dcCandidates && bit_is_set(dcCandidates, from))
605 || (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to));
608 // Discovered checks are impossible!
609 assert(!bit_is_set(dcCandidates, from));
610 return ( (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to))
611 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to)));
615 if ( bit_is_set(dcCandidates, from)
616 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
619 // Castling with check?
620 if (move_is_castle(m))
622 Square kfrom, kto, rfrom, rto;
623 Bitboard b = occupied_squares();
629 kto = relative_square(us, SQ_G1);
630 rto = relative_square(us, SQ_F1);
632 kto = relative_square(us, SQ_C1);
633 rto = relative_square(us, SQ_D1);
635 clear_bit(&b, kfrom);
636 clear_bit(&b, rfrom);
639 return bit_is_set(rook_attacks_bb(rto, b), ksq);
643 default: // NO_PIECE_TYPE
651 /// Position::update_checkers() udpates chekers info given the move. It is called
652 /// in do_move() and is faster then find_checkers().
654 template<PieceType Piece>
655 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
656 Square to, Bitboard dcCandidates) {
658 const bool Bishop = (Piece == QUEEN || Piece == BISHOP);
659 const bool Rook = (Piece == QUEEN || Piece == ROOK);
660 const bool Slider = Bishop || Rook;
663 if ( ( (Bishop && bit_is_set(BishopPseudoAttacks[ksq], to))
664 || (Rook && bit_is_set(RookPseudoAttacks[ksq], to)))
665 && bit_is_set(piece_attacks<Piece>(ksq), to)) // slow, try to early skip
666 set_bit(pCheckersBB, to);
668 else if ( Piece != KING
670 && bit_is_set(piece_attacks<Piece>(ksq), to))
671 set_bit(pCheckersBB, to);
674 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
677 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
680 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
685 /// Position::do_move() makes a move, and saves all information necessary
686 /// to a StateInfo object. The move is assumed to be legal.
687 /// Pseudo-legal moves should be filtered out before this function is called.
689 void Position::do_move(Move m, StateInfo& newSt) {
691 do_move(m, newSt, discovered_check_candidates(side_to_move()));
694 void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
697 assert(move_is_ok(m));
699 Bitboard key = st->key;
701 // Copy some fields of old state to our new StateInfo object except the
702 // ones which are recalculated from scratch anyway, then switch our state
703 // pointer to point to the new, ready to be updated, state.
704 struct ReducedStateInfo {
705 Key key, pawnKey, materialKey;
706 int castleRights, rule50;
708 Value mgValue, egValue;
712 memcpy(&newSt, st, sizeof(ReducedStateInfo));
716 // Save the current key to the history[] array, in order to be able to
717 // detect repetition draws.
718 history[gamePly] = key;
721 // Update side to move
722 key ^= zobSideToMove;
724 // Increment the 50 moves rule draw counter. Resetting it to zero in the
725 // case of non-reversible moves is taken care of later.
728 if (move_is_castle(m))
735 Color us = side_to_move();
736 Color them = opposite_color(us);
737 Square from = move_from(m);
738 Square to = move_to(m);
739 bool ep = move_is_ep(m);
740 bool pm = move_is_promotion(m);
742 Piece piece = piece_on(from);
743 PieceType pt = type_of_piece(piece);
745 assert(color_of_piece_on(from) == us);
746 assert(color_of_piece_on(to) == them || square_is_empty(to));
747 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
748 assert(!pm || relative_rank(us, to) == RANK_8);
750 st->capture = ep ? PAWN : type_of_piece_on(to);
753 do_capture_move(key, st->capture, them, to, ep);
756 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
758 // Reset en passant square
759 if (st->epSquare != SQ_NONE)
761 key ^= zobEp[st->epSquare];
762 st->epSquare = SQ_NONE;
765 // Update castle rights, try to shortcut a common case
766 int cm = castleRightsMask[from] & castleRightsMask[to];
767 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
769 key ^= zobCastle[st->castleRights];
770 st->castleRights &= castleRightsMask[from];
771 st->castleRights &= castleRightsMask[to];
772 key ^= zobCastle[st->castleRights];
775 // Prefetch TT access as soon as we know key is updated
779 Bitboard move_bb = make_move_bb(from, to);
780 do_move_bb(&(byColorBB[us]), move_bb);
781 do_move_bb(&(byTypeBB[pt]), move_bb);
782 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
784 board[to] = board[from];
787 // If the moving piece was a king, update the king square
791 // Update piece lists, note that index[from] is not updated and
792 // becomes stale. This works as long as index[] is accessed just
793 // by known occupied squares.
794 index[to] = index[from];
795 pieceList[us][pt][index[to]] = to;
797 // If the moving piece was a pawn do some special extra work
800 // Reset rule 50 draw counter
803 // Update pawn hash key
804 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
806 // Set en passant square, only if moved pawn can be captured
807 if (abs(int(to) - int(from)) == 16)
809 if (pawn_attacks(us, from + (us == WHITE ? DELTA_N : DELTA_S)) & pawns(them))
811 st->epSquare = Square((int(from) + int(to)) / 2);
812 key ^= zobEp[st->epSquare];
817 // Update incremental scores
818 st->mgValue += pst_delta<MidGame>(piece, from, to);
819 st->egValue += pst_delta<EndGame>(piece, from, to);
821 if (pm) // promotion ?
823 PieceType promotion = move_promotion_piece(m);
825 assert(promotion >= KNIGHT && promotion <= QUEEN);
827 // Insert promoted piece instead of pawn
828 clear_bit(&(byTypeBB[PAWN]), to);
829 set_bit(&(byTypeBB[promotion]), to);
830 board[to] = piece_of_color_and_type(us, promotion);
832 // Update piece counts
833 pieceCount[us][PAWN]--;
834 pieceCount[us][promotion]++;
836 // Update piece lists, move the last pawn at index[to] position
837 // and shrink the list. Add a new promotion piece to the list.
838 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
839 index[lastPawnSquare] = index[to];
840 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
841 index[to] = pieceCount[us][promotion] - 1;
842 pieceList[us][promotion][index[to]] = to;
844 // Partially revert hash keys update
845 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
846 st->pawnKey ^= zobrist[us][PAWN][to];
848 // Update material key
849 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
850 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
852 // Partially revert and update incremental scores
853 st->mgValue -= pst<MidGame>(us, PAWN, to);
854 st->mgValue += pst<MidGame>(us, promotion, to);
855 st->egValue -= pst<EndGame>(us, PAWN, to);
856 st->egValue += pst<EndGame>(us, promotion, to);
859 st->npMaterial[us] += piece_value_midgame(promotion);
862 // Update the key with the final value
865 // Update checkers bitboard, piece must be already moved
867 st->checkersBB = attacks_to(king_square(them), us);
870 st->checkersBB = EmptyBoardBB;
871 Square ksq = king_square(them);
874 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
875 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
876 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
877 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
878 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
879 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
880 default: assert(false); break;
885 sideToMove = opposite_color(sideToMove);
887 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
888 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
892 /// Position::do_capture_move() is a private method used to update captured
893 /// piece info. It is called from the main Position::do_move function.
895 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
897 assert(capture != KING);
901 if (ep) // en passant ?
903 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
905 assert(to == st->epSquare);
906 assert(relative_rank(opposite_color(them), to) == RANK_6);
907 assert(piece_on(to) == EMPTY);
908 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
910 board[capsq] = EMPTY;
913 // Remove captured piece
914 clear_bit(&(byColorBB[them]), capsq);
915 clear_bit(&(byTypeBB[capture]), capsq);
916 clear_bit(&(byTypeBB[0]), capsq);
919 key ^= zobrist[them][capture][capsq];
921 // If the captured piece was a pawn, update pawn hash key
923 st->pawnKey ^= zobrist[them][PAWN][capsq];
925 // Update incremental scores
926 st->mgValue -= pst<MidGame>(them, capture, capsq);
927 st->egValue -= pst<EndGame>(them, capture, capsq);
931 st->npMaterial[them] -= piece_value_midgame(capture);
933 // Update material hash key
934 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
936 // Update piece count
937 pieceCount[them][capture]--;
939 // Update piece list, move the last piece at index[capsq] position
940 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
941 index[lastPieceSquare] = index[capsq];
942 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
944 // Reset rule 50 counter
949 /// Position::do_castle_move() is a private method used to make a castling
950 /// move. It is called from the main Position::do_move function. Note that
951 /// castling moves are encoded as "king captures friendly rook" moves, for
952 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
954 void Position::do_castle_move(Move m) {
957 assert(move_is_ok(m));
958 assert(move_is_castle(m));
960 Color us = side_to_move();
961 Color them = opposite_color(us);
963 // Reset capture field
964 st->capture = NO_PIECE_TYPE;
966 // Find source squares for king and rook
967 Square kfrom = move_from(m);
968 Square rfrom = move_to(m); // HACK: See comment at beginning of function
971 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
972 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
974 // Find destination squares for king and rook
975 if (rfrom > kfrom) // O-O
977 kto = relative_square(us, SQ_G1);
978 rto = relative_square(us, SQ_F1);
980 kto = relative_square(us, SQ_C1);
981 rto = relative_square(us, SQ_D1);
985 Bitboard kmove_bb = make_move_bb(kfrom, kto);
986 do_move_bb(&(byColorBB[us]), kmove_bb);
987 do_move_bb(&(byTypeBB[KING]), kmove_bb);
988 do_move_bb(&(byTypeBB[0]), kmove_bb); // HACK: byTypeBB[0] == occupied squares
990 Bitboard rmove_bb = make_move_bb(rfrom, rto);
991 do_move_bb(&(byColorBB[us]), rmove_bb);
992 do_move_bb(&(byTypeBB[ROOK]), rmove_bb);
993 do_move_bb(&(byTypeBB[0]), rmove_bb); // HACK: byTypeBB[0] == occupied squares
995 // Update board array
996 Piece king = piece_of_color_and_type(us, KING);
997 Piece rook = piece_of_color_and_type(us, ROOK);
998 board[kfrom] = board[rfrom] = EMPTY;
1002 // Update king square
1003 kingSquare[us] = kto;
1005 // Update piece lists
1006 pieceList[us][KING][index[kfrom]] = kto;
1007 pieceList[us][ROOK][index[rfrom]] = rto;
1008 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1009 index[kto] = index[kfrom];
1012 // Update incremental scores
1013 st->mgValue += pst_delta<MidGame>(king, kfrom, kto);
1014 st->egValue += pst_delta<EndGame>(king, kfrom, kto);
1015 st->mgValue += pst_delta<MidGame>(rook, rfrom, rto);
1016 st->egValue += pst_delta<EndGame>(rook, rfrom, rto);
1019 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1020 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1022 // Clear en passant square
1023 if (st->epSquare != SQ_NONE)
1025 st->key ^= zobEp[st->epSquare];
1026 st->epSquare = SQ_NONE;
1029 // Update castling rights
1030 st->key ^= zobCastle[st->castleRights];
1031 st->castleRights &= castleRightsMask[kfrom];
1032 st->key ^= zobCastle[st->castleRights];
1034 // Reset rule 50 counter
1037 // Update checkers BB
1038 st->checkersBB = attacks_to(king_square(them), us);
1041 sideToMove = opposite_color(sideToMove);
1043 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1044 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1048 /// Position::undo_move() unmakes a move. When it returns, the position should
1049 /// be restored to exactly the same state as before the move was made.
1051 void Position::undo_move(Move m) {
1054 assert(move_is_ok(m));
1057 sideToMove = opposite_color(sideToMove);
1059 if (move_is_castle(m))
1061 undo_castle_move(m);
1065 Color us = side_to_move();
1066 Color them = opposite_color(us);
1067 Square from = move_from(m);
1068 Square to = move_to(m);
1069 bool ep = move_is_ep(m);
1070 bool pm = move_is_promotion(m);
1072 PieceType pt = type_of_piece_on(to);
1074 assert(square_is_empty(from));
1075 assert(color_of_piece_on(to) == us);
1076 assert(!pm || relative_rank(us, to) == RANK_8);
1077 assert(!ep || to == st->previous->epSquare);
1078 assert(!ep || relative_rank(us, to) == RANK_6);
1079 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1081 if (pm) // promotion ?
1083 PieceType promotion = move_promotion_piece(m);
1086 assert(promotion >= KNIGHT && promotion <= QUEEN);
1087 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1089 // Replace promoted piece with a pawn
1090 clear_bit(&(byTypeBB[promotion]), to);
1091 set_bit(&(byTypeBB[PAWN]), to);
1093 // Update piece counts
1094 pieceCount[us][promotion]--;
1095 pieceCount[us][PAWN]++;
1097 // Update piece list replacing promotion piece with a pawn
1098 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1099 index[lastPromotionSquare] = index[to];
1100 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1101 index[to] = pieceCount[us][PAWN] - 1;
1102 pieceList[us][PAWN][index[to]] = to;
1105 // Put the piece back at the source square
1106 Bitboard move_bb = make_move_bb(to, from);
1107 do_move_bb(&(byColorBB[us]), move_bb);
1108 do_move_bb(&(byTypeBB[pt]), move_bb);
1109 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1111 board[from] = piece_of_color_and_type(us, pt);
1114 // If the moving piece was a king, update the king square
1116 kingSquare[us] = from;
1118 // Update piece list
1119 index[from] = index[to];
1120 pieceList[us][pt][index[from]] = from;
1127 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1129 assert(st->capture != KING);
1130 assert(!ep || square_is_empty(capsq));
1132 // Restore the captured piece
1133 set_bit(&(byColorBB[them]), capsq);
1134 set_bit(&(byTypeBB[st->capture]), capsq);
1135 set_bit(&(byTypeBB[0]), capsq);
1137 board[capsq] = piece_of_color_and_type(them, st->capture);
1139 // Update piece count
1140 pieceCount[them][st->capture]++;
1142 // Update piece list, add a new captured piece in capsq square
1143 index[capsq] = pieceCount[them][st->capture] - 1;
1144 pieceList[them][st->capture][index[capsq]] = capsq;
1147 // Finally point our state pointer back to the previous state
1152 /// Position::undo_castle_move() is a private method used to unmake a castling
1153 /// move. It is called from the main Position::undo_move function. Note that
1154 /// castling moves are encoded as "king captures friendly rook" moves, for
1155 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1157 void Position::undo_castle_move(Move m) {
1159 assert(move_is_ok(m));
1160 assert(move_is_castle(m));
1162 // When we have arrived here, some work has already been done by
1163 // Position::undo_move. In particular, the side to move has been switched,
1164 // so the code below is correct.
1165 Color us = side_to_move();
1167 // Find source squares for king and rook
1168 Square kfrom = move_from(m);
1169 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1172 // Find destination squares for king and rook
1173 if (rfrom > kfrom) // O-O
1175 kto = relative_square(us, SQ_G1);
1176 rto = relative_square(us, SQ_F1);
1178 kto = relative_square(us, SQ_C1);
1179 rto = relative_square(us, SQ_D1);
1182 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1183 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1185 // Put the pieces back at the source square
1186 Bitboard kmove_bb = make_move_bb(kto, kfrom);
1187 do_move_bb(&(byColorBB[us]), kmove_bb);
1188 do_move_bb(&(byTypeBB[KING]), kmove_bb);
1189 do_move_bb(&(byTypeBB[0]), kmove_bb); // HACK: byTypeBB[0] == occupied squares
1191 Bitboard rmove_bb = make_move_bb(rto, rfrom);
1192 do_move_bb(&(byColorBB[us]), rmove_bb);
1193 do_move_bb(&(byTypeBB[ROOK]), rmove_bb);
1194 do_move_bb(&(byTypeBB[0]), rmove_bb); // HACK: byTypeBB[0] == occupied squares
1197 board[rto] = board[kto] = EMPTY;
1198 board[rfrom] = piece_of_color_and_type(us, ROOK);
1199 board[kfrom] = piece_of_color_and_type(us, KING);
1201 // Update king square
1202 kingSquare[us] = kfrom;
1204 // Update piece lists
1205 pieceList[us][KING][index[kto]] = kfrom;
1206 pieceList[us][ROOK][index[rto]] = rfrom;
1207 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1208 index[kfrom] = index[kto];
1211 // Finally point our state pointer back to the previous state
1216 /// Position::do_null_move makes() a "null move": It switches the side to move
1217 /// and updates the hash key without executing any move on the board.
1219 void Position::do_null_move(StateInfo& backupSt) {
1222 assert(!is_check());
1224 // Back up the information necessary to undo the null move to the supplied
1225 // StateInfo object.
1226 // Note that differently from normal case here backupSt is actually used as
1227 // a backup storage not as a new state to be used.
1228 backupSt.key = st->key;
1229 backupSt.epSquare = st->epSquare;
1230 backupSt.mgValue = st->mgValue;
1231 backupSt.egValue = st->egValue;
1232 backupSt.previous = st->previous;
1233 st->previous = &backupSt;
1235 // Save the current key to the history[] array, in order to be able to
1236 // detect repetition draws.
1237 history[gamePly] = st->key;
1239 // Update the necessary information
1240 if (st->epSquare != SQ_NONE)
1241 st->key ^= zobEp[st->epSquare];
1243 st->key ^= zobSideToMove;
1244 TT.prefetch(st->key);
1246 sideToMove = opposite_color(sideToMove);
1247 st->epSquare = SQ_NONE;
1251 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1252 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1256 /// Position::undo_null_move() unmakes a "null move".
1258 void Position::undo_null_move() {
1261 assert(!is_check());
1263 // Restore information from the our backup StateInfo object
1264 StateInfo* backupSt = st->previous;
1265 st->key = backupSt->key;
1266 st->epSquare = backupSt->epSquare;
1267 st->mgValue = backupSt->mgValue;
1268 st->egValue = backupSt->egValue;
1269 st->previous = backupSt->previous;
1271 // Update the necessary information
1272 sideToMove = opposite_color(sideToMove);
1278 /// Position::see() is a static exchange evaluator: It tries to estimate the
1279 /// material gain or loss resulting from a move. There are three versions of
1280 /// this function: One which takes a destination square as input, one takes a
1281 /// move, and one which takes a 'from' and a 'to' square. The function does
1282 /// not yet understand promotions captures.
1284 int Position::see(Square to) const {
1286 assert(square_is_ok(to));
1287 return see(SQ_NONE, to);
1290 int Position::see(Move m) const {
1292 assert(move_is_ok(m));
1293 return see(move_from(m), move_to(m));
1296 int Position::see_sign(Move m) const {
1298 assert(move_is_ok(m));
1300 Square from = move_from(m);
1301 Square to = move_to(m);
1303 // Early return if SEE cannot be negative because capturing piece value
1304 // is not bigger then captured one.
1305 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1306 && type_of_piece_on(from) != KING)
1309 return see(from, to);
1312 int Position::see(Square from, Square to) const {
1315 static const int seeValues[18] = {
1316 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1317 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1318 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1319 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1323 Bitboard attackers, stmAttackers, occ, b;
1325 assert(square_is_ok(from) || from == SQ_NONE);
1326 assert(square_is_ok(to));
1328 // Initialize colors
1329 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1330 Color them = opposite_color(us);
1332 // Initialize pieces
1333 Piece piece = piece_on(from);
1334 Piece capture = piece_on(to);
1336 // Find all attackers to the destination square, with the moving piece
1337 // removed, but possibly an X-ray attacker added behind it.
1338 occ = occupied_squares();
1340 // Handle en passant moves
1341 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1343 assert(capture == EMPTY);
1345 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1346 capture = piece_on(capQq);
1347 assert(type_of_piece_on(capQq) == PAWN);
1349 // Remove the captured pawn
1350 clear_bit(&occ, capQq);
1355 clear_bit(&occ, from);
1356 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1357 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1358 | (piece_attacks<KNIGHT>(to) & knights())
1359 | (piece_attacks<KING>(to) & kings())
1360 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1361 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1363 if (from != SQ_NONE)
1366 // If we don't have any attacker we are finished
1367 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1370 // Locate the least valuable attacker to the destination square
1371 // and use it to initialize from square.
1373 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1376 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1377 piece = piece_on(from);
1380 // If the opponent has no attackers we are finished
1381 stmAttackers = attackers & pieces_of_color(them);
1383 return seeValues[capture];
1385 attackers &= occ; // Remove the moving piece
1387 // The destination square is defended, which makes things rather more
1388 // difficult to compute. We proceed by building up a "swap list" containing
1389 // the material gain or loss at each stop in a sequence of captures to the
1390 // destination square, where the sides alternately capture, and always
1391 // capture with the least valuable piece. After each capture, we look for
1392 // new X-ray attacks from behind the capturing piece.
1393 int lastCapturingPieceValue = seeValues[piece];
1394 int swapList[32], n = 1;
1398 swapList[0] = seeValues[capture];
1401 // Locate the least valuable attacker for the side to move. The loop
1402 // below looks like it is potentially infinite, but it isn't. We know
1403 // that the side to move still has at least one attacker left.
1404 for (pt = PAWN; !(stmAttackers & pieces_of_type(pt)); pt++)
1407 // Remove the attacker we just found from the 'attackers' bitboard,
1408 // and scan for new X-ray attacks behind the attacker.
1409 b = stmAttackers & pieces_of_type(pt);
1410 occ ^= (b & (~b + 1));
1411 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1412 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1416 // Add the new entry to the swap list
1418 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1421 // Remember the value of the capturing piece, and change the side to move
1422 // before beginning the next iteration
1423 lastCapturingPieceValue = seeValues[pt];
1424 c = opposite_color(c);
1425 stmAttackers = attackers & pieces_of_color(c);
1427 // Stop after a king capture
1428 if (pt == KING && stmAttackers)
1431 swapList[n++] = QueenValueMidgame*10;
1434 } while (stmAttackers);
1436 // Having built the swap list, we negamax through it to find the best
1437 // achievable score from the point of view of the side to move
1439 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1445 /// Position::saveState() copies the content of the current state
1446 /// inside startState and makes st point to it. This is needed
1447 /// when the st pointee could become stale, as example because
1448 /// the caller is about to going out of scope.
1450 void Position::saveState() {
1454 st->previous = NULL; // as a safe guard
1458 /// Position::clear() erases the position object to a pristine state, with an
1459 /// empty board, white to move, and no castling rights.
1461 void Position::clear() {
1464 memset(st, 0, sizeof(StateInfo));
1465 st->epSquare = SQ_NONE;
1467 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1468 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1469 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1470 memset(index, 0, sizeof(int) * 64);
1472 for (int i = 0; i < 64; i++)
1475 for (int i = 0; i < 7; i++)
1476 for (int j = 0; j < 8; j++)
1477 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1481 initialKFile = FILE_E;
1482 initialKRFile = FILE_H;
1483 initialQRFile = FILE_A;
1487 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1488 /// UCI interface code, whenever a non-reversible move is made in a
1489 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1490 /// for the program to handle games of arbitrary length, as long as the GUI
1491 /// handles draws by the 50 move rule correctly.
1493 void Position::reset_game_ply() {
1499 /// Position::put_piece() puts a piece on the given square of the board,
1500 /// updating the board array, bitboards, and piece counts.
1502 void Position::put_piece(Piece p, Square s) {
1504 Color c = color_of_piece(p);
1505 PieceType pt = type_of_piece(p);
1508 index[s] = pieceCount[c][pt];
1509 pieceList[c][pt][index[s]] = s;
1511 set_bit(&(byTypeBB[pt]), s);
1512 set_bit(&(byColorBB[c]), s);
1513 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1515 pieceCount[c][pt]++;
1522 /// Position::allow_oo() gives the given side the right to castle kingside.
1523 /// Used when setting castling rights during parsing of FEN strings.
1525 void Position::allow_oo(Color c) {
1527 st->castleRights |= (1 + int(c));
1531 /// Position::allow_ooo() gives the given side the right to castle queenside.
1532 /// Used when setting castling rights during parsing of FEN strings.
1534 void Position::allow_ooo(Color c) {
1536 st->castleRights |= (4 + 4*int(c));
1540 /// Position::compute_key() computes the hash key of the position. The hash
1541 /// key is usually updated incrementally as moves are made and unmade, the
1542 /// compute_key() function is only used when a new position is set up, and
1543 /// to verify the correctness of the hash key when running in debug mode.
1545 Key Position::compute_key() const {
1547 Key result = Key(0ULL);
1549 for (Square s = SQ_A1; s <= SQ_H8; s++)
1550 if (square_is_occupied(s))
1551 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1553 if (ep_square() != SQ_NONE)
1554 result ^= zobEp[ep_square()];
1556 result ^= zobCastle[st->castleRights];
1557 if (side_to_move() == BLACK)
1558 result ^= zobSideToMove;
1564 /// Position::compute_pawn_key() computes the hash key of the position. The
1565 /// hash key is usually updated incrementally as moves are made and unmade,
1566 /// the compute_pawn_key() function is only used when a new position is set
1567 /// up, and to verify the correctness of the pawn hash key when running in
1570 Key Position::compute_pawn_key() const {
1572 Key result = Key(0ULL);
1576 for (Color c = WHITE; c <= BLACK; c++)
1581 s = pop_1st_bit(&b);
1582 result ^= zobrist[c][PAWN][s];
1589 /// Position::compute_material_key() computes the hash key of the position.
1590 /// The hash key is usually updated incrementally as moves are made and unmade,
1591 /// the compute_material_key() function is only used when a new position is set
1592 /// up, and to verify the correctness of the material hash key when running in
1595 Key Position::compute_material_key() const {
1597 Key result = Key(0ULL);
1598 for (Color c = WHITE; c <= BLACK; c++)
1599 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1601 int count = piece_count(c, pt);
1602 for (int i = 0; i <= count; i++)
1603 result ^= zobMaterial[c][pt][i];
1609 /// Position::compute_value() compute the incremental scores for the middle
1610 /// game and the endgame. These functions are used to initialize the incremental
1611 /// scores when a new position is set up, and to verify that the scores are correctly
1612 /// updated by do_move and undo_move when the program is running in debug mode.
1613 template<Position::GamePhase Phase>
1614 Value Position::compute_value() const {
1616 Value result = Value(0);
1620 for (Color c = WHITE; c <= BLACK; c++)
1621 for (PieceType pt = PAWN; pt <= KING; pt++)
1623 b = pieces_of_color_and_type(c, pt);
1626 s = pop_1st_bit(&b);
1627 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1628 result += pst<Phase>(c, pt, s);
1632 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1633 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1638 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1639 /// game material score for the given side. Material scores are updated
1640 /// incrementally during the search, this function is only used while
1641 /// initializing a new Position object.
1643 Value Position::compute_non_pawn_material(Color c) const {
1645 Value result = Value(0);
1647 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1649 Bitboard b = pieces_of_color_and_type(c, pt);
1652 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1654 result += piece_value_midgame(pt);
1661 /// Position::is_draw() tests whether the position is drawn by material,
1662 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1663 /// must be done by the search.
1665 bool Position::is_draw() const {
1667 // Draw by material?
1669 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1672 // Draw by the 50 moves rule?
1673 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1676 // Draw by repetition?
1677 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1678 if (history[gamePly - i] == st->key)
1685 /// Position::is_mate() returns true or false depending on whether the
1686 /// side to move is checkmated.
1688 bool Position::is_mate() const {
1690 MoveStack moves[256];
1692 return is_check() && !generate_evasions(*this, moves, pinned_pieces(sideToMove));
1696 /// Position::has_mate_threat() tests whether a given color has a mate in one
1697 /// from the current position.
1699 bool Position::has_mate_threat(Color c) {
1702 Color stm = side_to_move();
1707 // If the input color is not equal to the side to move, do a null move
1711 MoveStack mlist[120];
1713 bool result = false;
1714 Bitboard dc = discovered_check_candidates(sideToMove);
1715 Bitboard pinned = pinned_pieces(sideToMove);
1717 // Generate pseudo-legal non-capture and capture check moves
1718 count = generate_non_capture_checks(*this, mlist, dc);
1719 count += generate_captures(*this, mlist + count);
1721 // Loop through the moves, and see if one of them is mate
1722 for (int i = 0; i < count; i++)
1724 Move move = mlist[i].move;
1726 if (!pl_move_is_legal(move, pinned))
1736 // Undo null move, if necessary
1744 /// Position::init_zobrist() is a static member function which initializes the
1745 /// various arrays used to compute hash keys.
1747 void Position::init_zobrist() {
1749 for (int i = 0; i < 2; i++)
1750 for (int j = 0; j < 8; j++)
1751 for (int k = 0; k < 64; k++)
1752 zobrist[i][j][k] = Key(genrand_int64());
1754 for (int i = 0; i < 64; i++)
1755 zobEp[i] = Key(genrand_int64());
1757 for (int i = 0; i < 16; i++)
1758 zobCastle[i] = genrand_int64();
1760 zobSideToMove = genrand_int64();
1762 for (int i = 0; i < 2; i++)
1763 for (int j = 0; j < 8; j++)
1764 for (int k = 0; k < 16; k++)
1765 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1767 for (int i = 0; i < 16; i++)
1768 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1772 /// Position::init_piece_square_tables() initializes the piece square tables.
1773 /// This is a two-step operation: First, the white halves of the tables are
1774 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1775 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1776 /// Second, the black halves of the tables are initialized by mirroring
1777 /// and changing the sign of the corresponding white scores.
1779 void Position::init_piece_square_tables() {
1781 int r = get_option_value_int("Randomness"), i;
1782 for (Square s = SQ_A1; s <= SQ_H8; s++)
1783 for (Piece p = WP; p <= WK; p++)
1785 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1786 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1787 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1790 for (Square s = SQ_A1; s <= SQ_H8; s++)
1791 for (Piece p = BP; p <= BK; p++)
1793 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1794 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
1799 /// Position::flipped_copy() makes a copy of the input position, but with
1800 /// the white and black sides reversed. This is only useful for debugging,
1801 /// especially for finding evaluation symmetry bugs.
1803 void Position::flipped_copy(const Position& pos) {
1805 assert(pos.is_ok());
1810 for (Square s = SQ_A1; s <= SQ_H8; s++)
1811 if (!pos.square_is_empty(s))
1812 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1815 sideToMove = opposite_color(pos.side_to_move());
1818 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1819 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1820 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1821 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1823 initialKFile = pos.initialKFile;
1824 initialKRFile = pos.initialKRFile;
1825 initialQRFile = pos.initialQRFile;
1827 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1828 castleRightsMask[sq] = ALL_CASTLES;
1830 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1831 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1832 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1833 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1834 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1835 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1837 // En passant square
1838 if (pos.st->epSquare != SQ_NONE)
1839 st->epSquare = flip_square(pos.st->epSquare);
1845 st->key = compute_key();
1846 st->pawnKey = compute_pawn_key();
1847 st->materialKey = compute_material_key();
1849 // Incremental scores
1850 st->mgValue = compute_value<MidGame>();
1851 st->egValue = compute_value<EndGame>();
1854 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1855 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1861 /// Position::is_ok() performs some consitency checks for the position object.
1862 /// This is meant to be helpful when debugging.
1864 bool Position::is_ok(int* failedStep) const {
1866 // What features of the position should be verified?
1867 static const bool debugBitboards = false;
1868 static const bool debugKingCount = false;
1869 static const bool debugKingCapture = false;
1870 static const bool debugCheckerCount = false;
1871 static const bool debugKey = false;
1872 static const bool debugMaterialKey = false;
1873 static const bool debugPawnKey = false;
1874 static const bool debugIncrementalEval = false;
1875 static const bool debugNonPawnMaterial = false;
1876 static const bool debugPieceCounts = false;
1877 static const bool debugPieceList = false;
1879 if (failedStep) *failedStep = 1;
1882 if (!color_is_ok(side_to_move()))
1885 // Are the king squares in the position correct?
1886 if (failedStep) (*failedStep)++;
1887 if (piece_on(king_square(WHITE)) != WK)
1890 if (failedStep) (*failedStep)++;
1891 if (piece_on(king_square(BLACK)) != BK)
1895 if (failedStep) (*failedStep)++;
1896 if (!file_is_ok(initialKRFile))
1899 if (!file_is_ok(initialQRFile))
1902 // Do both sides have exactly one king?
1903 if (failedStep) (*failedStep)++;
1906 int kingCount[2] = {0, 0};
1907 for (Square s = SQ_A1; s <= SQ_H8; s++)
1908 if (type_of_piece_on(s) == KING)
1909 kingCount[color_of_piece_on(s)]++;
1911 if (kingCount[0] != 1 || kingCount[1] != 1)
1915 // Can the side to move capture the opponent's king?
1916 if (failedStep) (*failedStep)++;
1917 if (debugKingCapture)
1919 Color us = side_to_move();
1920 Color them = opposite_color(us);
1921 Square ksq = king_square(them);
1922 if (square_is_attacked(ksq, us))
1926 // Is there more than 2 checkers?
1927 if (failedStep) (*failedStep)++;
1928 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1932 if (failedStep) (*failedStep)++;
1935 // The intersection of the white and black pieces must be empty
1936 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1939 // The union of the white and black pieces must be equal to all
1941 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1944 // Separate piece type bitboards must have empty intersections
1945 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1946 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1947 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
1951 // En passant square OK?
1952 if (failedStep) (*failedStep)++;
1953 if (ep_square() != SQ_NONE)
1955 // The en passant square must be on rank 6, from the point of view of the
1957 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1962 if (failedStep) (*failedStep)++;
1963 if (debugKey && st->key != compute_key())
1966 // Pawn hash key OK?
1967 if (failedStep) (*failedStep)++;
1968 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1971 // Material hash key OK?
1972 if (failedStep) (*failedStep)++;
1973 if (debugMaterialKey && st->materialKey != compute_material_key())
1976 // Incremental eval OK?
1977 if (failedStep) (*failedStep)++;
1978 if (debugIncrementalEval)
1980 if (st->mgValue != compute_value<MidGame>())
1983 if (st->egValue != compute_value<EndGame>())
1987 // Non-pawn material OK?
1988 if (failedStep) (*failedStep)++;
1989 if (debugNonPawnMaterial)
1991 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1994 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1999 if (failedStep) (*failedStep)++;
2000 if (debugPieceCounts)
2001 for (Color c = WHITE; c <= BLACK; c++)
2002 for (PieceType pt = PAWN; pt <= KING; pt++)
2003 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2006 if (failedStep) (*failedStep)++;
2009 for(Color c = WHITE; c <= BLACK; c++)
2010 for(PieceType pt = PAWN; pt <= KING; pt++)
2011 for(int i = 0; i < pieceCount[c][pt]; i++)
2013 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2016 if (index[piece_list(c, pt, i)] != i)
2020 if (failedStep) *failedStep = 0;