2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
41 #include "ucioption.h"
49 //// Position's static data definitions
52 Key Position::zobrist[2][8][64];
53 Key Position::zobEp[64];
54 Key Position::zobCastle[16];
55 Key Position::zobSideToMove;
56 Key Position::zobExclusion;
58 Score Position::PieceSquareTable[16][64];
60 // Material values arrays, indexed by Piece
61 const Value Position::PieceValueMidgame[17] = {
63 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
64 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
65 VALUE_ZERO, VALUE_ZERO,
66 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
67 RookValueMidgame, QueenValueMidgame
70 const Value Position::PieceValueEndgame[17] = {
72 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
73 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
74 VALUE_ZERO, VALUE_ZERO,
75 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
76 RookValueEndgame, QueenValueEndgame
79 // Material values array used by SEE, indexed by PieceType
80 const Value Position::seeValues[] = {
82 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
83 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
89 // Bonus for having the side to move (modified by Joona Kiiski)
90 const Score TempoValue = make_score(48, 22);
92 bool isZero(char c) { return c == '0'; }
94 struct PieceLetters : public std::map<char, Piece> {
98 operator[]('K') = WK; operator[]('k') = BK;
99 operator[]('Q') = WQ; operator[]('q') = BQ;
100 operator[]('R') = WR; operator[]('r') = BR;
101 operator[]('B') = WB; operator[]('b') = BB;
102 operator[]('N') = WN; operator[]('n') = BN;
103 operator[]('P') = WP; operator[]('p') = BP;
104 operator[](' ') = PIECE_NONE;
105 operator[]('.') = PIECE_NONE_DARK_SQ;
108 char from_piece(Piece p) const {
110 std::map<char, Piece>::const_iterator it;
111 for (it = begin(); it != end(); ++it)
120 PieceLetters pieceLetters;
126 CheckInfo::CheckInfo(const Position& pos) {
128 Color us = pos.side_to_move();
129 Color them = opposite_color(us);
131 ksq = pos.king_square(them);
132 dcCandidates = pos.discovered_check_candidates(us);
134 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
135 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
136 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
137 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
138 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
139 checkSq[KING] = EmptyBoardBB;
143 /// Position c'tors. Here we always create a copy of the original position
144 /// or the FEN string, we want the new born Position object do not depend
145 /// on any external data so we detach state pointer from the source one.
147 Position::Position(const Position& pos, int th) {
149 memcpy(this, &pos, sizeof(Position));
150 detach(); // Always detach() in copy c'tor to avoid surprises
155 Position::Position(const string& fen, int th) {
162 /// Position::detach() copies the content of the current state and castling
163 /// masks inside the position itself. This is needed when the st pointee could
164 /// become stale, as example because the caller is about to going out of scope.
166 void Position::detach() {
170 st->previous = NULL; // as a safe guard
174 /// Position::from_fen() initializes the position object with the given FEN
175 /// string. This function is not very robust - make sure that input FENs are
176 /// correct (this is assumed to be the responsibility of the GUI).
178 void Position::from_fen(const string& fen) {
180 A FEN string defines a particular position using only the ASCII character set.
182 A FEN string contains six fields. The separator between fields is a space. The fields are:
184 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
185 with rank 1; within each rank, the contents of each square are described from file a through file h.
186 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
187 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
188 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
189 of blank squares), and "/" separate ranks.
191 2) Active color. "w" means white moves next, "b" means black.
193 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
194 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
195 kingside), and/or "q" (Black can castle queenside).
197 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
198 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
199 regardless of whether there is a pawn in position to make an en passant capture.
201 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
202 to determine if a draw can be claimed under the fifty-move rule.
204 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;
267 // 5-6. Halfmove clock and fullmove number are not parsed
269 // Various initialisations
270 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
271 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
272 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
273 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
274 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
275 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
277 isChess960 = initialKFile != FILE_E
278 || initialQRFile != FILE_A
279 || initialKRFile != FILE_H;
283 st->key = compute_key();
284 st->pawnKey = compute_pawn_key();
285 st->materialKey = compute_material_key();
286 st->value = compute_value();
287 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
288 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
292 cout << "Error in FEN string: " << fen << endl;
296 /// Position::set_castling_rights() sets castling parameters castling avaiability.
297 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
298 /// that uses the letters of the columns on which the rooks began the game instead
299 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
300 /// associated with the castling right, the traditional castling tag will be replaced
301 /// by the file letter of the involved rook as for the Shredder-FEN.
303 bool Position::set_castling_rights(char token) {
305 Color c = token >= 'a' ? BLACK : WHITE;
306 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
307 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
308 Piece rook = (c == WHITE ? WR : BR);
310 initialKFile = square_file(king_square(c));
311 token = char(toupper(token));
315 for (Square sq = sqH; sq >= sqA; sq--)
316 if (piece_on(sq) == rook)
319 initialKRFile = square_file(sq);
323 else if (token == 'Q')
325 for (Square sq = sqA; sq <= sqH; sq++)
326 if (piece_on(sq) == rook)
329 initialQRFile = square_file(sq);
333 else if (token >= 'A' && token <= 'H')
335 File rookFile = File(token - 'A') + FILE_A;
336 if (rookFile < initialKFile)
339 initialQRFile = rookFile;
344 initialKRFile = rookFile;
353 /// Position::to_fen() returns a FEN representation of the position. In case
354 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
356 const string Position::to_fen() const {
362 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
364 for (File file = FILE_A; file <= FILE_H; file++)
366 sq = make_square(file, rank);
368 if (square_is_occupied(sq))
371 fen += pieceLetters.from_piece(piece_on(sq));
381 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
382 fen.erase(--fen.end());
383 fen += (sideToMove == WHITE ? " w " : " b ");
385 if (st->castleRights != CASTLES_NONE)
387 if (can_castle_kingside(WHITE))
388 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
390 if (can_castle_queenside(WHITE))
391 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
393 if (can_castle_kingside(BLACK))
394 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
396 if (can_castle_queenside(BLACK))
397 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
401 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
406 /// Position::print() prints an ASCII representation of the position to
407 /// the standard output. If a move is given then also the san is printed.
409 void Position::print(Move move) const {
411 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
412 static bool requestPending = false;
414 // Check for reentrancy, as example when called from inside
415 // MovePicker that is used also here in move_to_san()
419 requestPending = true;
423 Position p(*this, thread());
424 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
425 cout << "\nMove is: " << dd << move_to_san(p, move);
428 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
430 cout << dottedLine << '|';
431 for (File file = FILE_A; file <= FILE_H; file++)
433 Square sq = make_square(file, rank);
434 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
435 Piece piece = piece_on(sq);
437 if (piece == PIECE_NONE && square_color(sq) == DARK)
438 piece = PIECE_NONE_DARK_SQ;
440 cout << c << pieceLetters.from_piece(piece) << c << '|';
443 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
444 requestPending = false;
448 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
449 /// king) pieces for the given color and for the given pinner type. Or, when
450 /// template parameter FindPinned is false, the pieces of the given color
451 /// candidate for a discovery check against the enemy king.
452 /// Bitboard checkersBB must be already updated when looking for pinners.
454 template<bool FindPinned>
455 Bitboard Position::hidden_checkers(Color c) const {
457 Bitboard result = EmptyBoardBB;
458 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
460 // Pinned pieces protect our king, dicovery checks attack
462 Square ksq = king_square(FindPinned ? c : opposite_color(c));
464 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
465 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
467 if (FindPinned && pinners)
468 pinners &= ~st->checkersBB;
472 Square s = pop_1st_bit(&pinners);
473 Bitboard b = squares_between(s, ksq) & occupied_squares();
477 if ( !(b & (b - 1)) // Only one bit set?
478 && (b & pieces_of_color(c))) // Is an our piece?
485 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
486 /// king) pieces for the given color. Note that checkersBB bitboard must
487 /// be already updated.
489 Bitboard Position::pinned_pieces(Color c) const {
491 return hidden_checkers<true>(c);
495 /// Position:discovered_check_candidates() returns a bitboard containing all
496 /// pieces for the given side which are candidates for giving a discovered
497 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
498 /// to be already updated.
500 Bitboard Position::discovered_check_candidates(Color c) const {
502 return hidden_checkers<false>(c);
505 /// Position::attackers_to() computes a bitboard containing all pieces which
506 /// attacks a given square.
508 Bitboard Position::attackers_to(Square s) const {
510 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
511 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
512 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
513 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
514 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
515 | (attacks_from<KING>(s) & pieces(KING));
518 /// Position::attacks_from() computes a bitboard of all attacks
519 /// of a given piece put in a given square.
521 Bitboard Position::attacks_from(Piece p, Square s) const {
523 assert(square_is_ok(s));
527 case WB: case BB: return attacks_from<BISHOP>(s);
528 case WR: case BR: return attacks_from<ROOK>(s);
529 case WQ: case BQ: return attacks_from<QUEEN>(s);
530 default: return StepAttackBB[p][s];
534 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
536 assert(square_is_ok(s));
540 case WB: case BB: return bishop_attacks_bb(s, occ);
541 case WR: case BR: return rook_attacks_bb(s, occ);
542 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
543 default: return StepAttackBB[p][s];
548 /// Position::move_attacks_square() tests whether a move from the current
549 /// position attacks a given square.
551 bool Position::move_attacks_square(Move m, Square s) const {
553 assert(move_is_ok(m));
554 assert(square_is_ok(s));
557 Square f = move_from(m), t = move_to(m);
559 assert(square_is_occupied(f));
561 if (bit_is_set(attacks_from(piece_on(f), t), s))
564 // Move the piece and scan for X-ray attacks behind it
565 occ = occupied_squares();
566 do_move_bb(&occ, make_move_bb(f, t));
567 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
568 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
569 & pieces_of_color(color_of_piece_on(f));
571 // If we have attacks we need to verify that are caused by our move
572 // and are not already existent ones.
573 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
577 /// Position::find_checkers() computes the checkersBB bitboard, which
578 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
579 /// currently works by calling Position::attackers_to, which is probably
580 /// inefficient. Consider rewriting this function to use the last move
581 /// played, like in non-bitboard versions of Glaurung.
583 void Position::find_checkers() {
585 Color us = side_to_move();
586 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
590 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
592 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
595 assert(move_is_ok(m));
596 assert(pinned == pinned_pieces(side_to_move()));
598 // Castling moves are checked for legality during move generation.
599 if (move_is_castle(m))
602 // En passant captures are a tricky special case. Because they are
603 // rather uncommon, we do it simply by testing whether the king is attacked
604 // after the move is made
607 Color us = side_to_move();
608 Color them = opposite_color(us);
609 Square from = move_from(m);
610 Square to = move_to(m);
611 Square capsq = make_square(square_file(to), square_rank(from));
612 Square ksq = king_square(us);
613 Bitboard b = occupied_squares();
615 assert(to == ep_square());
616 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
617 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
618 assert(piece_on(to) == PIECE_NONE);
621 clear_bit(&b, capsq);
624 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
625 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
628 Color us = side_to_move();
629 Square from = move_from(m);
631 assert(color_of_piece_on(from) == us);
632 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
634 // If the moving piece is a king, check whether the destination
635 // square is attacked by the opponent.
636 if (type_of_piece_on(from) == KING)
637 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
639 // A non-king move is legal if and only if it is not pinned or it
640 // is moving along the ray towards or away from the king.
642 || !bit_is_set(pinned, from)
643 || squares_aligned(from, move_to(m), king_square(us));
647 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
649 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
653 Color us = side_to_move();
654 Square from = move_from(m);
655 Square to = move_to(m);
657 // King moves and en-passant captures are verified in pl_move_is_legal()
658 if (type_of_piece_on(from) == KING || move_is_ep(m))
659 return pl_move_is_legal(m, pinned);
661 Bitboard target = checkers();
662 Square checksq = pop_1st_bit(&target);
664 if (target) // double check ?
667 // Our move must be a blocking evasion or a capture of the checking piece
668 target = squares_between(checksq, king_square(us)) | checkers();
669 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
673 /// Position::move_is_check() tests whether a pseudo-legal move is a check
675 bool Position::move_is_check(Move m) const {
677 return move_is_check(m, CheckInfo(*this));
680 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
683 assert(move_is_ok(m));
684 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
685 assert(color_of_piece_on(move_from(m)) == side_to_move());
686 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
688 Square from = move_from(m);
689 Square to = move_to(m);
690 PieceType pt = type_of_piece_on(from);
693 if (bit_is_set(ci.checkSq[pt], to))
697 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
699 // For pawn and king moves we need to verify also direction
700 if ( (pt != PAWN && pt != KING)
701 || !squares_aligned(from, to, ci.ksq))
705 // Can we skip the ugly special cases ?
706 if (!move_is_special(m))
709 Color us = side_to_move();
710 Bitboard b = occupied_squares();
712 // Promotion with check ?
713 if (move_is_promotion(m))
717 switch (move_promotion_piece(m))
720 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
722 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
724 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
726 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
732 // En passant capture with check ? We have already handled the case
733 // of direct checks and ordinary discovered check, the only case we
734 // need to handle is the unusual case of a discovered check through
735 // the captured pawn.
738 Square capsq = make_square(square_file(to), square_rank(from));
740 clear_bit(&b, capsq);
742 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
743 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
746 // Castling with check ?
747 if (move_is_castle(m))
749 Square kfrom, kto, rfrom, rto;
755 kto = relative_square(us, SQ_G1);
756 rto = relative_square(us, SQ_F1);
758 kto = relative_square(us, SQ_C1);
759 rto = relative_square(us, SQ_D1);
761 clear_bit(&b, kfrom);
762 clear_bit(&b, rfrom);
765 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
772 /// Position::do_move() makes a move, and saves all information necessary
773 /// to a StateInfo object. The move is assumed to be legal.
774 /// Pseudo-legal moves should be filtered out before this function is called.
776 void Position::do_move(Move m, StateInfo& newSt) {
779 do_move(m, newSt, ci, move_is_check(m, ci));
782 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
785 assert(move_is_ok(m));
790 // Copy some fields of old state to our new StateInfo object except the
791 // ones which are recalculated from scratch anyway, then switch our state
792 // pointer to point to the new, ready to be updated, state.
793 struct ReducedStateInfo {
794 Key pawnKey, materialKey;
795 int castleRights, rule50, gamePly, pliesFromNull;
802 memcpy(&newSt, st, sizeof(ReducedStateInfo));
807 // Save the current key to the history[] array, in order to be able to
808 // detect repetition draws.
809 history[st->gamePly++] = key;
811 // Update side to move
812 key ^= zobSideToMove;
814 // Increment the 50 moves rule draw counter. Resetting it to zero in the
815 // case of non-reversible moves is taken care of later.
819 if (move_is_castle(m))
826 Color us = side_to_move();
827 Color them = opposite_color(us);
828 Square from = move_from(m);
829 Square to = move_to(m);
830 bool ep = move_is_ep(m);
831 bool pm = move_is_promotion(m);
833 Piece piece = piece_on(from);
834 PieceType pt = type_of_piece(piece);
835 PieceType capture = ep ? PAWN : type_of_piece_on(to);
837 assert(color_of_piece_on(from) == us);
838 assert(color_of_piece_on(to) == them || square_is_empty(to));
839 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
840 assert(!pm || relative_rank(us, to) == RANK_8);
843 do_capture_move(key, capture, them, to, ep);
846 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
848 // Reset en passant square
849 if (st->epSquare != SQ_NONE)
851 key ^= zobEp[st->epSquare];
852 st->epSquare = SQ_NONE;
855 // Update castle rights, try to shortcut a common case
856 int cm = castleRightsMask[from] & castleRightsMask[to];
857 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
859 key ^= zobCastle[st->castleRights];
860 st->castleRights &= castleRightsMask[from];
861 st->castleRights &= castleRightsMask[to];
862 key ^= zobCastle[st->castleRights];
865 // Prefetch TT access as soon as we know key is updated
866 prefetch((char*)TT.first_entry(key));
869 Bitboard move_bb = make_move_bb(from, to);
870 do_move_bb(&(byColorBB[us]), move_bb);
871 do_move_bb(&(byTypeBB[pt]), move_bb);
872 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
874 board[to] = board[from];
875 board[from] = PIECE_NONE;
877 // Update piece lists, note that index[from] is not updated and
878 // becomes stale. This works as long as index[] is accessed just
879 // by known occupied squares.
880 index[to] = index[from];
881 pieceList[us][pt][index[to]] = to;
883 // If the moving piece was a pawn do some special extra work
886 // Reset rule 50 draw counter
889 // Update pawn hash key and prefetch in L1/L2 cache
890 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
891 prefetchPawn(st->pawnKey, threadID);
893 // Set en passant square, only if moved pawn can be captured
894 if ((to ^ from) == 16)
896 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
898 st->epSquare = Square((int(from) + int(to)) / 2);
899 key ^= zobEp[st->epSquare];
903 if (pm) // promotion ?
905 PieceType promotion = move_promotion_piece(m);
907 assert(promotion >= KNIGHT && promotion <= QUEEN);
909 // Insert promoted piece instead of pawn
910 clear_bit(&(byTypeBB[PAWN]), to);
911 set_bit(&(byTypeBB[promotion]), to);
912 board[to] = piece_of_color_and_type(us, promotion);
914 // Update piece counts
915 pieceCount[us][promotion]++;
916 pieceCount[us][PAWN]--;
918 // Update material key
919 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
920 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
922 // Update piece lists, move the last pawn at index[to] position
923 // and shrink the list. Add a new promotion piece to the list.
924 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
925 index[lastPawnSquare] = index[to];
926 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
927 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
928 index[to] = pieceCount[us][promotion] - 1;
929 pieceList[us][promotion][index[to]] = to;
931 // Partially revert hash keys update
932 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
933 st->pawnKey ^= zobrist[us][PAWN][to];
935 // Partially revert and update incremental scores
936 st->value -= pst(us, PAWN, to);
937 st->value += pst(us, promotion, to);
940 st->npMaterial[us] += PieceValueMidgame[promotion];
944 // Update incremental scores
945 st->value += pst_delta(piece, from, to);
948 st->capturedType = capture;
950 // Update the key with the final value
953 // Update checkers bitboard, piece must be already moved
954 st->checkersBB = EmptyBoardBB;
959 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
963 if (bit_is_set(ci.checkSq[pt], to))
964 st->checkersBB = SetMaskBB[to];
967 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
970 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
973 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
979 sideToMove = opposite_color(sideToMove);
980 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
986 /// Position::do_capture_move() is a private method used to update captured
987 /// piece info. It is called from the main Position::do_move function.
989 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
991 assert(capture != KING);
995 // If the captured piece was a pawn, update pawn hash key,
996 // otherwise update non-pawn material.
999 if (ep) // en passant ?
1001 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1003 assert(to == st->epSquare);
1004 assert(relative_rank(opposite_color(them), to) == RANK_6);
1005 assert(piece_on(to) == PIECE_NONE);
1006 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1008 board[capsq] = PIECE_NONE;
1010 st->pawnKey ^= zobrist[them][PAWN][capsq];
1013 st->npMaterial[them] -= PieceValueMidgame[capture];
1015 // Remove captured piece
1016 clear_bit(&(byColorBB[them]), capsq);
1017 clear_bit(&(byTypeBB[capture]), capsq);
1018 clear_bit(&(byTypeBB[0]), capsq);
1021 key ^= zobrist[them][capture][capsq];
1023 // Update incremental scores
1024 st->value -= pst(them, capture, capsq);
1026 // Update piece count
1027 pieceCount[them][capture]--;
1029 // Update material hash key
1030 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1032 // Update piece list, move the last piece at index[capsq] position
1034 // WARNING: This is a not perfectly revresible operation. When we
1035 // will reinsert the captured piece in undo_move() we will put it
1036 // at the end of the list and not in its original place, it means
1037 // index[] and pieceList[] are not guaranteed to be invariant to a
1038 // do_move() + undo_move() sequence.
1039 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1040 index[lastPieceSquare] = index[capsq];
1041 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1042 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1044 // Reset rule 50 counter
1049 /// Position::do_castle_move() is a private method used to make a castling
1050 /// move. It is called from the main Position::do_move function. Note that
1051 /// castling moves are encoded as "king captures friendly rook" moves, for
1052 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1054 void Position::do_castle_move(Move m) {
1056 assert(move_is_ok(m));
1057 assert(move_is_castle(m));
1059 Color us = side_to_move();
1060 Color them = opposite_color(us);
1062 // Reset capture field
1063 st->capturedType = PIECE_TYPE_NONE;
1065 // Find source squares for king and rook
1066 Square kfrom = move_from(m);
1067 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1070 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1071 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1073 // Find destination squares for king and rook
1074 if (rfrom > kfrom) // O-O
1076 kto = relative_square(us, SQ_G1);
1077 rto = relative_square(us, SQ_F1);
1079 kto = relative_square(us, SQ_C1);
1080 rto = relative_square(us, SQ_D1);
1083 // Remove pieces from source squares:
1084 clear_bit(&(byColorBB[us]), kfrom);
1085 clear_bit(&(byTypeBB[KING]), kfrom);
1086 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1087 clear_bit(&(byColorBB[us]), rfrom);
1088 clear_bit(&(byTypeBB[ROOK]), rfrom);
1089 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1091 // Put pieces on destination squares:
1092 set_bit(&(byColorBB[us]), kto);
1093 set_bit(&(byTypeBB[KING]), kto);
1094 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1095 set_bit(&(byColorBB[us]), rto);
1096 set_bit(&(byTypeBB[ROOK]), rto);
1097 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1099 // Update board array
1100 Piece king = piece_of_color_and_type(us, KING);
1101 Piece rook = piece_of_color_and_type(us, ROOK);
1102 board[kfrom] = board[rfrom] = PIECE_NONE;
1106 // Update piece lists
1107 pieceList[us][KING][index[kfrom]] = kto;
1108 pieceList[us][ROOK][index[rfrom]] = rto;
1109 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1110 index[kto] = index[kfrom];
1113 // Update incremental scores
1114 st->value += pst_delta(king, kfrom, kto);
1115 st->value += pst_delta(rook, rfrom, rto);
1118 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1119 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1121 // Clear en passant square
1122 if (st->epSquare != SQ_NONE)
1124 st->key ^= zobEp[st->epSquare];
1125 st->epSquare = SQ_NONE;
1128 // Update castling rights
1129 st->key ^= zobCastle[st->castleRights];
1130 st->castleRights &= castleRightsMask[kfrom];
1131 st->key ^= zobCastle[st->castleRights];
1133 // Reset rule 50 counter
1136 // Update checkers BB
1137 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1140 sideToMove = opposite_color(sideToMove);
1141 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1147 /// Position::undo_move() unmakes a move. When it returns, the position should
1148 /// be restored to exactly the same state as before the move was made.
1150 void Position::undo_move(Move m) {
1153 assert(move_is_ok(m));
1155 sideToMove = opposite_color(sideToMove);
1157 if (move_is_castle(m))
1159 undo_castle_move(m);
1163 Color us = side_to_move();
1164 Color them = opposite_color(us);
1165 Square from = move_from(m);
1166 Square to = move_to(m);
1167 bool ep = move_is_ep(m);
1168 bool pm = move_is_promotion(m);
1170 PieceType pt = type_of_piece_on(to);
1172 assert(square_is_empty(from));
1173 assert(color_of_piece_on(to) == us);
1174 assert(!pm || relative_rank(us, to) == RANK_8);
1175 assert(!ep || to == st->previous->epSquare);
1176 assert(!ep || relative_rank(us, to) == RANK_6);
1177 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1179 if (pm) // promotion ?
1181 PieceType promotion = move_promotion_piece(m);
1184 assert(promotion >= KNIGHT && promotion <= QUEEN);
1185 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1187 // Replace promoted piece with a pawn
1188 clear_bit(&(byTypeBB[promotion]), to);
1189 set_bit(&(byTypeBB[PAWN]), to);
1191 // Update piece counts
1192 pieceCount[us][promotion]--;
1193 pieceCount[us][PAWN]++;
1195 // Update piece list replacing promotion piece with a pawn
1196 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1197 index[lastPromotionSquare] = index[to];
1198 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1199 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1200 index[to] = pieceCount[us][PAWN] - 1;
1201 pieceList[us][PAWN][index[to]] = to;
1204 // Put the piece back at the source square
1205 Bitboard move_bb = make_move_bb(to, from);
1206 do_move_bb(&(byColorBB[us]), move_bb);
1207 do_move_bb(&(byTypeBB[pt]), move_bb);
1208 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1210 board[from] = piece_of_color_and_type(us, pt);
1211 board[to] = PIECE_NONE;
1213 // Update piece list
1214 index[from] = index[to];
1215 pieceList[us][pt][index[from]] = from;
1217 if (st->capturedType)
1222 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1224 assert(st->capturedType != KING);
1225 assert(!ep || square_is_empty(capsq));
1227 // Restore the captured piece
1228 set_bit(&(byColorBB[them]), capsq);
1229 set_bit(&(byTypeBB[st->capturedType]), capsq);
1230 set_bit(&(byTypeBB[0]), capsq);
1232 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1234 // Update piece count
1235 pieceCount[them][st->capturedType]++;
1237 // Update piece list, add a new captured piece in capsq square
1238 index[capsq] = pieceCount[them][st->capturedType] - 1;
1239 pieceList[them][st->capturedType][index[capsq]] = capsq;
1242 // Finally point our state pointer back to the previous state
1249 /// Position::undo_castle_move() is a private method used to unmake a castling
1250 /// move. It is called from the main Position::undo_move function. Note that
1251 /// castling moves are encoded as "king captures friendly rook" moves, for
1252 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1254 void Position::undo_castle_move(Move m) {
1256 assert(move_is_ok(m));
1257 assert(move_is_castle(m));
1259 // When we have arrived here, some work has already been done by
1260 // Position::undo_move. In particular, the side to move has been switched,
1261 // so the code below is correct.
1262 Color us = side_to_move();
1264 // Find source squares for king and rook
1265 Square kfrom = move_from(m);
1266 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1269 // Find destination squares for king and rook
1270 if (rfrom > kfrom) // O-O
1272 kto = relative_square(us, SQ_G1);
1273 rto = relative_square(us, SQ_F1);
1275 kto = relative_square(us, SQ_C1);
1276 rto = relative_square(us, SQ_D1);
1279 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1280 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1282 // Remove pieces from destination squares:
1283 clear_bit(&(byColorBB[us]), kto);
1284 clear_bit(&(byTypeBB[KING]), kto);
1285 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1286 clear_bit(&(byColorBB[us]), rto);
1287 clear_bit(&(byTypeBB[ROOK]), rto);
1288 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1290 // Put pieces on source squares:
1291 set_bit(&(byColorBB[us]), kfrom);
1292 set_bit(&(byTypeBB[KING]), kfrom);
1293 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1294 set_bit(&(byColorBB[us]), rfrom);
1295 set_bit(&(byTypeBB[ROOK]), rfrom);
1296 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1299 board[rto] = board[kto] = PIECE_NONE;
1300 board[rfrom] = piece_of_color_and_type(us, ROOK);
1301 board[kfrom] = piece_of_color_and_type(us, KING);
1303 // Update piece lists
1304 pieceList[us][KING][index[kto]] = kfrom;
1305 pieceList[us][ROOK][index[rto]] = rfrom;
1306 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1307 index[kfrom] = index[kto];
1310 // Finally point our state pointer back to the previous state
1317 /// Position::do_null_move makes() a "null move": It switches the side to move
1318 /// and updates the hash key without executing any move on the board.
1320 void Position::do_null_move(StateInfo& backupSt) {
1323 assert(!is_check());
1325 // Back up the information necessary to undo the null move to the supplied
1326 // StateInfo object.
1327 // Note that differently from normal case here backupSt is actually used as
1328 // a backup storage not as a new state to be used.
1329 backupSt.key = st->key;
1330 backupSt.epSquare = st->epSquare;
1331 backupSt.value = st->value;
1332 backupSt.previous = st->previous;
1333 backupSt.pliesFromNull = st->pliesFromNull;
1334 st->previous = &backupSt;
1336 // Save the current key to the history[] array, in order to be able to
1337 // detect repetition draws.
1338 history[st->gamePly++] = st->key;
1340 // Update the necessary information
1341 if (st->epSquare != SQ_NONE)
1342 st->key ^= zobEp[st->epSquare];
1344 st->key ^= zobSideToMove;
1345 prefetch((char*)TT.first_entry(st->key));
1347 sideToMove = opposite_color(sideToMove);
1348 st->epSquare = SQ_NONE;
1350 st->pliesFromNull = 0;
1351 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1355 /// Position::undo_null_move() unmakes a "null move".
1357 void Position::undo_null_move() {
1360 assert(!is_check());
1362 // Restore information from the our backup StateInfo object
1363 StateInfo* backupSt = st->previous;
1364 st->key = backupSt->key;
1365 st->epSquare = backupSt->epSquare;
1366 st->value = backupSt->value;
1367 st->previous = backupSt->previous;
1368 st->pliesFromNull = backupSt->pliesFromNull;
1370 // Update the necessary information
1371 sideToMove = opposite_color(sideToMove);
1377 /// Position::see() is a static exchange evaluator: It tries to estimate the
1378 /// material gain or loss resulting from a move. There are three versions of
1379 /// this function: One which takes a destination square as input, one takes a
1380 /// move, and one which takes a 'from' and a 'to' square. The function does
1381 /// not yet understand promotions captures.
1383 int Position::see(Move m) const {
1385 assert(move_is_ok(m));
1386 return see(move_from(m), move_to(m));
1389 int Position::see_sign(Move m) const {
1391 assert(move_is_ok(m));
1393 Square from = move_from(m);
1394 Square to = move_to(m);
1396 // Early return if SEE cannot be negative because captured piece value
1397 // is not less then capturing one. Note that king moves always return
1398 // here because king midgame value is set to 0.
1399 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1402 return see(from, to);
1405 int Position::see(Square from, Square to) const {
1407 Bitboard occupied, attackers, stmAttackers, b;
1408 int swapList[32], slIndex = 1;
1409 PieceType capturedType, pt;
1412 assert(square_is_ok(from));
1413 assert(square_is_ok(to));
1415 capturedType = type_of_piece_on(to);
1417 // King cannot be recaptured
1418 if (capturedType == KING)
1419 return seeValues[capturedType];
1421 occupied = occupied_squares();
1423 // Handle en passant moves
1424 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1426 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1428 assert(capturedType == PIECE_TYPE_NONE);
1429 assert(type_of_piece_on(capQq) == PAWN);
1431 // Remove the captured pawn
1432 clear_bit(&occupied, capQq);
1433 capturedType = PAWN;
1436 // Find all attackers to the destination square, with the moving piece
1437 // removed, but possibly an X-ray attacker added behind it.
1438 clear_bit(&occupied, from);
1439 attackers = (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1440 | (bishop_attacks_bb(to, occupied)& pieces(BISHOP, QUEEN))
1441 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1442 | (attacks_from<KING>(to) & pieces(KING))
1443 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1444 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1446 // If the opponent has no attackers we are finished
1447 stm = opposite_color(color_of_piece_on(from));
1448 stmAttackers = attackers & pieces_of_color(stm);
1450 return seeValues[capturedType];
1452 // The destination square is defended, which makes things rather more
1453 // difficult to compute. We proceed by building up a "swap list" containing
1454 // the material gain or loss at each stop in a sequence of captures to the
1455 // destination square, where the sides alternately capture, and always
1456 // capture with the least valuable piece. After each capture, we look for
1457 // new X-ray attacks from behind the capturing piece.
1458 swapList[0] = seeValues[capturedType];
1459 capturedType = type_of_piece_on(from);
1462 // Locate the least valuable attacker for the side to move. The loop
1463 // below looks like it is potentially infinite, but it isn't. We know
1464 // that the side to move still has at least one attacker left.
1465 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1468 // Remove the attacker we just found from the 'occupied' bitboard,
1469 // and scan for new X-ray attacks behind the attacker.
1470 b = stmAttackers & pieces(pt);
1471 occupied ^= (b & (~b + 1));
1472 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1473 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1475 attackers &= occupied; // Cut out pieces we've already done
1477 // Add the new entry to the swap list
1478 assert(slIndex < 32);
1479 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1482 // Remember the value of the capturing piece, and change the side to
1483 // move before beginning the next iteration.
1485 stm = opposite_color(stm);
1486 stmAttackers = attackers & pieces_of_color(stm);
1488 // Stop before processing a king capture
1489 if (capturedType == KING && stmAttackers)
1491 assert(slIndex < 32);
1492 swapList[slIndex++] = QueenValueMidgame*10;
1495 } while (stmAttackers);
1497 // Having built the swap list, we negamax through it to find the best
1498 // achievable score from the point of view of the side to move.
1500 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1506 /// Position::clear() erases the position object to a pristine state, with an
1507 /// empty board, white to move, and no castling rights.
1509 void Position::clear() {
1512 memset(st, 0, sizeof(StateInfo));
1513 st->epSquare = SQ_NONE;
1514 startPosPlyCounter = 0;
1517 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1518 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1519 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1520 memset(index, 0, sizeof(int) * 64);
1522 for (int i = 0; i < 64; i++)
1523 board[i] = PIECE_NONE;
1525 for (int i = 0; i < 8; i++)
1526 for (int j = 0; j < 16; j++)
1527 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1529 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1530 castleRightsMask[sq] = ALL_CASTLES;
1533 initialKFile = FILE_E;
1534 initialKRFile = FILE_H;
1535 initialQRFile = FILE_A;
1539 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1540 /// UCI interface code, whenever a non-reversible move is made in a
1541 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1542 /// for the program to handle games of arbitrary length, as long as the GUI
1543 /// handles draws by the 50 move rule correctly.
1545 void Position::reset_game_ply() {
1550 void Position::inc_startpos_ply_counter() {
1552 startPosPlyCounter++;
1555 /// Position::put_piece() puts a piece on the given square of the board,
1556 /// updating the board array, pieces list, bitboards, and piece counts.
1558 void Position::put_piece(Piece p, Square s) {
1560 Color c = color_of_piece(p);
1561 PieceType pt = type_of_piece(p);
1564 index[s] = pieceCount[c][pt]++;
1565 pieceList[c][pt][index[s]] = s;
1567 set_bit(&(byTypeBB[pt]), s);
1568 set_bit(&(byColorBB[c]), s);
1569 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1573 /// Position::compute_key() computes the hash key of the position. The hash
1574 /// key is usually updated incrementally as moves are made and unmade, the
1575 /// compute_key() function is only used when a new position is set up, and
1576 /// to verify the correctness of the hash key when running in debug mode.
1578 Key Position::compute_key() const {
1580 Key result = zobCastle[st->castleRights];
1582 for (Square s = SQ_A1; s <= SQ_H8; s++)
1583 if (square_is_occupied(s))
1584 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1586 if (ep_square() != SQ_NONE)
1587 result ^= zobEp[ep_square()];
1589 if (side_to_move() == BLACK)
1590 result ^= zobSideToMove;
1596 /// Position::compute_pawn_key() computes the hash key of the position. The
1597 /// hash key is usually updated incrementally as moves are made and unmade,
1598 /// the compute_pawn_key() function is only used when a new position is set
1599 /// up, and to verify the correctness of the pawn hash key when running in
1602 Key Position::compute_pawn_key() const {
1607 for (Color c = WHITE; c <= BLACK; c++)
1609 b = pieces(PAWN, c);
1611 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1617 /// Position::compute_material_key() computes the hash key of the position.
1618 /// The hash key is usually updated incrementally as moves are made and unmade,
1619 /// the compute_material_key() function is only used when a new position is set
1620 /// up, and to verify the correctness of the material hash key when running in
1623 Key Position::compute_material_key() const {
1628 for (Color c = WHITE; c <= BLACK; c++)
1629 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1631 count = piece_count(c, pt);
1632 for (int i = 0; i < count; i++)
1633 result ^= zobrist[c][pt][i];
1639 /// Position::compute_value() compute the incremental scores for the middle
1640 /// game and the endgame. These functions are used to initialize the incremental
1641 /// scores when a new position is set up, and to verify that the scores are correctly
1642 /// updated by do_move and undo_move when the program is running in debug mode.
1643 Score Position::compute_value() const {
1646 Score result = SCORE_ZERO;
1648 for (Color c = WHITE; c <= BLACK; c++)
1649 for (PieceType pt = PAWN; pt <= KING; pt++)
1653 result += pst(c, pt, pop_1st_bit(&b));
1656 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1661 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1662 /// game material value for the given side. Material values are updated
1663 /// incrementally during the search, this function is only used while
1664 /// initializing a new Position object.
1666 Value Position::compute_non_pawn_material(Color c) const {
1668 Value result = VALUE_ZERO;
1670 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1671 result += piece_count(c, pt) * PieceValueMidgame[pt];
1677 /// Position::is_draw() tests whether the position is drawn by material,
1678 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1679 /// must be done by the search.
1681 bool Position::is_draw() const {
1683 // Draw by material?
1685 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1688 // Draw by the 50 moves rule?
1689 if (st->rule50 > 99 && (st->rule50 > 100 || !is_mate()))
1692 // Draw by repetition?
1693 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1694 if (history[st->gamePly - i] == st->key)
1701 /// Position::is_mate() returns true or false depending on whether the
1702 /// side to move is checkmated.
1704 bool Position::is_mate() const {
1706 MoveStack moves[MOVES_MAX];
1707 return is_check() && generate_moves(*this, moves) == moves;
1711 /// Position::has_mate_threat() tests whether the side to move is under
1712 /// a threat of being mated in one from the current position.
1714 bool Position::has_mate_threat() {
1716 MoveStack mlist[MOVES_MAX], *last, *cur;
1718 bool mateFound = false;
1720 // If we are under check it's up to evasions to do the job
1724 // First pass the move to our opponent doing a null move
1727 // Then generate pseudo-legal moves that could give check
1728 last = generate_non_capture_checks(*this, mlist);
1729 last = generate_captures(*this, last);
1731 // Loop through the moves, and see if one of them gives mate
1732 Bitboard pinned = pinned_pieces(sideToMove);
1733 CheckInfo ci(*this);
1734 for (cur = mlist; cur != last && !mateFound; cur++)
1736 Move move = cur->move;
1737 if ( !pl_move_is_legal(move, pinned)
1738 || !move_is_check(move, ci))
1741 do_move(move, st2, ci, true);
1754 /// Position::init_zobrist() is a static member function which initializes at
1755 /// startup the various arrays used to compute hash keys.
1757 void Position::init_zobrist() {
1762 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1763 zobrist[i][j][k] = rk.rand<Key>();
1765 for (i = 0; i < 64; i++)
1766 zobEp[i] = rk.rand<Key>();
1768 for (i = 0; i < 16; i++)
1769 zobCastle[i] = rk.rand<Key>();
1771 zobSideToMove = rk.rand<Key>();
1772 zobExclusion = rk.rand<Key>();
1776 /// Position::init_piece_square_tables() initializes the piece square tables.
1777 /// This is a two-step operation: First, the white halves of the tables are
1778 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1779 /// of the tables are initialized by mirroring and changing the sign of the
1780 /// corresponding white scores.
1782 void Position::init_piece_square_tables() {
1784 for (Square s = SQ_A1; s <= SQ_H8; s++)
1785 for (Piece p = WP; p <= WK; p++)
1786 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1788 for (Square s = SQ_A1; s <= SQ_H8; s++)
1789 for (Piece p = BP; p <= BK; p++)
1790 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1794 /// Position::flipped_copy() makes a copy of the input position, but with
1795 /// the white and black sides reversed. This is only useful for debugging,
1796 /// especially for finding evaluation symmetry bugs.
1798 void Position::flipped_copy(const Position& pos) {
1800 assert(pos.is_ok());
1803 threadID = pos.thread();
1806 for (Square s = SQ_A1; s <= SQ_H8; s++)
1807 if (!pos.square_is_empty(s))
1808 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1811 sideToMove = opposite_color(pos.side_to_move());
1814 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1815 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1816 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1817 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1819 initialKFile = pos.initialKFile;
1820 initialKRFile = pos.initialKRFile;
1821 initialQRFile = pos.initialQRFile;
1823 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1824 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1825 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1826 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1827 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1828 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1830 // En passant square
1831 if (pos.st->epSquare != SQ_NONE)
1832 st->epSquare = flip_square(pos.st->epSquare);
1838 st->key = compute_key();
1839 st->pawnKey = compute_pawn_key();
1840 st->materialKey = compute_material_key();
1842 // Incremental scores
1843 st->value = compute_value();
1846 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1847 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1853 /// Position::is_ok() performs some consitency checks for the position object.
1854 /// This is meant to be helpful when debugging.
1856 bool Position::is_ok(int* failedStep) const {
1858 // What features of the position should be verified?
1859 const bool debugAll = false;
1861 const bool debugBitboards = debugAll || false;
1862 const bool debugKingCount = debugAll || false;
1863 const bool debugKingCapture = debugAll || false;
1864 const bool debugCheckerCount = debugAll || false;
1865 const bool debugKey = debugAll || false;
1866 const bool debugMaterialKey = debugAll || false;
1867 const bool debugPawnKey = debugAll || false;
1868 const bool debugIncrementalEval = debugAll || false;
1869 const bool debugNonPawnMaterial = debugAll || false;
1870 const bool debugPieceCounts = debugAll || false;
1871 const bool debugPieceList = debugAll || false;
1872 const bool debugCastleSquares = debugAll || false;
1874 if (failedStep) *failedStep = 1;
1877 if (!color_is_ok(side_to_move()))
1880 // Are the king squares in the position correct?
1881 if (failedStep) (*failedStep)++;
1882 if (piece_on(king_square(WHITE)) != WK)
1885 if (failedStep) (*failedStep)++;
1886 if (piece_on(king_square(BLACK)) != BK)
1890 if (failedStep) (*failedStep)++;
1891 if (!file_is_ok(initialKRFile))
1894 if (!file_is_ok(initialQRFile))
1897 // Do both sides have exactly one king?
1898 if (failedStep) (*failedStep)++;
1901 int kingCount[2] = {0, 0};
1902 for (Square s = SQ_A1; s <= SQ_H8; s++)
1903 if (type_of_piece_on(s) == KING)
1904 kingCount[color_of_piece_on(s)]++;
1906 if (kingCount[0] != 1 || kingCount[1] != 1)
1910 // Can the side to move capture the opponent's king?
1911 if (failedStep) (*failedStep)++;
1912 if (debugKingCapture)
1914 Color us = side_to_move();
1915 Color them = opposite_color(us);
1916 Square ksq = king_square(them);
1917 if (attackers_to(ksq) & pieces_of_color(us))
1921 // Is there more than 2 checkers?
1922 if (failedStep) (*failedStep)++;
1923 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1927 if (failedStep) (*failedStep)++;
1930 // The intersection of the white and black pieces must be empty
1931 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1934 // The union of the white and black pieces must be equal to all
1936 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1939 // Separate piece type bitboards must have empty intersections
1940 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1941 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1942 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1946 // En passant square OK?
1947 if (failedStep) (*failedStep)++;
1948 if (ep_square() != SQ_NONE)
1950 // The en passant square must be on rank 6, from the point of view of the
1952 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1957 if (failedStep) (*failedStep)++;
1958 if (debugKey && st->key != compute_key())
1961 // Pawn hash key OK?
1962 if (failedStep) (*failedStep)++;
1963 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1966 // Material hash key OK?
1967 if (failedStep) (*failedStep)++;
1968 if (debugMaterialKey && st->materialKey != compute_material_key())
1971 // Incremental eval OK?
1972 if (failedStep) (*failedStep)++;
1973 if (debugIncrementalEval && st->value != compute_value())
1976 // Non-pawn material OK?
1977 if (failedStep) (*failedStep)++;
1978 if (debugNonPawnMaterial)
1980 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1983 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1988 if (failedStep) (*failedStep)++;
1989 if (debugPieceCounts)
1990 for (Color c = WHITE; c <= BLACK; c++)
1991 for (PieceType pt = PAWN; pt <= KING; pt++)
1992 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1995 if (failedStep) (*failedStep)++;
1998 for (Color c = WHITE; c <= BLACK; c++)
1999 for (PieceType pt = PAWN; pt <= KING; pt++)
2000 for (int i = 0; i < pieceCount[c][pt]; i++)
2002 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2005 if (index[piece_list(c, pt, i)] != i)
2010 if (failedStep) (*failedStep)++;
2011 if (debugCastleSquares) {
2012 for (Color c = WHITE; c <= BLACK; c++) {
2013 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
2015 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2018 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2020 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2022 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2024 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2028 if (failedStep) *failedStep = 0;