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/>.
40 #include "ucioption.h"
48 //// Position's static data definitions
51 Key Position::zobrist[2][8][64];
52 Key Position::zobEp[64];
53 Key Position::zobCastle[16];
54 Key Position::zobSideToMove;
55 Key Position::zobExclusion;
57 Score Position::PieceSquareTable[16][64];
59 // Material values arrays, indexed by Piece
60 const Value Position::PieceValueMidgame[17] = {
62 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
63 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
64 VALUE_ZERO, VALUE_ZERO,
65 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
66 RookValueMidgame, QueenValueMidgame
69 const Value Position::PieceValueEndgame[17] = {
71 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
72 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
73 VALUE_ZERO, VALUE_ZERO,
74 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
75 RookValueEndgame, QueenValueEndgame
78 // Material values array used by SEE, indexed by PieceType
79 const Value Position::seeValues[] = {
81 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
82 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
88 // Bonus for having the side to move (modified by Joona Kiiski)
89 const Score TempoValue = make_score(48, 22);
91 bool isZero(char c) { return c == '0'; }
93 struct PieceLetters : public std::map<char, Piece> {
97 operator[]('K') = WK; operator[]('k') = BK;
98 operator[]('Q') = WQ; operator[]('q') = BQ;
99 operator[]('R') = WR; operator[]('r') = BR;
100 operator[]('B') = WB; operator[]('b') = BB;
101 operator[]('N') = WN; operator[]('n') = BN;
102 operator[]('P') = WP; operator[]('p') = BP;
103 operator[](' ') = PIECE_NONE;
104 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)
119 PieceLetters pieceLetters;
125 CheckInfo::CheckInfo(const Position& pos) {
127 Color us = pos.side_to_move();
128 Color them = opposite_color(us);
130 ksq = pos.king_square(them);
131 dcCandidates = pos.discovered_check_candidates(us);
133 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
134 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
135 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
136 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
137 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
138 checkSq[KING] = EmptyBoardBB;
142 /// Position c'tors. Here we always create a copy of the original position
143 /// or the FEN string, we want the new born Position object do not depend
144 /// on any external data so we detach state pointer from the source one.
146 Position::Position(const Position& pos, int th) {
148 memcpy(this, &pos, sizeof(Position));
149 detach(); // Always detach() in copy c'tor to avoid surprises
154 Position::Position(const string& fen, bool isChess960, int th) {
156 from_fen(fen, isChess960);
161 /// Position::detach() copies the content of the current state and castling
162 /// masks inside the position itself. This is needed when the st pointee could
163 /// become stale, as example because the caller is about to going out of scope.
165 void Position::detach() {
169 st->previous = NULL; // as a safe guard
173 /// Position::from_fen() initializes the position object with the given FEN
174 /// string. This function is not very robust - make sure that input FENs are
175 /// correct (this is assumed to be the responsibility of the GUI).
177 void Position::from_fen(const string& fen, bool c960) {
179 A FEN string defines a particular position using only the ASCII character set.
181 A FEN string contains six fields. The separator between fields is a space. The fields are:
183 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
184 with rank 1; within each rank, the contents of each square are described from file a through file h.
185 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
186 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
187 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
188 of blank squares), and "/" separate ranks.
190 2) Active color. "w" means white moves next, "b" means black.
192 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
193 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
194 kingside), and/or "q" (Black can castle queenside).
196 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
197 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
198 regardless of whether there is a pawn in position to make an en passant capture.
200 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
201 to determine if a draw can be claimed under the fifty-move rule.
203 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
208 std::istringstream ss(fen);
214 // 1. Piece placement field
215 while (ss.get(token) && token != ' ')
219 file += File(token - '0'); // Skip the given number of files
222 else if (token == '/')
229 if (pieceLetters.find(token) == pieceLetters.end())
232 put_piece(pieceLetters[token], make_square(file, rank));
237 if (!ss.get(token) || (token != 'w' && token != 'b'))
240 sideToMove = (token == 'w' ? WHITE : BLACK);
242 if (!ss.get(token) || token != ' ')
245 // 3. Castling availability
246 while (ss.get(token) && token != ' ')
251 if (!set_castling_rights(token))
255 // 4. En passant square -- ignore if no capture is possible
257 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
258 && (ss.get(row) && (row == '3' || row == '6')))
260 Square fenEpSquare = make_square(file_from_char(col), rank_from_char(row));
261 Color them = opposite_color(sideToMove);
263 if (attacks_from<PAWN>(fenEpSquare, them) & pieces(PAWN, sideToMove))
264 st->epSquare = fenEpSquare;
271 // 6. Fullmove number
273 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
275 // Various initialisations
276 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
277 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
278 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
279 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
280 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
281 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
286 st->key = compute_key();
287 st->pawnKey = compute_pawn_key();
288 st->materialKey = compute_material_key();
289 st->value = compute_value();
290 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
291 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
295 cout << "Error in FEN string: " << fen << endl;
299 /// Position::set_castling_rights() sets castling parameters castling avaiability.
300 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
301 /// that uses the letters of the columns on which the rooks began the game instead
302 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
303 /// associated with the castling right, the traditional castling tag will be replaced
304 /// by the file letter of the involved rook as for the Shredder-FEN.
306 bool Position::set_castling_rights(char token) {
308 Color c = token >= 'a' ? BLACK : WHITE;
309 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
310 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
311 Piece rook = (c == WHITE ? WR : BR);
313 initialKFile = square_file(king_square(c));
314 token = char(toupper(token));
318 for (Square sq = sqH; sq >= sqA; sq--)
319 if (piece_on(sq) == rook)
322 initialKRFile = square_file(sq);
326 else if (token == 'Q')
328 for (Square sq = sqA; sq <= sqH; sq++)
329 if (piece_on(sq) == rook)
332 initialQRFile = square_file(sq);
336 else if (token >= 'A' && token <= 'H')
338 File rookFile = File(token - 'A') + FILE_A;
339 if (rookFile < initialKFile)
342 initialQRFile = rookFile;
347 initialKRFile = rookFile;
356 /// Position::to_fen() returns a FEN representation of the position. In case
357 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
359 const string Position::to_fen() const {
365 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
367 for (File file = FILE_A; file <= FILE_H; file++)
369 sq = make_square(file, rank);
371 if (square_is_occupied(sq))
374 fen += pieceLetters.from_piece(piece_on(sq));
384 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
385 fen.erase(--fen.end());
386 fen += (sideToMove == WHITE ? " w " : " b ");
388 if (st->castleRights != CASTLES_NONE)
390 if (can_castle_kingside(WHITE))
391 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
393 if (can_castle_queenside(WHITE))
394 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
396 if (can_castle_kingside(BLACK))
397 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
399 if (can_castle_queenside(BLACK))
400 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
404 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
409 /// Position::print() prints an ASCII representation of the position to
410 /// the standard output. If a move is given then also the san is printed.
412 void Position::print(Move move) const {
414 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
415 static bool requestPending = false;
417 // Check for reentrancy, as example when called from inside
418 // MovePicker that is used also here in move_to_san()
422 requestPending = true;
426 Position p(*this, thread());
427 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
428 cout << "\nMove is: " << dd << move_to_san(p, move);
431 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
433 cout << dottedLine << '|';
434 for (File file = FILE_A; file <= FILE_H; file++)
436 Square sq = make_square(file, rank);
437 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
438 Piece piece = piece_on(sq);
440 if (piece == PIECE_NONE && square_color(sq) == DARK)
441 piece = PIECE_NONE_DARK_SQ;
443 cout << c << pieceLetters.from_piece(piece) << c << '|';
446 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
447 requestPending = false;
451 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
452 /// king) pieces for the given color and for the given pinner type. Or, when
453 /// template parameter FindPinned is false, the pieces of the given color
454 /// candidate for a discovery check against the enemy king.
455 /// Bitboard checkersBB must be already updated when looking for pinners.
457 template<bool FindPinned>
458 Bitboard Position::hidden_checkers(Color c) const {
460 Bitboard result = EmptyBoardBB;
461 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
463 // Pinned pieces protect our king, dicovery checks attack
465 Square ksq = king_square(FindPinned ? c : opposite_color(c));
467 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
468 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
470 if (FindPinned && pinners)
471 pinners &= ~st->checkersBB;
475 Square s = pop_1st_bit(&pinners);
476 Bitboard b = squares_between(s, ksq) & occupied_squares();
480 if ( !(b & (b - 1)) // Only one bit set?
481 && (b & pieces_of_color(c))) // Is an our piece?
488 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
489 /// king) pieces for the given color. Note that checkersBB bitboard must
490 /// be already updated.
492 Bitboard Position::pinned_pieces(Color c) const {
494 return hidden_checkers<true>(c);
498 /// Position:discovered_check_candidates() returns a bitboard containing all
499 /// pieces for the given side which are candidates for giving a discovered
500 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
501 /// to be already updated.
503 Bitboard Position::discovered_check_candidates(Color c) const {
505 return hidden_checkers<false>(c);
508 /// Position::attackers_to() computes a bitboard containing all pieces which
509 /// attacks a given square.
511 Bitboard Position::attackers_to(Square s) const {
513 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
514 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
515 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
516 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
517 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
518 | (attacks_from<KING>(s) & pieces(KING));
521 /// Position::attacks_from() computes a bitboard of all attacks
522 /// of a given piece put in a given square.
524 Bitboard Position::attacks_from(Piece p, Square s) const {
526 assert(square_is_ok(s));
530 case WB: case BB: return attacks_from<BISHOP>(s);
531 case WR: case BR: return attacks_from<ROOK>(s);
532 case WQ: case BQ: return attacks_from<QUEEN>(s);
533 default: return NonSlidingAttacksBB[p][s];
537 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
539 assert(square_is_ok(s));
543 case WB: case BB: return bishop_attacks_bb(s, occ);
544 case WR: case BR: return rook_attacks_bb(s, occ);
545 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
546 default: return NonSlidingAttacksBB[p][s];
551 /// Position::move_attacks_square() tests whether a move from the current
552 /// position attacks a given square.
554 bool Position::move_attacks_square(Move m, Square s) const {
556 assert(move_is_ok(m));
557 assert(square_is_ok(s));
560 Square f = move_from(m), t = move_to(m);
562 assert(square_is_occupied(f));
564 if (bit_is_set(attacks_from(piece_on(f), t), s))
567 // Move the piece and scan for X-ray attacks behind it
568 occ = occupied_squares();
569 do_move_bb(&occ, make_move_bb(f, t));
570 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
571 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
572 & pieces_of_color(color_of_piece_on(f));
574 // If we have attacks we need to verify that are caused by our move
575 // and are not already existent ones.
576 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
580 /// Position::find_checkers() computes the checkersBB bitboard, which
581 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
582 /// currently works by calling Position::attackers_to, which is probably
583 /// inefficient. Consider rewriting this function to use the last move
584 /// played, like in non-bitboard versions of Glaurung.
586 void Position::find_checkers() {
588 Color us = side_to_move();
589 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
593 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
595 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
598 assert(move_is_ok(m));
599 assert(pinned == pinned_pieces(side_to_move()));
601 // Castling moves are checked for legality during move generation.
602 if (move_is_castle(m))
605 // En passant captures are a tricky special case. Because they are
606 // rather uncommon, we do it simply by testing whether the king is attacked
607 // after the move is made
610 Color us = side_to_move();
611 Color them = opposite_color(us);
612 Square from = move_from(m);
613 Square to = move_to(m);
614 Square capsq = make_square(square_file(to), square_rank(from));
615 Square ksq = king_square(us);
616 Bitboard b = occupied_squares();
618 assert(to == ep_square());
619 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
620 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
621 assert(piece_on(to) == PIECE_NONE);
624 clear_bit(&b, capsq);
627 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
628 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
631 Color us = side_to_move();
632 Square from = move_from(m);
634 assert(color_of_piece_on(from) == us);
635 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
637 // If the moving piece is a king, check whether the destination
638 // square is attacked by the opponent.
639 if (type_of_piece_on(from) == KING)
640 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
642 // A non-king move is legal if and only if it is not pinned or it
643 // is moving along the ray towards or away from the king.
645 || !bit_is_set(pinned, from)
646 || squares_aligned(from, move_to(m), king_square(us));
650 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
652 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
656 Color us = side_to_move();
657 Square from = move_from(m);
658 Square to = move_to(m);
660 // King moves and en-passant captures are verified in pl_move_is_legal()
661 if (type_of_piece_on(from) == KING || move_is_ep(m))
662 return pl_move_is_legal(m, pinned);
664 Bitboard target = checkers();
665 Square checksq = pop_1st_bit(&target);
667 if (target) // double check ?
670 // Our move must be a blocking evasion or a capture of the checking piece
671 target = squares_between(checksq, king_square(us)) | checkers();
672 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
676 /// Position::move_is_check() tests whether a pseudo-legal move is a check
678 bool Position::move_is_check(Move m) const {
680 return move_is_check(m, CheckInfo(*this));
683 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
686 assert(move_is_ok(m));
687 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
688 assert(color_of_piece_on(move_from(m)) == side_to_move());
689 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
691 Square from = move_from(m);
692 Square to = move_to(m);
693 PieceType pt = type_of_piece_on(from);
696 if (bit_is_set(ci.checkSq[pt], to))
700 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
702 // For pawn and king moves we need to verify also direction
703 if ( (pt != PAWN && pt != KING)
704 || !squares_aligned(from, to, ci.ksq))
708 // Can we skip the ugly special cases ?
709 if (!move_is_special(m))
712 Color us = side_to_move();
713 Bitboard b = occupied_squares();
715 // Promotion with check ?
716 if (move_is_promotion(m))
720 switch (move_promotion_piece(m))
723 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
725 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
727 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
729 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
735 // En passant capture with check ? We have already handled the case
736 // of direct checks and ordinary discovered check, the only case we
737 // need to handle is the unusual case of a discovered check through
738 // the captured pawn.
741 Square capsq = make_square(square_file(to), square_rank(from));
743 clear_bit(&b, capsq);
745 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
746 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
749 // Castling with check ?
750 if (move_is_castle(m))
752 Square kfrom, kto, rfrom, rto;
758 kto = relative_square(us, SQ_G1);
759 rto = relative_square(us, SQ_F1);
761 kto = relative_square(us, SQ_C1);
762 rto = relative_square(us, SQ_D1);
764 clear_bit(&b, kfrom);
765 clear_bit(&b, rfrom);
768 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
775 /// Position::do_setup_move() makes a permanent move on the board.
776 /// It should be used when setting up a position on board.
777 /// You can't undo the move.
779 void Position::do_setup_move(Move m) {
785 // Reset "game ply" in case we made a non-reversible move.
786 // "game ply" is used for repetition detection.
790 // Update the number of plies played from the starting position
791 startPosPlyCounter++;
793 // Our StateInfo newSt is about going out of scope so copy
794 // its content inside pos before it disappears.
798 /// Position::do_move() makes a move, and saves all information necessary
799 /// to a StateInfo object. The move is assumed to be legal.
800 /// Pseudo-legal moves should be filtered out before this function is called.
802 void Position::do_move(Move m, StateInfo& newSt) {
805 do_move(m, newSt, ci, move_is_check(m, ci));
808 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
811 assert(move_is_ok(m));
812 assert(&newSt != st);
817 // Copy some fields of old state to our new StateInfo object except the
818 // ones which are recalculated from scratch anyway, then switch our state
819 // pointer to point to the new, ready to be updated, state.
820 struct ReducedStateInfo {
821 Key pawnKey, materialKey;
822 int castleRights, rule50, gamePly, pliesFromNull;
828 memcpy(&newSt, st, sizeof(ReducedStateInfo));
833 // Save the current key to the history[] array, in order to be able to
834 // detect repetition draws.
835 history[st->gamePly++] = key;
837 // Update side to move
838 key ^= zobSideToMove;
840 // Increment the 50 moves rule draw counter. Resetting it to zero in the
841 // case of non-reversible moves is taken care of later.
845 if (move_is_castle(m))
852 Color us = side_to_move();
853 Color them = opposite_color(us);
854 Square from = move_from(m);
855 Square to = move_to(m);
856 bool ep = move_is_ep(m);
857 bool pm = move_is_promotion(m);
859 Piece piece = piece_on(from);
860 PieceType pt = type_of_piece(piece);
861 PieceType capture = ep ? PAWN : type_of_piece_on(to);
863 assert(color_of_piece_on(from) == us);
864 assert(color_of_piece_on(to) == them || square_is_empty(to));
865 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
866 assert(!pm || relative_rank(us, to) == RANK_8);
869 do_capture_move(key, capture, them, to, ep);
872 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
874 // Reset en passant square
875 if (st->epSquare != SQ_NONE)
877 key ^= zobEp[st->epSquare];
878 st->epSquare = SQ_NONE;
881 // Update castle rights, try to shortcut a common case
882 int cm = castleRightsMask[from] & castleRightsMask[to];
883 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
885 key ^= zobCastle[st->castleRights];
886 st->castleRights &= castleRightsMask[from];
887 st->castleRights &= castleRightsMask[to];
888 key ^= zobCastle[st->castleRights];
891 // Prefetch TT access as soon as we know key is updated
892 prefetch((char*)TT.first_entry(key));
895 Bitboard move_bb = make_move_bb(from, to);
896 do_move_bb(&(byColorBB[us]), move_bb);
897 do_move_bb(&(byTypeBB[pt]), move_bb);
898 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
900 board[to] = board[from];
901 board[from] = PIECE_NONE;
903 // Update piece lists, note that index[from] is not updated and
904 // becomes stale. This works as long as index[] is accessed just
905 // by known occupied squares.
906 index[to] = index[from];
907 pieceList[us][pt][index[to]] = to;
909 // If the moving piece was a pawn do some special extra work
912 // Reset rule 50 draw counter
915 // Update pawn hash key and prefetch in L1/L2 cache
916 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
917 prefetchPawn(st->pawnKey, threadID);
919 // Set en passant square, only if moved pawn can be captured
920 if ((to ^ from) == 16)
922 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
924 st->epSquare = Square((int(from) + int(to)) / 2);
925 key ^= zobEp[st->epSquare];
929 if (pm) // promotion ?
931 PieceType promotion = move_promotion_piece(m);
933 assert(promotion >= KNIGHT && promotion <= QUEEN);
935 // Insert promoted piece instead of pawn
936 clear_bit(&(byTypeBB[PAWN]), to);
937 set_bit(&(byTypeBB[promotion]), to);
938 board[to] = piece_of_color_and_type(us, promotion);
940 // Update piece counts
941 pieceCount[us][promotion]++;
942 pieceCount[us][PAWN]--;
944 // Update material key
945 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
946 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
948 // Update piece lists, move the last pawn at index[to] position
949 // and shrink the list. Add a new promotion piece to the list.
950 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
951 index[lastPawnSquare] = index[to];
952 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
953 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
954 index[to] = pieceCount[us][promotion] - 1;
955 pieceList[us][promotion][index[to]] = to;
957 // Partially revert hash keys update
958 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
959 st->pawnKey ^= zobrist[us][PAWN][to];
961 // Partially revert and update incremental scores
962 st->value -= pst(us, PAWN, to);
963 st->value += pst(us, promotion, to);
966 st->npMaterial[us] += PieceValueMidgame[promotion];
970 // Update incremental scores
971 st->value += pst_delta(piece, from, to);
974 st->capturedType = capture;
976 // Update the key with the final value
979 // Update checkers bitboard, piece must be already moved
980 st->checkersBB = EmptyBoardBB;
985 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
989 if (bit_is_set(ci.checkSq[pt], to))
990 st->checkersBB = SetMaskBB[to];
993 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
996 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
999 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
1005 sideToMove = opposite_color(sideToMove);
1006 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1012 /// Position::do_capture_move() is a private method used to update captured
1013 /// piece info. It is called from the main Position::do_move function.
1015 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1017 assert(capture != KING);
1021 // If the captured piece was a pawn, update pawn hash key,
1022 // otherwise update non-pawn material.
1023 if (capture == PAWN)
1025 if (ep) // en passant ?
1027 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1029 assert(to == st->epSquare);
1030 assert(relative_rank(opposite_color(them), to) == RANK_6);
1031 assert(piece_on(to) == PIECE_NONE);
1032 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1034 board[capsq] = PIECE_NONE;
1036 st->pawnKey ^= zobrist[them][PAWN][capsq];
1039 st->npMaterial[them] -= PieceValueMidgame[capture];
1041 // Remove captured piece
1042 clear_bit(&(byColorBB[them]), capsq);
1043 clear_bit(&(byTypeBB[capture]), capsq);
1044 clear_bit(&(byTypeBB[0]), capsq);
1047 key ^= zobrist[them][capture][capsq];
1049 // Update incremental scores
1050 st->value -= pst(them, capture, capsq);
1052 // Update piece count
1053 pieceCount[them][capture]--;
1055 // Update material hash key
1056 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1058 // Update piece list, move the last piece at index[capsq] position
1060 // WARNING: This is a not perfectly revresible operation. When we
1061 // will reinsert the captured piece in undo_move() we will put it
1062 // at the end of the list and not in its original place, it means
1063 // index[] and pieceList[] are not guaranteed to be invariant to a
1064 // do_move() + undo_move() sequence.
1065 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1066 index[lastPieceSquare] = index[capsq];
1067 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1068 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1070 // Reset rule 50 counter
1075 /// Position::do_castle_move() is a private method used to make a castling
1076 /// move. It is called from the main Position::do_move function. Note that
1077 /// castling moves are encoded as "king captures friendly rook" moves, for
1078 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1080 void Position::do_castle_move(Move m) {
1082 assert(move_is_ok(m));
1083 assert(move_is_castle(m));
1085 Color us = side_to_move();
1086 Color them = opposite_color(us);
1088 // Reset capture field
1089 st->capturedType = PIECE_TYPE_NONE;
1091 // Find source squares for king and rook
1092 Square kfrom = move_from(m);
1093 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1096 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1097 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1099 // Find destination squares for king and rook
1100 if (rfrom > kfrom) // O-O
1102 kto = relative_square(us, SQ_G1);
1103 rto = relative_square(us, SQ_F1);
1105 kto = relative_square(us, SQ_C1);
1106 rto = relative_square(us, SQ_D1);
1109 // Remove pieces from source squares:
1110 clear_bit(&(byColorBB[us]), kfrom);
1111 clear_bit(&(byTypeBB[KING]), kfrom);
1112 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1113 clear_bit(&(byColorBB[us]), rfrom);
1114 clear_bit(&(byTypeBB[ROOK]), rfrom);
1115 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1117 // Put pieces on destination squares:
1118 set_bit(&(byColorBB[us]), kto);
1119 set_bit(&(byTypeBB[KING]), kto);
1120 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1121 set_bit(&(byColorBB[us]), rto);
1122 set_bit(&(byTypeBB[ROOK]), rto);
1123 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1125 // Update board array
1126 Piece king = piece_of_color_and_type(us, KING);
1127 Piece rook = piece_of_color_and_type(us, ROOK);
1128 board[kfrom] = board[rfrom] = PIECE_NONE;
1132 // Update piece lists
1133 pieceList[us][KING][index[kfrom]] = kto;
1134 pieceList[us][ROOK][index[rfrom]] = rto;
1135 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1136 index[kto] = index[kfrom];
1139 // Update incremental scores
1140 st->value += pst_delta(king, kfrom, kto);
1141 st->value += pst_delta(rook, rfrom, rto);
1144 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1145 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1147 // Clear en passant square
1148 if (st->epSquare != SQ_NONE)
1150 st->key ^= zobEp[st->epSquare];
1151 st->epSquare = SQ_NONE;
1154 // Update castling rights
1155 st->key ^= zobCastle[st->castleRights];
1156 st->castleRights &= castleRightsMask[kfrom];
1157 st->key ^= zobCastle[st->castleRights];
1159 // Reset rule 50 counter
1162 // Update checkers BB
1163 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1166 sideToMove = opposite_color(sideToMove);
1167 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1173 /// Position::undo_move() unmakes a move. When it returns, the position should
1174 /// be restored to exactly the same state as before the move was made.
1176 void Position::undo_move(Move m) {
1179 assert(move_is_ok(m));
1181 sideToMove = opposite_color(sideToMove);
1183 if (move_is_castle(m))
1185 undo_castle_move(m);
1189 Color us = side_to_move();
1190 Color them = opposite_color(us);
1191 Square from = move_from(m);
1192 Square to = move_to(m);
1193 bool ep = move_is_ep(m);
1194 bool pm = move_is_promotion(m);
1196 PieceType pt = type_of_piece_on(to);
1198 assert(square_is_empty(from));
1199 assert(color_of_piece_on(to) == us);
1200 assert(!pm || relative_rank(us, to) == RANK_8);
1201 assert(!ep || to == st->previous->epSquare);
1202 assert(!ep || relative_rank(us, to) == RANK_6);
1203 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1205 if (pm) // promotion ?
1207 PieceType promotion = move_promotion_piece(m);
1210 assert(promotion >= KNIGHT && promotion <= QUEEN);
1211 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1213 // Replace promoted piece with a pawn
1214 clear_bit(&(byTypeBB[promotion]), to);
1215 set_bit(&(byTypeBB[PAWN]), to);
1217 // Update piece counts
1218 pieceCount[us][promotion]--;
1219 pieceCount[us][PAWN]++;
1221 // Update piece list replacing promotion piece with a pawn
1222 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1223 index[lastPromotionSquare] = index[to];
1224 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1225 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1226 index[to] = pieceCount[us][PAWN] - 1;
1227 pieceList[us][PAWN][index[to]] = to;
1230 // Put the piece back at the source square
1231 Bitboard move_bb = make_move_bb(to, from);
1232 do_move_bb(&(byColorBB[us]), move_bb);
1233 do_move_bb(&(byTypeBB[pt]), move_bb);
1234 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1236 board[from] = piece_of_color_and_type(us, pt);
1237 board[to] = PIECE_NONE;
1239 // Update piece list
1240 index[from] = index[to];
1241 pieceList[us][pt][index[from]] = from;
1243 if (st->capturedType)
1248 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1250 assert(st->capturedType != KING);
1251 assert(!ep || square_is_empty(capsq));
1253 // Restore the captured piece
1254 set_bit(&(byColorBB[them]), capsq);
1255 set_bit(&(byTypeBB[st->capturedType]), capsq);
1256 set_bit(&(byTypeBB[0]), capsq);
1258 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1260 // Update piece count
1261 pieceCount[them][st->capturedType]++;
1263 // Update piece list, add a new captured piece in capsq square
1264 index[capsq] = pieceCount[them][st->capturedType] - 1;
1265 pieceList[them][st->capturedType][index[capsq]] = capsq;
1268 // Finally point our state pointer back to the previous state
1275 /// Position::undo_castle_move() is a private method used to unmake a castling
1276 /// move. It is called from the main Position::undo_move function. Note that
1277 /// castling moves are encoded as "king captures friendly rook" moves, for
1278 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1280 void Position::undo_castle_move(Move m) {
1282 assert(move_is_ok(m));
1283 assert(move_is_castle(m));
1285 // When we have arrived here, some work has already been done by
1286 // Position::undo_move. In particular, the side to move has been switched,
1287 // so the code below is correct.
1288 Color us = side_to_move();
1290 // Find source squares for king and rook
1291 Square kfrom = move_from(m);
1292 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1295 // Find destination squares for king and rook
1296 if (rfrom > kfrom) // O-O
1298 kto = relative_square(us, SQ_G1);
1299 rto = relative_square(us, SQ_F1);
1301 kto = relative_square(us, SQ_C1);
1302 rto = relative_square(us, SQ_D1);
1305 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1306 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1308 // Remove pieces from destination squares:
1309 clear_bit(&(byColorBB[us]), kto);
1310 clear_bit(&(byTypeBB[KING]), kto);
1311 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1312 clear_bit(&(byColorBB[us]), rto);
1313 clear_bit(&(byTypeBB[ROOK]), rto);
1314 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1316 // Put pieces on source squares:
1317 set_bit(&(byColorBB[us]), kfrom);
1318 set_bit(&(byTypeBB[KING]), kfrom);
1319 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1320 set_bit(&(byColorBB[us]), rfrom);
1321 set_bit(&(byTypeBB[ROOK]), rfrom);
1322 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1325 board[rto] = board[kto] = PIECE_NONE;
1326 board[rfrom] = piece_of_color_and_type(us, ROOK);
1327 board[kfrom] = piece_of_color_and_type(us, KING);
1329 // Update piece lists
1330 pieceList[us][KING][index[kto]] = kfrom;
1331 pieceList[us][ROOK][index[rto]] = rfrom;
1332 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1333 index[kfrom] = index[kto];
1336 // Finally point our state pointer back to the previous state
1343 /// Position::do_null_move makes() a "null move": It switches the side to move
1344 /// and updates the hash key without executing any move on the board.
1346 void Position::do_null_move(StateInfo& backupSt) {
1349 assert(!is_check());
1351 // Back up the information necessary to undo the null move to the supplied
1352 // StateInfo object.
1353 // Note that differently from normal case here backupSt is actually used as
1354 // a backup storage not as a new state to be used.
1355 backupSt.key = st->key;
1356 backupSt.epSquare = st->epSquare;
1357 backupSt.value = st->value;
1358 backupSt.previous = st->previous;
1359 backupSt.pliesFromNull = st->pliesFromNull;
1360 st->previous = &backupSt;
1362 // Save the current key to the history[] array, in order to be able to
1363 // detect repetition draws.
1364 history[st->gamePly++] = st->key;
1366 // Update the necessary information
1367 if (st->epSquare != SQ_NONE)
1368 st->key ^= zobEp[st->epSquare];
1370 st->key ^= zobSideToMove;
1371 prefetch((char*)TT.first_entry(st->key));
1373 sideToMove = opposite_color(sideToMove);
1374 st->epSquare = SQ_NONE;
1376 st->pliesFromNull = 0;
1377 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1381 /// Position::undo_null_move() unmakes a "null move".
1383 void Position::undo_null_move() {
1386 assert(!is_check());
1388 // Restore information from the our backup StateInfo object
1389 StateInfo* backupSt = st->previous;
1390 st->key = backupSt->key;
1391 st->epSquare = backupSt->epSquare;
1392 st->value = backupSt->value;
1393 st->previous = backupSt->previous;
1394 st->pliesFromNull = backupSt->pliesFromNull;
1396 // Update the necessary information
1397 sideToMove = opposite_color(sideToMove);
1403 /// Position::see() is a static exchange evaluator: It tries to estimate the
1404 /// material gain or loss resulting from a move. There are three versions of
1405 /// this function: One which takes a destination square as input, one takes a
1406 /// move, and one which takes a 'from' and a 'to' square. The function does
1407 /// not yet understand promotions captures.
1409 int Position::see(Move m) const {
1411 assert(move_is_ok(m));
1412 return see(move_from(m), move_to(m));
1415 int Position::see_sign(Move m) const {
1417 assert(move_is_ok(m));
1419 Square from = move_from(m);
1420 Square to = move_to(m);
1422 // Early return if SEE cannot be negative because captured piece value
1423 // is not less then capturing one. Note that king moves always return
1424 // here because king midgame value is set to 0.
1425 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1428 return see(from, to);
1431 int Position::see(Square from, Square to) const {
1433 Bitboard occupied, attackers, stmAttackers, b;
1434 int swapList[32], slIndex = 1;
1435 PieceType capturedType, pt;
1438 assert(square_is_ok(from));
1439 assert(square_is_ok(to));
1441 capturedType = type_of_piece_on(to);
1443 // King cannot be recaptured
1444 if (capturedType == KING)
1445 return seeValues[capturedType];
1447 occupied = occupied_squares();
1449 // Handle en passant moves
1450 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1452 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1454 assert(capturedType == PIECE_TYPE_NONE);
1455 assert(type_of_piece_on(capQq) == PAWN);
1457 // Remove the captured pawn
1458 clear_bit(&occupied, capQq);
1459 capturedType = PAWN;
1462 // Find all attackers to the destination square, with the moving piece
1463 // removed, but possibly an X-ray attacker added behind it.
1464 clear_bit(&occupied, from);
1465 attackers = (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1466 | (bishop_attacks_bb(to, occupied)& pieces(BISHOP, QUEEN))
1467 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1468 | (attacks_from<KING>(to) & pieces(KING))
1469 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1470 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1472 // If the opponent has no attackers we are finished
1473 stm = opposite_color(color_of_piece_on(from));
1474 stmAttackers = attackers & pieces_of_color(stm);
1476 return seeValues[capturedType];
1478 // The destination square is defended, which makes things rather more
1479 // difficult to compute. We proceed by building up a "swap list" containing
1480 // the material gain or loss at each stop in a sequence of captures to the
1481 // destination square, where the sides alternately capture, and always
1482 // capture with the least valuable piece. After each capture, we look for
1483 // new X-ray attacks from behind the capturing piece.
1484 swapList[0] = seeValues[capturedType];
1485 capturedType = type_of_piece_on(from);
1488 // Locate the least valuable attacker for the side to move. The loop
1489 // below looks like it is potentially infinite, but it isn't. We know
1490 // that the side to move still has at least one attacker left.
1491 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1494 // Remove the attacker we just found from the 'occupied' bitboard,
1495 // and scan for new X-ray attacks behind the attacker.
1496 b = stmAttackers & pieces(pt);
1497 occupied ^= (b & (~b + 1));
1498 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1499 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1501 attackers &= occupied; // Cut out pieces we've already done
1503 // Add the new entry to the swap list
1504 assert(slIndex < 32);
1505 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1508 // Remember the value of the capturing piece, and change the side to
1509 // move before beginning the next iteration.
1511 stm = opposite_color(stm);
1512 stmAttackers = attackers & pieces_of_color(stm);
1514 // Stop before processing a king capture
1515 if (capturedType == KING && stmAttackers)
1517 assert(slIndex < 32);
1518 swapList[slIndex++] = QueenValueMidgame*10;
1521 } while (stmAttackers);
1523 // Having built the swap list, we negamax through it to find the best
1524 // achievable score from the point of view of the side to move.
1526 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1532 /// Position::clear() erases the position object to a pristine state, with an
1533 /// empty board, white to move, and no castling rights.
1535 void Position::clear() {
1538 memset(st, 0, sizeof(StateInfo));
1539 st->epSquare = SQ_NONE;
1540 startPosPlyCounter = 0;
1543 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1544 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1545 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1546 memset(index, 0, sizeof(int) * 64);
1548 for (int i = 0; i < 64; i++)
1549 board[i] = PIECE_NONE;
1551 for (int i = 0; i < 8; i++)
1552 for (int j = 0; j < 16; j++)
1553 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1555 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1556 castleRightsMask[sq] = ALL_CASTLES;
1559 initialKFile = FILE_E;
1560 initialKRFile = FILE_H;
1561 initialQRFile = FILE_A;
1565 /// Position::put_piece() puts a piece on the given square of the board,
1566 /// updating the board array, pieces list, bitboards, and piece counts.
1568 void Position::put_piece(Piece p, Square s) {
1570 Color c = color_of_piece(p);
1571 PieceType pt = type_of_piece(p);
1574 index[s] = pieceCount[c][pt]++;
1575 pieceList[c][pt][index[s]] = s;
1577 set_bit(&(byTypeBB[pt]), s);
1578 set_bit(&(byColorBB[c]), s);
1579 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
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 = zobCastle[st->castleRights];
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 if (side_to_move() == BLACK)
1600 result ^= zobSideToMove;
1606 /// Position::compute_pawn_key() computes the hash key of the position. The
1607 /// hash key is usually updated incrementally as moves are made and unmade,
1608 /// the compute_pawn_key() function is only used when a new position is set
1609 /// up, and to verify the correctness of the pawn hash key when running in
1612 Key Position::compute_pawn_key() const {
1617 for (Color c = WHITE; c <= BLACK; c++)
1619 b = pieces(PAWN, c);
1621 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1627 /// Position::compute_material_key() computes the hash key of the position.
1628 /// The hash key is usually updated incrementally as moves are made and unmade,
1629 /// the compute_material_key() function is only used when a new position is set
1630 /// up, and to verify the correctness of the material hash key when running in
1633 Key Position::compute_material_key() const {
1638 for (Color c = WHITE; c <= BLACK; c++)
1639 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1641 count = piece_count(c, pt);
1642 for (int i = 0; i < count; i++)
1643 result ^= zobrist[c][pt][i];
1649 /// Position::compute_value() compute the incremental scores for the middle
1650 /// game and the endgame. These functions are used to initialize the incremental
1651 /// scores when a new position is set up, and to verify that the scores are correctly
1652 /// updated by do_move and undo_move when the program is running in debug mode.
1653 Score Position::compute_value() const {
1656 Score result = SCORE_ZERO;
1658 for (Color c = WHITE; c <= BLACK; c++)
1659 for (PieceType pt = PAWN; pt <= KING; pt++)
1663 result += pst(c, pt, pop_1st_bit(&b));
1666 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1671 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1672 /// game material value for the given side. Material values are updated
1673 /// incrementally during the search, this function is only used while
1674 /// initializing a new Position object.
1676 Value Position::compute_non_pawn_material(Color c) const {
1678 Value result = VALUE_ZERO;
1680 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1681 result += piece_count(c, pt) * PieceValueMidgame[pt];
1687 /// Position::is_draw() tests whether the position is drawn by material,
1688 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1689 /// must be done by the search.
1691 bool Position::is_draw() const {
1693 // Draw by material?
1695 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1698 // Draw by the 50 moves rule?
1699 if (st->rule50 > 99 && !is_mate())
1702 // Draw by repetition?
1703 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1704 if (history[st->gamePly - i] == st->key)
1711 /// Position::is_mate() returns true or false depending on whether the
1712 /// side to move is checkmated.
1714 bool Position::is_mate() const {
1716 MoveStack moves[MOVES_MAX];
1717 return is_check() && generate<MV_LEGAL>(*this, moves) == moves;
1721 /// Position::has_mate_threat() tests whether the side to move is under
1722 /// a threat of being mated in one from the current position.
1724 bool Position::has_mate_threat() {
1726 MoveStack mlist[MOVES_MAX], *last, *cur;
1728 bool mateFound = false;
1730 // If we are under check it's up to evasions to do the job
1734 // First pass the move to our opponent doing a null move
1737 // Then generate pseudo-legal moves that could give check
1738 last = generate<MV_NON_CAPTURE_CHECK>(*this, mlist);
1739 last = generate<MV_CAPTURE>(*this, last);
1741 // Loop through the moves, and see if one of them gives mate
1742 Bitboard pinned = pinned_pieces(sideToMove);
1743 CheckInfo ci(*this);
1744 for (cur = mlist; cur != last && !mateFound; cur++)
1746 Move move = cur->move;
1747 if ( !pl_move_is_legal(move, pinned)
1748 || !move_is_check(move, ci))
1751 do_move(move, st2, ci, true);
1764 /// Position::init_zobrist() is a static member function which initializes at
1765 /// startup the various arrays used to compute hash keys.
1767 void Position::init_zobrist() {
1772 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1773 zobrist[i][j][k] = rk.rand<Key>();
1775 for (i = 0; i < 64; i++)
1776 zobEp[i] = rk.rand<Key>();
1778 for (i = 0; i < 16; i++)
1779 zobCastle[i] = rk.rand<Key>();
1781 zobSideToMove = rk.rand<Key>();
1782 zobExclusion = rk.rand<Key>();
1786 /// Position::init_piece_square_tables() initializes the piece square tables.
1787 /// This is a two-step operation: First, the white halves of the tables are
1788 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1789 /// of the tables are initialized by mirroring and changing the sign of the
1790 /// corresponding white scores.
1792 void Position::init_piece_square_tables() {
1794 for (Square s = SQ_A1; s <= SQ_H8; s++)
1795 for (Piece p = WP; p <= WK; p++)
1796 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1798 for (Square s = SQ_A1; s <= SQ_H8; s++)
1799 for (Piece p = BP; p <= BK; p++)
1800 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1804 /// Position::flipped_copy() makes a copy of the input position, but with
1805 /// the white and black sides reversed. This is only useful for debugging,
1806 /// especially for finding evaluation symmetry bugs.
1808 void Position::flipped_copy(const Position& pos) {
1810 assert(pos.is_ok());
1813 threadID = pos.thread();
1816 for (Square s = SQ_A1; s <= SQ_H8; s++)
1817 if (!pos.square_is_empty(s))
1818 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1821 sideToMove = opposite_color(pos.side_to_move());
1824 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1825 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1826 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1827 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1829 initialKFile = pos.initialKFile;
1830 initialKRFile = pos.initialKRFile;
1831 initialQRFile = pos.initialQRFile;
1833 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1834 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1835 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1836 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1837 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1838 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1840 // En passant square
1841 if (pos.st->epSquare != SQ_NONE)
1842 st->epSquare = flip_square(pos.st->epSquare);
1848 st->key = compute_key();
1849 st->pawnKey = compute_pawn_key();
1850 st->materialKey = compute_material_key();
1852 // Incremental scores
1853 st->value = compute_value();
1856 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1857 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1863 /// Position::is_ok() performs some consitency checks for the position object.
1864 /// This is meant to be helpful when debugging.
1866 bool Position::is_ok(int* failedStep) const {
1868 // What features of the position should be verified?
1869 const bool debugAll = false;
1871 const bool debugBitboards = debugAll || false;
1872 const bool debugKingCount = debugAll || false;
1873 const bool debugKingCapture = debugAll || false;
1874 const bool debugCheckerCount = debugAll || false;
1875 const bool debugKey = debugAll || false;
1876 const bool debugMaterialKey = debugAll || false;
1877 const bool debugPawnKey = debugAll || false;
1878 const bool debugIncrementalEval = debugAll || false;
1879 const bool debugNonPawnMaterial = debugAll || false;
1880 const bool debugPieceCounts = debugAll || false;
1881 const bool debugPieceList = debugAll || false;
1882 const bool debugCastleSquares = debugAll || false;
1884 if (failedStep) *failedStep = 1;
1887 if (!color_is_ok(side_to_move()))
1890 // Are the king squares in the position correct?
1891 if (failedStep) (*failedStep)++;
1892 if (piece_on(king_square(WHITE)) != WK)
1895 if (failedStep) (*failedStep)++;
1896 if (piece_on(king_square(BLACK)) != BK)
1900 if (failedStep) (*failedStep)++;
1901 if (!file_is_ok(initialKRFile))
1904 if (!file_is_ok(initialQRFile))
1907 // Do both sides have exactly one king?
1908 if (failedStep) (*failedStep)++;
1911 int kingCount[2] = {0, 0};
1912 for (Square s = SQ_A1; s <= SQ_H8; s++)
1913 if (type_of_piece_on(s) == KING)
1914 kingCount[color_of_piece_on(s)]++;
1916 if (kingCount[0] != 1 || kingCount[1] != 1)
1920 // Can the side to move capture the opponent's king?
1921 if (failedStep) (*failedStep)++;
1922 if (debugKingCapture)
1924 Color us = side_to_move();
1925 Color them = opposite_color(us);
1926 Square ksq = king_square(them);
1927 if (attackers_to(ksq) & pieces_of_color(us))
1931 // Is there more than 2 checkers?
1932 if (failedStep) (*failedStep)++;
1933 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1937 if (failedStep) (*failedStep)++;
1940 // The intersection of the white and black pieces must be empty
1941 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1944 // The union of the white and black pieces must be equal to all
1946 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1949 // Separate piece type bitboards must have empty intersections
1950 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1951 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1952 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1956 // En passant square OK?
1957 if (failedStep) (*failedStep)++;
1958 if (ep_square() != SQ_NONE)
1960 // The en passant square must be on rank 6, from the point of view of the
1962 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1967 if (failedStep) (*failedStep)++;
1968 if (debugKey && st->key != compute_key())
1971 // Pawn hash key OK?
1972 if (failedStep) (*failedStep)++;
1973 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1976 // Material hash key OK?
1977 if (failedStep) (*failedStep)++;
1978 if (debugMaterialKey && st->materialKey != compute_material_key())
1981 // Incremental eval OK?
1982 if (failedStep) (*failedStep)++;
1983 if (debugIncrementalEval && st->value != compute_value())
1986 // Non-pawn material OK?
1987 if (failedStep) (*failedStep)++;
1988 if (debugNonPawnMaterial)
1990 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1993 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1998 if (failedStep) (*failedStep)++;
1999 if (debugPieceCounts)
2000 for (Color c = WHITE; c <= BLACK; c++)
2001 for (PieceType pt = PAWN; pt <= KING; pt++)
2002 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2005 if (failedStep) (*failedStep)++;
2008 for (Color c = WHITE; c <= BLACK; c++)
2009 for (PieceType pt = PAWN; pt <= KING; pt++)
2010 for (int i = 0; i < pieceCount[c][pt]; i++)
2012 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2015 if (index[piece_list(c, pt, i)] != i)
2020 if (failedStep) (*failedStep)++;
2021 if (debugCastleSquares) {
2022 for (Color c = WHITE; c <= BLACK; c++) {
2023 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2025 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2028 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2030 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2032 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2034 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2038 if (failedStep) *failedStep = 0;