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"
49 //// Position's static data definitions
52 Key Position::zobrist[2][8][64];
53 Key Position::zobEp[64];
54 Key Position::zobCastle[16];
55 Key Position::zobSideToMove;
56 Key Position::zobExclusion;
58 Score Position::PieceSquareTable[16][64];
60 // Material values arrays, indexed by Piece
61 const Value Position::PieceValueMidgame[17] = {
63 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
64 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
65 VALUE_ZERO, VALUE_ZERO,
66 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
67 RookValueMidgame, QueenValueMidgame
70 const Value Position::PieceValueEndgame[17] = {
72 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
73 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
74 VALUE_ZERO, VALUE_ZERO,
75 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
76 RookValueEndgame, QueenValueEndgame
79 // Material values array used by SEE, indexed by PieceType
80 const Value Position::seeValues[] = {
82 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
83 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
89 // Bonus for having the side to move (modified by Joona Kiiski)
90 const Score TempoValue = make_score(48, 22);
92 bool isZero(char c) { return c == '0'; }
94 struct PieceLetters : public std::map<char, Piece> {
98 operator[]('K') = WK; operator[]('k') = BK;
99 operator[]('Q') = WQ; operator[]('q') = BQ;
100 operator[]('R') = WR; operator[]('r') = BR;
101 operator[]('B') = WB; operator[]('b') = BB;
102 operator[]('N') = WN; operator[]('n') = BN;
103 operator[]('P') = WP; operator[]('p') = BP;
104 operator[](' ') = PIECE_NONE; operator[]('.') = PIECE_NONE_DARK_SQ;
107 char from_piece(Piece p) const {
109 std::map<char, Piece>::const_iterator it;
110 for (it = begin(); it != end(); ++it)
123 CheckInfo::CheckInfo(const Position& pos) {
125 Color us = pos.side_to_move();
126 Color them = opposite_color(us);
128 ksq = pos.king_square(them);
129 dcCandidates = pos.discovered_check_candidates(us);
131 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
132 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
133 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
134 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
135 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
136 checkSq[KING] = EmptyBoardBB;
140 /// Position c'tors. Here we always create a copy of the original position
141 /// or the FEN string, we want the new born Position object do not depend
142 /// on any external data so we detach state pointer from the source one.
144 Position::Position(const Position& pos, int th) {
146 memcpy(this, &pos, sizeof(Position));
147 detach(); // Always detach() in copy c'tor to avoid surprises
152 Position::Position(const string& fen, int th) {
159 /// Position::detach() copies the content of the current state and castling
160 /// masks inside the position itself. This is needed when the st pointee could
161 /// become stale, as example because the caller is about to going out of scope.
163 void Position::detach() {
167 st->previous = NULL; // as a safe guard
171 /// Position::from_fen() initializes the position object with the given FEN
172 /// string. This function is not very robust - make sure that input FENs are
173 /// correct (this is assumed to be the responsibility of the GUI).
175 void Position::from_fen(const string& fen) {
177 A FEN string defines a particular position using only the ASCII character set.
179 A FEN string contains six fields. The separator between fields is a space. The fields are:
181 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
182 with rank 1; within each rank, the contents of each square are described from file a through file h.
183 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
184 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
185 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
186 of blank squares), and "/" separate ranks.
188 2) Active color. "w" means white moves next, "b" means black.
190 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
191 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
192 kingside), and/or "q" (Black can castle queenside).
194 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
195 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
196 regardless of whether there is a pawn in position to make an en passant capture.
198 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
199 to determine if a draw can be claimed under the fifty-move rule.
201 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
205 std::istringstream ss(fen);
211 // 1. Piece placement field
212 while (ss.get(token) && token != ' ')
216 file += File(token - '0'); // Skip the given number of files
219 else if (token == '/')
226 if (pieceLetters.find(token) == pieceLetters.end())
229 put_piece(pieceLetters[token], make_square(file, rank));
234 if (!ss.get(token) || (token != 'w' && token != 'b'))
237 sideToMove = (token == 'w' ? WHITE : BLACK);
239 if (!ss.get(token) || token != ' ')
242 // 3. Castling availability
243 while (ss.get(token) && token != ' ')
248 if (!set_castling_rights(token))
252 // 4. En passant square -- ignore if no capture is possible
254 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
255 && (ss.get(row) && (row == '3' || row == '6')))
257 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
258 Color them = opposite_color(sideToMove);
260 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
261 st->epSquare = fenEpSquare;
264 // 5-6. Halfmove clock and fullmove number are not parsed
266 // Various initialisations
267 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
268 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
269 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
270 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
271 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
272 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
274 isChess960 = initialKFile != FILE_E
275 || initialQRFile != FILE_A
276 || initialKRFile != FILE_H;
280 st->key = compute_key();
281 st->pawnKey = compute_pawn_key();
282 st->materialKey = compute_material_key();
283 st->value = compute_value();
284 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
285 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
289 cout << "Error in FEN string: " << fen << endl;
293 /// Position::set_castling_rights() sets castling parameters castling avaiability.
294 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
295 /// that uses the letters of the columns on which the rooks began the game instead
296 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
297 /// associated with the castling right, the traditional castling tag will be replaced
298 /// by the file letter of the involved rook as for the Shredder-FEN.
300 bool Position::set_castling_rights(char token) {
302 Color c = token >= 'a' ? BLACK : WHITE;
303 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
304 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
305 Piece rook = (c == WHITE ? WR : BR);
307 initialKFile = square_file(king_square(c));
308 token = char(toupper(token));
312 for (Square sq = sqH; sq >= sqA; sq--)
313 if (piece_on(sq) == rook)
316 initialKRFile = square_file(sq);
320 else if (token == 'Q')
322 for (Square sq = sqA; sq <= sqH; sq++)
323 if (piece_on(sq) == rook)
326 initialQRFile = square_file(sq);
330 else if (token >= 'A' && token <= 'H')
332 File rookFile = File(token - 'A') + FILE_A;
333 if (rookFile < initialKFile)
336 initialQRFile = rookFile;
341 initialKRFile = rookFile;
350 /// Position::to_fen() returns a FEN representation of the position. In case
351 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
353 const string Position::to_fen() const {
359 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
361 for (File file = FILE_A; file <= FILE_H; file++)
363 sq = make_square(file, rank);
365 if (square_is_occupied(sq))
368 fen += pieceLetters.from_piece(piece_on(sq));
378 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
379 fen.erase(--fen.end());
380 fen += (sideToMove == WHITE ? " w " : " b ");
382 if (st->castleRights != CASTLES_NONE)
384 if (can_castle_kingside(WHITE))
385 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
387 if (can_castle_queenside(WHITE))
388 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
390 if (can_castle_kingside(BLACK))
391 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
393 if (can_castle_queenside(BLACK))
394 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
398 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
403 /// Position::print() prints an ASCII representation of the position to
404 /// the standard output. If a move is given then also the san is printed.
406 void Position::print(Move move) const {
408 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
409 static bool requestPending = false;
411 // Check for reentrancy, as example when called from inside
412 // MovePicker that is used also here in move_to_san()
416 requestPending = true;
420 Position p(*this, thread());
421 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
422 cout << "\nMove is: " << dd << move_to_san(p, move);
425 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
427 cout << dottedLine << '|';
428 for (File file = FILE_A; file <= FILE_H; file++)
430 Square sq = make_square(file, rank);
431 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
432 Piece piece = piece_on(sq);
434 if (piece == PIECE_NONE && square_color(sq) == DARK)
435 piece = PIECE_NONE_DARK_SQ;
437 cout << c << pieceLetters.from_piece(piece) << c << '|';
440 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
441 requestPending = false;
445 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
446 /// king) pieces for the given color and for the given pinner type. Or, when
447 /// template parameter FindPinned is false, the pieces of the given color
448 /// candidate for a discovery check against the enemy king.
449 /// Bitboard checkersBB must be already updated when looking for pinners.
451 template<bool FindPinned>
452 Bitboard Position::hidden_checkers(Color c) const {
454 Bitboard result = EmptyBoardBB;
455 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
457 // Pinned pieces protect our king, dicovery checks attack
459 Square ksq = king_square(FindPinned ? c : opposite_color(c));
461 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
462 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
464 if (FindPinned && pinners)
465 pinners &= ~st->checkersBB;
469 Square s = pop_1st_bit(&pinners);
470 Bitboard b = squares_between(s, ksq) & occupied_squares();
474 if ( !(b & (b - 1)) // Only one bit set?
475 && (b & pieces_of_color(c))) // Is an our piece?
482 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
483 /// king) pieces for the given color. Note that checkersBB bitboard must
484 /// be already updated.
486 Bitboard Position::pinned_pieces(Color c) const {
488 return hidden_checkers<true>(c);
492 /// Position:discovered_check_candidates() returns a bitboard containing all
493 /// pieces for the given side which are candidates for giving a discovered
494 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
495 /// to be already updated.
497 Bitboard Position::discovered_check_candidates(Color c) const {
499 return hidden_checkers<false>(c);
502 /// Position::attackers_to() computes a bitboard containing all pieces which
503 /// attacks a given square.
505 Bitboard Position::attackers_to(Square s) const {
507 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
508 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
509 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
510 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
511 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
512 | (attacks_from<KING>(s) & pieces(KING));
515 /// Position::attacks_from() computes a bitboard of all attacks
516 /// of a given piece put in a given square.
518 Bitboard Position::attacks_from(Piece p, Square s) const {
520 assert(square_is_ok(s));
524 case WP: return attacks_from<PAWN>(s, WHITE);
525 case BP: return attacks_from<PAWN>(s, BLACK);
526 case WN: case BN: return attacks_from<KNIGHT>(s);
527 case WB: case BB: return attacks_from<BISHOP>(s);
528 case WR: case BR: return attacks_from<ROOK>(s);
529 case WQ: case BQ: return attacks_from<QUEEN>(s);
530 case WK: case BK: return attacks_from<KING>(s);
537 /// Position::move_attacks_square() tests whether a move from the current
538 /// position attacks a given square.
540 bool Position::move_attacks_square(Move m, Square s) const {
542 assert(move_is_ok(m));
543 assert(square_is_ok(s));
546 Square f = move_from(m), t = move_to(m);
548 assert(square_is_occupied(f));
550 if (bit_is_set(attacks_from(piece_on(f), t), s))
553 // Move the piece and scan for X-ray attacks behind it
554 occ = occupied_squares();
555 do_move_bb(&occ, make_move_bb(f, t));
556 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
557 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
558 & pieces_of_color(color_of_piece_on(f));
560 // If we have attacks we need to verify that are caused by our move
561 // and are not already existent ones.
562 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
566 /// Position::find_checkers() computes the checkersBB bitboard, which
567 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
568 /// currently works by calling Position::attackers_to, which is probably
569 /// inefficient. Consider rewriting this function to use the last move
570 /// played, like in non-bitboard versions of Glaurung.
572 void Position::find_checkers() {
574 Color us = side_to_move();
575 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
579 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
581 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
584 assert(move_is_ok(m));
585 assert(pinned == pinned_pieces(side_to_move()));
587 // Castling moves are checked for legality during move generation.
588 if (move_is_castle(m))
591 // En passant captures are a tricky special case. Because they are
592 // rather uncommon, we do it simply by testing whether the king is attacked
593 // after the move is made
596 Color us = side_to_move();
597 Color them = opposite_color(us);
598 Square from = move_from(m);
599 Square to = move_to(m);
600 Square capsq = make_square(square_file(to), square_rank(from));
601 Square ksq = king_square(us);
602 Bitboard b = occupied_squares();
604 assert(to == ep_square());
605 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
606 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
607 assert(piece_on(to) == PIECE_NONE);
610 clear_bit(&b, capsq);
613 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
614 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
617 Color us = side_to_move();
618 Square from = move_from(m);
620 assert(color_of_piece_on(from) == us);
621 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
623 // If the moving piece is a king, check whether the destination
624 // square is attacked by the opponent.
625 if (type_of_piece_on(from) == KING)
626 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
628 // A non-king move is legal if and only if it is not pinned or it
629 // is moving along the ray towards or away from the king.
631 || !bit_is_set(pinned, from)
632 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
636 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
638 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
642 Color us = side_to_move();
643 Square from = move_from(m);
644 Square to = move_to(m);
646 // King moves and en-passant captures are verified in pl_move_is_legal()
647 if (type_of_piece_on(from) == KING || move_is_ep(m))
648 return pl_move_is_legal(m, pinned);
650 Bitboard target = checkers();
651 Square checksq = pop_1st_bit(&target);
653 if (target) // double check ?
656 // Our move must be a blocking evasion or a capture of the checking piece
657 target = squares_between(checksq, king_square(us)) | checkers();
658 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
662 /// Position::move_is_check() tests whether a pseudo-legal move is a check
664 bool Position::move_is_check(Move m) const {
666 return move_is_check(m, CheckInfo(*this));
669 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
672 assert(move_is_ok(m));
673 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
674 assert(color_of_piece_on(move_from(m)) == side_to_move());
675 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
677 Square from = move_from(m);
678 Square to = move_to(m);
679 PieceType pt = type_of_piece_on(from);
682 if (bit_is_set(ci.checkSq[pt], to))
686 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
688 // For pawn and king moves we need to verify also direction
689 if ( (pt != PAWN && pt != KING)
690 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
694 // Can we skip the ugly special cases ?
695 if (!move_is_special(m))
698 Color us = side_to_move();
699 Bitboard b = occupied_squares();
701 // Promotion with check ?
702 if (move_is_promotion(m))
706 switch (move_promotion_piece(m))
709 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
711 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
713 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
715 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
721 // En passant capture with check ? We have already handled the case
722 // of direct checks and ordinary discovered check, the only case we
723 // need to handle is the unusual case of a discovered check through
724 // the captured pawn.
727 Square capsq = make_square(square_file(to), square_rank(from));
729 clear_bit(&b, capsq);
731 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
732 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
735 // Castling with check ?
736 if (move_is_castle(m))
738 Square kfrom, kto, rfrom, rto;
744 kto = relative_square(us, SQ_G1);
745 rto = relative_square(us, SQ_F1);
747 kto = relative_square(us, SQ_C1);
748 rto = relative_square(us, SQ_D1);
750 clear_bit(&b, kfrom);
751 clear_bit(&b, rfrom);
754 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
761 /// Position::do_move() makes a move, and saves all information necessary
762 /// to a StateInfo object. The move is assumed to be legal.
763 /// Pseudo-legal moves should be filtered out before this function is called.
765 void Position::do_move(Move m, StateInfo& newSt) {
768 do_move(m, newSt, ci, move_is_check(m, ci));
771 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
774 assert(move_is_ok(m));
779 // Copy some fields of old state to our new StateInfo object except the
780 // ones which are recalculated from scratch anyway, then switch our state
781 // pointer to point to the new, ready to be updated, state.
782 struct ReducedStateInfo {
783 Key pawnKey, materialKey;
784 int castleRights, rule50, gamePly, pliesFromNull;
791 memcpy(&newSt, st, sizeof(ReducedStateInfo));
796 // Save the current key to the history[] array, in order to be able to
797 // detect repetition draws.
798 history[st->gamePly++] = key;
800 // Update side to move
801 key ^= zobSideToMove;
803 // Increment the 50 moves rule draw counter. Resetting it to zero in the
804 // case of non-reversible moves is taken care of later.
808 if (move_is_castle(m))
815 Color us = side_to_move();
816 Color them = opposite_color(us);
817 Square from = move_from(m);
818 Square to = move_to(m);
819 bool ep = move_is_ep(m);
820 bool pm = move_is_promotion(m);
822 Piece piece = piece_on(from);
823 PieceType pt = type_of_piece(piece);
824 PieceType capture = ep ? PAWN : type_of_piece_on(to);
826 assert(color_of_piece_on(from) == us);
827 assert(color_of_piece_on(to) == them || square_is_empty(to));
828 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
829 assert(!pm || relative_rank(us, to) == RANK_8);
832 do_capture_move(key, capture, them, to, ep);
835 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
837 // Reset en passant square
838 if (st->epSquare != SQ_NONE)
840 key ^= zobEp[st->epSquare];
841 st->epSquare = SQ_NONE;
844 // Update castle rights, try to shortcut a common case
845 int cm = castleRightsMask[from] & castleRightsMask[to];
846 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
848 key ^= zobCastle[st->castleRights];
849 st->castleRights &= castleRightsMask[from];
850 st->castleRights &= castleRightsMask[to];
851 key ^= zobCastle[st->castleRights];
854 // Prefetch TT access as soon as we know key is updated
855 prefetch((char*)TT.first_entry(key));
858 Bitboard move_bb = make_move_bb(from, to);
859 do_move_bb(&(byColorBB[us]), move_bb);
860 do_move_bb(&(byTypeBB[pt]), move_bb);
861 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
863 board[to] = board[from];
864 board[from] = PIECE_NONE;
866 // Update piece lists, note that index[from] is not updated and
867 // becomes stale. This works as long as index[] is accessed just
868 // by known occupied squares.
869 index[to] = index[from];
870 pieceList[us][pt][index[to]] = to;
872 // If the moving piece was a pawn do some special extra work
875 // Reset rule 50 draw counter
878 // Update pawn hash key and prefetch in L1/L2 cache
879 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
880 prefetchPawn(st->pawnKey, threadID);
882 // Set en passant square, only if moved pawn can be captured
883 if ((to ^ from) == 16)
885 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
887 st->epSquare = Square((int(from) + int(to)) / 2);
888 key ^= zobEp[st->epSquare];
892 if (pm) // promotion ?
894 PieceType promotion = move_promotion_piece(m);
896 assert(promotion >= KNIGHT && promotion <= QUEEN);
898 // Insert promoted piece instead of pawn
899 clear_bit(&(byTypeBB[PAWN]), to);
900 set_bit(&(byTypeBB[promotion]), to);
901 board[to] = piece_of_color_and_type(us, promotion);
903 // Update piece counts
904 pieceCount[us][promotion]++;
905 pieceCount[us][PAWN]--;
907 // Update material key
908 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
909 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
911 // Update piece lists, move the last pawn at index[to] position
912 // and shrink the list. Add a new promotion piece to the list.
913 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
914 index[lastPawnSquare] = index[to];
915 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
916 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
917 index[to] = pieceCount[us][promotion] - 1;
918 pieceList[us][promotion][index[to]] = to;
920 // Partially revert hash keys update
921 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
922 st->pawnKey ^= zobrist[us][PAWN][to];
924 // Partially revert and update incremental scores
925 st->value -= pst(us, PAWN, to);
926 st->value += pst(us, promotion, to);
929 st->npMaterial[us] += PieceValueMidgame[promotion];
933 // Update incremental scores
934 st->value += pst_delta(piece, from, to);
937 st->capturedType = capture;
939 // Update the key with the final value
942 // Update checkers bitboard, piece must be already moved
943 st->checkersBB = EmptyBoardBB;
948 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
952 if (bit_is_set(ci.checkSq[pt], to))
953 st->checkersBB = SetMaskBB[to];
956 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
959 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
962 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
968 sideToMove = opposite_color(sideToMove);
969 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
975 /// Position::do_capture_move() is a private method used to update captured
976 /// piece info. It is called from the main Position::do_move function.
978 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
980 assert(capture != KING);
984 // If the captured piece was a pawn, update pawn hash key,
985 // otherwise update non-pawn material.
988 if (ep) // en passant ?
990 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
992 assert(to == st->epSquare);
993 assert(relative_rank(opposite_color(them), to) == RANK_6);
994 assert(piece_on(to) == PIECE_NONE);
995 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
997 board[capsq] = PIECE_NONE;
999 st->pawnKey ^= zobrist[them][PAWN][capsq];
1002 st->npMaterial[them] -= PieceValueMidgame[capture];
1004 // Remove captured piece
1005 clear_bit(&(byColorBB[them]), capsq);
1006 clear_bit(&(byTypeBB[capture]), capsq);
1007 clear_bit(&(byTypeBB[0]), capsq);
1010 key ^= zobrist[them][capture][capsq];
1012 // Update incremental scores
1013 st->value -= pst(them, capture, capsq);
1015 // Update piece count
1016 pieceCount[them][capture]--;
1018 // Update material hash key
1019 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1021 // Update piece list, move the last piece at index[capsq] position
1023 // WARNING: This is a not perfectly revresible operation. When we
1024 // will reinsert the captured piece in undo_move() we will put it
1025 // at the end of the list and not in its original place, it means
1026 // index[] and pieceList[] are not guaranteed to be invariant to a
1027 // do_move() + undo_move() sequence.
1028 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1029 index[lastPieceSquare] = index[capsq];
1030 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1031 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1033 // Reset rule 50 counter
1038 /// Position::do_castle_move() is a private method used to make a castling
1039 /// move. It is called from the main Position::do_move function. Note that
1040 /// castling moves are encoded as "king captures friendly rook" moves, for
1041 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1043 void Position::do_castle_move(Move m) {
1045 assert(move_is_ok(m));
1046 assert(move_is_castle(m));
1048 Color us = side_to_move();
1049 Color them = opposite_color(us);
1051 // Reset capture field
1052 st->capturedType = PIECE_TYPE_NONE;
1054 // Find source squares for king and rook
1055 Square kfrom = move_from(m);
1056 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1059 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1060 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1062 // Find destination squares for king and rook
1063 if (rfrom > kfrom) // O-O
1065 kto = relative_square(us, SQ_G1);
1066 rto = relative_square(us, SQ_F1);
1068 kto = relative_square(us, SQ_C1);
1069 rto = relative_square(us, SQ_D1);
1072 // Remove pieces from source squares:
1073 clear_bit(&(byColorBB[us]), kfrom);
1074 clear_bit(&(byTypeBB[KING]), kfrom);
1075 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1076 clear_bit(&(byColorBB[us]), rfrom);
1077 clear_bit(&(byTypeBB[ROOK]), rfrom);
1078 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1080 // Put pieces on destination squares:
1081 set_bit(&(byColorBB[us]), kto);
1082 set_bit(&(byTypeBB[KING]), kto);
1083 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1084 set_bit(&(byColorBB[us]), rto);
1085 set_bit(&(byTypeBB[ROOK]), rto);
1086 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1088 // Update board array
1089 Piece king = piece_of_color_and_type(us, KING);
1090 Piece rook = piece_of_color_and_type(us, ROOK);
1091 board[kfrom] = board[rfrom] = PIECE_NONE;
1095 // Update piece lists
1096 pieceList[us][KING][index[kfrom]] = kto;
1097 pieceList[us][ROOK][index[rfrom]] = rto;
1098 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1099 index[kto] = index[kfrom];
1102 // Update incremental scores
1103 st->value += pst_delta(king, kfrom, kto);
1104 st->value += pst_delta(rook, rfrom, rto);
1107 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1108 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1110 // Clear en passant square
1111 if (st->epSquare != SQ_NONE)
1113 st->key ^= zobEp[st->epSquare];
1114 st->epSquare = SQ_NONE;
1117 // Update castling rights
1118 st->key ^= zobCastle[st->castleRights];
1119 st->castleRights &= castleRightsMask[kfrom];
1120 st->key ^= zobCastle[st->castleRights];
1122 // Reset rule 50 counter
1125 // Update checkers BB
1126 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1129 sideToMove = opposite_color(sideToMove);
1130 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1136 /// Position::undo_move() unmakes a move. When it returns, the position should
1137 /// be restored to exactly the same state as before the move was made.
1139 void Position::undo_move(Move m) {
1142 assert(move_is_ok(m));
1144 sideToMove = opposite_color(sideToMove);
1146 if (move_is_castle(m))
1148 undo_castle_move(m);
1152 Color us = side_to_move();
1153 Color them = opposite_color(us);
1154 Square from = move_from(m);
1155 Square to = move_to(m);
1156 bool ep = move_is_ep(m);
1157 bool pm = move_is_promotion(m);
1159 PieceType pt = type_of_piece_on(to);
1161 assert(square_is_empty(from));
1162 assert(color_of_piece_on(to) == us);
1163 assert(!pm || relative_rank(us, to) == RANK_8);
1164 assert(!ep || to == st->previous->epSquare);
1165 assert(!ep || relative_rank(us, to) == RANK_6);
1166 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1168 if (pm) // promotion ?
1170 PieceType promotion = move_promotion_piece(m);
1173 assert(promotion >= KNIGHT && promotion <= QUEEN);
1174 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1176 // Replace promoted piece with a pawn
1177 clear_bit(&(byTypeBB[promotion]), to);
1178 set_bit(&(byTypeBB[PAWN]), to);
1180 // Update piece counts
1181 pieceCount[us][promotion]--;
1182 pieceCount[us][PAWN]++;
1184 // Update piece list replacing promotion piece with a pawn
1185 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1186 index[lastPromotionSquare] = index[to];
1187 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1188 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1189 index[to] = pieceCount[us][PAWN] - 1;
1190 pieceList[us][PAWN][index[to]] = to;
1193 // Put the piece back at the source square
1194 Bitboard move_bb = make_move_bb(to, from);
1195 do_move_bb(&(byColorBB[us]), move_bb);
1196 do_move_bb(&(byTypeBB[pt]), move_bb);
1197 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1199 board[from] = piece_of_color_and_type(us, pt);
1200 board[to] = PIECE_NONE;
1202 // Update piece list
1203 index[from] = index[to];
1204 pieceList[us][pt][index[from]] = from;
1206 if (st->capturedType)
1211 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1213 assert(st->capturedType != KING);
1214 assert(!ep || square_is_empty(capsq));
1216 // Restore the captured piece
1217 set_bit(&(byColorBB[them]), capsq);
1218 set_bit(&(byTypeBB[st->capturedType]), capsq);
1219 set_bit(&(byTypeBB[0]), capsq);
1221 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1223 // Update piece count
1224 pieceCount[them][st->capturedType]++;
1226 // Update piece list, add a new captured piece in capsq square
1227 index[capsq] = pieceCount[them][st->capturedType] - 1;
1228 pieceList[them][st->capturedType][index[capsq]] = capsq;
1231 // Finally point our state pointer back to the previous state
1238 /// Position::undo_castle_move() is a private method used to unmake a castling
1239 /// move. It is called from the main Position::undo_move function. Note that
1240 /// castling moves are encoded as "king captures friendly rook" moves, for
1241 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1243 void Position::undo_castle_move(Move m) {
1245 assert(move_is_ok(m));
1246 assert(move_is_castle(m));
1248 // When we have arrived here, some work has already been done by
1249 // Position::undo_move. In particular, the side to move has been switched,
1250 // so the code below is correct.
1251 Color us = side_to_move();
1253 // Find source squares for king and rook
1254 Square kfrom = move_from(m);
1255 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1258 // Find destination squares for king and rook
1259 if (rfrom > kfrom) // O-O
1261 kto = relative_square(us, SQ_G1);
1262 rto = relative_square(us, SQ_F1);
1264 kto = relative_square(us, SQ_C1);
1265 rto = relative_square(us, SQ_D1);
1268 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1269 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1271 // Remove pieces from destination squares:
1272 clear_bit(&(byColorBB[us]), kto);
1273 clear_bit(&(byTypeBB[KING]), kto);
1274 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1275 clear_bit(&(byColorBB[us]), rto);
1276 clear_bit(&(byTypeBB[ROOK]), rto);
1277 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1279 // Put pieces on source squares:
1280 set_bit(&(byColorBB[us]), kfrom);
1281 set_bit(&(byTypeBB[KING]), kfrom);
1282 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1283 set_bit(&(byColorBB[us]), rfrom);
1284 set_bit(&(byTypeBB[ROOK]), rfrom);
1285 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1288 board[rto] = board[kto] = PIECE_NONE;
1289 board[rfrom] = piece_of_color_and_type(us, ROOK);
1290 board[kfrom] = piece_of_color_and_type(us, KING);
1292 // Update piece lists
1293 pieceList[us][KING][index[kto]] = kfrom;
1294 pieceList[us][ROOK][index[rto]] = rfrom;
1295 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1296 index[kfrom] = index[kto];
1299 // Finally point our state pointer back to the previous state
1306 /// Position::do_null_move makes() a "null move": It switches the side to move
1307 /// and updates the hash key without executing any move on the board.
1309 void Position::do_null_move(StateInfo& backupSt) {
1312 assert(!is_check());
1314 // Back up the information necessary to undo the null move to the supplied
1315 // StateInfo object.
1316 // Note that differently from normal case here backupSt is actually used as
1317 // a backup storage not as a new state to be used.
1318 backupSt.key = st->key;
1319 backupSt.epSquare = st->epSquare;
1320 backupSt.value = st->value;
1321 backupSt.previous = st->previous;
1322 backupSt.pliesFromNull = st->pliesFromNull;
1323 st->previous = &backupSt;
1325 // Save the current key to the history[] array, in order to be able to
1326 // detect repetition draws.
1327 history[st->gamePly++] = st->key;
1329 // Update the necessary information
1330 if (st->epSquare != SQ_NONE)
1331 st->key ^= zobEp[st->epSquare];
1333 st->key ^= zobSideToMove;
1334 prefetch((char*)TT.first_entry(st->key));
1336 sideToMove = opposite_color(sideToMove);
1337 st->epSquare = SQ_NONE;
1339 st->pliesFromNull = 0;
1340 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1344 /// Position::undo_null_move() unmakes a "null move".
1346 void Position::undo_null_move() {
1349 assert(!is_check());
1351 // Restore information from the our backup StateInfo object
1352 StateInfo* backupSt = st->previous;
1353 st->key = backupSt->key;
1354 st->epSquare = backupSt->epSquare;
1355 st->value = backupSt->value;
1356 st->previous = backupSt->previous;
1357 st->pliesFromNull = backupSt->pliesFromNull;
1359 // Update the necessary information
1360 sideToMove = opposite_color(sideToMove);
1366 /// Position::see() is a static exchange evaluator: It tries to estimate the
1367 /// material gain or loss resulting from a move. There are three versions of
1368 /// this function: One which takes a destination square as input, one takes a
1369 /// move, and one which takes a 'from' and a 'to' square. The function does
1370 /// not yet understand promotions captures.
1372 int Position::see(Move m) const {
1374 assert(move_is_ok(m));
1375 return see(move_from(m), move_to(m));
1378 int Position::see_sign(Move m) const {
1380 assert(move_is_ok(m));
1382 Square from = move_from(m);
1383 Square to = move_to(m);
1385 // Early return if SEE cannot be negative because captured piece value
1386 // is not less then capturing one. Note that king moves always return
1387 // here because king midgame value is set to 0.
1388 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1391 return see(from, to);
1394 int Position::see(Square from, Square to) const {
1396 Bitboard occupied, attackers, stmAttackers, b;
1397 int swapList[32], slIndex = 1;
1398 PieceType capturedType, pt;
1401 assert(square_is_ok(from));
1402 assert(square_is_ok(to));
1404 capturedType = type_of_piece_on(to);
1406 // King cannot be recaptured
1407 if (capturedType == KING)
1408 return seeValues[capturedType];
1410 occupied = occupied_squares();
1412 // Handle en passant moves
1413 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1415 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1417 assert(capturedType == PIECE_TYPE_NONE);
1418 assert(type_of_piece_on(capQq) == PAWN);
1420 // Remove the captured pawn
1421 clear_bit(&occupied, capQq);
1422 capturedType = PAWN;
1425 // Find all attackers to the destination square, with the moving piece
1426 // removed, but possibly an X-ray attacker added behind it.
1427 clear_bit(&occupied, from);
1428 attackers = (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1429 | (bishop_attacks_bb(to, occupied)& pieces(BISHOP, QUEEN))
1430 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1431 | (attacks_from<KING>(to) & pieces(KING))
1432 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1433 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1435 // If the opponent has no attackers we are finished
1436 stm = opposite_color(color_of_piece_on(from));
1437 stmAttackers = attackers & pieces_of_color(stm);
1439 return seeValues[capturedType];
1441 // The destination square is defended, which makes things rather more
1442 // difficult to compute. We proceed by building up a "swap list" containing
1443 // the material gain or loss at each stop in a sequence of captures to the
1444 // destination square, where the sides alternately capture, and always
1445 // capture with the least valuable piece. After each capture, we look for
1446 // new X-ray attacks from behind the capturing piece.
1447 swapList[0] = seeValues[capturedType];
1448 capturedType = type_of_piece_on(from);
1451 // Locate the least valuable attacker for the side to move. The loop
1452 // below looks like it is potentially infinite, but it isn't. We know
1453 // that the side to move still has at least one attacker left.
1454 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1457 // Remove the attacker we just found from the 'occupied' bitboard,
1458 // and scan for new X-ray attacks behind the attacker.
1459 b = stmAttackers & pieces(pt);
1460 occupied ^= (b & (~b + 1));
1461 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1462 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1464 attackers &= occupied; // Cut out pieces we've already done
1466 // Add the new entry to the swap list
1467 assert(slIndex < 32);
1468 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1471 // Remember the value of the capturing piece, and change the side to
1472 // move before beginning the next iteration.
1474 stm = opposite_color(stm);
1475 stmAttackers = attackers & pieces_of_color(stm);
1477 // Stop before processing a king capture
1478 if (capturedType == KING && stmAttackers)
1480 assert(slIndex < 32);
1481 swapList[slIndex++] = QueenValueMidgame*10;
1484 } while (stmAttackers);
1486 // Having built the swap list, we negamax through it to find the best
1487 // achievable score from the point of view of the side to move.
1489 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1495 /// Position::clear() erases the position object to a pristine state, with an
1496 /// empty board, white to move, and no castling rights.
1498 void Position::clear() {
1501 memset(st, 0, sizeof(StateInfo));
1502 st->epSquare = SQ_NONE;
1503 startPosPlyCounter = 0;
1506 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1507 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1508 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1509 memset(index, 0, sizeof(int) * 64);
1511 for (int i = 0; i < 64; i++)
1512 board[i] = PIECE_NONE;
1514 for (int i = 0; i < 8; i++)
1515 for (int j = 0; j < 16; j++)
1516 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1518 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1519 castleRightsMask[sq] = ALL_CASTLES;
1522 initialKFile = FILE_E;
1523 initialKRFile = FILE_H;
1524 initialQRFile = FILE_A;
1528 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1529 /// UCI interface code, whenever a non-reversible move is made in a
1530 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1531 /// for the program to handle games of arbitrary length, as long as the GUI
1532 /// handles draws by the 50 move rule correctly.
1534 void Position::reset_game_ply() {
1539 void Position::inc_startpos_ply_counter() {
1541 startPosPlyCounter++;
1544 /// Position::put_piece() puts a piece on the given square of the board,
1545 /// updating the board array, pieces list, bitboards, and piece counts.
1547 void Position::put_piece(Piece p, Square s) {
1549 Color c = color_of_piece(p);
1550 PieceType pt = type_of_piece(p);
1553 index[s] = pieceCount[c][pt]++;
1554 pieceList[c][pt][index[s]] = s;
1556 set_bit(&(byTypeBB[pt]), s);
1557 set_bit(&(byColorBB[c]), s);
1558 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1562 /// Position::compute_key() computes the hash key of the position. The hash
1563 /// key is usually updated incrementally as moves are made and unmade, the
1564 /// compute_key() function is only used when a new position is set up, and
1565 /// to verify the correctness of the hash key when running in debug mode.
1567 Key Position::compute_key() const {
1569 Key result = zobCastle[st->castleRights];
1571 for (Square s = SQ_A1; s <= SQ_H8; s++)
1572 if (square_is_occupied(s))
1573 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1575 if (ep_square() != SQ_NONE)
1576 result ^= zobEp[ep_square()];
1578 if (side_to_move() == BLACK)
1579 result ^= zobSideToMove;
1585 /// Position::compute_pawn_key() computes the hash key of the position. The
1586 /// hash key is usually updated incrementally as moves are made and unmade,
1587 /// the compute_pawn_key() function is only used when a new position is set
1588 /// up, and to verify the correctness of the pawn hash key when running in
1591 Key Position::compute_pawn_key() const {
1596 for (Color c = WHITE; c <= BLACK; c++)
1598 b = pieces(PAWN, c);
1600 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1606 /// Position::compute_material_key() computes the hash key of the position.
1607 /// The hash key is usually updated incrementally as moves are made and unmade,
1608 /// the compute_material_key() function is only used when a new position is set
1609 /// up, and to verify the correctness of the material hash key when running in
1612 Key Position::compute_material_key() const {
1617 for (Color c = WHITE; c <= BLACK; c++)
1618 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1620 count = piece_count(c, pt);
1621 for (int i = 0; i < count; i++)
1622 result ^= zobrist[c][pt][i];
1628 /// Position::compute_value() compute the incremental scores for the middle
1629 /// game and the endgame. These functions are used to initialize the incremental
1630 /// scores when a new position is set up, and to verify that the scores are correctly
1631 /// updated by do_move and undo_move when the program is running in debug mode.
1632 Score Position::compute_value() const {
1635 Score result = SCORE_ZERO;
1637 for (Color c = WHITE; c <= BLACK; c++)
1638 for (PieceType pt = PAWN; pt <= KING; pt++)
1642 result += pst(c, pt, pop_1st_bit(&b));
1645 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1650 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1651 /// game material value for the given side. Material values are updated
1652 /// incrementally during the search, this function is only used while
1653 /// initializing a new Position object.
1655 Value Position::compute_non_pawn_material(Color c) const {
1657 Value result = VALUE_ZERO;
1659 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1660 result += piece_count(c, pt) * PieceValueMidgame[pt];
1666 /// Position::is_draw() tests whether the position is drawn by material,
1667 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1668 /// must be done by the search.
1670 bool Position::is_draw() const {
1672 // Draw by material?
1674 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1677 // Draw by the 50 moves rule?
1678 if (st->rule50 > 99 && (st->rule50 > 100 || !is_mate()))
1681 // Draw by repetition?
1682 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1683 if (history[st->gamePly - i] == st->key)
1690 /// Position::is_mate() returns true or false depending on whether the
1691 /// side to move is checkmated.
1693 bool Position::is_mate() const {
1695 MoveStack moves[MOVES_MAX];
1696 return is_check() && generate_moves(*this, moves) == moves;
1700 /// Position::has_mate_threat() tests whether the side to move is under
1701 /// a threat of being mated in one from the current position.
1703 bool Position::has_mate_threat() {
1705 MoveStack mlist[MOVES_MAX], *last, *cur;
1707 bool mateFound = false;
1709 // If we are under check it's up to evasions to do the job
1713 // First pass the move to our opponent doing a null move
1716 // Then generate pseudo-legal moves that could give check
1717 last = generate_non_capture_checks(*this, mlist);
1718 last = generate_captures(*this, last);
1720 // Loop through the moves, and see if one of them gives mate
1721 Bitboard pinned = pinned_pieces(sideToMove);
1722 CheckInfo ci(*this);
1723 for (cur = mlist; cur != last && !mateFound; cur++)
1725 Move move = cur->move;
1726 if ( !pl_move_is_legal(move, pinned)
1727 || !move_is_check(move, ci))
1730 do_move(move, st2, ci, true);
1743 /// Position::init_zobrist() is a static member function which initializes at
1744 /// startup the various arrays used to compute hash keys.
1746 void Position::init_zobrist() {
1751 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1752 zobrist[i][j][k] = rk.rand<Key>();
1754 for (i = 0; i < 64; i++)
1755 zobEp[i] = rk.rand<Key>();
1757 for (i = 0; i < 16; i++)
1758 zobCastle[i] = rk.rand<Key>();
1760 zobSideToMove = rk.rand<Key>();
1761 zobExclusion = rk.rand<Key>();
1765 /// Position::init_piece_square_tables() initializes the piece square tables.
1766 /// This is a two-step operation: First, the white halves of the tables are
1767 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1768 /// of the tables are initialized by mirroring and changing the sign of the
1769 /// corresponding white scores.
1771 void Position::init_piece_square_tables() {
1773 for (Square s = SQ_A1; s <= SQ_H8; s++)
1774 for (Piece p = WP; p <= WK; p++)
1775 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1777 for (Square s = SQ_A1; s <= SQ_H8; s++)
1778 for (Piece p = BP; p <= BK; p++)
1779 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1783 /// Position::flipped_copy() makes a copy of the input position, but with
1784 /// the white and black sides reversed. This is only useful for debugging,
1785 /// especially for finding evaluation symmetry bugs.
1787 void Position::flipped_copy(const Position& pos) {
1789 assert(pos.is_ok());
1792 threadID = pos.thread();
1795 for (Square s = SQ_A1; s <= SQ_H8; s++)
1796 if (!pos.square_is_empty(s))
1797 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1800 sideToMove = opposite_color(pos.side_to_move());
1803 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1804 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1805 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1806 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1808 initialKFile = pos.initialKFile;
1809 initialKRFile = pos.initialKRFile;
1810 initialQRFile = pos.initialQRFile;
1812 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1813 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1814 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1815 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1816 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1817 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1819 // En passant square
1820 if (pos.st->epSquare != SQ_NONE)
1821 st->epSquare = flip_square(pos.st->epSquare);
1827 st->key = compute_key();
1828 st->pawnKey = compute_pawn_key();
1829 st->materialKey = compute_material_key();
1831 // Incremental scores
1832 st->value = compute_value();
1835 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1836 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1842 /// Position::is_ok() performs some consitency checks for the position object.
1843 /// This is meant to be helpful when debugging.
1845 bool Position::is_ok(int* failedStep) const {
1847 // What features of the position should be verified?
1848 const bool debugAll = false;
1850 const bool debugBitboards = debugAll || false;
1851 const bool debugKingCount = debugAll || false;
1852 const bool debugKingCapture = debugAll || false;
1853 const bool debugCheckerCount = debugAll || false;
1854 const bool debugKey = debugAll || false;
1855 const bool debugMaterialKey = debugAll || false;
1856 const bool debugPawnKey = debugAll || false;
1857 const bool debugIncrementalEval = debugAll || false;
1858 const bool debugNonPawnMaterial = debugAll || false;
1859 const bool debugPieceCounts = debugAll || false;
1860 const bool debugPieceList = debugAll || false;
1861 const bool debugCastleSquares = debugAll || false;
1863 if (failedStep) *failedStep = 1;
1866 if (!color_is_ok(side_to_move()))
1869 // Are the king squares in the position correct?
1870 if (failedStep) (*failedStep)++;
1871 if (piece_on(king_square(WHITE)) != WK)
1874 if (failedStep) (*failedStep)++;
1875 if (piece_on(king_square(BLACK)) != BK)
1879 if (failedStep) (*failedStep)++;
1880 if (!file_is_ok(initialKRFile))
1883 if (!file_is_ok(initialQRFile))
1886 // Do both sides have exactly one king?
1887 if (failedStep) (*failedStep)++;
1890 int kingCount[2] = {0, 0};
1891 for (Square s = SQ_A1; s <= SQ_H8; s++)
1892 if (type_of_piece_on(s) == KING)
1893 kingCount[color_of_piece_on(s)]++;
1895 if (kingCount[0] != 1 || kingCount[1] != 1)
1899 // Can the side to move capture the opponent's king?
1900 if (failedStep) (*failedStep)++;
1901 if (debugKingCapture)
1903 Color us = side_to_move();
1904 Color them = opposite_color(us);
1905 Square ksq = king_square(them);
1906 if (attackers_to(ksq) & pieces_of_color(us))
1910 // Is there more than 2 checkers?
1911 if (failedStep) (*failedStep)++;
1912 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1916 if (failedStep) (*failedStep)++;
1919 // The intersection of the white and black pieces must be empty
1920 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1923 // The union of the white and black pieces must be equal to all
1925 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1928 // Separate piece type bitboards must have empty intersections
1929 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1930 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1931 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1935 // En passant square OK?
1936 if (failedStep) (*failedStep)++;
1937 if (ep_square() != SQ_NONE)
1939 // The en passant square must be on rank 6, from the point of view of the
1941 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1946 if (failedStep) (*failedStep)++;
1947 if (debugKey && st->key != compute_key())
1950 // Pawn hash key OK?
1951 if (failedStep) (*failedStep)++;
1952 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1955 // Material hash key OK?
1956 if (failedStep) (*failedStep)++;
1957 if (debugMaterialKey && st->materialKey != compute_material_key())
1960 // Incremental eval OK?
1961 if (failedStep) (*failedStep)++;
1962 if (debugIncrementalEval && st->value != compute_value())
1965 // Non-pawn material OK?
1966 if (failedStep) (*failedStep)++;
1967 if (debugNonPawnMaterial)
1969 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1972 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1977 if (failedStep) (*failedStep)++;
1978 if (debugPieceCounts)
1979 for (Color c = WHITE; c <= BLACK; c++)
1980 for (PieceType pt = PAWN; pt <= KING; pt++)
1981 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1984 if (failedStep) (*failedStep)++;
1987 for (Color c = WHITE; c <= BLACK; c++)
1988 for (PieceType pt = PAWN; pt <= KING; pt++)
1989 for (int i = 0; i < pieceCount[c][pt]; i++)
1991 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
1994 if (index[piece_list(c, pt, i)] != i)
1999 if (failedStep) (*failedStep)++;
2000 if (debugCastleSquares) {
2001 for (Color c = WHITE; c <= BLACK; c++) {
2002 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2004 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2007 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2009 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2011 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2013 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2017 if (failedStep) *failedStep = 0;