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/>.
33 #include "ucioption.h"
39 Key Position::zobrist[2][8][64];
40 Key Position::zobEp[64];
41 Key Position::zobCastle[16];
42 Key Position::zobSideToMove;
43 Key Position::zobExclusion;
45 Score Position::pieceSquareTable[16][64];
47 // Material values arrays, indexed by Piece
48 const Value PieceValueMidgame[17] = {
50 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
51 RookValueMidgame, QueenValueMidgame,
52 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
53 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
54 RookValueMidgame, QueenValueMidgame
57 const Value PieceValueEndgame[17] = {
59 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
60 RookValueEndgame, QueenValueEndgame,
61 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
62 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
63 RookValueEndgame, QueenValueEndgame
69 // Bonus for having the side to move (modified by Joona Kiiski)
70 const Score TempoValue = make_score(48, 22);
72 // To convert a Piece to and from a FEN char
73 const string PieceToChar(".PNBRQK pnbrqk ");
79 CheckInfo::CheckInfo(const Position& pos) {
81 Color us = pos.side_to_move();
82 Color them = opposite_color(us);
83 Square ksq = pos.king_square(them);
85 dcCandidates = pos.discovered_check_candidates(us);
86 pinned = pos.pinned_pieces(us);
88 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
89 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
90 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
91 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
92 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
93 checkSq[KING] = EmptyBoardBB;
97 /// Position c'tors. Here we always create a copy of the original position
98 /// or the FEN string, we want the new born Position object do not depend
99 /// on any external data so we detach state pointer from the source one.
101 Position::Position(const Position& pos, int th) {
103 memcpy(this, &pos, sizeof(Position));
104 detach(); // Always detach() in copy c'tor to avoid surprises
109 Position::Position(const string& fen, bool isChess960, int th) {
111 from_fen(fen, isChess960);
116 /// Position::detach() copies the content of the current state and castling
117 /// masks inside the position itself. This is needed when the st pointee could
118 /// become stale, as example because the caller is about to going out of scope.
120 void Position::detach() {
124 st->previous = NULL; // As a safe guard
128 /// Position::from_fen() initializes the position object with the given FEN
129 /// string. This function is not very robust - make sure that input FENs are
130 /// correct (this is assumed to be the responsibility of the GUI).
132 void Position::from_fen(const string& fen, bool isChess960) {
134 A FEN string defines a particular position using only the ASCII character set.
136 A FEN string contains six fields. The separator between fields is a space. The fields are:
138 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
139 with rank 1; within each rank, the contents of each square are described from file A through file H.
140 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
141 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
142 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
143 of blank squares), and "/" separate ranks.
145 2) Active color. "w" means white moves next, "b" means black.
147 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
148 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
149 kingside), and/or "q" (Black can castle queenside).
151 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
152 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
153 regardless of whether there is a pawn in position to make an en passant capture.
155 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
156 to determine if a draw can be claimed under the fifty-move rule.
158 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
161 char col, row, token;
164 std::istringstream ss(fen);
169 // 1. Piece placement
170 while ((ss >> token) && !isspace(token))
173 sq -= Square(16); // Jump back of 2 rows
175 else if (isdigit(token))
176 sq += Square(token - '0'); // Skip the given number of files
178 else if ((p = PieceToChar.find(token)) != string::npos)
180 put_piece(Piece(p), sq);
187 sideToMove = (token == 'w' ? WHITE : BLACK);
190 // 3. Castling availability
191 while ((ss >> token) && !isspace(token))
192 set_castling_rights(token);
194 // 4. En passant square. Ignore if no pawn capture is possible
195 if ( ((ss >> col) && (col >= 'a' && col <= 'h'))
196 && ((ss >> row) && (row == '3' || row == '6')))
198 st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
199 Color them = opposite_color(sideToMove);
201 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
202 st->epSquare = SQ_NONE;
205 // 5-6. Halfmove clock and fullmove number
206 ss >> std::skipws >> st->rule50 >> fullMoves;
208 // Various initialisations
209 chess960 = isChess960;
210 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(opposite_color(sideToMove));
212 st->key = compute_key();
213 st->pawnKey = compute_pawn_key();
214 st->materialKey = compute_material_key();
215 st->value = compute_value();
216 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
217 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
221 /// Position::set_castle() is an helper function used to set
222 /// correct castling related flags.
224 void Position::set_castle(int f, Square ksq, Square rsq) {
226 st->castleRights |= f;
227 castleRightsMask[ksq] ^= f;
228 castleRightsMask[rsq] ^= f;
229 castleRookSquare[f] = rsq;
233 /// Position::set_castling_rights() sets castling parameters castling avaiability.
234 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
235 /// that uses the letters of the columns on which the rooks began the game instead
236 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
237 /// associated with the castling right, the traditional castling tag will be replaced
238 /// by the file letter of the involved rook as for the Shredder-FEN.
240 void Position::set_castling_rights(char token) {
242 Color c = islower(token) ? BLACK : WHITE;
244 Square sqA = relative_square(c, SQ_A1);
245 Square sqH = relative_square(c, SQ_H1);
246 Square rsq, ksq = king_square(c);
248 token = char(toupper(token));
251 for (rsq = sqH; piece_on(rsq) != make_piece(c, ROOK); rsq--) {}
253 else if (token == 'Q')
254 for (rsq = sqA; piece_on(rsq) != make_piece(c, ROOK); rsq++) {}
256 else if (token >= 'A' && token <= 'H')
257 rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
261 if (square_file(rsq) < square_file(ksq))
262 set_castle(WHITE_OOO << c, ksq, rsq);
264 set_castle(WHITE_OO << c, ksq, rsq);
268 /// Position::to_fen() returns a FEN representation of the position. In case
269 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
271 const string Position::to_fen() const {
277 for (Rank rank = RANK_8; rank >= RANK_1; rank--, fen += '/')
281 for (File file = FILE_A; file <= FILE_H; file++)
283 sq = make_square(file, rank);
285 if (!square_is_empty(sq))
292 fen += PieceToChar[piece_on(sq)];
301 fen += (sideToMove == WHITE ? " w " : " b ");
303 if (st->castleRights != CASTLES_NONE)
305 if (can_castle(WHITE_OO))
306 fen += chess960 ? char(toupper(file_to_char(square_file(castle_rook_square(WHITE_OO))))) : 'K';
308 if (can_castle(WHITE_OOO))
309 fen += chess960 ? char(toupper(file_to_char(square_file(castle_rook_square(WHITE_OOO))))) : 'Q';
311 if (can_castle(BLACK_OO))
312 fen += chess960 ? file_to_char(square_file(castle_rook_square(BLACK_OO))) : 'k';
314 if (can_castle(BLACK_OOO))
315 fen += chess960 ? file_to_char(square_file(castle_rook_square(BLACK_OOO))) : 'q';
319 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
324 /// Position::print() prints an ASCII representation of the position to
325 /// the standard output. If a move is given then also the san is printed.
327 void Position::print(Move move) const {
329 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
333 Position p(*this, thread());
334 string dd = (piece_color(piece_on(move_from(move))) == BLACK ? ".." : "");
335 cout << "\nMove is: " << dd << move_to_san(p, move);
338 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
340 cout << dottedLine << '|';
341 for (File file = FILE_A; file <= FILE_H; file++)
343 Square sq = make_square(file, rank);
344 Piece piece = piece_on(sq);
346 if (piece == PIECE_NONE && square_color(sq) == DARK)
347 piece = PIECE_NONE_DARK_SQ;
349 char c = (piece_color(piece_on(sq)) == BLACK ? '=' : ' ');
350 cout << c << PieceToChar[piece] << c << '|';
353 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
357 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
358 /// king) pieces for the given color and for the given pinner type. Or, when
359 /// template parameter FindPinned is false, the pieces of the given color
360 /// candidate for a discovery check against the enemy king.
361 /// Bitboard checkersBB must be already updated when looking for pinners.
363 template<bool FindPinned>
364 Bitboard Position::hidden_checkers(Color c) const {
366 Bitboard result = EmptyBoardBB;
367 Bitboard pinners = pieces(FindPinned ? opposite_color(c) : c);
369 // Pinned pieces protect our king, dicovery checks attack
371 Square ksq = king_square(FindPinned ? c : opposite_color(c));
373 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
374 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
376 if (FindPinned && pinners)
377 pinners &= ~st->checkersBB;
381 Square s = pop_1st_bit(&pinners);
382 Bitboard b = squares_between(s, ksq) & occupied_squares();
386 if ( !(b & (b - 1)) // Only one bit set?
387 && (b & pieces(c))) // Is an our piece?
394 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
395 /// king) pieces for the given color. Note that checkersBB bitboard must
396 /// be already updated.
398 Bitboard Position::pinned_pieces(Color c) const {
400 return hidden_checkers<true>(c);
404 /// Position:discovered_check_candidates() returns a bitboard containing all
405 /// pieces for the given side which are candidates for giving a discovered
406 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
407 /// to be already updated.
409 Bitboard Position::discovered_check_candidates(Color c) const {
411 return hidden_checkers<false>(c);
414 /// Position::attackers_to() computes a bitboard containing all pieces which
415 /// attacks a given square.
417 Bitboard Position::attackers_to(Square s) const {
419 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
420 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
421 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
422 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
423 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
424 | (attacks_from<KING>(s) & pieces(KING));
427 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
429 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
430 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
431 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
432 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
433 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
434 | (attacks_from<KING>(s) & pieces(KING));
437 /// Position::attacks_from() computes a bitboard of all attacks
438 /// of a given piece put in a given square.
440 Bitboard Position::attacks_from(Piece p, Square s) const {
442 assert(square_is_ok(s));
446 case WB: case BB: return attacks_from<BISHOP>(s);
447 case WR: case BR: return attacks_from<ROOK>(s);
448 case WQ: case BQ: return attacks_from<QUEEN>(s);
449 default: return StepAttacksBB[p][s];
453 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
455 assert(square_is_ok(s));
459 case WB: case BB: return bishop_attacks_bb(s, occ);
460 case WR: case BR: return rook_attacks_bb(s, occ);
461 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
462 default: return StepAttacksBB[p][s];
467 /// Position::move_attacks_square() tests whether a move from the current
468 /// position attacks a given square.
470 bool Position::move_attacks_square(Move m, Square s) const {
472 assert(move_is_ok(m));
473 assert(square_is_ok(s));
476 Square f = move_from(m), t = move_to(m);
478 assert(!square_is_empty(f));
480 if (bit_is_set(attacks_from(piece_on(f), t), s))
483 // Move the piece and scan for X-ray attacks behind it
484 occ = occupied_squares();
485 do_move_bb(&occ, make_move_bb(f, t));
486 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
487 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
488 & pieces(piece_color(piece_on(f)));
490 // If we have attacks we need to verify that are caused by our move
491 // and are not already existent ones.
492 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
496 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
498 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
501 assert(move_is_ok(m));
502 assert(pinned == pinned_pieces(side_to_move()));
504 Color us = side_to_move();
505 Square from = move_from(m);
507 assert(piece_color(piece_on(from)) == us);
508 assert(piece_on(king_square(us)) == make_piece(us, KING));
510 // En passant captures are a tricky special case. Because they are
511 // rather uncommon, we do it simply by testing whether the king is attacked
512 // after the move is made
515 Color them = opposite_color(us);
516 Square to = move_to(m);
517 Square capsq = make_square(square_file(to), square_rank(from));
518 Square ksq = king_square(us);
519 Bitboard b = occupied_squares();
521 assert(to == ep_square());
522 assert(piece_on(from) == make_piece(us, PAWN));
523 assert(piece_on(capsq) == make_piece(them, PAWN));
524 assert(piece_on(to) == PIECE_NONE);
527 clear_bit(&b, capsq);
530 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
531 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
534 // If the moving piece is a king, check whether the destination
535 // square is attacked by the opponent. Castling moves are checked
536 // for legality during move generation.
537 if (piece_type(piece_on(from)) == KING)
538 return move_is_castle(m) || !(attackers_to(move_to(m)) & pieces(opposite_color(us)));
540 // A non-king move is legal if and only if it is not pinned or it
541 // is moving along the ray towards or away from the king.
543 || !bit_is_set(pinned, from)
544 || squares_aligned(from, move_to(m), king_square(us));
548 /// Position::move_is_legal() takes a move and tests whether the move
549 /// is legal. This version is not very fast and should be used only
550 /// in non time-critical paths.
552 bool Position::move_is_legal(const Move m) const {
554 for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
562 /// Fast version of Position::move_is_pl() that takes a move and a bitboard
563 /// of pinned pieces as input, and tests whether the move is pseudo legal.
565 bool Position::move_is_pl(const Move m) const {
569 Color us = sideToMove;
570 Color them = opposite_color(sideToMove);
571 Square from = move_from(m);
572 Square to = move_to(m);
573 Piece pc = piece_on(from);
575 // Use a slower but simpler function for uncommon cases
576 if (move_is_special(m))
577 return move_is_legal(m);
579 // Is not a promotion, so promotion piece must be empty
580 if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
583 // If the from square is not occupied by a piece belonging to the side to
584 // move, the move is obviously not legal.
585 if (pc == PIECE_NONE || piece_color(pc) != us)
588 // The destination square cannot be occupied by a friendly piece
589 if (piece_color(piece_on(to)) == us)
592 // Handle the special case of a pawn move
593 if (piece_type(pc) == PAWN)
595 // Move direction must be compatible with pawn color
596 int direction = to - from;
597 if ((us == WHITE) != (direction > 0))
600 // We have already handled promotion moves, so destination
601 // cannot be on the 8/1th rank.
602 if (square_rank(to) == RANK_8 || square_rank(to) == RANK_1)
605 // Proceed according to the square delta between the origin and
606 // destination squares.
613 // Capture. The destination square must be occupied by an enemy
614 // piece (en passant captures was handled earlier).
615 if (piece_color(piece_on(to)) != them)
618 // From and to files must be one file apart, avoids a7h5
619 if (abs(square_file(from) - square_file(to)) != 1)
625 // Pawn push. The destination square must be empty.
626 if (!square_is_empty(to))
631 // Double white pawn push. The destination square must be on the fourth
632 // rank, and both the destination square and the square between the
633 // source and destination squares must be empty.
634 if ( square_rank(to) != RANK_4
635 || !square_is_empty(to)
636 || !square_is_empty(from + DELTA_N))
641 // Double black pawn push. The destination square must be on the fifth
642 // rank, and both the destination square and the square between the
643 // source and destination squares must be empty.
644 if ( square_rank(to) != RANK_5
645 || !square_is_empty(to)
646 || !square_is_empty(from + DELTA_S))
654 else if (!bit_is_set(attacks_from(pc, from), to))
659 // In case of king moves under check we have to remove king so to catch
660 // as invalid moves like b1a1 when opposite queen is on c1.
661 if (piece_type(piece_on(from)) == KING)
663 Bitboard b = occupied_squares();
665 if (attackers_to(move_to(m), b) & pieces(opposite_color(us)))
670 Bitboard target = checkers();
671 Square checksq = pop_1st_bit(&target);
673 if (target) // double check ? In this case a king move is required
676 // Our move must be a blocking evasion or a capture of the checking piece
677 target = squares_between(checksq, king_square(us)) | checkers();
678 if (!bit_is_set(target, move_to(m)))
687 /// Position::move_gives_check() tests whether a pseudo-legal move is a check
689 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
692 assert(move_is_ok(m));
693 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
694 assert(piece_color(piece_on(move_from(m))) == side_to_move());
696 Square from = move_from(m);
697 Square to = move_to(m);
698 PieceType pt = piece_type(piece_on(from));
701 if (bit_is_set(ci.checkSq[pt], to))
705 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
707 // For pawn and king moves we need to verify also direction
708 if ( (pt != PAWN && pt != KING)
709 || !squares_aligned(from, to, king_square(opposite_color(side_to_move()))))
713 // Can we skip the ugly special cases ?
714 if (!move_is_special(m))
717 Color us = side_to_move();
718 Bitboard b = occupied_squares();
719 Square ksq = king_square(opposite_color(us));
721 // Promotion with check ?
722 if (move_is_promotion(m))
726 switch (promotion_piece_type(m))
729 return bit_is_set(attacks_from<KNIGHT>(to), ksq);
731 return bit_is_set(bishop_attacks_bb(to, b), ksq);
733 return bit_is_set(rook_attacks_bb(to, b), ksq);
735 return bit_is_set(queen_attacks_bb(to, b), ksq);
741 // En passant capture with check ? We have already handled the case
742 // of direct checks and ordinary discovered check, the only case we
743 // need to handle is the unusual case of a discovered check through
744 // the captured pawn.
747 Square capsq = make_square(square_file(to), square_rank(from));
749 clear_bit(&b, capsq);
751 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
752 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
755 // Castling with check ?
756 if (move_is_castle(m))
758 Square kfrom, kto, rfrom, rto;
764 kto = relative_square(us, SQ_G1);
765 rto = relative_square(us, SQ_F1);
767 kto = relative_square(us, SQ_C1);
768 rto = relative_square(us, SQ_D1);
770 clear_bit(&b, kfrom);
771 clear_bit(&b, rfrom);
774 return bit_is_set(rook_attacks_bb(rto, b), ksq);
781 /// Position::do_setup_move() makes a permanent move on the board. It should
782 /// be used when setting up a position on board. You can't undo the move.
784 void Position::do_setup_move(Move m) {
788 // Update the number of full moves after black's move
789 if (sideToMove == BLACK)
794 // Reset "game ply" in case we made a non-reversible move.
795 // "game ply" is used for repetition detection.
799 // Our StateInfo newSt is about going out of scope so copy
800 // its content before it disappears.
805 /// Position::do_move() makes a move, and saves all information necessary
806 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
807 /// moves should be filtered out before this function is called.
809 void Position::do_move(Move m, StateInfo& newSt) {
812 do_move(m, newSt, ci, move_gives_check(m, ci));
815 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
818 assert(move_is_ok(m));
819 assert(&newSt != st);
824 // Copy some fields of old state to our new StateInfo object except the
825 // ones which are recalculated from scratch anyway, then switch our state
826 // pointer to point to the new, ready to be updated, state.
827 struct ReducedStateInfo {
828 Key pawnKey, materialKey;
829 int castleRights, rule50, gamePly, pliesFromNull;
835 memcpy(&newSt, st, sizeof(ReducedStateInfo));
840 // Save the current key to the history[] array, in order to be able to
841 // detect repetition draws.
842 history[st->gamePly++] = key;
844 // Update side to move
845 key ^= zobSideToMove;
847 // Increment the 50 moves rule draw counter. Resetting it to zero in the
848 // case of non-reversible moves is taken care of later.
852 if (move_is_castle(m))
859 Color us = side_to_move();
860 Color them = opposite_color(us);
861 Square from = move_from(m);
862 Square to = move_to(m);
863 bool ep = move_is_ep(m);
864 bool pm = move_is_promotion(m);
866 Piece piece = piece_on(from);
867 PieceType pt = piece_type(piece);
868 PieceType capture = ep ? PAWN : piece_type(piece_on(to));
870 assert(piece_color(piece_on(from)) == us);
871 assert(piece_color(piece_on(to)) == them || square_is_empty(to));
872 assert(!(ep || pm) || piece == make_piece(us, PAWN));
873 assert(!pm || relative_rank(us, to) == RANK_8);
876 do_capture_move(key, capture, them, to, ep);
879 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
881 // Reset en passant square
882 if (st->epSquare != SQ_NONE)
884 key ^= zobEp[st->epSquare];
885 st->epSquare = SQ_NONE;
888 // Update castle rights if needed
889 if ( st->castleRights != CASTLES_NONE
890 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
892 key ^= zobCastle[st->castleRights];
893 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
894 key ^= zobCastle[st->castleRights];
897 // Prefetch TT access as soon as we know key is updated
898 prefetch((char*)TT.first_entry(key));
901 Bitboard move_bb = make_move_bb(from, to);
902 do_move_bb(&byColorBB[us], move_bb);
903 do_move_bb(&byTypeBB[pt], move_bb);
904 do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
906 board[to] = board[from];
907 board[from] = PIECE_NONE;
909 // Update piece lists, note that index[from] is not updated and
910 // becomes stale. This works as long as index[] is accessed just
911 // by known occupied squares.
912 index[to] = index[from];
913 pieceList[us][pt][index[to]] = to;
915 // If the moving piece was a pawn do some special extra work
918 // Reset rule 50 draw counter
921 // Update pawn hash key and prefetch in L1/L2 cache
922 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
924 // Set en passant square, only if moved pawn can be captured
925 if ((to ^ from) == 16)
927 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
929 st->epSquare = Square((int(from) + int(to)) / 2);
930 key ^= zobEp[st->epSquare];
934 if (pm) // promotion ?
936 PieceType promotion = promotion_piece_type(m);
938 assert(promotion >= KNIGHT && promotion <= QUEEN);
940 // Insert promoted piece instead of pawn
941 clear_bit(&byTypeBB[PAWN], to);
942 set_bit(&byTypeBB[promotion], to);
943 board[to] = make_piece(us, promotion);
945 // Update piece counts
946 pieceCount[us][promotion]++;
947 pieceCount[us][PAWN]--;
949 // Update material key
950 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
951 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
953 // Update piece lists, move the last pawn at index[to] position
954 // and shrink the list. Add a new promotion piece to the list.
955 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
956 index[lastPawnSquare] = index[to];
957 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
958 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
959 index[to] = pieceCount[us][promotion] - 1;
960 pieceList[us][promotion][index[to]] = to;
962 // Partially revert hash keys update
963 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
964 st->pawnKey ^= zobrist[us][PAWN][to];
966 // Partially revert and update incremental scores
967 st->value -= pst(make_piece(us, PAWN), to);
968 st->value += pst(make_piece(us, promotion), to);
971 st->npMaterial[us] += PieceValueMidgame[promotion];
975 // Prefetch pawn and material hash tables
976 Threads[threadID].pawnTable.prefetch(st->pawnKey);
977 Threads[threadID].materialTable.prefetch(st->materialKey);
979 // Update incremental scores
980 st->value += pst_delta(piece, from, to);
983 st->capturedType = capture;
985 // Update the key with the final value
988 // Update checkers bitboard, piece must be already moved
989 st->checkersBB = EmptyBoardBB;
994 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
998 if (bit_is_set(ci.checkSq[pt], to))
999 st->checkersBB = SetMaskBB[to];
1002 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1005 st->checkersBB |= (attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us));
1008 st->checkersBB |= (attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us));
1014 sideToMove = opposite_color(sideToMove);
1015 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1021 /// Position::do_capture_move() is a private method used to update captured
1022 /// piece info. It is called from the main Position::do_move function.
1024 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1026 assert(capture != KING);
1030 // If the captured piece was a pawn, update pawn hash key,
1031 // otherwise update non-pawn material.
1032 if (capture == PAWN)
1034 if (ep) // en passant ?
1036 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1038 assert(to == st->epSquare);
1039 assert(relative_rank(opposite_color(them), to) == RANK_6);
1040 assert(piece_on(to) == PIECE_NONE);
1041 assert(piece_on(capsq) == make_piece(them, PAWN));
1043 board[capsq] = PIECE_NONE;
1045 st->pawnKey ^= zobrist[them][PAWN][capsq];
1048 st->npMaterial[them] -= PieceValueMidgame[capture];
1050 // Remove captured piece
1051 clear_bit(&byColorBB[them], capsq);
1052 clear_bit(&byTypeBB[capture], capsq);
1053 clear_bit(&byTypeBB[0], capsq);
1056 key ^= zobrist[them][capture][capsq];
1058 // Update incremental scores
1059 st->value -= pst(make_piece(them, capture), capsq);
1061 // Update piece count
1062 pieceCount[them][capture]--;
1064 // Update material hash key
1065 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1067 // Update piece list, move the last piece at index[capsq] position
1069 // WARNING: This is a not perfectly revresible operation. When we
1070 // will reinsert the captured piece in undo_move() we will put it
1071 // at the end of the list and not in its original place, it means
1072 // index[] and pieceList[] are not guaranteed to be invariant to a
1073 // do_move() + undo_move() sequence.
1074 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1075 index[lastPieceSquare] = index[capsq];
1076 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1077 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1079 // Reset rule 50 counter
1084 /// Position::do_castle_move() is a private method used to make a castling
1085 /// move. It is called from the main Position::do_move function. Note that
1086 /// castling moves are encoded as "king captures friendly rook" moves, for
1087 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1089 void Position::do_castle_move(Move m) {
1091 assert(move_is_ok(m));
1092 assert(move_is_castle(m));
1094 Color us = side_to_move();
1095 Color them = opposite_color(us);
1097 // Find source squares for king and rook
1098 Square kfrom = move_from(m);
1099 Square rfrom = move_to(m);
1102 assert(piece_on(kfrom) == make_piece(us, KING));
1103 assert(piece_on(rfrom) == make_piece(us, ROOK));
1105 // Find destination squares for king and rook
1106 if (rfrom > kfrom) // O-O
1108 kto = relative_square(us, SQ_G1);
1109 rto = relative_square(us, SQ_F1);
1113 kto = relative_square(us, SQ_C1);
1114 rto = relative_square(us, SQ_D1);
1117 // Remove pieces from source squares
1118 clear_bit(&byColorBB[us], kfrom);
1119 clear_bit(&byTypeBB[KING], kfrom);
1120 clear_bit(&byTypeBB[0], kfrom);
1121 clear_bit(&byColorBB[us], rfrom);
1122 clear_bit(&byTypeBB[ROOK], rfrom);
1123 clear_bit(&byTypeBB[0], rfrom);
1125 // Put pieces on destination squares
1126 set_bit(&byColorBB[us], kto);
1127 set_bit(&byTypeBB[KING], kto);
1128 set_bit(&byTypeBB[0], kto);
1129 set_bit(&byColorBB[us], rto);
1130 set_bit(&byTypeBB[ROOK], rto);
1131 set_bit(&byTypeBB[0], rto);
1134 Piece king = make_piece(us, KING);
1135 Piece rook = make_piece(us, ROOK);
1136 board[kfrom] = board[rfrom] = PIECE_NONE;
1140 // Update piece lists
1141 pieceList[us][KING][index[kfrom]] = kto;
1142 pieceList[us][ROOK][index[rfrom]] = rto;
1143 int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1144 index[kto] = index[kfrom];
1147 // Reset capture field
1148 st->capturedType = PIECE_TYPE_NONE;
1150 // Update incremental scores
1151 st->value += pst_delta(king, kfrom, kto);
1152 st->value += pst_delta(rook, rfrom, rto);
1155 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1156 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1158 // Clear en passant square
1159 if (st->epSquare != SQ_NONE)
1161 st->key ^= zobEp[st->epSquare];
1162 st->epSquare = SQ_NONE;
1165 // Update castling rights
1166 st->key ^= zobCastle[st->castleRights];
1167 st->castleRights &= castleRightsMask[kfrom];
1168 st->key ^= zobCastle[st->castleRights];
1170 // Reset rule 50 counter
1173 // Update checkers BB
1174 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
1177 sideToMove = opposite_color(sideToMove);
1178 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1184 /// Position::undo_move() unmakes a move. When it returns, the position should
1185 /// be restored to exactly the same state as before the move was made.
1187 void Position::undo_move(Move m) {
1190 assert(move_is_ok(m));
1192 sideToMove = opposite_color(sideToMove);
1194 if (move_is_castle(m))
1196 undo_castle_move(m);
1200 Color us = side_to_move();
1201 Color them = opposite_color(us);
1202 Square from = move_from(m);
1203 Square to = move_to(m);
1204 bool ep = move_is_ep(m);
1205 bool pm = move_is_promotion(m);
1207 PieceType pt = piece_type(piece_on(to));
1209 assert(square_is_empty(from));
1210 assert(piece_color(piece_on(to)) == us);
1211 assert(!pm || relative_rank(us, to) == RANK_8);
1212 assert(!ep || to == st->previous->epSquare);
1213 assert(!ep || relative_rank(us, to) == RANK_6);
1214 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1216 if (pm) // promotion ?
1218 PieceType promotion = promotion_piece_type(m);
1221 assert(promotion >= KNIGHT && promotion <= QUEEN);
1222 assert(piece_on(to) == make_piece(us, promotion));
1224 // Replace promoted piece with a pawn
1225 clear_bit(&byTypeBB[promotion], to);
1226 set_bit(&byTypeBB[PAWN], to);
1228 // Update piece counts
1229 pieceCount[us][promotion]--;
1230 pieceCount[us][PAWN]++;
1232 // Update piece list replacing promotion piece with a pawn
1233 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1234 index[lastPromotionSquare] = index[to];
1235 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1236 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1237 index[to] = pieceCount[us][PAWN] - 1;
1238 pieceList[us][PAWN][index[to]] = to;
1241 // Put the piece back at the source square
1242 Bitboard move_bb = make_move_bb(to, from);
1243 do_move_bb(&byColorBB[us], move_bb);
1244 do_move_bb(&byTypeBB[pt], move_bb);
1245 do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
1247 board[from] = make_piece(us, pt);
1248 board[to] = PIECE_NONE;
1250 // Update piece list
1251 index[from] = index[to];
1252 pieceList[us][pt][index[from]] = from;
1254 if (st->capturedType)
1259 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1261 assert(st->capturedType != KING);
1262 assert(!ep || square_is_empty(capsq));
1264 // Restore the captured piece
1265 set_bit(&byColorBB[them], capsq);
1266 set_bit(&byTypeBB[st->capturedType], capsq);
1267 set_bit(&byTypeBB[0], capsq);
1269 board[capsq] = make_piece(them, st->capturedType);
1271 // Update piece count
1272 pieceCount[them][st->capturedType]++;
1274 // Update piece list, add a new captured piece in capsq square
1275 index[capsq] = pieceCount[them][st->capturedType] - 1;
1276 pieceList[them][st->capturedType][index[capsq]] = capsq;
1279 // Finally point our state pointer back to the previous state
1286 /// Position::undo_castle_move() is a private method used to unmake a castling
1287 /// move. It is called from the main Position::undo_move function. Note that
1288 /// castling moves are encoded as "king captures friendly rook" moves, for
1289 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1291 void Position::undo_castle_move(Move m) {
1293 assert(move_is_ok(m));
1294 assert(move_is_castle(m));
1296 // When we have arrived here, some work has already been done by
1297 // Position::undo_move. In particular, the side to move has been switched,
1298 // so the code below is correct.
1299 Color us = side_to_move();
1301 // Find source squares for king and rook
1302 Square kfrom = move_from(m);
1303 Square rfrom = move_to(m);
1306 // Find destination squares for king and rook
1307 if (rfrom > kfrom) // O-O
1309 kto = relative_square(us, SQ_G1);
1310 rto = relative_square(us, SQ_F1);
1314 kto = relative_square(us, SQ_C1);
1315 rto = relative_square(us, SQ_D1);
1318 assert(piece_on(kto) == make_piece(us, KING));
1319 assert(piece_on(rto) == make_piece(us, ROOK));
1321 // Remove pieces from destination squares
1322 clear_bit(&byColorBB[us], kto);
1323 clear_bit(&byTypeBB[KING], kto);
1324 clear_bit(&byTypeBB[0], kto);
1325 clear_bit(&byColorBB[us], rto);
1326 clear_bit(&byTypeBB[ROOK], rto);
1327 clear_bit(&byTypeBB[0], rto);
1329 // Put pieces on source squares
1330 set_bit(&byColorBB[us], kfrom);
1331 set_bit(&byTypeBB[KING], kfrom);
1332 set_bit(&byTypeBB[0], kfrom);
1333 set_bit(&byColorBB[us], rfrom);
1334 set_bit(&byTypeBB[ROOK], rfrom);
1335 set_bit(&byTypeBB[0], rfrom);
1338 Piece king = make_piece(us, KING);
1339 Piece rook = make_piece(us, ROOK);
1340 board[kto] = board[rto] = PIECE_NONE;
1341 board[kfrom] = king;
1342 board[rfrom] = rook;
1344 // Update piece lists
1345 pieceList[us][KING][index[kto]] = kfrom;
1346 pieceList[us][ROOK][index[rto]] = rfrom;
1347 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1348 index[kfrom] = index[kto];
1351 // Finally point our state pointer back to the previous state
1358 /// Position::do_null_move makes() a "null move": It switches the side to move
1359 /// and updates the hash key without executing any move on the board.
1361 void Position::do_null_move(StateInfo& backupSt) {
1364 assert(!in_check());
1366 // Back up the information necessary to undo the null move to the supplied
1367 // StateInfo object.
1368 // Note that differently from normal case here backupSt is actually used as
1369 // a backup storage not as a new state to be used.
1370 backupSt.key = st->key;
1371 backupSt.epSquare = st->epSquare;
1372 backupSt.value = st->value;
1373 backupSt.previous = st->previous;
1374 backupSt.pliesFromNull = st->pliesFromNull;
1375 st->previous = &backupSt;
1377 // Save the current key to the history[] array, in order to be able to
1378 // detect repetition draws.
1379 history[st->gamePly++] = st->key;
1381 // Update the necessary information
1382 if (st->epSquare != SQ_NONE)
1383 st->key ^= zobEp[st->epSquare];
1385 st->key ^= zobSideToMove;
1386 prefetch((char*)TT.first_entry(st->key));
1388 sideToMove = opposite_color(sideToMove);
1389 st->epSquare = SQ_NONE;
1391 st->pliesFromNull = 0;
1392 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1396 /// Position::undo_null_move() unmakes a "null move".
1398 void Position::undo_null_move() {
1401 assert(!in_check());
1403 // Restore information from the our backup StateInfo object
1404 StateInfo* backupSt = st->previous;
1405 st->key = backupSt->key;
1406 st->epSquare = backupSt->epSquare;
1407 st->value = backupSt->value;
1408 st->previous = backupSt->previous;
1409 st->pliesFromNull = backupSt->pliesFromNull;
1411 // Update the necessary information
1412 sideToMove = opposite_color(sideToMove);
1418 /// Position::see() is a static exchange evaluator: It tries to estimate the
1419 /// material gain or loss resulting from a move. There are three versions of
1420 /// this function: One which takes a destination square as input, one takes a
1421 /// move, and one which takes a 'from' and a 'to' square. The function does
1422 /// not yet understand promotions captures.
1424 int Position::see_sign(Move m) const {
1426 assert(move_is_ok(m));
1428 Square from = move_from(m);
1429 Square to = move_to(m);
1431 // Early return if SEE cannot be negative because captured piece value
1432 // is not less then capturing one. Note that king moves always return
1433 // here because king midgame value is set to 0.
1434 if (piece_value_midgame(piece_on(to)) >= piece_value_midgame(piece_on(from)))
1440 int Position::see(Move m) const {
1443 Bitboard occupied, attackers, stmAttackers, b;
1444 int swapList[32], slIndex = 1;
1445 PieceType capturedType, pt;
1448 assert(move_is_ok(m));
1450 // As castle moves are implemented as capturing the rook, they have
1451 // SEE == RookValueMidgame most of the times (unless the rook is under
1453 if (move_is_castle(m))
1456 from = move_from(m);
1458 capturedType = piece_type(piece_on(to));
1459 occupied = occupied_squares();
1461 // Handle en passant moves
1462 if (st->epSquare == to && piece_type(piece_on(from)) == PAWN)
1464 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1466 assert(capturedType == PIECE_TYPE_NONE);
1467 assert(piece_type(piece_on(capQq)) == PAWN);
1469 // Remove the captured pawn
1470 clear_bit(&occupied, capQq);
1471 capturedType = PAWN;
1474 // Find all attackers to the destination square, with the moving piece
1475 // removed, but possibly an X-ray attacker added behind it.
1476 clear_bit(&occupied, from);
1477 attackers = attackers_to(to, occupied);
1479 // If the opponent has no attackers we are finished
1480 stm = opposite_color(piece_color(piece_on(from)));
1481 stmAttackers = attackers & pieces(stm);
1483 return PieceValueMidgame[capturedType];
1485 // The destination square is defended, which makes things rather more
1486 // difficult to compute. We proceed by building up a "swap list" containing
1487 // the material gain or loss at each stop in a sequence of captures to the
1488 // destination square, where the sides alternately capture, and always
1489 // capture with the least valuable piece. After each capture, we look for
1490 // new X-ray attacks from behind the capturing piece.
1491 swapList[0] = PieceValueMidgame[capturedType];
1492 capturedType = piece_type(piece_on(from));
1495 // Locate the least valuable attacker for the side to move. The loop
1496 // below looks like it is potentially infinite, but it isn't. We know
1497 // that the side to move still has at least one attacker left.
1498 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1501 // Remove the attacker we just found from the 'occupied' bitboard,
1502 // and scan for new X-ray attacks behind the attacker.
1503 b = stmAttackers & pieces(pt);
1504 occupied ^= (b & (~b + 1));
1505 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1506 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1508 attackers &= occupied; // Cut out pieces we've already done
1510 // Add the new entry to the swap list
1511 assert(slIndex < 32);
1512 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1515 // Remember the value of the capturing piece, and change the side to
1516 // move before beginning the next iteration.
1518 stm = opposite_color(stm);
1519 stmAttackers = attackers & pieces(stm);
1521 // Stop before processing a king capture
1522 if (capturedType == KING && stmAttackers)
1524 assert(slIndex < 32);
1525 swapList[slIndex++] = QueenValueMidgame*10;
1528 } while (stmAttackers);
1530 // Having built the swap list, we negamax through it to find the best
1531 // achievable score from the point of view of the side to move.
1533 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1539 /// Position::clear() erases the position object to a pristine state, with an
1540 /// empty board, white to move, and no castling rights.
1542 void Position::clear() {
1545 memset(st, 0, sizeof(StateInfo));
1546 st->epSquare = SQ_NONE;
1548 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1549 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1550 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1551 memset(index, 0, sizeof(int) * 64);
1553 for (int i = 0; i < 8; i++)
1554 for (int j = 0; j < 16; j++)
1555 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1557 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1559 board[sq] = PIECE_NONE;
1560 castleRightsMask[sq] = ALL_CASTLES;
1568 /// Position::put_piece() puts a piece on the given square of the board,
1569 /// updating the board array, pieces list, bitboards, and piece counts.
1571 void Position::put_piece(Piece p, Square s) {
1573 Color c = piece_color(p);
1574 PieceType pt = piece_type(p);
1577 index[s] = pieceCount[c][pt]++;
1578 pieceList[c][pt][index[s]] = s;
1580 set_bit(&byTypeBB[pt], s);
1581 set_bit(&byColorBB[c], s);
1582 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1586 /// Position::compute_key() computes the hash key of the position. The hash
1587 /// key is usually updated incrementally as moves are made and unmade, the
1588 /// compute_key() function is only used when a new position is set up, and
1589 /// to verify the correctness of the hash key when running in debug mode.
1591 Key Position::compute_key() const {
1593 Key result = zobCastle[st->castleRights];
1595 for (Square s = SQ_A1; s <= SQ_H8; s++)
1596 if (!square_is_empty(s))
1597 result ^= zobrist[piece_color(piece_on(s))][piece_type(piece_on(s))][s];
1599 if (ep_square() != SQ_NONE)
1600 result ^= zobEp[ep_square()];
1602 if (side_to_move() == BLACK)
1603 result ^= zobSideToMove;
1609 /// Position::compute_pawn_key() computes the hash key of the position. The
1610 /// hash key is usually updated incrementally as moves are made and unmade,
1611 /// the compute_pawn_key() function is only used when a new position is set
1612 /// up, and to verify the correctness of the pawn hash key when running in
1615 Key Position::compute_pawn_key() const {
1620 for (Color c = WHITE; c <= BLACK; c++)
1622 b = pieces(PAWN, c);
1624 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1630 /// Position::compute_material_key() computes the hash key of the position.
1631 /// The hash key is usually updated incrementally as moves are made and unmade,
1632 /// the compute_material_key() function is only used when a new position is set
1633 /// up, and to verify the correctness of the material hash key when running in
1636 Key Position::compute_material_key() const {
1640 for (Color c = WHITE; c <= BLACK; c++)
1641 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1642 for (int i = 0, cnt = piece_count(c, pt); i < cnt; 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(make_piece(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.
1690 template<bool SkipRepetition>
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 if (!SkipRepetition)
1704 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1705 if (history[st->gamePly - i] == st->key)
1711 // Explicit template instantiations
1712 template bool Position::is_draw<false>() const;
1713 template bool Position::is_draw<true>() const;
1716 /// Position::is_mate() returns true or false depending on whether the
1717 /// side to move is checkmated.
1719 bool Position::is_mate() const {
1721 return in_check() && !MoveList<MV_LEGAL>(*this).size();
1725 /// Position::init() is a static member function which initializes at
1726 /// startup the various arrays used to compute hash keys and the piece
1727 /// square tables. The latter is a two-step operation: First, the white
1728 /// halves of the tables are copied from the MgPST[][] and EgPST[][] arrays.
1729 /// Second, the black halves of the tables are initialized by mirroring
1730 /// and changing the sign of the corresponding white scores.
1732 void Position::init() {
1736 for (Color c = WHITE; c <= BLACK; c++)
1737 for (PieceType pt = PAWN; pt <= KING; pt++)
1738 for (Square s = SQ_A1; s <= SQ_H8; s++)
1739 zobrist[c][pt][s] = rk.rand<Key>();
1741 for (Square s = SQ_A1; s <= SQ_H8; s++)
1742 zobEp[s] = rk.rand<Key>();
1744 for (int i = 0; i < 16; i++)
1745 zobCastle[i] = rk.rand<Key>();
1747 zobSideToMove = rk.rand<Key>();
1748 zobExclusion = rk.rand<Key>();
1750 for (Square s = SQ_A1; s <= SQ_H8; s++)
1751 for (Piece p = WP; p <= WK; p++)
1752 pieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1754 for (Square s = SQ_A1; s <= SQ_H8; s++)
1755 for (Piece p = BP; p <= BK; p++)
1756 pieceSquareTable[p][s] = -pieceSquareTable[p-8][flip_square(s)];
1760 /// Position::flip() flips position with the white and black sides reversed. This
1761 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1763 void Position::flip() {
1767 // Make a copy of current position before to start changing
1768 const Position pos(*this, threadID);
1771 threadID = pos.thread();
1774 for (Square s = SQ_A1; s <= SQ_H8; s++)
1775 if (!pos.square_is_empty(s))
1776 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1779 sideToMove = opposite_color(pos.side_to_move());
1782 if (pos.can_castle(WHITE_OO))
1783 set_castle(BLACK_OO, king_square(BLACK), flip_square(pos.castle_rook_square(WHITE_OO)));
1784 if (pos.can_castle(WHITE_OOO))
1785 set_castle(BLACK_OOO, king_square(BLACK), flip_square(pos.castle_rook_square(WHITE_OOO)));
1786 if (pos.can_castle(BLACK_OO))
1787 set_castle(WHITE_OO, king_square(WHITE), flip_square(pos.castle_rook_square(BLACK_OO)));
1788 if (pos.can_castle(BLACK_OOO))
1789 set_castle(WHITE_OOO, king_square(WHITE), flip_square(pos.castle_rook_square(BLACK_OOO)));
1791 // En passant square
1792 if (pos.st->epSquare != SQ_NONE)
1793 st->epSquare = flip_square(pos.st->epSquare);
1796 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(opposite_color(sideToMove));
1799 st->key = compute_key();
1800 st->pawnKey = compute_pawn_key();
1801 st->materialKey = compute_material_key();
1803 // Incremental scores
1804 st->value = compute_value();
1807 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1808 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1814 /// Position::is_ok() performs some consitency checks for the position object.
1815 /// This is meant to be helpful when debugging.
1817 bool Position::is_ok(int* failedStep) const {
1819 // What features of the position should be verified?
1820 const bool debugAll = false;
1822 const bool debugBitboards = debugAll || false;
1823 const bool debugKingCount = debugAll || false;
1824 const bool debugKingCapture = debugAll || false;
1825 const bool debugCheckerCount = debugAll || false;
1826 const bool debugKey = debugAll || false;
1827 const bool debugMaterialKey = debugAll || false;
1828 const bool debugPawnKey = debugAll || false;
1829 const bool debugIncrementalEval = debugAll || false;
1830 const bool debugNonPawnMaterial = debugAll || false;
1831 const bool debugPieceCounts = debugAll || false;
1832 const bool debugPieceList = debugAll || false;
1833 const bool debugCastleSquares = debugAll || false;
1835 if (failedStep) *failedStep = 1;
1838 if (side_to_move() != WHITE && side_to_move() != BLACK)
1841 // Are the king squares in the position correct?
1842 if (failedStep) (*failedStep)++;
1843 if (piece_on(king_square(WHITE)) != WK)
1846 if (failedStep) (*failedStep)++;
1847 if (piece_on(king_square(BLACK)) != BK)
1850 // Do both sides have exactly one king?
1851 if (failedStep) (*failedStep)++;
1854 int kingCount[2] = {0, 0};
1855 for (Square s = SQ_A1; s <= SQ_H8; s++)
1856 if (piece_type(piece_on(s)) == KING)
1857 kingCount[piece_color(piece_on(s))]++;
1859 if (kingCount[0] != 1 || kingCount[1] != 1)
1863 // Can the side to move capture the opponent's king?
1864 if (failedStep) (*failedStep)++;
1865 if (debugKingCapture)
1867 Color us = side_to_move();
1868 Color them = opposite_color(us);
1869 Square ksq = king_square(them);
1870 if (attackers_to(ksq) & pieces(us))
1874 // Is there more than 2 checkers?
1875 if (failedStep) (*failedStep)++;
1876 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1880 if (failedStep) (*failedStep)++;
1883 // The intersection of the white and black pieces must be empty
1884 if ((pieces(WHITE) & pieces(BLACK)) != EmptyBoardBB)
1887 // The union of the white and black pieces must be equal to all
1889 if ((pieces(WHITE) | pieces(BLACK)) != occupied_squares())
1892 // Separate piece type bitboards must have empty intersections
1893 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1894 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1895 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1899 // En passant square OK?
1900 if (failedStep) (*failedStep)++;
1901 if (ep_square() != SQ_NONE)
1903 // The en passant square must be on rank 6, from the point of view of the
1905 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1910 if (failedStep) (*failedStep)++;
1911 if (debugKey && st->key != compute_key())
1914 // Pawn hash key OK?
1915 if (failedStep) (*failedStep)++;
1916 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1919 // Material hash key OK?
1920 if (failedStep) (*failedStep)++;
1921 if (debugMaterialKey && st->materialKey != compute_material_key())
1924 // Incremental eval OK?
1925 if (failedStep) (*failedStep)++;
1926 if (debugIncrementalEval && st->value != compute_value())
1929 // Non-pawn material OK?
1930 if (failedStep) (*failedStep)++;
1931 if (debugNonPawnMaterial)
1933 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1936 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1941 if (failedStep) (*failedStep)++;
1942 if (debugPieceCounts)
1943 for (Color c = WHITE; c <= BLACK; c++)
1944 for (PieceType pt = PAWN; pt <= KING; pt++)
1945 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1948 if (failedStep) (*failedStep)++;
1950 for (Color c = WHITE; c <= BLACK; c++)
1951 for (PieceType pt = PAWN; pt <= KING; pt++)
1952 for (int i = 0; i < pieceCount[c][pt]; i++)
1954 if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1957 if (index[piece_list(c, pt)[i]] != i)
1961 if (failedStep) (*failedStep)++;
1962 if (debugCastleSquares)
1963 for (CastleRight f = WHITE_OO; f <= BLACK_OOO; f = CastleRight(f << 1))
1968 Piece rook = (f & (WHITE_OO | WHITE_OOO) ? WR : BR);
1970 if ( castleRightsMask[castleRookSquare[f]] != (ALL_CASTLES ^ f)
1971 || piece_on(castleRookSquare[f]) != rook)
1975 if (failedStep) *failedStep = 0;