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/>.
41 #include "ucioption.h"
47 static inline bool isZero(char c) { return c == '0'; }
49 struct PieceLetters : std::map<char, Piece> {
53 operator[]('K') = WK; operator[]('k') = BK;
54 operator[]('Q') = WQ; operator[]('q') = BQ;
55 operator[]('R') = WR; operator[]('r') = BR;
56 operator[]('B') = WB; operator[]('b') = BB;
57 operator[]('N') = WN; operator[]('n') = BN;
58 operator[]('P') = WP; operator[]('p') = BP;
61 char from_piece(Piece p) const {
63 map<char, Piece>::const_iterator it;
64 for (it = begin(); it != end(); ++it)
77 Key Position::zobrist[2][8][64];
78 Key Position::zobEp[64];
79 Key Position::zobCastle[16];
80 Key Position::zobSideToMove;
81 Key Position::zobExclusion;
83 Score Position::PieceSquareTable[16][64];
85 static bool RequestPending = false;
86 static PieceLetters pieceLetters;
91 CheckInfo::CheckInfo(const Position& pos) {
93 Color us = pos.side_to_move();
94 Color them = opposite_color(us);
96 ksq = pos.king_square(them);
97 dcCandidates = pos.discovered_check_candidates(us);
99 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
100 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
101 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
102 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
103 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
104 checkSq[KING] = EmptyBoardBB;
108 /// Position c'tors. Here we always create a copy of the original position
109 /// or the FEN string, we want the new born Position object do not depend
110 /// on any external data so we detach state pointer from the source one.
112 Position::Position(int th) : threadID(th) {}
114 Position::Position(const Position& pos, int th) {
116 memcpy(this, &pos, sizeof(Position));
117 detach(); // Always detach() in copy c'tor to avoid surprises
121 Position::Position(const string& fen, int th) {
128 /// Position::detach() copies the content of the current state and castling
129 /// masks inside the position itself. This is needed when the st pointee could
130 /// become stale, as example because the caller is about to going out of scope.
132 void Position::detach() {
136 st->previous = NULL; // as a safe guard
140 /// Position::from_fen() initializes the position object with the given FEN
141 /// string. This function is not very robust - make sure that input FENs are
142 /// correct (this is assumed to be the responsibility of the GUI).
144 void Position::from_fen(const string& fen) {
146 A FEN string defines a particular position using only the ASCII character set.
148 A FEN string contains six fields. The separator between fields is a space. The fields are:
150 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
151 with rank 1; within each rank, the contents of each square are described from file a through file h.
152 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
153 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
154 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
155 of blank squares), and "/" separate ranks.
157 2) Active color. "w" means white moves next, "b" means black.
159 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
160 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
161 kingside), and/or "q" (Black can castle queenside).
163 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
164 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
165 regardless of whether there is a pawn in position to make an en passant capture.
167 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
168 to determine if a draw can be claimed under the fifty-move rule.
170 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
174 std::istringstream ss(fen);
180 // 1. Piece placement field
181 while (ss.get(token) && token != ' ')
185 file += token - '0'; // Skip the given number of files
188 else if (token == '/')
195 if (pieceLetters.find(token) == pieceLetters.end())
198 put_piece(pieceLetters[token], make_square(file, rank));
203 if (!ss.get(token) || (token != 'w' && token != 'b'))
206 sideToMove = (token == 'w' ? WHITE : BLACK);
208 if (!ss.get(token) || token != ' ')
211 // 3. Castling availability
212 while (ss.get(token) && token != ' ')
217 if (!set_castling_rights(token))
221 // 4. En passant square -- ignore if no capture is possible
223 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
224 && (ss.get(row) && (row == '3' || row == '6')))
226 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
227 Color them = opposite_color(sideToMove);
229 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
230 st->epSquare = fenEpSquare;
233 // 5-6. Halfmove clock and fullmove number are not parsed
235 // Various initialisations
236 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
237 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
238 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
239 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
240 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
241 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
245 st->key = compute_key();
246 st->pawnKey = compute_pawn_key();
247 st->materialKey = compute_material_key();
248 st->value = compute_value();
249 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
250 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
254 cout << "Error in FEN string: " << fen << endl;
258 /// Position::set_castling_rights() sets castling parameters castling avaiability.
259 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
260 /// that uses the letters of the columns on which the rooks began the game instead
261 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
262 /// associated with the castling right, the traditional castling tag will be replaced
263 /// by the file letter of the involved rook as for the Shredder-FEN.
265 bool Position::set_castling_rights(char token) {
267 Color c = token >= 'a' ? BLACK : WHITE;
268 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
269 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
270 Piece rook = (c == WHITE ? WR : BR);
272 initialKFile = square_file(king_square(c));
273 token = char(toupper(token));
277 for (Square sq = sqH; sq >= sqA; sq--)
278 if (piece_on(sq) == rook)
281 initialKRFile = square_file(sq);
285 else if (token == 'Q')
287 for (Square sq = sqA; sq <= sqH; sq++)
288 if (piece_on(sq) == rook)
291 initialQRFile = square_file(sq);
295 else if (token >= 'A' && token <= 'H')
297 File rookFile = File(token - 'A') + FILE_A;
298 if (rookFile < initialKFile)
301 initialQRFile = rookFile;
306 initialKRFile = rookFile;
315 /// Position::to_fen() returns a FEN representation of the position. In case
316 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
318 const string Position::to_fen() const {
324 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
326 for (File file = FILE_A; file <= FILE_H; file++)
328 sq = make_square(file, rank);
330 if (square_is_occupied(sq))
333 fen += pieceLetters.from_piece(piece_on(sq));
343 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
344 fen.erase(--fen.end());
345 fen += (sideToMove == WHITE ? " w " : " b ");
347 if (st->castleRights != NO_CASTLES)
349 const bool Chess960 = initialKFile != FILE_E
350 || initialQRFile != FILE_A
351 || initialKRFile != FILE_H;
353 if (can_castle_kingside(WHITE))
354 fen += Chess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
356 if (can_castle_queenside(WHITE))
357 fen += Chess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
359 if (can_castle_kingside(BLACK))
360 fen += Chess960 ? file_to_char(initialKRFile) : 'k';
362 if (can_castle_queenside(BLACK))
363 fen += Chess960 ? file_to_char(initialQRFile) : 'q';
367 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
372 /// Position::print() prints an ASCII representation of the position to
373 /// the standard output. If a move is given then also the san is print.
375 void Position::print(Move m) const {
377 static const string pieceLetters = " PNBRQK PNBRQK .";
379 // Check for reentrancy, as example when called from inside
380 // MovePicker that is used also here in move_to_san()
384 RequestPending = true;
389 Position p(*this, thread());
390 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
391 cout << "Move is: " << col << move_to_san(p, m) << endl;
393 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
395 cout << "+---+---+---+---+---+---+---+---+" << endl;
396 for (File file = FILE_A; file <= FILE_H; file++)
398 Square sq = make_square(file, rank);
399 Piece piece = piece_on(sq);
400 if (piece == EMPTY && square_color(sq) == WHITE)
403 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
404 cout << '|' << col << pieceLetters[piece] << col;
408 cout << "+---+---+---+---+---+---+---+---+" << endl
409 << "Fen is: " << to_fen() << endl
410 << "Key is: " << st->key << endl;
412 RequestPending = false;
416 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
417 /// king) pieces for the given color and for the given pinner type. Or, when
418 /// template parameter FindPinned is false, the pieces of the given color
419 /// candidate for a discovery check against the enemy king.
420 /// Bitboard checkersBB must be already updated when looking for pinners.
422 template<bool FindPinned>
423 Bitboard Position::hidden_checkers(Color c) const {
425 Bitboard result = EmptyBoardBB;
426 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
428 // Pinned pieces protect our king, dicovery checks attack
430 Square ksq = king_square(FindPinned ? c : opposite_color(c));
432 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
433 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
435 if (FindPinned && pinners)
436 pinners &= ~st->checkersBB;
440 Square s = pop_1st_bit(&pinners);
441 Bitboard b = squares_between(s, ksq) & occupied_squares();
445 if ( !(b & (b - 1)) // Only one bit set?
446 && (b & pieces_of_color(c))) // Is an our piece?
453 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
454 /// king) pieces for the given color. Note that checkersBB bitboard must
455 /// be already updated.
457 Bitboard Position::pinned_pieces(Color c) const {
459 return hidden_checkers<true>(c);
463 /// Position:discovered_check_candidates() returns a bitboard containing all
464 /// pieces for the given side which are candidates for giving a discovered
465 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
466 /// to be already updated.
468 Bitboard Position::discovered_check_candidates(Color c) const {
470 return hidden_checkers<false>(c);
473 /// Position::attackers_to() computes a bitboard containing all pieces which
474 /// attacks a given square.
476 Bitboard Position::attackers_to(Square s) const {
478 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
479 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
480 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
481 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
482 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
483 | (attacks_from<KING>(s) & pieces(KING));
486 /// Position::attacks_from() computes a bitboard of all attacks
487 /// of a given piece put in a given square.
489 Bitboard Position::attacks_from(Piece p, Square s) const {
491 assert(square_is_ok(s));
495 case WP: return attacks_from<PAWN>(s, WHITE);
496 case BP: return attacks_from<PAWN>(s, BLACK);
497 case WN: case BN: return attacks_from<KNIGHT>(s);
498 case WB: case BB: return attacks_from<BISHOP>(s);
499 case WR: case BR: return attacks_from<ROOK>(s);
500 case WQ: case BQ: return attacks_from<QUEEN>(s);
501 case WK: case BK: return attacks_from<KING>(s);
508 /// Position::move_attacks_square() tests whether a move from the current
509 /// position attacks a given square.
511 bool Position::move_attacks_square(Move m, Square s) const {
513 assert(move_is_ok(m));
514 assert(square_is_ok(s));
516 Square f = move_from(m), t = move_to(m);
518 assert(square_is_occupied(f));
520 if (bit_is_set(attacks_from(piece_on(f), t), s))
523 // Move the piece and scan for X-ray attacks behind it
524 Bitboard occ = occupied_squares();
525 Color us = color_of_piece_on(f);
528 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
529 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
531 // If we have attacks we need to verify that are caused by our move
532 // and are not already existent ones.
533 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
537 /// Position::find_checkers() computes the checkersBB bitboard, which
538 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
539 /// currently works by calling Position::attackers_to, which is probably
540 /// inefficient. Consider rewriting this function to use the last move
541 /// played, like in non-bitboard versions of Glaurung.
543 void Position::find_checkers() {
545 Color us = side_to_move();
546 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
550 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
552 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
555 assert(move_is_ok(m));
556 assert(pinned == pinned_pieces(side_to_move()));
558 // Castling moves are checked for legality during move generation.
559 if (move_is_castle(m))
562 Color us = side_to_move();
563 Square from = move_from(m);
565 assert(color_of_piece_on(from) == us);
566 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
568 // En passant captures are a tricky special case. Because they are
569 // rather uncommon, we do it simply by testing whether the king is attacked
570 // after the move is made
573 Color them = opposite_color(us);
574 Square to = move_to(m);
575 Square capsq = make_square(square_file(to), square_rank(from));
576 Bitboard b = occupied_squares();
577 Square ksq = king_square(us);
579 assert(to == ep_square());
580 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
581 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
582 assert(piece_on(to) == EMPTY);
585 clear_bit(&b, capsq);
588 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
589 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
592 // If the moving piece is a king, check whether the destination
593 // square is attacked by the opponent.
594 if (type_of_piece_on(from) == KING)
595 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
597 // A non-king move is legal if and only if it is not pinned or it
598 // is moving along the ray towards or away from the king.
600 || !bit_is_set(pinned, from)
601 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
605 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
607 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
611 Color us = side_to_move();
612 Square from = move_from(m);
613 Square to = move_to(m);
615 // King moves and en-passant captures are verified in pl_move_is_legal()
616 if (type_of_piece_on(from) == KING || move_is_ep(m))
617 return pl_move_is_legal(m, pinned);
619 Bitboard target = checkers();
620 Square checksq = pop_1st_bit(&target);
622 if (target) // double check ?
625 // Our move must be a blocking evasion or a capture of the checking piece
626 target = squares_between(checksq, king_square(us)) | checkers();
627 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
631 /// Position::move_is_check() tests whether a pseudo-legal move is a check
633 bool Position::move_is_check(Move m) const {
635 return move_is_check(m, CheckInfo(*this));
638 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
641 assert(move_is_ok(m));
642 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
643 assert(color_of_piece_on(move_from(m)) == side_to_move());
644 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
646 Square from = move_from(m);
647 Square to = move_to(m);
648 PieceType pt = type_of_piece_on(from);
651 if (bit_is_set(ci.checkSq[pt], to))
655 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
657 // For pawn and king moves we need to verify also direction
658 if ( (pt != PAWN && pt != KING)
659 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
663 // Can we skip the ugly special cases ?
664 if (!move_is_special(m))
667 Color us = side_to_move();
668 Bitboard b = occupied_squares();
670 // Promotion with check ?
671 if (move_is_promotion(m))
675 switch (move_promotion_piece(m))
678 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
680 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
682 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
684 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
690 // En passant capture with check ? We have already handled the case
691 // of direct checks and ordinary discovered check, the only case we
692 // need to handle is the unusual case of a discovered check through
693 // the captured pawn.
696 Square capsq = make_square(square_file(to), square_rank(from));
698 clear_bit(&b, capsq);
700 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
701 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
704 // Castling with check ?
705 if (move_is_castle(m))
707 Square kfrom, kto, rfrom, rto;
713 kto = relative_square(us, SQ_G1);
714 rto = relative_square(us, SQ_F1);
716 kto = relative_square(us, SQ_C1);
717 rto = relative_square(us, SQ_D1);
719 clear_bit(&b, kfrom);
720 clear_bit(&b, rfrom);
723 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
730 /// Position::do_move() makes a move, and saves all information necessary
731 /// to a StateInfo object. The move is assumed to be legal.
732 /// Pseudo-legal moves should be filtered out before this function is called.
734 void Position::do_move(Move m, StateInfo& newSt) {
737 do_move(m, newSt, ci, move_is_check(m, ci));
740 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
743 assert(move_is_ok(m));
747 // Copy some fields of old state to our new StateInfo object except the
748 // ones which are recalculated from scratch anyway, then switch our state
749 // pointer to point to the new, ready to be updated, state.
750 struct ReducedStateInfo {
751 Key pawnKey, materialKey;
752 int castleRights, rule50, gamePly, pliesFromNull;
758 memcpy(&newSt, st, sizeof(ReducedStateInfo));
762 // Save the current key to the history[] array, in order to be able to
763 // detect repetition draws.
764 history[st->gamePly++] = key;
766 // Update side to move
767 key ^= zobSideToMove;
769 // Increment the 50 moves rule draw counter. Resetting it to zero in the
770 // case of non-reversible moves is taken care of later.
774 if (move_is_castle(m))
781 Color us = side_to_move();
782 Color them = opposite_color(us);
783 Square from = move_from(m);
784 Square to = move_to(m);
785 bool ep = move_is_ep(m);
786 bool pm = move_is_promotion(m);
788 Piece piece = piece_on(from);
789 PieceType pt = type_of_piece(piece);
790 PieceType capture = ep ? PAWN : type_of_piece_on(to);
792 assert(color_of_piece_on(from) == us);
793 assert(color_of_piece_on(to) == them || square_is_empty(to));
794 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
795 assert(!pm || relative_rank(us, to) == RANK_8);
798 do_capture_move(key, capture, them, to, ep);
801 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
803 // Reset en passant square
804 if (st->epSquare != SQ_NONE)
806 key ^= zobEp[st->epSquare];
807 st->epSquare = SQ_NONE;
810 // Update castle rights, try to shortcut a common case
811 int cm = castleRightsMask[from] & castleRightsMask[to];
812 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
814 key ^= zobCastle[st->castleRights];
815 st->castleRights &= castleRightsMask[from];
816 st->castleRights &= castleRightsMask[to];
817 key ^= zobCastle[st->castleRights];
820 // Prefetch TT access as soon as we know key is updated
821 prefetch((char*)TT.first_entry(key));
824 Bitboard move_bb = make_move_bb(from, to);
825 do_move_bb(&(byColorBB[us]), move_bb);
826 do_move_bb(&(byTypeBB[pt]), move_bb);
827 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
829 board[to] = board[from];
832 // Update piece lists, note that index[from] is not updated and
833 // becomes stale. This works as long as index[] is accessed just
834 // by known occupied squares.
835 index[to] = index[from];
836 pieceList[us][pt][index[to]] = to;
838 // If the moving piece was a pawn do some special extra work
841 // Reset rule 50 draw counter
844 // Update pawn hash key
845 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
847 // Set en passant square, only if moved pawn can be captured
848 if ((to ^ from) == 16)
850 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
852 st->epSquare = Square((int(from) + int(to)) / 2);
853 key ^= zobEp[st->epSquare];
857 if (pm) // promotion ?
859 PieceType promotion = move_promotion_piece(m);
861 assert(promotion >= KNIGHT && promotion <= QUEEN);
863 // Insert promoted piece instead of pawn
864 clear_bit(&(byTypeBB[PAWN]), to);
865 set_bit(&(byTypeBB[promotion]), to);
866 board[to] = piece_of_color_and_type(us, promotion);
868 // Update piece counts
869 pieceCount[us][promotion]++;
870 pieceCount[us][PAWN]--;
872 // Update material key
873 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
874 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
876 // Update piece lists, move the last pawn at index[to] position
877 // and shrink the list. Add a new promotion piece to the list.
878 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
879 index[lastPawnSquare] = index[to];
880 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
881 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
882 index[to] = pieceCount[us][promotion] - 1;
883 pieceList[us][promotion][index[to]] = to;
885 // Partially revert hash keys update
886 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
887 st->pawnKey ^= zobrist[us][PAWN][to];
889 // Partially revert and update incremental scores
890 st->value -= pst(us, PAWN, to);
891 st->value += pst(us, promotion, to);
894 st->npMaterial[us] += piece_value_midgame(promotion);
898 // Update incremental scores
899 st->value += pst_delta(piece, from, to);
902 st->capture = capture;
904 // Update the key with the final value
907 // Update checkers bitboard, piece must be already moved
908 st->checkersBB = EmptyBoardBB;
913 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
917 if (bit_is_set(ci.checkSq[pt], to))
918 st->checkersBB = SetMaskBB[to];
921 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
924 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
927 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
933 sideToMove = opposite_color(sideToMove);
934 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
940 /// Position::do_capture_move() is a private method used to update captured
941 /// piece info. It is called from the main Position::do_move function.
943 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
945 assert(capture != KING);
949 // If the captured piece was a pawn, update pawn hash key,
950 // otherwise update non-pawn material.
953 if (ep) // en passant ?
955 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
957 assert(to == st->epSquare);
958 assert(relative_rank(opposite_color(them), to) == RANK_6);
959 assert(piece_on(to) == EMPTY);
960 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
962 board[capsq] = EMPTY;
964 st->pawnKey ^= zobrist[them][PAWN][capsq];
967 st->npMaterial[them] -= piece_value_midgame(capture);
969 // Remove captured piece
970 clear_bit(&(byColorBB[them]), capsq);
971 clear_bit(&(byTypeBB[capture]), capsq);
972 clear_bit(&(byTypeBB[0]), capsq);
975 key ^= zobrist[them][capture][capsq];
977 // Update incremental scores
978 st->value -= pst(them, capture, capsq);
980 // Update piece count
981 pieceCount[them][capture]--;
983 // Update material hash key
984 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
986 // Update piece list, move the last piece at index[capsq] position
988 // WARNING: This is a not perfectly revresible operation. When we
989 // will reinsert the captured piece in undo_move() we will put it
990 // at the end of the list and not in its original place, it means
991 // index[] and pieceList[] are not guaranteed to be invariant to a
992 // do_move() + undo_move() sequence.
993 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
994 index[lastPieceSquare] = index[capsq];
995 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
996 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
998 // Reset rule 50 counter
1003 /// Position::do_castle_move() is a private method used to make a castling
1004 /// move. It is called from the main Position::do_move function. Note that
1005 /// castling moves are encoded as "king captures friendly rook" moves, for
1006 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1008 void Position::do_castle_move(Move m) {
1010 assert(move_is_ok(m));
1011 assert(move_is_castle(m));
1013 Color us = side_to_move();
1014 Color them = opposite_color(us);
1016 // Reset capture field
1017 st->capture = NO_PIECE_TYPE;
1019 // Find source squares for king and rook
1020 Square kfrom = move_from(m);
1021 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1024 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1025 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1027 // Find destination squares for king and rook
1028 if (rfrom > kfrom) // O-O
1030 kto = relative_square(us, SQ_G1);
1031 rto = relative_square(us, SQ_F1);
1033 kto = relative_square(us, SQ_C1);
1034 rto = relative_square(us, SQ_D1);
1037 // Remove pieces from source squares:
1038 clear_bit(&(byColorBB[us]), kfrom);
1039 clear_bit(&(byTypeBB[KING]), kfrom);
1040 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1041 clear_bit(&(byColorBB[us]), rfrom);
1042 clear_bit(&(byTypeBB[ROOK]), rfrom);
1043 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1045 // Put pieces on destination squares:
1046 set_bit(&(byColorBB[us]), kto);
1047 set_bit(&(byTypeBB[KING]), kto);
1048 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1049 set_bit(&(byColorBB[us]), rto);
1050 set_bit(&(byTypeBB[ROOK]), rto);
1051 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1053 // Update board array
1054 Piece king = piece_of_color_and_type(us, KING);
1055 Piece rook = piece_of_color_and_type(us, ROOK);
1056 board[kfrom] = board[rfrom] = EMPTY;
1060 // Update piece lists
1061 pieceList[us][KING][index[kfrom]] = kto;
1062 pieceList[us][ROOK][index[rfrom]] = rto;
1063 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1064 index[kto] = index[kfrom];
1067 // Update incremental scores
1068 st->value += pst_delta(king, kfrom, kto);
1069 st->value += pst_delta(rook, rfrom, rto);
1072 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1073 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1075 // Clear en passant square
1076 if (st->epSquare != SQ_NONE)
1078 st->key ^= zobEp[st->epSquare];
1079 st->epSquare = SQ_NONE;
1082 // Update castling rights
1083 st->key ^= zobCastle[st->castleRights];
1084 st->castleRights &= castleRightsMask[kfrom];
1085 st->key ^= zobCastle[st->castleRights];
1087 // Reset rule 50 counter
1090 // Update checkers BB
1091 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1094 sideToMove = opposite_color(sideToMove);
1095 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1101 /// Position::undo_move() unmakes a move. When it returns, the position should
1102 /// be restored to exactly the same state as before the move was made.
1104 void Position::undo_move(Move m) {
1107 assert(move_is_ok(m));
1109 sideToMove = opposite_color(sideToMove);
1111 if (move_is_castle(m))
1113 undo_castle_move(m);
1117 Color us = side_to_move();
1118 Color them = opposite_color(us);
1119 Square from = move_from(m);
1120 Square to = move_to(m);
1121 bool ep = move_is_ep(m);
1122 bool pm = move_is_promotion(m);
1124 PieceType pt = type_of_piece_on(to);
1126 assert(square_is_empty(from));
1127 assert(color_of_piece_on(to) == us);
1128 assert(!pm || relative_rank(us, to) == RANK_8);
1129 assert(!ep || to == st->previous->epSquare);
1130 assert(!ep || relative_rank(us, to) == RANK_6);
1131 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1133 if (pm) // promotion ?
1135 PieceType promotion = move_promotion_piece(m);
1138 assert(promotion >= KNIGHT && promotion <= QUEEN);
1139 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1141 // Replace promoted piece with a pawn
1142 clear_bit(&(byTypeBB[promotion]), to);
1143 set_bit(&(byTypeBB[PAWN]), to);
1145 // Update piece counts
1146 pieceCount[us][promotion]--;
1147 pieceCount[us][PAWN]++;
1149 // Update piece list replacing promotion piece with a pawn
1150 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1151 index[lastPromotionSquare] = index[to];
1152 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1153 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1154 index[to] = pieceCount[us][PAWN] - 1;
1155 pieceList[us][PAWN][index[to]] = to;
1158 // Put the piece back at the source square
1159 Bitboard move_bb = make_move_bb(to, from);
1160 do_move_bb(&(byColorBB[us]), move_bb);
1161 do_move_bb(&(byTypeBB[pt]), move_bb);
1162 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1164 board[from] = piece_of_color_and_type(us, pt);
1167 // Update piece list
1168 index[from] = index[to];
1169 pieceList[us][pt][index[from]] = from;
1176 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1178 assert(st->capture != KING);
1179 assert(!ep || square_is_empty(capsq));
1181 // Restore the captured piece
1182 set_bit(&(byColorBB[them]), capsq);
1183 set_bit(&(byTypeBB[st->capture]), capsq);
1184 set_bit(&(byTypeBB[0]), capsq);
1186 board[capsq] = piece_of_color_and_type(them, st->capture);
1188 // Update piece count
1189 pieceCount[them][st->capture]++;
1191 // Update piece list, add a new captured piece in capsq square
1192 index[capsq] = pieceCount[them][st->capture] - 1;
1193 pieceList[them][st->capture][index[capsq]] = capsq;
1196 // Finally point our state pointer back to the previous state
1203 /// Position::undo_castle_move() is a private method used to unmake a castling
1204 /// move. It is called from the main Position::undo_move function. Note that
1205 /// castling moves are encoded as "king captures friendly rook" moves, for
1206 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1208 void Position::undo_castle_move(Move m) {
1210 assert(move_is_ok(m));
1211 assert(move_is_castle(m));
1213 // When we have arrived here, some work has already been done by
1214 // Position::undo_move. In particular, the side to move has been switched,
1215 // so the code below is correct.
1216 Color us = side_to_move();
1218 // Find source squares for king and rook
1219 Square kfrom = move_from(m);
1220 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1223 // Find destination squares for king and rook
1224 if (rfrom > kfrom) // O-O
1226 kto = relative_square(us, SQ_G1);
1227 rto = relative_square(us, SQ_F1);
1229 kto = relative_square(us, SQ_C1);
1230 rto = relative_square(us, SQ_D1);
1233 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1234 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1236 // Remove pieces from destination squares:
1237 clear_bit(&(byColorBB[us]), kto);
1238 clear_bit(&(byTypeBB[KING]), kto);
1239 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1240 clear_bit(&(byColorBB[us]), rto);
1241 clear_bit(&(byTypeBB[ROOK]), rto);
1242 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1244 // Put pieces on source squares:
1245 set_bit(&(byColorBB[us]), kfrom);
1246 set_bit(&(byTypeBB[KING]), kfrom);
1247 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1248 set_bit(&(byColorBB[us]), rfrom);
1249 set_bit(&(byTypeBB[ROOK]), rfrom);
1250 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1253 board[rto] = board[kto] = EMPTY;
1254 board[rfrom] = piece_of_color_and_type(us, ROOK);
1255 board[kfrom] = piece_of_color_and_type(us, KING);
1257 // Update piece lists
1258 pieceList[us][KING][index[kto]] = kfrom;
1259 pieceList[us][ROOK][index[rto]] = rfrom;
1260 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1261 index[kfrom] = index[kto];
1264 // Finally point our state pointer back to the previous state
1271 /// Position::do_null_move makes() a "null move": It switches the side to move
1272 /// and updates the hash key without executing any move on the board.
1274 void Position::do_null_move(StateInfo& backupSt) {
1277 assert(!is_check());
1279 // Back up the information necessary to undo the null move to the supplied
1280 // StateInfo object.
1281 // Note that differently from normal case here backupSt is actually used as
1282 // a backup storage not as a new state to be used.
1283 backupSt.key = st->key;
1284 backupSt.epSquare = st->epSquare;
1285 backupSt.value = st->value;
1286 backupSt.previous = st->previous;
1287 backupSt.pliesFromNull = st->pliesFromNull;
1288 st->previous = &backupSt;
1290 // Save the current key to the history[] array, in order to be able to
1291 // detect repetition draws.
1292 history[st->gamePly++] = st->key;
1294 // Update the necessary information
1295 if (st->epSquare != SQ_NONE)
1296 st->key ^= zobEp[st->epSquare];
1298 st->key ^= zobSideToMove;
1299 prefetch((char*)TT.first_entry(st->key));
1301 sideToMove = opposite_color(sideToMove);
1302 st->epSquare = SQ_NONE;
1304 st->pliesFromNull = 0;
1305 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1309 /// Position::undo_null_move() unmakes a "null move".
1311 void Position::undo_null_move() {
1314 assert(!is_check());
1316 // Restore information from the our backup StateInfo object
1317 StateInfo* backupSt = st->previous;
1318 st->key = backupSt->key;
1319 st->epSquare = backupSt->epSquare;
1320 st->value = backupSt->value;
1321 st->previous = backupSt->previous;
1322 st->pliesFromNull = backupSt->pliesFromNull;
1324 // Update the necessary information
1325 sideToMove = opposite_color(sideToMove);
1331 /// Position::see() is a static exchange evaluator: It tries to estimate the
1332 /// material gain or loss resulting from a move. There are three versions of
1333 /// this function: One which takes a destination square as input, one takes a
1334 /// move, and one which takes a 'from' and a 'to' square. The function does
1335 /// not yet understand promotions captures.
1337 int Position::see(Square to) const {
1339 assert(square_is_ok(to));
1340 return see(SQ_NONE, to);
1343 int Position::see(Move m) const {
1345 assert(move_is_ok(m));
1346 return see(move_from(m), move_to(m));
1349 int Position::see_sign(Move m) const {
1351 assert(move_is_ok(m));
1353 Square from = move_from(m);
1354 Square to = move_to(m);
1356 // Early return if SEE cannot be negative because captured piece value
1357 // is not less then capturing one. Note that king moves always return
1358 // here because king midgame value is set to 0.
1359 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1362 return see(from, to);
1365 int Position::see(Square from, Square to) const {
1368 static const int seeValues[18] = {
1369 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1370 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1371 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1372 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1376 Bitboard attackers, stmAttackers, b;
1378 assert(square_is_ok(from) || from == SQ_NONE);
1379 assert(square_is_ok(to));
1381 // Initialize colors
1382 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1383 Color them = opposite_color(us);
1385 // Initialize pieces
1386 Piece piece = piece_on(from);
1387 Piece capture = piece_on(to);
1388 Bitboard occ = occupied_squares();
1390 // King cannot be recaptured
1391 if (type_of_piece(piece) == KING)
1392 return seeValues[capture];
1394 // Handle en passant moves
1395 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1397 assert(capture == EMPTY);
1399 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1400 capture = piece_on(capQq);
1401 assert(type_of_piece_on(capQq) == PAWN);
1403 // Remove the captured pawn
1404 clear_bit(&occ, capQq);
1409 // Find all attackers to the destination square, with the moving piece
1410 // removed, but possibly an X-ray attacker added behind it.
1411 clear_bit(&occ, from);
1412 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1413 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1414 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1415 | (attacks_from<KING>(to) & pieces(KING))
1416 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1417 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1419 if (from != SQ_NONE)
1422 // If we don't have any attacker we are finished
1423 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1426 // Locate the least valuable attacker to the destination square
1427 // and use it to initialize from square.
1428 stmAttackers = attackers & pieces_of_color(us);
1430 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1433 from = first_1(stmAttackers & pieces(pt));
1434 piece = piece_on(from);
1437 // If the opponent has no attackers we are finished
1438 stmAttackers = attackers & pieces_of_color(them);
1440 return seeValues[capture];
1442 attackers &= occ; // Remove the moving piece
1444 // The destination square is defended, which makes things rather more
1445 // difficult to compute. We proceed by building up a "swap list" containing
1446 // the material gain or loss at each stop in a sequence of captures to the
1447 // destination square, where the sides alternately capture, and always
1448 // capture with the least valuable piece. After each capture, we look for
1449 // new X-ray attacks from behind the capturing piece.
1450 int lastCapturingPieceValue = seeValues[piece];
1451 int swapList[32], n = 1;
1455 swapList[0] = seeValues[capture];
1458 // Locate the least valuable attacker for the side to move. The loop
1459 // below looks like it is potentially infinite, but it isn't. We know
1460 // that the side to move still has at least one attacker left.
1461 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1464 // Remove the attacker we just found from the 'attackers' bitboard,
1465 // and scan for new X-ray attacks behind the attacker.
1466 b = stmAttackers & pieces(pt);
1467 occ ^= (b & (~b + 1));
1468 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1469 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1473 // Add the new entry to the swap list
1475 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1478 // Remember the value of the capturing piece, and change the side to move
1479 // before beginning the next iteration
1480 lastCapturingPieceValue = seeValues[pt];
1481 c = opposite_color(c);
1482 stmAttackers = attackers & pieces_of_color(c);
1484 // Stop after a king capture
1485 if (pt == KING && stmAttackers)
1488 swapList[n++] = QueenValueMidgame*10;
1491 } while (stmAttackers);
1493 // Having built the swap list, we negamax through it to find the best
1494 // achievable score from the point of view of the side to move
1496 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1502 /// Position::clear() erases the position object to a pristine state, with an
1503 /// empty board, white to move, and no castling rights.
1505 void Position::clear() {
1508 memset(st, 0, sizeof(StateInfo));
1509 st->epSquare = SQ_NONE;
1511 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1512 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1513 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1514 memset(index, 0, sizeof(int) * 64);
1516 for (int i = 0; i < 64; i++)
1519 for (int i = 0; i < 8; i++)
1520 for (int j = 0; j < 16; j++)
1521 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1523 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1524 castleRightsMask[sq] = ALL_CASTLES;
1527 initialKFile = FILE_E;
1528 initialKRFile = FILE_H;
1529 initialQRFile = FILE_A;
1533 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1534 /// UCI interface code, whenever a non-reversible move is made in a
1535 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1536 /// for the program to handle games of arbitrary length, as long as the GUI
1537 /// handles draws by the 50 move rule correctly.
1539 void Position::reset_game_ply() {
1545 /// Position::put_piece() puts a piece on the given square of the board,
1546 /// updating the board array, bitboards, and piece counts.
1548 void Position::put_piece(Piece p, Square s) {
1550 Color c = color_of_piece(p);
1551 PieceType pt = type_of_piece(p);
1554 index[s] = pieceCount[c][pt];
1555 pieceList[c][pt][index[s]] = s;
1557 set_bit(&(byTypeBB[pt]), s);
1558 set_bit(&(byColorBB[c]), s);
1559 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1561 pieceCount[c][pt]++;
1565 /// Position::allow_oo() gives the given side the right to castle kingside.
1566 /// Used when setting castling rights during parsing of FEN strings.
1568 void Position::allow_oo(Color c) {
1570 st->castleRights |= (1 + int(c));
1574 /// Position::allow_ooo() gives the given side the right to castle queenside.
1575 /// Used when setting castling rights during parsing of FEN strings.
1577 void Position::allow_ooo(Color c) {
1579 st->castleRights |= (4 + 4*int(c));
1583 /// Position::compute_key() computes the hash key of the position. The hash
1584 /// key is usually updated incrementally as moves are made and unmade, the
1585 /// compute_key() function is only used when a new position is set up, and
1586 /// to verify the correctness of the hash key when running in debug mode.
1588 Key Position::compute_key() const {
1590 Key result = Key(0ULL);
1592 for (Square s = SQ_A1; s <= SQ_H8; s++)
1593 if (square_is_occupied(s))
1594 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1596 if (ep_square() != SQ_NONE)
1597 result ^= zobEp[ep_square()];
1599 result ^= zobCastle[st->castleRights];
1600 if (side_to_move() == BLACK)
1601 result ^= zobSideToMove;
1607 /// Position::compute_pawn_key() computes the hash key of the position. The
1608 /// hash key is usually updated incrementally as moves are made and unmade,
1609 /// the compute_pawn_key() function is only used when a new position is set
1610 /// up, and to verify the correctness of the pawn hash key when running in
1613 Key Position::compute_pawn_key() const {
1615 Key result = Key(0ULL);
1619 for (Color c = WHITE; c <= BLACK; c++)
1621 b = pieces(PAWN, c);
1624 s = pop_1st_bit(&b);
1625 result ^= zobrist[c][PAWN][s];
1632 /// Position::compute_material_key() computes the hash key of the position.
1633 /// The hash key is usually updated incrementally as moves are made and unmade,
1634 /// the compute_material_key() function is only used when a new position is set
1635 /// up, and to verify the correctness of the material hash key when running in
1638 Key Position::compute_material_key() const {
1640 Key result = Key(0ULL);
1641 for (Color c = WHITE; c <= BLACK; c++)
1642 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1644 int count = piece_count(c, pt);
1645 for (int i = 0; i < count; i++)
1646 result ^= zobrist[c][pt][i];
1652 /// Position::compute_value() compute the incremental scores for the middle
1653 /// game and the endgame. These functions are used to initialize the incremental
1654 /// scores when a new position is set up, and to verify that the scores are correctly
1655 /// updated by do_move and undo_move when the program is running in debug mode.
1656 Score Position::compute_value() const {
1658 Score result = make_score(0, 0);
1662 for (Color c = WHITE; c <= BLACK; c++)
1663 for (PieceType pt = PAWN; pt <= KING; pt++)
1668 s = pop_1st_bit(&b);
1669 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1670 result += pst(c, pt, s);
1674 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1679 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1680 /// game material score for the given side. Material scores are updated
1681 /// incrementally during the search, this function is only used while
1682 /// initializing a new Position object.
1684 Value Position::compute_non_pawn_material(Color c) const {
1686 Value result = Value(0);
1688 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1690 Bitboard b = pieces(pt, c);
1693 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1695 result += piece_value_midgame(pt);
1702 /// Position::is_draw() tests whether the position is drawn by material,
1703 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1704 /// must be done by the search.
1705 // FIXME: Currently we are not handling 50 move rule correctly when in check
1707 bool Position::is_draw() const {
1709 // Draw by material?
1711 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1714 // Draw by the 50 moves rule?
1715 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1718 // Draw by repetition?
1719 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1720 if (history[st->gamePly - i] == st->key)
1727 /// Position::is_mate() returns true or false depending on whether the
1728 /// side to move is checkmated.
1730 bool Position::is_mate() const {
1732 MoveStack moves[256];
1733 return is_check() && (generate_moves(*this, moves, false) == moves);
1737 /// Position::has_mate_threat() tests whether a given color has a mate in one
1738 /// from the current position.
1740 bool Position::has_mate_threat(Color c) {
1743 Color stm = side_to_move();
1748 // If the input color is not equal to the side to move, do a null move
1752 MoveStack mlist[120];
1753 bool result = false;
1754 Bitboard pinned = pinned_pieces(sideToMove);
1756 // Generate pseudo-legal non-capture and capture check moves
1757 MoveStack* last = generate_non_capture_checks(*this, mlist);
1758 last = generate_captures(*this, last);
1760 // Loop through the moves, and see if one of them is mate
1761 for (MoveStack* cur = mlist; cur != last; cur++)
1763 Move move = cur->move;
1764 if (!pl_move_is_legal(move, pinned))
1774 // Undo null move, if necessary
1782 /// Position::init_zobrist() is a static member function which initializes the
1783 /// various arrays used to compute hash keys.
1785 void Position::init_zobrist() {
1787 for (int i = 0; i < 2; i++)
1788 for (int j = 0; j < 8; j++)
1789 for (int k = 0; k < 64; k++)
1790 zobrist[i][j][k] = Key(genrand_int64());
1792 for (int i = 0; i < 64; i++)
1793 zobEp[i] = Key(genrand_int64());
1795 for (int i = 0; i < 16; i++)
1796 zobCastle[i] = genrand_int64();
1798 zobSideToMove = genrand_int64();
1799 zobExclusion = genrand_int64();
1803 /// Position::init_piece_square_tables() initializes the piece square tables.
1804 /// This is a two-step operation:
1805 /// First, the white halves of the tables are
1806 /// copied from the MgPST[][] and EgPST[][] arrays.
1807 /// Second, the black halves of the tables are initialized by mirroring
1808 /// and changing the sign of the corresponding white scores.
1810 void Position::init_piece_square_tables() {
1812 for (Square s = SQ_A1; s <= SQ_H8; s++)
1813 for (Piece p = WP; p <= WK; p++)
1814 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1816 for (Square s = SQ_A1; s <= SQ_H8; s++)
1817 for (Piece p = BP; p <= BK; p++)
1818 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1822 /// Position::flipped_copy() makes a copy of the input position, but with
1823 /// the white and black sides reversed. This is only useful for debugging,
1824 /// especially for finding evaluation symmetry bugs.
1826 void Position::flipped_copy(const Position& pos) {
1828 assert(pos.is_ok());
1831 threadID = pos.thread();
1834 for (Square s = SQ_A1; s <= SQ_H8; s++)
1835 if (!pos.square_is_empty(s))
1836 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1839 sideToMove = opposite_color(pos.side_to_move());
1842 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1843 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1844 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1845 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1847 initialKFile = pos.initialKFile;
1848 initialKRFile = pos.initialKRFile;
1849 initialQRFile = pos.initialQRFile;
1851 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1852 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1853 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1854 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1855 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1856 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1858 // En passant square
1859 if (pos.st->epSquare != SQ_NONE)
1860 st->epSquare = flip_square(pos.st->epSquare);
1866 st->key = compute_key();
1867 st->pawnKey = compute_pawn_key();
1868 st->materialKey = compute_material_key();
1870 // Incremental scores
1871 st->value = compute_value();
1874 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1875 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1881 /// Position::is_ok() performs some consitency checks for the position object.
1882 /// This is meant to be helpful when debugging.
1884 bool Position::is_ok(int* failedStep) const {
1886 // What features of the position should be verified?
1887 static const bool debugBitboards = false;
1888 static const bool debugKingCount = false;
1889 static const bool debugKingCapture = false;
1890 static const bool debugCheckerCount = false;
1891 static const bool debugKey = false;
1892 static const bool debugMaterialKey = false;
1893 static const bool debugPawnKey = false;
1894 static const bool debugIncrementalEval = false;
1895 static const bool debugNonPawnMaterial = false;
1896 static const bool debugPieceCounts = false;
1897 static const bool debugPieceList = false;
1898 static const bool debugCastleSquares = false;
1900 if (failedStep) *failedStep = 1;
1903 if (!color_is_ok(side_to_move()))
1906 // Are the king squares in the position correct?
1907 if (failedStep) (*failedStep)++;
1908 if (piece_on(king_square(WHITE)) != WK)
1911 if (failedStep) (*failedStep)++;
1912 if (piece_on(king_square(BLACK)) != BK)
1916 if (failedStep) (*failedStep)++;
1917 if (!file_is_ok(initialKRFile))
1920 if (!file_is_ok(initialQRFile))
1923 // Do both sides have exactly one king?
1924 if (failedStep) (*failedStep)++;
1927 int kingCount[2] = {0, 0};
1928 for (Square s = SQ_A1; s <= SQ_H8; s++)
1929 if (type_of_piece_on(s) == KING)
1930 kingCount[color_of_piece_on(s)]++;
1932 if (kingCount[0] != 1 || kingCount[1] != 1)
1936 // Can the side to move capture the opponent's king?
1937 if (failedStep) (*failedStep)++;
1938 if (debugKingCapture)
1940 Color us = side_to_move();
1941 Color them = opposite_color(us);
1942 Square ksq = king_square(them);
1943 if (attackers_to(ksq) & pieces_of_color(us))
1947 // Is there more than 2 checkers?
1948 if (failedStep) (*failedStep)++;
1949 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1953 if (failedStep) (*failedStep)++;
1956 // The intersection of the white and black pieces must be empty
1957 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1960 // The union of the white and black pieces must be equal to all
1962 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1965 // Separate piece type bitboards must have empty intersections
1966 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1967 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1968 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1972 // En passant square OK?
1973 if (failedStep) (*failedStep)++;
1974 if (ep_square() != SQ_NONE)
1976 // The en passant square must be on rank 6, from the point of view of the
1978 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1983 if (failedStep) (*failedStep)++;
1984 if (debugKey && st->key != compute_key())
1987 // Pawn hash key OK?
1988 if (failedStep) (*failedStep)++;
1989 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1992 // Material hash key OK?
1993 if (failedStep) (*failedStep)++;
1994 if (debugMaterialKey && st->materialKey != compute_material_key())
1997 // Incremental eval OK?
1998 if (failedStep) (*failedStep)++;
1999 if (debugIncrementalEval && st->value != compute_value())
2002 // Non-pawn material OK?
2003 if (failedStep) (*failedStep)++;
2004 if (debugNonPawnMaterial)
2006 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2009 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2014 if (failedStep) (*failedStep)++;
2015 if (debugPieceCounts)
2016 for (Color c = WHITE; c <= BLACK; c++)
2017 for (PieceType pt = PAWN; pt <= KING; pt++)
2018 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2021 if (failedStep) (*failedStep)++;
2024 for (Color c = WHITE; c <= BLACK; c++)
2025 for (PieceType pt = PAWN; pt <= KING; pt++)
2026 for (int i = 0; i < pieceCount[c][pt]; i++)
2028 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2031 if (index[piece_list(c, pt, i)] != i)
2036 if (failedStep) (*failedStep)++;
2037 if (debugCastleSquares) {
2038 for (Color c = WHITE; c <= BLACK; c++) {
2039 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2041 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2044 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2046 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2048 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2050 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2054 if (failedStep) *failedStep = 0;