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_from_char(col), rank_from_char(row));
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)
274 initialKRFile = square_file(sq);
278 else if (token == 'Q')
280 for (Square sq = sqA; sq <= sqH; sq++)
281 if (piece_on(sq) == rook)
284 initialQRFile = square_file(sq);
288 else if (token >= 'A' && token <= 'H')
290 File rookFile = File(token - 'A') + FILE_A;
291 if (rookFile < initialKFile)
294 initialQRFile = rookFile;
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 (move_promotion_piece(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 (move_promotion_piece(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, try to shortcut a common case
953 int cm = castleRightsMask[from] & castleRightsMask[to];
954 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
956 key ^= zobCastle[st->castleRights];
957 st->castleRights &= castleRightsMask[from];
958 st->castleRights &= castleRightsMask[to];
959 key ^= zobCastle[st->castleRights];
962 // Prefetch TT access as soon as we know key is updated
963 prefetch((char*)TT.first_entry(key));
966 Bitboard move_bb = make_move_bb(from, to);
967 do_move_bb(&(byColorBB[us]), move_bb);
968 do_move_bb(&(byTypeBB[pt]), move_bb);
969 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
971 board[to] = board[from];
972 board[from] = PIECE_NONE;
974 // Update piece lists, note that index[from] is not updated and
975 // becomes stale. This works as long as index[] is accessed just
976 // by known occupied squares.
977 index[to] = index[from];
978 pieceList[us][pt][index[to]] = to;
980 // If the moving piece was a pawn do some special extra work
983 // Reset rule 50 draw counter
986 // Update pawn hash key and prefetch in L1/L2 cache
987 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
989 // Set en passant square, only if moved pawn can be captured
990 if ((to ^ from) == 16)
992 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
994 st->epSquare = Square((int(from) + int(to)) / 2);
995 key ^= zobEp[st->epSquare];
999 if (pm) // promotion ?
1001 PieceType promotion = move_promotion_piece(m);
1003 assert(promotion >= KNIGHT && promotion <= QUEEN);
1005 // Insert promoted piece instead of pawn
1006 clear_bit(&(byTypeBB[PAWN]), to);
1007 set_bit(&(byTypeBB[promotion]), to);
1008 board[to] = make_piece(us, promotion);
1010 // Update piece counts
1011 pieceCount[us][promotion]++;
1012 pieceCount[us][PAWN]--;
1014 // Update material key
1015 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
1016 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
1018 // Update piece lists, move the last pawn at index[to] position
1019 // and shrink the list. Add a new promotion piece to the list.
1020 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
1021 index[lastPawnSquare] = index[to];
1022 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
1023 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
1024 index[to] = pieceCount[us][promotion] - 1;
1025 pieceList[us][promotion][index[to]] = to;
1027 // Partially revert hash keys update
1028 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
1029 st->pawnKey ^= zobrist[us][PAWN][to];
1031 // Partially revert and update incremental scores
1032 st->value -= pst(us, PAWN, to);
1033 st->value += pst(us, promotion, to);
1036 st->npMaterial[us] += PieceValueMidgame[promotion];
1040 // Prefetch pawn and material hash tables
1041 Threads[threadID].pawnTable.prefetch(st->pawnKey);
1042 Threads[threadID].materialTable.prefetch(st->materialKey);
1044 // Update incremental scores
1045 st->value += pst_delta(piece, from, to);
1047 // Set capture piece
1048 st->capturedType = capture;
1050 // Update the key with the final value
1053 // Update checkers bitboard, piece must be already moved
1054 st->checkersBB = EmptyBoardBB;
1059 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1063 if (bit_is_set(ci.checkSq[pt], to))
1064 st->checkersBB = SetMaskBB[to];
1067 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1070 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
1073 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
1079 sideToMove = opposite_color(sideToMove);
1080 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1086 /// Position::do_capture_move() is a private method used to update captured
1087 /// piece info. It is called from the main Position::do_move function.
1089 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1091 assert(capture != KING);
1095 // If the captured piece was a pawn, update pawn hash key,
1096 // otherwise update non-pawn material.
1097 if (capture == PAWN)
1099 if (ep) // en passant ?
1101 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1103 assert(to == st->epSquare);
1104 assert(relative_rank(opposite_color(them), to) == RANK_6);
1105 assert(piece_on(to) == PIECE_NONE);
1106 assert(piece_on(capsq) == make_piece(them, PAWN));
1108 board[capsq] = PIECE_NONE;
1110 st->pawnKey ^= zobrist[them][PAWN][capsq];
1113 st->npMaterial[them] -= PieceValueMidgame[capture];
1115 // Remove captured piece
1116 clear_bit(&(byColorBB[them]), capsq);
1117 clear_bit(&(byTypeBB[capture]), capsq);
1118 clear_bit(&(byTypeBB[0]), capsq);
1121 key ^= zobrist[them][capture][capsq];
1123 // Update incremental scores
1124 st->value -= pst(them, capture, capsq);
1126 // Update piece count
1127 pieceCount[them][capture]--;
1129 // Update material hash key
1130 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1132 // Update piece list, move the last piece at index[capsq] position
1134 // WARNING: This is a not perfectly revresible operation. When we
1135 // will reinsert the captured piece in undo_move() we will put it
1136 // at the end of the list and not in its original place, it means
1137 // index[] and pieceList[] are not guaranteed to be invariant to a
1138 // do_move() + undo_move() sequence.
1139 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1140 index[lastPieceSquare] = index[capsq];
1141 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1142 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1144 // Reset rule 50 counter
1149 /// Position::do_castle_move() is a private method used to make a castling
1150 /// move. It is called from the main Position::do_move function. Note that
1151 /// castling moves are encoded as "king captures friendly rook" moves, for
1152 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1154 void Position::do_castle_move(Move m) {
1156 assert(move_is_ok(m));
1157 assert(move_is_castle(m));
1159 Color us = side_to_move();
1160 Color them = opposite_color(us);
1162 // Reset capture field
1163 st->capturedType = PIECE_TYPE_NONE;
1165 // Find source squares for king and rook
1166 Square kfrom = move_from(m);
1167 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1170 assert(piece_on(kfrom) == make_piece(us, KING));
1171 assert(piece_on(rfrom) == make_piece(us, ROOK));
1173 // Find destination squares for king and rook
1174 if (rfrom > kfrom) // O-O
1176 kto = relative_square(us, SQ_G1);
1177 rto = relative_square(us, SQ_F1);
1179 kto = relative_square(us, SQ_C1);
1180 rto = relative_square(us, SQ_D1);
1183 // Remove pieces from source squares:
1184 clear_bit(&(byColorBB[us]), kfrom);
1185 clear_bit(&(byTypeBB[KING]), kfrom);
1186 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1187 clear_bit(&(byColorBB[us]), rfrom);
1188 clear_bit(&(byTypeBB[ROOK]), rfrom);
1189 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1191 // Put pieces on destination squares:
1192 set_bit(&(byColorBB[us]), kto);
1193 set_bit(&(byTypeBB[KING]), kto);
1194 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1195 set_bit(&(byColorBB[us]), rto);
1196 set_bit(&(byTypeBB[ROOK]), rto);
1197 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1199 // Update board array
1200 Piece king = make_piece(us, KING);
1201 Piece rook = make_piece(us, ROOK);
1202 board[kfrom] = board[rfrom] = PIECE_NONE;
1206 // Update piece lists
1207 pieceList[us][KING][index[kfrom]] = kto;
1208 pieceList[us][ROOK][index[rfrom]] = rto;
1209 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1210 index[kto] = index[kfrom];
1213 // Update incremental scores
1214 st->value += pst_delta(king, kfrom, kto);
1215 st->value += pst_delta(rook, rfrom, rto);
1218 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1219 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1221 // Clear en passant square
1222 if (st->epSquare != SQ_NONE)
1224 st->key ^= zobEp[st->epSquare];
1225 st->epSquare = SQ_NONE;
1228 // Update castling rights
1229 st->key ^= zobCastle[st->castleRights];
1230 st->castleRights &= castleRightsMask[kfrom];
1231 st->key ^= zobCastle[st->castleRights];
1233 // Reset rule 50 counter
1236 // Update checkers BB
1237 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1240 sideToMove = opposite_color(sideToMove);
1241 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1247 /// Position::undo_move() unmakes a move. When it returns, the position should
1248 /// be restored to exactly the same state as before the move was made.
1250 void Position::undo_move(Move m) {
1253 assert(move_is_ok(m));
1255 sideToMove = opposite_color(sideToMove);
1257 if (move_is_castle(m))
1259 undo_castle_move(m);
1263 Color us = side_to_move();
1264 Color them = opposite_color(us);
1265 Square from = move_from(m);
1266 Square to = move_to(m);
1267 bool ep = move_is_ep(m);
1268 bool pm = move_is_promotion(m);
1270 PieceType pt = type_of_piece_on(to);
1272 assert(square_is_empty(from));
1273 assert(color_of_piece_on(to) == us);
1274 assert(!pm || relative_rank(us, to) == RANK_8);
1275 assert(!ep || to == st->previous->epSquare);
1276 assert(!ep || relative_rank(us, to) == RANK_6);
1277 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1279 if (pm) // promotion ?
1281 PieceType promotion = move_promotion_piece(m);
1284 assert(promotion >= KNIGHT && promotion <= QUEEN);
1285 assert(piece_on(to) == make_piece(us, promotion));
1287 // Replace promoted piece with a pawn
1288 clear_bit(&(byTypeBB[promotion]), to);
1289 set_bit(&(byTypeBB[PAWN]), to);
1291 // Update piece counts
1292 pieceCount[us][promotion]--;
1293 pieceCount[us][PAWN]++;
1295 // Update piece list replacing promotion piece with a pawn
1296 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1297 index[lastPromotionSquare] = index[to];
1298 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1299 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1300 index[to] = pieceCount[us][PAWN] - 1;
1301 pieceList[us][PAWN][index[to]] = to;
1304 // Put the piece back at the source square
1305 Bitboard move_bb = make_move_bb(to, from);
1306 do_move_bb(&(byColorBB[us]), move_bb);
1307 do_move_bb(&(byTypeBB[pt]), move_bb);
1308 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1310 board[from] = make_piece(us, pt);
1311 board[to] = PIECE_NONE;
1313 // Update piece list
1314 index[from] = index[to];
1315 pieceList[us][pt][index[from]] = from;
1317 if (st->capturedType)
1322 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1324 assert(st->capturedType != KING);
1325 assert(!ep || square_is_empty(capsq));
1327 // Restore the captured piece
1328 set_bit(&(byColorBB[them]), capsq);
1329 set_bit(&(byTypeBB[st->capturedType]), capsq);
1330 set_bit(&(byTypeBB[0]), capsq);
1332 board[capsq] = make_piece(them, st->capturedType);
1334 // Update piece count
1335 pieceCount[them][st->capturedType]++;
1337 // Update piece list, add a new captured piece in capsq square
1338 index[capsq] = pieceCount[them][st->capturedType] - 1;
1339 pieceList[them][st->capturedType][index[capsq]] = capsq;
1342 // Finally point our state pointer back to the previous state
1349 /// Position::undo_castle_move() is a private method used to unmake a castling
1350 /// move. It is called from the main Position::undo_move function. Note that
1351 /// castling moves are encoded as "king captures friendly rook" moves, for
1352 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1354 void Position::undo_castle_move(Move m) {
1356 assert(move_is_ok(m));
1357 assert(move_is_castle(m));
1359 // When we have arrived here, some work has already been done by
1360 // Position::undo_move. In particular, the side to move has been switched,
1361 // so the code below is correct.
1362 Color us = side_to_move();
1364 // Find source squares for king and rook
1365 Square kfrom = move_from(m);
1366 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1369 // Find destination squares for king and rook
1370 if (rfrom > kfrom) // O-O
1372 kto = relative_square(us, SQ_G1);
1373 rto = relative_square(us, SQ_F1);
1375 kto = relative_square(us, SQ_C1);
1376 rto = relative_square(us, SQ_D1);
1379 assert(piece_on(kto) == make_piece(us, KING));
1380 assert(piece_on(rto) == make_piece(us, ROOK));
1382 // Remove pieces from destination squares:
1383 clear_bit(&(byColorBB[us]), kto);
1384 clear_bit(&(byTypeBB[KING]), kto);
1385 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1386 clear_bit(&(byColorBB[us]), rto);
1387 clear_bit(&(byTypeBB[ROOK]), rto);
1388 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1390 // Put pieces on source squares:
1391 set_bit(&(byColorBB[us]), kfrom);
1392 set_bit(&(byTypeBB[KING]), kfrom);
1393 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1394 set_bit(&(byColorBB[us]), rfrom);
1395 set_bit(&(byTypeBB[ROOK]), rfrom);
1396 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1399 board[rto] = board[kto] = PIECE_NONE;
1400 board[rfrom] = make_piece(us, ROOK);
1401 board[kfrom] = make_piece(us, KING);
1403 // Update piece lists
1404 pieceList[us][KING][index[kto]] = kfrom;
1405 pieceList[us][ROOK][index[rto]] = rfrom;
1406 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1407 index[kfrom] = index[kto];
1410 // Finally point our state pointer back to the previous state
1417 /// Position::do_null_move makes() a "null move": It switches the side to move
1418 /// and updates the hash key without executing any move on the board.
1420 void Position::do_null_move(StateInfo& backupSt) {
1423 assert(!in_check());
1425 // Back up the information necessary to undo the null move to the supplied
1426 // StateInfo object.
1427 // Note that differently from normal case here backupSt is actually used as
1428 // a backup storage not as a new state to be used.
1429 backupSt.key = st->key;
1430 backupSt.epSquare = st->epSquare;
1431 backupSt.value = st->value;
1432 backupSt.previous = st->previous;
1433 backupSt.pliesFromNull = st->pliesFromNull;
1434 st->previous = &backupSt;
1436 // Save the current key to the history[] array, in order to be able to
1437 // detect repetition draws.
1438 history[st->gamePly++] = st->key;
1440 // Update the necessary information
1441 if (st->epSquare != SQ_NONE)
1442 st->key ^= zobEp[st->epSquare];
1444 st->key ^= zobSideToMove;
1445 prefetch((char*)TT.first_entry(st->key));
1447 sideToMove = opposite_color(sideToMove);
1448 st->epSquare = SQ_NONE;
1450 st->pliesFromNull = 0;
1451 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1455 /// Position::undo_null_move() unmakes a "null move".
1457 void Position::undo_null_move() {
1460 assert(!in_check());
1462 // Restore information from the our backup StateInfo object
1463 StateInfo* backupSt = st->previous;
1464 st->key = backupSt->key;
1465 st->epSquare = backupSt->epSquare;
1466 st->value = backupSt->value;
1467 st->previous = backupSt->previous;
1468 st->pliesFromNull = backupSt->pliesFromNull;
1470 // Update the necessary information
1471 sideToMove = opposite_color(sideToMove);
1477 /// Position::see() is a static exchange evaluator: It tries to estimate the
1478 /// material gain or loss resulting from a move. There are three versions of
1479 /// this function: One which takes a destination square as input, one takes a
1480 /// move, and one which takes a 'from' and a 'to' square. The function does
1481 /// not yet understand promotions captures.
1483 int Position::see_sign(Move m) const {
1485 assert(move_is_ok(m));
1487 Square from = move_from(m);
1488 Square to = move_to(m);
1490 // Early return if SEE cannot be negative because captured piece value
1491 // is not less then capturing one. Note that king moves always return
1492 // here because king midgame value is set to 0.
1493 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1499 int Position::see(Move m) const {
1502 Bitboard occupied, attackers, stmAttackers, b;
1503 int swapList[32], slIndex = 1;
1504 PieceType capturedType, pt;
1507 assert(move_is_ok(m));
1509 // As castle moves are implemented as capturing the rook, they have
1510 // SEE == RookValueMidgame most of the times (unless the rook is under
1512 if (move_is_castle(m))
1515 from = move_from(m);
1517 capturedType = type_of_piece_on(to);
1518 occupied = occupied_squares();
1520 // Handle en passant moves
1521 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1523 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1525 assert(capturedType == PIECE_TYPE_NONE);
1526 assert(type_of_piece_on(capQq) == PAWN);
1528 // Remove the captured pawn
1529 clear_bit(&occupied, capQq);
1530 capturedType = PAWN;
1533 // Find all attackers to the destination square, with the moving piece
1534 // removed, but possibly an X-ray attacker added behind it.
1535 clear_bit(&occupied, from);
1536 attackers = attackers_to(to, occupied);
1538 // If the opponent has no attackers we are finished
1539 stm = opposite_color(color_of_piece_on(from));
1540 stmAttackers = attackers & pieces_of_color(stm);
1542 return seeValues[capturedType];
1544 // The destination square is defended, which makes things rather more
1545 // difficult to compute. We proceed by building up a "swap list" containing
1546 // the material gain or loss at each stop in a sequence of captures to the
1547 // destination square, where the sides alternately capture, and always
1548 // capture with the least valuable piece. After each capture, we look for
1549 // new X-ray attacks from behind the capturing piece.
1550 swapList[0] = seeValues[capturedType];
1551 capturedType = type_of_piece_on(from);
1554 // Locate the least valuable attacker for the side to move. The loop
1555 // below looks like it is potentially infinite, but it isn't. We know
1556 // that the side to move still has at least one attacker left.
1557 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1560 // Remove the attacker we just found from the 'occupied' bitboard,
1561 // and scan for new X-ray attacks behind the attacker.
1562 b = stmAttackers & pieces(pt);
1563 occupied ^= (b & (~b + 1));
1564 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1565 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1567 attackers &= occupied; // Cut out pieces we've already done
1569 // Add the new entry to the swap list
1570 assert(slIndex < 32);
1571 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1574 // Remember the value of the capturing piece, and change the side to
1575 // move before beginning the next iteration.
1577 stm = opposite_color(stm);
1578 stmAttackers = attackers & pieces_of_color(stm);
1580 // Stop before processing a king capture
1581 if (capturedType == KING && stmAttackers)
1583 assert(slIndex < 32);
1584 swapList[slIndex++] = QueenValueMidgame*10;
1587 } while (stmAttackers);
1589 // Having built the swap list, we negamax through it to find the best
1590 // achievable score from the point of view of the side to move.
1592 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1598 /// Position::clear() erases the position object to a pristine state, with an
1599 /// empty board, white to move, and no castling rights.
1601 void Position::clear() {
1604 memset(st, 0, sizeof(StateInfo));
1605 st->epSquare = SQ_NONE;
1606 startPosPlyCounter = 0;
1609 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1610 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1611 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1612 memset(index, 0, sizeof(int) * 64);
1614 for (int i = 0; i < 64; i++)
1615 board[i] = PIECE_NONE;
1617 for (int i = 0; i < 8; i++)
1618 for (int j = 0; j < 16; j++)
1619 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1621 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1622 castleRightsMask[sq] = ALL_CASTLES;
1625 initialKFile = FILE_E;
1626 initialKRFile = FILE_H;
1627 initialQRFile = FILE_A;
1631 /// Position::put_piece() puts a piece on the given square of the board,
1632 /// updating the board array, pieces list, bitboards, and piece counts.
1634 void Position::put_piece(Piece p, Square s) {
1636 Color c = color_of_piece(p);
1637 PieceType pt = type_of_piece(p);
1640 index[s] = pieceCount[c][pt]++;
1641 pieceList[c][pt][index[s]] = s;
1643 set_bit(&(byTypeBB[pt]), s);
1644 set_bit(&(byColorBB[c]), s);
1645 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1649 /// Position::compute_key() computes the hash key of the position. The hash
1650 /// key is usually updated incrementally as moves are made and unmade, the
1651 /// compute_key() function is only used when a new position is set up, and
1652 /// to verify the correctness of the hash key when running in debug mode.
1654 Key Position::compute_key() const {
1656 Key result = zobCastle[st->castleRights];
1658 for (Square s = SQ_A1; s <= SQ_H8; s++)
1659 if (square_is_occupied(s))
1660 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1662 if (ep_square() != SQ_NONE)
1663 result ^= zobEp[ep_square()];
1665 if (side_to_move() == BLACK)
1666 result ^= zobSideToMove;
1672 /// Position::compute_pawn_key() computes the hash key of the position. The
1673 /// hash key is usually updated incrementally as moves are made and unmade,
1674 /// the compute_pawn_key() function is only used when a new position is set
1675 /// up, and to verify the correctness of the pawn hash key when running in
1678 Key Position::compute_pawn_key() const {
1683 for (Color c = WHITE; c <= BLACK; c++)
1685 b = pieces(PAWN, c);
1687 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1693 /// Position::compute_material_key() computes the hash key of the position.
1694 /// The hash key is usually updated incrementally as moves are made and unmade,
1695 /// the compute_material_key() function is only used when a new position is set
1696 /// up, and to verify the correctness of the material hash key when running in
1699 Key Position::compute_material_key() const {
1704 for (Color c = WHITE; c <= BLACK; c++)
1705 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1707 count = piece_count(c, pt);
1708 for (int i = 0; i < count; i++)
1709 result ^= zobrist[c][pt][i];
1715 /// Position::compute_value() compute the incremental scores for the middle
1716 /// game and the endgame. These functions are used to initialize the incremental
1717 /// scores when a new position is set up, and to verify that the scores are correctly
1718 /// updated by do_move and undo_move when the program is running in debug mode.
1719 Score Position::compute_value() const {
1722 Score result = SCORE_ZERO;
1724 for (Color c = WHITE; c <= BLACK; c++)
1725 for (PieceType pt = PAWN; pt <= KING; pt++)
1729 result += pst(c, pt, pop_1st_bit(&b));
1732 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1737 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1738 /// game material value for the given side. Material values are updated
1739 /// incrementally during the search, this function is only used while
1740 /// initializing a new Position object.
1742 Value Position::compute_non_pawn_material(Color c) const {
1744 Value result = VALUE_ZERO;
1746 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1747 result += piece_count(c, pt) * PieceValueMidgame[pt];
1753 /// Position::is_draw() tests whether the position is drawn by material,
1754 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1755 /// must be done by the search.
1756 template<bool SkipRepetition>
1757 bool Position::is_draw() const {
1759 // Draw by material?
1761 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1764 // Draw by the 50 moves rule?
1765 if (st->rule50 > 99 && !is_mate())
1768 // Draw by repetition?
1769 if (!SkipRepetition)
1770 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1771 if (history[st->gamePly - i] == st->key)
1777 // Explicit template instantiations
1778 template bool Position::is_draw<false>() const;
1779 template bool Position::is_draw<true>() const;
1782 /// Position::is_mate() returns true or false depending on whether the
1783 /// side to move is checkmated.
1785 bool Position::is_mate() const {
1787 MoveStack moves[MAX_MOVES];
1788 return in_check() && generate<MV_LEGAL>(*this, moves) == moves;
1792 /// Position::init_zobrist() is a static member function which initializes at
1793 /// startup the various arrays used to compute hash keys.
1795 void Position::init_zobrist() {
1800 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1801 zobrist[i][j][k] = rk.rand<Key>();
1803 for (i = 0; i < 64; i++)
1804 zobEp[i] = rk.rand<Key>();
1806 for (i = 0; i < 16; i++)
1807 zobCastle[i] = rk.rand<Key>();
1809 zobSideToMove = rk.rand<Key>();
1810 zobExclusion = rk.rand<Key>();
1814 /// Position::init_piece_square_tables() initializes the piece square tables.
1815 /// This is a two-step operation: First, the white halves of the tables are
1816 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1817 /// of the tables are initialized by mirroring and changing the sign of the
1818 /// corresponding white scores.
1820 void Position::init_piece_square_tables() {
1822 for (Square s = SQ_A1; s <= SQ_H8; s++)
1823 for (Piece p = WP; p <= WK; p++)
1824 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1826 for (Square s = SQ_A1; s <= SQ_H8; s++)
1827 for (Piece p = BP; p <= BK; p++)
1828 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1832 /// Position::flip() flips position with the white and black sides reversed. This
1833 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1835 void Position::flip() {
1839 // Make a copy of current position before to start changing
1840 const Position pos(*this, threadID);
1843 threadID = pos.thread();
1846 for (Square s = SQ_A1; s <= SQ_H8; s++)
1847 if (!pos.square_is_empty(s))
1848 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1851 sideToMove = opposite_color(pos.side_to_move());
1854 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1855 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1856 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1857 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1859 initialKFile = pos.initialKFile;
1860 initialKRFile = pos.initialKRFile;
1861 initialQRFile = pos.initialQRFile;
1863 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1864 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1865 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1866 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1867 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1868 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1870 // En passant square
1871 if (pos.st->epSquare != SQ_NONE)
1872 st->epSquare = flip_square(pos.st->epSquare);
1878 st->key = compute_key();
1879 st->pawnKey = compute_pawn_key();
1880 st->materialKey = compute_material_key();
1882 // Incremental scores
1883 st->value = compute_value();
1886 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1887 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1893 /// Position::is_ok() performs some consitency checks for the position object.
1894 /// This is meant to be helpful when debugging.
1896 bool Position::is_ok(int* failedStep) const {
1898 // What features of the position should be verified?
1899 const bool debugAll = false;
1901 const bool debugBitboards = debugAll || false;
1902 const bool debugKingCount = debugAll || false;
1903 const bool debugKingCapture = debugAll || false;
1904 const bool debugCheckerCount = debugAll || false;
1905 const bool debugKey = debugAll || false;
1906 const bool debugMaterialKey = debugAll || false;
1907 const bool debugPawnKey = debugAll || false;
1908 const bool debugIncrementalEval = debugAll || false;
1909 const bool debugNonPawnMaterial = debugAll || false;
1910 const bool debugPieceCounts = debugAll || false;
1911 const bool debugPieceList = debugAll || false;
1912 const bool debugCastleSquares = debugAll || false;
1914 if (failedStep) *failedStep = 1;
1917 if (!color_is_ok(side_to_move()))
1920 // Are the king squares in the position correct?
1921 if (failedStep) (*failedStep)++;
1922 if (piece_on(king_square(WHITE)) != WK)
1925 if (failedStep) (*failedStep)++;
1926 if (piece_on(king_square(BLACK)) != BK)
1930 if (failedStep) (*failedStep)++;
1931 if (!file_is_ok(initialKRFile))
1934 if (!file_is_ok(initialQRFile))
1937 // Do both sides have exactly one king?
1938 if (failedStep) (*failedStep)++;
1941 int kingCount[2] = {0, 0};
1942 for (Square s = SQ_A1; s <= SQ_H8; s++)
1943 if (type_of_piece_on(s) == KING)
1944 kingCount[color_of_piece_on(s)]++;
1946 if (kingCount[0] != 1 || kingCount[1] != 1)
1950 // Can the side to move capture the opponent's king?
1951 if (failedStep) (*failedStep)++;
1952 if (debugKingCapture)
1954 Color us = side_to_move();
1955 Color them = opposite_color(us);
1956 Square ksq = king_square(them);
1957 if (attackers_to(ksq) & pieces_of_color(us))
1961 // Is there more than 2 checkers?
1962 if (failedStep) (*failedStep)++;
1963 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1967 if (failedStep) (*failedStep)++;
1970 // The intersection of the white and black pieces must be empty
1971 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1974 // The union of the white and black pieces must be equal to all
1976 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1979 // Separate piece type bitboards must have empty intersections
1980 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1981 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1982 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1986 // En passant square OK?
1987 if (failedStep) (*failedStep)++;
1988 if (ep_square() != SQ_NONE)
1990 // The en passant square must be on rank 6, from the point of view of the
1992 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1997 if (failedStep) (*failedStep)++;
1998 if (debugKey && st->key != compute_key())
2001 // Pawn hash key OK?
2002 if (failedStep) (*failedStep)++;
2003 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2006 // Material hash key OK?
2007 if (failedStep) (*failedStep)++;
2008 if (debugMaterialKey && st->materialKey != compute_material_key())
2011 // Incremental eval OK?
2012 if (failedStep) (*failedStep)++;
2013 if (debugIncrementalEval && st->value != compute_value())
2016 // Non-pawn material OK?
2017 if (failedStep) (*failedStep)++;
2018 if (debugNonPawnMaterial)
2020 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2023 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2028 if (failedStep) (*failedStep)++;
2029 if (debugPieceCounts)
2030 for (Color c = WHITE; c <= BLACK; c++)
2031 for (PieceType pt = PAWN; pt <= KING; pt++)
2032 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2035 if (failedStep) (*failedStep)++;
2037 for (Color c = WHITE; c <= BLACK; c++)
2038 for (PieceType pt = PAWN; pt <= KING; pt++)
2039 for (int i = 0; i < pieceCount[c][pt]; i++)
2041 if (piece_on(piece_list(c, pt, i)) != make_piece(c, pt))
2044 if (index[piece_list(c, pt, i)] != i)
2048 if (failedStep) (*failedStep)++;
2049 if (debugCastleSquares)
2051 for (Color c = WHITE; c <= BLACK; c++)
2053 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != make_piece(c, ROOK))
2056 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != make_piece(c, ROOK))
2059 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2061 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2063 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2065 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2069 if (failedStep) *failedStep = 0;