2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
33 #include "ucioption.h"
39 Key Position::zobrist[2][8][64];
40 Key Position::zobEp[64];
41 Key Position::zobCastle[16];
42 Key Position::zobSideToMove;
43 Key Position::zobExclusion;
45 Score Position::pieceSquareTable[16][64];
47 // Material values arrays, indexed by Piece
48 const Value PieceValueMidgame[17] = {
50 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
51 RookValueMidgame, QueenValueMidgame,
52 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
53 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
54 RookValueMidgame, QueenValueMidgame
57 const Value PieceValueEndgame[17] = {
59 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
60 RookValueEndgame, QueenValueEndgame,
61 VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
62 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
63 RookValueEndgame, QueenValueEndgame
69 // Bonus for having the side to move (modified by Joona Kiiski)
70 const Score TempoValue = make_score(48, 22);
72 // To convert a Piece to and from a FEN char
73 const string PieceToChar(".PNBRQK pnbrqk ");
79 CheckInfo::CheckInfo(const Position& pos) {
81 Color them = opposite_color(pos.side_to_move());
82 Square ksq = pos.king_square(them);
84 pinned = pos.pinned_pieces();
85 dcCandidates = pos.discovered_check_candidates();
87 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
88 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
89 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
90 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
91 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
92 checkSq[KING] = EmptyBoardBB;
96 /// Position c'tors. Here we always create a copy of the original position
97 /// or the FEN string, we want the new born Position object do not depend
98 /// on any external data so we detach state pointer from the source one.
100 Position::Position(const Position& pos, int th) {
102 memcpy(this, &pos, sizeof(Position));
103 detach(); // Always detach() in copy c'tor to avoid surprises
110 Position::Position(const string& fen, bool isChess960, int th) {
112 from_fen(fen, isChess960);
117 /// Position::detach() copies the content of the current state and castling
118 /// masks inside the position itself. This is needed when the st pointee could
119 /// become stale, as example because the caller is about to going out of scope.
121 void Position::detach() {
125 st->previous = NULL; // As a safe guard
129 /// Position::from_fen() initializes the position object with the given FEN
130 /// string. This function is not very robust - make sure that input FENs are
131 /// correct (this is assumed to be the responsibility of the GUI).
133 void Position::from_fen(const string& fenStr, bool isChess960) {
135 A FEN string defines a particular position using only the ASCII character set.
137 A FEN string contains six fields. The separator between fields is a space. The fields are:
139 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
140 with rank 1; within each rank, the contents of each square are described from file A through file H.
141 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
142 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
143 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
144 of blank squares), and "/" separate ranks.
146 2) Active color. "w" means white moves next, "b" means black.
148 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
149 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
150 kingside), and/or "q" (Black can castle queenside).
152 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
153 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
154 regardless of whether there is a pawn in position to make an en passant capture.
156 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
157 to determine if a draw can be claimed under the fifty-move rule.
159 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
162 char col, row, token;
165 std::istringstream fen(fenStr);
168 fen >> std::noskipws;
170 // 1. Piece placement
171 while ((fen >> token) && !isspace(token))
174 sq -= Square(16); // Jump back of 2 rows
176 else if (isdigit(token))
177 sq += Square(token - '0'); // Skip the given number of files
179 else if ((p = PieceToChar.find(token)) != string::npos)
181 put_piece(Piece(p), sq);
188 sideToMove = (token == 'w' ? WHITE : BLACK);
191 // 3. Castling availability
192 while ((fen >> token) && !isspace(token))
193 set_castling_rights(token);
195 // 4. En passant square. Ignore if no pawn capture is possible
196 if ( ((fen >> col) && (col >= 'a' && col <= 'h'))
197 && ((fen >> row) && (row == '3' || row == '6')))
199 st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
200 Color them = opposite_color(sideToMove);
202 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
203 st->epSquare = SQ_NONE;
206 // 5-6. Halfmove clock and fullmove number
207 fen >> std::skipws >> st->rule50 >> fullMoves;
209 // Various initialisations
210 chess960 = isChess960;
211 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(opposite_color(sideToMove));
213 st->key = compute_key();
214 st->pawnKey = compute_pawn_key();
215 st->materialKey = compute_material_key();
216 st->value = compute_value();
217 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
218 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
224 /// Position::set_castle() is an helper function used to set
225 /// correct castling related flags.
227 void Position::set_castle(int f, Square ksq, Square rsq) {
229 st->castleRights |= f;
230 castleRightsMask[ksq] ^= f;
231 castleRightsMask[rsq] ^= f;
232 castleRookSquare[f] = rsq;
236 /// Position::set_castling_rights() sets castling parameters castling avaiability.
237 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
238 /// that uses the letters of the columns on which the rooks began the game instead
239 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
240 /// associated with the castling right, the traditional castling tag will be replaced
241 /// by the file letter of the involved rook as for the Shredder-FEN.
243 void Position::set_castling_rights(char token) {
245 Color c = islower(token) ? BLACK : WHITE;
247 Square sqA = relative_square(c, SQ_A1);
248 Square sqH = relative_square(c, SQ_H1);
249 Square rsq, ksq = king_square(c);
251 token = char(toupper(token));
254 for (rsq = sqH; piece_on(rsq) != make_piece(c, ROOK); rsq--) {}
256 else if (token == 'Q')
257 for (rsq = sqA; piece_on(rsq) != make_piece(c, ROOK); rsq++) {}
259 else if (token >= 'A' && token <= 'H')
260 rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
264 if (square_file(rsq) < square_file(ksq))
265 set_castle(WHITE_OOO << c, ksq, rsq);
267 set_castle(WHITE_OO << c, ksq, rsq);
271 /// Position::to_fen() returns a FEN representation of the position. In case
272 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
274 const string Position::to_fen() const {
276 std::ostringstream fen;
280 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
284 for (File file = FILE_A; file <= FILE_H; file++)
286 sq = make_square(file, rank);
288 if (!square_is_empty(sq))
295 fen << PieceToChar[piece_on(sq)];
308 fen << (sideToMove == WHITE ? " w " : " b ");
310 if (st->castleRights != CASTLES_NONE)
312 if (can_castle(WHITE_OO))
313 fen << (chess960 ? char(toupper(file_to_char(square_file(castle_rook_square(WHITE_OO))))) : 'K');
315 if (can_castle(WHITE_OOO))
316 fen << (chess960 ? char(toupper(file_to_char(square_file(castle_rook_square(WHITE_OOO))))) : 'Q');
318 if (can_castle(BLACK_OO))
319 fen << (chess960 ? file_to_char(square_file(castle_rook_square(BLACK_OO))) : 'k');
321 if (can_castle(BLACK_OOO))
322 fen << (chess960 ? file_to_char(square_file(castle_rook_square(BLACK_OOO))) : 'q');
326 fen << (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()))
327 << " " << st->rule50 << " " << fullMoves;
333 /// Position::print() prints an ASCII representation of the position to
334 /// the standard output. If a move is given then also the san is printed.
336 void Position::print(Move move) const {
338 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
342 Position p(*this, thread());
343 string dd = (sideToMove == BLACK ? ".." : "");
344 cout << "\nMove is: " << dd << move_to_san(p, move);
347 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
349 cout << dottedLine << '|';
350 for (File file = FILE_A; file <= FILE_H; file++)
352 Square sq = make_square(file, rank);
353 Piece piece = piece_on(sq);
355 if (piece == PIECE_NONE && square_color(sq) == DARK)
356 piece = PIECE_NONE_DARK_SQ;
358 char c = (piece_color(piece_on(sq)) == BLACK ? '=' : ' ');
359 cout << c << PieceToChar[piece] << c << '|';
362 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
366 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
367 /// king) pieces for the given color. Or, when template parameter FindPinned is
368 /// false, the function return the pieces of the given color candidate for a
369 /// discovery check against the enemy king.
371 template<bool FindPinned>
372 Bitboard Position::hidden_checkers() const {
374 // Pinned pieces protect our king, dicovery checks attack the enemy king
375 Bitboard b, result = EmptyBoardBB;
376 Bitboard pinners = pieces(FindPinned ? opposite_color(sideToMove) : sideToMove);
377 Square ksq = king_square(FindPinned ? sideToMove : opposite_color(sideToMove));
379 // Pinners are sliders, that give check when candidate pinned is removed
380 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq])
381 | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
385 b = squares_between(ksq, pop_1st_bit(&pinners)) & occupied_squares();
387 // Only one bit set and is an our piece?
388 if (b && !(b & (b - 1)) && (b & pieces(sideToMove)))
395 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
396 /// king) pieces for the side to move.
398 Bitboard Position::pinned_pieces() const {
400 return hidden_checkers<true>();
404 /// Position:discovered_check_candidates() returns a bitboard containing all
405 /// pieces for the side to move which are candidates for giving a discovered
408 Bitboard Position::discovered_check_candidates() const {
410 return hidden_checkers<false>();
413 /// Position::attackers_to() computes a bitboard containing all pieces which
414 /// attacks a given square.
416 Bitboard Position::attackers_to(Square s) const {
418 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
419 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
420 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
421 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
422 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
423 | (attacks_from<KING>(s) & pieces(KING));
426 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
428 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
429 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
430 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
431 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
432 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
433 | (attacks_from<KING>(s) & pieces(KING));
436 /// Position::attacks_from() computes a bitboard of all attacks
437 /// of a given piece put in a given square.
439 Bitboard Position::attacks_from(Piece p, Square s) const {
441 assert(square_is_ok(s));
445 case WB: case BB: return attacks_from<BISHOP>(s);
446 case WR: case BR: return attacks_from<ROOK>(s);
447 case WQ: case BQ: return attacks_from<QUEEN>(s);
448 default: return StepAttacksBB[p][s];
452 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
454 assert(square_is_ok(s));
458 case WB: case BB: return bishop_attacks_bb(s, occ);
459 case WR: case BR: return rook_attacks_bb(s, occ);
460 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
461 default: return StepAttacksBB[p][s];
466 /// Position::move_attacks_square() tests whether a move from the current
467 /// position attacks a given square.
469 bool Position::move_attacks_square(Move m, Square s) const {
471 assert(move_is_ok(m));
472 assert(square_is_ok(s));
475 Square f = move_from(m), t = move_to(m);
477 assert(!square_is_empty(f));
479 if (bit_is_set(attacks_from(piece_on(f), t), s))
482 // Move the piece and scan for X-ray attacks behind it
483 occ = occupied_squares();
484 do_move_bb(&occ, make_move_bb(f, t));
485 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
486 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
487 & pieces(piece_color(piece_on(f)));
489 // If we have attacks we need to verify that are caused by our move
490 // and are not already existent ones.
491 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
495 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
497 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
499 assert(move_is_ok(m));
500 assert(pinned == pinned_pieces());
502 Color us = side_to_move();
503 Square from = move_from(m);
505 assert(piece_color(piece_on(from)) == us);
506 assert(piece_on(king_square(us)) == make_piece(us, KING));
508 // En passant captures are a tricky special case. Because they are rather
509 // uncommon, we do it simply by testing whether the king is attacked after
513 Color them = opposite_color(us);
514 Square to = move_to(m);
515 Square capsq = to + pawn_push(them);
516 Square ksq = king_square(us);
517 Bitboard b = occupied_squares();
519 assert(to == ep_square());
520 assert(piece_on(from) == make_piece(us, PAWN));
521 assert(piece_on(capsq) == make_piece(them, PAWN));
522 assert(piece_on(to) == PIECE_NONE);
525 clear_bit(&b, capsq);
528 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
529 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
532 // If the moving piece is a king, check whether the destination
533 // square is attacked by the opponent. Castling moves are checked
534 // for legality during move generation.
535 if (piece_type(piece_on(from)) == KING)
536 return move_is_castle(m) || !(attackers_to(move_to(m)) & pieces(opposite_color(us)));
538 // A non-king move is legal if and only if it is not pinned or it
539 // is moving along the ray towards or away from the king.
541 || !bit_is_set(pinned, from)
542 || squares_aligned(from, move_to(m), king_square(us));
546 /// Position::move_is_legal() takes a move and tests whether the move
547 /// is legal. This version is not very fast and should be used only
548 /// in non time-critical paths.
550 bool Position::move_is_legal(const Move m) const {
552 for (MoveList<MV_LEGAL> ml(*this); !ml.end(); ++ml)
560 /// Fast version of Position::move_is_pl() that takes a move and a bitboard
561 /// of pinned pieces as input, and tests whether the move is pseudo legal.
563 bool Position::move_is_pl(const Move m) const {
565 Color us = sideToMove;
566 Color them = opposite_color(sideToMove);
567 Square from = move_from(m);
568 Square to = move_to(m);
569 Piece pc = piece_on(from);
571 // Use a slower but simpler function for uncommon cases
572 if (move_is_special(m))
573 return move_is_legal(m);
575 // Is not a promotion, so promotion piece must be empty
576 if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
579 // If the from square is not occupied by a piece belonging to the side to
580 // move, the move is obviously not legal.
581 if (pc == PIECE_NONE || piece_color(pc) != us)
584 // The destination square cannot be occupied by a friendly piece
585 if (piece_color(piece_on(to)) == us)
588 // Handle the special case of a pawn move
589 if (piece_type(pc) == PAWN)
591 // Move direction must be compatible with pawn color
592 int direction = to - from;
593 if ((us == WHITE) != (direction > 0))
596 // We have already handled promotion moves, so destination
597 // cannot be on the 8/1th rank.
598 if (square_rank(to) == RANK_8 || square_rank(to) == RANK_1)
601 // Proceed according to the square delta between the origin and
602 // destination squares.
609 // Capture. The destination square must be occupied by an enemy
610 // piece (en passant captures was handled earlier).
611 if (piece_color(piece_on(to)) != them)
614 // From and to files must be one file apart, avoids a7h5
615 if (abs(square_file(from) - square_file(to)) != 1)
621 // Pawn push. The destination square must be empty.
622 if (!square_is_empty(to))
627 // Double white pawn push. The destination square must be on the fourth
628 // rank, and both the destination square and the square between the
629 // source and destination squares must be empty.
630 if ( square_rank(to) != RANK_4
631 || !square_is_empty(to)
632 || !square_is_empty(from + DELTA_N))
637 // Double black pawn push. The destination square must be on the fifth
638 // rank, and both the destination square and the square between the
639 // source and destination squares must be empty.
640 if ( square_rank(to) != RANK_5
641 || !square_is_empty(to)
642 || !square_is_empty(from + DELTA_S))
650 else if (!bit_is_set(attacks_from(pc, from), to))
655 // In case of king moves under check we have to remove king so to catch
656 // as invalid moves like b1a1 when opposite queen is on c1.
657 if (piece_type(piece_on(from)) == KING)
659 Bitboard b = occupied_squares();
661 if (attackers_to(move_to(m), b) & pieces(opposite_color(us)))
666 Bitboard target = checkers();
667 Square checksq = pop_1st_bit(&target);
669 if (target) // double check ? In this case a king move is required
672 // Our move must be a blocking evasion or a capture of the checking piece
673 target = squares_between(checksq, king_square(us)) | checkers();
674 if (!bit_is_set(target, move_to(m)))
683 /// Position::move_gives_check() tests whether a pseudo-legal move is a check
685 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
687 assert(move_is_ok(m));
688 assert(ci.dcCandidates == discovered_check_candidates());
689 assert(piece_color(piece_on(move_from(m))) == side_to_move());
691 Square from = move_from(m);
692 Square to = move_to(m);
693 PieceType pt = piece_type(piece_on(from));
696 if (bit_is_set(ci.checkSq[pt], to))
700 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
702 // For pawn and king moves we need to verify also direction
703 if ( (pt != PAWN && pt != KING)
704 || !squares_aligned(from, to, king_square(opposite_color(side_to_move()))))
708 // Can we skip the ugly special cases ?
709 if (!move_is_special(m))
712 Color us = side_to_move();
713 Bitboard b = occupied_squares();
714 Square ksq = king_square(opposite_color(us));
716 // Promotion with check ?
717 if (move_is_promotion(m))
721 switch (promotion_piece_type(m))
724 return bit_is_set(attacks_from<KNIGHT>(to), ksq);
726 return bit_is_set(bishop_attacks_bb(to, b), ksq);
728 return bit_is_set(rook_attacks_bb(to, b), ksq);
730 return bit_is_set(queen_attacks_bb(to, b), ksq);
736 // En passant capture with check ? We have already handled the case
737 // of direct checks and ordinary discovered check, the only case we
738 // need to handle is the unusual case of a discovered check through
739 // the captured pawn.
742 Square capsq = make_square(square_file(to), square_rank(from));
744 clear_bit(&b, capsq);
746 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
747 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
750 // Castling with check ?
751 if (move_is_castle(m))
753 Square kfrom, kto, rfrom, rto;
759 kto = relative_square(us, SQ_G1);
760 rto = relative_square(us, SQ_F1);
762 kto = relative_square(us, SQ_C1);
763 rto = relative_square(us, SQ_D1);
765 clear_bit(&b, kfrom);
766 clear_bit(&b, rfrom);
769 return bit_is_set(rook_attacks_bb(rto, b), ksq);
776 /// Position::do_setup_move() makes a permanent move on the board. It should
777 /// be used when setting up a position on board. You can't undo the move.
779 void Position::do_setup_move(Move m) {
783 // Update the number of full moves after black's move
784 if (sideToMove == BLACK)
789 // Reset "game ply" in case we made a non-reversible move.
790 // "game ply" is used for repetition detection.
794 // Our StateInfo newSt is about going out of scope so copy
795 // its content before it disappears.
802 /// Position::do_move() makes a move, and saves all information necessary
803 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
804 /// moves should be filtered out before this function is called.
806 void Position::do_move(Move m, StateInfo& newSt) {
809 do_move(m, newSt, ci, move_gives_check(m, ci));
812 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
814 assert(move_is_ok(m));
815 assert(&newSt != st);
820 // Copy some fields of old state to our new StateInfo object except the
821 // ones which are recalculated from scratch anyway, then switch our state
822 // pointer to point to the new, ready to be updated, state.
823 struct ReducedStateInfo {
824 Key pawnKey, materialKey;
825 int castleRights, rule50, gamePly, pliesFromNull;
831 memcpy(&newSt, st, sizeof(ReducedStateInfo));
836 // Save the current key to the history[] array, in order to be able to
837 // detect repetition draws.
838 history[st->gamePly++] = key;
840 // Update side to move
841 key ^= zobSideToMove;
843 // Increment the 50 moves rule draw counter. Resetting it to zero in the
844 // case of non-reversible moves is taken care of later.
848 if (move_is_castle(m))
855 Color us = side_to_move();
856 Color them = opposite_color(us);
857 Square from = move_from(m);
858 Square to = move_to(m);
859 bool ep = move_is_ep(m);
860 bool pm = move_is_promotion(m);
862 Piece piece = piece_on(from);
863 PieceType pt = piece_type(piece);
864 PieceType capture = ep ? PAWN : piece_type(piece_on(to));
866 assert(piece_color(piece_on(from)) == us);
867 assert(piece_color(piece_on(to)) == them || square_is_empty(to));
868 assert(!(ep || pm) || piece == make_piece(us, PAWN));
869 assert(!pm || relative_rank(us, to) == RANK_8);
872 do_capture_move(key, capture, them, to, ep);
875 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
877 // Reset en passant square
878 if (st->epSquare != SQ_NONE)
880 key ^= zobEp[st->epSquare];
881 st->epSquare = SQ_NONE;
884 // Update castle rights if needed
885 if ( st->castleRights != CASTLES_NONE
886 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
888 key ^= zobCastle[st->castleRights];
889 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
890 key ^= zobCastle[st->castleRights];
893 // Prefetch TT access as soon as we know key is updated
894 prefetch((char*)TT.first_entry(key));
897 Bitboard move_bb = make_move_bb(from, to);
898 do_move_bb(&byColorBB[us], move_bb);
899 do_move_bb(&byTypeBB[pt], move_bb);
900 do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
902 board[to] = board[from];
903 board[from] = PIECE_NONE;
905 // Update piece lists, note that index[from] is not updated and
906 // becomes stale. This works as long as index[] is accessed just
907 // by known occupied squares.
908 index[to] = index[from];
909 pieceList[us][pt][index[to]] = to;
911 // If the moving piece was a pawn do some special extra work
914 // Reset rule 50 draw counter
917 // Update pawn hash key and prefetch in L1/L2 cache
918 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
920 // Set en passant square, only if moved pawn can be captured
921 if ((to ^ from) == 16)
923 if (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(PAWN, them))
925 st->epSquare = Square((int(from) + int(to)) / 2);
926 key ^= zobEp[st->epSquare];
930 if (pm) // promotion ?
932 PieceType promotion = promotion_piece_type(m);
934 assert(promotion >= KNIGHT && promotion <= QUEEN);
936 // Insert promoted piece instead of pawn
937 clear_bit(&byTypeBB[PAWN], to);
938 set_bit(&byTypeBB[promotion], to);
939 board[to] = make_piece(us, promotion);
941 // Update piece counts
942 pieceCount[us][promotion]++;
943 pieceCount[us][PAWN]--;
945 // Update material key
946 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
947 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
949 // Update piece lists, move the last pawn at index[to] position
950 // and shrink the list. Add a new promotion piece to the list.
951 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
952 index[lastPawnSquare] = index[to];
953 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
954 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
955 index[to] = pieceCount[us][promotion] - 1;
956 pieceList[us][promotion][index[to]] = to;
958 // Partially revert hash keys update
959 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
960 st->pawnKey ^= zobrist[us][PAWN][to];
962 // Partially revert and update incremental scores
963 st->value -= pst(make_piece(us, PAWN), to);
964 st->value += pst(make_piece(us, promotion), to);
967 st->npMaterial[us] += PieceValueMidgame[promotion];
971 // Prefetch pawn and material hash tables
972 Threads[threadID].pawnTable.prefetch(st->pawnKey);
973 Threads[threadID].materialTable.prefetch(st->materialKey);
975 // Update incremental scores
976 st->value += pst_delta(piece, from, to);
979 st->capturedType = capture;
981 // Update the key with the final value
984 // Update checkers bitboard, piece must be already moved
985 st->checkersBB = EmptyBoardBB;
990 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
994 if (bit_is_set(ci.checkSq[pt], to))
995 st->checkersBB = SetMaskBB[to];
998 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1001 st->checkersBB |= (attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us));
1004 st->checkersBB |= (attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us));
1010 sideToMove = opposite_color(sideToMove);
1011 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1017 /// Position::do_capture_move() is a private method used to update captured
1018 /// piece info. It is called from the main Position::do_move function.
1020 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1022 assert(capture != KING);
1026 // If the captured piece was a pawn, update pawn hash key,
1027 // otherwise update non-pawn material.
1028 if (capture == PAWN)
1030 if (ep) // en passant ?
1032 capsq = to + pawn_push(them);
1034 assert(to == st->epSquare);
1035 assert(relative_rank(opposite_color(them), to) == RANK_6);
1036 assert(piece_on(to) == PIECE_NONE);
1037 assert(piece_on(capsq) == make_piece(them, PAWN));
1039 board[capsq] = PIECE_NONE;
1041 st->pawnKey ^= zobrist[them][PAWN][capsq];
1044 st->npMaterial[them] -= PieceValueMidgame[capture];
1046 // Remove captured piece
1047 clear_bit(&byColorBB[them], capsq);
1048 clear_bit(&byTypeBB[capture], capsq);
1049 clear_bit(&byTypeBB[0], capsq);
1052 key ^= zobrist[them][capture][capsq];
1054 // Update incremental scores
1055 st->value -= pst(make_piece(them, capture), capsq);
1057 // Update piece count
1058 pieceCount[them][capture]--;
1060 // Update material hash key
1061 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1063 // Update piece list, move the last piece at index[capsq] position
1065 // WARNING: This is a not perfectly revresible operation. When we
1066 // will reinsert the captured piece in undo_move() we will put it
1067 // at the end of the list and not in its original place, it means
1068 // index[] and pieceList[] are not guaranteed to be invariant to a
1069 // do_move() + undo_move() sequence.
1070 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1071 index[lastPieceSquare] = index[capsq];
1072 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1073 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1075 // Reset rule 50 counter
1080 /// Position::do_castle_move() is a private method used to make a castling
1081 /// move. It is called from the main Position::do_move function. Note that
1082 /// castling moves are encoded as "king captures friendly rook" moves, for
1083 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1085 void Position::do_castle_move(Move m) {
1087 assert(move_is_ok(m));
1088 assert(move_is_castle(m));
1090 Color us = side_to_move();
1091 Color them = opposite_color(us);
1093 // Find source squares for king and rook
1094 Square kfrom = move_from(m);
1095 Square rfrom = move_to(m);
1098 assert(piece_on(kfrom) == make_piece(us, KING));
1099 assert(piece_on(rfrom) == make_piece(us, ROOK));
1101 // Find destination squares for king and rook
1102 if (rfrom > kfrom) // O-O
1104 kto = relative_square(us, SQ_G1);
1105 rto = relative_square(us, SQ_F1);
1109 kto = relative_square(us, SQ_C1);
1110 rto = relative_square(us, SQ_D1);
1113 // Remove pieces from source squares
1114 clear_bit(&byColorBB[us], kfrom);
1115 clear_bit(&byTypeBB[KING], kfrom);
1116 clear_bit(&byTypeBB[0], kfrom);
1117 clear_bit(&byColorBB[us], rfrom);
1118 clear_bit(&byTypeBB[ROOK], rfrom);
1119 clear_bit(&byTypeBB[0], rfrom);
1121 // Put pieces on destination squares
1122 set_bit(&byColorBB[us], kto);
1123 set_bit(&byTypeBB[KING], kto);
1124 set_bit(&byTypeBB[0], kto);
1125 set_bit(&byColorBB[us], rto);
1126 set_bit(&byTypeBB[ROOK], rto);
1127 set_bit(&byTypeBB[0], rto);
1130 Piece king = make_piece(us, KING);
1131 Piece rook = make_piece(us, ROOK);
1132 board[kfrom] = board[rfrom] = PIECE_NONE;
1136 // Update piece lists
1137 pieceList[us][KING][index[kfrom]] = kto;
1138 pieceList[us][ROOK][index[rfrom]] = rto;
1139 int tmp = index[rfrom]; // In Chess960 could be kto == rfrom
1140 index[kto] = index[kfrom];
1143 // Reset capture field
1144 st->capturedType = PIECE_TYPE_NONE;
1146 // Update incremental scores
1147 st->value += pst_delta(king, kfrom, kto);
1148 st->value += pst_delta(rook, rfrom, rto);
1151 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1152 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1154 // Clear en passant square
1155 if (st->epSquare != SQ_NONE)
1157 st->key ^= zobEp[st->epSquare];
1158 st->epSquare = SQ_NONE;
1161 // Update castling rights
1162 st->key ^= zobCastle[st->castleRights];
1163 st->castleRights &= castleRightsMask[kfrom];
1164 st->key ^= zobCastle[st->castleRights];
1166 // Reset rule 50 counter
1169 // Update checkers BB
1170 st->checkersBB = attackers_to(king_square(them)) & pieces(us);
1173 sideToMove = opposite_color(sideToMove);
1174 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1180 /// Position::undo_move() unmakes a move. When it returns, the position should
1181 /// be restored to exactly the same state as before the move was made.
1183 void Position::undo_move(Move m) {
1185 assert(move_is_ok(m));
1187 sideToMove = opposite_color(sideToMove);
1189 if (move_is_castle(m))
1191 undo_castle_move(m);
1195 Color us = side_to_move();
1196 Color them = opposite_color(us);
1197 Square from = move_from(m);
1198 Square to = move_to(m);
1199 bool ep = move_is_ep(m);
1200 bool pm = move_is_promotion(m);
1202 PieceType pt = piece_type(piece_on(to));
1204 assert(square_is_empty(from));
1205 assert(piece_color(piece_on(to)) == us);
1206 assert(!pm || relative_rank(us, to) == RANK_8);
1207 assert(!ep || to == st->previous->epSquare);
1208 assert(!ep || relative_rank(us, to) == RANK_6);
1209 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1211 if (pm) // promotion ?
1213 PieceType promotion = promotion_piece_type(m);
1216 assert(promotion >= KNIGHT && promotion <= QUEEN);
1217 assert(piece_on(to) == make_piece(us, promotion));
1219 // Replace promoted piece with a pawn
1220 clear_bit(&byTypeBB[promotion], to);
1221 set_bit(&byTypeBB[PAWN], to);
1223 // Update piece counts
1224 pieceCount[us][promotion]--;
1225 pieceCount[us][PAWN]++;
1227 // Update piece list replacing promotion piece with a pawn
1228 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1229 index[lastPromotionSquare] = index[to];
1230 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1231 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1232 index[to] = pieceCount[us][PAWN] - 1;
1233 pieceList[us][PAWN][index[to]] = to;
1236 // Put the piece back at the source square
1237 Bitboard move_bb = make_move_bb(to, from);
1238 do_move_bb(&byColorBB[us], move_bb);
1239 do_move_bb(&byTypeBB[pt], move_bb);
1240 do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
1242 board[from] = make_piece(us, pt);
1243 board[to] = PIECE_NONE;
1245 // Update piece list
1246 index[from] = index[to];
1247 pieceList[us][pt][index[from]] = from;
1249 if (st->capturedType)
1254 capsq = to - pawn_push(us);
1256 assert(st->capturedType != KING);
1257 assert(!ep || square_is_empty(capsq));
1259 // Restore the captured piece
1260 set_bit(&byColorBB[them], capsq);
1261 set_bit(&byTypeBB[st->capturedType], capsq);
1262 set_bit(&byTypeBB[0], capsq);
1264 board[capsq] = make_piece(them, st->capturedType);
1266 // Update piece count
1267 pieceCount[them][st->capturedType]++;
1269 // Update piece list, add a new captured piece in capsq square
1270 index[capsq] = pieceCount[them][st->capturedType] - 1;
1271 pieceList[them][st->capturedType][index[capsq]] = capsq;
1274 // Finally point our state pointer back to the previous state
1281 /// Position::undo_castle_move() is a private method used to unmake a castling
1282 /// move. It is called from the main Position::undo_move function. Note that
1283 /// castling moves are encoded as "king captures friendly rook" moves, for
1284 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1286 void Position::undo_castle_move(Move m) {
1288 assert(move_is_ok(m));
1289 assert(move_is_castle(m));
1291 // When we have arrived here, some work has already been done by
1292 // Position::undo_move. In particular, the side to move has been switched,
1293 // so the code below is correct.
1294 Color us = side_to_move();
1296 // Find source squares for king and rook
1297 Square kfrom = move_from(m);
1298 Square rfrom = move_to(m);
1301 // Find destination squares for king and rook
1302 if (rfrom > kfrom) // O-O
1304 kto = relative_square(us, SQ_G1);
1305 rto = relative_square(us, SQ_F1);
1309 kto = relative_square(us, SQ_C1);
1310 rto = relative_square(us, SQ_D1);
1313 assert(piece_on(kto) == make_piece(us, KING));
1314 assert(piece_on(rto) == make_piece(us, ROOK));
1316 // Remove pieces from destination squares
1317 clear_bit(&byColorBB[us], kto);
1318 clear_bit(&byTypeBB[KING], kto);
1319 clear_bit(&byTypeBB[0], kto);
1320 clear_bit(&byColorBB[us], rto);
1321 clear_bit(&byTypeBB[ROOK], rto);
1322 clear_bit(&byTypeBB[0], rto);
1324 // Put pieces on source squares
1325 set_bit(&byColorBB[us], kfrom);
1326 set_bit(&byTypeBB[KING], kfrom);
1327 set_bit(&byTypeBB[0], kfrom);
1328 set_bit(&byColorBB[us], rfrom);
1329 set_bit(&byTypeBB[ROOK], rfrom);
1330 set_bit(&byTypeBB[0], rfrom);
1333 Piece king = make_piece(us, KING);
1334 Piece rook = make_piece(us, ROOK);
1335 board[kto] = board[rto] = PIECE_NONE;
1336 board[kfrom] = king;
1337 board[rfrom] = rook;
1339 // Update piece lists
1340 pieceList[us][KING][index[kto]] = kfrom;
1341 pieceList[us][ROOK][index[rto]] = rfrom;
1342 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1343 index[kfrom] = index[kto];
1346 // Finally point our state pointer back to the previous state
1353 /// Position::do_null_move makes() a "null move": It switches the side to move
1354 /// and updates the hash key without executing any move on the board.
1356 void Position::do_null_move(StateInfo& backupSt) {
1358 assert(!in_check());
1360 // Back up the information necessary to undo the null move to the supplied
1361 // StateInfo object.
1362 // Note that differently from normal case here backupSt is actually used as
1363 // a backup storage not as a new state to be used.
1364 backupSt.key = st->key;
1365 backupSt.epSquare = st->epSquare;
1366 backupSt.value = st->value;
1367 backupSt.previous = st->previous;
1368 backupSt.pliesFromNull = st->pliesFromNull;
1369 st->previous = &backupSt;
1371 // Save the current key to the history[] array, in order to be able to
1372 // detect repetition draws.
1373 history[st->gamePly++] = st->key;
1375 // Update the necessary information
1376 if (st->epSquare != SQ_NONE)
1377 st->key ^= zobEp[st->epSquare];
1379 st->key ^= zobSideToMove;
1380 prefetch((char*)TT.first_entry(st->key));
1382 sideToMove = opposite_color(sideToMove);
1383 st->epSquare = SQ_NONE;
1385 st->pliesFromNull = 0;
1386 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1392 /// Position::undo_null_move() unmakes a "null move".
1394 void Position::undo_null_move() {
1396 assert(!in_check());
1398 // Restore information from the our backup StateInfo object
1399 StateInfo* backupSt = st->previous;
1400 st->key = backupSt->key;
1401 st->epSquare = backupSt->epSquare;
1402 st->value = backupSt->value;
1403 st->previous = backupSt->previous;
1404 st->pliesFromNull = backupSt->pliesFromNull;
1406 // Update the necessary information
1407 sideToMove = opposite_color(sideToMove);
1415 /// Position::see() is a static exchange evaluator: It tries to estimate the
1416 /// material gain or loss resulting from a move. There are three versions of
1417 /// this function: One which takes a destination square as input, one takes a
1418 /// move, and one which takes a 'from' and a 'to' square. The function does
1419 /// not yet understand promotions captures.
1421 int Position::see_sign(Move m) const {
1423 assert(move_is_ok(m));
1425 Square from = move_from(m);
1426 Square to = move_to(m);
1428 // Early return if SEE cannot be negative because captured piece value
1429 // is not less then capturing one. Note that king moves always return
1430 // here because king midgame value is set to 0.
1431 if (piece_value_midgame(piece_on(to)) >= piece_value_midgame(piece_on(from)))
1437 int Position::see(Move m) const {
1440 Bitboard occupied, attackers, stmAttackers, b;
1441 int swapList[32], slIndex = 1;
1442 PieceType capturedType, pt;
1445 assert(move_is_ok(m));
1447 // As castle moves are implemented as capturing the rook, they have
1448 // SEE == RookValueMidgame most of the times (unless the rook is under
1450 if (move_is_castle(m))
1453 from = move_from(m);
1455 capturedType = piece_type(piece_on(to));
1456 occupied = occupied_squares();
1458 // Handle en passant moves
1459 if (st->epSquare == to && piece_type(piece_on(from)) == PAWN)
1461 Square capQq = to - pawn_push(side_to_move());
1463 assert(capturedType == PIECE_TYPE_NONE);
1464 assert(piece_type(piece_on(capQq)) == PAWN);
1466 // Remove the captured pawn
1467 clear_bit(&occupied, capQq);
1468 capturedType = PAWN;
1471 // Find all attackers to the destination square, with the moving piece
1472 // removed, but possibly an X-ray attacker added behind it.
1473 clear_bit(&occupied, from);
1474 attackers = attackers_to(to, occupied);
1476 // If the opponent has no attackers we are finished
1477 stm = opposite_color(piece_color(piece_on(from)));
1478 stmAttackers = attackers & pieces(stm);
1480 return PieceValueMidgame[capturedType];
1482 // The destination square is defended, which makes things rather more
1483 // difficult to compute. We proceed by building up a "swap list" containing
1484 // the material gain or loss at each stop in a sequence of captures to the
1485 // destination square, where the sides alternately capture, and always
1486 // capture with the least valuable piece. After each capture, we look for
1487 // new X-ray attacks from behind the capturing piece.
1488 swapList[0] = PieceValueMidgame[capturedType];
1489 capturedType = piece_type(piece_on(from));
1492 // Locate the least valuable attacker for the side to move. The loop
1493 // below looks like it is potentially infinite, but it isn't. We know
1494 // that the side to move still has at least one attacker left.
1495 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1498 // Remove the attacker we just found from the 'occupied' bitboard,
1499 // and scan for new X-ray attacks behind the attacker.
1500 b = stmAttackers & pieces(pt);
1501 occupied ^= (b & (~b + 1));
1502 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1503 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1505 attackers &= occupied; // Cut out pieces we've already done
1507 // Add the new entry to the swap list
1508 assert(slIndex < 32);
1509 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1512 // Remember the value of the capturing piece, and change the side to
1513 // move before beginning the next iteration.
1515 stm = opposite_color(stm);
1516 stmAttackers = attackers & pieces(stm);
1518 // Stop before processing a king capture
1519 if (capturedType == KING && stmAttackers)
1521 assert(slIndex < 32);
1522 swapList[slIndex++] = QueenValueMidgame*10;
1525 } while (stmAttackers);
1527 // Having built the swap list, we negamax through it to find the best
1528 // achievable score from the point of view of the side to move.
1530 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1536 /// Position::clear() erases the position object to a pristine state, with an
1537 /// empty board, white to move, and no castling rights.
1539 void Position::clear() {
1542 memset(st, 0, sizeof(StateInfo));
1543 st->epSquare = SQ_NONE;
1545 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1546 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1547 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1548 memset(index, 0, sizeof(int) * 64);
1550 for (int i = 0; i < 8; i++)
1551 for (int j = 0; j < 16; j++)
1552 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1554 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1556 board[sq] = PIECE_NONE;
1557 castleRightsMask[sq] = ALL_CASTLES;
1565 /// Position::put_piece() puts a piece on the given square of the board,
1566 /// updating the board array, pieces list, bitboards, and piece counts.
1568 void Position::put_piece(Piece p, Square s) {
1570 Color c = piece_color(p);
1571 PieceType pt = piece_type(p);
1574 index[s] = pieceCount[c][pt]++;
1575 pieceList[c][pt][index[s]] = s;
1577 set_bit(&byTypeBB[pt], s);
1578 set_bit(&byColorBB[c], s);
1579 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1583 /// Position::compute_key() computes the hash key of the position. The hash
1584 /// key is usually updated incrementally as moves are made and unmade, the
1585 /// compute_key() function is only used when a new position is set up, and
1586 /// to verify the correctness of the hash key when running in debug mode.
1588 Key Position::compute_key() const {
1590 Key result = zobCastle[st->castleRights];
1592 for (Square s = SQ_A1; s <= SQ_H8; s++)
1593 if (!square_is_empty(s))
1594 result ^= zobrist[piece_color(piece_on(s))][piece_type(piece_on(s))][s];
1596 if (ep_square() != SQ_NONE)
1597 result ^= zobEp[ep_square()];
1599 if (side_to_move() == BLACK)
1600 result ^= zobSideToMove;
1606 /// Position::compute_pawn_key() computes the hash key of the position. The
1607 /// hash key is usually updated incrementally as moves are made and unmade,
1608 /// the compute_pawn_key() function is only used when a new position is set
1609 /// up, and to verify the correctness of the pawn hash key when running in
1612 Key Position::compute_pawn_key() const {
1617 for (Color c = WHITE; c <= BLACK; c++)
1619 b = pieces(PAWN, c);
1621 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1627 /// Position::compute_material_key() computes the hash key of the position.
1628 /// The hash key is usually updated incrementally as moves are made and unmade,
1629 /// the compute_material_key() function is only used when a new position is set
1630 /// up, and to verify the correctness of the material hash key when running in
1633 Key Position::compute_material_key() const {
1637 for (Color c = WHITE; c <= BLACK; c++)
1638 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1639 for (int i = 0, cnt = piece_count(c, pt); i < cnt; i++)
1640 result ^= zobrist[c][pt][i];
1646 /// Position::compute_value() compute the incremental scores for the middle
1647 /// game and the endgame. These functions are used to initialize the incremental
1648 /// scores when a new position is set up, and to verify that the scores are correctly
1649 /// updated by do_move and undo_move when the program is running in debug mode.
1650 Score Position::compute_value() const {
1653 Score result = SCORE_ZERO;
1655 for (Color c = WHITE; c <= BLACK; c++)
1656 for (PieceType pt = PAWN; pt <= KING; pt++)
1660 result += pst(make_piece(c, pt), pop_1st_bit(&b));
1663 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1668 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1669 /// game material value for the given side. Material values are updated
1670 /// incrementally during the search, this function is only used while
1671 /// initializing a new Position object.
1673 Value Position::compute_non_pawn_material(Color c) const {
1675 Value result = VALUE_ZERO;
1677 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1678 result += piece_count(c, pt) * PieceValueMidgame[pt];
1684 /// Position::is_draw() tests whether the position is drawn by material,
1685 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1686 /// must be done by the search.
1687 template<bool SkipRepetition>
1688 bool Position::is_draw() const {
1690 // Draw by material?
1692 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1695 // Draw by the 50 moves rule?
1696 if (st->rule50 > 99 && !is_mate())
1699 // Draw by repetition?
1700 if (!SkipRepetition)
1701 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1702 if (history[st->gamePly - i] == st->key)
1708 // Explicit template instantiations
1709 template bool Position::is_draw<false>() const;
1710 template bool Position::is_draw<true>() const;
1713 /// Position::is_mate() returns true or false depending on whether the
1714 /// side to move is checkmated.
1716 bool Position::is_mate() const {
1718 return in_check() && !MoveList<MV_LEGAL>(*this).size();
1722 /// Position::init() is a static member function which initializes at
1723 /// startup the various arrays used to compute hash keys and the piece
1724 /// square tables. The latter is a two-step operation: First, the white
1725 /// halves of the tables are copied from the MgPST[][] and EgPST[][] arrays.
1726 /// Second, the black halves of the tables are initialized by mirroring
1727 /// and changing the sign of the corresponding white scores.
1729 void Position::init() {
1733 for (Color c = WHITE; c <= BLACK; c++)
1734 for (PieceType pt = PAWN; pt <= KING; pt++)
1735 for (Square s = SQ_A1; s <= SQ_H8; s++)
1736 zobrist[c][pt][s] = rk.rand<Key>();
1738 for (Square s = SQ_A1; s <= SQ_H8; s++)
1739 zobEp[s] = rk.rand<Key>();
1741 for (int i = 0; i < 16; i++)
1742 zobCastle[i] = rk.rand<Key>();
1744 zobSideToMove = rk.rand<Key>();
1745 zobExclusion = rk.rand<Key>();
1747 for (Square s = SQ_A1; s <= SQ_H8; s++)
1748 for (Piece p = WP; p <= WK; p++)
1749 pieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1751 for (Square s = SQ_A1; s <= SQ_H8; s++)
1752 for (Piece p = BP; p <= BK; p++)
1753 pieceSquareTable[p][s] = -pieceSquareTable[p-8][flip_square(s)];
1757 /// Position::flip() flips position with the white and black sides reversed. This
1758 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1760 void Position::flip() {
1762 // Make a copy of current position before to start changing
1763 const Position pos(*this, threadID);
1766 threadID = pos.thread();
1769 for (Square s = SQ_A1; s <= SQ_H8; s++)
1770 if (!pos.square_is_empty(s))
1771 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1774 sideToMove = opposite_color(pos.side_to_move());
1777 if (pos.can_castle(WHITE_OO))
1778 set_castle(BLACK_OO, king_square(BLACK), flip_square(pos.castle_rook_square(WHITE_OO)));
1779 if (pos.can_castle(WHITE_OOO))
1780 set_castle(BLACK_OOO, king_square(BLACK), flip_square(pos.castle_rook_square(WHITE_OOO)));
1781 if (pos.can_castle(BLACK_OO))
1782 set_castle(WHITE_OO, king_square(WHITE), flip_square(pos.castle_rook_square(BLACK_OO)));
1783 if (pos.can_castle(BLACK_OOO))
1784 set_castle(WHITE_OOO, king_square(WHITE), flip_square(pos.castle_rook_square(BLACK_OOO)));
1786 // En passant square
1787 if (pos.st->epSquare != SQ_NONE)
1788 st->epSquare = flip_square(pos.st->epSquare);
1791 st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(opposite_color(sideToMove));
1794 st->key = compute_key();
1795 st->pawnKey = compute_pawn_key();
1796 st->materialKey = compute_material_key();
1798 // Incremental scores
1799 st->value = compute_value();
1802 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1803 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1809 /// Position::is_ok() performs some consitency checks for the position object.
1810 /// This is meant to be helpful when debugging.
1812 bool Position::is_ok(int* failedStep) const {
1814 // What features of the position should be verified?
1815 const bool debugAll = false;
1817 const bool debugBitboards = debugAll || false;
1818 const bool debugKingCount = debugAll || false;
1819 const bool debugKingCapture = debugAll || false;
1820 const bool debugCheckerCount = debugAll || false;
1821 const bool debugKey = debugAll || false;
1822 const bool debugMaterialKey = debugAll || false;
1823 const bool debugPawnKey = debugAll || false;
1824 const bool debugIncrementalEval = debugAll || false;
1825 const bool debugNonPawnMaterial = debugAll || false;
1826 const bool debugPieceCounts = debugAll || false;
1827 const bool debugPieceList = debugAll || false;
1828 const bool debugCastleSquares = debugAll || false;
1830 if (failedStep) *failedStep = 1;
1833 if (side_to_move() != WHITE && side_to_move() != BLACK)
1836 // Are the king squares in the position correct?
1837 if (failedStep) (*failedStep)++;
1838 if (piece_on(king_square(WHITE)) != WK)
1841 if (failedStep) (*failedStep)++;
1842 if (piece_on(king_square(BLACK)) != BK)
1845 // Do both sides have exactly one king?
1846 if (failedStep) (*failedStep)++;
1849 int kingCount[2] = {0, 0};
1850 for (Square s = SQ_A1; s <= SQ_H8; s++)
1851 if (piece_type(piece_on(s)) == KING)
1852 kingCount[piece_color(piece_on(s))]++;
1854 if (kingCount[0] != 1 || kingCount[1] != 1)
1858 // Can the side to move capture the opponent's king?
1859 if (failedStep) (*failedStep)++;
1860 if (debugKingCapture)
1862 Color us = side_to_move();
1863 Color them = opposite_color(us);
1864 Square ksq = king_square(them);
1865 if (attackers_to(ksq) & pieces(us))
1869 // Is there more than 2 checkers?
1870 if (failedStep) (*failedStep)++;
1871 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1875 if (failedStep) (*failedStep)++;
1878 // The intersection of the white and black pieces must be empty
1879 if ((pieces(WHITE) & pieces(BLACK)) != EmptyBoardBB)
1882 // The union of the white and black pieces must be equal to all
1884 if ((pieces(WHITE) | pieces(BLACK)) != occupied_squares())
1887 // Separate piece type bitboards must have empty intersections
1888 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1889 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1890 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1894 // En passant square OK?
1895 if (failedStep) (*failedStep)++;
1896 if (ep_square() != SQ_NONE)
1898 // The en passant square must be on rank 6, from the point of view of the
1900 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1905 if (failedStep) (*failedStep)++;
1906 if (debugKey && st->key != compute_key())
1909 // Pawn hash key OK?
1910 if (failedStep) (*failedStep)++;
1911 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1914 // Material hash key OK?
1915 if (failedStep) (*failedStep)++;
1916 if (debugMaterialKey && st->materialKey != compute_material_key())
1919 // Incremental eval OK?
1920 if (failedStep) (*failedStep)++;
1921 if (debugIncrementalEval && st->value != compute_value())
1924 // Non-pawn material OK?
1925 if (failedStep) (*failedStep)++;
1926 if (debugNonPawnMaterial)
1928 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1931 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1936 if (failedStep) (*failedStep)++;
1937 if (debugPieceCounts)
1938 for (Color c = WHITE; c <= BLACK; c++)
1939 for (PieceType pt = PAWN; pt <= KING; pt++)
1940 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1943 if (failedStep) (*failedStep)++;
1945 for (Color c = WHITE; c <= BLACK; c++)
1946 for (PieceType pt = PAWN; pt <= KING; pt++)
1947 for (int i = 0; i < pieceCount[c][pt]; i++)
1949 if (piece_on(piece_list(c, pt)[i]) != make_piece(c, pt))
1952 if (index[piece_list(c, pt)[i]] != i)
1956 if (failedStep) (*failedStep)++;
1957 if (debugCastleSquares)
1958 for (CastleRight f = WHITE_OO; f <= BLACK_OOO; f = CastleRight(f << 1))
1963 Piece rook = (f & (WHITE_OO | WHITE_OOO) ? WR : BR);
1965 if ( castleRightsMask[castleRookSquare[f]] != (ALL_CASTLES ^ f)
1966 || piece_on(castleRookSquare[f]) != rook)
1970 if (failedStep) *failedStep = 0;