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 = (pieces(ROOK, QUEEN, FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
344 | (pieces(BISHOP, QUEEN, 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::attackers_to() computes a bitboard containing all pieces which
383 /// attacks a given square.
385 Bitboard Position::attackers_to(Square s) const {
387 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
388 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
389 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
390 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
391 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
392 | (attacks_from<KING>(s) & pieces(KING));
395 /// Position::attacks_from() computes a bitboard of all attacks
396 /// of a given piece put in a given square.
398 Bitboard Position::attacks_from(Piece p, Square s) const {
400 assert(square_is_ok(s));
404 case WP: return attacks_from<PAWN>(s, WHITE);
405 case BP: return attacks_from<PAWN>(s, BLACK);
406 case WN: case BN: return attacks_from<KNIGHT>(s);
407 case WB: case BB: return attacks_from<BISHOP>(s);
408 case WR: case BR: return attacks_from<ROOK>(s);
409 case WQ: case BQ: return attacks_from<QUEEN>(s);
410 case WK: case BK: return attacks_from<KING>(s);
417 /// Position::move_attacks_square() tests whether a move from the current
418 /// position attacks a given square.
420 bool Position::move_attacks_square(Move m, Square s) const {
422 assert(move_is_ok(m));
423 assert(square_is_ok(s));
425 Square f = move_from(m), t = move_to(m);
427 assert(square_is_occupied(f));
429 if (bit_is_set(attacks_from(piece_on(f), t), s))
432 // Move the piece and scan for X-ray attacks behind it
433 Bitboard occ = occupied_squares();
434 Color us = color_of_piece_on(f);
437 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
438 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
440 // If we have attacks we need to verify that are caused by our move
441 // and are not already existent ones.
442 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
446 /// Position::find_checkers() computes the checkersBB bitboard, which
447 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
448 /// currently works by calling Position::attackers_to, which is probably
449 /// inefficient. Consider rewriting this function to use the last move
450 /// played, like in non-bitboard versions of Glaurung.
452 void Position::find_checkers() {
454 Color us = side_to_move();
455 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
459 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
461 bool Position::pl_move_is_legal(Move m) const {
463 // If we're in check, all pseudo-legal moves are legal, because our
464 // check evasion generator only generates true legal moves.
465 return is_check() || pl_move_is_legal(m, pinned_pieces(side_to_move()));
468 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
471 assert(move_is_ok(m));
472 assert(pinned == pinned_pieces(side_to_move()));
475 // Castling moves are checked for legality during move generation.
476 if (move_is_castle(m))
479 Color us = side_to_move();
480 Square from = move_from(m);
482 assert(color_of_piece_on(from) == us);
483 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
485 // En passant captures are a tricky special case. Because they are
486 // rather uncommon, we do it simply by testing whether the king is attacked
487 // after the move is made
490 Color them = opposite_color(us);
491 Square to = move_to(m);
492 Square capsq = make_square(square_file(to), square_rank(from));
493 Bitboard b = occupied_squares();
494 Square ksq = king_square(us);
496 assert(to == ep_square());
497 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
498 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
499 assert(piece_on(to) == EMPTY);
502 clear_bit(&b, capsq);
505 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
506 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
509 // If the moving piece is a king, check whether the destination
510 // square is attacked by the opponent.
511 if (type_of_piece_on(from) == KING)
512 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
514 // A non-king move is legal if and only if it is not pinned or it
515 // is moving along the ray towards or away from the king.
517 || !bit_is_set(pinned, from)
518 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
522 /// Position::move_is_check() tests whether a pseudo-legal move is a check
524 bool Position::move_is_check(Move m) const {
526 Bitboard dc = discovered_check_candidates(side_to_move());
527 return move_is_check(m, dc);
530 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
533 assert(move_is_ok(m));
534 assert(dcCandidates == discovered_check_candidates(side_to_move()));
536 Color us = side_to_move();
537 Color them = opposite_color(us);
538 Square from = move_from(m);
539 Square to = move_to(m);
540 Square ksq = king_square(them);
542 assert(color_of_piece_on(from) == us);
543 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
545 // Proceed according to the type of the moving piece
546 switch (type_of_piece_on(from))
550 if (bit_is_set(attacks_from<PAWN>(ksq, them), to)) // Normal check?
553 if ( dcCandidates // Discovered check?
554 && bit_is_set(dcCandidates, from)
555 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
558 if (move_is_promotion(m)) // Promotion with check?
560 Bitboard b = occupied_squares();
563 switch (move_promotion_piece(m))
566 return bit_is_set(attacks_from<KNIGHT>(to), ksq);
568 return bit_is_set(bishop_attacks_bb(to, b), ksq);
570 return bit_is_set(rook_attacks_bb(to, b), ksq);
572 return bit_is_set(queen_attacks_bb(to, b), ksq);
577 // En passant capture with check? We have already handled the case
578 // of direct checks and ordinary discovered check, the only case we
579 // need to handle is the unusual case of a discovered check through the
581 else if (move_is_ep(m))
583 Square capsq = make_square(square_file(to), square_rank(from));
584 Bitboard b = occupied_squares();
586 clear_bit(&b, capsq);
588 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
589 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
593 // Test discovered check and normal check according to piece type
595 return (dcCandidates && bit_is_set(dcCandidates, from))
596 || bit_is_set(attacks_from<KNIGHT>(ksq), to);
599 return (dcCandidates && bit_is_set(dcCandidates, from))
600 || (direction_is_diagonal(ksq, to) && bit_is_set(attacks_from<BISHOP>(ksq), to));
603 return (dcCandidates && bit_is_set(dcCandidates, from))
604 || (direction_is_straight(ksq, to) && bit_is_set(attacks_from<ROOK>(ksq), to));
607 // Discovered checks are impossible!
608 assert(!bit_is_set(dcCandidates, from));
609 return ( (direction_is_straight(ksq, to) && bit_is_set(attacks_from<ROOK>(ksq), to))
610 || (direction_is_diagonal(ksq, to) && bit_is_set(attacks_from<BISHOP>(ksq), to)));
614 if ( bit_is_set(dcCandidates, from)
615 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
618 // Castling with check?
619 if (move_is_castle(m))
621 Square kfrom, kto, rfrom, rto;
622 Bitboard b = occupied_squares();
628 kto = relative_square(us, SQ_G1);
629 rto = relative_square(us, SQ_F1);
631 kto = relative_square(us, SQ_C1);
632 rto = relative_square(us, SQ_D1);
634 clear_bit(&b, kfrom);
635 clear_bit(&b, rfrom);
638 return bit_is_set(rook_attacks_bb(rto, b), ksq);
642 default: // NO_PIECE_TYPE
650 /// Position::update_checkers() udpates chekers info given the move. It is called
651 /// in do_move() and is faster then find_checkers().
653 template<PieceType Piece>
654 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
655 Square to, Bitboard dcCandidates) {
657 const bool Bishop = (Piece == QUEEN || Piece == BISHOP);
658 const bool Rook = (Piece == QUEEN || Piece == ROOK);
659 const bool Slider = Bishop || Rook;
662 if ( ( (Bishop && bit_is_set(BishopPseudoAttacks[ksq], to))
663 || (Rook && bit_is_set(RookPseudoAttacks[ksq], to)))
664 && bit_is_set(attacks_from<Piece>(ksq), to)) // slow, try to early skip
665 set_bit(pCheckersBB, to);
667 else if ( Piece != KING
669 && bit_is_set(Piece == PAWN ? attacks_from<PAWN>(ksq, opposite_color(sideToMove))
670 : attacks_from<Piece>(ksq), to))
671 set_bit(pCheckersBB, to);
674 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
677 (*pCheckersBB) |= (attacks_from<ROOK>(ksq) & pieces(ROOK, QUEEN, side_to_move()));
680 (*pCheckersBB) |= (attacks_from<BISHOP>(ksq) & pieces(BISHOP, QUEEN, 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, pliesFromNull;
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.
729 if (move_is_castle(m))
736 Color us = side_to_move();
737 Color them = opposite_color(us);
738 Square from = move_from(m);
739 Square to = move_to(m);
740 bool ep = move_is_ep(m);
741 bool pm = move_is_promotion(m);
743 Piece piece = piece_on(from);
744 PieceType pt = type_of_piece(piece);
746 assert(color_of_piece_on(from) == us);
747 assert(color_of_piece_on(to) == them || square_is_empty(to));
748 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
749 assert(!pm || relative_rank(us, to) == RANK_8);
751 st->capture = ep ? PAWN : type_of_piece_on(to);
754 do_capture_move(key, st->capture, them, to, ep);
757 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
759 // Reset en passant square
760 if (st->epSquare != SQ_NONE)
762 key ^= zobEp[st->epSquare];
763 st->epSquare = SQ_NONE;
766 // Update castle rights, try to shortcut a common case
767 int cm = castleRightsMask[from] & castleRightsMask[to];
768 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
770 key ^= zobCastle[st->castleRights];
771 st->castleRights &= castleRightsMask[from];
772 st->castleRights &= castleRightsMask[to];
773 key ^= zobCastle[st->castleRights];
776 // Prefetch TT access as soon as we know key is updated
780 Bitboard move_bb = make_move_bb(from, to);
781 do_move_bb(&(byColorBB[us]), move_bb);
782 do_move_bb(&(byTypeBB[pt]), move_bb);
783 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
785 board[to] = board[from];
788 // Update piece lists, note that index[from] is not updated and
789 // becomes stale. This works as long as index[] is accessed just
790 // by known occupied squares.
791 index[to] = index[from];
792 pieceList[us][pt][index[to]] = to;
794 // If the moving piece was a pawn do some special extra work
797 // Reset rule 50 draw counter
800 // Update pawn hash key
801 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
803 // Set en passant square, only if moved pawn can be captured
804 if (abs(int(to) - int(from)) == 16)
806 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
808 st->epSquare = Square((int(from) + int(to)) / 2);
809 key ^= zobEp[st->epSquare];
814 // Update incremental scores
815 st->mgValue += pst_delta<MidGame>(piece, from, to);
816 st->egValue += pst_delta<EndGame>(piece, from, to);
818 if (pm) // promotion ?
820 PieceType promotion = move_promotion_piece(m);
822 assert(promotion >= KNIGHT && promotion <= QUEEN);
824 // Insert promoted piece instead of pawn
825 clear_bit(&(byTypeBB[PAWN]), to);
826 set_bit(&(byTypeBB[promotion]), to);
827 board[to] = piece_of_color_and_type(us, promotion);
829 // Update material key
830 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
831 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
833 // Update piece counts
834 pieceCount[us][PAWN]--;
835 pieceCount[us][promotion]++;
837 // Update piece lists, move the last pawn at index[to] position
838 // and shrink the list. Add a new promotion piece to the list.
839 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
840 index[lastPawnSquare] = index[to];
841 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
842 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
843 index[to] = pieceCount[us][promotion] - 1;
844 pieceList[us][promotion][index[to]] = to;
846 // Partially revert hash keys update
847 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
848 st->pawnKey ^= zobrist[us][PAWN][to];
850 // Partially revert and update incremental scores
851 st->mgValue -= pst<MidGame>(us, PAWN, to);
852 st->mgValue += pst<MidGame>(us, promotion, to);
853 st->egValue -= pst<EndGame>(us, PAWN, to);
854 st->egValue += pst<EndGame>(us, promotion, to);
857 st->npMaterial[us] += piece_value_midgame(promotion);
860 // Update the key with the final value
863 // Update checkers bitboard, piece must be already moved
865 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
868 st->checkersBB = EmptyBoardBB;
869 Square ksq = king_square(them);
872 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
873 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
874 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
875 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
876 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
877 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
878 default: assert(false); break;
883 sideToMove = opposite_color(sideToMove);
885 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
886 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 // Update incremental scores
922 st->mgValue -= pst<MidGame>(them, capture, capsq);
923 st->egValue -= pst<EndGame>(them, capture, capsq);
925 // If the captured piece was a pawn, update pawn hash key,
926 // otherwise update non-pawn material.
928 st->pawnKey ^= zobrist[them][PAWN][capsq];
930 st->npMaterial[them] -= piece_value_midgame(capture);
932 // Update material hash key
933 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
935 // Update piece count
936 pieceCount[them][capture]--;
938 // Update piece list, move the last piece at index[capsq] position
940 // WARNING: This is a not perfectly revresible operation. When we
941 // will reinsert the captured piece in undo_move() we will put it
942 // at the end of the list and not in its original place, it means
943 // index[] and pieceList[] are not guaranteed to be invariant to a
944 // do_move() + undo_move() sequence.
945 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
946 index[lastPieceSquare] = index[capsq];
947 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
948 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
950 // Reset rule 50 counter
955 /// Position::do_castle_move() is a private method used to make a castling
956 /// move. It is called from the main Position::do_move function. Note that
957 /// castling moves are encoded as "king captures friendly rook" moves, for
958 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
960 void Position::do_castle_move(Move m) {
962 assert(move_is_ok(m));
963 assert(move_is_castle(m));
965 Color us = side_to_move();
966 Color them = opposite_color(us);
968 // Reset capture field
969 st->capture = NO_PIECE_TYPE;
971 // Find source squares for king and rook
972 Square kfrom = move_from(m);
973 Square rfrom = move_to(m); // HACK: See comment at beginning of function
976 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
977 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
979 // Find destination squares for king and rook
980 if (rfrom > kfrom) // O-O
982 kto = relative_square(us, SQ_G1);
983 rto = relative_square(us, SQ_F1);
985 kto = relative_square(us, SQ_C1);
986 rto = relative_square(us, SQ_D1);
989 // Remove pieces from source squares:
990 clear_bit(&(byColorBB[us]), kfrom);
991 clear_bit(&(byTypeBB[KING]), kfrom);
992 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
993 clear_bit(&(byColorBB[us]), rfrom);
994 clear_bit(&(byTypeBB[ROOK]), rfrom);
995 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
997 // Put pieces on destination squares:
998 set_bit(&(byColorBB[us]), kto);
999 set_bit(&(byTypeBB[KING]), kto);
1000 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1001 set_bit(&(byColorBB[us]), rto);
1002 set_bit(&(byTypeBB[ROOK]), rto);
1003 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1005 // Update board array
1006 Piece king = piece_of_color_and_type(us, KING);
1007 Piece rook = piece_of_color_and_type(us, ROOK);
1008 board[kfrom] = board[rfrom] = EMPTY;
1012 // Update piece lists
1013 pieceList[us][KING][index[kfrom]] = kto;
1014 pieceList[us][ROOK][index[rfrom]] = rto;
1015 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1016 index[kto] = index[kfrom];
1019 // Update incremental scores
1020 st->mgValue += pst_delta<MidGame>(king, kfrom, kto);
1021 st->egValue += pst_delta<EndGame>(king, kfrom, kto);
1022 st->mgValue += pst_delta<MidGame>(rook, rfrom, rto);
1023 st->egValue += pst_delta<EndGame>(rook, rfrom, rto);
1026 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1027 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1029 // Clear en passant square
1030 if (st->epSquare != SQ_NONE)
1032 st->key ^= zobEp[st->epSquare];
1033 st->epSquare = SQ_NONE;
1036 // Update castling rights
1037 st->key ^= zobCastle[st->castleRights];
1038 st->castleRights &= castleRightsMask[kfrom];
1039 st->key ^= zobCastle[st->castleRights];
1041 // Reset rule 50 counter
1044 // Update checkers BB
1045 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1048 sideToMove = opposite_color(sideToMove);
1050 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1051 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1057 /// Position::undo_move() unmakes a move. When it returns, the position should
1058 /// be restored to exactly the same state as before the move was made.
1060 void Position::undo_move(Move m) {
1063 assert(move_is_ok(m));
1066 sideToMove = opposite_color(sideToMove);
1068 if (move_is_castle(m))
1070 undo_castle_move(m);
1074 Color us = side_to_move();
1075 Color them = opposite_color(us);
1076 Square from = move_from(m);
1077 Square to = move_to(m);
1078 bool ep = move_is_ep(m);
1079 bool pm = move_is_promotion(m);
1081 PieceType pt = type_of_piece_on(to);
1083 assert(square_is_empty(from));
1084 assert(color_of_piece_on(to) == us);
1085 assert(!pm || relative_rank(us, to) == RANK_8);
1086 assert(!ep || to == st->previous->epSquare);
1087 assert(!ep || relative_rank(us, to) == RANK_6);
1088 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1090 if (pm) // promotion ?
1092 PieceType promotion = move_promotion_piece(m);
1095 assert(promotion >= KNIGHT && promotion <= QUEEN);
1096 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1098 // Replace promoted piece with a pawn
1099 clear_bit(&(byTypeBB[promotion]), to);
1100 set_bit(&(byTypeBB[PAWN]), to);
1102 // Update piece counts
1103 pieceCount[us][promotion]--;
1104 pieceCount[us][PAWN]++;
1106 // Update piece list replacing promotion piece with a pawn
1107 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1108 index[lastPromotionSquare] = index[to];
1109 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1110 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1111 index[to] = pieceCount[us][PAWN] - 1;
1112 pieceList[us][PAWN][index[to]] = to;
1116 // Put the piece back at the source square
1117 Bitboard move_bb = make_move_bb(to, from);
1118 do_move_bb(&(byColorBB[us]), move_bb);
1119 do_move_bb(&(byTypeBB[pt]), move_bb);
1120 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1122 board[from] = piece_of_color_and_type(us, pt);
1125 // Update piece list
1126 index[from] = index[to];
1127 pieceList[us][pt][index[from]] = from;
1134 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1136 assert(st->capture != KING);
1137 assert(!ep || square_is_empty(capsq));
1139 // Restore the captured piece
1140 set_bit(&(byColorBB[them]), capsq);
1141 set_bit(&(byTypeBB[st->capture]), capsq);
1142 set_bit(&(byTypeBB[0]), capsq);
1144 board[capsq] = piece_of_color_and_type(them, st->capture);
1146 // Update piece count
1147 pieceCount[them][st->capture]++;
1149 // Update piece list, add a new captured piece in capsq square
1150 index[capsq] = pieceCount[them][st->capture] - 1;
1151 pieceList[them][st->capture][index[capsq]] = capsq;
1154 // Finally point our state pointer back to the previous state
1161 /// Position::undo_castle_move() is a private method used to unmake a castling
1162 /// move. It is called from the main Position::undo_move function. Note that
1163 /// castling moves are encoded as "king captures friendly rook" moves, for
1164 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1166 void Position::undo_castle_move(Move m) {
1168 assert(move_is_ok(m));
1169 assert(move_is_castle(m));
1171 // When we have arrived here, some work has already been done by
1172 // Position::undo_move. In particular, the side to move has been switched,
1173 // so the code below is correct.
1174 Color us = side_to_move();
1176 // Find source squares for king and rook
1177 Square kfrom = move_from(m);
1178 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1181 // Find destination squares for king and rook
1182 if (rfrom > kfrom) // O-O
1184 kto = relative_square(us, SQ_G1);
1185 rto = relative_square(us, SQ_F1);
1187 kto = relative_square(us, SQ_C1);
1188 rto = relative_square(us, SQ_D1);
1191 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1192 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1194 // Remove pieces from destination squares:
1195 clear_bit(&(byColorBB[us]), kto);
1196 clear_bit(&(byTypeBB[KING]), kto);
1197 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1198 clear_bit(&(byColorBB[us]), rto);
1199 clear_bit(&(byTypeBB[ROOK]), rto);
1200 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1202 // Put pieces on source squares:
1203 set_bit(&(byColorBB[us]), kfrom);
1204 set_bit(&(byTypeBB[KING]), kfrom);
1205 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1206 set_bit(&(byColorBB[us]), rfrom);
1207 set_bit(&(byTypeBB[ROOK]), rfrom);
1208 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1211 board[rto] = board[kto] = EMPTY;
1212 board[rfrom] = piece_of_color_and_type(us, ROOK);
1213 board[kfrom] = piece_of_color_and_type(us, KING);
1215 // Update piece lists
1216 pieceList[us][KING][index[kto]] = kfrom;
1217 pieceList[us][ROOK][index[rto]] = rfrom;
1218 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1219 index[kfrom] = index[kto];
1222 // Finally point our state pointer back to the previous state
1229 /// Position::do_null_move makes() a "null move": It switches the side to move
1230 /// and updates the hash key without executing any move on the board.
1232 void Position::do_null_move(StateInfo& backupSt) {
1235 assert(!is_check());
1237 // Back up the information necessary to undo the null move to the supplied
1238 // StateInfo object.
1239 // Note that differently from normal case here backupSt is actually used as
1240 // a backup storage not as a new state to be used.
1241 backupSt.key = st->key;
1242 backupSt.epSquare = st->epSquare;
1243 backupSt.mgValue = st->mgValue;
1244 backupSt.egValue = st->egValue;
1245 backupSt.previous = st->previous;
1246 backupSt.pliesFromNull = st->pliesFromNull;
1247 st->previous = &backupSt;
1249 // Save the current key to the history[] array, in order to be able to
1250 // detect repetition draws.
1251 history[gamePly] = st->key;
1253 // Update the necessary information
1254 if (st->epSquare != SQ_NONE)
1255 st->key ^= zobEp[st->epSquare];
1257 st->key ^= zobSideToMove;
1258 TT.prefetch(st->key);
1260 sideToMove = opposite_color(sideToMove);
1261 st->epSquare = SQ_NONE;
1263 st->pliesFromNull = 0;
1266 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1267 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1271 /// Position::undo_null_move() unmakes a "null move".
1273 void Position::undo_null_move() {
1276 assert(!is_check());
1278 // Restore information from the our backup StateInfo object
1279 StateInfo* backupSt = st->previous;
1280 st->key = backupSt->key;
1281 st->epSquare = backupSt->epSquare;
1282 st->mgValue = backupSt->mgValue;
1283 st->egValue = backupSt->egValue;
1284 st->previous = backupSt->previous;
1285 st->pliesFromNull = backupSt->pliesFromNull;
1287 // Update the necessary information
1288 sideToMove = opposite_color(sideToMove);
1294 /// Position::see() is a static exchange evaluator: It tries to estimate the
1295 /// material gain or loss resulting from a move. There are three versions of
1296 /// this function: One which takes a destination square as input, one takes a
1297 /// move, and one which takes a 'from' and a 'to' square. The function does
1298 /// not yet understand promotions captures.
1300 int Position::see(Square to) const {
1302 assert(square_is_ok(to));
1303 return see(SQ_NONE, to, false);
1306 int Position::see(Move m) const {
1308 assert(move_is_ok(m));
1309 return see(move_from(m), move_to(m), false);
1312 int Position::see_sign(Move m) const {
1314 assert(move_is_ok(m));
1316 Square from = move_from(m);
1317 Square to = move_to(m);
1319 // Early return if SEE cannot be negative because capturing piece value
1320 // is not bigger then captured one.
1321 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1322 && type_of_piece_on(from) != KING)
1325 return see(from, to, true);
1328 int Position::see(Square from, Square to, bool shortcut) const {
1331 static const int seeValues[18] = {
1332 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1333 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1334 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1335 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1339 Bitboard attackers, stmAttackers, b;
1342 assert(!shortcut || from != SQ_NONE);
1343 assert(square_is_ok(from) || from == SQ_NONE);
1344 assert(square_is_ok(to));
1346 // Initialize colors
1347 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1348 Color them = opposite_color(us);
1350 // Initialize pieces
1351 Piece piece = piece_on(from);
1352 Piece capture = piece_on(to);
1353 Bitboard occ = occupied_squares();
1355 // King cannot be recaptured
1356 if (type_of_piece(piece) == KING)
1357 return seeValues[capture];
1359 // If captured piece is defended by enemy pawns or knights then SEE is negative
1360 // when captured piece value does not compensate the lost of capturing one.
1363 pieceDiff = seeValues[piece] - seeValues[capture];
1365 if ( pieceDiff > seeValues[PAWN]
1366 &&(attacks_from<PAWN>(to, us) & pieces(PAWN, them)))
1367 return -(pieceDiff - seeValues[PAWN] / 2);
1369 if ( pieceDiff > seeValues[KNIGHT]
1370 && pieces(KNIGHT, them)
1371 &&(pieces(KNIGHT, them) & attacks_from<KNIGHT>(to)))
1372 return -(pieceDiff - seeValues[KNIGHT] / 2);
1375 // Handle en passant moves
1376 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1378 assert(capture == EMPTY);
1380 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1381 capture = piece_on(capQq);
1382 assert(type_of_piece_on(capQq) == PAWN);
1384 // Remove the captured pawn
1385 clear_bit(&occ, capQq);
1390 // Find all attackers to the destination square, with the moving piece
1391 // removed, but possibly an X-ray attacker added behind it.
1392 clear_bit(&occ, from);
1393 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1394 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1395 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1396 | (attacks_from<KING>(to) & pieces(KING))
1397 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1398 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1400 if (from != SQ_NONE)
1403 // If we don't have any attacker we are finished
1404 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1407 // Locate the least valuable attacker to the destination square
1408 // and use it to initialize from square.
1409 stmAttackers = attackers & pieces_of_color(us);
1411 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1414 from = first_1(stmAttackers & pieces(pt));
1415 piece = piece_on(from);
1418 // If the opponent has no attackers we are finished
1419 stmAttackers = attackers & pieces_of_color(them);
1421 return seeValues[capture];
1423 attackers &= occ; // Remove the moving piece
1425 // The destination square is defended, which makes things rather more
1426 // difficult to compute. We proceed by building up a "swap list" containing
1427 // the material gain or loss at each stop in a sequence of captures to the
1428 // destination square, where the sides alternately capture, and always
1429 // capture with the least valuable piece. After each capture, we look for
1430 // new X-ray attacks from behind the capturing piece.
1431 int lastCapturingPieceValue = seeValues[piece];
1432 int swapList[32], n = 1;
1436 swapList[0] = seeValues[capture];
1439 // Locate the least valuable attacker for the side to move. The loop
1440 // below looks like it is potentially infinite, but it isn't. We know
1441 // that the side to move still has at least one attacker left.
1442 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1445 // If captured piece is defended by an enemy piece then SEE is negative
1446 // if captured piece value does not compensate the lost of capturing one.
1447 if (pieceDiff > seeValues[pt])
1450 return -(pieceDiff - seeValues[pt] / 2);
1452 pieceDiff = 0; // Only first cycle
1454 // Remove the attacker we just found from the 'attackers' bitboard,
1455 // and scan for new X-ray attacks behind the attacker.
1456 b = stmAttackers & pieces(pt);
1457 occ ^= (b & (~b + 1));
1458 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1459 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1463 // Add the new entry to the swap list
1465 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1468 // Remember the value of the capturing piece, and change the side to move
1469 // before beginning the next iteration
1470 lastCapturingPieceValue = seeValues[pt];
1471 c = opposite_color(c);
1472 stmAttackers = attackers & pieces_of_color(c);
1474 // Stop after a king capture
1475 if (pt == KING && stmAttackers)
1478 swapList[n++] = QueenValueMidgame*10;
1481 } while (stmAttackers);
1483 // Having built the swap list, we negamax through it to find the best
1484 // achievable score from the point of view of the side to move
1486 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1492 /// Position::saveState() copies the content of the current state
1493 /// inside startState and makes st point to it. This is needed
1494 /// when the st pointee could become stale, as example because
1495 /// the caller is about to going out of scope.
1497 void Position::saveState() {
1501 st->previous = NULL; // as a safe guard
1505 /// Position::clear() erases the position object to a pristine state, with an
1506 /// empty board, white to move, and no castling rights.
1508 void Position::clear() {
1511 memset(st, 0, sizeof(StateInfo));
1512 st->epSquare = SQ_NONE;
1514 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1515 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1516 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1517 memset(index, 0, sizeof(int) * 64);
1519 for (int i = 0; i < 64; i++)
1522 for (int i = 0; i < 8; i++)
1523 for (int j = 0; j < 16; j++)
1524 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1528 initialKFile = FILE_E;
1529 initialKRFile = FILE_H;
1530 initialQRFile = FILE_A;
1534 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1535 /// UCI interface code, whenever a non-reversible move is made in a
1536 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1537 /// for the program to handle games of arbitrary length, as long as the GUI
1538 /// handles draws by the 50 move rule correctly.
1540 void Position::reset_game_ply() {
1546 /// Position::put_piece() puts a piece on the given square of the board,
1547 /// updating the board array, bitboards, and piece counts.
1549 void Position::put_piece(Piece p, Square s) {
1551 Color c = color_of_piece(p);
1552 PieceType pt = type_of_piece(p);
1555 index[s] = pieceCount[c][pt];
1556 pieceList[c][pt][index[s]] = s;
1558 set_bit(&(byTypeBB[pt]), s);
1559 set_bit(&(byColorBB[c]), s);
1560 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1562 pieceCount[c][pt]++;
1566 /// Position::allow_oo() gives the given side the right to castle kingside.
1567 /// Used when setting castling rights during parsing of FEN strings.
1569 void Position::allow_oo(Color c) {
1571 st->castleRights |= (1 + int(c));
1575 /// Position::allow_ooo() gives the given side the right to castle queenside.
1576 /// Used when setting castling rights during parsing of FEN strings.
1578 void Position::allow_ooo(Color c) {
1580 st->castleRights |= (4 + 4*int(c));
1584 /// Position::compute_key() computes the hash key of the position. The hash
1585 /// key is usually updated incrementally as moves are made and unmade, the
1586 /// compute_key() function is only used when a new position is set up, and
1587 /// to verify the correctness of the hash key when running in debug mode.
1589 Key Position::compute_key() const {
1591 Key result = Key(0ULL);
1593 for (Square s = SQ_A1; s <= SQ_H8; s++)
1594 if (square_is_occupied(s))
1595 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1597 if (ep_square() != SQ_NONE)
1598 result ^= zobEp[ep_square()];
1600 result ^= zobCastle[st->castleRights];
1601 if (side_to_move() == BLACK)
1602 result ^= zobSideToMove;
1608 /// Position::compute_pawn_key() computes the hash key of the position. The
1609 /// hash key is usually updated incrementally as moves are made and unmade,
1610 /// the compute_pawn_key() function is only used when a new position is set
1611 /// up, and to verify the correctness of the pawn hash key when running in
1614 Key Position::compute_pawn_key() const {
1616 Key result = Key(0ULL);
1620 for (Color c = WHITE; c <= BLACK; c++)
1622 b = pieces(PAWN, c);
1625 s = pop_1st_bit(&b);
1626 result ^= zobrist[c][PAWN][s];
1633 /// Position::compute_material_key() computes the hash key of the position.
1634 /// The hash key is usually updated incrementally as moves are made and unmade,
1635 /// the compute_material_key() function is only used when a new position is set
1636 /// up, and to verify the correctness of the material hash key when running in
1639 Key Position::compute_material_key() const {
1641 Key result = Key(0ULL);
1642 for (Color c = WHITE; c <= BLACK; c++)
1643 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1645 int count = piece_count(c, pt);
1646 for (int i = 0; i <= count; i++)
1647 result ^= zobMaterial[c][pt][i];
1653 /// Position::compute_value() compute the incremental scores for the middle
1654 /// game and the endgame. These functions are used to initialize the incremental
1655 /// scores when a new position is set up, and to verify that the scores are correctly
1656 /// updated by do_move and undo_move when the program is running in debug mode.
1657 template<Position::GamePhase Phase>
1658 Value Position::compute_value() const {
1660 Value result = Value(0);
1664 for (Color c = WHITE; c <= BLACK; c++)
1665 for (PieceType pt = PAWN; pt <= KING; pt++)
1670 s = pop_1st_bit(&b);
1671 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1672 result += pst<Phase>(c, pt, s);
1676 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1677 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1682 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1683 /// game material score for the given side. Material scores are updated
1684 /// incrementally during the search, this function is only used while
1685 /// initializing a new Position object.
1687 Value Position::compute_non_pawn_material(Color c) const {
1689 Value result = Value(0);
1691 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1693 Bitboard b = pieces(pt, c);
1696 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1698 result += piece_value_midgame(pt);
1705 /// Position::is_draw() tests whether the position is drawn by material,
1706 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1707 /// must be done by the search.
1709 bool Position::is_draw() const {
1711 // Draw by material?
1713 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1716 // Draw by the 50 moves rule?
1717 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1720 // Draw by repetition?
1721 for (int i = 2; i < Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1722 if (history[gamePly - i] == st->key)
1729 /// Position::is_mate() returns true or false depending on whether the
1730 /// side to move is checkmated.
1732 bool Position::is_mate() const {
1734 MoveStack moves[256];
1736 return is_check() && (generate_evasions(*this, moves, pinned_pieces(sideToMove)) == moves);
1740 /// Position::has_mate_threat() tests whether a given color has a mate in one
1741 /// from the current position.
1743 bool Position::has_mate_threat(Color c) {
1746 Color stm = side_to_move();
1751 // If the input color is not equal to the side to move, do a null move
1755 MoveStack mlist[120];
1756 bool result = false;
1757 Bitboard dc = discovered_check_candidates(sideToMove);
1758 Bitboard pinned = pinned_pieces(sideToMove);
1760 // Generate pseudo-legal non-capture and capture check moves
1761 MoveStack* last = generate_non_capture_checks(*this, mlist, dc);
1762 last = generate_captures(*this, last);
1764 // Loop through the moves, and see if one of them is mate
1765 for (MoveStack* cur = mlist; cur != last; cur++)
1767 Move move = cur->move;
1768 if (!pl_move_is_legal(move, pinned))
1778 // Undo null move, if necessary
1786 /// Position::init_zobrist() is a static member function which initializes the
1787 /// various arrays used to compute hash keys.
1789 void Position::init_zobrist() {
1791 for (int i = 0; i < 2; i++)
1792 for (int j = 0; j < 8; j++)
1793 for (int k = 0; k < 64; k++)
1794 zobrist[i][j][k] = Key(genrand_int64());
1796 for (int i = 0; i < 64; i++)
1797 zobEp[i] = Key(genrand_int64());
1799 for (int i = 0; i < 16; i++)
1800 zobCastle[i] = genrand_int64();
1802 zobSideToMove = genrand_int64();
1804 for (int i = 0; i < 2; i++)
1805 for (int j = 0; j < 8; j++)
1806 for (int k = 0; k < 16; k++)
1807 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1809 for (int i = 0; i < 16; i++)
1810 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1814 /// Position::init_piece_square_tables() initializes the piece square tables.
1815 /// This is a two-step operation: First, the white halves of the tables are
1816 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1817 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1818 /// Second, the black halves of the tables are initialized by mirroring
1819 /// and changing the sign of the corresponding white scores.
1821 void Position::init_piece_square_tables() {
1823 int r = get_option_value_int("Randomness"), i;
1824 for (Square s = SQ_A1; s <= SQ_H8; s++)
1825 for (Piece p = WP; p <= WK; p++)
1827 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1828 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1829 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1832 for (Square s = SQ_A1; s <= SQ_H8; s++)
1833 for (Piece p = BP; p <= BK; p++)
1835 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1836 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
1841 /// Position::flipped_copy() makes a copy of the input position, but with
1842 /// the white and black sides reversed. This is only useful for debugging,
1843 /// especially for finding evaluation symmetry bugs.
1845 void Position::flipped_copy(const Position& pos) {
1847 assert(pos.is_ok());
1852 for (Square s = SQ_A1; s <= SQ_H8; s++)
1853 if (!pos.square_is_empty(s))
1854 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1857 sideToMove = opposite_color(pos.side_to_move());
1860 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1861 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1862 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1863 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1865 initialKFile = pos.initialKFile;
1866 initialKRFile = pos.initialKRFile;
1867 initialQRFile = pos.initialQRFile;
1869 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1870 castleRightsMask[sq] = ALL_CASTLES;
1872 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1873 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1874 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1875 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1876 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1877 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1879 // En passant square
1880 if (pos.st->epSquare != SQ_NONE)
1881 st->epSquare = flip_square(pos.st->epSquare);
1887 st->key = compute_key();
1888 st->pawnKey = compute_pawn_key();
1889 st->materialKey = compute_material_key();
1891 // Incremental scores
1892 st->mgValue = compute_value<MidGame>();
1893 st->egValue = compute_value<EndGame>();
1896 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1897 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1903 /// Position::is_ok() performs some consitency checks for the position object.
1904 /// This is meant to be helpful when debugging.
1906 bool Position::is_ok(int* failedStep) const {
1908 // What features of the position should be verified?
1909 static const bool debugBitboards = false;
1910 static const bool debugKingCount = false;
1911 static const bool debugKingCapture = false;
1912 static const bool debugCheckerCount = false;
1913 static const bool debugKey = false;
1914 static const bool debugMaterialKey = false;
1915 static const bool debugPawnKey = false;
1916 static const bool debugIncrementalEval = false;
1917 static const bool debugNonPawnMaterial = false;
1918 static const bool debugPieceCounts = false;
1919 static const bool debugPieceList = false;
1921 if (failedStep) *failedStep = 1;
1924 if (!color_is_ok(side_to_move()))
1927 // Are the king squares in the position correct?
1928 if (failedStep) (*failedStep)++;
1929 if (piece_on(king_square(WHITE)) != WK)
1932 if (failedStep) (*failedStep)++;
1933 if (piece_on(king_square(BLACK)) != BK)
1937 if (failedStep) (*failedStep)++;
1938 if (!file_is_ok(initialKRFile))
1941 if (!file_is_ok(initialQRFile))
1944 // Do both sides have exactly one king?
1945 if (failedStep) (*failedStep)++;
1948 int kingCount[2] = {0, 0};
1949 for (Square s = SQ_A1; s <= SQ_H8; s++)
1950 if (type_of_piece_on(s) == KING)
1951 kingCount[color_of_piece_on(s)]++;
1953 if (kingCount[0] != 1 || kingCount[1] != 1)
1957 // Can the side to move capture the opponent's king?
1958 if (failedStep) (*failedStep)++;
1959 if (debugKingCapture)
1961 Color us = side_to_move();
1962 Color them = opposite_color(us);
1963 Square ksq = king_square(them);
1964 if (attackers_to(ksq) & pieces_of_color(us))
1968 // Is there more than 2 checkers?
1969 if (failedStep) (*failedStep)++;
1970 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1974 if (failedStep) (*failedStep)++;
1977 // The intersection of the white and black pieces must be empty
1978 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1981 // The union of the white and black pieces must be equal to all
1983 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1986 // Separate piece type bitboards must have empty intersections
1987 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1988 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1989 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1993 // En passant square OK?
1994 if (failedStep) (*failedStep)++;
1995 if (ep_square() != SQ_NONE)
1997 // The en passant square must be on rank 6, from the point of view of the
1999 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2004 if (failedStep) (*failedStep)++;
2005 if (debugKey && st->key != compute_key())
2008 // Pawn hash key OK?
2009 if (failedStep) (*failedStep)++;
2010 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2013 // Material hash key OK?
2014 if (failedStep) (*failedStep)++;
2015 if (debugMaterialKey && st->materialKey != compute_material_key())
2018 // Incremental eval OK?
2019 if (failedStep) (*failedStep)++;
2020 if (debugIncrementalEval)
2022 if (st->mgValue != compute_value<MidGame>())
2025 if (st->egValue != compute_value<EndGame>())
2029 // Non-pawn material OK?
2030 if (failedStep) (*failedStep)++;
2031 if (debugNonPawnMaterial)
2033 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2036 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2041 if (failedStep) (*failedStep)++;
2042 if (debugPieceCounts)
2043 for (Color c = WHITE; c <= BLACK; c++)
2044 for (PieceType pt = PAWN; pt <= KING; pt++)
2045 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2048 if (failedStep) (*failedStep)++;
2051 for(Color c = WHITE; c <= BLACK; c++)
2052 for(PieceType pt = PAWN; pt <= KING; pt++)
2053 for(int i = 0; i < pieceCount[c][pt]; i++)
2055 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2058 if (index[piece_list(c, pt, i)] != i)
2062 if (failedStep) *failedStep = 0;