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 Position::PieceValueMidgame[17] = {
50 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
51 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
52 VALUE_ZERO, VALUE_ZERO,
53 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
54 RookValueMidgame, QueenValueMidgame
57 const Value Position::PieceValueEndgame[17] = {
59 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
60 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
61 VALUE_ZERO, VALUE_ZERO,
62 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
63 RookValueEndgame, QueenValueEndgame
66 // Material values array used by SEE, indexed by PieceType
67 const Value Position::seeValues[] = {
69 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
70 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
76 // Bonus for having the side to move (modified by Joona Kiiski)
77 const Score TempoValue = make_score(48, 22);
79 // To convert a Piece to and from a FEN char
80 const string PieceToChar(".PNBRQK pnbrqk ");
86 CheckInfo::CheckInfo(const Position& pos) {
88 Color us = pos.side_to_move();
89 Color them = opposite_color(us);
91 ksq = pos.king_square(them);
92 dcCandidates = pos.discovered_check_candidates(us);
94 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
95 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
96 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
97 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
98 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
99 checkSq[KING] = EmptyBoardBB;
103 /// Position c'tors. Here we always create a copy of the original position
104 /// or the FEN string, we want the new born Position object do not depend
105 /// on any external data so we detach state pointer from the source one.
107 Position::Position(const Position& pos, int th) {
109 memcpy(this, &pos, sizeof(Position));
110 detach(); // Always detach() in copy c'tor to avoid surprises
115 Position::Position(const string& fen, bool isChess960, int th) {
117 from_fen(fen, isChess960);
122 /// Position::detach() copies the content of the current state and castling
123 /// masks inside the position itself. This is needed when the st pointee could
124 /// become stale, as example because the caller is about to going out of scope.
126 void Position::detach() {
130 st->previous = NULL; // as a safe guard
134 /// Position::from_fen() initializes the position object with the given FEN
135 /// string. This function is not very robust - make sure that input FENs are
136 /// correct (this is assumed to be the responsibility of the GUI).
138 void Position::from_fen(const string& fen, bool isChess960) {
140 A FEN string defines a particular position using only the ASCII character set.
142 A FEN string contains six fields. The separator between fields is a space. The fields are:
144 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
145 with rank 1; within each rank, the contents of each square are described from file A through file H.
146 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
147 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
148 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
149 of blank squares), and "/" separate ranks.
151 2) Active color. "w" means white moves next, "b" means black.
153 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
154 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
155 kingside), and/or "q" (Black can castle queenside).
157 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
158 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
159 regardless of whether there is a pawn in position to make an en passant capture.
161 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
162 to determine if a draw can be claimed under the fifty-move rule.
164 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
171 std::istringstream ss(fen);
176 // 1. Piece placement field
177 while ((ss >> token) && !isspace(token))
179 if ((p = PieceToChar.find(token)) != string::npos)
181 put_piece(Piece(p), sq);
184 else if (isdigit(token))
185 sq += Square(token - '0'); // Skip the given number of files
186 else if (token == '/')
187 sq -= SQ_A3; // Jump back of 2 rows
193 if (!(ss >> token) || (token != 'w' && token != 'b'))
196 sideToMove = (token == 'w' ? WHITE : BLACK);
198 if (!(ss >> token) || !isspace(token))
201 // 3. Castling availability
202 while ((ss >> token) && !isspace(token))
203 if (!set_castling_rights(token))
206 // 4. En passant square
208 if ( ((ss >> col) && (col >= 'a' && col <= 'h'))
209 && ((ss >> row) && (row == '3' || row == '6')))
211 st->epSquare = make_square(File(col - 'a') + FILE_A, Rank(row - '1') + RANK_1);
213 // Ignore if no capture is possible
214 Color them = opposite_color(sideToMove);
215 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
216 st->epSquare = SQ_NONE;
220 if (ss >> std::skipws >> hmc)
223 // 6. Fullmove number
225 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
227 // Various initialisations
228 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
229 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
230 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
231 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
232 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
233 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
235 chess960 = isChess960;
238 st->key = compute_key();
239 st->pawnKey = compute_pawn_key();
240 st->materialKey = compute_material_key();
241 st->value = compute_value();
242 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
243 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
247 cout << "Error in FEN string: " << fen << endl;
251 /// Position::set_castling_rights() sets castling parameters castling avaiability.
252 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
253 /// that uses the letters of the columns on which the rooks began the game instead
254 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
255 /// associated with the castling right, the traditional castling tag will be replaced
256 /// by the file letter of the involved rook as for the Shredder-FEN.
258 bool Position::set_castling_rights(char token) {
260 Color c = token >= 'a' ? BLACK : WHITE;
261 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
262 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
263 Piece rook = (c == WHITE ? WR : BR);
265 initialKFile = square_file(king_square(c));
266 token = char(toupper(token));
270 for (Square sq = sqH; sq >= sqA; sq--)
271 if (piece_on(sq) == rook)
273 set_castle_kingside(c);
274 initialKRFile = square_file(sq);
278 else if (token == 'Q')
280 for (Square sq = sqA; sq <= sqH; sq++)
281 if (piece_on(sq) == rook)
283 set_castle_queenside(c);
284 initialQRFile = square_file(sq);
288 else if (token >= 'A' && token <= 'H')
290 File rookFile = File(token - 'A') + FILE_A;
291 if (rookFile < initialKFile)
293 set_castle_queenside(c);
294 initialQRFile = rookFile;
298 set_castle_kingside(c);
299 initialKRFile = rookFile;
309 /// Position::to_fen() returns a FEN representation of the position. In case
310 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
312 const string Position::to_fen() const {
318 for (Rank rank = RANK_8; rank >= RANK_1; rank--, fen += '/')
322 for (File file = FILE_A; file <= FILE_H; file++)
324 sq = make_square(file, rank);
326 if (square_is_occupied(sq))
333 fen += PieceToChar[piece_on(sq)];
342 fen += (sideToMove == WHITE ? " w " : " b ");
344 if (st->castleRights != CASTLES_NONE)
346 if (can_castle_kingside(WHITE))
347 fen += chess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
349 if (can_castle_queenside(WHITE))
350 fen += chess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
352 if (can_castle_kingside(BLACK))
353 fen += chess960 ? file_to_char(initialKRFile) : 'k';
355 if (can_castle_queenside(BLACK))
356 fen += chess960 ? file_to_char(initialQRFile) : 'q';
360 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
365 /// Position::print() prints an ASCII representation of the position to
366 /// the standard output. If a move is given then also the san is printed.
368 void Position::print(Move move) const {
370 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
374 Position p(*this, thread());
375 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
376 cout << "\nMove is: " << dd << move_to_san(p, move);
379 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
381 cout << dottedLine << '|';
382 for (File file = FILE_A; file <= FILE_H; file++)
384 Square sq = make_square(file, rank);
385 Piece piece = piece_on(sq);
387 if (piece == PIECE_NONE && square_color(sq) == DARK)
388 piece = PIECE_NONE_DARK_SQ;
390 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
391 cout << c << PieceToChar[piece] << c << '|';
394 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
398 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
399 /// king) pieces for the given color and for the given pinner type. Or, when
400 /// template parameter FindPinned is false, the pieces of the given color
401 /// candidate for a discovery check against the enemy king.
402 /// Bitboard checkersBB must be already updated when looking for pinners.
404 template<bool FindPinned>
405 Bitboard Position::hidden_checkers(Color c) const {
407 Bitboard result = EmptyBoardBB;
408 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
410 // Pinned pieces protect our king, dicovery checks attack
412 Square ksq = king_square(FindPinned ? c : opposite_color(c));
414 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
415 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
417 if (FindPinned && pinners)
418 pinners &= ~st->checkersBB;
422 Square s = pop_1st_bit(&pinners);
423 Bitboard b = squares_between(s, ksq) & occupied_squares();
427 if ( !(b & (b - 1)) // Only one bit set?
428 && (b & pieces_of_color(c))) // Is an our piece?
435 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
436 /// king) pieces for the given color. Note that checkersBB bitboard must
437 /// be already updated.
439 Bitboard Position::pinned_pieces(Color c) const {
441 return hidden_checkers<true>(c);
445 /// Position:discovered_check_candidates() returns a bitboard containing all
446 /// pieces for the given side which are candidates for giving a discovered
447 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
448 /// to be already updated.
450 Bitboard Position::discovered_check_candidates(Color c) const {
452 return hidden_checkers<false>(c);
455 /// Position::attackers_to() computes a bitboard containing all pieces which
456 /// attacks a given square.
458 Bitboard Position::attackers_to(Square s) const {
460 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
461 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
462 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
463 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
464 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
465 | (attacks_from<KING>(s) & pieces(KING));
468 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
470 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
471 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
472 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
473 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
474 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
475 | (attacks_from<KING>(s) & pieces(KING));
478 /// Position::attacks_from() computes a bitboard of all attacks
479 /// of a given piece put in a given square.
481 Bitboard Position::attacks_from(Piece p, Square s) const {
483 assert(square_is_ok(s));
487 case WB: case BB: return attacks_from<BISHOP>(s);
488 case WR: case BR: return attacks_from<ROOK>(s);
489 case WQ: case BQ: return attacks_from<QUEEN>(s);
490 default: return StepAttacksBB[p][s];
494 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
496 assert(square_is_ok(s));
500 case WB: case BB: return bishop_attacks_bb(s, occ);
501 case WR: case BR: return rook_attacks_bb(s, occ);
502 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
503 default: return StepAttacksBB[p][s];
508 /// Position::move_attacks_square() tests whether a move from the current
509 /// position attacks a given square.
511 bool Position::move_attacks_square(Move m, Square s) const {
513 assert(move_is_ok(m));
514 assert(square_is_ok(s));
517 Square f = move_from(m), t = move_to(m);
519 assert(square_is_occupied(f));
521 if (bit_is_set(attacks_from(piece_on(f), t), s))
524 // Move the piece and scan for X-ray attacks behind it
525 occ = occupied_squares();
526 do_move_bb(&occ, make_move_bb(f, t));
527 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
528 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
529 & pieces_of_color(color_of_piece_on(f));
531 // If we have attacks we need to verify that are caused by our move
532 // and are not already existent ones.
533 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
537 /// Position::find_checkers() computes the checkersBB bitboard, which
538 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
539 /// currently works by calling Position::attackers_to, which is probably
540 /// inefficient. Consider rewriting this function to use the last move
541 /// played, like in non-bitboard versions of Glaurung.
543 void Position::find_checkers() {
545 Color us = side_to_move();
546 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
550 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
552 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
555 assert(move_is_ok(m));
556 assert(pinned == pinned_pieces(side_to_move()));
558 Color us = side_to_move();
559 Square from = move_from(m);
561 assert(color_of_piece_on(from) == us);
562 assert(piece_on(king_square(us)) == make_piece(us, KING));
564 // En passant captures are a tricky special case. Because they are
565 // rather uncommon, we do it simply by testing whether the king is attacked
566 // after the move is made
569 Color them = opposite_color(us);
570 Square to = move_to(m);
571 Square capsq = make_square(square_file(to), square_rank(from));
572 Square ksq = king_square(us);
573 Bitboard b = occupied_squares();
575 assert(to == ep_square());
576 assert(piece_on(from) == make_piece(us, PAWN));
577 assert(piece_on(capsq) == make_piece(them, PAWN));
578 assert(piece_on(to) == PIECE_NONE);
581 clear_bit(&b, capsq);
584 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
585 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
588 // If the moving piece is a king, check whether the destination
589 // square is attacked by the opponent. Castling moves are checked
590 // for legality during move generation.
591 if (type_of_piece_on(from) == KING)
592 return move_is_castle(m) || !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
594 // A non-king move is legal if and only if it is not pinned or it
595 // is moving along the ray towards or away from the king.
597 || !bit_is_set(pinned, from)
598 || squares_aligned(from, move_to(m), king_square(us));
602 /// Position::move_is_pl_slow() takes a position and a move and tests whether
603 /// the move is pseudo legal. This version is not very fast and should be used
604 /// only in non time-critical paths.
606 bool Position::move_is_pl_slow(const Move m) const {
608 MoveStack mlist[MAX_MOVES];
609 MoveStack *cur, *last;
611 last = in_check() ? generate<MV_EVASION>(*this, mlist)
612 : generate<MV_NON_EVASION>(*this, mlist);
614 for (cur = mlist; cur != last; cur++)
622 /// Fast version of Position::move_is_pl() that takes a position a move and a
623 /// bitboard of pinned pieces as input, and tests whether the move is pseudo legal.
625 bool Position::move_is_pl(const Move m) const {
629 Color us = sideToMove;
630 Color them = opposite_color(sideToMove);
631 Square from = move_from(m);
632 Square to = move_to(m);
633 Piece pc = piece_on(from);
635 // Use a slower but simpler function for uncommon cases
636 if (move_is_special(m))
637 return move_is_pl_slow(m);
639 // Is not a promotion, so promotion piece must be empty
640 if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
643 // If the from square is not occupied by a piece belonging to the side to
644 // move, the move is obviously not legal.
645 if (pc == PIECE_NONE || color_of_piece(pc) != us)
648 // The destination square cannot be occupied by a friendly piece
649 if (color_of_piece_on(to) == us)
652 // Handle the special case of a pawn move
653 if (type_of_piece(pc) == PAWN)
655 // Move direction must be compatible with pawn color
656 int direction = to - from;
657 if ((us == WHITE) != (direction > 0))
660 // We have already handled promotion moves, so destination
661 // cannot be on the 8/1th rank.
662 if (square_rank(to) == RANK_8 || square_rank(to) == RANK_1)
665 // Proceed according to the square delta between the origin and
666 // destination squares.
673 // Capture. The destination square must be occupied by an enemy
674 // piece (en passant captures was handled earlier).
675 if (color_of_piece_on(to) != them)
678 // From and to files must be one file apart, avoids a7h5
679 if (abs(square_file(from) - square_file(to)) != 1)
685 // Pawn push. The destination square must be empty.
686 if (!square_is_empty(to))
691 // Double white pawn push. The destination square must be on the fourth
692 // rank, and both the destination square and the square between the
693 // source and destination squares must be empty.
694 if ( square_rank(to) != RANK_4
695 || !square_is_empty(to)
696 || !square_is_empty(from + DELTA_N))
701 // Double black pawn push. The destination square must be on the fifth
702 // rank, and both the destination square and the square between the
703 // source and destination squares must be empty.
704 if ( square_rank(to) != RANK_5
705 || !square_is_empty(to)
706 || !square_is_empty(from + DELTA_S))
714 else if (!bit_is_set(attacks_from(pc, from), to))
719 // In case of king moves under check we have to remove king so to catch
720 // as invalid moves like b1a1 when opposite queen is on c1.
721 if (type_of_piece_on(from) == KING)
723 Bitboard b = occupied_squares();
725 if (attackers_to(move_to(m), b) & pieces_of_color(opposite_color(us)))
730 Bitboard target = checkers();
731 Square checksq = pop_1st_bit(&target);
733 if (target) // double check ? In this case a king move is required
736 // Our move must be a blocking evasion or a capture of the checking piece
737 target = squares_between(checksq, king_square(us)) | checkers();
738 if (!bit_is_set(target, move_to(m)))
747 /// Position::move_gives_check() tests whether a pseudo-legal move is a check
749 bool Position::move_gives_check(Move m) const {
751 return move_gives_check(m, CheckInfo(*this));
754 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
757 assert(move_is_ok(m));
758 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
759 assert(color_of_piece_on(move_from(m)) == side_to_move());
760 assert(piece_on(ci.ksq) == make_piece(opposite_color(side_to_move()), KING));
762 Square from = move_from(m);
763 Square to = move_to(m);
764 PieceType pt = type_of_piece_on(from);
767 if (bit_is_set(ci.checkSq[pt], to))
771 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
773 // For pawn and king moves we need to verify also direction
774 if ( (pt != PAWN && pt != KING)
775 || !squares_aligned(from, to, ci.ksq))
779 // Can we skip the ugly special cases ?
780 if (!move_is_special(m))
783 Color us = side_to_move();
784 Bitboard b = occupied_squares();
786 // Promotion with check ?
787 if (move_is_promotion(m))
791 switch (promotion_piece_type(m))
794 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
796 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
798 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
800 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
806 // En passant capture with check ? We have already handled the case
807 // of direct checks and ordinary discovered check, the only case we
808 // need to handle is the unusual case of a discovered check through
809 // the captured pawn.
812 Square capsq = make_square(square_file(to), square_rank(from));
814 clear_bit(&b, capsq);
816 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
817 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
820 // Castling with check ?
821 if (move_is_castle(m))
823 Square kfrom, kto, rfrom, rto;
829 kto = relative_square(us, SQ_G1);
830 rto = relative_square(us, SQ_F1);
832 kto = relative_square(us, SQ_C1);
833 rto = relative_square(us, SQ_D1);
835 clear_bit(&b, kfrom);
836 clear_bit(&b, rfrom);
839 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
846 /// Position::do_setup_move() makes a permanent move on the board. It should
847 /// be used when setting up a position on board. You can't undo the move.
849 void Position::do_setup_move(Move m) {
855 // Reset "game ply" in case we made a non-reversible move.
856 // "game ply" is used for repetition detection.
860 // Update the number of plies played from the starting position
861 startPosPlyCounter++;
863 // Our StateInfo newSt is about going out of scope so copy
864 // its content before it disappears.
869 /// Position::do_move() makes a move, and saves all information necessary
870 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
871 /// moves should be filtered out before this function is called.
873 void Position::do_move(Move m, StateInfo& newSt) {
876 do_move(m, newSt, ci, move_gives_check(m, ci));
879 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
882 assert(move_is_ok(m));
883 assert(&newSt != st);
888 // Copy some fields of old state to our new StateInfo object except the
889 // ones which are recalculated from scratch anyway, then switch our state
890 // pointer to point to the new, ready to be updated, state.
891 struct ReducedStateInfo {
892 Key pawnKey, materialKey;
893 int castleRights, rule50, gamePly, pliesFromNull;
899 memcpy(&newSt, st, sizeof(ReducedStateInfo));
904 // Save the current key to the history[] array, in order to be able to
905 // detect repetition draws.
906 history[st->gamePly++] = key;
908 // Update side to move
909 key ^= zobSideToMove;
911 // Increment the 50 moves rule draw counter. Resetting it to zero in the
912 // case of non-reversible moves is taken care of later.
916 if (move_is_castle(m))
923 Color us = side_to_move();
924 Color them = opposite_color(us);
925 Square from = move_from(m);
926 Square to = move_to(m);
927 bool ep = move_is_ep(m);
928 bool pm = move_is_promotion(m);
930 Piece piece = piece_on(from);
931 PieceType pt = type_of_piece(piece);
932 PieceType capture = ep ? PAWN : type_of_piece_on(to);
934 assert(color_of_piece_on(from) == us);
935 assert(color_of_piece_on(to) == them || square_is_empty(to));
936 assert(!(ep || pm) || piece == make_piece(us, PAWN));
937 assert(!pm || relative_rank(us, to) == RANK_8);
940 do_capture_move(key, capture, them, to, ep);
943 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
945 // Reset en passant square
946 if (st->epSquare != SQ_NONE)
948 key ^= zobEp[st->epSquare];
949 st->epSquare = SQ_NONE;
952 // Update castle rights if needed
953 if ( st->castleRights != CASTLES_NONE
954 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
956 key ^= zobCastle[st->castleRights];
957 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
958 key ^= zobCastle[st->castleRights];
961 // Prefetch TT access as soon as we know key is updated
962 prefetch((char*)TT.first_entry(key));
965 Bitboard move_bb = make_move_bb(from, to);
966 do_move_bb(&(byColorBB[us]), move_bb);
967 do_move_bb(&(byTypeBB[pt]), move_bb);
968 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
970 board[to] = board[from];
971 board[from] = PIECE_NONE;
973 // Update piece lists, note that index[from] is not updated and
974 // becomes stale. This works as long as index[] is accessed just
975 // by known occupied squares.
976 index[to] = index[from];
977 pieceList[us][pt][index[to]] = to;
979 // If the moving piece was a pawn do some special extra work
982 // Reset rule 50 draw counter
985 // Update pawn hash key and prefetch in L1/L2 cache
986 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
988 // Set en passant square, only if moved pawn can be captured
989 if ((to ^ from) == 16)
991 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
993 st->epSquare = Square((int(from) + int(to)) / 2);
994 key ^= zobEp[st->epSquare];
998 if (pm) // promotion ?
1000 PieceType promotion = promotion_piece_type(m);
1002 assert(promotion >= KNIGHT && promotion <= QUEEN);
1004 // Insert promoted piece instead of pawn
1005 clear_bit(&(byTypeBB[PAWN]), to);
1006 set_bit(&(byTypeBB[promotion]), to);
1007 board[to] = make_piece(us, promotion);
1009 // Update piece counts
1010 pieceCount[us][promotion]++;
1011 pieceCount[us][PAWN]--;
1013 // Update material key
1014 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
1015 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
1017 // Update piece lists, move the last pawn at index[to] position
1018 // and shrink the list. Add a new promotion piece to the list.
1019 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
1020 index[lastPawnSquare] = index[to];
1021 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
1022 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
1023 index[to] = pieceCount[us][promotion] - 1;
1024 pieceList[us][promotion][index[to]] = to;
1026 // Partially revert hash keys update
1027 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
1028 st->pawnKey ^= zobrist[us][PAWN][to];
1030 // Partially revert and update incremental scores
1031 st->value -= pst(us, PAWN, to);
1032 st->value += pst(us, promotion, to);
1035 st->npMaterial[us] += PieceValueMidgame[promotion];
1039 // Prefetch pawn and material hash tables
1040 Threads[threadID].pawnTable.prefetch(st->pawnKey);
1041 Threads[threadID].materialTable.prefetch(st->materialKey);
1043 // Update incremental scores
1044 st->value += pst_delta(piece, from, to);
1046 // Set capture piece
1047 st->capturedType = capture;
1049 // Update the key with the final value
1052 // Update checkers bitboard, piece must be already moved
1053 st->checkersBB = EmptyBoardBB;
1058 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1062 if (bit_is_set(ci.checkSq[pt], to))
1063 st->checkersBB = SetMaskBB[to];
1066 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1069 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
1072 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
1078 sideToMove = opposite_color(sideToMove);
1079 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1085 /// Position::do_capture_move() is a private method used to update captured
1086 /// piece info. It is called from the main Position::do_move function.
1088 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1090 assert(capture != KING);
1094 // If the captured piece was a pawn, update pawn hash key,
1095 // otherwise update non-pawn material.
1096 if (capture == PAWN)
1098 if (ep) // en passant ?
1100 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1102 assert(to == st->epSquare);
1103 assert(relative_rank(opposite_color(them), to) == RANK_6);
1104 assert(piece_on(to) == PIECE_NONE);
1105 assert(piece_on(capsq) == make_piece(them, PAWN));
1107 board[capsq] = PIECE_NONE;
1109 st->pawnKey ^= zobrist[them][PAWN][capsq];
1112 st->npMaterial[them] -= PieceValueMidgame[capture];
1114 // Remove captured piece
1115 clear_bit(&(byColorBB[them]), capsq);
1116 clear_bit(&(byTypeBB[capture]), capsq);
1117 clear_bit(&(byTypeBB[0]), capsq);
1120 key ^= zobrist[them][capture][capsq];
1122 // Update incremental scores
1123 st->value -= pst(them, capture, capsq);
1125 // Update piece count
1126 pieceCount[them][capture]--;
1128 // Update material hash key
1129 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1131 // Update piece list, move the last piece at index[capsq] position
1133 // WARNING: This is a not perfectly revresible operation. When we
1134 // will reinsert the captured piece in undo_move() we will put it
1135 // at the end of the list and not in its original place, it means
1136 // index[] and pieceList[] are not guaranteed to be invariant to a
1137 // do_move() + undo_move() sequence.
1138 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1139 index[lastPieceSquare] = index[capsq];
1140 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1141 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1143 // Reset rule 50 counter
1148 /// Position::do_castle_move() is a private method used to make a castling
1149 /// move. It is called from the main Position::do_move function. Note that
1150 /// castling moves are encoded as "king captures friendly rook" moves, for
1151 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1153 void Position::do_castle_move(Move m) {
1155 assert(move_is_ok(m));
1156 assert(move_is_castle(m));
1158 Color us = side_to_move();
1159 Color them = opposite_color(us);
1161 // Reset capture field
1162 st->capturedType = PIECE_TYPE_NONE;
1164 // Find source squares for king and rook
1165 Square kfrom = move_from(m);
1166 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1169 assert(piece_on(kfrom) == make_piece(us, KING));
1170 assert(piece_on(rfrom) == make_piece(us, ROOK));
1172 // Find destination squares for king and rook
1173 if (rfrom > kfrom) // O-O
1175 kto = relative_square(us, SQ_G1);
1176 rto = relative_square(us, SQ_F1);
1178 kto = relative_square(us, SQ_C1);
1179 rto = relative_square(us, SQ_D1);
1182 // Remove pieces from source squares:
1183 clear_bit(&(byColorBB[us]), kfrom);
1184 clear_bit(&(byTypeBB[KING]), kfrom);
1185 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1186 clear_bit(&(byColorBB[us]), rfrom);
1187 clear_bit(&(byTypeBB[ROOK]), rfrom);
1188 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1190 // Put pieces on destination squares:
1191 set_bit(&(byColorBB[us]), kto);
1192 set_bit(&(byTypeBB[KING]), kto);
1193 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1194 set_bit(&(byColorBB[us]), rto);
1195 set_bit(&(byTypeBB[ROOK]), rto);
1196 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1198 // Update board array
1199 Piece king = make_piece(us, KING);
1200 Piece rook = make_piece(us, ROOK);
1201 board[kfrom] = board[rfrom] = PIECE_NONE;
1205 // Update piece lists
1206 pieceList[us][KING][index[kfrom]] = kto;
1207 pieceList[us][ROOK][index[rfrom]] = rto;
1208 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1209 index[kto] = index[kfrom];
1212 // Update incremental scores
1213 st->value += pst_delta(king, kfrom, kto);
1214 st->value += pst_delta(rook, rfrom, rto);
1217 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1218 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1220 // Clear en passant square
1221 if (st->epSquare != SQ_NONE)
1223 st->key ^= zobEp[st->epSquare];
1224 st->epSquare = SQ_NONE;
1227 // Update castling rights
1228 st->key ^= zobCastle[st->castleRights];
1229 st->castleRights &= castleRightsMask[kfrom];
1230 st->key ^= zobCastle[st->castleRights];
1232 // Reset rule 50 counter
1235 // Update checkers BB
1236 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1239 sideToMove = opposite_color(sideToMove);
1240 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1246 /// Position::undo_move() unmakes a move. When it returns, the position should
1247 /// be restored to exactly the same state as before the move was made.
1249 void Position::undo_move(Move m) {
1252 assert(move_is_ok(m));
1254 sideToMove = opposite_color(sideToMove);
1256 if (move_is_castle(m))
1258 undo_castle_move(m);
1262 Color us = side_to_move();
1263 Color them = opposite_color(us);
1264 Square from = move_from(m);
1265 Square to = move_to(m);
1266 bool ep = move_is_ep(m);
1267 bool pm = move_is_promotion(m);
1269 PieceType pt = type_of_piece_on(to);
1271 assert(square_is_empty(from));
1272 assert(color_of_piece_on(to) == us);
1273 assert(!pm || relative_rank(us, to) == RANK_8);
1274 assert(!ep || to == st->previous->epSquare);
1275 assert(!ep || relative_rank(us, to) == RANK_6);
1276 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1278 if (pm) // promotion ?
1280 PieceType promotion = promotion_piece_type(m);
1283 assert(promotion >= KNIGHT && promotion <= QUEEN);
1284 assert(piece_on(to) == make_piece(us, promotion));
1286 // Replace promoted piece with a pawn
1287 clear_bit(&(byTypeBB[promotion]), to);
1288 set_bit(&(byTypeBB[PAWN]), to);
1290 // Update piece counts
1291 pieceCount[us][promotion]--;
1292 pieceCount[us][PAWN]++;
1294 // Update piece list replacing promotion piece with a pawn
1295 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1296 index[lastPromotionSquare] = index[to];
1297 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1298 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1299 index[to] = pieceCount[us][PAWN] - 1;
1300 pieceList[us][PAWN][index[to]] = to;
1303 // Put the piece back at the source square
1304 Bitboard move_bb = make_move_bb(to, from);
1305 do_move_bb(&(byColorBB[us]), move_bb);
1306 do_move_bb(&(byTypeBB[pt]), move_bb);
1307 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1309 board[from] = make_piece(us, pt);
1310 board[to] = PIECE_NONE;
1312 // Update piece list
1313 index[from] = index[to];
1314 pieceList[us][pt][index[from]] = from;
1316 if (st->capturedType)
1321 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1323 assert(st->capturedType != KING);
1324 assert(!ep || square_is_empty(capsq));
1326 // Restore the captured piece
1327 set_bit(&(byColorBB[them]), capsq);
1328 set_bit(&(byTypeBB[st->capturedType]), capsq);
1329 set_bit(&(byTypeBB[0]), capsq);
1331 board[capsq] = make_piece(them, st->capturedType);
1333 // Update piece count
1334 pieceCount[them][st->capturedType]++;
1336 // Update piece list, add a new captured piece in capsq square
1337 index[capsq] = pieceCount[them][st->capturedType] - 1;
1338 pieceList[them][st->capturedType][index[capsq]] = capsq;
1341 // Finally point our state pointer back to the previous state
1348 /// Position::undo_castle_move() is a private method used to unmake a castling
1349 /// move. It is called from the main Position::undo_move function. Note that
1350 /// castling moves are encoded as "king captures friendly rook" moves, for
1351 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1353 void Position::undo_castle_move(Move m) {
1355 assert(move_is_ok(m));
1356 assert(move_is_castle(m));
1358 // When we have arrived here, some work has already been done by
1359 // Position::undo_move. In particular, the side to move has been switched,
1360 // so the code below is correct.
1361 Color us = side_to_move();
1363 // Find source squares for king and rook
1364 Square kfrom = move_from(m);
1365 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1368 // Find destination squares for king and rook
1369 if (rfrom > kfrom) // O-O
1371 kto = relative_square(us, SQ_G1);
1372 rto = relative_square(us, SQ_F1);
1374 kto = relative_square(us, SQ_C1);
1375 rto = relative_square(us, SQ_D1);
1378 assert(piece_on(kto) == make_piece(us, KING));
1379 assert(piece_on(rto) == make_piece(us, ROOK));
1381 // Remove pieces from destination squares:
1382 clear_bit(&(byColorBB[us]), kto);
1383 clear_bit(&(byTypeBB[KING]), kto);
1384 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1385 clear_bit(&(byColorBB[us]), rto);
1386 clear_bit(&(byTypeBB[ROOK]), rto);
1387 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1389 // Put pieces on source squares:
1390 set_bit(&(byColorBB[us]), kfrom);
1391 set_bit(&(byTypeBB[KING]), kfrom);
1392 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1393 set_bit(&(byColorBB[us]), rfrom);
1394 set_bit(&(byTypeBB[ROOK]), rfrom);
1395 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1398 board[rto] = board[kto] = PIECE_NONE;
1399 board[rfrom] = make_piece(us, ROOK);
1400 board[kfrom] = make_piece(us, KING);
1402 // Update piece lists
1403 pieceList[us][KING][index[kto]] = kfrom;
1404 pieceList[us][ROOK][index[rto]] = rfrom;
1405 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1406 index[kfrom] = index[kto];
1409 // Finally point our state pointer back to the previous state
1416 /// Position::do_null_move makes() a "null move": It switches the side to move
1417 /// and updates the hash key without executing any move on the board.
1419 void Position::do_null_move(StateInfo& backupSt) {
1422 assert(!in_check());
1424 // Back up the information necessary to undo the null move to the supplied
1425 // StateInfo object.
1426 // Note that differently from normal case here backupSt is actually used as
1427 // a backup storage not as a new state to be used.
1428 backupSt.key = st->key;
1429 backupSt.epSquare = st->epSquare;
1430 backupSt.value = st->value;
1431 backupSt.previous = st->previous;
1432 backupSt.pliesFromNull = st->pliesFromNull;
1433 st->previous = &backupSt;
1435 // Save the current key to the history[] array, in order to be able to
1436 // detect repetition draws.
1437 history[st->gamePly++] = st->key;
1439 // Update the necessary information
1440 if (st->epSquare != SQ_NONE)
1441 st->key ^= zobEp[st->epSquare];
1443 st->key ^= zobSideToMove;
1444 prefetch((char*)TT.first_entry(st->key));
1446 sideToMove = opposite_color(sideToMove);
1447 st->epSquare = SQ_NONE;
1449 st->pliesFromNull = 0;
1450 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1454 /// Position::undo_null_move() unmakes a "null move".
1456 void Position::undo_null_move() {
1459 assert(!in_check());
1461 // Restore information from the our backup StateInfo object
1462 StateInfo* backupSt = st->previous;
1463 st->key = backupSt->key;
1464 st->epSquare = backupSt->epSquare;
1465 st->value = backupSt->value;
1466 st->previous = backupSt->previous;
1467 st->pliesFromNull = backupSt->pliesFromNull;
1469 // Update the necessary information
1470 sideToMove = opposite_color(sideToMove);
1476 /// Position::see() is a static exchange evaluator: It tries to estimate the
1477 /// material gain or loss resulting from a move. There are three versions of
1478 /// this function: One which takes a destination square as input, one takes a
1479 /// move, and one which takes a 'from' and a 'to' square. The function does
1480 /// not yet understand promotions captures.
1482 int Position::see_sign(Move m) const {
1484 assert(move_is_ok(m));
1486 Square from = move_from(m);
1487 Square to = move_to(m);
1489 // Early return if SEE cannot be negative because captured piece value
1490 // is not less then capturing one. Note that king moves always return
1491 // here because king midgame value is set to 0.
1492 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1498 int Position::see(Move m) const {
1501 Bitboard occupied, attackers, stmAttackers, b;
1502 int swapList[32], slIndex = 1;
1503 PieceType capturedType, pt;
1506 assert(move_is_ok(m));
1508 // As castle moves are implemented as capturing the rook, they have
1509 // SEE == RookValueMidgame most of the times (unless the rook is under
1511 if (move_is_castle(m))
1514 from = move_from(m);
1516 capturedType = type_of_piece_on(to);
1517 occupied = occupied_squares();
1519 // Handle en passant moves
1520 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1522 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1524 assert(capturedType == PIECE_TYPE_NONE);
1525 assert(type_of_piece_on(capQq) == PAWN);
1527 // Remove the captured pawn
1528 clear_bit(&occupied, capQq);
1529 capturedType = PAWN;
1532 // Find all attackers to the destination square, with the moving piece
1533 // removed, but possibly an X-ray attacker added behind it.
1534 clear_bit(&occupied, from);
1535 attackers = attackers_to(to, occupied);
1537 // If the opponent has no attackers we are finished
1538 stm = opposite_color(color_of_piece_on(from));
1539 stmAttackers = attackers & pieces_of_color(stm);
1541 return seeValues[capturedType];
1543 // The destination square is defended, which makes things rather more
1544 // difficult to compute. We proceed by building up a "swap list" containing
1545 // the material gain or loss at each stop in a sequence of captures to the
1546 // destination square, where the sides alternately capture, and always
1547 // capture with the least valuable piece. After each capture, we look for
1548 // new X-ray attacks from behind the capturing piece.
1549 swapList[0] = seeValues[capturedType];
1550 capturedType = type_of_piece_on(from);
1553 // Locate the least valuable attacker for the side to move. The loop
1554 // below looks like it is potentially infinite, but it isn't. We know
1555 // that the side to move still has at least one attacker left.
1556 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1559 // Remove the attacker we just found from the 'occupied' bitboard,
1560 // and scan for new X-ray attacks behind the attacker.
1561 b = stmAttackers & pieces(pt);
1562 occupied ^= (b & (~b + 1));
1563 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1564 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1566 attackers &= occupied; // Cut out pieces we've already done
1568 // Add the new entry to the swap list
1569 assert(slIndex < 32);
1570 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1573 // Remember the value of the capturing piece, and change the side to
1574 // move before beginning the next iteration.
1576 stm = opposite_color(stm);
1577 stmAttackers = attackers & pieces_of_color(stm);
1579 // Stop before processing a king capture
1580 if (capturedType == KING && stmAttackers)
1582 assert(slIndex < 32);
1583 swapList[slIndex++] = QueenValueMidgame*10;
1586 } while (stmAttackers);
1588 // Having built the swap list, we negamax through it to find the best
1589 // achievable score from the point of view of the side to move.
1591 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1597 /// Position::clear() erases the position object to a pristine state, with an
1598 /// empty board, white to move, and no castling rights.
1600 void Position::clear() {
1603 memset(st, 0, sizeof(StateInfo));
1604 st->epSquare = SQ_NONE;
1605 startPosPlyCounter = 0;
1608 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1609 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1610 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1611 memset(index, 0, sizeof(int) * 64);
1613 for (int i = 0; i < 64; i++)
1614 board[i] = PIECE_NONE;
1616 for (int i = 0; i < 8; i++)
1617 for (int j = 0; j < 16; j++)
1618 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1620 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1621 castleRightsMask[sq] = ALL_CASTLES;
1624 initialKFile = FILE_E;
1625 initialKRFile = FILE_H;
1626 initialQRFile = FILE_A;
1630 /// Position::put_piece() puts a piece on the given square of the board,
1631 /// updating the board array, pieces list, bitboards, and piece counts.
1633 void Position::put_piece(Piece p, Square s) {
1635 Color c = color_of_piece(p);
1636 PieceType pt = type_of_piece(p);
1639 index[s] = pieceCount[c][pt]++;
1640 pieceList[c][pt][index[s]] = s;
1642 set_bit(&(byTypeBB[pt]), s);
1643 set_bit(&(byColorBB[c]), s);
1644 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1648 /// Position::compute_key() computes the hash key of the position. The hash
1649 /// key is usually updated incrementally as moves are made and unmade, the
1650 /// compute_key() function is only used when a new position is set up, and
1651 /// to verify the correctness of the hash key when running in debug mode.
1653 Key Position::compute_key() const {
1655 Key result = zobCastle[st->castleRights];
1657 for (Square s = SQ_A1; s <= SQ_H8; s++)
1658 if (square_is_occupied(s))
1659 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1661 if (ep_square() != SQ_NONE)
1662 result ^= zobEp[ep_square()];
1664 if (side_to_move() == BLACK)
1665 result ^= zobSideToMove;
1671 /// Position::compute_pawn_key() computes the hash key of the position. The
1672 /// hash key is usually updated incrementally as moves are made and unmade,
1673 /// the compute_pawn_key() function is only used when a new position is set
1674 /// up, and to verify the correctness of the pawn hash key when running in
1677 Key Position::compute_pawn_key() const {
1682 for (Color c = WHITE; c <= BLACK; c++)
1684 b = pieces(PAWN, c);
1686 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1692 /// Position::compute_material_key() computes the hash key of the position.
1693 /// The hash key is usually updated incrementally as moves are made and unmade,
1694 /// the compute_material_key() function is only used when a new position is set
1695 /// up, and to verify the correctness of the material hash key when running in
1698 Key Position::compute_material_key() const {
1703 for (Color c = WHITE; c <= BLACK; c++)
1704 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1706 count = piece_count(c, pt);
1707 for (int i = 0; i < count; i++)
1708 result ^= zobrist[c][pt][i];
1714 /// Position::compute_value() compute the incremental scores for the middle
1715 /// game and the endgame. These functions are used to initialize the incremental
1716 /// scores when a new position is set up, and to verify that the scores are correctly
1717 /// updated by do_move and undo_move when the program is running in debug mode.
1718 Score Position::compute_value() const {
1721 Score result = SCORE_ZERO;
1723 for (Color c = WHITE; c <= BLACK; c++)
1724 for (PieceType pt = PAWN; pt <= KING; pt++)
1728 result += pst(c, pt, pop_1st_bit(&b));
1731 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1736 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1737 /// game material value for the given side. Material values are updated
1738 /// incrementally during the search, this function is only used while
1739 /// initializing a new Position object.
1741 Value Position::compute_non_pawn_material(Color c) const {
1743 Value result = VALUE_ZERO;
1745 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1746 result += piece_count(c, pt) * PieceValueMidgame[pt];
1752 /// Position::is_draw() tests whether the position is drawn by material,
1753 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1754 /// must be done by the search.
1755 template<bool SkipRepetition>
1756 bool Position::is_draw() const {
1758 // Draw by material?
1760 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1763 // Draw by the 50 moves rule?
1764 if (st->rule50 > 99 && !is_mate())
1767 // Draw by repetition?
1768 if (!SkipRepetition)
1769 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1770 if (history[st->gamePly - i] == st->key)
1776 // Explicit template instantiations
1777 template bool Position::is_draw<false>() const;
1778 template bool Position::is_draw<true>() const;
1781 /// Position::is_mate() returns true or false depending on whether the
1782 /// side to move is checkmated.
1784 bool Position::is_mate() const {
1786 MoveStack moves[MAX_MOVES];
1787 return in_check() && generate<MV_LEGAL>(*this, moves) == moves;
1791 /// Position::init() is a static member function which initializes at
1792 /// startup the various arrays used to compute hash keys and the piece
1793 /// square tables. The latter is a two-step operation: First, the white
1794 /// halves of the tables are copied from the MgPST[][] and EgPST[][] arrays.
1795 /// Second, the black halves of the tables are initialized by mirroring
1796 /// and changing the sign of the corresponding white scores.
1798 void Position::init() {
1802 for (Color c = WHITE; c <= BLACK; c++)
1803 for (PieceType pt = PAWN; pt <= KING; pt++)
1804 for (Square s = SQ_A1; s <= SQ_H8; s++)
1805 zobrist[c][pt][s] = rk.rand<Key>();
1807 for (Square s = SQ_A1; s <= SQ_H8; s++)
1808 zobEp[s] = rk.rand<Key>();
1810 for (int i = 0; i < 16; i++)
1811 zobCastle[i] = rk.rand<Key>();
1813 zobSideToMove = rk.rand<Key>();
1814 zobExclusion = rk.rand<Key>();
1816 for (Square s = SQ_A1; s <= SQ_H8; s++)
1817 for (Piece p = WP; p <= WK; p++)
1818 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1820 for (Square s = SQ_A1; s <= SQ_H8; s++)
1821 for (Piece p = BP; p <= BK; p++)
1822 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1826 /// Position::flip() flips position with the white and black sides reversed. This
1827 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1829 void Position::flip() {
1833 // Make a copy of current position before to start changing
1834 const Position pos(*this, threadID);
1837 threadID = pos.thread();
1840 for (Square s = SQ_A1; s <= SQ_H8; s++)
1841 if (!pos.square_is_empty(s))
1842 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1845 sideToMove = opposite_color(pos.side_to_move());
1848 if (pos.can_castle_kingside(WHITE)) set_castle_kingside(BLACK);
1849 if (pos.can_castle_queenside(WHITE)) set_castle_queenside(BLACK);
1850 if (pos.can_castle_kingside(BLACK)) set_castle_kingside(WHITE);
1851 if (pos.can_castle_queenside(BLACK)) set_castle_queenside(WHITE);
1853 initialKFile = pos.initialKFile;
1854 initialKRFile = pos.initialKRFile;
1855 initialQRFile = pos.initialQRFile;
1857 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1858 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1859 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1860 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1861 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1862 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1864 // En passant square
1865 if (pos.st->epSquare != SQ_NONE)
1866 st->epSquare = flip_square(pos.st->epSquare);
1872 st->key = compute_key();
1873 st->pawnKey = compute_pawn_key();
1874 st->materialKey = compute_material_key();
1876 // Incremental scores
1877 st->value = compute_value();
1880 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1881 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1887 /// Position::is_ok() performs some consitency checks for the position object.
1888 /// This is meant to be helpful when debugging.
1890 bool Position::is_ok(int* failedStep) const {
1892 // What features of the position should be verified?
1893 const bool debugAll = false;
1895 const bool debugBitboards = debugAll || false;
1896 const bool debugKingCount = debugAll || false;
1897 const bool debugKingCapture = debugAll || false;
1898 const bool debugCheckerCount = debugAll || false;
1899 const bool debugKey = debugAll || false;
1900 const bool debugMaterialKey = debugAll || false;
1901 const bool debugPawnKey = debugAll || false;
1902 const bool debugIncrementalEval = debugAll || false;
1903 const bool debugNonPawnMaterial = debugAll || false;
1904 const bool debugPieceCounts = debugAll || false;
1905 const bool debugPieceList = debugAll || false;
1906 const bool debugCastleSquares = debugAll || false;
1908 if (failedStep) *failedStep = 1;
1911 if (side_to_move() != WHITE && side_to_move() != BLACK)
1914 // Are the king squares in the position correct?
1915 if (failedStep) (*failedStep)++;
1916 if (piece_on(king_square(WHITE)) != WK)
1919 if (failedStep) (*failedStep)++;
1920 if (piece_on(king_square(BLACK)) != BK)
1924 if (failedStep) (*failedStep)++;
1925 if (!square_is_ok(make_square(initialKRFile, RANK_1)))
1928 if (!square_is_ok(make_square(initialQRFile, RANK_1)))
1931 // Do both sides have exactly one king?
1932 if (failedStep) (*failedStep)++;
1935 int kingCount[2] = {0, 0};
1936 for (Square s = SQ_A1; s <= SQ_H8; s++)
1937 if (type_of_piece_on(s) == KING)
1938 kingCount[color_of_piece_on(s)]++;
1940 if (kingCount[0] != 1 || kingCount[1] != 1)
1944 // Can the side to move capture the opponent's king?
1945 if (failedStep) (*failedStep)++;
1946 if (debugKingCapture)
1948 Color us = side_to_move();
1949 Color them = opposite_color(us);
1950 Square ksq = king_square(them);
1951 if (attackers_to(ksq) & pieces_of_color(us))
1955 // Is there more than 2 checkers?
1956 if (failedStep) (*failedStep)++;
1957 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1961 if (failedStep) (*failedStep)++;
1964 // The intersection of the white and black pieces must be empty
1965 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1968 // The union of the white and black pieces must be equal to all
1970 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1973 // Separate piece type bitboards must have empty intersections
1974 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1975 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1976 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1980 // En passant square OK?
1981 if (failedStep) (*failedStep)++;
1982 if (ep_square() != SQ_NONE)
1984 // The en passant square must be on rank 6, from the point of view of the
1986 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1991 if (failedStep) (*failedStep)++;
1992 if (debugKey && st->key != compute_key())
1995 // Pawn hash key OK?
1996 if (failedStep) (*failedStep)++;
1997 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2000 // Material hash key OK?
2001 if (failedStep) (*failedStep)++;
2002 if (debugMaterialKey && st->materialKey != compute_material_key())
2005 // Incremental eval OK?
2006 if (failedStep) (*failedStep)++;
2007 if (debugIncrementalEval && st->value != compute_value())
2010 // Non-pawn material OK?
2011 if (failedStep) (*failedStep)++;
2012 if (debugNonPawnMaterial)
2014 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2017 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2022 if (failedStep) (*failedStep)++;
2023 if (debugPieceCounts)
2024 for (Color c = WHITE; c <= BLACK; c++)
2025 for (PieceType pt = PAWN; pt <= KING; pt++)
2026 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2029 if (failedStep) (*failedStep)++;
2031 for (Color c = WHITE; c <= BLACK; c++)
2032 for (PieceType pt = PAWN; pt <= KING; pt++)
2033 for (int i = 0; i < pieceCount[c][pt]; i++)
2035 if (piece_on(piece_list(c, pt, i)) != make_piece(c, pt))
2038 if (index[piece_list(c, pt, i)] != i)
2042 if (failedStep) (*failedStep)++;
2043 if (debugCastleSquares)
2045 for (Color c = WHITE; c <= BLACK; c++)
2047 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != make_piece(c, ROOK))
2050 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != make_piece(c, ROOK))
2053 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2055 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2057 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2059 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2063 if (failedStep) *failedStep = 0;