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 result = EmptyBoardBB;
347 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
349 // Pinned pieces protect our king, dicovery checks attack
351 Square ksq = king_square(FindPinned ? c : opposite_color(c));
353 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
354 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
356 if (FindPinned && pinners)
357 pinners &= ~st->checkersBB;
361 Square s = pop_1st_bit(&pinners);
362 Bitboard b = squares_between(s, ksq) & occupied_squares();
366 if ( !(b & (b - 1)) // Only one bit set?
367 && (b & pieces_of_color(c))) // Is an our piece?
374 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
375 /// king) pieces for the given color.
377 Bitboard Position::pinned_pieces(Color c) const {
379 return hidden_checkers<true>(c);
383 /// Position:discovered_check_candidates() returns a bitboard containing all
384 /// pieces for the given side which are candidates for giving a discovered
387 Bitboard Position::discovered_check_candidates(Color c) const {
389 return hidden_checkers<false>(c);
392 /// Position::attackers_to() computes a bitboard containing all pieces which
393 /// attacks a given square.
395 Bitboard Position::attackers_to(Square s) const {
397 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
398 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
399 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
400 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
401 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
402 | (attacks_from<KING>(s) & pieces(KING));
405 /// Position::attacks_from() computes a bitboard of all attacks
406 /// of a given piece put in a given square.
408 Bitboard Position::attacks_from(Piece p, Square s) const {
410 assert(square_is_ok(s));
414 case WP: return attacks_from<PAWN>(s, WHITE);
415 case BP: return attacks_from<PAWN>(s, BLACK);
416 case WN: case BN: return attacks_from<KNIGHT>(s);
417 case WB: case BB: return attacks_from<BISHOP>(s);
418 case WR: case BR: return attacks_from<ROOK>(s);
419 case WQ: case BQ: return attacks_from<QUEEN>(s);
420 case WK: case BK: return attacks_from<KING>(s);
427 /// Position::move_attacks_square() tests whether a move from the current
428 /// position attacks a given square.
430 bool Position::move_attacks_square(Move m, Square s) const {
432 assert(move_is_ok(m));
433 assert(square_is_ok(s));
435 Square f = move_from(m), t = move_to(m);
437 assert(square_is_occupied(f));
439 if (bit_is_set(attacks_from(piece_on(f), t), s))
442 // Move the piece and scan for X-ray attacks behind it
443 Bitboard occ = occupied_squares();
444 Color us = color_of_piece_on(f);
447 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
448 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
450 // If we have attacks we need to verify that are caused by our move
451 // and are not already existent ones.
452 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
456 /// Position::find_checkers() computes the checkersBB bitboard, which
457 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
458 /// currently works by calling Position::attackers_to, which is probably
459 /// inefficient. Consider rewriting this function to use the last move
460 /// played, like in non-bitboard versions of Glaurung.
462 void Position::find_checkers() {
464 Color us = side_to_move();
465 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
469 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
471 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
474 assert(move_is_ok(m));
475 assert(pinned == pinned_pieces(side_to_move()));
477 // Castling moves are checked for legality during move generation.
478 if (move_is_castle(m))
481 Color us = side_to_move();
482 Square from = move_from(m);
484 assert(color_of_piece_on(from) == us);
485 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
487 // En passant captures are a tricky special case. Because they are
488 // rather uncommon, we do it simply by testing whether the king is attacked
489 // after the move is made
492 Color them = opposite_color(us);
493 Square to = move_to(m);
494 Square capsq = make_square(square_file(to), square_rank(from));
495 Bitboard b = occupied_squares();
496 Square ksq = king_square(us);
498 assert(to == ep_square());
499 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
500 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
501 assert(piece_on(to) == EMPTY);
504 clear_bit(&b, capsq);
507 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
508 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
511 // If the moving piece is a king, check whether the destination
512 // square is attacked by the opponent.
513 if (type_of_piece_on(from) == KING)
514 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
516 // A non-king move is legal if and only if it is not pinned or it
517 // is moving along the ray towards or away from the king.
519 || !bit_is_set(pinned, from)
520 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
524 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
526 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
530 Color us = side_to_move();
531 Square from = move_from(m);
532 Square to = move_to(m);
534 // King moves and en-passant captures are verified in pl_move_is_legal()
535 if (type_of_piece_on(from) == KING || move_is_ep(m))
536 return pl_move_is_legal(m, pinned);
538 Bitboard target = checkers();
539 Square checksq = pop_1st_bit(&target);
541 if (target) // double check ?
544 // Our move must be a blocking evasion or a capture of the checking piece
545 target = squares_between(checksq, king_square(us)) | checkers();
546 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
550 /// Position::move_is_check() tests whether a pseudo-legal move is a check
552 bool Position::move_is_check(Move m) const {
554 return move_is_check(m, CheckInfo(*this));
557 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
560 assert(move_is_ok(m));
561 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
562 assert(color_of_piece_on(move_from(m)) == side_to_move());
563 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
565 Square from = move_from(m);
566 Square to = move_to(m);
567 PieceType pt = type_of_piece_on(from);
570 if (bit_is_set(ci.checkSq[pt], to))
574 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
576 // For pawn and king moves we need to verify also direction
577 if ( (pt != PAWN && pt != KING)
578 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
582 // Can we skip the ugly special cases ?
583 if (!move_is_special(m))
586 Color us = side_to_move();
587 Bitboard b = occupied_squares();
589 // Promotion with check ?
590 if (move_is_promotion(m))
594 switch (move_promotion_piece(m))
597 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
599 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
601 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
603 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
609 // En passant capture with check? We have already handled the case
610 // of direct checks and ordinary discovered check, the only case we
611 // need to handle is the unusual case of a discovered check through the
615 Square capsq = make_square(square_file(to), square_rank(from));
617 clear_bit(&b, capsq);
619 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
620 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
623 // Castling with check ?
624 if (move_is_castle(m))
626 Square kfrom, kto, rfrom, rto;
632 kto = relative_square(us, SQ_G1);
633 rto = relative_square(us, SQ_F1);
635 kto = relative_square(us, SQ_C1);
636 rto = relative_square(us, SQ_D1);
638 clear_bit(&b, kfrom);
639 clear_bit(&b, rfrom);
642 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
649 /// Position::do_move() makes a move, and saves all information necessary
650 /// to a StateInfo object. The move is assumed to be legal.
651 /// Pseudo-legal moves should be filtered out before this function is called.
653 void Position::do_move(Move m, StateInfo& newSt) {
656 do_move(m, newSt, ci, move_is_check(m, ci));
659 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
662 assert(move_is_ok(m));
664 Bitboard key = st->key;
666 // Copy some fields of old state to our new StateInfo object except the
667 // ones which are recalculated from scratch anyway, then switch our state
668 // pointer to point to the new, ready to be updated, state.
669 struct ReducedStateInfo {
670 Key pawnKey, materialKey;
671 int castleRights, rule50, pliesFromNull;
677 memcpy(&newSt, st, sizeof(ReducedStateInfo));
681 // Save the current key to the history[] array, in order to be able to
682 // detect repetition draws.
683 history[gamePly] = key;
686 // Update side to move
687 key ^= zobSideToMove;
689 // Increment the 50 moves rule draw counter. Resetting it to zero in the
690 // case of non-reversible moves is taken care of later.
694 if (move_is_castle(m))
701 Color us = side_to_move();
702 Color them = opposite_color(us);
703 Square from = move_from(m);
704 Square to = move_to(m);
705 bool ep = move_is_ep(m);
706 bool pm = move_is_promotion(m);
708 Piece piece = piece_on(from);
709 PieceType pt = type_of_piece(piece);
710 PieceType capture = ep ? PAWN : type_of_piece_on(to);
712 assert(color_of_piece_on(from) == us);
713 assert(color_of_piece_on(to) == them || square_is_empty(to));
714 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
715 assert(!pm || relative_rank(us, to) == RANK_8);
718 do_capture_move(key, capture, them, to, ep);
721 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
723 // Reset en passant square
724 if (st->epSquare != SQ_NONE)
726 key ^= zobEp[st->epSquare];
727 st->epSquare = SQ_NONE;
730 // Update castle rights, try to shortcut a common case
731 int cm = castleRightsMask[from] & castleRightsMask[to];
732 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
734 key ^= zobCastle[st->castleRights];
735 st->castleRights &= castleRightsMask[from];
736 st->castleRights &= castleRightsMask[to];
737 key ^= zobCastle[st->castleRights];
740 // Prefetch TT access as soon as we know key is updated
744 Bitboard move_bb = make_move_bb(from, to);
745 do_move_bb(&(byColorBB[us]), move_bb);
746 do_move_bb(&(byTypeBB[pt]), move_bb);
747 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
749 board[to] = board[from];
752 // Update piece lists, note that index[from] is not updated and
753 // becomes stale. This works as long as index[] is accessed just
754 // by known occupied squares.
755 index[to] = index[from];
756 pieceList[us][pt][index[to]] = to;
758 // If the moving piece was a pawn do some special extra work
761 // Reset rule 50 draw counter
764 // Update pawn hash key
765 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
767 // Set en passant square, only if moved pawn can be captured
768 if ((to ^ from) == 16)
770 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
772 st->epSquare = Square((int(from) + int(to)) / 2);
773 key ^= zobEp[st->epSquare];
778 // Update incremental scores
779 st->value += pst_delta(piece, from, to);
782 st->capture = capture;
784 if (pm) // promotion ?
786 PieceType promotion = move_promotion_piece(m);
788 assert(promotion >= KNIGHT && promotion <= QUEEN);
790 // Insert promoted piece instead of pawn
791 clear_bit(&(byTypeBB[PAWN]), to);
792 set_bit(&(byTypeBB[promotion]), to);
793 board[to] = piece_of_color_and_type(us, promotion);
795 // Update material key
796 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
797 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
799 // Update piece counts
800 pieceCount[us][PAWN]--;
801 pieceCount[us][promotion]++;
803 // Update piece lists, move the last pawn at index[to] position
804 // and shrink the list. Add a new promotion piece to the list.
805 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
806 index[lastPawnSquare] = index[to];
807 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
808 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
809 index[to] = pieceCount[us][promotion] - 1;
810 pieceList[us][promotion][index[to]] = to;
812 // Partially revert hash keys update
813 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
814 st->pawnKey ^= zobrist[us][PAWN][to];
816 // Partially revert and update incremental scores
817 st->value -= pst(us, PAWN, to);
818 st->value += pst(us, promotion, to);
821 st->npMaterial[us] += piece_value_midgame(promotion);
824 // Update the key with the final value
827 // Update checkers bitboard, piece must be already moved
828 st->checkersBB = EmptyBoardBB;
833 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
837 if (bit_is_set(ci.checkSq[pt], to))
838 st->checkersBB = SetMaskBB[to];
841 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
844 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
847 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
853 sideToMove = opposite_color(sideToMove);
854 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
860 /// Position::do_capture_move() is a private method used to update captured
861 /// piece info. It is called from the main Position::do_move function.
863 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
865 assert(capture != KING);
869 if (ep) // en passant ?
871 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
873 assert(to == st->epSquare);
874 assert(relative_rank(opposite_color(them), to) == RANK_6);
875 assert(piece_on(to) == EMPTY);
876 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
878 board[capsq] = EMPTY;
881 // Remove captured piece
882 clear_bit(&(byColorBB[them]), capsq);
883 clear_bit(&(byTypeBB[capture]), capsq);
884 clear_bit(&(byTypeBB[0]), capsq);
887 key ^= zobrist[them][capture][capsq];
889 // Update incremental scores
890 st->value -= pst(them, capture, capsq);
892 // If the captured piece was a pawn, update pawn hash key,
893 // otherwise update non-pawn material.
895 st->pawnKey ^= zobrist[them][PAWN][capsq];
897 st->npMaterial[them] -= piece_value_midgame(capture);
899 // Update material hash key
900 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
902 // Update piece count
903 pieceCount[them][capture]--;
905 // Update piece list, move the last piece at index[capsq] position
907 // WARNING: This is a not perfectly revresible operation. When we
908 // will reinsert the captured piece in undo_move() we will put it
909 // at the end of the list and not in its original place, it means
910 // index[] and pieceList[] are not guaranteed to be invariant to a
911 // do_move() + undo_move() sequence.
912 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
913 index[lastPieceSquare] = index[capsq];
914 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
915 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
917 // Reset rule 50 counter
922 /// Position::do_castle_move() is a private method used to make a castling
923 /// move. It is called from the main Position::do_move function. Note that
924 /// castling moves are encoded as "king captures friendly rook" moves, for
925 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
927 void Position::do_castle_move(Move m) {
929 assert(move_is_ok(m));
930 assert(move_is_castle(m));
932 Color us = side_to_move();
933 Color them = opposite_color(us);
935 // Reset capture field
936 st->capture = NO_PIECE_TYPE;
938 // Find source squares for king and rook
939 Square kfrom = move_from(m);
940 Square rfrom = move_to(m); // HACK: See comment at beginning of function
943 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
944 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
946 // Find destination squares for king and rook
947 if (rfrom > kfrom) // O-O
949 kto = relative_square(us, SQ_G1);
950 rto = relative_square(us, SQ_F1);
952 kto = relative_square(us, SQ_C1);
953 rto = relative_square(us, SQ_D1);
956 // Remove pieces from source squares:
957 clear_bit(&(byColorBB[us]), kfrom);
958 clear_bit(&(byTypeBB[KING]), kfrom);
959 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
960 clear_bit(&(byColorBB[us]), rfrom);
961 clear_bit(&(byTypeBB[ROOK]), rfrom);
962 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
964 // Put pieces on destination squares:
965 set_bit(&(byColorBB[us]), kto);
966 set_bit(&(byTypeBB[KING]), kto);
967 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
968 set_bit(&(byColorBB[us]), rto);
969 set_bit(&(byTypeBB[ROOK]), rto);
970 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
972 // Update board array
973 Piece king = piece_of_color_and_type(us, KING);
974 Piece rook = piece_of_color_and_type(us, ROOK);
975 board[kfrom] = board[rfrom] = EMPTY;
979 // Update piece lists
980 pieceList[us][KING][index[kfrom]] = kto;
981 pieceList[us][ROOK][index[rfrom]] = rto;
982 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
983 index[kto] = index[kfrom];
986 // Update incremental scores
987 st->value += pst_delta(king, kfrom, kto);
988 st->value += pst_delta(rook, rfrom, rto);
991 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
992 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
994 // Clear en passant square
995 if (st->epSquare != SQ_NONE)
997 st->key ^= zobEp[st->epSquare];
998 st->epSquare = SQ_NONE;
1001 // Update castling rights
1002 st->key ^= zobCastle[st->castleRights];
1003 st->castleRights &= castleRightsMask[kfrom];
1004 st->key ^= zobCastle[st->castleRights];
1006 // Reset rule 50 counter
1009 // Update checkers BB
1010 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1013 sideToMove = opposite_color(sideToMove);
1014 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1020 /// Position::undo_move() unmakes a move. When it returns, the position should
1021 /// be restored to exactly the same state as before the move was made.
1023 void Position::undo_move(Move m) {
1026 assert(move_is_ok(m));
1029 sideToMove = opposite_color(sideToMove);
1031 if (move_is_castle(m))
1033 undo_castle_move(m);
1037 Color us = side_to_move();
1038 Color them = opposite_color(us);
1039 Square from = move_from(m);
1040 Square to = move_to(m);
1041 bool ep = move_is_ep(m);
1042 bool pm = move_is_promotion(m);
1044 PieceType pt = type_of_piece_on(to);
1046 assert(square_is_empty(from));
1047 assert(color_of_piece_on(to) == us);
1048 assert(!pm || relative_rank(us, to) == RANK_8);
1049 assert(!ep || to == st->previous->epSquare);
1050 assert(!ep || relative_rank(us, to) == RANK_6);
1051 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1053 if (pm) // promotion ?
1055 PieceType promotion = move_promotion_piece(m);
1058 assert(promotion >= KNIGHT && promotion <= QUEEN);
1059 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1061 // Replace promoted piece with a pawn
1062 clear_bit(&(byTypeBB[promotion]), to);
1063 set_bit(&(byTypeBB[PAWN]), to);
1065 // Update piece counts
1066 pieceCount[us][promotion]--;
1067 pieceCount[us][PAWN]++;
1069 // Update piece list replacing promotion piece with a pawn
1070 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1071 index[lastPromotionSquare] = index[to];
1072 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1073 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1074 index[to] = pieceCount[us][PAWN] - 1;
1075 pieceList[us][PAWN][index[to]] = to;
1079 // Put the piece back at the source square
1080 Bitboard move_bb = make_move_bb(to, from);
1081 do_move_bb(&(byColorBB[us]), move_bb);
1082 do_move_bb(&(byTypeBB[pt]), move_bb);
1083 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1085 board[from] = piece_of_color_and_type(us, pt);
1088 // Update piece list
1089 index[from] = index[to];
1090 pieceList[us][pt][index[from]] = from;
1097 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1099 assert(st->capture != KING);
1100 assert(!ep || square_is_empty(capsq));
1102 // Restore the captured piece
1103 set_bit(&(byColorBB[them]), capsq);
1104 set_bit(&(byTypeBB[st->capture]), capsq);
1105 set_bit(&(byTypeBB[0]), capsq);
1107 board[capsq] = piece_of_color_and_type(them, st->capture);
1109 // Update piece count
1110 pieceCount[them][st->capture]++;
1112 // Update piece list, add a new captured piece in capsq square
1113 index[capsq] = pieceCount[them][st->capture] - 1;
1114 pieceList[them][st->capture][index[capsq]] = capsq;
1117 // Finally point our state pointer back to the previous state
1124 /// Position::undo_castle_move() is a private method used to unmake a castling
1125 /// move. It is called from the main Position::undo_move function. Note that
1126 /// castling moves are encoded as "king captures friendly rook" moves, for
1127 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1129 void Position::undo_castle_move(Move m) {
1131 assert(move_is_ok(m));
1132 assert(move_is_castle(m));
1134 // When we have arrived here, some work has already been done by
1135 // Position::undo_move. In particular, the side to move has been switched,
1136 // so the code below is correct.
1137 Color us = side_to_move();
1139 // Find source squares for king and rook
1140 Square kfrom = move_from(m);
1141 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1144 // Find destination squares for king and rook
1145 if (rfrom > kfrom) // O-O
1147 kto = relative_square(us, SQ_G1);
1148 rto = relative_square(us, SQ_F1);
1150 kto = relative_square(us, SQ_C1);
1151 rto = relative_square(us, SQ_D1);
1154 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1155 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1157 // Remove pieces from destination squares:
1158 clear_bit(&(byColorBB[us]), kto);
1159 clear_bit(&(byTypeBB[KING]), kto);
1160 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1161 clear_bit(&(byColorBB[us]), rto);
1162 clear_bit(&(byTypeBB[ROOK]), rto);
1163 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1165 // Put pieces on source squares:
1166 set_bit(&(byColorBB[us]), kfrom);
1167 set_bit(&(byTypeBB[KING]), kfrom);
1168 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1169 set_bit(&(byColorBB[us]), rfrom);
1170 set_bit(&(byTypeBB[ROOK]), rfrom);
1171 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1174 board[rto] = board[kto] = EMPTY;
1175 board[rfrom] = piece_of_color_and_type(us, ROOK);
1176 board[kfrom] = piece_of_color_and_type(us, KING);
1178 // Update piece lists
1179 pieceList[us][KING][index[kto]] = kfrom;
1180 pieceList[us][ROOK][index[rto]] = rfrom;
1181 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1182 index[kfrom] = index[kto];
1185 // Finally point our state pointer back to the previous state
1192 /// Position::do_null_move makes() a "null move": It switches the side to move
1193 /// and updates the hash key without executing any move on the board.
1195 void Position::do_null_move(StateInfo& backupSt) {
1198 assert(!is_check());
1200 // Back up the information necessary to undo the null move to the supplied
1201 // StateInfo object.
1202 // Note that differently from normal case here backupSt is actually used as
1203 // a backup storage not as a new state to be used.
1204 backupSt.key = st->key;
1205 backupSt.epSquare = st->epSquare;
1206 backupSt.value = st->value;
1207 backupSt.previous = st->previous;
1208 backupSt.pliesFromNull = st->pliesFromNull;
1209 st->previous = &backupSt;
1211 // Save the current key to the history[] array, in order to be able to
1212 // detect repetition draws.
1213 history[gamePly] = st->key;
1215 // Update the necessary information
1216 if (st->epSquare != SQ_NONE)
1217 st->key ^= zobEp[st->epSquare];
1219 st->key ^= zobSideToMove;
1220 TT.prefetch(st->key);
1222 sideToMove = opposite_color(sideToMove);
1223 st->epSquare = SQ_NONE;
1225 st->pliesFromNull = 0;
1226 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1231 /// Position::undo_null_move() unmakes a "null move".
1233 void Position::undo_null_move() {
1236 assert(!is_check());
1238 // Restore information from the our backup StateInfo object
1239 StateInfo* backupSt = st->previous;
1240 st->key = backupSt->key;
1241 st->epSquare = backupSt->epSquare;
1242 st->value = backupSt->value;
1243 st->previous = backupSt->previous;
1244 st->pliesFromNull = backupSt->pliesFromNull;
1246 // Update the necessary information
1247 sideToMove = opposite_color(sideToMove);
1253 /// Position::see() is a static exchange evaluator: It tries to estimate the
1254 /// material gain or loss resulting from a move. There are three versions of
1255 /// this function: One which takes a destination square as input, one takes a
1256 /// move, and one which takes a 'from' and a 'to' square. The function does
1257 /// not yet understand promotions captures.
1259 int Position::see(Square to) const {
1261 assert(square_is_ok(to));
1262 return see(SQ_NONE, to);
1265 int Position::see(Move m) const {
1267 assert(move_is_ok(m));
1268 return see(move_from(m), move_to(m));
1271 int Position::see_sign(Move m) const {
1273 assert(move_is_ok(m));
1275 Square from = move_from(m);
1276 Square to = move_to(m);
1278 // Early return if SEE cannot be negative because capturing piece value
1279 // is not bigger then captured one.
1280 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1281 && type_of_piece_on(from) != KING)
1284 return see(from, to);
1287 int Position::see(Square from, Square to) const {
1290 static const int seeValues[18] = {
1291 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1292 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1293 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1294 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1298 Bitboard attackers, stmAttackers, b;
1300 assert(square_is_ok(from) || from == SQ_NONE);
1301 assert(square_is_ok(to));
1303 // Initialize colors
1304 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1305 Color them = opposite_color(us);
1307 // Initialize pieces
1308 Piece piece = piece_on(from);
1309 Piece capture = piece_on(to);
1310 Bitboard occ = occupied_squares();
1312 // King cannot be recaptured
1313 if (type_of_piece(piece) == KING)
1314 return seeValues[capture];
1316 // Handle en passant moves
1317 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1319 assert(capture == EMPTY);
1321 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1322 capture = piece_on(capQq);
1323 assert(type_of_piece_on(capQq) == PAWN);
1325 // Remove the captured pawn
1326 clear_bit(&occ, capQq);
1331 // Find all attackers to the destination square, with the moving piece
1332 // removed, but possibly an X-ray attacker added behind it.
1333 clear_bit(&occ, from);
1334 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1335 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1336 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1337 | (attacks_from<KING>(to) & pieces(KING))
1338 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1339 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1341 if (from != SQ_NONE)
1344 // If we don't have any attacker we are finished
1345 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1348 // Locate the least valuable attacker to the destination square
1349 // and use it to initialize from square.
1350 stmAttackers = attackers & pieces_of_color(us);
1352 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1355 from = first_1(stmAttackers & pieces(pt));
1356 piece = piece_on(from);
1359 // If the opponent has no attackers we are finished
1360 stmAttackers = attackers & pieces_of_color(them);
1362 return seeValues[capture];
1364 attackers &= occ; // Remove the moving piece
1366 // The destination square is defended, which makes things rather more
1367 // difficult to compute. We proceed by building up a "swap list" containing
1368 // the material gain or loss at each stop in a sequence of captures to the
1369 // destination square, where the sides alternately capture, and always
1370 // capture with the least valuable piece. After each capture, we look for
1371 // new X-ray attacks from behind the capturing piece.
1372 int lastCapturingPieceValue = seeValues[piece];
1373 int swapList[32], n = 1;
1377 swapList[0] = seeValues[capture];
1380 // Locate the least valuable attacker for the side to move. The loop
1381 // below looks like it is potentially infinite, but it isn't. We know
1382 // that the side to move still has at least one attacker left.
1383 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1386 // Remove the attacker we just found from the 'attackers' bitboard,
1387 // and scan for new X-ray attacks behind the attacker.
1388 b = stmAttackers & pieces(pt);
1389 occ ^= (b & (~b + 1));
1390 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1391 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1395 // Add the new entry to the swap list
1397 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1400 // Remember the value of the capturing piece, and change the side to move
1401 // before beginning the next iteration
1402 lastCapturingPieceValue = seeValues[pt];
1403 c = opposite_color(c);
1404 stmAttackers = attackers & pieces_of_color(c);
1406 // Stop after a king capture
1407 if (pt == KING && stmAttackers)
1410 swapList[n++] = QueenValueMidgame*10;
1413 } while (stmAttackers);
1415 // Having built the swap list, we negamax through it to find the best
1416 // achievable score from the point of view of the side to move
1418 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1424 /// Position::saveState() copies the content of the current state
1425 /// inside startState and makes st point to it. This is needed
1426 /// when the st pointee could become stale, as example because
1427 /// the caller is about to going out of scope.
1429 void Position::saveState() {
1433 st->previous = NULL; // as a safe guard
1437 /// Position::clear() erases the position object to a pristine state, with an
1438 /// empty board, white to move, and no castling rights.
1440 void Position::clear() {
1443 memset(st, 0, sizeof(StateInfo));
1444 st->epSquare = SQ_NONE;
1446 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1447 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1448 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1449 memset(index, 0, sizeof(int) * 64);
1451 for (int i = 0; i < 64; i++)
1454 for (int i = 0; i < 8; i++)
1455 for (int j = 0; j < 16; j++)
1456 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1460 initialKFile = FILE_E;
1461 initialKRFile = FILE_H;
1462 initialQRFile = FILE_A;
1466 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1467 /// UCI interface code, whenever a non-reversible move is made in a
1468 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1469 /// for the program to handle games of arbitrary length, as long as the GUI
1470 /// handles draws by the 50 move rule correctly.
1472 void Position::reset_game_ply() {
1478 /// Position::put_piece() puts a piece on the given square of the board,
1479 /// updating the board array, bitboards, and piece counts.
1481 void Position::put_piece(Piece p, Square s) {
1483 Color c = color_of_piece(p);
1484 PieceType pt = type_of_piece(p);
1487 index[s] = pieceCount[c][pt];
1488 pieceList[c][pt][index[s]] = s;
1490 set_bit(&(byTypeBB[pt]), s);
1491 set_bit(&(byColorBB[c]), s);
1492 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1494 pieceCount[c][pt]++;
1498 /// Position::allow_oo() gives the given side the right to castle kingside.
1499 /// Used when setting castling rights during parsing of FEN strings.
1501 void Position::allow_oo(Color c) {
1503 st->castleRights |= (1 + int(c));
1507 /// Position::allow_ooo() gives the given side the right to castle queenside.
1508 /// Used when setting castling rights during parsing of FEN strings.
1510 void Position::allow_ooo(Color c) {
1512 st->castleRights |= (4 + 4*int(c));
1516 /// Position::compute_key() computes the hash key of the position. The hash
1517 /// key is usually updated incrementally as moves are made and unmade, the
1518 /// compute_key() function is only used when a new position is set up, and
1519 /// to verify the correctness of the hash key when running in debug mode.
1521 Key Position::compute_key() const {
1523 Key result = Key(0ULL);
1525 for (Square s = SQ_A1; s <= SQ_H8; s++)
1526 if (square_is_occupied(s))
1527 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1529 if (ep_square() != SQ_NONE)
1530 result ^= zobEp[ep_square()];
1532 result ^= zobCastle[st->castleRights];
1533 if (side_to_move() == BLACK)
1534 result ^= zobSideToMove;
1540 /// Position::compute_pawn_key() computes the hash key of the position. The
1541 /// hash key is usually updated incrementally as moves are made and unmade,
1542 /// the compute_pawn_key() function is only used when a new position is set
1543 /// up, and to verify the correctness of the pawn hash key when running in
1546 Key Position::compute_pawn_key() const {
1548 Key result = Key(0ULL);
1552 for (Color c = WHITE; c <= BLACK; c++)
1554 b = pieces(PAWN, c);
1557 s = pop_1st_bit(&b);
1558 result ^= zobrist[c][PAWN][s];
1565 /// Position::compute_material_key() computes the hash key of the position.
1566 /// The hash key is usually updated incrementally as moves are made and unmade,
1567 /// the compute_material_key() function is only used when a new position is set
1568 /// up, and to verify the correctness of the material hash key when running in
1571 Key Position::compute_material_key() const {
1573 Key result = Key(0ULL);
1574 for (Color c = WHITE; c <= BLACK; c++)
1575 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1577 int count = piece_count(c, pt);
1578 for (int i = 0; i <= count; i++)
1579 result ^= zobMaterial[c][pt][i];
1585 /// Position::compute_value() compute the incremental scores for the middle
1586 /// game and the endgame. These functions are used to initialize the incremental
1587 /// scores when a new position is set up, and to verify that the scores are correctly
1588 /// updated by do_move and undo_move when the program is running in debug mode.
1589 Score Position::compute_value() const {
1591 Score result = make_score(0, 0);
1595 for (Color c = WHITE; c <= BLACK; c++)
1596 for (PieceType pt = PAWN; pt <= KING; pt++)
1601 s = pop_1st_bit(&b);
1602 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1603 result += pst(c, pt, s);
1607 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1612 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1613 /// game material score for the given side. Material scores are updated
1614 /// incrementally during the search, this function is only used while
1615 /// initializing a new Position object.
1617 Value Position::compute_non_pawn_material(Color c) const {
1619 Value result = Value(0);
1621 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1623 Bitboard b = pieces(pt, c);
1626 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1628 result += piece_value_midgame(pt);
1635 /// Position::is_draw() tests whether the position is drawn by material,
1636 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1637 /// must be done by the search.
1639 bool Position::is_draw() const {
1641 // Draw by material?
1643 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1646 // Draw by the 50 moves rule?
1647 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1650 // Draw by repetition?
1651 for (int i = 2; i < Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1652 if (history[gamePly - i] == st->key)
1659 /// Position::is_mate() returns true or false depending on whether the
1660 /// side to move is checkmated.
1662 bool Position::is_mate() const {
1664 MoveStack moves[256];
1665 return is_check() && (generate_moves(*this, moves, false) == moves);
1669 /// Position::has_mate_threat() tests whether a given color has a mate in one
1670 /// from the current position.
1672 bool Position::has_mate_threat(Color c) {
1675 Color stm = side_to_move();
1680 // If the input color is not equal to the side to move, do a null move
1684 MoveStack mlist[120];
1685 bool result = false;
1686 Bitboard pinned = pinned_pieces(sideToMove);
1688 // Generate pseudo-legal non-capture and capture check moves
1689 MoveStack* last = generate_non_capture_checks(*this, mlist);
1690 last = generate_captures(*this, last);
1692 // Loop through the moves, and see if one of them is mate
1693 for (MoveStack* cur = mlist; cur != last; cur++)
1695 Move move = cur->move;
1696 if (!pl_move_is_legal(move, pinned))
1706 // Undo null move, if necessary
1714 /// Position::init_zobrist() is a static member function which initializes the
1715 /// various arrays used to compute hash keys.
1717 void Position::init_zobrist() {
1719 for (int i = 0; i < 2; i++)
1720 for (int j = 0; j < 8; j++)
1721 for (int k = 0; k < 64; k++)
1722 zobrist[i][j][k] = Key(genrand_int64());
1724 for (int i = 0; i < 64; i++)
1725 zobEp[i] = Key(genrand_int64());
1727 for (int i = 0; i < 16; i++)
1728 zobCastle[i] = genrand_int64();
1730 zobSideToMove = genrand_int64();
1732 for (int i = 0; i < 2; i++)
1733 for (int j = 0; j < 8; j++)
1734 for (int k = 0; k < 16; k++)
1735 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1737 for (int i = 0; i < 16; i++)
1738 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1742 /// Position::init_piece_square_tables() initializes the piece square tables.
1743 /// This is a two-step operation: First, the white halves of the tables are
1744 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1745 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1746 /// Second, the black halves of the tables are initialized by mirroring
1747 /// and changing the sign of the corresponding white scores.
1749 void Position::init_piece_square_tables() {
1751 int r = get_option_value_int("Randomness"), i;
1752 for (Square s = SQ_A1; s <= SQ_H8; s++)
1753 for (Piece p = WP; p <= WK; p++)
1755 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1756 PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1759 for (Square s = SQ_A1; s <= SQ_H8; s++)
1760 for (Piece p = BP; p <= BK; p++)
1761 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1765 /// Position::flipped_copy() makes a copy of the input position, but with
1766 /// the white and black sides reversed. This is only useful for debugging,
1767 /// especially for finding evaluation symmetry bugs.
1769 void Position::flipped_copy(const Position& pos) {
1771 assert(pos.is_ok());
1776 for (Square s = SQ_A1; s <= SQ_H8; s++)
1777 if (!pos.square_is_empty(s))
1778 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1781 sideToMove = opposite_color(pos.side_to_move());
1784 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1785 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1786 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1787 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1789 initialKFile = pos.initialKFile;
1790 initialKRFile = pos.initialKRFile;
1791 initialQRFile = pos.initialQRFile;
1793 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1794 castleRightsMask[sq] = ALL_CASTLES;
1796 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1797 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1798 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1799 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1800 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1801 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1803 // En passant square
1804 if (pos.st->epSquare != SQ_NONE)
1805 st->epSquare = flip_square(pos.st->epSquare);
1811 st->key = compute_key();
1812 st->pawnKey = compute_pawn_key();
1813 st->materialKey = compute_material_key();
1815 // Incremental scores
1816 st->value = compute_value();
1819 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1820 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1826 /// Position::is_ok() performs some consitency checks for the position object.
1827 /// This is meant to be helpful when debugging.
1829 bool Position::is_ok(int* failedStep) const {
1831 // What features of the position should be verified?
1832 static const bool debugBitboards = false;
1833 static const bool debugKingCount = false;
1834 static const bool debugKingCapture = false;
1835 static const bool debugCheckerCount = false;
1836 static const bool debugKey = false;
1837 static const bool debugMaterialKey = false;
1838 static const bool debugPawnKey = false;
1839 static const bool debugIncrementalEval = false;
1840 static const bool debugNonPawnMaterial = false;
1841 static const bool debugPieceCounts = false;
1842 static const bool debugPieceList = false;
1844 if (failedStep) *failedStep = 1;
1847 if (!color_is_ok(side_to_move()))
1850 // Are the king squares in the position correct?
1851 if (failedStep) (*failedStep)++;
1852 if (piece_on(king_square(WHITE)) != WK)
1855 if (failedStep) (*failedStep)++;
1856 if (piece_on(king_square(BLACK)) != BK)
1860 if (failedStep) (*failedStep)++;
1861 if (!file_is_ok(initialKRFile))
1864 if (!file_is_ok(initialQRFile))
1867 // Do both sides have exactly one king?
1868 if (failedStep) (*failedStep)++;
1871 int kingCount[2] = {0, 0};
1872 for (Square s = SQ_A1; s <= SQ_H8; s++)
1873 if (type_of_piece_on(s) == KING)
1874 kingCount[color_of_piece_on(s)]++;
1876 if (kingCount[0] != 1 || kingCount[1] != 1)
1880 // Can the side to move capture the opponent's king?
1881 if (failedStep) (*failedStep)++;
1882 if (debugKingCapture)
1884 Color us = side_to_move();
1885 Color them = opposite_color(us);
1886 Square ksq = king_square(them);
1887 if (attackers_to(ksq) & pieces_of_color(us))
1891 // Is there more than 2 checkers?
1892 if (failedStep) (*failedStep)++;
1893 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1897 if (failedStep) (*failedStep)++;
1900 // The intersection of the white and black pieces must be empty
1901 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1904 // The union of the white and black pieces must be equal to all
1906 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1909 // Separate piece type bitboards must have empty intersections
1910 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1911 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1912 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1916 // En passant square OK?
1917 if (failedStep) (*failedStep)++;
1918 if (ep_square() != SQ_NONE)
1920 // The en passant square must be on rank 6, from the point of view of the
1922 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1927 if (failedStep) (*failedStep)++;
1928 if (debugKey && st->key != compute_key())
1931 // Pawn hash key OK?
1932 if (failedStep) (*failedStep)++;
1933 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1936 // Material hash key OK?
1937 if (failedStep) (*failedStep)++;
1938 if (debugMaterialKey && st->materialKey != compute_material_key())
1941 // Incremental eval OK?
1942 if (failedStep) (*failedStep)++;
1943 if (debugIncrementalEval && st->value != compute_value())
1946 // Non-pawn material OK?
1947 if (failedStep) (*failedStep)++;
1948 if (debugNonPawnMaterial)
1950 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1953 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1958 if (failedStep) (*failedStep)++;
1959 if (debugPieceCounts)
1960 for (Color c = WHITE; c <= BLACK; c++)
1961 for (PieceType pt = PAWN; pt <= KING; pt++)
1962 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
1965 if (failedStep) (*failedStep)++;
1968 for(Color c = WHITE; c <= BLACK; c++)
1969 for(PieceType pt = PAWN; pt <= KING; pt++)
1970 for(int i = 0; i < pieceCount[c][pt]; i++)
1972 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
1975 if (index[piece_list(c, pt, i)] != i)
1979 if (failedStep) *failedStep = 0;