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);
90 Square ksq = pos.king_square(them);
92 dcCandidates = pos.discovered_check_candidates(us);
93 pinned = pos.pinned_pieces(us);
95 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
96 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
97 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
98 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
99 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
100 checkSq[KING] = EmptyBoardBB;
104 /// Position c'tors. Here we always create a copy of the original position
105 /// or the FEN string, we want the new born Position object do not depend
106 /// on any external data so we detach state pointer from the source one.
108 Position::Position(const Position& pos, int th) {
110 memcpy(this, &pos, sizeof(Position));
111 detach(); // Always detach() in copy c'tor to avoid surprises
116 Position::Position(const string& fen, bool isChess960, int th) {
118 from_fen(fen, isChess960);
123 /// Position::detach() copies the content of the current state and castling
124 /// masks inside the position itself. This is needed when the st pointee could
125 /// become stale, as example because the caller is about to going out of scope.
127 void Position::detach() {
131 st->previous = NULL; // as a safe guard
135 /// Position::from_fen() initializes the position object with the given FEN
136 /// string. This function is not very robust - make sure that input FENs are
137 /// correct (this is assumed to be the responsibility of the GUI).
139 void Position::from_fen(const string& fen, bool isChess960) {
141 A FEN string defines a particular position using only the ASCII character set.
143 A FEN string contains six fields. The separator between fields is a space. The fields are:
145 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
146 with rank 1; within each rank, the contents of each square are described from file A through file H.
147 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
148 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
149 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
150 of blank squares), and "/" separate ranks.
152 2) Active color. "w" means white moves next, "b" means black.
154 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
155 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
156 kingside), and/or "q" (Black can castle queenside).
158 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
159 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
160 regardless of whether there is a pawn in position to make an en passant capture.
162 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
163 to determine if a draw can be claimed under the fifty-move rule.
165 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
172 std::istringstream ss(fen);
177 // 1. Piece placement field
178 while ((ss >> token) && !isspace(token))
180 if ((p = PieceToChar.find(token)) != string::npos)
182 put_piece(Piece(p), sq);
185 else if (isdigit(token))
186 sq += Square(token - '0'); // Skip the given number of files
187 else if (token == '/')
188 sq -= SQ_A3; // Jump back of 2 rows
194 if (!(ss >> token) || (token != 'w' && token != 'b'))
197 sideToMove = (token == 'w' ? WHITE : BLACK);
199 if (!(ss >> token) || !isspace(token))
202 // 3. Castling availability
203 while ((ss >> token) && !isspace(token))
204 if (!set_castling_rights(token))
207 // 4. En passant square
209 if ( ((ss >> col) && (col >= 'a' && col <= 'h'))
210 && ((ss >> row) && (row == '3' || row == '6')))
212 st->epSquare = make_square(File(col - 'a') + FILE_A, Rank(row - '1') + RANK_1);
214 // Ignore if no capture is possible
215 Color them = opposite_color(sideToMove);
216 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
217 st->epSquare = SQ_NONE;
221 if (ss >> std::skipws >> hmc)
224 // 6. Fullmove number
226 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
228 // Various initialisations
229 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
230 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
231 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
232 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
233 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
234 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
236 chess960 = isChess960;
239 st->key = compute_key();
240 st->pawnKey = compute_pawn_key();
241 st->materialKey = compute_material_key();
242 st->value = compute_value();
243 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
244 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
248 cout << "Error in FEN string: " << fen << endl;
252 /// Position::set_castling_rights() sets castling parameters castling avaiability.
253 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
254 /// that uses the letters of the columns on which the rooks began the game instead
255 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
256 /// associated with the castling right, the traditional castling tag will be replaced
257 /// by the file letter of the involved rook as for the Shredder-FEN.
259 bool Position::set_castling_rights(char token) {
261 Color c = token >= 'a' ? BLACK : WHITE;
262 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
263 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
264 Piece rook = (c == WHITE ? WR : BR);
266 initialKFile = square_file(king_square(c));
267 token = char(toupper(token));
271 for (Square sq = sqH; sq >= sqA; sq--)
272 if (piece_on(sq) == rook)
274 set_castle_kingside(c);
275 initialKRFile = square_file(sq);
279 else if (token == 'Q')
281 for (Square sq = sqA; sq <= sqH; sq++)
282 if (piece_on(sq) == rook)
284 set_castle_queenside(c);
285 initialQRFile = square_file(sq);
289 else if (token >= 'A' && token <= 'H')
291 File rookFile = File(token - 'A') + FILE_A;
292 if (rookFile < initialKFile)
294 set_castle_queenside(c);
295 initialQRFile = rookFile;
299 set_castle_kingside(c);
300 initialKRFile = rookFile;
310 /// Position::to_fen() returns a FEN representation of the position. In case
311 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
313 const string Position::to_fen() const {
319 for (Rank rank = RANK_8; rank >= RANK_1; rank--, fen += '/')
323 for (File file = FILE_A; file <= FILE_H; file++)
325 sq = make_square(file, rank);
327 if (square_is_occupied(sq))
334 fen += PieceToChar[piece_on(sq)];
343 fen += (sideToMove == WHITE ? " w " : " b ");
345 if (st->castleRights != CASTLES_NONE)
347 if (can_castle_kingside(WHITE))
348 fen += chess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
350 if (can_castle_queenside(WHITE))
351 fen += chess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
353 if (can_castle_kingside(BLACK))
354 fen += chess960 ? file_to_char(initialKRFile) : 'k';
356 if (can_castle_queenside(BLACK))
357 fen += chess960 ? file_to_char(initialQRFile) : 'q';
361 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
366 /// Position::print() prints an ASCII representation of the position to
367 /// the standard output. If a move is given then also the san is printed.
369 void Position::print(Move move) const {
371 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
375 Position p(*this, thread());
376 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
377 cout << "\nMove is: " << dd << move_to_san(p, move);
380 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
382 cout << dottedLine << '|';
383 for (File file = FILE_A; file <= FILE_H; file++)
385 Square sq = make_square(file, rank);
386 Piece piece = piece_on(sq);
388 if (piece == PIECE_NONE && square_color(sq) == DARK)
389 piece = PIECE_NONE_DARK_SQ;
391 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
392 cout << c << PieceToChar[piece] << c << '|';
395 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
399 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
400 /// king) pieces for the given color and for the given pinner type. Or, when
401 /// template parameter FindPinned is false, the pieces of the given color
402 /// candidate for a discovery check against the enemy king.
403 /// Bitboard checkersBB must be already updated when looking for pinners.
405 template<bool FindPinned>
406 Bitboard Position::hidden_checkers(Color c) const {
408 Bitboard result = EmptyBoardBB;
409 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
411 // Pinned pieces protect our king, dicovery checks attack
413 Square ksq = king_square(FindPinned ? c : opposite_color(c));
415 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
416 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
418 if (FindPinned && pinners)
419 pinners &= ~st->checkersBB;
423 Square s = pop_1st_bit(&pinners);
424 Bitboard b = squares_between(s, ksq) & occupied_squares();
428 if ( !(b & (b - 1)) // Only one bit set?
429 && (b & pieces_of_color(c))) // Is an our piece?
436 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
437 /// king) pieces for the given color. Note that checkersBB bitboard must
438 /// be already updated.
440 Bitboard Position::pinned_pieces(Color c) const {
442 return hidden_checkers<true>(c);
446 /// Position:discovered_check_candidates() returns a bitboard containing all
447 /// pieces for the given side which are candidates for giving a discovered
448 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
449 /// to be already updated.
451 Bitboard Position::discovered_check_candidates(Color c) const {
453 return hidden_checkers<false>(c);
456 /// Position::attackers_to() computes a bitboard containing all pieces which
457 /// attacks a given square.
459 Bitboard Position::attackers_to(Square s) const {
461 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
462 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
463 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
464 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
465 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
466 | (attacks_from<KING>(s) & pieces(KING));
469 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
471 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
472 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
473 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
474 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
475 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
476 | (attacks_from<KING>(s) & pieces(KING));
479 /// Position::attacks_from() computes a bitboard of all attacks
480 /// of a given piece put in a given square.
482 Bitboard Position::attacks_from(Piece p, Square s) const {
484 assert(square_is_ok(s));
488 case WB: case BB: return attacks_from<BISHOP>(s);
489 case WR: case BR: return attacks_from<ROOK>(s);
490 case WQ: case BQ: return attacks_from<QUEEN>(s);
491 default: return StepAttacksBB[p][s];
495 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
497 assert(square_is_ok(s));
501 case WB: case BB: return bishop_attacks_bb(s, occ);
502 case WR: case BR: return rook_attacks_bb(s, occ);
503 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
504 default: return StepAttacksBB[p][s];
509 /// Position::move_attacks_square() tests whether a move from the current
510 /// position attacks a given square.
512 bool Position::move_attacks_square(Move m, Square s) const {
514 assert(move_is_ok(m));
515 assert(square_is_ok(s));
518 Square f = move_from(m), t = move_to(m);
520 assert(square_is_occupied(f));
522 if (bit_is_set(attacks_from(piece_on(f), t), s))
525 // Move the piece and scan for X-ray attacks behind it
526 occ = occupied_squares();
527 do_move_bb(&occ, make_move_bb(f, t));
528 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
529 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
530 & pieces_of_color(color_of_piece_on(f));
532 // If we have attacks we need to verify that are caused by our move
533 // and are not already existent ones.
534 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
538 /// Position::find_checkers() computes the checkersBB bitboard, which
539 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
540 /// currently works by calling Position::attackers_to, which is probably
541 /// inefficient. Consider rewriting this function to use the last move
542 /// played, like in non-bitboard versions of Glaurung.
544 void Position::find_checkers() {
546 Color us = side_to_move();
547 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
551 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
553 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
556 assert(move_is_ok(m));
557 assert(pinned == pinned_pieces(side_to_move()));
559 Color us = side_to_move();
560 Square from = move_from(m);
562 assert(color_of_piece_on(from) == us);
563 assert(piece_on(king_square(us)) == make_piece(us, KING));
565 // En passant captures are a tricky special case. Because they are
566 // rather uncommon, we do it simply by testing whether the king is attacked
567 // after the move is made
570 Color them = opposite_color(us);
571 Square to = move_to(m);
572 Square capsq = make_square(square_file(to), square_rank(from));
573 Square ksq = king_square(us);
574 Bitboard b = occupied_squares();
576 assert(to == ep_square());
577 assert(piece_on(from) == make_piece(us, PAWN));
578 assert(piece_on(capsq) == make_piece(them, PAWN));
579 assert(piece_on(to) == PIECE_NONE);
582 clear_bit(&b, capsq);
585 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
586 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
589 // If the moving piece is a king, check whether the destination
590 // square is attacked by the opponent. Castling moves are checked
591 // for legality during move generation.
592 if (type_of_piece_on(from) == KING)
593 return move_is_castle(m) || !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
595 // A non-king move is legal if and only if it is not pinned or it
596 // is moving along the ray towards or away from the king.
598 || !bit_is_set(pinned, from)
599 || squares_aligned(from, move_to(m), king_square(us));
603 /// Position::move_is_pl_slow() takes a position and a move and tests whether
604 /// the move is pseudo legal. This version is not very fast and should be used
605 /// only in non time-critical paths.
607 bool Position::move_is_pl_slow(const Move m) const {
609 MoveStack mlist[MAX_MOVES];
610 MoveStack *cur, *last;
612 last = in_check() ? generate<MV_EVASION>(*this, mlist)
613 : generate<MV_NON_EVASION>(*this, mlist);
615 for (cur = mlist; cur != last; cur++)
623 /// Fast version of Position::move_is_pl() that takes a position a move and a
624 /// bitboard of pinned pieces as input, and tests whether the move is pseudo legal.
626 bool Position::move_is_pl(const Move m) const {
630 Color us = sideToMove;
631 Color them = opposite_color(sideToMove);
632 Square from = move_from(m);
633 Square to = move_to(m);
634 Piece pc = piece_on(from);
636 // Use a slower but simpler function for uncommon cases
637 if (move_is_special(m))
638 return move_is_pl_slow(m);
640 // Is not a promotion, so promotion piece must be empty
641 if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
644 // If the from square is not occupied by a piece belonging to the side to
645 // move, the move is obviously not legal.
646 if (pc == PIECE_NONE || color_of_piece(pc) != us)
649 // The destination square cannot be occupied by a friendly piece
650 if (color_of_piece_on(to) == us)
653 // Handle the special case of a pawn move
654 if (type_of_piece(pc) == PAWN)
656 // Move direction must be compatible with pawn color
657 int direction = to - from;
658 if ((us == WHITE) != (direction > 0))
661 // We have already handled promotion moves, so destination
662 // cannot be on the 8/1th rank.
663 if (square_rank(to) == RANK_8 || square_rank(to) == RANK_1)
666 // Proceed according to the square delta between the origin and
667 // destination squares.
674 // Capture. The destination square must be occupied by an enemy
675 // piece (en passant captures was handled earlier).
676 if (color_of_piece_on(to) != them)
679 // From and to files must be one file apart, avoids a7h5
680 if (abs(square_file(from) - square_file(to)) != 1)
686 // Pawn push. The destination square must be empty.
687 if (!square_is_empty(to))
692 // Double white pawn push. The destination square must be on the fourth
693 // rank, and both the destination square and the square between the
694 // source and destination squares must be empty.
695 if ( square_rank(to) != RANK_4
696 || !square_is_empty(to)
697 || !square_is_empty(from + DELTA_N))
702 // Double black pawn push. The destination square must be on the fifth
703 // rank, and both the destination square and the square between the
704 // source and destination squares must be empty.
705 if ( square_rank(to) != RANK_5
706 || !square_is_empty(to)
707 || !square_is_empty(from + DELTA_S))
715 else if (!bit_is_set(attacks_from(pc, from), to))
720 // In case of king moves under check we have to remove king so to catch
721 // as invalid moves like b1a1 when opposite queen is on c1.
722 if (type_of_piece_on(from) == KING)
724 Bitboard b = occupied_squares();
726 if (attackers_to(move_to(m), b) & pieces_of_color(opposite_color(us)))
731 Bitboard target = checkers();
732 Square checksq = pop_1st_bit(&target);
734 if (target) // double check ? In this case a king move is required
737 // Our move must be a blocking evasion or a capture of the checking piece
738 target = squares_between(checksq, king_square(us)) | checkers();
739 if (!bit_is_set(target, move_to(m)))
748 /// Position::move_gives_check() tests whether a pseudo-legal move is a check
750 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
753 assert(move_is_ok(m));
754 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
755 assert(color_of_piece_on(move_from(m)) == side_to_move());
757 Square from = move_from(m);
758 Square to = move_to(m);
759 PieceType pt = type_of_piece_on(from);
762 if (bit_is_set(ci.checkSq[pt], to))
766 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
768 // For pawn and king moves we need to verify also direction
769 if ( (pt != PAWN && pt != KING)
770 || !squares_aligned(from, to, king_square(opposite_color(side_to_move()))))
774 // Can we skip the ugly special cases ?
775 if (!move_is_special(m))
778 Color us = side_to_move();
779 Bitboard b = occupied_squares();
780 Square ksq = king_square(opposite_color(us));
782 // Promotion with check ?
783 if (move_is_promotion(m))
787 switch (promotion_piece_type(m))
790 return bit_is_set(attacks_from<KNIGHT>(to), ksq);
792 return bit_is_set(bishop_attacks_bb(to, b), ksq);
794 return bit_is_set(rook_attacks_bb(to, b), ksq);
796 return bit_is_set(queen_attacks_bb(to, b), ksq);
802 // En passant capture with check ? We have already handled the case
803 // of direct checks and ordinary discovered check, the only case we
804 // need to handle is the unusual case of a discovered check through
805 // the captured pawn.
808 Square capsq = make_square(square_file(to), square_rank(from));
810 clear_bit(&b, capsq);
812 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
813 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
816 // Castling with check ?
817 if (move_is_castle(m))
819 Square kfrom, kto, rfrom, rto;
825 kto = relative_square(us, SQ_G1);
826 rto = relative_square(us, SQ_F1);
828 kto = relative_square(us, SQ_C1);
829 rto = relative_square(us, SQ_D1);
831 clear_bit(&b, kfrom);
832 clear_bit(&b, rfrom);
835 return bit_is_set(rook_attacks_bb(rto, b), ksq);
842 /// Position::do_setup_move() makes a permanent move on the board. It should
843 /// be used when setting up a position on board. You can't undo the move.
845 void Position::do_setup_move(Move m) {
851 // Reset "game ply" in case we made a non-reversible move.
852 // "game ply" is used for repetition detection.
856 // Update the number of plies played from the starting position
857 startPosPlyCounter++;
859 // Our StateInfo newSt is about going out of scope so copy
860 // its content before it disappears.
865 /// Position::do_move() makes a move, and saves all information necessary
866 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
867 /// moves should be filtered out before this function is called.
869 void Position::do_move(Move m, StateInfo& newSt) {
872 do_move(m, newSt, ci, move_gives_check(m, ci));
875 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
878 assert(move_is_ok(m));
879 assert(&newSt != st);
884 // Copy some fields of old state to our new StateInfo object except the
885 // ones which are recalculated from scratch anyway, then switch our state
886 // pointer to point to the new, ready to be updated, state.
887 struct ReducedStateInfo {
888 Key pawnKey, materialKey;
889 int castleRights, rule50, gamePly, pliesFromNull;
895 memcpy(&newSt, st, sizeof(ReducedStateInfo));
900 // Save the current key to the history[] array, in order to be able to
901 // detect repetition draws.
902 history[st->gamePly++] = key;
904 // Update side to move
905 key ^= zobSideToMove;
907 // Increment the 50 moves rule draw counter. Resetting it to zero in the
908 // case of non-reversible moves is taken care of later.
912 if (move_is_castle(m))
919 Color us = side_to_move();
920 Color them = opposite_color(us);
921 Square from = move_from(m);
922 Square to = move_to(m);
923 bool ep = move_is_ep(m);
924 bool pm = move_is_promotion(m);
926 Piece piece = piece_on(from);
927 PieceType pt = type_of_piece(piece);
928 PieceType capture = ep ? PAWN : type_of_piece_on(to);
930 assert(color_of_piece_on(from) == us);
931 assert(color_of_piece_on(to) == them || square_is_empty(to));
932 assert(!(ep || pm) || piece == make_piece(us, PAWN));
933 assert(!pm || relative_rank(us, to) == RANK_8);
936 do_capture_move(key, capture, them, to, ep);
939 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
941 // Reset en passant square
942 if (st->epSquare != SQ_NONE)
944 key ^= zobEp[st->epSquare];
945 st->epSquare = SQ_NONE;
948 // Update castle rights if needed
949 if ( st->castleRights != CASTLES_NONE
950 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
952 key ^= zobCastle[st->castleRights];
953 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
954 key ^= zobCastle[st->castleRights];
957 // Prefetch TT access as soon as we know key is updated
958 prefetch((char*)TT.first_entry(key));
961 Bitboard move_bb = make_move_bb(from, to);
962 do_move_bb(&(byColorBB[us]), move_bb);
963 do_move_bb(&(byTypeBB[pt]), move_bb);
964 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
966 board[to] = board[from];
967 board[from] = PIECE_NONE;
969 // Update piece lists, note that index[from] is not updated and
970 // becomes stale. This works as long as index[] is accessed just
971 // by known occupied squares.
972 index[to] = index[from];
973 pieceList[us][pt][index[to]] = to;
975 // If the moving piece was a pawn do some special extra work
978 // Reset rule 50 draw counter
981 // Update pawn hash key and prefetch in L1/L2 cache
982 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
984 // Set en passant square, only if moved pawn can be captured
985 if ((to ^ from) == 16)
987 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
989 st->epSquare = Square((int(from) + int(to)) / 2);
990 key ^= zobEp[st->epSquare];
994 if (pm) // promotion ?
996 PieceType promotion = promotion_piece_type(m);
998 assert(promotion >= KNIGHT && promotion <= QUEEN);
1000 // Insert promoted piece instead of pawn
1001 clear_bit(&(byTypeBB[PAWN]), to);
1002 set_bit(&(byTypeBB[promotion]), to);
1003 board[to] = make_piece(us, promotion);
1005 // Update piece counts
1006 pieceCount[us][promotion]++;
1007 pieceCount[us][PAWN]--;
1009 // Update material key
1010 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
1011 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
1013 // Update piece lists, move the last pawn at index[to] position
1014 // and shrink the list. Add a new promotion piece to the list.
1015 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
1016 index[lastPawnSquare] = index[to];
1017 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
1018 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
1019 index[to] = pieceCount[us][promotion] - 1;
1020 pieceList[us][promotion][index[to]] = to;
1022 // Partially revert hash keys update
1023 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
1024 st->pawnKey ^= zobrist[us][PAWN][to];
1026 // Partially revert and update incremental scores
1027 st->value -= pst(us, PAWN, to);
1028 st->value += pst(us, promotion, to);
1031 st->npMaterial[us] += PieceValueMidgame[promotion];
1035 // Prefetch pawn and material hash tables
1036 Threads[threadID].pawnTable.prefetch(st->pawnKey);
1037 Threads[threadID].materialTable.prefetch(st->materialKey);
1039 // Update incremental scores
1040 st->value += pst_delta(piece, from, to);
1042 // Set capture piece
1043 st->capturedType = capture;
1045 // Update the key with the final value
1048 // Update checkers bitboard, piece must be already moved
1049 st->checkersBB = EmptyBoardBB;
1054 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1058 if (bit_is_set(ci.checkSq[pt], to))
1059 st->checkersBB = SetMaskBB[to];
1062 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1065 st->checkersBB |= (attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us));
1068 st->checkersBB |= (attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us));
1074 sideToMove = opposite_color(sideToMove);
1075 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1081 /// Position::do_capture_move() is a private method used to update captured
1082 /// piece info. It is called from the main Position::do_move function.
1084 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1086 assert(capture != KING);
1090 // If the captured piece was a pawn, update pawn hash key,
1091 // otherwise update non-pawn material.
1092 if (capture == PAWN)
1094 if (ep) // en passant ?
1096 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1098 assert(to == st->epSquare);
1099 assert(relative_rank(opposite_color(them), to) == RANK_6);
1100 assert(piece_on(to) == PIECE_NONE);
1101 assert(piece_on(capsq) == make_piece(them, PAWN));
1103 board[capsq] = PIECE_NONE;
1105 st->pawnKey ^= zobrist[them][PAWN][capsq];
1108 st->npMaterial[them] -= PieceValueMidgame[capture];
1110 // Remove captured piece
1111 clear_bit(&(byColorBB[them]), capsq);
1112 clear_bit(&(byTypeBB[capture]), capsq);
1113 clear_bit(&(byTypeBB[0]), capsq);
1116 key ^= zobrist[them][capture][capsq];
1118 // Update incremental scores
1119 st->value -= pst(them, capture, capsq);
1121 // Update piece count
1122 pieceCount[them][capture]--;
1124 // Update material hash key
1125 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1127 // Update piece list, move the last piece at index[capsq] position
1129 // WARNING: This is a not perfectly revresible operation. When we
1130 // will reinsert the captured piece in undo_move() we will put it
1131 // at the end of the list and not in its original place, it means
1132 // index[] and pieceList[] are not guaranteed to be invariant to a
1133 // do_move() + undo_move() sequence.
1134 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1135 index[lastPieceSquare] = index[capsq];
1136 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1137 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1139 // Reset rule 50 counter
1144 /// Position::do_castle_move() is a private method used to make a castling
1145 /// move. It is called from the main Position::do_move function. Note that
1146 /// castling moves are encoded as "king captures friendly rook" moves, for
1147 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1149 void Position::do_castle_move(Move m) {
1151 assert(move_is_ok(m));
1152 assert(move_is_castle(m));
1154 Color us = side_to_move();
1155 Color them = opposite_color(us);
1157 // Reset capture field
1158 st->capturedType = PIECE_TYPE_NONE;
1160 // Find source squares for king and rook
1161 Square kfrom = move_from(m);
1162 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1165 assert(piece_on(kfrom) == make_piece(us, KING));
1166 assert(piece_on(rfrom) == make_piece(us, ROOK));
1168 // Find destination squares for king and rook
1169 if (rfrom > kfrom) // O-O
1171 kto = relative_square(us, SQ_G1);
1172 rto = relative_square(us, SQ_F1);
1174 kto = relative_square(us, SQ_C1);
1175 rto = relative_square(us, SQ_D1);
1178 // Remove pieces from source squares:
1179 clear_bit(&(byColorBB[us]), kfrom);
1180 clear_bit(&(byTypeBB[KING]), kfrom);
1181 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1182 clear_bit(&(byColorBB[us]), rfrom);
1183 clear_bit(&(byTypeBB[ROOK]), rfrom);
1184 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1186 // Put pieces on destination squares:
1187 set_bit(&(byColorBB[us]), kto);
1188 set_bit(&(byTypeBB[KING]), kto);
1189 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1190 set_bit(&(byColorBB[us]), rto);
1191 set_bit(&(byTypeBB[ROOK]), rto);
1192 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1194 // Update board array
1195 Piece king = make_piece(us, KING);
1196 Piece rook = make_piece(us, ROOK);
1197 board[kfrom] = board[rfrom] = PIECE_NONE;
1201 // Update piece lists
1202 pieceList[us][KING][index[kfrom]] = kto;
1203 pieceList[us][ROOK][index[rfrom]] = rto;
1204 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1205 index[kto] = index[kfrom];
1208 // Update incremental scores
1209 st->value += pst_delta(king, kfrom, kto);
1210 st->value += pst_delta(rook, rfrom, rto);
1213 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1214 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1216 // Clear en passant square
1217 if (st->epSquare != SQ_NONE)
1219 st->key ^= zobEp[st->epSquare];
1220 st->epSquare = SQ_NONE;
1223 // Update castling rights
1224 st->key ^= zobCastle[st->castleRights];
1225 st->castleRights &= castleRightsMask[kfrom];
1226 st->key ^= zobCastle[st->castleRights];
1228 // Reset rule 50 counter
1231 // Update checkers BB
1232 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1235 sideToMove = opposite_color(sideToMove);
1236 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1242 /// Position::undo_move() unmakes a move. When it returns, the position should
1243 /// be restored to exactly the same state as before the move was made.
1245 void Position::undo_move(Move m) {
1248 assert(move_is_ok(m));
1250 sideToMove = opposite_color(sideToMove);
1252 if (move_is_castle(m))
1254 undo_castle_move(m);
1258 Color us = side_to_move();
1259 Color them = opposite_color(us);
1260 Square from = move_from(m);
1261 Square to = move_to(m);
1262 bool ep = move_is_ep(m);
1263 bool pm = move_is_promotion(m);
1265 PieceType pt = type_of_piece_on(to);
1267 assert(square_is_empty(from));
1268 assert(color_of_piece_on(to) == us);
1269 assert(!pm || relative_rank(us, to) == RANK_8);
1270 assert(!ep || to == st->previous->epSquare);
1271 assert(!ep || relative_rank(us, to) == RANK_6);
1272 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1274 if (pm) // promotion ?
1276 PieceType promotion = promotion_piece_type(m);
1279 assert(promotion >= KNIGHT && promotion <= QUEEN);
1280 assert(piece_on(to) == make_piece(us, promotion));
1282 // Replace promoted piece with a pawn
1283 clear_bit(&(byTypeBB[promotion]), to);
1284 set_bit(&(byTypeBB[PAWN]), to);
1286 // Update piece counts
1287 pieceCount[us][promotion]--;
1288 pieceCount[us][PAWN]++;
1290 // Update piece list replacing promotion piece with a pawn
1291 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1292 index[lastPromotionSquare] = index[to];
1293 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1294 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1295 index[to] = pieceCount[us][PAWN] - 1;
1296 pieceList[us][PAWN][index[to]] = to;
1299 // Put the piece back at the source square
1300 Bitboard move_bb = make_move_bb(to, from);
1301 do_move_bb(&(byColorBB[us]), move_bb);
1302 do_move_bb(&(byTypeBB[pt]), move_bb);
1303 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1305 board[from] = make_piece(us, pt);
1306 board[to] = PIECE_NONE;
1308 // Update piece list
1309 index[from] = index[to];
1310 pieceList[us][pt][index[from]] = from;
1312 if (st->capturedType)
1317 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1319 assert(st->capturedType != KING);
1320 assert(!ep || square_is_empty(capsq));
1322 // Restore the captured piece
1323 set_bit(&(byColorBB[them]), capsq);
1324 set_bit(&(byTypeBB[st->capturedType]), capsq);
1325 set_bit(&(byTypeBB[0]), capsq);
1327 board[capsq] = make_piece(them, st->capturedType);
1329 // Update piece count
1330 pieceCount[them][st->capturedType]++;
1332 // Update piece list, add a new captured piece in capsq square
1333 index[capsq] = pieceCount[them][st->capturedType] - 1;
1334 pieceList[them][st->capturedType][index[capsq]] = capsq;
1337 // Finally point our state pointer back to the previous state
1344 /// Position::undo_castle_move() is a private method used to unmake a castling
1345 /// move. It is called from the main Position::undo_move function. Note that
1346 /// castling moves are encoded as "king captures friendly rook" moves, for
1347 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1349 void Position::undo_castle_move(Move m) {
1351 assert(move_is_ok(m));
1352 assert(move_is_castle(m));
1354 // When we have arrived here, some work has already been done by
1355 // Position::undo_move. In particular, the side to move has been switched,
1356 // so the code below is correct.
1357 Color us = side_to_move();
1359 // Find source squares for king and rook
1360 Square kfrom = move_from(m);
1361 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1364 // Find destination squares for king and rook
1365 if (rfrom > kfrom) // O-O
1367 kto = relative_square(us, SQ_G1);
1368 rto = relative_square(us, SQ_F1);
1370 kto = relative_square(us, SQ_C1);
1371 rto = relative_square(us, SQ_D1);
1374 assert(piece_on(kto) == make_piece(us, KING));
1375 assert(piece_on(rto) == make_piece(us, ROOK));
1377 // Remove pieces from destination squares:
1378 clear_bit(&(byColorBB[us]), kto);
1379 clear_bit(&(byTypeBB[KING]), kto);
1380 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1381 clear_bit(&(byColorBB[us]), rto);
1382 clear_bit(&(byTypeBB[ROOK]), rto);
1383 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1385 // Put pieces on source squares:
1386 set_bit(&(byColorBB[us]), kfrom);
1387 set_bit(&(byTypeBB[KING]), kfrom);
1388 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1389 set_bit(&(byColorBB[us]), rfrom);
1390 set_bit(&(byTypeBB[ROOK]), rfrom);
1391 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1394 board[rto] = board[kto] = PIECE_NONE;
1395 board[rfrom] = make_piece(us, ROOK);
1396 board[kfrom] = make_piece(us, KING);
1398 // Update piece lists
1399 pieceList[us][KING][index[kto]] = kfrom;
1400 pieceList[us][ROOK][index[rto]] = rfrom;
1401 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1402 index[kfrom] = index[kto];
1405 // Finally point our state pointer back to the previous state
1412 /// Position::do_null_move makes() a "null move": It switches the side to move
1413 /// and updates the hash key without executing any move on the board.
1415 void Position::do_null_move(StateInfo& backupSt) {
1418 assert(!in_check());
1420 // Back up the information necessary to undo the null move to the supplied
1421 // StateInfo object.
1422 // Note that differently from normal case here backupSt is actually used as
1423 // a backup storage not as a new state to be used.
1424 backupSt.key = st->key;
1425 backupSt.epSquare = st->epSquare;
1426 backupSt.value = st->value;
1427 backupSt.previous = st->previous;
1428 backupSt.pliesFromNull = st->pliesFromNull;
1429 st->previous = &backupSt;
1431 // Save the current key to the history[] array, in order to be able to
1432 // detect repetition draws.
1433 history[st->gamePly++] = st->key;
1435 // Update the necessary information
1436 if (st->epSquare != SQ_NONE)
1437 st->key ^= zobEp[st->epSquare];
1439 st->key ^= zobSideToMove;
1440 prefetch((char*)TT.first_entry(st->key));
1442 sideToMove = opposite_color(sideToMove);
1443 st->epSquare = SQ_NONE;
1445 st->pliesFromNull = 0;
1446 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1450 /// Position::undo_null_move() unmakes a "null move".
1452 void Position::undo_null_move() {
1455 assert(!in_check());
1457 // Restore information from the our backup StateInfo object
1458 StateInfo* backupSt = st->previous;
1459 st->key = backupSt->key;
1460 st->epSquare = backupSt->epSquare;
1461 st->value = backupSt->value;
1462 st->previous = backupSt->previous;
1463 st->pliesFromNull = backupSt->pliesFromNull;
1465 // Update the necessary information
1466 sideToMove = opposite_color(sideToMove);
1472 /// Position::see() is a static exchange evaluator: It tries to estimate the
1473 /// material gain or loss resulting from a move. There are three versions of
1474 /// this function: One which takes a destination square as input, one takes a
1475 /// move, and one which takes a 'from' and a 'to' square. The function does
1476 /// not yet understand promotions captures.
1478 int Position::see_sign(Move m) const {
1480 assert(move_is_ok(m));
1482 Square from = move_from(m);
1483 Square to = move_to(m);
1485 // Early return if SEE cannot be negative because captured piece value
1486 // is not less then capturing one. Note that king moves always return
1487 // here because king midgame value is set to 0.
1488 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1494 int Position::see(Move m) const {
1497 Bitboard occupied, attackers, stmAttackers, b;
1498 int swapList[32], slIndex = 1;
1499 PieceType capturedType, pt;
1502 assert(move_is_ok(m));
1504 // As castle moves are implemented as capturing the rook, they have
1505 // SEE == RookValueMidgame most of the times (unless the rook is under
1507 if (move_is_castle(m))
1510 from = move_from(m);
1512 capturedType = type_of_piece_on(to);
1513 occupied = occupied_squares();
1515 // Handle en passant moves
1516 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1518 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1520 assert(capturedType == PIECE_TYPE_NONE);
1521 assert(type_of_piece_on(capQq) == PAWN);
1523 // Remove the captured pawn
1524 clear_bit(&occupied, capQq);
1525 capturedType = PAWN;
1528 // Find all attackers to the destination square, with the moving piece
1529 // removed, but possibly an X-ray attacker added behind it.
1530 clear_bit(&occupied, from);
1531 attackers = attackers_to(to, occupied);
1533 // If the opponent has no attackers we are finished
1534 stm = opposite_color(color_of_piece_on(from));
1535 stmAttackers = attackers & pieces_of_color(stm);
1537 return seeValues[capturedType];
1539 // The destination square is defended, which makes things rather more
1540 // difficult to compute. We proceed by building up a "swap list" containing
1541 // the material gain or loss at each stop in a sequence of captures to the
1542 // destination square, where the sides alternately capture, and always
1543 // capture with the least valuable piece. After each capture, we look for
1544 // new X-ray attacks from behind the capturing piece.
1545 swapList[0] = seeValues[capturedType];
1546 capturedType = type_of_piece_on(from);
1549 // Locate the least valuable attacker for the side to move. The loop
1550 // below looks like it is potentially infinite, but it isn't. We know
1551 // that the side to move still has at least one attacker left.
1552 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1555 // Remove the attacker we just found from the 'occupied' bitboard,
1556 // and scan for new X-ray attacks behind the attacker.
1557 b = stmAttackers & pieces(pt);
1558 occupied ^= (b & (~b + 1));
1559 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1560 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1562 attackers &= occupied; // Cut out pieces we've already done
1564 // Add the new entry to the swap list
1565 assert(slIndex < 32);
1566 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1569 // Remember the value of the capturing piece, and change the side to
1570 // move before beginning the next iteration.
1572 stm = opposite_color(stm);
1573 stmAttackers = attackers & pieces_of_color(stm);
1575 // Stop before processing a king capture
1576 if (capturedType == KING && stmAttackers)
1578 assert(slIndex < 32);
1579 swapList[slIndex++] = QueenValueMidgame*10;
1582 } while (stmAttackers);
1584 // Having built the swap list, we negamax through it to find the best
1585 // achievable score from the point of view of the side to move.
1587 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1593 /// Position::clear() erases the position object to a pristine state, with an
1594 /// empty board, white to move, and no castling rights.
1596 void Position::clear() {
1599 memset(st, 0, sizeof(StateInfo));
1600 st->epSquare = SQ_NONE;
1601 startPosPlyCounter = 0;
1604 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1605 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1606 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1607 memset(index, 0, sizeof(int) * 64);
1609 for (int i = 0; i < 64; i++)
1610 board[i] = PIECE_NONE;
1612 for (int i = 0; i < 8; i++)
1613 for (int j = 0; j < 16; j++)
1614 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1616 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1617 castleRightsMask[sq] = ALL_CASTLES;
1620 initialKFile = FILE_E;
1621 initialKRFile = FILE_H;
1622 initialQRFile = FILE_A;
1626 /// Position::put_piece() puts a piece on the given square of the board,
1627 /// updating the board array, pieces list, bitboards, and piece counts.
1629 void Position::put_piece(Piece p, Square s) {
1631 Color c = color_of_piece(p);
1632 PieceType pt = type_of_piece(p);
1635 index[s] = pieceCount[c][pt]++;
1636 pieceList[c][pt][index[s]] = s;
1638 set_bit(&(byTypeBB[pt]), s);
1639 set_bit(&(byColorBB[c]), s);
1640 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1644 /// Position::compute_key() computes the hash key of the position. The hash
1645 /// key is usually updated incrementally as moves are made and unmade, the
1646 /// compute_key() function is only used when a new position is set up, and
1647 /// to verify the correctness of the hash key when running in debug mode.
1649 Key Position::compute_key() const {
1651 Key result = zobCastle[st->castleRights];
1653 for (Square s = SQ_A1; s <= SQ_H8; s++)
1654 if (square_is_occupied(s))
1655 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1657 if (ep_square() != SQ_NONE)
1658 result ^= zobEp[ep_square()];
1660 if (side_to_move() == BLACK)
1661 result ^= zobSideToMove;
1667 /// Position::compute_pawn_key() computes the hash key of the position. The
1668 /// hash key is usually updated incrementally as moves are made and unmade,
1669 /// the compute_pawn_key() function is only used when a new position is set
1670 /// up, and to verify the correctness of the pawn hash key when running in
1673 Key Position::compute_pawn_key() const {
1678 for (Color c = WHITE; c <= BLACK; c++)
1680 b = pieces(PAWN, c);
1682 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1688 /// Position::compute_material_key() computes the hash key of the position.
1689 /// The hash key is usually updated incrementally as moves are made and unmade,
1690 /// the compute_material_key() function is only used when a new position is set
1691 /// up, and to verify the correctness of the material hash key when running in
1694 Key Position::compute_material_key() const {
1699 for (Color c = WHITE; c <= BLACK; c++)
1700 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1702 count = piece_count(c, pt);
1703 for (int i = 0; i < count; i++)
1704 result ^= zobrist[c][pt][i];
1710 /// Position::compute_value() compute the incremental scores for the middle
1711 /// game and the endgame. These functions are used to initialize the incremental
1712 /// scores when a new position is set up, and to verify that the scores are correctly
1713 /// updated by do_move and undo_move when the program is running in debug mode.
1714 Score Position::compute_value() const {
1717 Score result = SCORE_ZERO;
1719 for (Color c = WHITE; c <= BLACK; c++)
1720 for (PieceType pt = PAWN; pt <= KING; pt++)
1724 result += pst(c, pt, pop_1st_bit(&b));
1727 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1732 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1733 /// game material value for the given side. Material values are updated
1734 /// incrementally during the search, this function is only used while
1735 /// initializing a new Position object.
1737 Value Position::compute_non_pawn_material(Color c) const {
1739 Value result = VALUE_ZERO;
1741 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1742 result += piece_count(c, pt) * PieceValueMidgame[pt];
1748 /// Position::is_draw() tests whether the position is drawn by material,
1749 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1750 /// must be done by the search.
1751 template<bool SkipRepetition>
1752 bool Position::is_draw() const {
1754 // Draw by material?
1756 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1759 // Draw by the 50 moves rule?
1760 if (st->rule50 > 99 && !is_mate())
1763 // Draw by repetition?
1764 if (!SkipRepetition)
1765 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1766 if (history[st->gamePly - i] == st->key)
1772 // Explicit template instantiations
1773 template bool Position::is_draw<false>() const;
1774 template bool Position::is_draw<true>() const;
1777 /// Position::is_mate() returns true or false depending on whether the
1778 /// side to move is checkmated.
1780 bool Position::is_mate() const {
1782 MoveStack moves[MAX_MOVES];
1783 return in_check() && generate<MV_LEGAL>(*this, moves) == moves;
1787 /// Position::init() is a static member function which initializes at
1788 /// startup the various arrays used to compute hash keys and the piece
1789 /// square tables. The latter is a two-step operation: First, the white
1790 /// halves of the tables are copied from the MgPST[][] and EgPST[][] arrays.
1791 /// Second, the black halves of the tables are initialized by mirroring
1792 /// and changing the sign of the corresponding white scores.
1794 void Position::init() {
1798 for (Color c = WHITE; c <= BLACK; c++)
1799 for (PieceType pt = PAWN; pt <= KING; pt++)
1800 for (Square s = SQ_A1; s <= SQ_H8; s++)
1801 zobrist[c][pt][s] = rk.rand<Key>();
1803 for (Square s = SQ_A1; s <= SQ_H8; s++)
1804 zobEp[s] = rk.rand<Key>();
1806 for (int i = 0; i < 16; i++)
1807 zobCastle[i] = rk.rand<Key>();
1809 zobSideToMove = rk.rand<Key>();
1810 zobExclusion = rk.rand<Key>();
1812 for (Square s = SQ_A1; s <= SQ_H8; s++)
1813 for (Piece p = WP; p <= WK; p++)
1814 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1816 for (Square s = SQ_A1; s <= SQ_H8; s++)
1817 for (Piece p = BP; p <= BK; p++)
1818 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1822 /// Position::flip() flips position with the white and black sides reversed. This
1823 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1825 void Position::flip() {
1829 // Make a copy of current position before to start changing
1830 const Position pos(*this, threadID);
1833 threadID = pos.thread();
1836 for (Square s = SQ_A1; s <= SQ_H8; s++)
1837 if (!pos.square_is_empty(s))
1838 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1841 sideToMove = opposite_color(pos.side_to_move());
1844 if (pos.can_castle_kingside(WHITE)) set_castle_kingside(BLACK);
1845 if (pos.can_castle_queenside(WHITE)) set_castle_queenside(BLACK);
1846 if (pos.can_castle_kingside(BLACK)) set_castle_kingside(WHITE);
1847 if (pos.can_castle_queenside(BLACK)) set_castle_queenside(WHITE);
1849 initialKFile = pos.initialKFile;
1850 initialKRFile = pos.initialKRFile;
1851 initialQRFile = pos.initialQRFile;
1853 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1854 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1855 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1856 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1857 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1858 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1860 // En passant square
1861 if (pos.st->epSquare != SQ_NONE)
1862 st->epSquare = flip_square(pos.st->epSquare);
1868 st->key = compute_key();
1869 st->pawnKey = compute_pawn_key();
1870 st->materialKey = compute_material_key();
1872 // Incremental scores
1873 st->value = compute_value();
1876 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1877 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1883 /// Position::is_ok() performs some consitency checks for the position object.
1884 /// This is meant to be helpful when debugging.
1886 bool Position::is_ok(int* failedStep) const {
1888 // What features of the position should be verified?
1889 const bool debugAll = false;
1891 const bool debugBitboards = debugAll || false;
1892 const bool debugKingCount = debugAll || false;
1893 const bool debugKingCapture = debugAll || false;
1894 const bool debugCheckerCount = debugAll || false;
1895 const bool debugKey = debugAll || false;
1896 const bool debugMaterialKey = debugAll || false;
1897 const bool debugPawnKey = debugAll || false;
1898 const bool debugIncrementalEval = debugAll || false;
1899 const bool debugNonPawnMaterial = debugAll || false;
1900 const bool debugPieceCounts = debugAll || false;
1901 const bool debugPieceList = debugAll || false;
1902 const bool debugCastleSquares = debugAll || false;
1904 if (failedStep) *failedStep = 1;
1907 if (side_to_move() != WHITE && side_to_move() != BLACK)
1910 // Are the king squares in the position correct?
1911 if (failedStep) (*failedStep)++;
1912 if (piece_on(king_square(WHITE)) != WK)
1915 if (failedStep) (*failedStep)++;
1916 if (piece_on(king_square(BLACK)) != BK)
1920 if (failedStep) (*failedStep)++;
1921 if (!square_is_ok(make_square(initialKRFile, RANK_1)))
1924 if (!square_is_ok(make_square(initialQRFile, RANK_1)))
1927 // Do both sides have exactly one king?
1928 if (failedStep) (*failedStep)++;
1931 int kingCount[2] = {0, 0};
1932 for (Square s = SQ_A1; s <= SQ_H8; s++)
1933 if (type_of_piece_on(s) == KING)
1934 kingCount[color_of_piece_on(s)]++;
1936 if (kingCount[0] != 1 || kingCount[1] != 1)
1940 // Can the side to move capture the opponent's king?
1941 if (failedStep) (*failedStep)++;
1942 if (debugKingCapture)
1944 Color us = side_to_move();
1945 Color them = opposite_color(us);
1946 Square ksq = king_square(them);
1947 if (attackers_to(ksq) & pieces_of_color(us))
1951 // Is there more than 2 checkers?
1952 if (failedStep) (*failedStep)++;
1953 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1957 if (failedStep) (*failedStep)++;
1960 // The intersection of the white and black pieces must be empty
1961 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1964 // The union of the white and black pieces must be equal to all
1966 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1969 // Separate piece type bitboards must have empty intersections
1970 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1971 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1972 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1976 // En passant square OK?
1977 if (failedStep) (*failedStep)++;
1978 if (ep_square() != SQ_NONE)
1980 // The en passant square must be on rank 6, from the point of view of the
1982 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1987 if (failedStep) (*failedStep)++;
1988 if (debugKey && st->key != compute_key())
1991 // Pawn hash key OK?
1992 if (failedStep) (*failedStep)++;
1993 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1996 // Material hash key OK?
1997 if (failedStep) (*failedStep)++;
1998 if (debugMaterialKey && st->materialKey != compute_material_key())
2001 // Incremental eval OK?
2002 if (failedStep) (*failedStep)++;
2003 if (debugIncrementalEval && st->value != compute_value())
2006 // Non-pawn material OK?
2007 if (failedStep) (*failedStep)++;
2008 if (debugNonPawnMaterial)
2010 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2013 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2018 if (failedStep) (*failedStep)++;
2019 if (debugPieceCounts)
2020 for (Color c = WHITE; c <= BLACK; c++)
2021 for (PieceType pt = PAWN; pt <= KING; pt++)
2022 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2025 if (failedStep) (*failedStep)++;
2027 for (Color c = WHITE; c <= BLACK; c++)
2028 for (PieceType pt = PAWN; pt <= KING; pt++)
2029 for (int i = 0; i < pieceCount[c][pt]; i++)
2031 if (piece_on(piece_list(c, pt, i)) != make_piece(c, pt))
2034 if (index[piece_list(c, pt, i)] != i)
2038 if (failedStep) (*failedStep)++;
2039 if (debugCastleSquares)
2041 for (Color c = WHITE; c <= BLACK; c++)
2043 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != make_piece(c, ROOK))
2046 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != make_piece(c, ROOK))
2049 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2051 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2053 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2055 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2059 if (failedStep) *failedStep = 0;