2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2009 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
38 #include "ucioption.h"
47 int Position::castleRightsMask[64];
49 Key Position::zobrist[2][8][64];
50 Key Position::zobEp[64];
51 Key Position::zobCastle[16];
52 Key Position::zobMaterial[2][8][16];
53 Key Position::zobSideToMove;
55 Score Position::PieceSquareTable[16][64];
57 static bool RequestPending = false;
62 CheckInfo::CheckInfo(const Position& pos) {
64 Color us = pos.side_to_move();
65 Color them = opposite_color(us);
67 ksq = pos.king_square(them);
68 dcCandidates = pos.discovered_check_candidates(us);
70 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
71 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
72 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
73 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
74 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
75 checkSq[KING] = EmptyBoardBB;
78 Position::Position(const Position& pos) {
82 Position::Position(const string& fen) {
87 /// Position::from_fen() initializes the position object with the given FEN
88 /// string. This function is not very robust - make sure that input FENs are
89 /// correct (this is assumed to be the responsibility of the GUI).
91 void Position::from_fen(const string& fen) {
93 static const string pieceLetters = "KQRBNPkqrbnp";
94 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
102 for ( ; fen[i] != ' '; i++)
106 // Skip the given number of files
107 file += (fen[i] - '1' + 1);
110 else if (fen[i] == '/')
116 size_t idx = pieceLetters.find(fen[i]);
117 if (idx == string::npos)
119 std::cout << "Error in FEN at character " << i << std::endl;
122 Square square = make_square(file, rank);
123 put_piece(pieces[idx], square);
129 if (fen[i] != 'w' && fen[i] != 'b')
131 std::cout << "Error in FEN at character " << i << std::endl;
134 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
140 std::cout << "Error in FEN at character " << i << std::endl;
145 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
151 else if(fen[i] == 'K') allow_oo(WHITE);
152 else if(fen[i] == 'Q') allow_ooo(WHITE);
153 else if(fen[i] == 'k') allow_oo(BLACK);
154 else if(fen[i] == 'q') allow_ooo(BLACK);
155 else if(fen[i] >= 'A' && fen[i] <= 'H') {
156 File rookFile, kingFile = FILE_NONE;
157 for(Square square = SQ_B1; square <= SQ_G1; square++)
158 if(piece_on(square) == WK)
159 kingFile = square_file(square);
160 if(kingFile == FILE_NONE) {
161 std::cout << "Error in FEN at character " << i << std::endl;
164 initialKFile = kingFile;
165 rookFile = File(fen[i] - 'A') + FILE_A;
166 if(rookFile < initialKFile) {
168 initialQRFile = rookFile;
172 initialKRFile = rookFile;
175 else if(fen[i] >= 'a' && fen[i] <= 'h') {
176 File rookFile, kingFile = FILE_NONE;
177 for(Square square = SQ_B8; square <= SQ_G8; square++)
178 if(piece_on(square) == BK)
179 kingFile = square_file(square);
180 if(kingFile == FILE_NONE) {
181 std::cout << "Error in FEN at character " << i << std::endl;
184 initialKFile = kingFile;
185 rookFile = File(fen[i] - 'a') + FILE_A;
186 if(rookFile < initialKFile) {
188 initialQRFile = rookFile;
192 initialKRFile = rookFile;
196 std::cout << "Error in FEN at character " << i << std::endl;
203 while (fen[i] == ' ')
207 if ( i <= fen.length() - 2
208 && (fen[i] >= 'a' && fen[i] <= 'h')
209 && (fen[i+1] == '3' || fen[i+1] == '6'))
210 st->epSquare = square_from_string(fen.substr(i, 2));
212 // Various initialisation
213 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
214 castleRightsMask[sq] = ALL_CASTLES;
216 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
217 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
218 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
219 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
220 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
221 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
225 st->key = compute_key();
226 st->pawnKey = compute_pawn_key();
227 st->materialKey = compute_material_key();
228 st->value = compute_value();
229 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
230 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
234 /// Position::to_fen() converts the position object to a FEN string. This is
235 /// probably only useful for debugging.
237 const string Position::to_fen() const {
239 static const string pieceLetters = " PNBRQK pnbrqk";
243 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
246 for (File file = FILE_A; file <= FILE_H; file++)
248 Square sq = make_square(file, rank);
249 if (!square_is_occupied(sq))
255 fen += (char)skip + '0';
258 fen += pieceLetters[piece_on(sq)];
261 fen += (char)skip + '0';
263 fen += (rank > RANK_1 ? '/' : ' ');
265 fen += (sideToMove == WHITE ? "w " : "b ");
266 if (st->castleRights != NO_CASTLES)
268 if (can_castle_kingside(WHITE)) fen += 'K';
269 if (can_castle_queenside(WHITE)) fen += 'Q';
270 if (can_castle_kingside(BLACK)) fen += 'k';
271 if (can_castle_queenside(BLACK)) fen += 'q';
276 if (ep_square() != SQ_NONE)
277 fen += square_to_string(ep_square());
285 /// Position::print() prints an ASCII representation of the position to
286 /// the standard output. If a move is given then also the san is print.
288 void Position::print(Move m) const {
290 static const string pieceLetters = " PNBRQK PNBRQK .";
292 // Check for reentrancy, as example when called from inside
293 // MovePicker that is used also here in move_to_san()
297 RequestPending = true;
299 std::cout << std::endl;
302 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
303 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
305 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
307 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
308 for (File file = FILE_A; file <= FILE_H; file++)
310 Square sq = make_square(file, rank);
311 Piece piece = piece_on(sq);
312 if (piece == EMPTY && square_color(sq) == WHITE)
315 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
316 std::cout << '|' << col << pieceLetters[piece] << col;
318 std::cout << '|' << std::endl;
320 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
321 << "Fen is: " << to_fen() << std::endl
322 << "Key is: " << st->key << std::endl;
324 RequestPending = false;
328 /// Position::copy() creates a copy of the input position.
330 void Position::copy(const Position& pos) {
332 memcpy(this, &pos, sizeof(Position));
333 saveState(); // detach and copy state info
337 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
338 /// king) pieces for the given color and for the given pinner type. Or, when
339 /// template parameter FindPinned is false, the pieces of the given color
340 /// candidate for a discovery check against the enemy king.
341 /// Note that checkersBB bitboard must be already updated.
343 template<bool FindPinned>
344 Bitboard Position::hidden_checkers(Color c) const {
346 Bitboard pinners, result = EmptyBoardBB;
348 // Pinned pieces protect our king, dicovery checks attack
350 Square ksq = king_square(FindPinned ? c : opposite_color(c));
352 // Pinners are sliders, not checkers, that give check when
353 // candidate pinned is removed.
354 pinners = (pieces(ROOK, QUEEN, FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
355 | (pieces(BISHOP, QUEEN, FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq]);
357 if (FindPinned && pinners)
358 pinners &= ~st->checkersBB;
362 Square s = pop_1st_bit(&pinners);
363 Bitboard b = squares_between(s, ksq) & occupied_squares();
367 if ( !(b & (b - 1)) // Only one bit set?
368 && (b & pieces_of_color(c))) // Is an our piece?
375 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
376 /// king) pieces for the given color.
378 Bitboard Position::pinned_pieces(Color c) const {
380 return hidden_checkers<true>(c);
384 /// Position:discovered_check_candidates() returns a bitboard containing all
385 /// pieces for the given side which are candidates for giving a discovered
388 Bitboard Position::discovered_check_candidates(Color c) const {
390 return hidden_checkers<false>(c);
393 /// Position::attackers_to() computes a bitboard containing all pieces which
394 /// attacks a given square.
396 Bitboard Position::attackers_to(Square s) const {
398 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
399 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
400 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
401 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
402 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
403 | (attacks_from<KING>(s) & pieces(KING));
406 /// Position::attacks_from() computes a bitboard of all attacks
407 /// of a given piece put in a given square.
409 Bitboard Position::attacks_from(Piece p, Square s) const {
411 assert(square_is_ok(s));
415 case WP: return attacks_from<PAWN>(s, WHITE);
416 case BP: return attacks_from<PAWN>(s, BLACK);
417 case WN: case BN: return attacks_from<KNIGHT>(s);
418 case WB: case BB: return attacks_from<BISHOP>(s);
419 case WR: case BR: return attacks_from<ROOK>(s);
420 case WQ: case BQ: return attacks_from<QUEEN>(s);
421 case WK: case BK: return attacks_from<KING>(s);
428 /// Position::move_attacks_square() tests whether a move from the current
429 /// position attacks a given square.
431 bool Position::move_attacks_square(Move m, Square s) const {
433 assert(move_is_ok(m));
434 assert(square_is_ok(s));
436 Square f = move_from(m), t = move_to(m);
438 assert(square_is_occupied(f));
440 if (bit_is_set(attacks_from(piece_on(f), t), s))
443 // Move the piece and scan for X-ray attacks behind it
444 Bitboard occ = occupied_squares();
445 Color us = color_of_piece_on(f);
448 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
449 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
451 // If we have attacks we need to verify that are caused by our move
452 // and are not already existent ones.
453 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
457 /// Position::find_checkers() computes the checkersBB bitboard, which
458 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
459 /// currently works by calling Position::attackers_to, which is probably
460 /// inefficient. Consider rewriting this function to use the last move
461 /// played, like in non-bitboard versions of Glaurung.
463 void Position::find_checkers() {
465 Color us = side_to_move();
466 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
470 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
472 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
475 assert(move_is_ok(m));
476 assert(pinned == pinned_pieces(side_to_move()));
478 // Castling moves are checked for legality during move generation.
479 if (move_is_castle(m))
482 Color us = side_to_move();
483 Square from = move_from(m);
485 assert(color_of_piece_on(from) == us);
486 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
488 // En passant captures are a tricky special case. Because they are
489 // rather uncommon, we do it simply by testing whether the king is attacked
490 // after the move is made
493 Color them = opposite_color(us);
494 Square to = move_to(m);
495 Square capsq = make_square(square_file(to), square_rank(from));
496 Bitboard b = occupied_squares();
497 Square ksq = king_square(us);
499 assert(to == ep_square());
500 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
501 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
502 assert(piece_on(to) == EMPTY);
505 clear_bit(&b, capsq);
508 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
509 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
512 // If the moving piece is a king, check whether the destination
513 // square is attacked by the opponent.
514 if (type_of_piece_on(from) == KING)
515 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
517 // A non-king move is legal if and only if it is not pinned or it
518 // is moving along the ray towards or away from the king.
520 || !bit_is_set(pinned, from)
521 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
525 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
527 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
531 Color us = side_to_move();
532 Square from = move_from(m);
533 Square to = move_to(m);
535 // King moves and en-passant captures are verified in pl_move_is_legal()
536 if (type_of_piece_on(from) == KING || move_is_ep(m))
537 return pl_move_is_legal(m, pinned);
539 Bitboard target = checkers();
540 Square checksq = pop_1st_bit(&target);
542 if (target) // double check ?
545 // Our move must be a blocking evasion or a capture of the checking piece
546 target = squares_between(checksq, king_square(us)) | checkers();
547 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
551 /// Position::move_is_check() tests whether a pseudo-legal move is a check
553 bool Position::move_is_check(Move m) const {
555 return move_is_check(m, CheckInfo(*this));
558 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
561 assert(move_is_ok(m));
562 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
563 assert(color_of_piece_on(move_from(m)) == side_to_move());
564 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
566 Square from = move_from(m);
567 Square to = move_to(m);
568 PieceType pt = type_of_piece_on(from);
571 if (bit_is_set(ci.checkSq[pt], to))
575 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
577 // For pawn and king moves we need to verify also direction
578 if ( (pt != PAWN && pt != KING)
579 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
583 // Can we skip the ugly special cases ?
584 if (!move_is_special(m))
587 Color us = side_to_move();
588 Bitboard b = occupied_squares();
590 // Promotion with check ?
591 if (move_is_promotion(m))
595 switch (move_promotion_piece(m))
598 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
600 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
602 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
604 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
610 // En passant capture with check? We have already handled the case
611 // of direct checks and ordinary discovered check, the only case we
612 // need to handle is the unusual case of a discovered check through the
616 Square capsq = make_square(square_file(to), square_rank(from));
618 clear_bit(&b, capsq);
620 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
621 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
624 // Castling with check ?
625 if (move_is_castle(m))
627 Square kfrom, kto, rfrom, rto;
633 kto = relative_square(us, SQ_G1);
634 rto = relative_square(us, SQ_F1);
636 kto = relative_square(us, SQ_C1);
637 rto = relative_square(us, SQ_D1);
639 clear_bit(&b, kfrom);
640 clear_bit(&b, rfrom);
643 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
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 pawnKey, materialKey;
706 int castleRights, rule50, pliesFromNull;
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);
745 PieceType capture = ep ? PAWN : type_of_piece_on(to);
747 assert(color_of_piece_on(from) == us);
748 assert(color_of_piece_on(to) == them || square_is_empty(to));
749 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
750 assert(!pm || relative_rank(us, to) == RANK_8);
753 do_capture_move(key, 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 // Update piece lists, note that index[from] is not updated and
788 // becomes stale. This works as long as index[] is accessed just
789 // by known occupied squares.
790 index[to] = index[from];
791 pieceList[us][pt][index[to]] = to;
793 // If the moving piece was a pawn do some special extra work
796 // Reset rule 50 draw counter
799 // Update pawn hash key
800 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
802 // Set en passant square, only if moved pawn can be captured
803 if ((to ^ from) == 16)
805 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
807 st->epSquare = Square((int(from) + int(to)) / 2);
808 key ^= zobEp[st->epSquare];
813 // Update incremental scores
814 st->value += pst_delta(piece, from, to);
817 st->capture = capture;
819 if (pm) // promotion ?
821 PieceType promotion = move_promotion_piece(m);
823 assert(promotion >= KNIGHT && promotion <= QUEEN);
825 // Insert promoted piece instead of pawn
826 clear_bit(&(byTypeBB[PAWN]), to);
827 set_bit(&(byTypeBB[promotion]), to);
828 board[to] = piece_of_color_and_type(us, promotion);
830 // Update material key
831 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
832 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
834 // Update piece counts
835 pieceCount[us][PAWN]--;
836 pieceCount[us][promotion]++;
838 // Update piece lists, move the last pawn at index[to] position
839 // and shrink the list. Add a new promotion piece to the list.
840 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
841 index[lastPawnSquare] = index[to];
842 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
843 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
844 index[to] = pieceCount[us][promotion] - 1;
845 pieceList[us][promotion][index[to]] = to;
847 // Partially revert hash keys update
848 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
849 st->pawnKey ^= zobrist[us][PAWN][to];
851 // Partially revert and update incremental scores
852 st->value -= pst(us, PAWN, to);
853 st->value += pst(us, promotion, to);
856 st->npMaterial[us] += piece_value_midgame(promotion);
859 // Update the key with the final value
862 // Update checkers bitboard, piece must be already moved
864 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
867 st->checkersBB = EmptyBoardBB;
868 Square ksq = king_square(them);
871 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
872 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
873 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
874 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
875 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
876 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
877 default: assert(false); break;
882 sideToMove = opposite_color(sideToMove);
883 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
889 /// Position::do_capture_move() is a private method used to update captured
890 /// piece info. It is called from the main Position::do_move function.
892 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
894 assert(capture != KING);
898 if (ep) // en passant ?
900 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
902 assert(to == st->epSquare);
903 assert(relative_rank(opposite_color(them), to) == RANK_6);
904 assert(piece_on(to) == EMPTY);
905 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
907 board[capsq] = EMPTY;
910 // Remove captured piece
911 clear_bit(&(byColorBB[them]), capsq);
912 clear_bit(&(byTypeBB[capture]), capsq);
913 clear_bit(&(byTypeBB[0]), capsq);
916 key ^= zobrist[them][capture][capsq];
918 // Update incremental scores
919 st->value -= pst(them, capture, capsq);
921 // If the captured piece was a pawn, update pawn hash key,
922 // otherwise update non-pawn material.
924 st->pawnKey ^= zobrist[them][PAWN][capsq];
926 st->npMaterial[them] -= piece_value_midgame(capture);
928 // Update material hash key
929 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
931 // Update piece count
932 pieceCount[them][capture]--;
934 // Update piece list, move the last piece at index[capsq] position
936 // WARNING: This is a not perfectly revresible operation. When we
937 // will reinsert the captured piece in undo_move() we will put it
938 // at the end of the list and not in its original place, it means
939 // index[] and pieceList[] are not guaranteed to be invariant to a
940 // do_move() + undo_move() sequence.
941 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
942 index[lastPieceSquare] = index[capsq];
943 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
944 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
946 // Reset rule 50 counter
951 /// Position::do_castle_move() is a private method used to make a castling
952 /// move. It is called from the main Position::do_move function. Note that
953 /// castling moves are encoded as "king captures friendly rook" moves, for
954 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
956 void Position::do_castle_move(Move m) {
958 assert(move_is_ok(m));
959 assert(move_is_castle(m));
961 Color us = side_to_move();
962 Color them = opposite_color(us);
964 // Reset capture field
965 st->capture = NO_PIECE_TYPE;
967 // Find source squares for king and rook
968 Square kfrom = move_from(m);
969 Square rfrom = move_to(m); // HACK: See comment at beginning of function
972 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
973 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
975 // Find destination squares for king and rook
976 if (rfrom > kfrom) // O-O
978 kto = relative_square(us, SQ_G1);
979 rto = relative_square(us, SQ_F1);
981 kto = relative_square(us, SQ_C1);
982 rto = relative_square(us, SQ_D1);
985 // Remove pieces from source squares:
986 clear_bit(&(byColorBB[us]), kfrom);
987 clear_bit(&(byTypeBB[KING]), kfrom);
988 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
989 clear_bit(&(byColorBB[us]), rfrom);
990 clear_bit(&(byTypeBB[ROOK]), rfrom);
991 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
993 // Put pieces on destination squares:
994 set_bit(&(byColorBB[us]), kto);
995 set_bit(&(byTypeBB[KING]), kto);
996 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
997 set_bit(&(byColorBB[us]), rto);
998 set_bit(&(byTypeBB[ROOK]), rto);
999 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1001 // Update board array
1002 Piece king = piece_of_color_and_type(us, KING);
1003 Piece rook = piece_of_color_and_type(us, ROOK);
1004 board[kfrom] = board[rfrom] = EMPTY;
1008 // Update piece lists
1009 pieceList[us][KING][index[kfrom]] = kto;
1010 pieceList[us][ROOK][index[rfrom]] = rto;
1011 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1012 index[kto] = index[kfrom];
1015 // Update incremental scores
1016 st->value += pst_delta(king, kfrom, kto);
1017 st->value += pst_delta(rook, rfrom, rto);
1020 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1021 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1023 // Clear en passant square
1024 if (st->epSquare != SQ_NONE)
1026 st->key ^= zobEp[st->epSquare];
1027 st->epSquare = SQ_NONE;
1030 // Update castling rights
1031 st->key ^= zobCastle[st->castleRights];
1032 st->castleRights &= castleRightsMask[kfrom];
1033 st->key ^= zobCastle[st->castleRights];
1035 // Reset rule 50 counter
1038 // Update checkers BB
1039 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1042 sideToMove = opposite_color(sideToMove);
1043 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1049 /// Position::undo_move() unmakes a move. When it returns, the position should
1050 /// be restored to exactly the same state as before the move was made.
1052 void Position::undo_move(Move m) {
1055 assert(move_is_ok(m));
1058 sideToMove = opposite_color(sideToMove);
1060 if (move_is_castle(m))
1062 undo_castle_move(m);
1066 Color us = side_to_move();
1067 Color them = opposite_color(us);
1068 Square from = move_from(m);
1069 Square to = move_to(m);
1070 bool ep = move_is_ep(m);
1071 bool pm = move_is_promotion(m);
1073 PieceType pt = type_of_piece_on(to);
1075 assert(square_is_empty(from));
1076 assert(color_of_piece_on(to) == us);
1077 assert(!pm || relative_rank(us, to) == RANK_8);
1078 assert(!ep || to == st->previous->epSquare);
1079 assert(!ep || relative_rank(us, to) == RANK_6);
1080 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1082 if (pm) // promotion ?
1084 PieceType promotion = move_promotion_piece(m);
1087 assert(promotion >= KNIGHT && promotion <= QUEEN);
1088 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1090 // Replace promoted piece with a pawn
1091 clear_bit(&(byTypeBB[promotion]), to);
1092 set_bit(&(byTypeBB[PAWN]), to);
1094 // Update piece counts
1095 pieceCount[us][promotion]--;
1096 pieceCount[us][PAWN]++;
1098 // Update piece list replacing promotion piece with a pawn
1099 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1100 index[lastPromotionSquare] = index[to];
1101 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1102 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1103 index[to] = pieceCount[us][PAWN] - 1;
1104 pieceList[us][PAWN][index[to]] = to;
1108 // Put the piece back at the source square
1109 Bitboard move_bb = make_move_bb(to, from);
1110 do_move_bb(&(byColorBB[us]), move_bb);
1111 do_move_bb(&(byTypeBB[pt]), move_bb);
1112 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1114 board[from] = piece_of_color_and_type(us, pt);
1117 // Update piece list
1118 index[from] = index[to];
1119 pieceList[us][pt][index[from]] = from;
1126 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1128 assert(st->capture != KING);
1129 assert(!ep || square_is_empty(capsq));
1131 // Restore the captured piece
1132 set_bit(&(byColorBB[them]), capsq);
1133 set_bit(&(byTypeBB[st->capture]), capsq);
1134 set_bit(&(byTypeBB[0]), capsq);
1136 board[capsq] = piece_of_color_and_type(them, st->capture);
1138 // Update piece count
1139 pieceCount[them][st->capture]++;
1141 // Update piece list, add a new captured piece in capsq square
1142 index[capsq] = pieceCount[them][st->capture] - 1;
1143 pieceList[them][st->capture][index[capsq]] = capsq;
1146 // Finally point our state pointer back to the previous state
1153 /// Position::undo_castle_move() is a private method used to unmake a castling
1154 /// move. It is called from the main Position::undo_move function. Note that
1155 /// castling moves are encoded as "king captures friendly rook" moves, for
1156 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1158 void Position::undo_castle_move(Move m) {
1160 assert(move_is_ok(m));
1161 assert(move_is_castle(m));
1163 // When we have arrived here, some work has already been done by
1164 // Position::undo_move. In particular, the side to move has been switched,
1165 // so the code below is correct.
1166 Color us = side_to_move();
1168 // Find source squares for king and rook
1169 Square kfrom = move_from(m);
1170 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1173 // Find destination squares for king and rook
1174 if (rfrom > kfrom) // O-O
1176 kto = relative_square(us, SQ_G1);
1177 rto = relative_square(us, SQ_F1);
1179 kto = relative_square(us, SQ_C1);
1180 rto = relative_square(us, SQ_D1);
1183 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1184 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1186 // Remove pieces from destination squares:
1187 clear_bit(&(byColorBB[us]), kto);
1188 clear_bit(&(byTypeBB[KING]), kto);
1189 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1190 clear_bit(&(byColorBB[us]), rto);
1191 clear_bit(&(byTypeBB[ROOK]), rto);
1192 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1194 // Put pieces on source squares:
1195 set_bit(&(byColorBB[us]), kfrom);
1196 set_bit(&(byTypeBB[KING]), kfrom);
1197 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1198 set_bit(&(byColorBB[us]), rfrom);
1199 set_bit(&(byTypeBB[ROOK]), rfrom);
1200 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1203 board[rto] = board[kto] = EMPTY;
1204 board[rfrom] = piece_of_color_and_type(us, ROOK);
1205 board[kfrom] = piece_of_color_and_type(us, KING);
1207 // Update piece lists
1208 pieceList[us][KING][index[kto]] = kfrom;
1209 pieceList[us][ROOK][index[rto]] = rfrom;
1210 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1211 index[kfrom] = index[kto];
1214 // Finally point our state pointer back to the previous state
1221 /// Position::do_null_move makes() a "null move": It switches the side to move
1222 /// and updates the hash key without executing any move on the board.
1224 void Position::do_null_move(StateInfo& backupSt) {
1227 assert(!is_check());
1229 // Back up the information necessary to undo the null move to the supplied
1230 // StateInfo object.
1231 // Note that differently from normal case here backupSt is actually used as
1232 // a backup storage not as a new state to be used.
1233 backupSt.key = st->key;
1234 backupSt.epSquare = st->epSquare;
1235 backupSt.value = st->value;
1236 backupSt.previous = st->previous;
1237 backupSt.pliesFromNull = st->pliesFromNull;
1238 st->previous = &backupSt;
1240 // Save the current key to the history[] array, in order to be able to
1241 // detect repetition draws.
1242 history[gamePly] = st->key;
1244 // Update the necessary information
1245 if (st->epSquare != SQ_NONE)
1246 st->key ^= zobEp[st->epSquare];
1248 st->key ^= zobSideToMove;
1249 TT.prefetch(st->key);
1251 sideToMove = opposite_color(sideToMove);
1252 st->epSquare = SQ_NONE;
1254 st->pliesFromNull = 0;
1255 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1260 /// Position::undo_null_move() unmakes a "null move".
1262 void Position::undo_null_move() {
1265 assert(!is_check());
1267 // Restore information from the our backup StateInfo object
1268 StateInfo* backupSt = st->previous;
1269 st->key = backupSt->key;
1270 st->epSquare = backupSt->epSquare;
1271 st->value = backupSt->value;
1272 st->previous = backupSt->previous;
1273 st->pliesFromNull = backupSt->pliesFromNull;
1275 // Update the necessary information
1276 sideToMove = opposite_color(sideToMove);
1282 /// Position::see() is a static exchange evaluator: It tries to estimate the
1283 /// material gain or loss resulting from a move. There are three versions of
1284 /// this function: One which takes a destination square as input, one takes a
1285 /// move, and one which takes a 'from' and a 'to' square. The function does
1286 /// not yet understand promotions captures.
1288 int Position::see(Square to) const {
1290 assert(square_is_ok(to));
1291 return see(SQ_NONE, to);
1294 int Position::see(Move m) const {
1296 assert(move_is_ok(m));
1297 return see(move_from(m), move_to(m));
1300 int Position::see_sign(Move m) const {
1302 assert(move_is_ok(m));
1304 Square from = move_from(m);
1305 Square to = move_to(m);
1307 // Early return if SEE cannot be negative because capturing piece value
1308 // is not bigger then captured one.
1309 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1310 && type_of_piece_on(from) != KING)
1313 return see(from, to);
1316 int Position::see(Square from, Square to) const {
1319 static const int seeValues[18] = {
1320 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1321 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1322 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1323 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1327 Bitboard attackers, stmAttackers, b;
1329 assert(square_is_ok(from) || from == SQ_NONE);
1330 assert(square_is_ok(to));
1332 // Initialize colors
1333 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1334 Color them = opposite_color(us);
1336 // Initialize pieces
1337 Piece piece = piece_on(from);
1338 Piece capture = piece_on(to);
1339 Bitboard occ = occupied_squares();
1341 // King cannot be recaptured
1342 if (type_of_piece(piece) == KING)
1343 return seeValues[capture];
1345 // Handle en passant moves
1346 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1348 assert(capture == EMPTY);
1350 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1351 capture = piece_on(capQq);
1352 assert(type_of_piece_on(capQq) == PAWN);
1354 // Remove the captured pawn
1355 clear_bit(&occ, capQq);
1360 // Find all attackers to the destination square, with the moving piece
1361 // removed, but possibly an X-ray attacker added behind it.
1362 clear_bit(&occ, from);
1363 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1364 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1365 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1366 | (attacks_from<KING>(to) & pieces(KING))
1367 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1368 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1370 if (from != SQ_NONE)
1373 // If we don't have any attacker we are finished
1374 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1377 // Locate the least valuable attacker to the destination square
1378 // and use it to initialize from square.
1379 stmAttackers = attackers & pieces_of_color(us);
1381 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1384 from = first_1(stmAttackers & pieces(pt));
1385 piece = piece_on(from);
1388 // If the opponent has no attackers we are finished
1389 stmAttackers = attackers & pieces_of_color(them);
1391 return seeValues[capture];
1393 attackers &= occ; // Remove the moving piece
1395 // The destination square is defended, which makes things rather more
1396 // difficult to compute. We proceed by building up a "swap list" containing
1397 // the material gain or loss at each stop in a sequence of captures to the
1398 // destination square, where the sides alternately capture, and always
1399 // capture with the least valuable piece. After each capture, we look for
1400 // new X-ray attacks from behind the capturing piece.
1401 int lastCapturingPieceValue = seeValues[piece];
1402 int swapList[32], n = 1;
1406 swapList[0] = seeValues[capture];
1409 // Locate the least valuable attacker for the side to move. The loop
1410 // below looks like it is potentially infinite, but it isn't. We know
1411 // that the side to move still has at least one attacker left.
1412 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1415 // Remove the attacker we just found from the 'attackers' bitboard,
1416 // and scan for new X-ray attacks behind the attacker.
1417 b = stmAttackers & pieces(pt);
1418 occ ^= (b & (~b + 1));
1419 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1420 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1424 // Add the new entry to the swap list
1426 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1429 // Remember the value of the capturing piece, and change the side to move
1430 // before beginning the next iteration
1431 lastCapturingPieceValue = seeValues[pt];
1432 c = opposite_color(c);
1433 stmAttackers = attackers & pieces_of_color(c);
1435 // Stop after a king capture
1436 if (pt == KING && stmAttackers)
1439 swapList[n++] = QueenValueMidgame*10;
1442 } while (stmAttackers);
1444 // Having built the swap list, we negamax through it to find the best
1445 // achievable score from the point of view of the side to move
1447 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1453 /// Position::saveState() copies the content of the current state
1454 /// inside startState and makes st point to it. This is needed
1455 /// when the st pointee could become stale, as example because
1456 /// the caller is about to going out of scope.
1458 void Position::saveState() {
1462 st->previous = NULL; // as a safe guard
1466 /// Position::clear() erases the position object to a pristine state, with an
1467 /// empty board, white to move, and no castling rights.
1469 void Position::clear() {
1472 memset(st, 0, sizeof(StateInfo));
1473 st->epSquare = SQ_NONE;
1475 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1476 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1477 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1478 memset(index, 0, sizeof(int) * 64);
1480 for (int i = 0; i < 64; i++)
1483 for (int i = 0; i < 8; i++)
1484 for (int j = 0; j < 16; j++)
1485 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1489 initialKFile = FILE_E;
1490 initialKRFile = FILE_H;
1491 initialQRFile = FILE_A;
1495 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1496 /// UCI interface code, whenever a non-reversible move is made in a
1497 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1498 /// for the program to handle games of arbitrary length, as long as the GUI
1499 /// handles draws by the 50 move rule correctly.
1501 void Position::reset_game_ply() {
1507 /// Position::put_piece() puts a piece on the given square of the board,
1508 /// updating the board array, bitboards, and piece counts.
1510 void Position::put_piece(Piece p, Square s) {
1512 Color c = color_of_piece(p);
1513 PieceType pt = type_of_piece(p);
1516 index[s] = pieceCount[c][pt];
1517 pieceList[c][pt][index[s]] = s;
1519 set_bit(&(byTypeBB[pt]), s);
1520 set_bit(&(byColorBB[c]), s);
1521 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1523 pieceCount[c][pt]++;
1527 /// Position::allow_oo() gives the given side the right to castle kingside.
1528 /// Used when setting castling rights during parsing of FEN strings.
1530 void Position::allow_oo(Color c) {
1532 st->castleRights |= (1 + int(c));
1536 /// Position::allow_ooo() gives the given side the right to castle queenside.
1537 /// Used when setting castling rights during parsing of FEN strings.
1539 void Position::allow_ooo(Color c) {
1541 st->castleRights |= (4 + 4*int(c));
1545 /// Position::compute_key() computes the hash key of the position. The hash
1546 /// key is usually updated incrementally as moves are made and unmade, the
1547 /// compute_key() function is only used when a new position is set up, and
1548 /// to verify the correctness of the hash key when running in debug mode.
1550 Key Position::compute_key() const {
1552 Key result = Key(0ULL);
1554 for (Square s = SQ_A1; s <= SQ_H8; s++)
1555 if (square_is_occupied(s))
1556 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1558 if (ep_square() != SQ_NONE)
1559 result ^= zobEp[ep_square()];
1561 result ^= zobCastle[st->castleRights];
1562 if (side_to_move() == BLACK)
1563 result ^= zobSideToMove;
1569 /// Position::compute_pawn_key() computes the hash key of the position. The
1570 /// hash key is usually updated incrementally as moves are made and unmade,
1571 /// the compute_pawn_key() function is only used when a new position is set
1572 /// up, and to verify the correctness of the pawn hash key when running in
1575 Key Position::compute_pawn_key() const {
1577 Key result = Key(0ULL);
1581 for (Color c = WHITE; c <= BLACK; c++)
1583 b = pieces(PAWN, c);
1586 s = pop_1st_bit(&b);
1587 result ^= zobrist[c][PAWN][s];
1594 /// Position::compute_material_key() computes the hash key of the position.
1595 /// The hash key is usually updated incrementally as moves are made and unmade,
1596 /// the compute_material_key() function is only used when a new position is set
1597 /// up, and to verify the correctness of the material hash key when running in
1600 Key Position::compute_material_key() const {
1602 Key result = Key(0ULL);
1603 for (Color c = WHITE; c <= BLACK; c++)
1604 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1606 int count = piece_count(c, pt);
1607 for (int i = 0; i <= count; i++)
1608 result ^= zobMaterial[c][pt][i];
1614 /// Position::compute_value() compute the incremental scores for the middle
1615 /// game and the endgame. These functions are used to initialize the incremental
1616 /// scores when a new position is set up, and to verify that the scores are correctly
1617 /// updated by do_move and undo_move when the program is running in debug mode.
1618 Score Position::compute_value() const {
1620 Score result = make_score(0, 0);
1624 for (Color c = WHITE; c <= BLACK; c++)
1625 for (PieceType pt = PAWN; pt <= KING; pt++)
1630 s = pop_1st_bit(&b);
1631 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1632 result += pst(c, pt, s);
1636 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1641 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1642 /// game material score for the given side. Material scores are updated
1643 /// incrementally during the search, this function is only used while
1644 /// initializing a new Position object.
1646 Value Position::compute_non_pawn_material(Color c) const {
1648 Value result = Value(0);
1650 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1652 Bitboard b = pieces(pt, c);
1655 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1657 result += piece_value_midgame(pt);
1664 /// Position::is_draw() tests whether the position is drawn by material,
1665 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1666 /// must be done by the search.
1668 bool Position::is_draw() const {
1670 // Draw by material?
1672 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1675 // Draw by the 50 moves rule?
1676 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1679 // Draw by repetition?
1680 for (int i = 2; i < Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1681 if (history[gamePly - i] == st->key)
1688 /// Position::is_mate() returns true or false depending on whether the
1689 /// side to move is checkmated.
1691 bool Position::is_mate() const {
1693 MoveStack moves[256];
1694 return is_check() && (generate_moves(*this, moves, false) == moves);
1698 /// Position::has_mate_threat() tests whether a given color has a mate in one
1699 /// from the current position.
1701 bool Position::has_mate_threat(Color c) {
1704 Color stm = side_to_move();
1709 // If the input color is not equal to the side to move, do a null move
1713 MoveStack mlist[120];
1714 bool result = false;
1715 Bitboard pinned = pinned_pieces(sideToMove);
1717 // Generate pseudo-legal non-capture and capture check moves
1718 MoveStack* last = generate_non_capture_checks(*this, mlist);
1719 last = generate_captures(*this, last);
1721 // Loop through the moves, and see if one of them is mate
1722 for (MoveStack* cur = mlist; cur != last; cur++)
1724 Move move = cur->move;
1725 if (!pl_move_is_legal(move, pinned))
1735 // Undo null move, if necessary
1743 /// Position::init_zobrist() is a static member function which initializes the
1744 /// various arrays used to compute hash keys.
1746 void Position::init_zobrist() {
1748 for (int i = 0; i < 2; i++)
1749 for (int j = 0; j < 8; j++)
1750 for (int k = 0; k < 64; k++)
1751 zobrist[i][j][k] = Key(genrand_int64());
1753 for (int i = 0; i < 64; i++)
1754 zobEp[i] = Key(genrand_int64());
1756 for (int i = 0; i < 16; i++)
1757 zobCastle[i] = genrand_int64();
1759 zobSideToMove = genrand_int64();
1761 for (int i = 0; i < 2; i++)
1762 for (int j = 0; j < 8; j++)
1763 for (int k = 0; k < 16; k++)
1764 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1766 for (int i = 0; i < 16; i++)
1767 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1771 /// Position::init_piece_square_tables() initializes the piece square tables.
1772 /// This is a two-step operation: First, the white halves of the tables are
1773 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1774 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1775 /// Second, the black halves of the tables are initialized by mirroring
1776 /// and changing the sign of the corresponding white scores.
1778 void Position::init_piece_square_tables() {
1780 int r = get_option_value_int("Randomness"), i;
1781 for (Square s = SQ_A1; s <= SQ_H8; s++)
1782 for (Piece p = WP; p <= WK; p++)
1784 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1785 PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1788 for (Square s = SQ_A1; s <= SQ_H8; s++)
1789 for (Piece p = BP; p <= BK; p++)
1790 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1794 /// Position::flipped_copy() makes a copy of the input position, but with
1795 /// the white and black sides reversed. This is only useful for debugging,
1796 /// especially for finding evaluation symmetry bugs.
1798 void Position::flipped_copy(const Position& pos) {
1800 assert(pos.is_ok());
1805 for (Square s = SQ_A1; s <= SQ_H8; s++)
1806 if (!pos.square_is_empty(s))
1807 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1810 sideToMove = opposite_color(pos.side_to_move());
1813 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1814 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1815 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1816 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1818 initialKFile = pos.initialKFile;
1819 initialKRFile = pos.initialKRFile;
1820 initialQRFile = pos.initialQRFile;
1822 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1823 castleRightsMask[sq] = ALL_CASTLES;
1825 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1826 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1827 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1828 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1829 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1830 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1832 // En passant square
1833 if (pos.st->epSquare != SQ_NONE)
1834 st->epSquare = flip_square(pos.st->epSquare);
1840 st->key = compute_key();
1841 st->pawnKey = compute_pawn_key();
1842 st->materialKey = compute_material_key();
1844 // Incremental scores
1845 st->value = compute_value();
1848 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1849 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1855 /// Position::is_ok() performs some consitency checks for the position object.
1856 /// This is meant to be helpful when debugging.
1858 bool Position::is_ok(int* failedStep) const {
1860 // What features of the position should be verified?
1861 static const bool debugBitboards = false;
1862 static const bool debugKingCount = false;
1863 static const bool debugKingCapture = false;
1864 static const bool debugCheckerCount = false;
1865 static const bool debugKey = false;
1866 static const bool debugMaterialKey = false;
1867 static const bool debugPawnKey = false;
1868 static const bool debugIncrementalEval = false;
1869 static const bool debugNonPawnMaterial = false;
1870 static const bool debugPieceCounts = false;
1871 static const bool debugPieceList = false;
1873 if (failedStep) *failedStep = 1;
1876 if (!color_is_ok(side_to_move()))
1879 // Are the king squares in the position correct?
1880 if (failedStep) (*failedStep)++;
1881 if (piece_on(king_square(WHITE)) != WK)
1884 if (failedStep) (*failedStep)++;
1885 if (piece_on(king_square(BLACK)) != BK)
1889 if (failedStep) (*failedStep)++;
1890 if (!file_is_ok(initialKRFile))
1893 if (!file_is_ok(initialQRFile))
1896 // Do both sides have exactly one king?
1897 if (failedStep) (*failedStep)++;
1900 int kingCount[2] = {0, 0};
1901 for (Square s = SQ_A1; s <= SQ_H8; s++)
1902 if (type_of_piece_on(s) == KING)
1903 kingCount[color_of_piece_on(s)]++;
1905 if (kingCount[0] != 1 || kingCount[1] != 1)
1909 // Can the side to move capture the opponent's king?
1910 if (failedStep) (*failedStep)++;
1911 if (debugKingCapture)
1913 Color us = side_to_move();
1914 Color them = opposite_color(us);
1915 Square ksq = king_square(them);
1916 if (attackers_to(ksq) & pieces_of_color(us))
1920 // Is there more than 2 checkers?
1921 if (failedStep) (*failedStep)++;
1922 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1926 if (failedStep) (*failedStep)++;
1929 // The intersection of the white and black pieces must be empty
1930 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1933 // The union of the white and black pieces must be equal to all
1935 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1938 // Separate piece type bitboards must have empty intersections
1939 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1940 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1941 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1945 // En passant square OK?
1946 if (failedStep) (*failedStep)++;
1947 if (ep_square() != SQ_NONE)
1949 // The en passant square must be on rank 6, from the point of view of the
1951 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1956 if (failedStep) (*failedStep)++;
1957 if (debugKey && st->key != compute_key())
1960 // Pawn hash key OK?
1961 if (failedStep) (*failedStep)++;
1962 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1965 // Material hash key OK?
1966 if (failedStep) (*failedStep)++;
1967 if (debugMaterialKey && st->materialKey != compute_material_key())
1970 // Incremental eval OK?
1971 if (failedStep) (*failedStep)++;
1972 if (debugIncrementalEval && st->value != compute_value())
1975 // Non-pawn material OK?
1976 if (failedStep) (*failedStep)++;
1977 if (debugNonPawnMaterial)
1979 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1982 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1987 if (failedStep) (*failedStep)++;
1988 if (debugPieceCounts)
1989 for (Color c = WHITE; c <= BLACK; c++)
1990 for (PieceType pt = PAWN; pt <= KING; pt++)
1991 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
1994 if (failedStep) (*failedStep)++;
1997 for(Color c = WHITE; c <= BLACK; c++)
1998 for(PieceType pt = PAWN; pt <= KING; pt++)
1999 for(int i = 0; i < pieceCount[c][pt]; i++)
2001 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2004 if (index[piece_list(c, pt, i)] != i)
2008 if (failedStep) *failedStep = 0;