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;
54 Key Position::zobExclusion;
56 Score Position::PieceSquareTable[16][64];
58 static bool RequestPending = false;
63 CheckInfo::CheckInfo(const Position& pos) {
65 Color us = pos.side_to_move();
66 Color them = opposite_color(us);
68 ksq = pos.king_square(them);
69 dcCandidates = pos.discovered_check_candidates(us);
71 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
72 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
73 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
74 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
75 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
76 checkSq[KING] = EmptyBoardBB;
80 /// Position c'tors. Here we always create a slower but safer copy of
81 /// the original position or the FEN string, we want the new born Position
82 /// object do not depend on any external data. Instead if we know what we
83 /// are doing and we need speed we can create a position with default
84 /// c'tor Position() and then use just fast_copy().
86 Position::Position() {}
88 Position::Position(const Position& pos) {
91 detach(); // Always detach() in copy c'tor to avoid surprises
94 Position::Position(const string& fen) {
100 /// Position::fast_copy() creates a partial copy of the given position,
101 /// only data that changes with a do_move() / undo_move() cycle is copied,
102 /// in particular for stateInfo are copied only the pointers, so that the
103 /// actual data remains stored in the parent Position. This is not a problem
104 /// if the parent Position is known not to be destroyed while we are still alive,
105 /// as is the common case, see detach() otherwise.
107 void Position::fast_copy(const Position& pos) {
109 memcpy(this, &pos, sizeof(Position));
113 /// Position::detach() copies the content of the current state and castling
114 /// masks inside the position itself. This is needed when the st pointee could
115 /// become stale, as example because the caller is about to going out of scope.
117 void Position::detach() {
121 st->previous = NULL; // as a safe guard
125 /// Position::from_fen() initializes the position object with the given FEN
126 /// string. This function is not very robust - make sure that input FENs are
127 /// correct (this is assumed to be the responsibility of the GUI).
129 void Position::from_fen(const string& fen) {
131 static const string pieceLetters = "KQRBNPkqrbnp";
132 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
140 for ( ; fen[i] != ' '; i++)
144 // Skip the given number of files
145 file += (fen[i] - '1' + 1);
148 else if (fen[i] == '/')
154 size_t idx = pieceLetters.find(fen[i]);
155 if (idx == string::npos)
157 std::cout << "Error in FEN at character " << i << std::endl;
160 Square square = make_square(file, rank);
161 put_piece(pieces[idx], square);
167 if (fen[i] != 'w' && fen[i] != 'b')
169 std::cout << "Error in FEN at character " << i << std::endl;
172 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
178 std::cout << "Error in FEN at character " << i << std::endl;
183 while (strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
189 else if (fen[i] == 'K') allow_oo(WHITE);
190 else if (fen[i] == 'Q') allow_ooo(WHITE);
191 else if (fen[i] == 'k') allow_oo(BLACK);
192 else if (fen[i] == 'q') allow_ooo(BLACK);
193 else if (fen[i] >= 'A' && fen[i] <= 'H') {
194 File rookFile, kingFile = FILE_NONE;
195 for (Square square = SQ_B1; square <= SQ_G1; square++)
196 if (piece_on(square) == WK)
197 kingFile = square_file(square);
198 if (kingFile == FILE_NONE) {
199 std::cout << "Error in FEN at character " << i << std::endl;
202 initialKFile = kingFile;
203 rookFile = File(fen[i] - 'A') + FILE_A;
204 if (rookFile < initialKFile) {
206 initialQRFile = rookFile;
210 initialKRFile = rookFile;
213 else if (fen[i] >= 'a' && fen[i] <= 'h') {
214 File rookFile, kingFile = FILE_NONE;
215 for (Square square = SQ_B8; square <= SQ_G8; square++)
216 if (piece_on(square) == BK)
217 kingFile = square_file(square);
218 if (kingFile == FILE_NONE) {
219 std::cout << "Error in FEN at character " << i << std::endl;
222 initialKFile = kingFile;
223 rookFile = File(fen[i] - 'a') + FILE_A;
224 if (rookFile < initialKFile) {
226 initialQRFile = rookFile;
230 initialKRFile = rookFile;
234 std::cout << "Error in FEN at character " << i << std::endl;
241 while (fen[i] == ' ')
244 // En passant square -- ignore if no capture is possible
245 if ( i <= fen.length() - 2
246 && (fen[i] >= 'a' && fen[i] <= 'h')
247 && (fen[i+1] == '3' || fen[i+1] == '6'))
249 Square fenEpSquare = square_from_string(fen.substr(i, 2));
250 Color them = opposite_color(sideToMove);
251 if (attacks_from<PAWN>(fenEpSquare, them) & this->pieces(PAWN, sideToMove))
252 st->epSquare = square_from_string(fen.substr(i, 2));
255 // Various initialisation
256 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
257 castleRightsMask[sq] = ALL_CASTLES;
259 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
260 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
261 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
262 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
263 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
264 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
268 st->key = compute_key();
269 st->pawnKey = compute_pawn_key();
270 st->materialKey = compute_material_key();
271 st->value = compute_value();
272 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
273 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
277 /// Position::to_fen() converts the position object to a FEN string. This is
278 /// probably only useful for debugging.
280 const string Position::to_fen() const {
282 static const string pieceLetters = " PNBRQK pnbrqk";
286 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
289 for (File file = FILE_A; file <= FILE_H; file++)
291 Square sq = make_square(file, rank);
292 if (!square_is_occupied(sq))
298 fen += (char)skip + '0';
301 fen += pieceLetters[piece_on(sq)];
304 fen += (char)skip + '0';
306 fen += (rank > RANK_1 ? '/' : ' ');
308 fen += (sideToMove == WHITE ? "w " : "b ");
309 if (st->castleRights != NO_CASTLES)
311 if (initialKFile == FILE_E && initialQRFile == FILE_A && initialKRFile == FILE_H)
313 if (can_castle_kingside(WHITE)) fen += 'K';
314 if (can_castle_queenside(WHITE)) fen += 'Q';
315 if (can_castle_kingside(BLACK)) fen += 'k';
316 if (can_castle_queenside(BLACK)) fen += 'q';
320 if (can_castle_kingside(WHITE))
321 fen += char(toupper(file_to_char(initialKRFile)));
322 if (can_castle_queenside(WHITE))
323 fen += char(toupper(file_to_char(initialQRFile)));
324 if (can_castle_kingside(BLACK))
325 fen += file_to_char(initialKRFile);
326 if (can_castle_queenside(BLACK))
327 fen += file_to_char(initialQRFile);
333 if (ep_square() != SQ_NONE)
334 fen += square_to_string(ep_square());
342 /// Position::print() prints an ASCII representation of the position to
343 /// the standard output. If a move is given then also the san is print.
345 void Position::print(Move m) const {
347 static const string pieceLetters = " PNBRQK PNBRQK .";
349 // Check for reentrancy, as example when called from inside
350 // MovePicker that is used also here in move_to_san()
354 RequestPending = true;
356 std::cout << std::endl;
360 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
361 std::cout << "Move is: " << col << move_to_san(p, m) << std::endl;
363 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
365 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
366 for (File file = FILE_A; file <= FILE_H; file++)
368 Square sq = make_square(file, rank);
369 Piece piece = piece_on(sq);
370 if (piece == EMPTY && square_color(sq) == WHITE)
373 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
374 std::cout << '|' << col << pieceLetters[piece] << col;
376 std::cout << '|' << std::endl;
378 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
379 << "Fen is: " << to_fen() << std::endl
380 << "Key is: " << st->key << std::endl;
382 RequestPending = false;
386 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
387 /// king) pieces for the given color and for the given pinner type. Or, when
388 /// template parameter FindPinned is false, the pieces of the given color
389 /// candidate for a discovery check against the enemy king.
390 /// Bitboard checkersBB must be already updated when looking for pinners.
392 template<bool FindPinned>
393 Bitboard Position::hidden_checkers(Color c) const {
395 Bitboard result = EmptyBoardBB;
396 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
398 // Pinned pieces protect our king, dicovery checks attack
400 Square ksq = king_square(FindPinned ? c : opposite_color(c));
402 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
403 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
405 if (FindPinned && pinners)
406 pinners &= ~st->checkersBB;
410 Square s = pop_1st_bit(&pinners);
411 Bitboard b = squares_between(s, ksq) & occupied_squares();
415 if ( !(b & (b - 1)) // Only one bit set?
416 && (b & pieces_of_color(c))) // Is an our piece?
423 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
424 /// king) pieces for the given color. Note that checkersBB bitboard must
425 /// be already updated.
427 Bitboard Position::pinned_pieces(Color c) const {
429 return hidden_checkers<true>(c);
433 /// Position:discovered_check_candidates() returns a bitboard containing all
434 /// pieces for the given side which are candidates for giving a discovered
435 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
436 /// to be already updated.
438 Bitboard Position::discovered_check_candidates(Color c) const {
440 return hidden_checkers<false>(c);
443 /// Position::attackers_to() computes a bitboard containing all pieces which
444 /// attacks a given square.
446 Bitboard Position::attackers_to(Square s) const {
448 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
449 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
450 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
451 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
452 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
453 | (attacks_from<KING>(s) & pieces(KING));
456 /// Position::attacks_from() computes a bitboard of all attacks
457 /// of a given piece put in a given square.
459 Bitboard Position::attacks_from(Piece p, Square s) const {
461 assert(square_is_ok(s));
465 case WP: return attacks_from<PAWN>(s, WHITE);
466 case BP: return attacks_from<PAWN>(s, BLACK);
467 case WN: case BN: return attacks_from<KNIGHT>(s);
468 case WB: case BB: return attacks_from<BISHOP>(s);
469 case WR: case BR: return attacks_from<ROOK>(s);
470 case WQ: case BQ: return attacks_from<QUEEN>(s);
471 case WK: case BK: return attacks_from<KING>(s);
478 /// Position::move_attacks_square() tests whether a move from the current
479 /// position attacks a given square.
481 bool Position::move_attacks_square(Move m, Square s) const {
483 assert(move_is_ok(m));
484 assert(square_is_ok(s));
486 Square f = move_from(m), t = move_to(m);
488 assert(square_is_occupied(f));
490 if (bit_is_set(attacks_from(piece_on(f), t), s))
493 // Move the piece and scan for X-ray attacks behind it
494 Bitboard occ = occupied_squares();
495 Color us = color_of_piece_on(f);
498 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
499 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
501 // If we have attacks we need to verify that are caused by our move
502 // and are not already existent ones.
503 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
507 /// Position::find_checkers() computes the checkersBB bitboard, which
508 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
509 /// currently works by calling Position::attackers_to, which is probably
510 /// inefficient. Consider rewriting this function to use the last move
511 /// played, like in non-bitboard versions of Glaurung.
513 void Position::find_checkers() {
515 Color us = side_to_move();
516 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
520 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
522 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
525 assert(move_is_ok(m));
526 assert(pinned == pinned_pieces(side_to_move()));
528 // Castling moves are checked for legality during move generation.
529 if (move_is_castle(m))
532 Color us = side_to_move();
533 Square from = move_from(m);
535 assert(color_of_piece_on(from) == us);
536 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
538 // En passant captures are a tricky special case. Because they are
539 // rather uncommon, we do it simply by testing whether the king is attacked
540 // after the move is made
543 Color them = opposite_color(us);
544 Square to = move_to(m);
545 Square capsq = make_square(square_file(to), square_rank(from));
546 Bitboard b = occupied_squares();
547 Square ksq = king_square(us);
549 assert(to == ep_square());
550 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
551 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
552 assert(piece_on(to) == EMPTY);
555 clear_bit(&b, capsq);
558 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
559 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
562 // If the moving piece is a king, check whether the destination
563 // square is attacked by the opponent.
564 if (type_of_piece_on(from) == KING)
565 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
567 // A non-king move is legal if and only if it is not pinned or it
568 // is moving along the ray towards or away from the king.
570 || !bit_is_set(pinned, from)
571 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
575 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
577 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
581 Color us = side_to_move();
582 Square from = move_from(m);
583 Square to = move_to(m);
585 // King moves and en-passant captures are verified in pl_move_is_legal()
586 if (type_of_piece_on(from) == KING || move_is_ep(m))
587 return pl_move_is_legal(m, pinned);
589 Bitboard target = checkers();
590 Square checksq = pop_1st_bit(&target);
592 if (target) // double check ?
595 // Our move must be a blocking evasion or a capture of the checking piece
596 target = squares_between(checksq, king_square(us)) | checkers();
597 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
601 /// Position::move_is_check() tests whether a pseudo-legal move is a check
603 bool Position::move_is_check(Move m) const {
605 return move_is_check(m, CheckInfo(*this));
608 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
611 assert(move_is_ok(m));
612 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
613 assert(color_of_piece_on(move_from(m)) == side_to_move());
614 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
616 Square from = move_from(m);
617 Square to = move_to(m);
618 PieceType pt = type_of_piece_on(from);
621 if (bit_is_set(ci.checkSq[pt], to))
625 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
627 // For pawn and king moves we need to verify also direction
628 if ( (pt != PAWN && pt != KING)
629 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
633 // Can we skip the ugly special cases ?
634 if (!move_is_special(m))
637 Color us = side_to_move();
638 Bitboard b = occupied_squares();
640 // Promotion with check ?
641 if (move_is_promotion(m))
645 switch (move_promotion_piece(m))
648 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
650 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
652 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
654 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
660 // En passant capture with check? We have already handled the case
661 // of direct checks and ordinary discovered check, the only case we
662 // need to handle is the unusual case of a discovered check through the
666 Square capsq = make_square(square_file(to), square_rank(from));
668 clear_bit(&b, capsq);
670 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
671 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
674 // Castling with check ?
675 if (move_is_castle(m))
677 Square kfrom, kto, rfrom, rto;
683 kto = relative_square(us, SQ_G1);
684 rto = relative_square(us, SQ_F1);
686 kto = relative_square(us, SQ_C1);
687 rto = relative_square(us, SQ_D1);
689 clear_bit(&b, kfrom);
690 clear_bit(&b, rfrom);
693 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
700 /// Position::do_move() makes a move, and saves all information necessary
701 /// to a StateInfo object. The move is assumed to be legal.
702 /// Pseudo-legal moves should be filtered out before this function is called.
704 void Position::do_move(Move m, StateInfo& newSt) {
707 do_move(m, newSt, ci, move_is_check(m, ci));
710 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
713 assert(move_is_ok(m));
715 Bitboard key = st->key;
717 // Copy some fields of old state to our new StateInfo object except the
718 // ones which are recalculated from scratch anyway, then switch our state
719 // pointer to point to the new, ready to be updated, state.
720 struct ReducedStateInfo {
721 Key pawnKey, materialKey;
722 int castleRights, rule50, pliesFromNull;
728 memcpy(&newSt, st, sizeof(ReducedStateInfo));
732 // Save the current key to the history[] array, in order to be able to
733 // detect repetition draws.
734 history[gamePly] = key;
737 // Update side to move
738 key ^= zobSideToMove;
740 // Increment the 50 moves rule draw counter. Resetting it to zero in the
741 // case of non-reversible moves is taken care of later.
745 if (move_is_castle(m))
752 Color us = side_to_move();
753 Color them = opposite_color(us);
754 Square from = move_from(m);
755 Square to = move_to(m);
756 bool ep = move_is_ep(m);
757 bool pm = move_is_promotion(m);
759 Piece piece = piece_on(from);
760 PieceType pt = type_of_piece(piece);
761 PieceType capture = ep ? PAWN : type_of_piece_on(to);
763 assert(color_of_piece_on(from) == us);
764 assert(color_of_piece_on(to) == them || square_is_empty(to));
765 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
766 assert(!pm || relative_rank(us, to) == RANK_8);
769 do_capture_move(key, capture, them, to, ep);
772 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
774 // Reset en passant square
775 if (st->epSquare != SQ_NONE)
777 key ^= zobEp[st->epSquare];
778 st->epSquare = SQ_NONE;
781 // Update castle rights, try to shortcut a common case
782 int cm = castleRightsMask[from] & castleRightsMask[to];
783 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
785 key ^= zobCastle[st->castleRights];
786 st->castleRights &= castleRightsMask[from];
787 st->castleRights &= castleRightsMask[to];
788 key ^= zobCastle[st->castleRights];
791 // Prefetch TT access as soon as we know key is updated
795 Bitboard move_bb = make_move_bb(from, to);
796 do_move_bb(&(byColorBB[us]), move_bb);
797 do_move_bb(&(byTypeBB[pt]), move_bb);
798 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
800 board[to] = board[from];
803 // Update piece lists, note that index[from] is not updated and
804 // becomes stale. This works as long as index[] is accessed just
805 // by known occupied squares.
806 index[to] = index[from];
807 pieceList[us][pt][index[to]] = to;
809 // If the moving piece was a pawn do some special extra work
812 // Reset rule 50 draw counter
815 // Update pawn hash key
816 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
818 // Set en passant square, only if moved pawn can be captured
819 if ((to ^ from) == 16)
821 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
823 st->epSquare = Square((int(from) + int(to)) / 2);
824 key ^= zobEp[st->epSquare];
829 // Update incremental scores
830 st->value += pst_delta(piece, from, to);
833 st->capture = capture;
835 if (pm) // promotion ?
837 PieceType promotion = move_promotion_piece(m);
839 assert(promotion >= KNIGHT && promotion <= QUEEN);
841 // Insert promoted piece instead of pawn
842 clear_bit(&(byTypeBB[PAWN]), to);
843 set_bit(&(byTypeBB[promotion]), to);
844 board[to] = piece_of_color_and_type(us, promotion);
846 // Update material key
847 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
848 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
850 // Update piece counts
851 pieceCount[us][PAWN]--;
852 pieceCount[us][promotion]++;
854 // Update piece lists, move the last pawn at index[to] position
855 // and shrink the list. Add a new promotion piece to the list.
856 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
857 index[lastPawnSquare] = index[to];
858 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
859 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
860 index[to] = pieceCount[us][promotion] - 1;
861 pieceList[us][promotion][index[to]] = to;
863 // Partially revert hash keys update
864 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
865 st->pawnKey ^= zobrist[us][PAWN][to];
867 // Partially revert and update incremental scores
868 st->value -= pst(us, PAWN, to);
869 st->value += pst(us, promotion, to);
872 st->npMaterial[us] += piece_value_midgame(promotion);
875 // Update the key with the final value
878 // Update checkers bitboard, piece must be already moved
879 st->checkersBB = EmptyBoardBB;
884 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
888 if (bit_is_set(ci.checkSq[pt], to))
889 st->checkersBB = SetMaskBB[to];
892 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
895 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
898 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
904 sideToMove = opposite_color(sideToMove);
905 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
911 /// Position::do_capture_move() is a private method used to update captured
912 /// piece info. It is called from the main Position::do_move function.
914 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
916 assert(capture != KING);
920 if (ep) // en passant ?
922 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
924 assert(to == st->epSquare);
925 assert(relative_rank(opposite_color(them), to) == RANK_6);
926 assert(piece_on(to) == EMPTY);
927 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
929 board[capsq] = EMPTY;
932 // Remove captured piece
933 clear_bit(&(byColorBB[them]), capsq);
934 clear_bit(&(byTypeBB[capture]), capsq);
935 clear_bit(&(byTypeBB[0]), capsq);
938 key ^= zobrist[them][capture][capsq];
940 // Update incremental scores
941 st->value -= pst(them, capture, capsq);
943 // If the captured piece was a pawn, update pawn hash key,
944 // otherwise update non-pawn material.
946 st->pawnKey ^= zobrist[them][PAWN][capsq];
948 st->npMaterial[them] -= piece_value_midgame(capture);
950 // Update material hash key
951 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
953 // Update piece count
954 pieceCount[them][capture]--;
956 // Update piece list, move the last piece at index[capsq] position
958 // WARNING: This is a not perfectly revresible operation. When we
959 // will reinsert the captured piece in undo_move() we will put it
960 // at the end of the list and not in its original place, it means
961 // index[] and pieceList[] are not guaranteed to be invariant to a
962 // do_move() + undo_move() sequence.
963 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
964 index[lastPieceSquare] = index[capsq];
965 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
966 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
968 // Reset rule 50 counter
973 /// Position::do_castle_move() is a private method used to make a castling
974 /// move. It is called from the main Position::do_move function. Note that
975 /// castling moves are encoded as "king captures friendly rook" moves, for
976 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
978 void Position::do_castle_move(Move m) {
980 assert(move_is_ok(m));
981 assert(move_is_castle(m));
983 Color us = side_to_move();
984 Color them = opposite_color(us);
986 // Reset capture field
987 st->capture = NO_PIECE_TYPE;
989 // Find source squares for king and rook
990 Square kfrom = move_from(m);
991 Square rfrom = move_to(m); // HACK: See comment at beginning of function
994 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
995 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
997 // Find destination squares for king and rook
998 if (rfrom > kfrom) // O-O
1000 kto = relative_square(us, SQ_G1);
1001 rto = relative_square(us, SQ_F1);
1003 kto = relative_square(us, SQ_C1);
1004 rto = relative_square(us, SQ_D1);
1007 // Remove pieces from source squares:
1008 clear_bit(&(byColorBB[us]), kfrom);
1009 clear_bit(&(byTypeBB[KING]), kfrom);
1010 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1011 clear_bit(&(byColorBB[us]), rfrom);
1012 clear_bit(&(byTypeBB[ROOK]), rfrom);
1013 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1015 // Put pieces on destination squares:
1016 set_bit(&(byColorBB[us]), kto);
1017 set_bit(&(byTypeBB[KING]), kto);
1018 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1019 set_bit(&(byColorBB[us]), rto);
1020 set_bit(&(byTypeBB[ROOK]), rto);
1021 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1023 // Update board array
1024 Piece king = piece_of_color_and_type(us, KING);
1025 Piece rook = piece_of_color_and_type(us, ROOK);
1026 board[kfrom] = board[rfrom] = EMPTY;
1030 // Update piece lists
1031 pieceList[us][KING][index[kfrom]] = kto;
1032 pieceList[us][ROOK][index[rfrom]] = rto;
1033 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1034 index[kto] = index[kfrom];
1037 // Update incremental scores
1038 st->value += pst_delta(king, kfrom, kto);
1039 st->value += pst_delta(rook, rfrom, rto);
1042 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1043 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1045 // Clear en passant square
1046 if (st->epSquare != SQ_NONE)
1048 st->key ^= zobEp[st->epSquare];
1049 st->epSquare = SQ_NONE;
1052 // Update castling rights
1053 st->key ^= zobCastle[st->castleRights];
1054 st->castleRights &= castleRightsMask[kfrom];
1055 st->key ^= zobCastle[st->castleRights];
1057 // Reset rule 50 counter
1060 // Update checkers BB
1061 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1064 sideToMove = opposite_color(sideToMove);
1065 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1071 /// Position::undo_move() unmakes a move. When it returns, the position should
1072 /// be restored to exactly the same state as before the move was made.
1074 void Position::undo_move(Move m) {
1077 assert(move_is_ok(m));
1080 sideToMove = opposite_color(sideToMove);
1082 if (move_is_castle(m))
1084 undo_castle_move(m);
1088 Color us = side_to_move();
1089 Color them = opposite_color(us);
1090 Square from = move_from(m);
1091 Square to = move_to(m);
1092 bool ep = move_is_ep(m);
1093 bool pm = move_is_promotion(m);
1095 PieceType pt = type_of_piece_on(to);
1097 assert(square_is_empty(from));
1098 assert(color_of_piece_on(to) == us);
1099 assert(!pm || relative_rank(us, to) == RANK_8);
1100 assert(!ep || to == st->previous->epSquare);
1101 assert(!ep || relative_rank(us, to) == RANK_6);
1102 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1104 if (pm) // promotion ?
1106 PieceType promotion = move_promotion_piece(m);
1109 assert(promotion >= KNIGHT && promotion <= QUEEN);
1110 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1112 // Replace promoted piece with a pawn
1113 clear_bit(&(byTypeBB[promotion]), to);
1114 set_bit(&(byTypeBB[PAWN]), to);
1116 // Update piece counts
1117 pieceCount[us][promotion]--;
1118 pieceCount[us][PAWN]++;
1120 // Update piece list replacing promotion piece with a pawn
1121 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1122 index[lastPromotionSquare] = index[to];
1123 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1124 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1125 index[to] = pieceCount[us][PAWN] - 1;
1126 pieceList[us][PAWN][index[to]] = to;
1130 // Put the piece back at the source square
1131 Bitboard move_bb = make_move_bb(to, from);
1132 do_move_bb(&(byColorBB[us]), move_bb);
1133 do_move_bb(&(byTypeBB[pt]), move_bb);
1134 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1136 board[from] = piece_of_color_and_type(us, pt);
1139 // Update piece list
1140 index[from] = index[to];
1141 pieceList[us][pt][index[from]] = from;
1148 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1150 assert(st->capture != KING);
1151 assert(!ep || square_is_empty(capsq));
1153 // Restore the captured piece
1154 set_bit(&(byColorBB[them]), capsq);
1155 set_bit(&(byTypeBB[st->capture]), capsq);
1156 set_bit(&(byTypeBB[0]), capsq);
1158 board[capsq] = piece_of_color_and_type(them, st->capture);
1160 // Update piece count
1161 pieceCount[them][st->capture]++;
1163 // Update piece list, add a new captured piece in capsq square
1164 index[capsq] = pieceCount[them][st->capture] - 1;
1165 pieceList[them][st->capture][index[capsq]] = capsq;
1168 // Finally point our state pointer back to the previous state
1175 /// Position::undo_castle_move() is a private method used to unmake a castling
1176 /// move. It is called from the main Position::undo_move function. Note that
1177 /// castling moves are encoded as "king captures friendly rook" moves, for
1178 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1180 void Position::undo_castle_move(Move m) {
1182 assert(move_is_ok(m));
1183 assert(move_is_castle(m));
1185 // When we have arrived here, some work has already been done by
1186 // Position::undo_move. In particular, the side to move has been switched,
1187 // so the code below is correct.
1188 Color us = side_to_move();
1190 // Find source squares for king and rook
1191 Square kfrom = move_from(m);
1192 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1195 // Find destination squares for king and rook
1196 if (rfrom > kfrom) // O-O
1198 kto = relative_square(us, SQ_G1);
1199 rto = relative_square(us, SQ_F1);
1201 kto = relative_square(us, SQ_C1);
1202 rto = relative_square(us, SQ_D1);
1205 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1206 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1208 // Remove pieces from destination squares:
1209 clear_bit(&(byColorBB[us]), kto);
1210 clear_bit(&(byTypeBB[KING]), kto);
1211 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1212 clear_bit(&(byColorBB[us]), rto);
1213 clear_bit(&(byTypeBB[ROOK]), rto);
1214 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1216 // Put pieces on source squares:
1217 set_bit(&(byColorBB[us]), kfrom);
1218 set_bit(&(byTypeBB[KING]), kfrom);
1219 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1220 set_bit(&(byColorBB[us]), rfrom);
1221 set_bit(&(byTypeBB[ROOK]), rfrom);
1222 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1225 board[rto] = board[kto] = EMPTY;
1226 board[rfrom] = piece_of_color_and_type(us, ROOK);
1227 board[kfrom] = piece_of_color_and_type(us, KING);
1229 // Update piece lists
1230 pieceList[us][KING][index[kto]] = kfrom;
1231 pieceList[us][ROOK][index[rto]] = rfrom;
1232 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1233 index[kfrom] = index[kto];
1236 // Finally point our state pointer back to the previous state
1243 /// Position::do_null_move makes() a "null move": It switches the side to move
1244 /// and updates the hash key without executing any move on the board.
1246 void Position::do_null_move(StateInfo& backupSt) {
1249 assert(!is_check());
1251 // Back up the information necessary to undo the null move to the supplied
1252 // StateInfo object.
1253 // Note that differently from normal case here backupSt is actually used as
1254 // a backup storage not as a new state to be used.
1255 backupSt.key = st->key;
1256 backupSt.epSquare = st->epSquare;
1257 backupSt.value = st->value;
1258 backupSt.previous = st->previous;
1259 backupSt.pliesFromNull = st->pliesFromNull;
1260 st->previous = &backupSt;
1262 // Save the current key to the history[] array, in order to be able to
1263 // detect repetition draws.
1264 history[gamePly] = st->key;
1266 // Update the necessary information
1267 if (st->epSquare != SQ_NONE)
1268 st->key ^= zobEp[st->epSquare];
1270 st->key ^= zobSideToMove;
1271 TT.prefetch(st->key);
1273 sideToMove = opposite_color(sideToMove);
1274 st->epSquare = SQ_NONE;
1276 st->pliesFromNull = 0;
1277 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1282 /// Position::undo_null_move() unmakes a "null move".
1284 void Position::undo_null_move() {
1287 assert(!is_check());
1289 // Restore information from the our backup StateInfo object
1290 StateInfo* backupSt = st->previous;
1291 st->key = backupSt->key;
1292 st->epSquare = backupSt->epSquare;
1293 st->value = backupSt->value;
1294 st->previous = backupSt->previous;
1295 st->pliesFromNull = backupSt->pliesFromNull;
1297 // Update the necessary information
1298 sideToMove = opposite_color(sideToMove);
1305 PieceType Position::captured_piece() const {
1309 /// Position::see() is a static exchange evaluator: It tries to estimate the
1310 /// material gain or loss resulting from a move. There are three versions of
1311 /// this function: One which takes a destination square as input, one takes a
1312 /// move, and one which takes a 'from' and a 'to' square. The function does
1313 /// not yet understand promotions captures.
1315 int Position::see(Square to) const {
1317 assert(square_is_ok(to));
1318 return see(SQ_NONE, to);
1321 int Position::see(Move m) const {
1323 assert(move_is_ok(m));
1324 return see(move_from(m), move_to(m));
1327 int Position::see_sign(Move m) const {
1329 assert(move_is_ok(m));
1331 Square from = move_from(m);
1332 Square to = move_to(m);
1334 // Early return if SEE cannot be negative because capturing piece value
1335 // is not bigger then captured one.
1336 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1337 && type_of_piece_on(from) != KING)
1340 return see(from, to);
1343 int Position::see(Square from, Square to) const {
1346 static const int seeValues[18] = {
1347 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1348 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1349 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1350 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1354 Bitboard attackers, stmAttackers, b;
1356 assert(square_is_ok(from) || from == SQ_NONE);
1357 assert(square_is_ok(to));
1359 // Initialize colors
1360 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1361 Color them = opposite_color(us);
1363 // Initialize pieces
1364 Piece piece = piece_on(from);
1365 Piece capture = piece_on(to);
1366 Bitboard occ = occupied_squares();
1368 // King cannot be recaptured
1369 if (type_of_piece(piece) == KING)
1370 return seeValues[capture];
1372 // Handle en passant moves
1373 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1375 assert(capture == EMPTY);
1377 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1378 capture = piece_on(capQq);
1379 assert(type_of_piece_on(capQq) == PAWN);
1381 // Remove the captured pawn
1382 clear_bit(&occ, capQq);
1387 // Find all attackers to the destination square, with the moving piece
1388 // removed, but possibly an X-ray attacker added behind it.
1389 clear_bit(&occ, from);
1390 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1391 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1392 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1393 | (attacks_from<KING>(to) & pieces(KING))
1394 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1395 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1397 if (from != SQ_NONE)
1400 // If we don't have any attacker we are finished
1401 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1404 // Locate the least valuable attacker to the destination square
1405 // and use it to initialize from square.
1406 stmAttackers = attackers & pieces_of_color(us);
1408 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1411 from = first_1(stmAttackers & pieces(pt));
1412 piece = piece_on(from);
1415 // If the opponent has no attackers we are finished
1416 stmAttackers = attackers & pieces_of_color(them);
1418 return seeValues[capture];
1420 attackers &= occ; // Remove the moving piece
1422 // The destination square is defended, which makes things rather more
1423 // difficult to compute. We proceed by building up a "swap list" containing
1424 // the material gain or loss at each stop in a sequence of captures to the
1425 // destination square, where the sides alternately capture, and always
1426 // capture with the least valuable piece. After each capture, we look for
1427 // new X-ray attacks from behind the capturing piece.
1428 int lastCapturingPieceValue = seeValues[piece];
1429 int swapList[32], n = 1;
1433 swapList[0] = seeValues[capture];
1436 // Locate the least valuable attacker for the side to move. The loop
1437 // below looks like it is potentially infinite, but it isn't. We know
1438 // that the side to move still has at least one attacker left.
1439 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1442 // Remove the attacker we just found from the 'attackers' bitboard,
1443 // and scan for new X-ray attacks behind the attacker.
1444 b = stmAttackers & pieces(pt);
1445 occ ^= (b & (~b + 1));
1446 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1447 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1451 // Add the new entry to the swap list
1453 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1456 // Remember the value of the capturing piece, and change the side to move
1457 // before beginning the next iteration
1458 lastCapturingPieceValue = seeValues[pt];
1459 c = opposite_color(c);
1460 stmAttackers = attackers & pieces_of_color(c);
1462 // Stop after a king capture
1463 if (pt == KING && stmAttackers)
1466 swapList[n++] = QueenValueMidgame*10;
1469 } while (stmAttackers);
1471 // Having built the swap list, we negamax through it to find the best
1472 // achievable score from the point of view of the side to move
1474 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1480 /// Position::clear() erases the position object to a pristine state, with an
1481 /// empty board, white to move, and no castling rights.
1483 void Position::clear() {
1486 memset(st, 0, sizeof(StateInfo));
1487 st->epSquare = SQ_NONE;
1489 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1490 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1491 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1492 memset(index, 0, sizeof(int) * 64);
1494 for (int i = 0; i < 64; i++)
1497 for (int i = 0; i < 8; i++)
1498 for (int j = 0; j < 16; j++)
1499 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1503 initialKFile = FILE_E;
1504 initialKRFile = FILE_H;
1505 initialQRFile = FILE_A;
1509 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1510 /// UCI interface code, whenever a non-reversible move is made in a
1511 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1512 /// for the program to handle games of arbitrary length, as long as the GUI
1513 /// handles draws by the 50 move rule correctly.
1515 void Position::reset_game_ply() {
1521 /// Position::put_piece() puts a piece on the given square of the board,
1522 /// updating the board array, bitboards, and piece counts.
1524 void Position::put_piece(Piece p, Square s) {
1526 Color c = color_of_piece(p);
1527 PieceType pt = type_of_piece(p);
1530 index[s] = pieceCount[c][pt];
1531 pieceList[c][pt][index[s]] = s;
1533 set_bit(&(byTypeBB[pt]), s);
1534 set_bit(&(byColorBB[c]), s);
1535 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1537 pieceCount[c][pt]++;
1541 /// Position::allow_oo() gives the given side the right to castle kingside.
1542 /// Used when setting castling rights during parsing of FEN strings.
1544 void Position::allow_oo(Color c) {
1546 st->castleRights |= (1 + int(c));
1550 /// Position::allow_ooo() gives the given side the right to castle queenside.
1551 /// Used when setting castling rights during parsing of FEN strings.
1553 void Position::allow_ooo(Color c) {
1555 st->castleRights |= (4 + 4*int(c));
1559 /// Position::compute_key() computes the hash key of the position. The hash
1560 /// key is usually updated incrementally as moves are made and unmade, the
1561 /// compute_key() function is only used when a new position is set up, and
1562 /// to verify the correctness of the hash key when running in debug mode.
1564 Key Position::compute_key() const {
1566 Key result = Key(0ULL);
1568 for (Square s = SQ_A1; s <= SQ_H8; s++)
1569 if (square_is_occupied(s))
1570 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1572 if (ep_square() != SQ_NONE)
1573 result ^= zobEp[ep_square()];
1575 result ^= zobCastle[st->castleRights];
1576 if (side_to_move() == BLACK)
1577 result ^= zobSideToMove;
1583 /// Position::compute_pawn_key() computes the hash key of the position. The
1584 /// hash key is usually updated incrementally as moves are made and unmade,
1585 /// the compute_pawn_key() function is only used when a new position is set
1586 /// up, and to verify the correctness of the pawn hash key when running in
1589 Key Position::compute_pawn_key() const {
1591 Key result = Key(0ULL);
1595 for (Color c = WHITE; c <= BLACK; c++)
1597 b = pieces(PAWN, c);
1600 s = pop_1st_bit(&b);
1601 result ^= zobrist[c][PAWN][s];
1608 /// Position::compute_material_key() computes the hash key of the position.
1609 /// The hash key is usually updated incrementally as moves are made and unmade,
1610 /// the compute_material_key() function is only used when a new position is set
1611 /// up, and to verify the correctness of the material hash key when running in
1614 Key Position::compute_material_key() const {
1616 Key result = Key(0ULL);
1617 for (Color c = WHITE; c <= BLACK; c++)
1618 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1620 int count = piece_count(c, pt);
1621 for (int i = 0; i <= count; i++)
1622 result ^= zobMaterial[c][pt][i];
1628 /// Position::compute_value() compute the incremental scores for the middle
1629 /// game and the endgame. These functions are used to initialize the incremental
1630 /// scores when a new position is set up, and to verify that the scores are correctly
1631 /// updated by do_move and undo_move when the program is running in debug mode.
1632 Score Position::compute_value() const {
1634 Score result = make_score(0, 0);
1638 for (Color c = WHITE; c <= BLACK; c++)
1639 for (PieceType pt = PAWN; pt <= KING; pt++)
1644 s = pop_1st_bit(&b);
1645 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1646 result += pst(c, pt, s);
1650 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1655 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1656 /// game material score for the given side. Material scores are updated
1657 /// incrementally during the search, this function is only used while
1658 /// initializing a new Position object.
1660 Value Position::compute_non_pawn_material(Color c) const {
1662 Value result = Value(0);
1664 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1666 Bitboard b = pieces(pt, c);
1669 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1671 result += piece_value_midgame(pt);
1678 /// Position::is_draw() tests whether the position is drawn by material,
1679 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1680 /// must be done by the search.
1681 // FIXME: Currently we are not handling 50 move rule correctly when in check
1683 bool Position::is_draw() const {
1685 // Draw by material?
1687 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1690 // Draw by the 50 moves rule?
1691 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1694 // Draw by repetition?
1695 for (int i = 4; i <= Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1696 if (history[gamePly - i] == st->key)
1703 /// Position::is_mate() returns true or false depending on whether the
1704 /// side to move is checkmated.
1706 bool Position::is_mate() const {
1708 MoveStack moves[256];
1709 return is_check() && (generate_moves(*this, moves, false) == moves);
1713 /// Position::has_mate_threat() tests whether a given color has a mate in one
1714 /// from the current position.
1716 bool Position::has_mate_threat(Color c) {
1719 Color stm = side_to_move();
1724 // If the input color is not equal to the side to move, do a null move
1728 MoveStack mlist[120];
1729 bool result = false;
1730 Bitboard pinned = pinned_pieces(sideToMove);
1732 // Generate pseudo-legal non-capture and capture check moves
1733 MoveStack* last = generate_non_capture_checks(*this, mlist);
1734 last = generate_captures(*this, last);
1736 // Loop through the moves, and see if one of them is mate
1737 for (MoveStack* cur = mlist; cur != last; cur++)
1739 Move move = cur->move;
1740 if (!pl_move_is_legal(move, pinned))
1750 // Undo null move, if necessary
1758 /// Position::init_zobrist() is a static member function which initializes the
1759 /// various arrays used to compute hash keys.
1761 void Position::init_zobrist() {
1763 for (int i = 0; i < 2; i++)
1764 for (int j = 0; j < 8; j++)
1765 for (int k = 0; k < 64; k++)
1766 zobrist[i][j][k] = Key(genrand_int64());
1768 for (int i = 0; i < 64; i++)
1769 zobEp[i] = Key(genrand_int64());
1771 for (int i = 0; i < 16; i++)
1772 zobCastle[i] = genrand_int64();
1774 zobSideToMove = genrand_int64();
1776 for (int i = 0; i < 2; i++)
1777 for (int j = 0; j < 8; j++)
1778 for (int k = 0; k < 16; k++)
1779 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1781 for (int i = 0; i < 16; i++)
1782 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1784 zobExclusion = genrand_int64();
1788 /// Position::init_piece_square_tables() initializes the piece square tables.
1789 /// This is a two-step operation: First, the white halves of the tables are
1790 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1791 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1792 /// Second, the black halves of the tables are initialized by mirroring
1793 /// and changing the sign of the corresponding white scores.
1795 void Position::init_piece_square_tables() {
1797 int r = get_option_value_int("Randomness"), i;
1798 for (Square s = SQ_A1; s <= SQ_H8; s++)
1799 for (Piece p = WP; p <= WK; p++)
1801 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1802 PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1805 for (Square s = SQ_A1; s <= SQ_H8; s++)
1806 for (Piece p = BP; p <= BK; p++)
1807 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1811 /// Position::flipped_copy() makes a copy of the input position, but with
1812 /// the white and black sides reversed. This is only useful for debugging,
1813 /// especially for finding evaluation symmetry bugs.
1815 void Position::flipped_copy(const Position& pos) {
1817 assert(pos.is_ok());
1822 for (Square s = SQ_A1; s <= SQ_H8; s++)
1823 if (!pos.square_is_empty(s))
1824 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1827 sideToMove = opposite_color(pos.side_to_move());
1830 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1831 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1832 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1833 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1835 initialKFile = pos.initialKFile;
1836 initialKRFile = pos.initialKRFile;
1837 initialQRFile = pos.initialQRFile;
1839 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1840 castleRightsMask[sq] = ALL_CASTLES;
1842 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1843 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1844 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1845 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1846 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1847 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1849 // En passant square
1850 if (pos.st->epSquare != SQ_NONE)
1851 st->epSquare = flip_square(pos.st->epSquare);
1857 st->key = compute_key();
1858 st->pawnKey = compute_pawn_key();
1859 st->materialKey = compute_material_key();
1861 // Incremental scores
1862 st->value = compute_value();
1865 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1866 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1872 /// Position::is_ok() performs some consitency checks for the position object.
1873 /// This is meant to be helpful when debugging.
1875 bool Position::is_ok(int* failedStep) const {
1877 // What features of the position should be verified?
1878 static const bool debugBitboards = false;
1879 static const bool debugKingCount = false;
1880 static const bool debugKingCapture = false;
1881 static const bool debugCheckerCount = false;
1882 static const bool debugKey = false;
1883 static const bool debugMaterialKey = false;
1884 static const bool debugPawnKey = false;
1885 static const bool debugIncrementalEval = false;
1886 static const bool debugNonPawnMaterial = false;
1887 static const bool debugPieceCounts = false;
1888 static const bool debugPieceList = false;
1889 static const bool debugCastleSquares = false;
1891 if (failedStep) *failedStep = 1;
1894 if (!color_is_ok(side_to_move()))
1897 // Are the king squares in the position correct?
1898 if (failedStep) (*failedStep)++;
1899 if (piece_on(king_square(WHITE)) != WK)
1902 if (failedStep) (*failedStep)++;
1903 if (piece_on(king_square(BLACK)) != BK)
1907 if (failedStep) (*failedStep)++;
1908 if (!file_is_ok(initialKRFile))
1911 if (!file_is_ok(initialQRFile))
1914 // Do both sides have exactly one king?
1915 if (failedStep) (*failedStep)++;
1918 int kingCount[2] = {0, 0};
1919 for (Square s = SQ_A1; s <= SQ_H8; s++)
1920 if (type_of_piece_on(s) == KING)
1921 kingCount[color_of_piece_on(s)]++;
1923 if (kingCount[0] != 1 || kingCount[1] != 1)
1927 // Can the side to move capture the opponent's king?
1928 if (failedStep) (*failedStep)++;
1929 if (debugKingCapture)
1931 Color us = side_to_move();
1932 Color them = opposite_color(us);
1933 Square ksq = king_square(them);
1934 if (attackers_to(ksq) & pieces_of_color(us))
1938 // Is there more than 2 checkers?
1939 if (failedStep) (*failedStep)++;
1940 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1944 if (failedStep) (*failedStep)++;
1947 // The intersection of the white and black pieces must be empty
1948 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1951 // The union of the white and black pieces must be equal to all
1953 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1956 // Separate piece type bitboards must have empty intersections
1957 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1958 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1959 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1963 // En passant square OK?
1964 if (failedStep) (*failedStep)++;
1965 if (ep_square() != SQ_NONE)
1967 // The en passant square must be on rank 6, from the point of view of the
1969 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1974 if (failedStep) (*failedStep)++;
1975 if (debugKey && st->key != compute_key())
1978 // Pawn hash key OK?
1979 if (failedStep) (*failedStep)++;
1980 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1983 // Material hash key OK?
1984 if (failedStep) (*failedStep)++;
1985 if (debugMaterialKey && st->materialKey != compute_material_key())
1988 // Incremental eval OK?
1989 if (failedStep) (*failedStep)++;
1990 if (debugIncrementalEval && st->value != compute_value())
1993 // Non-pawn material OK?
1994 if (failedStep) (*failedStep)++;
1995 if (debugNonPawnMaterial)
1997 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2000 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2005 if (failedStep) (*failedStep)++;
2006 if (debugPieceCounts)
2007 for (Color c = WHITE; c <= BLACK; c++)
2008 for (PieceType pt = PAWN; pt <= KING; pt++)
2009 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2012 if (failedStep) (*failedStep)++;
2015 for (Color c = WHITE; c <= BLACK; c++)
2016 for (PieceType pt = PAWN; pt <= KING; pt++)
2017 for (int i = 0; i < pieceCount[c][pt]; i++)
2019 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2022 if (index[piece_list(c, pt, i)] != i)
2027 if (failedStep) (*failedStep)++;
2028 if (debugCastleSquares) {
2029 for (Color c = WHITE; c <= BLACK; c++) {
2030 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2032 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2035 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2037 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2039 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2041 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2045 if (failedStep) *failedStep = 0;