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/>.
34 #include "ucioption.h"
40 Key Position::zobrist[2][8][64];
41 Key Position::zobEp[64];
42 Key Position::zobCastle[16];
43 Key Position::zobSideToMove;
44 Key Position::zobExclusion;
46 Score Position::PieceSquareTable[16][64];
48 // Material values arrays, indexed by Piece
49 const Value Position::PieceValueMidgame[17] = {
51 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
52 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
53 VALUE_ZERO, VALUE_ZERO,
54 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
55 RookValueMidgame, QueenValueMidgame
58 const Value Position::PieceValueEndgame[17] = {
60 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
61 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
62 VALUE_ZERO, VALUE_ZERO,
63 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
64 RookValueEndgame, QueenValueEndgame
67 // Material values array used by SEE, indexed by PieceType
68 const Value Position::seeValues[] = {
70 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
71 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
77 // Bonus for having the side to move (modified by Joona Kiiski)
78 const Score TempoValue = make_score(48, 22);
80 bool isZero(char c) { return c == '0'; }
82 struct PieceLetters : public std::map<char, Piece> {
86 operator[]('K') = WK; operator[]('k') = BK;
87 operator[]('Q') = WQ; operator[]('q') = BQ;
88 operator[]('R') = WR; operator[]('r') = BR;
89 operator[]('B') = WB; operator[]('b') = BB;
90 operator[]('N') = WN; operator[]('n') = BN;
91 operator[]('P') = WP; operator[]('p') = BP;
92 operator[](' ') = PIECE_NONE;
93 operator[]('.') = PIECE_NONE_DARK_SQ;
96 char from_piece(Piece p) const {
98 std::map<char, Piece>::const_iterator it;
99 for (it = begin(); it != end(); ++it)
108 PieceLetters pieceLetters;
114 CheckInfo::CheckInfo(const Position& pos) {
116 Color us = pos.side_to_move();
117 Color them = opposite_color(us);
119 ksq = pos.king_square(them);
120 dcCandidates = pos.discovered_check_candidates(us);
122 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
123 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
124 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
125 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
126 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
127 checkSq[KING] = EmptyBoardBB;
131 /// Position c'tors. Here we always create a copy of the original position
132 /// or the FEN string, we want the new born Position object do not depend
133 /// on any external data so we detach state pointer from the source one.
135 Position::Position(const Position& pos, int th) {
137 memcpy(this, &pos, sizeof(Position));
138 detach(); // Always detach() in copy c'tor to avoid surprises
143 Position::Position(const string& fen, bool isChess960, int th) {
145 from_fen(fen, isChess960);
150 /// Position::detach() copies the content of the current state and castling
151 /// masks inside the position itself. This is needed when the st pointee could
152 /// become stale, as example because the caller is about to going out of scope.
154 void Position::detach() {
158 st->previous = NULL; // as a safe guard
162 /// Position::from_fen() initializes the position object with the given FEN
163 /// string. This function is not very robust - make sure that input FENs are
164 /// correct (this is assumed to be the responsibility of the GUI).
166 void Position::from_fen(const string& fen, bool c960) {
168 A FEN string defines a particular position using only the ASCII character set.
170 A FEN string contains six fields. The separator between fields is a space. The fields are:
172 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
173 with rank 1; within each rank, the contents of each square are described from file A through file H.
174 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
175 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
176 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
177 of blank squares), and "/" separate ranks.
179 2) Active color. "w" means white moves next, "b" means black.
181 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
182 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
183 kingside), and/or "q" (Black can castle queenside).
185 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
186 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
187 regardless of whether there is a pawn in position to make an en passant capture.
189 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
190 to determine if a draw can be claimed under the fifty-move rule.
192 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
197 std::istringstream ss(fen);
202 // 1. Piece placement field
203 while (ss.get(token) && token != ' ')
205 if (pieceLetters.find(token) != pieceLetters.end())
207 put_piece(pieceLetters[token], sq);
210 else if (isdigit(token))
211 sq += Square(token - '0'); // Skip the given number of files
212 else if (token == '/')
213 sq -= SQ_A3; // Jump back of 2 rows
219 if (!ss.get(token) || (token != 'w' && token != 'b'))
222 sideToMove = (token == 'w' ? WHITE : BLACK);
224 if (!ss.get(token) || token != ' ')
227 // 3. Castling availability
228 while (ss.get(token) && token != ' ')
229 if (!set_castling_rights(token))
232 // 4. En passant square
234 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
235 && (ss.get(row) && (row == '3' || row == '6')))
237 st->epSquare = make_square(file_from_char(col), rank_from_char(row));
239 // Ignore if no capture is possible
240 Color them = opposite_color(sideToMove);
241 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
242 st->epSquare = SQ_NONE;
249 // 6. Fullmove number
251 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
253 // Various initialisations
254 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
255 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
256 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
257 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
258 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
259 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
264 st->key = compute_key();
265 st->pawnKey = compute_pawn_key();
266 st->materialKey = compute_material_key();
267 st->value = compute_value();
268 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
269 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
273 cout << "Error in FEN string: " << fen << endl;
277 /// Position::set_castling_rights() sets castling parameters castling avaiability.
278 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
279 /// that uses the letters of the columns on which the rooks began the game instead
280 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
281 /// associated with the castling right, the traditional castling tag will be replaced
282 /// by the file letter of the involved rook as for the Shredder-FEN.
284 bool Position::set_castling_rights(char token) {
286 Color c = token >= 'a' ? BLACK : WHITE;
287 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
288 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
289 Piece rook = (c == WHITE ? WR : BR);
291 initialKFile = square_file(king_square(c));
292 token = char(toupper(token));
296 for (Square sq = sqH; sq >= sqA; sq--)
297 if (piece_on(sq) == rook)
300 initialKRFile = square_file(sq);
304 else if (token == 'Q')
306 for (Square sq = sqA; sq <= sqH; sq++)
307 if (piece_on(sq) == rook)
310 initialQRFile = square_file(sq);
314 else if (token >= 'A' && token <= 'H')
316 File rookFile = File(token - 'A') + FILE_A;
317 if (rookFile < initialKFile)
320 initialQRFile = rookFile;
325 initialKRFile = rookFile;
335 /// Position::to_fen() returns a FEN representation of the position. In case
336 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
338 const string Position::to_fen() const {
344 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
346 for (File file = FILE_A; file <= FILE_H; file++)
348 sq = make_square(file, rank);
350 if (square_is_occupied(sq))
353 fen += pieceLetters.from_piece(piece_on(sq));
363 fen.erase(std::remove_if(fen.begin(), fen.end(), isZero), fen.end());
364 fen.erase(--fen.end());
365 fen += (sideToMove == WHITE ? " w " : " b ");
367 if (st->castleRights != CASTLES_NONE)
369 if (can_castle_kingside(WHITE))
370 fen += isChess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
372 if (can_castle_queenside(WHITE))
373 fen += isChess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
375 if (can_castle_kingside(BLACK))
376 fen += isChess960 ? file_to_char(initialKRFile) : 'k';
378 if (can_castle_queenside(BLACK))
379 fen += isChess960 ? file_to_char(initialQRFile) : 'q';
383 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
388 /// Position::print() prints an ASCII representation of the position to
389 /// the standard output. If a move is given then also the san is printed.
391 void Position::print(Move move) const {
393 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
397 Position p(*this, thread());
398 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
399 cout << "\nMove is: " << dd << move_to_san(p, move);
402 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
404 cout << dottedLine << '|';
405 for (File file = FILE_A; file <= FILE_H; file++)
407 Square sq = make_square(file, rank);
408 Piece piece = piece_on(sq);
410 if (piece == PIECE_NONE && square_color(sq) == DARK)
411 piece = PIECE_NONE_DARK_SQ;
413 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
414 cout << c << pieceLetters.from_piece(piece) << c << '|';
417 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
421 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
422 /// king) pieces for the given color and for the given pinner type. Or, when
423 /// template parameter FindPinned is false, the pieces of the given color
424 /// candidate for a discovery check against the enemy king.
425 /// Bitboard checkersBB must be already updated when looking for pinners.
427 template<bool FindPinned>
428 Bitboard Position::hidden_checkers(Color c) const {
430 Bitboard result = EmptyBoardBB;
431 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
433 // Pinned pieces protect our king, dicovery checks attack
435 Square ksq = king_square(FindPinned ? c : opposite_color(c));
437 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
438 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
440 if (FindPinned && pinners)
441 pinners &= ~st->checkersBB;
445 Square s = pop_1st_bit(&pinners);
446 Bitboard b = squares_between(s, ksq) & occupied_squares();
450 if ( !(b & (b - 1)) // Only one bit set?
451 && (b & pieces_of_color(c))) // Is an our piece?
458 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
459 /// king) pieces for the given color. Note that checkersBB bitboard must
460 /// be already updated.
462 Bitboard Position::pinned_pieces(Color c) const {
464 return hidden_checkers<true>(c);
468 /// Position:discovered_check_candidates() returns a bitboard containing all
469 /// pieces for the given side which are candidates for giving a discovered
470 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
471 /// to be already updated.
473 Bitboard Position::discovered_check_candidates(Color c) const {
475 return hidden_checkers<false>(c);
478 /// Position::attackers_to() computes a bitboard containing all pieces which
479 /// attacks a given square.
481 Bitboard Position::attackers_to(Square s) const {
483 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
484 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
485 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
486 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
487 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
488 | (attacks_from<KING>(s) & pieces(KING));
491 /// Position::attacks_from() computes a bitboard of all attacks
492 /// of a given piece put in a given square.
494 Bitboard Position::attacks_from(Piece p, Square s) const {
496 assert(square_is_ok(s));
500 case WB: case BB: return attacks_from<BISHOP>(s);
501 case WR: case BR: return attacks_from<ROOK>(s);
502 case WQ: case BQ: return attacks_from<QUEEN>(s);
503 default: return NonSlidingAttacksBB[p][s];
507 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
509 assert(square_is_ok(s));
513 case WB: case BB: return bishop_attacks_bb(s, occ);
514 case WR: case BR: return rook_attacks_bb(s, occ);
515 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
516 default: return NonSlidingAttacksBB[p][s];
521 /// Position::move_attacks_square() tests whether a move from the current
522 /// position attacks a given square.
524 bool Position::move_attacks_square(Move m, Square s) const {
526 assert(move_is_ok(m));
527 assert(square_is_ok(s));
530 Square f = move_from(m), t = move_to(m);
532 assert(square_is_occupied(f));
534 if (bit_is_set(attacks_from(piece_on(f), t), s))
537 // Move the piece and scan for X-ray attacks behind it
538 occ = occupied_squares();
539 do_move_bb(&occ, make_move_bb(f, t));
540 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
541 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
542 & pieces_of_color(color_of_piece_on(f));
544 // If we have attacks we need to verify that are caused by our move
545 // and are not already existent ones.
546 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
550 /// Position::find_checkers() computes the checkersBB bitboard, which
551 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
552 /// currently works by calling Position::attackers_to, which is probably
553 /// inefficient. Consider rewriting this function to use the last move
554 /// played, like in non-bitboard versions of Glaurung.
556 void Position::find_checkers() {
558 Color us = side_to_move();
559 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
563 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
565 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
568 assert(move_is_ok(m));
569 assert(pinned == pinned_pieces(side_to_move()));
571 // Castling moves are checked for legality during move generation.
572 if (move_is_castle(m))
575 // En passant captures are a tricky special case. Because they are
576 // rather uncommon, we do it simply by testing whether the king is attacked
577 // after the move is made
580 Color us = side_to_move();
581 Color them = opposite_color(us);
582 Square from = move_from(m);
583 Square to = move_to(m);
584 Square capsq = make_square(square_file(to), square_rank(from));
585 Square ksq = king_square(us);
586 Bitboard b = occupied_squares();
588 assert(to == ep_square());
589 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
590 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
591 assert(piece_on(to) == PIECE_NONE);
594 clear_bit(&b, capsq);
597 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
598 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
601 Color us = side_to_move();
602 Square from = move_from(m);
604 assert(color_of_piece_on(from) == us);
605 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
607 // If the moving piece is a king, check whether the destination
608 // square is attacked by the opponent.
609 if (type_of_piece_on(from) == KING)
610 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
612 // A non-king move is legal if and only if it is not pinned or it
613 // is moving along the ray towards or away from the king.
615 || !bit_is_set(pinned, from)
616 || squares_aligned(from, move_to(m), king_square(us));
620 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
622 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
626 Color us = side_to_move();
627 Square from = move_from(m);
628 Square to = move_to(m);
630 // King moves and en-passant captures are verified in pl_move_is_legal()
631 if (type_of_piece_on(from) == KING || move_is_ep(m))
632 return pl_move_is_legal(m, pinned);
634 Bitboard target = checkers();
635 Square checksq = pop_1st_bit(&target);
637 if (target) // double check ?
640 // Our move must be a blocking evasion or a capture of the checking piece
641 target = squares_between(checksq, king_square(us)) | checkers();
642 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
646 /// Position::move_is_check() tests whether a pseudo-legal move is a check
648 bool Position::move_is_check(Move m) const {
650 return move_is_check(m, CheckInfo(*this));
653 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
656 assert(move_is_ok(m));
657 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
658 assert(color_of_piece_on(move_from(m)) == side_to_move());
659 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
661 Square from = move_from(m);
662 Square to = move_to(m);
663 PieceType pt = type_of_piece_on(from);
666 if (bit_is_set(ci.checkSq[pt], to))
670 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
672 // For pawn and king moves we need to verify also direction
673 if ( (pt != PAWN && pt != KING)
674 || !squares_aligned(from, to, ci.ksq))
678 // Can we skip the ugly special cases ?
679 if (!move_is_special(m))
682 Color us = side_to_move();
683 Bitboard b = occupied_squares();
685 // Promotion with check ?
686 if (move_is_promotion(m))
690 switch (move_promotion_piece(m))
693 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
695 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
697 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
699 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
705 // En passant capture with check ? We have already handled the case
706 // of direct checks and ordinary discovered check, the only case we
707 // need to handle is the unusual case of a discovered check through
708 // the captured pawn.
711 Square capsq = make_square(square_file(to), square_rank(from));
713 clear_bit(&b, capsq);
715 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
716 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
719 // Castling with check ?
720 if (move_is_castle(m))
722 Square kfrom, kto, rfrom, rto;
728 kto = relative_square(us, SQ_G1);
729 rto = relative_square(us, SQ_F1);
731 kto = relative_square(us, SQ_C1);
732 rto = relative_square(us, SQ_D1);
734 clear_bit(&b, kfrom);
735 clear_bit(&b, rfrom);
738 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
745 /// Position::do_setup_move() makes a permanent move on the board.
746 /// It should be used when setting up a position on board.
747 /// You can't undo the move.
749 void Position::do_setup_move(Move m) {
755 // Reset "game ply" in case we made a non-reversible move.
756 // "game ply" is used for repetition detection.
760 // Update the number of plies played from the starting position
761 startPosPlyCounter++;
763 // Our StateInfo newSt is about going out of scope so copy
764 // its content inside pos before it disappears.
768 /// Position::do_move() makes a move, and saves all information necessary
769 /// to a StateInfo object. The move is assumed to be legal.
770 /// Pseudo-legal moves should be filtered out before this function is called.
772 void Position::do_move(Move m, StateInfo& newSt) {
775 do_move(m, newSt, ci, move_is_check(m, ci));
778 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
781 assert(move_is_ok(m));
782 assert(&newSt != st);
787 // Copy some fields of old state to our new StateInfo object except the
788 // ones which are recalculated from scratch anyway, then switch our state
789 // pointer to point to the new, ready to be updated, state.
790 struct ReducedStateInfo {
791 Key pawnKey, materialKey;
792 int castleRights, rule50, gamePly, pliesFromNull;
798 memcpy(&newSt, st, sizeof(ReducedStateInfo));
803 // Save the current key to the history[] array, in order to be able to
804 // detect repetition draws.
805 history[st->gamePly++] = key;
807 // Update side to move
808 key ^= zobSideToMove;
810 // Increment the 50 moves rule draw counter. Resetting it to zero in the
811 // case of non-reversible moves is taken care of later.
815 if (move_is_castle(m))
822 Color us = side_to_move();
823 Color them = opposite_color(us);
824 Square from = move_from(m);
825 Square to = move_to(m);
826 bool ep = move_is_ep(m);
827 bool pm = move_is_promotion(m);
829 Piece piece = piece_on(from);
830 PieceType pt = type_of_piece(piece);
831 PieceType capture = ep ? PAWN : type_of_piece_on(to);
833 assert(color_of_piece_on(from) == us);
834 assert(color_of_piece_on(to) == them || square_is_empty(to));
835 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
836 assert(!pm || relative_rank(us, to) == RANK_8);
839 do_capture_move(key, capture, them, to, ep);
842 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
844 // Reset en passant square
845 if (st->epSquare != SQ_NONE)
847 key ^= zobEp[st->epSquare];
848 st->epSquare = SQ_NONE;
851 // Update castle rights, try to shortcut a common case
852 int cm = castleRightsMask[from] & castleRightsMask[to];
853 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
855 key ^= zobCastle[st->castleRights];
856 st->castleRights &= castleRightsMask[from];
857 st->castleRights &= castleRightsMask[to];
858 key ^= zobCastle[st->castleRights];
861 // Prefetch TT access as soon as we know key is updated
862 prefetch((char*)TT.first_entry(key));
865 Bitboard move_bb = make_move_bb(from, to);
866 do_move_bb(&(byColorBB[us]), move_bb);
867 do_move_bb(&(byTypeBB[pt]), move_bb);
868 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
870 board[to] = board[from];
871 board[from] = PIECE_NONE;
873 // Update piece lists, note that index[from] is not updated and
874 // becomes stale. This works as long as index[] is accessed just
875 // by known occupied squares.
876 index[to] = index[from];
877 pieceList[us][pt][index[to]] = to;
879 // If the moving piece was a pawn do some special extra work
882 // Reset rule 50 draw counter
885 // Update pawn hash key and prefetch in L1/L2 cache
886 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
887 prefetchPawn(st->pawnKey, threadID);
889 // Set en passant square, only if moved pawn can be captured
890 if ((to ^ from) == 16)
892 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
894 st->epSquare = Square((int(from) + int(to)) / 2);
895 key ^= zobEp[st->epSquare];
899 if (pm) // promotion ?
901 PieceType promotion = move_promotion_piece(m);
903 assert(promotion >= KNIGHT && promotion <= QUEEN);
905 // Insert promoted piece instead of pawn
906 clear_bit(&(byTypeBB[PAWN]), to);
907 set_bit(&(byTypeBB[promotion]), to);
908 board[to] = piece_of_color_and_type(us, promotion);
910 // Update piece counts
911 pieceCount[us][promotion]++;
912 pieceCount[us][PAWN]--;
914 // Update material key
915 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
916 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
918 // Update piece lists, move the last pawn at index[to] position
919 // and shrink the list. Add a new promotion piece to the list.
920 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
921 index[lastPawnSquare] = index[to];
922 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
923 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
924 index[to] = pieceCount[us][promotion] - 1;
925 pieceList[us][promotion][index[to]] = to;
927 // Partially revert hash keys update
928 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
929 st->pawnKey ^= zobrist[us][PAWN][to];
931 // Partially revert and update incremental scores
932 st->value -= pst(us, PAWN, to);
933 st->value += pst(us, promotion, to);
936 st->npMaterial[us] += PieceValueMidgame[promotion];
940 // Update incremental scores
941 st->value += pst_delta(piece, from, to);
944 st->capturedType = capture;
946 // Update the key with the final value
949 // Update checkers bitboard, piece must be already moved
950 st->checkersBB = EmptyBoardBB;
955 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
959 if (bit_is_set(ci.checkSq[pt], to))
960 st->checkersBB = SetMaskBB[to];
963 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
966 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
969 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
975 sideToMove = opposite_color(sideToMove);
976 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
982 /// Position::do_capture_move() is a private method used to update captured
983 /// piece info. It is called from the main Position::do_move function.
985 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
987 assert(capture != KING);
991 // If the captured piece was a pawn, update pawn hash key,
992 // otherwise update non-pawn material.
995 if (ep) // en passant ?
997 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
999 assert(to == st->epSquare);
1000 assert(relative_rank(opposite_color(them), to) == RANK_6);
1001 assert(piece_on(to) == PIECE_NONE);
1002 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1004 board[capsq] = PIECE_NONE;
1006 st->pawnKey ^= zobrist[them][PAWN][capsq];
1009 st->npMaterial[them] -= PieceValueMidgame[capture];
1011 // Remove captured piece
1012 clear_bit(&(byColorBB[them]), capsq);
1013 clear_bit(&(byTypeBB[capture]), capsq);
1014 clear_bit(&(byTypeBB[0]), capsq);
1017 key ^= zobrist[them][capture][capsq];
1019 // Update incremental scores
1020 st->value -= pst(them, capture, capsq);
1022 // Update piece count
1023 pieceCount[them][capture]--;
1025 // Update material hash key
1026 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1028 // Update piece list, move the last piece at index[capsq] position
1030 // WARNING: This is a not perfectly revresible operation. When we
1031 // will reinsert the captured piece in undo_move() we will put it
1032 // at the end of the list and not in its original place, it means
1033 // index[] and pieceList[] are not guaranteed to be invariant to a
1034 // do_move() + undo_move() sequence.
1035 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1036 index[lastPieceSquare] = index[capsq];
1037 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1038 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1040 // Reset rule 50 counter
1045 /// Position::do_castle_move() is a private method used to make a castling
1046 /// move. It is called from the main Position::do_move function. Note that
1047 /// castling moves are encoded as "king captures friendly rook" moves, for
1048 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1050 void Position::do_castle_move(Move m) {
1052 assert(move_is_ok(m));
1053 assert(move_is_castle(m));
1055 Color us = side_to_move();
1056 Color them = opposite_color(us);
1058 // Reset capture field
1059 st->capturedType = PIECE_TYPE_NONE;
1061 // Find source squares for king and rook
1062 Square kfrom = move_from(m);
1063 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1066 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
1067 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
1069 // Find destination squares for king and rook
1070 if (rfrom > kfrom) // O-O
1072 kto = relative_square(us, SQ_G1);
1073 rto = relative_square(us, SQ_F1);
1075 kto = relative_square(us, SQ_C1);
1076 rto = relative_square(us, SQ_D1);
1079 // Remove pieces from source squares:
1080 clear_bit(&(byColorBB[us]), kfrom);
1081 clear_bit(&(byTypeBB[KING]), kfrom);
1082 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1083 clear_bit(&(byColorBB[us]), rfrom);
1084 clear_bit(&(byTypeBB[ROOK]), rfrom);
1085 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1087 // Put pieces on destination squares:
1088 set_bit(&(byColorBB[us]), kto);
1089 set_bit(&(byTypeBB[KING]), kto);
1090 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1091 set_bit(&(byColorBB[us]), rto);
1092 set_bit(&(byTypeBB[ROOK]), rto);
1093 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1095 // Update board array
1096 Piece king = piece_of_color_and_type(us, KING);
1097 Piece rook = piece_of_color_and_type(us, ROOK);
1098 board[kfrom] = board[rfrom] = PIECE_NONE;
1102 // Update piece lists
1103 pieceList[us][KING][index[kfrom]] = kto;
1104 pieceList[us][ROOK][index[rfrom]] = rto;
1105 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1106 index[kto] = index[kfrom];
1109 // Update incremental scores
1110 st->value += pst_delta(king, kfrom, kto);
1111 st->value += pst_delta(rook, rfrom, rto);
1114 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1115 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1117 // Clear en passant square
1118 if (st->epSquare != SQ_NONE)
1120 st->key ^= zobEp[st->epSquare];
1121 st->epSquare = SQ_NONE;
1124 // Update castling rights
1125 st->key ^= zobCastle[st->castleRights];
1126 st->castleRights &= castleRightsMask[kfrom];
1127 st->key ^= zobCastle[st->castleRights];
1129 // Reset rule 50 counter
1132 // Update checkers BB
1133 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1136 sideToMove = opposite_color(sideToMove);
1137 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1143 /// Position::undo_move() unmakes a move. When it returns, the position should
1144 /// be restored to exactly the same state as before the move was made.
1146 void Position::undo_move(Move m) {
1149 assert(move_is_ok(m));
1151 sideToMove = opposite_color(sideToMove);
1153 if (move_is_castle(m))
1155 undo_castle_move(m);
1159 Color us = side_to_move();
1160 Color them = opposite_color(us);
1161 Square from = move_from(m);
1162 Square to = move_to(m);
1163 bool ep = move_is_ep(m);
1164 bool pm = move_is_promotion(m);
1166 PieceType pt = type_of_piece_on(to);
1168 assert(square_is_empty(from));
1169 assert(color_of_piece_on(to) == us);
1170 assert(!pm || relative_rank(us, to) == RANK_8);
1171 assert(!ep || to == st->previous->epSquare);
1172 assert(!ep || relative_rank(us, to) == RANK_6);
1173 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1175 if (pm) // promotion ?
1177 PieceType promotion = move_promotion_piece(m);
1180 assert(promotion >= KNIGHT && promotion <= QUEEN);
1181 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1183 // Replace promoted piece with a pawn
1184 clear_bit(&(byTypeBB[promotion]), to);
1185 set_bit(&(byTypeBB[PAWN]), to);
1187 // Update piece counts
1188 pieceCount[us][promotion]--;
1189 pieceCount[us][PAWN]++;
1191 // Update piece list replacing promotion piece with a pawn
1192 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1193 index[lastPromotionSquare] = index[to];
1194 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1195 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1196 index[to] = pieceCount[us][PAWN] - 1;
1197 pieceList[us][PAWN][index[to]] = to;
1200 // Put the piece back at the source square
1201 Bitboard move_bb = make_move_bb(to, from);
1202 do_move_bb(&(byColorBB[us]), move_bb);
1203 do_move_bb(&(byTypeBB[pt]), move_bb);
1204 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1206 board[from] = piece_of_color_and_type(us, pt);
1207 board[to] = PIECE_NONE;
1209 // Update piece list
1210 index[from] = index[to];
1211 pieceList[us][pt][index[from]] = from;
1213 if (st->capturedType)
1218 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1220 assert(st->capturedType != KING);
1221 assert(!ep || square_is_empty(capsq));
1223 // Restore the captured piece
1224 set_bit(&(byColorBB[them]), capsq);
1225 set_bit(&(byTypeBB[st->capturedType]), capsq);
1226 set_bit(&(byTypeBB[0]), capsq);
1228 board[capsq] = piece_of_color_and_type(them, st->capturedType);
1230 // Update piece count
1231 pieceCount[them][st->capturedType]++;
1233 // Update piece list, add a new captured piece in capsq square
1234 index[capsq] = pieceCount[them][st->capturedType] - 1;
1235 pieceList[them][st->capturedType][index[capsq]] = capsq;
1238 // Finally point our state pointer back to the previous state
1245 /// Position::undo_castle_move() is a private method used to unmake a castling
1246 /// move. It is called from the main Position::undo_move function. Note that
1247 /// castling moves are encoded as "king captures friendly rook" moves, for
1248 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1250 void Position::undo_castle_move(Move m) {
1252 assert(move_is_ok(m));
1253 assert(move_is_castle(m));
1255 // When we have arrived here, some work has already been done by
1256 // Position::undo_move. In particular, the side to move has been switched,
1257 // so the code below is correct.
1258 Color us = side_to_move();
1260 // Find source squares for king and rook
1261 Square kfrom = move_from(m);
1262 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1265 // Find destination squares for king and rook
1266 if (rfrom > kfrom) // O-O
1268 kto = relative_square(us, SQ_G1);
1269 rto = relative_square(us, SQ_F1);
1271 kto = relative_square(us, SQ_C1);
1272 rto = relative_square(us, SQ_D1);
1275 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1276 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1278 // Remove pieces from destination squares:
1279 clear_bit(&(byColorBB[us]), kto);
1280 clear_bit(&(byTypeBB[KING]), kto);
1281 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1282 clear_bit(&(byColorBB[us]), rto);
1283 clear_bit(&(byTypeBB[ROOK]), rto);
1284 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1286 // Put pieces on source squares:
1287 set_bit(&(byColorBB[us]), kfrom);
1288 set_bit(&(byTypeBB[KING]), kfrom);
1289 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1290 set_bit(&(byColorBB[us]), rfrom);
1291 set_bit(&(byTypeBB[ROOK]), rfrom);
1292 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1295 board[rto] = board[kto] = PIECE_NONE;
1296 board[rfrom] = piece_of_color_and_type(us, ROOK);
1297 board[kfrom] = piece_of_color_and_type(us, KING);
1299 // Update piece lists
1300 pieceList[us][KING][index[kto]] = kfrom;
1301 pieceList[us][ROOK][index[rto]] = rfrom;
1302 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1303 index[kfrom] = index[kto];
1306 // Finally point our state pointer back to the previous state
1313 /// Position::do_null_move makes() a "null move": It switches the side to move
1314 /// and updates the hash key without executing any move on the board.
1316 void Position::do_null_move(StateInfo& backupSt) {
1319 assert(!is_check());
1321 // Back up the information necessary to undo the null move to the supplied
1322 // StateInfo object.
1323 // Note that differently from normal case here backupSt is actually used as
1324 // a backup storage not as a new state to be used.
1325 backupSt.key = st->key;
1326 backupSt.epSquare = st->epSquare;
1327 backupSt.value = st->value;
1328 backupSt.previous = st->previous;
1329 backupSt.pliesFromNull = st->pliesFromNull;
1330 st->previous = &backupSt;
1332 // Save the current key to the history[] array, in order to be able to
1333 // detect repetition draws.
1334 history[st->gamePly++] = st->key;
1336 // Update the necessary information
1337 if (st->epSquare != SQ_NONE)
1338 st->key ^= zobEp[st->epSquare];
1340 st->key ^= zobSideToMove;
1341 prefetch((char*)TT.first_entry(st->key));
1343 sideToMove = opposite_color(sideToMove);
1344 st->epSquare = SQ_NONE;
1346 st->pliesFromNull = 0;
1347 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1351 /// Position::undo_null_move() unmakes a "null move".
1353 void Position::undo_null_move() {
1356 assert(!is_check());
1358 // Restore information from the our backup StateInfo object
1359 StateInfo* backupSt = st->previous;
1360 st->key = backupSt->key;
1361 st->epSquare = backupSt->epSquare;
1362 st->value = backupSt->value;
1363 st->previous = backupSt->previous;
1364 st->pliesFromNull = backupSt->pliesFromNull;
1366 // Update the necessary information
1367 sideToMove = opposite_color(sideToMove);
1373 /// Position::see() is a static exchange evaluator: It tries to estimate the
1374 /// material gain or loss resulting from a move. There are three versions of
1375 /// this function: One which takes a destination square as input, one takes a
1376 /// move, and one which takes a 'from' and a 'to' square. The function does
1377 /// not yet understand promotions captures.
1379 int Position::see(Move m) const {
1381 assert(move_is_ok(m));
1382 return see(move_from(m), move_to(m));
1385 int Position::see_sign(Move m) const {
1387 assert(move_is_ok(m));
1389 Square from = move_from(m);
1390 Square to = move_to(m);
1392 // Early return if SEE cannot be negative because captured piece value
1393 // is not less then capturing one. Note that king moves always return
1394 // here because king midgame value is set to 0.
1395 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1398 return see(from, to);
1401 int Position::see(Square from, Square to) const {
1403 Bitboard occupied, attackers, stmAttackers, b;
1404 int swapList[32], slIndex = 1;
1405 PieceType capturedType, pt;
1408 assert(square_is_ok(from));
1409 assert(square_is_ok(to));
1411 capturedType = type_of_piece_on(to);
1413 // King cannot be recaptured
1414 if (capturedType == KING)
1415 return seeValues[capturedType];
1417 occupied = occupied_squares();
1419 // Handle en passant moves
1420 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1422 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1424 assert(capturedType == PIECE_TYPE_NONE);
1425 assert(type_of_piece_on(capQq) == PAWN);
1427 // Remove the captured pawn
1428 clear_bit(&occupied, capQq);
1429 capturedType = PAWN;
1432 // Find all attackers to the destination square, with the moving piece
1433 // removed, but possibly an X-ray attacker added behind it.
1434 clear_bit(&occupied, from);
1435 attackers = (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1436 | (bishop_attacks_bb(to, occupied)& pieces(BISHOP, QUEEN))
1437 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1438 | (attacks_from<KING>(to) & pieces(KING))
1439 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1440 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1442 // If the opponent has no attackers we are finished
1443 stm = opposite_color(color_of_piece_on(from));
1444 stmAttackers = attackers & pieces_of_color(stm);
1446 return seeValues[capturedType];
1448 // The destination square is defended, which makes things rather more
1449 // difficult to compute. We proceed by building up a "swap list" containing
1450 // the material gain or loss at each stop in a sequence of captures to the
1451 // destination square, where the sides alternately capture, and always
1452 // capture with the least valuable piece. After each capture, we look for
1453 // new X-ray attacks from behind the capturing piece.
1454 swapList[0] = seeValues[capturedType];
1455 capturedType = type_of_piece_on(from);
1458 // Locate the least valuable attacker for the side to move. The loop
1459 // below looks like it is potentially infinite, but it isn't. We know
1460 // that the side to move still has at least one attacker left.
1461 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1464 // Remove the attacker we just found from the 'occupied' bitboard,
1465 // and scan for new X-ray attacks behind the attacker.
1466 b = stmAttackers & pieces(pt);
1467 occupied ^= (b & (~b + 1));
1468 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1469 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1471 attackers &= occupied; // Cut out pieces we've already done
1473 // Add the new entry to the swap list
1474 assert(slIndex < 32);
1475 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1478 // Remember the value of the capturing piece, and change the side to
1479 // move before beginning the next iteration.
1481 stm = opposite_color(stm);
1482 stmAttackers = attackers & pieces_of_color(stm);
1484 // Stop before processing a king capture
1485 if (capturedType == KING && stmAttackers)
1487 assert(slIndex < 32);
1488 swapList[slIndex++] = QueenValueMidgame*10;
1491 } while (stmAttackers);
1493 // Having built the swap list, we negamax through it to find the best
1494 // achievable score from the point of view of the side to move.
1496 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1502 /// Position::clear() erases the position object to a pristine state, with an
1503 /// empty board, white to move, and no castling rights.
1505 void Position::clear() {
1508 memset(st, 0, sizeof(StateInfo));
1509 st->epSquare = SQ_NONE;
1510 startPosPlyCounter = 0;
1513 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1514 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1515 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1516 memset(index, 0, sizeof(int) * 64);
1518 for (int i = 0; i < 64; i++)
1519 board[i] = PIECE_NONE;
1521 for (int i = 0; i < 8; i++)
1522 for (int j = 0; j < 16; j++)
1523 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1525 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1526 castleRightsMask[sq] = ALL_CASTLES;
1529 initialKFile = FILE_E;
1530 initialKRFile = FILE_H;
1531 initialQRFile = FILE_A;
1535 /// Position::put_piece() puts a piece on the given square of the board,
1536 /// updating the board array, pieces list, bitboards, and piece counts.
1538 void Position::put_piece(Piece p, Square s) {
1540 Color c = color_of_piece(p);
1541 PieceType pt = type_of_piece(p);
1544 index[s] = pieceCount[c][pt]++;
1545 pieceList[c][pt][index[s]] = s;
1547 set_bit(&(byTypeBB[pt]), s);
1548 set_bit(&(byColorBB[c]), s);
1549 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1553 /// Position::compute_key() computes the hash key of the position. The hash
1554 /// key is usually updated incrementally as moves are made and unmade, the
1555 /// compute_key() function is only used when a new position is set up, and
1556 /// to verify the correctness of the hash key when running in debug mode.
1558 Key Position::compute_key() const {
1560 Key result = zobCastle[st->castleRights];
1562 for (Square s = SQ_A1; s <= SQ_H8; s++)
1563 if (square_is_occupied(s))
1564 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1566 if (ep_square() != SQ_NONE)
1567 result ^= zobEp[ep_square()];
1569 if (side_to_move() == BLACK)
1570 result ^= zobSideToMove;
1576 /// Position::compute_pawn_key() computes the hash key of the position. The
1577 /// hash key is usually updated incrementally as moves are made and unmade,
1578 /// the compute_pawn_key() function is only used when a new position is set
1579 /// up, and to verify the correctness of the pawn hash key when running in
1582 Key Position::compute_pawn_key() const {
1587 for (Color c = WHITE; c <= BLACK; c++)
1589 b = pieces(PAWN, c);
1591 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1597 /// Position::compute_material_key() computes the hash key of the position.
1598 /// The hash key is usually updated incrementally as moves are made and unmade,
1599 /// the compute_material_key() function is only used when a new position is set
1600 /// up, and to verify the correctness of the material hash key when running in
1603 Key Position::compute_material_key() const {
1608 for (Color c = WHITE; c <= BLACK; c++)
1609 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1611 count = piece_count(c, pt);
1612 for (int i = 0; i < count; i++)
1613 result ^= zobrist[c][pt][i];
1619 /// Position::compute_value() compute the incremental scores for the middle
1620 /// game and the endgame. These functions are used to initialize the incremental
1621 /// scores when a new position is set up, and to verify that the scores are correctly
1622 /// updated by do_move and undo_move when the program is running in debug mode.
1623 Score Position::compute_value() const {
1626 Score result = SCORE_ZERO;
1628 for (Color c = WHITE; c <= BLACK; c++)
1629 for (PieceType pt = PAWN; pt <= KING; pt++)
1633 result += pst(c, pt, pop_1st_bit(&b));
1636 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1641 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1642 /// game material value for the given side. Material values are updated
1643 /// incrementally during the search, this function is only used while
1644 /// initializing a new Position object.
1646 Value Position::compute_non_pawn_material(Color c) const {
1648 Value result = VALUE_ZERO;
1650 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1651 result += piece_count(c, pt) * PieceValueMidgame[pt];
1657 /// Position::is_draw() tests whether the position is drawn by material,
1658 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1659 /// must be done by the search.
1661 bool Position::is_draw() const {
1663 // Draw by material?
1665 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1668 // Draw by the 50 moves rule?
1669 if (st->rule50 > 99 && !is_mate())
1672 // Draw by repetition?
1673 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1674 if (history[st->gamePly - i] == st->key)
1681 /// Position::is_mate() returns true or false depending on whether the
1682 /// side to move is checkmated.
1684 bool Position::is_mate() const {
1686 MoveStack moves[MOVES_MAX];
1687 return is_check() && generate<MV_LEGAL>(*this, moves) == moves;
1691 /// Position::has_mate_threat() tests whether the side to move is under
1692 /// a threat of being mated in one from the current position.
1694 bool Position::has_mate_threat() {
1696 MoveStack mlist[MOVES_MAX], *last, *cur;
1698 bool mateFound = false;
1700 // If we are under check it's up to evasions to do the job
1704 // First pass the move to our opponent doing a null move
1707 // Then generate pseudo-legal moves that could give check
1708 last = generate<MV_NON_CAPTURE_CHECK>(*this, mlist);
1709 last = generate<MV_CAPTURE>(*this, last);
1711 // Loop through the moves, and see if one of them gives mate
1712 Bitboard pinned = pinned_pieces(sideToMove);
1713 CheckInfo ci(*this);
1714 for (cur = mlist; cur != last && !mateFound; cur++)
1716 Move move = cur->move;
1717 if ( !pl_move_is_legal(move, pinned)
1718 || !move_is_check(move, ci))
1721 do_move(move, st2, ci, true);
1734 /// Position::init_zobrist() is a static member function which initializes at
1735 /// startup the various arrays used to compute hash keys.
1737 void Position::init_zobrist() {
1742 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1743 zobrist[i][j][k] = rk.rand<Key>();
1745 for (i = 0; i < 64; i++)
1746 zobEp[i] = rk.rand<Key>();
1748 for (i = 0; i < 16; i++)
1749 zobCastle[i] = rk.rand<Key>();
1751 zobSideToMove = rk.rand<Key>();
1752 zobExclusion = rk.rand<Key>();
1756 /// Position::init_piece_square_tables() initializes the piece square tables.
1757 /// This is a two-step operation: First, the white halves of the tables are
1758 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1759 /// of the tables are initialized by mirroring and changing the sign of the
1760 /// corresponding white scores.
1762 void Position::init_piece_square_tables() {
1764 for (Square s = SQ_A1; s <= SQ_H8; s++)
1765 for (Piece p = WP; p <= WK; p++)
1766 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1768 for (Square s = SQ_A1; s <= SQ_H8; s++)
1769 for (Piece p = BP; p <= BK; p++)
1770 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1774 /// Position::flipped_copy() makes a copy of the input position, but with
1775 /// the white and black sides reversed. This is only useful for debugging,
1776 /// especially for finding evaluation symmetry bugs.
1778 void Position::flipped_copy(const Position& pos) {
1780 assert(pos.is_ok());
1783 threadID = pos.thread();
1786 for (Square s = SQ_A1; s <= SQ_H8; s++)
1787 if (!pos.square_is_empty(s))
1788 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1791 sideToMove = opposite_color(pos.side_to_move());
1794 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1795 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1796 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1797 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1799 initialKFile = pos.initialKFile;
1800 initialKRFile = pos.initialKRFile;
1801 initialQRFile = pos.initialQRFile;
1803 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1804 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1805 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1806 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1807 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1808 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1810 // En passant square
1811 if (pos.st->epSquare != SQ_NONE)
1812 st->epSquare = flip_square(pos.st->epSquare);
1818 st->key = compute_key();
1819 st->pawnKey = compute_pawn_key();
1820 st->materialKey = compute_material_key();
1822 // Incremental scores
1823 st->value = compute_value();
1826 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1827 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1833 /// Position::is_ok() performs some consitency checks for the position object.
1834 /// This is meant to be helpful when debugging.
1836 bool Position::is_ok(int* failedStep) const {
1838 // What features of the position should be verified?
1839 const bool debugAll = false;
1841 const bool debugBitboards = debugAll || false;
1842 const bool debugKingCount = debugAll || false;
1843 const bool debugKingCapture = debugAll || false;
1844 const bool debugCheckerCount = debugAll || false;
1845 const bool debugKey = debugAll || false;
1846 const bool debugMaterialKey = debugAll || false;
1847 const bool debugPawnKey = debugAll || false;
1848 const bool debugIncrementalEval = debugAll || false;
1849 const bool debugNonPawnMaterial = debugAll || false;
1850 const bool debugPieceCounts = debugAll || false;
1851 const bool debugPieceList = debugAll || false;
1852 const bool debugCastleSquares = debugAll || false;
1854 if (failedStep) *failedStep = 1;
1857 if (!color_is_ok(side_to_move()))
1860 // Are the king squares in the position correct?
1861 if (failedStep) (*failedStep)++;
1862 if (piece_on(king_square(WHITE)) != WK)
1865 if (failedStep) (*failedStep)++;
1866 if (piece_on(king_square(BLACK)) != BK)
1870 if (failedStep) (*failedStep)++;
1871 if (!file_is_ok(initialKRFile))
1874 if (!file_is_ok(initialQRFile))
1877 // Do both sides have exactly one king?
1878 if (failedStep) (*failedStep)++;
1881 int kingCount[2] = {0, 0};
1882 for (Square s = SQ_A1; s <= SQ_H8; s++)
1883 if (type_of_piece_on(s) == KING)
1884 kingCount[color_of_piece_on(s)]++;
1886 if (kingCount[0] != 1 || kingCount[1] != 1)
1890 // Can the side to move capture the opponent's king?
1891 if (failedStep) (*failedStep)++;
1892 if (debugKingCapture)
1894 Color us = side_to_move();
1895 Color them = opposite_color(us);
1896 Square ksq = king_square(them);
1897 if (attackers_to(ksq) & pieces_of_color(us))
1901 // Is there more than 2 checkers?
1902 if (failedStep) (*failedStep)++;
1903 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1907 if (failedStep) (*failedStep)++;
1910 // The intersection of the white and black pieces must be empty
1911 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1914 // The union of the white and black pieces must be equal to all
1916 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1919 // Separate piece type bitboards must have empty intersections
1920 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1921 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1922 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1926 // En passant square OK?
1927 if (failedStep) (*failedStep)++;
1928 if (ep_square() != SQ_NONE)
1930 // The en passant square must be on rank 6, from the point of view of the
1932 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1937 if (failedStep) (*failedStep)++;
1938 if (debugKey && st->key != compute_key())
1941 // Pawn hash key OK?
1942 if (failedStep) (*failedStep)++;
1943 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1946 // Material hash key OK?
1947 if (failedStep) (*failedStep)++;
1948 if (debugMaterialKey && st->materialKey != compute_material_key())
1951 // Incremental eval OK?
1952 if (failedStep) (*failedStep)++;
1953 if (debugIncrementalEval && st->value != compute_value())
1956 // Non-pawn material OK?
1957 if (failedStep) (*failedStep)++;
1958 if (debugNonPawnMaterial)
1960 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1963 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1968 if (failedStep) (*failedStep)++;
1969 if (debugPieceCounts)
1970 for (Color c = WHITE; c <= BLACK; c++)
1971 for (PieceType pt = PAWN; pt <= KING; pt++)
1972 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1975 if (failedStep) (*failedStep)++;
1978 for (Color c = WHITE; c <= BLACK; c++)
1979 for (PieceType pt = PAWN; pt <= KING; pt++)
1980 for (int i = 0; i < pieceCount[c][pt]; i++)
1982 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
1985 if (index[piece_list(c, pt, i)] != i)
1990 if (failedStep) (*failedStep)++;
1991 if (debugCastleSquares) {
1992 for (Color c = WHITE; c <= BLACK; c++) {
1993 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
1995 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
1998 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2000 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2002 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2004 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2008 if (failedStep) *failedStep = 0;