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-2010 Marco Costalba, Joona Kiiski, Tord Romstad
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) {
90 memcpy(this, &pos, sizeof(Position));
91 detach(); // Always detach() in copy c'tor to avoid surprises
94 Position::Position(const string& fen) {
100 /// Position::detach() copies the content of the current state and castling
101 /// masks inside the position itself. This is needed when the st pointee could
102 /// become stale, as example because the caller is about to going out of scope.
104 void Position::detach() {
108 st->previous = NULL; // as a safe guard
112 /// Position::from_fen() initializes the position object with the given FEN
113 /// string. This function is not very robust - make sure that input FENs are
114 /// correct (this is assumed to be the responsibility of the GUI).
116 void Position::from_fen(const string& fen) {
118 static const string pieceLetters = "KQRBNPkqrbnp";
119 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
127 for ( ; fen[i] != ' '; i++)
131 // Skip the given number of files
132 file += (fen[i] - '1' + 1);
135 else if (fen[i] == '/')
141 size_t idx = pieceLetters.find(fen[i]);
142 if (idx == string::npos)
144 std::cout << "Error in FEN at character " << i << std::endl;
147 Square square = make_square(file, rank);
148 put_piece(pieces[idx], square);
154 if (fen[i] != 'w' && fen[i] != 'b')
156 std::cout << "Error in FEN at character " << i << std::endl;
159 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
165 std::cout << "Error in FEN at character " << i << std::endl;
170 while (strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
176 else if (fen[i] == 'K') allow_oo(WHITE);
177 else if (fen[i] == 'Q') allow_ooo(WHITE);
178 else if (fen[i] == 'k') allow_oo(BLACK);
179 else if (fen[i] == 'q') allow_ooo(BLACK);
180 else if (fen[i] >= 'A' && fen[i] <= 'H') {
181 File rookFile, kingFile = FILE_NONE;
182 for (Square square = SQ_B1; square <= SQ_G1; square++)
183 if (piece_on(square) == WK)
184 kingFile = square_file(square);
185 if (kingFile == FILE_NONE) {
186 std::cout << "Error in FEN at character " << i << std::endl;
189 initialKFile = kingFile;
190 rookFile = File(fen[i] - 'A') + FILE_A;
191 if (rookFile < initialKFile) {
193 initialQRFile = rookFile;
197 initialKRFile = rookFile;
200 else if (fen[i] >= 'a' && fen[i] <= 'h') {
201 File rookFile, kingFile = FILE_NONE;
202 for (Square square = SQ_B8; square <= SQ_G8; square++)
203 if (piece_on(square) == BK)
204 kingFile = square_file(square);
205 if (kingFile == FILE_NONE) {
206 std::cout << "Error in FEN at character " << i << std::endl;
209 initialKFile = kingFile;
210 rookFile = File(fen[i] - 'a') + FILE_A;
211 if (rookFile < initialKFile) {
213 initialQRFile = rookFile;
217 initialKRFile = rookFile;
221 std::cout << "Error in FEN at character " << i << std::endl;
228 while (fen[i] == ' ')
231 // En passant square -- ignore if no capture is possible
232 if ( i <= fen.length() - 2
233 && (fen[i] >= 'a' && fen[i] <= 'h')
234 && (fen[i+1] == '3' || fen[i+1] == '6'))
236 Square fenEpSquare = square_from_string(fen.substr(i, 2));
237 Color them = opposite_color(sideToMove);
238 if (attacks_from<PAWN>(fenEpSquare, them) & this->pieces(PAWN, sideToMove))
239 st->epSquare = square_from_string(fen.substr(i, 2));
242 // Various initialisation
243 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
244 castleRightsMask[sq] = ALL_CASTLES;
246 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
247 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
248 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
249 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
250 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
251 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
255 st->key = compute_key();
256 st->pawnKey = compute_pawn_key();
257 st->materialKey = compute_material_key();
258 st->value = compute_value();
259 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
260 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
264 /// Position::to_fen() converts the position object to a FEN string. This is
265 /// probably only useful for debugging.
267 const string Position::to_fen() const {
269 static const string pieceLetters = " PNBRQK pnbrqk";
273 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
276 for (File file = FILE_A; file <= FILE_H; file++)
278 Square sq = make_square(file, rank);
279 if (!square_is_occupied(sq))
285 fen += (char)skip + '0';
288 fen += pieceLetters[piece_on(sq)];
291 fen += (char)skip + '0';
293 fen += (rank > RANK_1 ? '/' : ' ');
295 fen += (sideToMove == WHITE ? "w " : "b ");
296 if (st->castleRights != NO_CASTLES)
298 if (initialKFile == FILE_E && initialQRFile == FILE_A && initialKRFile == FILE_H)
300 if (can_castle_kingside(WHITE)) fen += 'K';
301 if (can_castle_queenside(WHITE)) fen += 'Q';
302 if (can_castle_kingside(BLACK)) fen += 'k';
303 if (can_castle_queenside(BLACK)) fen += 'q';
307 if (can_castle_kingside(WHITE))
308 fen += char(toupper(file_to_char(initialKRFile)));
309 if (can_castle_queenside(WHITE))
310 fen += char(toupper(file_to_char(initialQRFile)));
311 if (can_castle_kingside(BLACK))
312 fen += file_to_char(initialKRFile);
313 if (can_castle_queenside(BLACK))
314 fen += file_to_char(initialQRFile);
320 if (ep_square() != SQ_NONE)
321 fen += square_to_string(ep_square());
329 /// Position::print() prints an ASCII representation of the position to
330 /// the standard output. If a move is given then also the san is print.
332 void Position::print(Move m) const {
334 static const string pieceLetters = " PNBRQK PNBRQK .";
336 // Check for reentrancy, as example when called from inside
337 // MovePicker that is used also here in move_to_san()
341 RequestPending = true;
343 std::cout << std::endl;
347 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
348 std::cout << "Move is: " << col << move_to_san(p, m) << std::endl;
350 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
352 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
353 for (File file = FILE_A; file <= FILE_H; file++)
355 Square sq = make_square(file, rank);
356 Piece piece = piece_on(sq);
357 if (piece == EMPTY && square_color(sq) == WHITE)
360 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
361 std::cout << '|' << col << pieceLetters[piece] << col;
363 std::cout << '|' << std::endl;
365 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
366 << "Fen is: " << to_fen() << std::endl
367 << "Key is: " << st->key << std::endl;
369 RequestPending = false;
373 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
374 /// king) pieces for the given color and for the given pinner type. Or, when
375 /// template parameter FindPinned is false, the pieces of the given color
376 /// candidate for a discovery check against the enemy king.
377 /// Bitboard checkersBB must be already updated when looking for pinners.
379 template<bool FindPinned>
380 Bitboard Position::hidden_checkers(Color c) const {
382 Bitboard result = EmptyBoardBB;
383 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
385 // Pinned pieces protect our king, dicovery checks attack
387 Square ksq = king_square(FindPinned ? c : opposite_color(c));
389 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
390 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
392 if (FindPinned && pinners)
393 pinners &= ~st->checkersBB;
397 Square s = pop_1st_bit(&pinners);
398 Bitboard b = squares_between(s, ksq) & occupied_squares();
402 if ( !(b & (b - 1)) // Only one bit set?
403 && (b & pieces_of_color(c))) // Is an our piece?
410 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
411 /// king) pieces for the given color. Note that checkersBB bitboard must
412 /// be already updated.
414 Bitboard Position::pinned_pieces(Color c) const {
416 return hidden_checkers<true>(c);
420 /// Position:discovered_check_candidates() returns a bitboard containing all
421 /// pieces for the given side which are candidates for giving a discovered
422 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
423 /// to be already updated.
425 Bitboard Position::discovered_check_candidates(Color c) const {
427 return hidden_checkers<false>(c);
430 /// Position::attackers_to() computes a bitboard containing all pieces which
431 /// attacks a given square.
433 Bitboard Position::attackers_to(Square s) const {
435 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
436 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
437 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
438 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
439 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
440 | (attacks_from<KING>(s) & pieces(KING));
443 /// Position::attacks_from() computes a bitboard of all attacks
444 /// of a given piece put in a given square.
446 Bitboard Position::attacks_from(Piece p, Square s) const {
448 assert(square_is_ok(s));
452 case WP: return attacks_from<PAWN>(s, WHITE);
453 case BP: return attacks_from<PAWN>(s, BLACK);
454 case WN: case BN: return attacks_from<KNIGHT>(s);
455 case WB: case BB: return attacks_from<BISHOP>(s);
456 case WR: case BR: return attacks_from<ROOK>(s);
457 case WQ: case BQ: return attacks_from<QUEEN>(s);
458 case WK: case BK: return attacks_from<KING>(s);
465 /// Position::move_attacks_square() tests whether a move from the current
466 /// position attacks a given square.
468 bool Position::move_attacks_square(Move m, Square s) const {
470 assert(move_is_ok(m));
471 assert(square_is_ok(s));
473 Square f = move_from(m), t = move_to(m);
475 assert(square_is_occupied(f));
477 if (bit_is_set(attacks_from(piece_on(f), t), s))
480 // Move the piece and scan for X-ray attacks behind it
481 Bitboard occ = occupied_squares();
482 Color us = color_of_piece_on(f);
485 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
486 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
488 // If we have attacks we need to verify that are caused by our move
489 // and are not already existent ones.
490 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
494 /// Position::find_checkers() computes the checkersBB bitboard, which
495 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
496 /// currently works by calling Position::attackers_to, which is probably
497 /// inefficient. Consider rewriting this function to use the last move
498 /// played, like in non-bitboard versions of Glaurung.
500 void Position::find_checkers() {
502 Color us = side_to_move();
503 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
507 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
509 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
512 assert(move_is_ok(m));
513 assert(pinned == pinned_pieces(side_to_move()));
515 // Castling moves are checked for legality during move generation.
516 if (move_is_castle(m))
519 Color us = side_to_move();
520 Square from = move_from(m);
522 assert(color_of_piece_on(from) == us);
523 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
525 // En passant captures are a tricky special case. Because they are
526 // rather uncommon, we do it simply by testing whether the king is attacked
527 // after the move is made
530 Color them = opposite_color(us);
531 Square to = move_to(m);
532 Square capsq = make_square(square_file(to), square_rank(from));
533 Bitboard b = occupied_squares();
534 Square ksq = king_square(us);
536 assert(to == ep_square());
537 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
538 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
539 assert(piece_on(to) == EMPTY);
542 clear_bit(&b, capsq);
545 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
546 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
549 // If the moving piece is a king, check whether the destination
550 // square is attacked by the opponent.
551 if (type_of_piece_on(from) == KING)
552 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
554 // A non-king move is legal if and only if it is not pinned or it
555 // is moving along the ray towards or away from the king.
557 || !bit_is_set(pinned, from)
558 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
562 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
564 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
568 Color us = side_to_move();
569 Square from = move_from(m);
570 Square to = move_to(m);
572 // King moves and en-passant captures are verified in pl_move_is_legal()
573 if (type_of_piece_on(from) == KING || move_is_ep(m))
574 return pl_move_is_legal(m, pinned);
576 Bitboard target = checkers();
577 Square checksq = pop_1st_bit(&target);
579 if (target) // double check ?
582 // Our move must be a blocking evasion or a capture of the checking piece
583 target = squares_between(checksq, king_square(us)) | checkers();
584 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
588 /// Position::move_is_check() tests whether a pseudo-legal move is a check
590 bool Position::move_is_check(Move m) const {
592 return move_is_check(m, CheckInfo(*this));
595 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
598 assert(move_is_ok(m));
599 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
600 assert(color_of_piece_on(move_from(m)) == side_to_move());
601 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
603 Square from = move_from(m);
604 Square to = move_to(m);
605 PieceType pt = type_of_piece_on(from);
608 if (bit_is_set(ci.checkSq[pt], to))
612 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
614 // For pawn and king moves we need to verify also direction
615 if ( (pt != PAWN && pt != KING)
616 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
620 // Can we skip the ugly special cases ?
621 if (!move_is_special(m))
624 Color us = side_to_move();
625 Bitboard b = occupied_squares();
627 // Promotion with check ?
628 if (move_is_promotion(m))
632 switch (move_promotion_piece(m))
635 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
637 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
639 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
641 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
647 // En passant capture with check? We have already handled the case
648 // of direct checks and ordinary discovered check, the only case we
649 // need to handle is the unusual case of a discovered check through the
653 Square capsq = make_square(square_file(to), square_rank(from));
655 clear_bit(&b, capsq);
657 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
658 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
661 // Castling with check ?
662 if (move_is_castle(m))
664 Square kfrom, kto, rfrom, rto;
670 kto = relative_square(us, SQ_G1);
671 rto = relative_square(us, SQ_F1);
673 kto = relative_square(us, SQ_C1);
674 rto = relative_square(us, SQ_D1);
676 clear_bit(&b, kfrom);
677 clear_bit(&b, rfrom);
680 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
687 /// Position::do_move() makes a move, and saves all information necessary
688 /// to a StateInfo object. The move is assumed to be legal.
689 /// Pseudo-legal moves should be filtered out before this function is called.
691 void Position::do_move(Move m, StateInfo& newSt) {
694 do_move(m, newSt, ci, move_is_check(m, ci));
697 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
700 assert(move_is_ok(m));
702 Bitboard key = st->key;
704 // Copy some fields of old state to our new StateInfo object except the
705 // ones which are recalculated from scratch anyway, then switch our state
706 // pointer to point to the new, ready to be updated, state.
707 struct ReducedStateInfo {
708 Key pawnKey, materialKey;
709 int castleRights, rule50, pliesFromNull;
715 memcpy(&newSt, st, sizeof(ReducedStateInfo));
719 // Save the current key to the history[] array, in order to be able to
720 // detect repetition draws.
721 history[gamePly] = key;
724 // Update side to move
725 key ^= zobSideToMove;
727 // Increment the 50 moves rule draw counter. Resetting it to zero in the
728 // case of non-reversible moves is taken care of later.
732 if (move_is_castle(m))
739 Color us = side_to_move();
740 Color them = opposite_color(us);
741 Square from = move_from(m);
742 Square to = move_to(m);
743 bool ep = move_is_ep(m);
744 bool pm = move_is_promotion(m);
746 Piece piece = piece_on(from);
747 PieceType pt = type_of_piece(piece);
748 PieceType capture = ep ? PAWN : type_of_piece_on(to);
750 assert(color_of_piece_on(from) == us);
751 assert(color_of_piece_on(to) == them || square_is_empty(to));
752 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
753 assert(!pm || relative_rank(us, to) == RANK_8);
756 do_capture_move(key, capture, them, to, ep);
759 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
761 // Reset en passant square
762 if (st->epSquare != SQ_NONE)
764 key ^= zobEp[st->epSquare];
765 st->epSquare = SQ_NONE;
768 // Update castle rights, try to shortcut a common case
769 int cm = castleRightsMask[from] & castleRightsMask[to];
770 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
772 key ^= zobCastle[st->castleRights];
773 st->castleRights &= castleRightsMask[from];
774 st->castleRights &= castleRightsMask[to];
775 key ^= zobCastle[st->castleRights];
778 // Prefetch TT access as soon as we know key is updated
782 Bitboard move_bb = make_move_bb(from, to);
783 do_move_bb(&(byColorBB[us]), move_bb);
784 do_move_bb(&(byTypeBB[pt]), move_bb);
785 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
787 board[to] = board[from];
790 // Update piece lists, note that index[from] is not updated and
791 // becomes stale. This works as long as index[] is accessed just
792 // by known occupied squares.
793 index[to] = index[from];
794 pieceList[us][pt][index[to]] = to;
796 // If the moving piece was a pawn do some special extra work
799 // Reset rule 50 draw counter
802 // Update pawn hash key
803 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
805 // Set en passant square, only if moved pawn can be captured
806 if ((to ^ from) == 16)
808 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
810 st->epSquare = Square((int(from) + int(to)) / 2);
811 key ^= zobEp[st->epSquare];
816 // Update incremental scores
817 st->value += pst_delta(piece, from, to);
820 st->capture = capture;
822 if (pm) // promotion ?
824 PieceType promotion = move_promotion_piece(m);
826 assert(promotion >= KNIGHT && promotion <= QUEEN);
828 // Insert promoted piece instead of pawn
829 clear_bit(&(byTypeBB[PAWN]), to);
830 set_bit(&(byTypeBB[promotion]), to);
831 board[to] = piece_of_color_and_type(us, promotion);
833 // Update material key
834 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
835 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
837 // Update piece counts
838 pieceCount[us][PAWN]--;
839 pieceCount[us][promotion]++;
841 // Update piece lists, move the last pawn at index[to] position
842 // and shrink the list. Add a new promotion piece to the list.
843 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
844 index[lastPawnSquare] = index[to];
845 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
846 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
847 index[to] = pieceCount[us][promotion] - 1;
848 pieceList[us][promotion][index[to]] = to;
850 // Partially revert hash keys update
851 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
852 st->pawnKey ^= zobrist[us][PAWN][to];
854 // Partially revert and update incremental scores
855 st->value -= pst(us, PAWN, to);
856 st->value += pst(us, promotion, to);
859 st->npMaterial[us] += piece_value_midgame(promotion);
862 // Update the key with the final value
865 // Update checkers bitboard, piece must be already moved
866 st->checkersBB = EmptyBoardBB;
871 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
875 if (bit_is_set(ci.checkSq[pt], to))
876 st->checkersBB = SetMaskBB[to];
879 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
882 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
885 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
891 sideToMove = opposite_color(sideToMove);
892 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
898 /// Position::do_capture_move() is a private method used to update captured
899 /// piece info. It is called from the main Position::do_move function.
901 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
903 assert(capture != KING);
907 if (ep) // en passant ?
909 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
911 assert(to == st->epSquare);
912 assert(relative_rank(opposite_color(them), to) == RANK_6);
913 assert(piece_on(to) == EMPTY);
914 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
916 board[capsq] = EMPTY;
919 // Remove captured piece
920 clear_bit(&(byColorBB[them]), capsq);
921 clear_bit(&(byTypeBB[capture]), capsq);
922 clear_bit(&(byTypeBB[0]), capsq);
925 key ^= zobrist[them][capture][capsq];
927 // Update incremental scores
928 st->value -= pst(them, capture, capsq);
930 // If the captured piece was a pawn, update pawn hash key,
931 // otherwise update non-pawn material.
933 st->pawnKey ^= zobrist[them][PAWN][capsq];
935 st->npMaterial[them] -= piece_value_midgame(capture);
937 // Update material hash key
938 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
940 // Update piece count
941 pieceCount[them][capture]--;
943 // Update piece list, move the last piece at index[capsq] position
945 // WARNING: This is a not perfectly revresible operation. When we
946 // will reinsert the captured piece in undo_move() we will put it
947 // at the end of the list and not in its original place, it means
948 // index[] and pieceList[] are not guaranteed to be invariant to a
949 // do_move() + undo_move() sequence.
950 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
951 index[lastPieceSquare] = index[capsq];
952 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
953 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
955 // Reset rule 50 counter
960 /// Position::do_castle_move() is a private method used to make a castling
961 /// move. It is called from the main Position::do_move function. Note that
962 /// castling moves are encoded as "king captures friendly rook" moves, for
963 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
965 void Position::do_castle_move(Move m) {
967 assert(move_is_ok(m));
968 assert(move_is_castle(m));
970 Color us = side_to_move();
971 Color them = opposite_color(us);
973 // Reset capture field
974 st->capture = NO_PIECE_TYPE;
976 // Find source squares for king and rook
977 Square kfrom = move_from(m);
978 Square rfrom = move_to(m); // HACK: See comment at beginning of function
981 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
982 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
984 // Find destination squares for king and rook
985 if (rfrom > kfrom) // O-O
987 kto = relative_square(us, SQ_G1);
988 rto = relative_square(us, SQ_F1);
990 kto = relative_square(us, SQ_C1);
991 rto = relative_square(us, SQ_D1);
994 // Remove pieces from source squares:
995 clear_bit(&(byColorBB[us]), kfrom);
996 clear_bit(&(byTypeBB[KING]), kfrom);
997 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
998 clear_bit(&(byColorBB[us]), rfrom);
999 clear_bit(&(byTypeBB[ROOK]), rfrom);
1000 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1002 // Put pieces on destination squares:
1003 set_bit(&(byColorBB[us]), kto);
1004 set_bit(&(byTypeBB[KING]), kto);
1005 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1006 set_bit(&(byColorBB[us]), rto);
1007 set_bit(&(byTypeBB[ROOK]), rto);
1008 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1010 // Update board array
1011 Piece king = piece_of_color_and_type(us, KING);
1012 Piece rook = piece_of_color_and_type(us, ROOK);
1013 board[kfrom] = board[rfrom] = EMPTY;
1017 // Update piece lists
1018 pieceList[us][KING][index[kfrom]] = kto;
1019 pieceList[us][ROOK][index[rfrom]] = rto;
1020 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1021 index[kto] = index[kfrom];
1024 // Update incremental scores
1025 st->value += pst_delta(king, kfrom, kto);
1026 st->value += pst_delta(rook, rfrom, rto);
1029 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1030 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1032 // Clear en passant square
1033 if (st->epSquare != SQ_NONE)
1035 st->key ^= zobEp[st->epSquare];
1036 st->epSquare = SQ_NONE;
1039 // Update castling rights
1040 st->key ^= zobCastle[st->castleRights];
1041 st->castleRights &= castleRightsMask[kfrom];
1042 st->key ^= zobCastle[st->castleRights];
1044 // Reset rule 50 counter
1047 // Update checkers BB
1048 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1051 sideToMove = opposite_color(sideToMove);
1052 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1058 /// Position::undo_move() unmakes a move. When it returns, the position should
1059 /// be restored to exactly the same state as before the move was made.
1061 void Position::undo_move(Move m) {
1064 assert(move_is_ok(m));
1067 sideToMove = opposite_color(sideToMove);
1069 if (move_is_castle(m))
1071 undo_castle_move(m);
1075 Color us = side_to_move();
1076 Color them = opposite_color(us);
1077 Square from = move_from(m);
1078 Square to = move_to(m);
1079 bool ep = move_is_ep(m);
1080 bool pm = move_is_promotion(m);
1082 PieceType pt = type_of_piece_on(to);
1084 assert(square_is_empty(from));
1085 assert(color_of_piece_on(to) == us);
1086 assert(!pm || relative_rank(us, to) == RANK_8);
1087 assert(!ep || to == st->previous->epSquare);
1088 assert(!ep || relative_rank(us, to) == RANK_6);
1089 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1091 if (pm) // promotion ?
1093 PieceType promotion = move_promotion_piece(m);
1096 assert(promotion >= KNIGHT && promotion <= QUEEN);
1097 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1099 // Replace promoted piece with a pawn
1100 clear_bit(&(byTypeBB[promotion]), to);
1101 set_bit(&(byTypeBB[PAWN]), to);
1103 // Update piece counts
1104 pieceCount[us][promotion]--;
1105 pieceCount[us][PAWN]++;
1107 // Update piece list replacing promotion piece with a pawn
1108 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1109 index[lastPromotionSquare] = index[to];
1110 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1111 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1112 index[to] = pieceCount[us][PAWN] - 1;
1113 pieceList[us][PAWN][index[to]] = to;
1117 // Put the piece back at the source square
1118 Bitboard move_bb = make_move_bb(to, from);
1119 do_move_bb(&(byColorBB[us]), move_bb);
1120 do_move_bb(&(byTypeBB[pt]), move_bb);
1121 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1123 board[from] = piece_of_color_and_type(us, pt);
1126 // Update piece list
1127 index[from] = index[to];
1128 pieceList[us][pt][index[from]] = from;
1135 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1137 assert(st->capture != KING);
1138 assert(!ep || square_is_empty(capsq));
1140 // Restore the captured piece
1141 set_bit(&(byColorBB[them]), capsq);
1142 set_bit(&(byTypeBB[st->capture]), capsq);
1143 set_bit(&(byTypeBB[0]), capsq);
1145 board[capsq] = piece_of_color_and_type(them, st->capture);
1147 // Update piece count
1148 pieceCount[them][st->capture]++;
1150 // Update piece list, add a new captured piece in capsq square
1151 index[capsq] = pieceCount[them][st->capture] - 1;
1152 pieceList[them][st->capture][index[capsq]] = capsq;
1155 // Finally point our state pointer back to the previous state
1162 /// Position::undo_castle_move() is a private method used to unmake a castling
1163 /// move. It is called from the main Position::undo_move function. Note that
1164 /// castling moves are encoded as "king captures friendly rook" moves, for
1165 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1167 void Position::undo_castle_move(Move m) {
1169 assert(move_is_ok(m));
1170 assert(move_is_castle(m));
1172 // When we have arrived here, some work has already been done by
1173 // Position::undo_move. In particular, the side to move has been switched,
1174 // so the code below is correct.
1175 Color us = side_to_move();
1177 // Find source squares for king and rook
1178 Square kfrom = move_from(m);
1179 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1182 // Find destination squares for king and rook
1183 if (rfrom > kfrom) // O-O
1185 kto = relative_square(us, SQ_G1);
1186 rto = relative_square(us, SQ_F1);
1188 kto = relative_square(us, SQ_C1);
1189 rto = relative_square(us, SQ_D1);
1192 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1193 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1195 // Remove pieces from destination squares:
1196 clear_bit(&(byColorBB[us]), kto);
1197 clear_bit(&(byTypeBB[KING]), kto);
1198 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1199 clear_bit(&(byColorBB[us]), rto);
1200 clear_bit(&(byTypeBB[ROOK]), rto);
1201 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1203 // Put pieces on source squares:
1204 set_bit(&(byColorBB[us]), kfrom);
1205 set_bit(&(byTypeBB[KING]), kfrom);
1206 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1207 set_bit(&(byColorBB[us]), rfrom);
1208 set_bit(&(byTypeBB[ROOK]), rfrom);
1209 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1212 board[rto] = board[kto] = EMPTY;
1213 board[rfrom] = piece_of_color_and_type(us, ROOK);
1214 board[kfrom] = piece_of_color_and_type(us, KING);
1216 // Update piece lists
1217 pieceList[us][KING][index[kto]] = kfrom;
1218 pieceList[us][ROOK][index[rto]] = rfrom;
1219 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1220 index[kfrom] = index[kto];
1223 // Finally point our state pointer back to the previous state
1230 /// Position::do_null_move makes() a "null move": It switches the side to move
1231 /// and updates the hash key without executing any move on the board.
1233 void Position::do_null_move(StateInfo& backupSt) {
1236 assert(!is_check());
1238 // Back up the information necessary to undo the null move to the supplied
1239 // StateInfo object.
1240 // Note that differently from normal case here backupSt is actually used as
1241 // a backup storage not as a new state to be used.
1242 backupSt.key = st->key;
1243 backupSt.epSquare = st->epSquare;
1244 backupSt.value = st->value;
1245 backupSt.previous = st->previous;
1246 backupSt.pliesFromNull = st->pliesFromNull;
1247 st->previous = &backupSt;
1249 // Save the current key to the history[] array, in order to be able to
1250 // detect repetition draws.
1251 history[gamePly] = st->key;
1253 // Update the necessary information
1254 if (st->epSquare != SQ_NONE)
1255 st->key ^= zobEp[st->epSquare];
1257 st->key ^= zobSideToMove;
1258 TT.prefetch(st->key);
1260 sideToMove = opposite_color(sideToMove);
1261 st->epSquare = SQ_NONE;
1263 st->pliesFromNull = 0;
1264 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1269 /// Position::undo_null_move() unmakes a "null move".
1271 void Position::undo_null_move() {
1274 assert(!is_check());
1276 // Restore information from the our backup StateInfo object
1277 StateInfo* backupSt = st->previous;
1278 st->key = backupSt->key;
1279 st->epSquare = backupSt->epSquare;
1280 st->value = backupSt->value;
1281 st->previous = backupSt->previous;
1282 st->pliesFromNull = backupSt->pliesFromNull;
1284 // Update the necessary information
1285 sideToMove = opposite_color(sideToMove);
1291 /// Position::see() is a static exchange evaluator: It tries to estimate the
1292 /// material gain or loss resulting from a move. There are three versions of
1293 /// this function: One which takes a destination square as input, one takes a
1294 /// move, and one which takes a 'from' and a 'to' square. The function does
1295 /// not yet understand promotions captures.
1297 int Position::see(Square to) const {
1299 assert(square_is_ok(to));
1300 return see(SQ_NONE, to);
1303 int Position::see(Move m) const {
1305 assert(move_is_ok(m));
1306 return see(move_from(m), move_to(m));
1309 int Position::see_sign(Move m) const {
1311 assert(move_is_ok(m));
1313 Square from = move_from(m);
1314 Square to = move_to(m);
1316 // Early return if SEE cannot be negative because capturing piece value
1317 // is not bigger then captured one.
1318 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1319 && type_of_piece_on(from) != KING)
1322 return see(from, to);
1325 int Position::see(Square from, Square to) const {
1328 static const int seeValues[18] = {
1329 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1330 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1331 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1332 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1336 Bitboard attackers, stmAttackers, b;
1338 assert(square_is_ok(from) || from == SQ_NONE);
1339 assert(square_is_ok(to));
1341 // Initialize colors
1342 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1343 Color them = opposite_color(us);
1345 // Initialize pieces
1346 Piece piece = piece_on(from);
1347 Piece capture = piece_on(to);
1348 Bitboard occ = occupied_squares();
1350 // King cannot be recaptured
1351 if (type_of_piece(piece) == KING)
1352 return seeValues[capture];
1354 // Handle en passant moves
1355 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1357 assert(capture == EMPTY);
1359 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1360 capture = piece_on(capQq);
1361 assert(type_of_piece_on(capQq) == PAWN);
1363 // Remove the captured pawn
1364 clear_bit(&occ, capQq);
1369 // Find all attackers to the destination square, with the moving piece
1370 // removed, but possibly an X-ray attacker added behind it.
1371 clear_bit(&occ, from);
1372 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1373 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1374 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1375 | (attacks_from<KING>(to) & pieces(KING))
1376 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1377 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1379 if (from != SQ_NONE)
1382 // If we don't have any attacker we are finished
1383 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1386 // Locate the least valuable attacker to the destination square
1387 // and use it to initialize from square.
1388 stmAttackers = attackers & pieces_of_color(us);
1390 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1393 from = first_1(stmAttackers & pieces(pt));
1394 piece = piece_on(from);
1397 // If the opponent has no attackers we are finished
1398 stmAttackers = attackers & pieces_of_color(them);
1400 return seeValues[capture];
1402 attackers &= occ; // Remove the moving piece
1404 // The destination square is defended, which makes things rather more
1405 // difficult to compute. We proceed by building up a "swap list" containing
1406 // the material gain or loss at each stop in a sequence of captures to the
1407 // destination square, where the sides alternately capture, and always
1408 // capture with the least valuable piece. After each capture, we look for
1409 // new X-ray attacks from behind the capturing piece.
1410 int lastCapturingPieceValue = seeValues[piece];
1411 int swapList[32], n = 1;
1415 swapList[0] = seeValues[capture];
1418 // Locate the least valuable attacker for the side to move. The loop
1419 // below looks like it is potentially infinite, but it isn't. We know
1420 // that the side to move still has at least one attacker left.
1421 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1424 // Remove the attacker we just found from the 'attackers' bitboard,
1425 // and scan for new X-ray attacks behind the attacker.
1426 b = stmAttackers & pieces(pt);
1427 occ ^= (b & (~b + 1));
1428 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1429 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1433 // Add the new entry to the swap list
1435 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1438 // Remember the value of the capturing piece, and change the side to move
1439 // before beginning the next iteration
1440 lastCapturingPieceValue = seeValues[pt];
1441 c = opposite_color(c);
1442 stmAttackers = attackers & pieces_of_color(c);
1444 // Stop after a king capture
1445 if (pt == KING && stmAttackers)
1448 swapList[n++] = QueenValueMidgame*10;
1451 } while (stmAttackers);
1453 // Having built the swap list, we negamax through it to find the best
1454 // achievable score from the point of view of the side to move
1456 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1462 /// Position::clear() erases the position object to a pristine state, with an
1463 /// empty board, white to move, and no castling rights.
1465 void Position::clear() {
1468 memset(st, 0, sizeof(StateInfo));
1469 st->epSquare = SQ_NONE;
1471 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1472 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1473 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1474 memset(index, 0, sizeof(int) * 64);
1476 for (int i = 0; i < 64; i++)
1479 for (int i = 0; i < 8; i++)
1480 for (int j = 0; j < 16; j++)
1481 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1485 initialKFile = FILE_E;
1486 initialKRFile = FILE_H;
1487 initialQRFile = FILE_A;
1491 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1492 /// UCI interface code, whenever a non-reversible move is made in a
1493 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1494 /// for the program to handle games of arbitrary length, as long as the GUI
1495 /// handles draws by the 50 move rule correctly.
1497 void Position::reset_game_ply() {
1503 /// Position::put_piece() puts a piece on the given square of the board,
1504 /// updating the board array, bitboards, and piece counts.
1506 void Position::put_piece(Piece p, Square s) {
1508 Color c = color_of_piece(p);
1509 PieceType pt = type_of_piece(p);
1512 index[s] = pieceCount[c][pt];
1513 pieceList[c][pt][index[s]] = s;
1515 set_bit(&(byTypeBB[pt]), s);
1516 set_bit(&(byColorBB[c]), s);
1517 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1519 pieceCount[c][pt]++;
1523 /// Position::allow_oo() gives the given side the right to castle kingside.
1524 /// Used when setting castling rights during parsing of FEN strings.
1526 void Position::allow_oo(Color c) {
1528 st->castleRights |= (1 + int(c));
1532 /// Position::allow_ooo() gives the given side the right to castle queenside.
1533 /// Used when setting castling rights during parsing of FEN strings.
1535 void Position::allow_ooo(Color c) {
1537 st->castleRights |= (4 + 4*int(c));
1541 /// Position::compute_key() computes the hash key of the position. The hash
1542 /// key is usually updated incrementally as moves are made and unmade, the
1543 /// compute_key() function is only used when a new position is set up, and
1544 /// to verify the correctness of the hash key when running in debug mode.
1546 Key Position::compute_key() const {
1548 Key result = Key(0ULL);
1550 for (Square s = SQ_A1; s <= SQ_H8; s++)
1551 if (square_is_occupied(s))
1552 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1554 if (ep_square() != SQ_NONE)
1555 result ^= zobEp[ep_square()];
1557 result ^= zobCastle[st->castleRights];
1558 if (side_to_move() == BLACK)
1559 result ^= zobSideToMove;
1565 /// Position::compute_pawn_key() computes the hash key of the position. The
1566 /// hash key is usually updated incrementally as moves are made and unmade,
1567 /// the compute_pawn_key() function is only used when a new position is set
1568 /// up, and to verify the correctness of the pawn hash key when running in
1571 Key Position::compute_pawn_key() const {
1573 Key result = Key(0ULL);
1577 for (Color c = WHITE; c <= BLACK; c++)
1579 b = pieces(PAWN, c);
1582 s = pop_1st_bit(&b);
1583 result ^= zobrist[c][PAWN][s];
1590 /// Position::compute_material_key() computes the hash key of the position.
1591 /// The hash key is usually updated incrementally as moves are made and unmade,
1592 /// the compute_material_key() function is only used when a new position is set
1593 /// up, and to verify the correctness of the material hash key when running in
1596 Key Position::compute_material_key() const {
1598 Key result = Key(0ULL);
1599 for (Color c = WHITE; c <= BLACK; c++)
1600 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1602 int count = piece_count(c, pt);
1603 for (int i = 0; i <= count; i++)
1604 result ^= zobMaterial[c][pt][i];
1610 /// Position::compute_value() compute the incremental scores for the middle
1611 /// game and the endgame. These functions are used to initialize the incremental
1612 /// scores when a new position is set up, and to verify that the scores are correctly
1613 /// updated by do_move and undo_move when the program is running in debug mode.
1614 Score Position::compute_value() const {
1616 Score result = make_score(0, 0);
1620 for (Color c = WHITE; c <= BLACK; c++)
1621 for (PieceType pt = PAWN; pt <= KING; pt++)
1626 s = pop_1st_bit(&b);
1627 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1628 result += pst(c, pt, s);
1632 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1637 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1638 /// game material score for the given side. Material scores are updated
1639 /// incrementally during the search, this function is only used while
1640 /// initializing a new Position object.
1642 Value Position::compute_non_pawn_material(Color c) const {
1644 Value result = Value(0);
1646 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1648 Bitboard b = pieces(pt, c);
1651 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1653 result += piece_value_midgame(pt);
1660 /// Position::is_draw() tests whether the position is drawn by material,
1661 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1662 /// must be done by the search.
1663 // FIXME: Currently we are not handling 50 move rule correctly when in check
1665 bool Position::is_draw() const {
1667 // Draw by material?
1669 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1672 // Draw by the 50 moves rule?
1673 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1676 // Draw by repetition?
1677 for (int i = 4; i <= Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1678 if (history[gamePly - i] == st->key)
1685 /// Position::is_mate() returns true or false depending on whether the
1686 /// side to move is checkmated.
1688 bool Position::is_mate() const {
1690 MoveStack moves[256];
1691 return is_check() && (generate_moves(*this, moves, false) == moves);
1695 /// Position::has_mate_threat() tests whether a given color has a mate in one
1696 /// from the current position.
1698 bool Position::has_mate_threat(Color c) {
1701 Color stm = side_to_move();
1706 // If the input color is not equal to the side to move, do a null move
1710 MoveStack mlist[120];
1711 bool result = false;
1712 Bitboard pinned = pinned_pieces(sideToMove);
1714 // Generate pseudo-legal non-capture and capture check moves
1715 MoveStack* last = generate_non_capture_checks(*this, mlist);
1716 last = generate_captures(*this, last);
1718 // Loop through the moves, and see if one of them is mate
1719 for (MoveStack* cur = mlist; cur != last; cur++)
1721 Move move = cur->move;
1722 if (!pl_move_is_legal(move, pinned))
1732 // Undo null move, if necessary
1740 /// Position::init_zobrist() is a static member function which initializes the
1741 /// various arrays used to compute hash keys.
1743 void Position::init_zobrist() {
1745 for (int i = 0; i < 2; i++)
1746 for (int j = 0; j < 8; j++)
1747 for (int k = 0; k < 64; k++)
1748 zobrist[i][j][k] = Key(genrand_int64());
1750 for (int i = 0; i < 64; i++)
1751 zobEp[i] = Key(genrand_int64());
1753 for (int i = 0; i < 16; i++)
1754 zobCastle[i] = genrand_int64();
1756 zobSideToMove = genrand_int64();
1758 for (int i = 0; i < 2; i++)
1759 for (int j = 0; j < 8; j++)
1760 for (int k = 0; k < 16; k++)
1761 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1763 for (int i = 0; i < 16; i++)
1764 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1766 zobExclusion = genrand_int64();
1770 /// Position::init_piece_square_tables() initializes the piece square tables.
1771 /// This is a two-step operation: First, the white halves of the tables are
1772 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1773 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1774 /// Second, the black halves of the tables are initialized by mirroring
1775 /// and changing the sign of the corresponding white scores.
1777 void Position::init_piece_square_tables() {
1779 int r = get_option_value_int("Randomness"), i;
1780 for (Square s = SQ_A1; s <= SQ_H8; s++)
1781 for (Piece p = WP; p <= WK; p++)
1783 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1784 PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1787 for (Square s = SQ_A1; s <= SQ_H8; s++)
1788 for (Piece p = BP; p <= BK; p++)
1789 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1793 /// Position::flipped_copy() makes a copy of the input position, but with
1794 /// the white and black sides reversed. This is only useful for debugging,
1795 /// especially for finding evaluation symmetry bugs.
1797 void Position::flipped_copy(const Position& pos) {
1799 assert(pos.is_ok());
1804 for (Square s = SQ_A1; s <= SQ_H8; s++)
1805 if (!pos.square_is_empty(s))
1806 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1809 sideToMove = opposite_color(pos.side_to_move());
1812 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1813 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1814 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1815 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1817 initialKFile = pos.initialKFile;
1818 initialKRFile = pos.initialKRFile;
1819 initialQRFile = pos.initialQRFile;
1821 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1822 castleRightsMask[sq] = ALL_CASTLES;
1824 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1825 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1826 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1827 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1828 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1829 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1831 // En passant square
1832 if (pos.st->epSquare != SQ_NONE)
1833 st->epSquare = flip_square(pos.st->epSquare);
1839 st->key = compute_key();
1840 st->pawnKey = compute_pawn_key();
1841 st->materialKey = compute_material_key();
1843 // Incremental scores
1844 st->value = compute_value();
1847 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1848 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1854 /// Position::is_ok() performs some consitency checks for the position object.
1855 /// This is meant to be helpful when debugging.
1857 bool Position::is_ok(int* failedStep) const {
1859 // What features of the position should be verified?
1860 static const bool debugBitboards = false;
1861 static const bool debugKingCount = false;
1862 static const bool debugKingCapture = false;
1863 static const bool debugCheckerCount = false;
1864 static const bool debugKey = false;
1865 static const bool debugMaterialKey = false;
1866 static const bool debugPawnKey = false;
1867 static const bool debugIncrementalEval = false;
1868 static const bool debugNonPawnMaterial = false;
1869 static const bool debugPieceCounts = false;
1870 static const bool debugPieceList = false;
1871 static const bool debugCastleSquares = false;
1873 if (failedStep) *failedStep = 1;
1876 if (!color_is_ok(side_to_move()))
1879 // Are the king squares in the position correct?
1880 if (failedStep) (*failedStep)++;
1881 if (piece_on(king_square(WHITE)) != WK)
1884 if (failedStep) (*failedStep)++;
1885 if (piece_on(king_square(BLACK)) != BK)
1889 if (failedStep) (*failedStep)++;
1890 if (!file_is_ok(initialKRFile))
1893 if (!file_is_ok(initialQRFile))
1896 // Do both sides have exactly one king?
1897 if (failedStep) (*failedStep)++;
1900 int kingCount[2] = {0, 0};
1901 for (Square s = SQ_A1; s <= SQ_H8; s++)
1902 if (type_of_piece_on(s) == KING)
1903 kingCount[color_of_piece_on(s)]++;
1905 if (kingCount[0] != 1 || kingCount[1] != 1)
1909 // Can the side to move capture the opponent's king?
1910 if (failedStep) (*failedStep)++;
1911 if (debugKingCapture)
1913 Color us = side_to_move();
1914 Color them = opposite_color(us);
1915 Square ksq = king_square(them);
1916 if (attackers_to(ksq) & pieces_of_color(us))
1920 // Is there more than 2 checkers?
1921 if (failedStep) (*failedStep)++;
1922 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1926 if (failedStep) (*failedStep)++;
1929 // The intersection of the white and black pieces must be empty
1930 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1933 // The union of the white and black pieces must be equal to all
1935 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1938 // Separate piece type bitboards must have empty intersections
1939 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1940 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1941 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1945 // En passant square OK?
1946 if (failedStep) (*failedStep)++;
1947 if (ep_square() != SQ_NONE)
1949 // The en passant square must be on rank 6, from the point of view of the
1951 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1956 if (failedStep) (*failedStep)++;
1957 if (debugKey && st->key != compute_key())
1960 // Pawn hash key OK?
1961 if (failedStep) (*failedStep)++;
1962 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1965 // Material hash key OK?
1966 if (failedStep) (*failedStep)++;
1967 if (debugMaterialKey && st->materialKey != compute_material_key())
1970 // Incremental eval OK?
1971 if (failedStep) (*failedStep)++;
1972 if (debugIncrementalEval && st->value != compute_value())
1975 // Non-pawn material OK?
1976 if (failedStep) (*failedStep)++;
1977 if (debugNonPawnMaterial)
1979 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1982 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1987 if (failedStep) (*failedStep)++;
1988 if (debugPieceCounts)
1989 for (Color c = WHITE; c <= BLACK; c++)
1990 for (PieceType pt = PAWN; pt <= KING; pt++)
1991 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
1994 if (failedStep) (*failedStep)++;
1997 for (Color c = WHITE; c <= BLACK; c++)
1998 for (PieceType pt = PAWN; pt <= KING; pt++)
1999 for (int i = 0; i < pieceCount[c][pt]; i++)
2001 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2004 if (index[piece_list(c, pt, i)] != i)
2009 if (failedStep) (*failedStep)++;
2010 if (debugCastleSquares) {
2011 for (Color c = WHITE; c <= BLACK; c++) {
2012 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2014 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2017 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2019 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2021 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2023 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2027 if (failedStep) *failedStep = 0;