2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
33 #include "ucioption.h"
39 Key Position::zobrist[2][8][64];
40 Key Position::zobEp[64];
41 Key Position::zobCastle[16];
42 Key Position::zobSideToMove;
43 Key Position::zobExclusion;
45 Score Position::PieceSquareTable[16][64];
47 // Material values arrays, indexed by Piece
48 const Value PieceValueMidgame[17] = {
50 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
51 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
52 VALUE_ZERO, VALUE_ZERO,
53 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
54 RookValueMidgame, QueenValueMidgame
57 const Value PieceValueEndgame[17] = {
59 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
60 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
61 VALUE_ZERO, VALUE_ZERO,
62 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
63 RookValueEndgame, QueenValueEndgame
69 // Bonus for having the side to move (modified by Joona Kiiski)
70 const Score TempoValue = make_score(48, 22);
72 // To convert a Piece to and from a FEN char
73 const string PieceToChar(".PNBRQK pnbrqk ");
79 CheckInfo::CheckInfo(const Position& pos) {
81 Color us = pos.side_to_move();
82 Color them = opposite_color(us);
83 Square ksq = pos.king_square(them);
85 dcCandidates = pos.discovered_check_candidates(us);
86 pinned = pos.pinned_pieces(us);
88 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
89 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
90 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
91 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
92 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
93 checkSq[KING] = EmptyBoardBB;
97 /// Position c'tors. Here we always create a copy of the original position
98 /// or the FEN string, we want the new born Position object do not depend
99 /// on any external data so we detach state pointer from the source one.
101 Position::Position(const Position& pos, int th) {
103 memcpy(this, &pos, sizeof(Position));
104 detach(); // Always detach() in copy c'tor to avoid surprises
109 Position::Position(const string& fen, bool isChess960, int th) {
111 from_fen(fen, isChess960);
116 /// Position::detach() copies the content of the current state and castling
117 /// masks inside the position itself. This is needed when the st pointee could
118 /// become stale, as example because the caller is about to going out of scope.
120 void Position::detach() {
124 st->previous = NULL; // as a safe guard
128 /// Position::from_fen() initializes the position object with the given FEN
129 /// string. This function is not very robust - make sure that input FENs are
130 /// correct (this is assumed to be the responsibility of the GUI).
132 void Position::from_fen(const string& fen, bool isChess960) {
134 A FEN string defines a particular position using only the ASCII character set.
136 A FEN string contains six fields. The separator between fields is a space. The fields are:
138 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
139 with rank 1; within each rank, the contents of each square are described from file A through file H.
140 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
141 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
142 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
143 of blank squares), and "/" separate ranks.
145 2) Active color. "w" means white moves next, "b" means black.
147 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
148 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
149 kingside), and/or "q" (Black can castle queenside).
151 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
152 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
153 regardless of whether there is a pawn in position to make an en passant capture.
155 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
156 to determine if a draw can be claimed under the fifty-move rule.
158 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
165 std::istringstream ss(fen);
170 // 1. Piece placement field
171 while ((ss >> token) && !isspace(token))
173 if ((p = PieceToChar.find(token)) != string::npos)
175 put_piece(Piece(p), sq);
178 else if (isdigit(token))
179 sq += Square(token - '0'); // Skip the given number of files
180 else if (token == '/')
181 sq -= SQ_A3; // Jump back of 2 rows
187 if (!(ss >> token) || (token != 'w' && token != 'b'))
190 sideToMove = (token == 'w' ? WHITE : BLACK);
192 if (!(ss >> token) || !isspace(token))
195 // 3. Castling availability
196 while ((ss >> token) && !isspace(token))
197 if (!set_castling_rights(token))
200 // 4. En passant square
202 if ( ((ss >> col) && (col >= 'a' && col <= 'h'))
203 && ((ss >> row) && (row == '3' || row == '6')))
205 st->epSquare = make_square(File(col - 'a') + FILE_A, Rank(row - '1') + RANK_1);
207 // Ignore if no capture is possible
208 Color them = opposite_color(sideToMove);
209 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
210 st->epSquare = SQ_NONE;
214 if (ss >> std::skipws >> hmc)
217 // 6. Fullmove number
219 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
221 // Various initialisations
222 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
223 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
224 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
225 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
226 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
227 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
229 chess960 = isChess960;
232 st->key = compute_key();
233 st->pawnKey = compute_pawn_key();
234 st->materialKey = compute_material_key();
235 st->value = compute_value();
236 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
237 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
241 cout << "Error in FEN string: " << fen << endl;
245 /// Position::set_castling_rights() sets castling parameters castling avaiability.
246 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
247 /// that uses the letters of the columns on which the rooks began the game instead
248 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
249 /// associated with the castling right, the traditional castling tag will be replaced
250 /// by the file letter of the involved rook as for the Shredder-FEN.
252 bool Position::set_castling_rights(char token) {
254 Color c = token >= 'a' ? BLACK : WHITE;
255 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
256 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
257 Piece rook = (c == WHITE ? WR : BR);
259 initialKFile = square_file(king_square(c));
260 token = char(toupper(token));
264 for (Square sq = sqH; sq >= sqA; sq--)
265 if (piece_on(sq) == rook)
267 set_castle_kingside(c);
268 initialKRFile = square_file(sq);
272 else if (token == 'Q')
274 for (Square sq = sqA; sq <= sqH; sq++)
275 if (piece_on(sq) == rook)
277 set_castle_queenside(c);
278 initialQRFile = square_file(sq);
282 else if (token >= 'A' && token <= 'H')
284 File rookFile = File(token - 'A') + FILE_A;
285 if (rookFile < initialKFile)
287 set_castle_queenside(c);
288 initialQRFile = rookFile;
292 set_castle_kingside(c);
293 initialKRFile = rookFile;
303 /// Position::to_fen() returns a FEN representation of the position. In case
304 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
306 const string Position::to_fen() const {
312 for (Rank rank = RANK_8; rank >= RANK_1; rank--, fen += '/')
316 for (File file = FILE_A; file <= FILE_H; file++)
318 sq = make_square(file, rank);
320 if (square_is_occupied(sq))
327 fen += PieceToChar[piece_on(sq)];
336 fen += (sideToMove == WHITE ? " w " : " b ");
338 if (st->castleRights != CASTLES_NONE)
340 if (can_castle_kingside(WHITE))
341 fen += chess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
343 if (can_castle_queenside(WHITE))
344 fen += chess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
346 if (can_castle_kingside(BLACK))
347 fen += chess960 ? file_to_char(initialKRFile) : 'k';
349 if (can_castle_queenside(BLACK))
350 fen += chess960 ? file_to_char(initialQRFile) : 'q';
354 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
359 /// Position::print() prints an ASCII representation of the position to
360 /// the standard output. If a move is given then also the san is printed.
362 void Position::print(Move move) const {
364 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
368 Position p(*this, thread());
369 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
370 cout << "\nMove is: " << dd << move_to_san(p, move);
373 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
375 cout << dottedLine << '|';
376 for (File file = FILE_A; file <= FILE_H; file++)
378 Square sq = make_square(file, rank);
379 Piece piece = piece_on(sq);
381 if (piece == PIECE_NONE && square_color(sq) == DARK)
382 piece = PIECE_NONE_DARK_SQ;
384 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
385 cout << c << PieceToChar[piece] << c << '|';
388 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
392 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
393 /// king) pieces for the given color and for the given pinner type. Or, when
394 /// template parameter FindPinned is false, the pieces of the given color
395 /// candidate for a discovery check against the enemy king.
396 /// Bitboard checkersBB must be already updated when looking for pinners.
398 template<bool FindPinned>
399 Bitboard Position::hidden_checkers(Color c) const {
401 Bitboard result = EmptyBoardBB;
402 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
404 // Pinned pieces protect our king, dicovery checks attack
406 Square ksq = king_square(FindPinned ? c : opposite_color(c));
408 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
409 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
411 if (FindPinned && pinners)
412 pinners &= ~st->checkersBB;
416 Square s = pop_1st_bit(&pinners);
417 Bitboard b = squares_between(s, ksq) & occupied_squares();
421 if ( !(b & (b - 1)) // Only one bit set?
422 && (b & pieces_of_color(c))) // Is an our piece?
429 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
430 /// king) pieces for the given color. Note that checkersBB bitboard must
431 /// be already updated.
433 Bitboard Position::pinned_pieces(Color c) const {
435 return hidden_checkers<true>(c);
439 /// Position:discovered_check_candidates() returns a bitboard containing all
440 /// pieces for the given side which are candidates for giving a discovered
441 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
442 /// to be already updated.
444 Bitboard Position::discovered_check_candidates(Color c) const {
446 return hidden_checkers<false>(c);
449 /// Position::attackers_to() computes a bitboard containing all pieces which
450 /// attacks a given square.
452 Bitboard Position::attackers_to(Square s) const {
454 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
455 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
456 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
457 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
458 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
459 | (attacks_from<KING>(s) & pieces(KING));
462 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
464 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
465 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
466 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
467 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
468 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
469 | (attacks_from<KING>(s) & pieces(KING));
472 /// Position::attacks_from() computes a bitboard of all attacks
473 /// of a given piece put in a given square.
475 Bitboard Position::attacks_from(Piece p, Square s) const {
477 assert(square_is_ok(s));
481 case WB: case BB: return attacks_from<BISHOP>(s);
482 case WR: case BR: return attacks_from<ROOK>(s);
483 case WQ: case BQ: return attacks_from<QUEEN>(s);
484 default: return StepAttacksBB[p][s];
488 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
490 assert(square_is_ok(s));
494 case WB: case BB: return bishop_attacks_bb(s, occ);
495 case WR: case BR: return rook_attacks_bb(s, occ);
496 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
497 default: return StepAttacksBB[p][s];
502 /// Position::move_attacks_square() tests whether a move from the current
503 /// position attacks a given square.
505 bool Position::move_attacks_square(Move m, Square s) const {
507 assert(move_is_ok(m));
508 assert(square_is_ok(s));
511 Square f = move_from(m), t = move_to(m);
513 assert(square_is_occupied(f));
515 if (bit_is_set(attacks_from(piece_on(f), t), s))
518 // Move the piece and scan for X-ray attacks behind it
519 occ = occupied_squares();
520 do_move_bb(&occ, make_move_bb(f, t));
521 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
522 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
523 & pieces_of_color(color_of_piece_on(f));
525 // If we have attacks we need to verify that are caused by our move
526 // and are not already existent ones.
527 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
531 /// Position::find_checkers() computes the checkersBB bitboard, which
532 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
533 /// currently works by calling Position::attackers_to, which is probably
534 /// inefficient. Consider rewriting this function to use the last move
535 /// played, like in non-bitboard versions of Glaurung.
537 void Position::find_checkers() {
539 Color us = side_to_move();
540 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
544 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
546 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
549 assert(move_is_ok(m));
550 assert(pinned == pinned_pieces(side_to_move()));
552 Color us = side_to_move();
553 Square from = move_from(m);
555 assert(color_of_piece_on(from) == us);
556 assert(piece_on(king_square(us)) == make_piece(us, KING));
558 // En passant captures are a tricky special case. Because they are
559 // rather uncommon, we do it simply by testing whether the king is attacked
560 // after the move is made
563 Color them = opposite_color(us);
564 Square to = move_to(m);
565 Square capsq = make_square(square_file(to), square_rank(from));
566 Square ksq = king_square(us);
567 Bitboard b = occupied_squares();
569 assert(to == ep_square());
570 assert(piece_on(from) == make_piece(us, PAWN));
571 assert(piece_on(capsq) == make_piece(them, PAWN));
572 assert(piece_on(to) == PIECE_NONE);
575 clear_bit(&b, capsq);
578 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
579 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
582 // If the moving piece is a king, check whether the destination
583 // square is attacked by the opponent. Castling moves are checked
584 // for legality during move generation.
585 if (type_of_piece(piece_on(from)) == KING)
586 return move_is_castle(m) || !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
588 // A non-king move is legal if and only if it is not pinned or it
589 // is moving along the ray towards or away from the king.
591 || !bit_is_set(pinned, from)
592 || squares_aligned(from, move_to(m), king_square(us));
596 /// Position::move_is_pl_slow() takes a position and a move and tests whether
597 /// the move is pseudo legal. This version is not very fast and should be used
598 /// only in non time-critical paths.
600 bool Position::move_is_pl_slow(const Move m) const {
602 MoveStack mlist[MAX_MOVES];
603 MoveStack *cur, *last;
605 last = in_check() ? generate<MV_EVASION>(*this, mlist)
606 : generate<MV_NON_EVASION>(*this, mlist);
608 for (cur = mlist; cur != last; cur++)
616 /// Fast version of Position::move_is_pl() that takes a position a move and a
617 /// bitboard of pinned pieces as input, and tests whether the move is pseudo legal.
619 bool Position::move_is_pl(const Move m) const {
623 Color us = sideToMove;
624 Color them = opposite_color(sideToMove);
625 Square from = move_from(m);
626 Square to = move_to(m);
627 Piece pc = piece_on(from);
629 // Use a slower but simpler function for uncommon cases
630 if (move_is_special(m))
631 return move_is_pl_slow(m);
633 // Is not a promotion, so promotion piece must be empty
634 if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
637 // If the from square is not occupied by a piece belonging to the side to
638 // move, the move is obviously not legal.
639 if (pc == PIECE_NONE || color_of_piece(pc) != us)
642 // The destination square cannot be occupied by a friendly piece
643 if (color_of_piece_on(to) == us)
646 // Handle the special case of a pawn move
647 if (type_of_piece(pc) == PAWN)
649 // Move direction must be compatible with pawn color
650 int direction = to - from;
651 if ((us == WHITE) != (direction > 0))
654 // We have already handled promotion moves, so destination
655 // cannot be on the 8/1th rank.
656 if (square_rank(to) == RANK_8 || square_rank(to) == RANK_1)
659 // Proceed according to the square delta between the origin and
660 // destination squares.
667 // Capture. The destination square must be occupied by an enemy
668 // piece (en passant captures was handled earlier).
669 if (color_of_piece_on(to) != them)
672 // From and to files must be one file apart, avoids a7h5
673 if (abs(square_file(from) - square_file(to)) != 1)
679 // Pawn push. The destination square must be empty.
680 if (!square_is_empty(to))
685 // Double white pawn push. The destination square must be on the fourth
686 // rank, and both the destination square and the square between the
687 // source and destination squares must be empty.
688 if ( square_rank(to) != RANK_4
689 || !square_is_empty(to)
690 || !square_is_empty(from + DELTA_N))
695 // Double black pawn push. The destination square must be on the fifth
696 // rank, and both the destination square and the square between the
697 // source and destination squares must be empty.
698 if ( square_rank(to) != RANK_5
699 || !square_is_empty(to)
700 || !square_is_empty(from + DELTA_S))
708 else if (!bit_is_set(attacks_from(pc, from), to))
713 // In case of king moves under check we have to remove king so to catch
714 // as invalid moves like b1a1 when opposite queen is on c1.
715 if (type_of_piece(piece_on(from)) == KING)
717 Bitboard b = occupied_squares();
719 if (attackers_to(move_to(m), b) & pieces_of_color(opposite_color(us)))
724 Bitboard target = checkers();
725 Square checksq = pop_1st_bit(&target);
727 if (target) // double check ? In this case a king move is required
730 // Our move must be a blocking evasion or a capture of the checking piece
731 target = squares_between(checksq, king_square(us)) | checkers();
732 if (!bit_is_set(target, move_to(m)))
741 /// Position::move_gives_check() tests whether a pseudo-legal move is a check
743 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
746 assert(move_is_ok(m));
747 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
748 assert(color_of_piece_on(move_from(m)) == side_to_move());
750 Square from = move_from(m);
751 Square to = move_to(m);
752 PieceType pt = type_of_piece(piece_on(from));
755 if (bit_is_set(ci.checkSq[pt], to))
759 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
761 // For pawn and king moves we need to verify also direction
762 if ( (pt != PAWN && pt != KING)
763 || !squares_aligned(from, to, king_square(opposite_color(side_to_move()))))
767 // Can we skip the ugly special cases ?
768 if (!move_is_special(m))
771 Color us = side_to_move();
772 Bitboard b = occupied_squares();
773 Square ksq = king_square(opposite_color(us));
775 // Promotion with check ?
776 if (move_is_promotion(m))
780 switch (promotion_piece_type(m))
783 return bit_is_set(attacks_from<KNIGHT>(to), ksq);
785 return bit_is_set(bishop_attacks_bb(to, b), ksq);
787 return bit_is_set(rook_attacks_bb(to, b), ksq);
789 return bit_is_set(queen_attacks_bb(to, b), ksq);
795 // En passant capture with check ? We have already handled the case
796 // of direct checks and ordinary discovered check, the only case we
797 // need to handle is the unusual case of a discovered check through
798 // the captured pawn.
801 Square capsq = make_square(square_file(to), square_rank(from));
803 clear_bit(&b, capsq);
805 return (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
806 ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
809 // Castling with check ?
810 if (move_is_castle(m))
812 Square kfrom, kto, rfrom, rto;
818 kto = relative_square(us, SQ_G1);
819 rto = relative_square(us, SQ_F1);
821 kto = relative_square(us, SQ_C1);
822 rto = relative_square(us, SQ_D1);
824 clear_bit(&b, kfrom);
825 clear_bit(&b, rfrom);
828 return bit_is_set(rook_attacks_bb(rto, b), ksq);
835 /// Position::do_setup_move() makes a permanent move on the board. It should
836 /// be used when setting up a position on board. You can't undo the move.
838 void Position::do_setup_move(Move m) {
844 // Reset "game ply" in case we made a non-reversible move.
845 // "game ply" is used for repetition detection.
849 // Update the number of plies played from the starting position
850 startPosPlyCounter++;
852 // Our StateInfo newSt is about going out of scope so copy
853 // its content before it disappears.
858 /// Position::do_move() makes a move, and saves all information necessary
859 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
860 /// moves should be filtered out before this function is called.
862 void Position::do_move(Move m, StateInfo& newSt) {
865 do_move(m, newSt, ci, move_gives_check(m, ci));
868 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
871 assert(move_is_ok(m));
872 assert(&newSt != st);
877 // Copy some fields of old state to our new StateInfo object except the
878 // ones which are recalculated from scratch anyway, then switch our state
879 // pointer to point to the new, ready to be updated, state.
880 struct ReducedStateInfo {
881 Key pawnKey, materialKey;
882 int castleRights, rule50, gamePly, pliesFromNull;
888 memcpy(&newSt, st, sizeof(ReducedStateInfo));
893 // Save the current key to the history[] array, in order to be able to
894 // detect repetition draws.
895 history[st->gamePly++] = key;
897 // Update side to move
898 key ^= zobSideToMove;
900 // Increment the 50 moves rule draw counter. Resetting it to zero in the
901 // case of non-reversible moves is taken care of later.
905 if (move_is_castle(m))
912 Color us = side_to_move();
913 Color them = opposite_color(us);
914 Square from = move_from(m);
915 Square to = move_to(m);
916 bool ep = move_is_ep(m);
917 bool pm = move_is_promotion(m);
919 Piece piece = piece_on(from);
920 PieceType pt = type_of_piece(piece);
921 PieceType capture = ep ? PAWN : type_of_piece(piece_on(to));
923 assert(color_of_piece_on(from) == us);
924 assert(color_of_piece_on(to) == them || square_is_empty(to));
925 assert(!(ep || pm) || piece == make_piece(us, PAWN));
926 assert(!pm || relative_rank(us, to) == RANK_8);
929 do_capture_move(key, capture, them, to, ep);
932 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
934 // Reset en passant square
935 if (st->epSquare != SQ_NONE)
937 key ^= zobEp[st->epSquare];
938 st->epSquare = SQ_NONE;
941 // Update castle rights if needed
942 if ( st->castleRights != CASTLES_NONE
943 && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
945 key ^= zobCastle[st->castleRights];
946 st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
947 key ^= zobCastle[st->castleRights];
950 // Prefetch TT access as soon as we know key is updated
951 prefetch((char*)TT.first_entry(key));
954 Bitboard move_bb = make_move_bb(from, to);
955 do_move_bb(&(byColorBB[us]), move_bb);
956 do_move_bb(&(byTypeBB[pt]), move_bb);
957 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
959 board[to] = board[from];
960 board[from] = PIECE_NONE;
962 // Update piece lists, note that index[from] is not updated and
963 // becomes stale. This works as long as index[] is accessed just
964 // by known occupied squares.
965 index[to] = index[from];
966 pieceList[us][pt][index[to]] = to;
968 // If the moving piece was a pawn do some special extra work
971 // Reset rule 50 draw counter
974 // Update pawn hash key and prefetch in L1/L2 cache
975 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
977 // Set en passant square, only if moved pawn can be captured
978 if ((to ^ from) == 16)
980 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
982 st->epSquare = Square((int(from) + int(to)) / 2);
983 key ^= zobEp[st->epSquare];
987 if (pm) // promotion ?
989 PieceType promotion = promotion_piece_type(m);
991 assert(promotion >= KNIGHT && promotion <= QUEEN);
993 // Insert promoted piece instead of pawn
994 clear_bit(&(byTypeBB[PAWN]), to);
995 set_bit(&(byTypeBB[promotion]), to);
996 board[to] = make_piece(us, promotion);
998 // Update piece counts
999 pieceCount[us][promotion]++;
1000 pieceCount[us][PAWN]--;
1002 // Update material key
1003 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
1004 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
1006 // Update piece lists, move the last pawn at index[to] position
1007 // and shrink the list. Add a new promotion piece to the list.
1008 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
1009 index[lastPawnSquare] = index[to];
1010 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
1011 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
1012 index[to] = pieceCount[us][promotion] - 1;
1013 pieceList[us][promotion][index[to]] = to;
1015 // Partially revert hash keys update
1016 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
1017 st->pawnKey ^= zobrist[us][PAWN][to];
1019 // Partially revert and update incremental scores
1020 st->value -= pst(us, PAWN, to);
1021 st->value += pst(us, promotion, to);
1024 st->npMaterial[us] += PieceValueMidgame[promotion];
1028 // Prefetch pawn and material hash tables
1029 Threads[threadID].pawnTable.prefetch(st->pawnKey);
1030 Threads[threadID].materialTable.prefetch(st->materialKey);
1032 // Update incremental scores
1033 st->value += pst_delta(piece, from, to);
1035 // Set capture piece
1036 st->capturedType = capture;
1038 // Update the key with the final value
1041 // Update checkers bitboard, piece must be already moved
1042 st->checkersBB = EmptyBoardBB;
1047 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1051 if (bit_is_set(ci.checkSq[pt], to))
1052 st->checkersBB = SetMaskBB[to];
1055 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1058 st->checkersBB |= (attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us));
1061 st->checkersBB |= (attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us));
1067 sideToMove = opposite_color(sideToMove);
1068 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1074 /// Position::do_capture_move() is a private method used to update captured
1075 /// piece info. It is called from the main Position::do_move function.
1077 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1079 assert(capture != KING);
1083 // If the captured piece was a pawn, update pawn hash key,
1084 // otherwise update non-pawn material.
1085 if (capture == PAWN)
1087 if (ep) // en passant ?
1089 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1091 assert(to == st->epSquare);
1092 assert(relative_rank(opposite_color(them), to) == RANK_6);
1093 assert(piece_on(to) == PIECE_NONE);
1094 assert(piece_on(capsq) == make_piece(them, PAWN));
1096 board[capsq] = PIECE_NONE;
1098 st->pawnKey ^= zobrist[them][PAWN][capsq];
1101 st->npMaterial[them] -= PieceValueMidgame[capture];
1103 // Remove captured piece
1104 clear_bit(&(byColorBB[them]), capsq);
1105 clear_bit(&(byTypeBB[capture]), capsq);
1106 clear_bit(&(byTypeBB[0]), capsq);
1109 key ^= zobrist[them][capture][capsq];
1111 // Update incremental scores
1112 st->value -= pst(them, capture, capsq);
1114 // Update piece count
1115 pieceCount[them][capture]--;
1117 // Update material hash key
1118 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1120 // Update piece list, move the last piece at index[capsq] position
1122 // WARNING: This is a not perfectly revresible operation. When we
1123 // will reinsert the captured piece in undo_move() we will put it
1124 // at the end of the list and not in its original place, it means
1125 // index[] and pieceList[] are not guaranteed to be invariant to a
1126 // do_move() + undo_move() sequence.
1127 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1128 index[lastPieceSquare] = index[capsq];
1129 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1130 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1132 // Reset rule 50 counter
1137 /// Position::do_castle_move() is a private method used to make a castling
1138 /// move. It is called from the main Position::do_move function. Note that
1139 /// castling moves are encoded as "king captures friendly rook" moves, for
1140 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1142 void Position::do_castle_move(Move m) {
1144 assert(move_is_ok(m));
1145 assert(move_is_castle(m));
1147 Color us = side_to_move();
1148 Color them = opposite_color(us);
1150 // Reset capture field
1151 st->capturedType = PIECE_TYPE_NONE;
1153 // Find source squares for king and rook
1154 Square kfrom = move_from(m);
1155 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1158 assert(piece_on(kfrom) == make_piece(us, KING));
1159 assert(piece_on(rfrom) == make_piece(us, ROOK));
1161 // Find destination squares for king and rook
1162 if (rfrom > kfrom) // O-O
1164 kto = relative_square(us, SQ_G1);
1165 rto = relative_square(us, SQ_F1);
1167 kto = relative_square(us, SQ_C1);
1168 rto = relative_square(us, SQ_D1);
1171 // Remove pieces from source squares:
1172 clear_bit(&(byColorBB[us]), kfrom);
1173 clear_bit(&(byTypeBB[KING]), kfrom);
1174 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1175 clear_bit(&(byColorBB[us]), rfrom);
1176 clear_bit(&(byTypeBB[ROOK]), rfrom);
1177 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1179 // Put pieces on destination squares:
1180 set_bit(&(byColorBB[us]), kto);
1181 set_bit(&(byTypeBB[KING]), kto);
1182 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1183 set_bit(&(byColorBB[us]), rto);
1184 set_bit(&(byTypeBB[ROOK]), rto);
1185 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1187 // Update board array
1188 Piece king = make_piece(us, KING);
1189 Piece rook = make_piece(us, ROOK);
1190 board[kfrom] = board[rfrom] = PIECE_NONE;
1194 // Update piece lists
1195 pieceList[us][KING][index[kfrom]] = kto;
1196 pieceList[us][ROOK][index[rfrom]] = rto;
1197 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1198 index[kto] = index[kfrom];
1201 // Update incremental scores
1202 st->value += pst_delta(king, kfrom, kto);
1203 st->value += pst_delta(rook, rfrom, rto);
1206 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1207 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1209 // Clear en passant square
1210 if (st->epSquare != SQ_NONE)
1212 st->key ^= zobEp[st->epSquare];
1213 st->epSquare = SQ_NONE;
1216 // Update castling rights
1217 st->key ^= zobCastle[st->castleRights];
1218 st->castleRights &= castleRightsMask[kfrom];
1219 st->key ^= zobCastle[st->castleRights];
1221 // Reset rule 50 counter
1224 // Update checkers BB
1225 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1228 sideToMove = opposite_color(sideToMove);
1229 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1235 /// Position::undo_move() unmakes a move. When it returns, the position should
1236 /// be restored to exactly the same state as before the move was made.
1238 void Position::undo_move(Move m) {
1241 assert(move_is_ok(m));
1243 sideToMove = opposite_color(sideToMove);
1245 if (move_is_castle(m))
1247 undo_castle_move(m);
1251 Color us = side_to_move();
1252 Color them = opposite_color(us);
1253 Square from = move_from(m);
1254 Square to = move_to(m);
1255 bool ep = move_is_ep(m);
1256 bool pm = move_is_promotion(m);
1258 PieceType pt = type_of_piece(piece_on(to));
1260 assert(square_is_empty(from));
1261 assert(color_of_piece_on(to) == us);
1262 assert(!pm || relative_rank(us, to) == RANK_8);
1263 assert(!ep || to == st->previous->epSquare);
1264 assert(!ep || relative_rank(us, to) == RANK_6);
1265 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1267 if (pm) // promotion ?
1269 PieceType promotion = promotion_piece_type(m);
1272 assert(promotion >= KNIGHT && promotion <= QUEEN);
1273 assert(piece_on(to) == make_piece(us, promotion));
1275 // Replace promoted piece with a pawn
1276 clear_bit(&(byTypeBB[promotion]), to);
1277 set_bit(&(byTypeBB[PAWN]), to);
1279 // Update piece counts
1280 pieceCount[us][promotion]--;
1281 pieceCount[us][PAWN]++;
1283 // Update piece list replacing promotion piece with a pawn
1284 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1285 index[lastPromotionSquare] = index[to];
1286 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1287 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1288 index[to] = pieceCount[us][PAWN] - 1;
1289 pieceList[us][PAWN][index[to]] = to;
1292 // Put the piece back at the source square
1293 Bitboard move_bb = make_move_bb(to, from);
1294 do_move_bb(&(byColorBB[us]), move_bb);
1295 do_move_bb(&(byTypeBB[pt]), move_bb);
1296 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1298 board[from] = make_piece(us, pt);
1299 board[to] = PIECE_NONE;
1301 // Update piece list
1302 index[from] = index[to];
1303 pieceList[us][pt][index[from]] = from;
1305 if (st->capturedType)
1310 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1312 assert(st->capturedType != KING);
1313 assert(!ep || square_is_empty(capsq));
1315 // Restore the captured piece
1316 set_bit(&(byColorBB[them]), capsq);
1317 set_bit(&(byTypeBB[st->capturedType]), capsq);
1318 set_bit(&(byTypeBB[0]), capsq);
1320 board[capsq] = make_piece(them, st->capturedType);
1322 // Update piece count
1323 pieceCount[them][st->capturedType]++;
1325 // Update piece list, add a new captured piece in capsq square
1326 index[capsq] = pieceCount[them][st->capturedType] - 1;
1327 pieceList[them][st->capturedType][index[capsq]] = capsq;
1330 // Finally point our state pointer back to the previous state
1337 /// Position::undo_castle_move() is a private method used to unmake a castling
1338 /// move. It is called from the main Position::undo_move function. Note that
1339 /// castling moves are encoded as "king captures friendly rook" moves, for
1340 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1342 void Position::undo_castle_move(Move m) {
1344 assert(move_is_ok(m));
1345 assert(move_is_castle(m));
1347 // When we have arrived here, some work has already been done by
1348 // Position::undo_move. In particular, the side to move has been switched,
1349 // so the code below is correct.
1350 Color us = side_to_move();
1352 // Find source squares for king and rook
1353 Square kfrom = move_from(m);
1354 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1357 // Find destination squares for king and rook
1358 if (rfrom > kfrom) // O-O
1360 kto = relative_square(us, SQ_G1);
1361 rto = relative_square(us, SQ_F1);
1363 kto = relative_square(us, SQ_C1);
1364 rto = relative_square(us, SQ_D1);
1367 assert(piece_on(kto) == make_piece(us, KING));
1368 assert(piece_on(rto) == make_piece(us, ROOK));
1370 // Remove pieces from destination squares:
1371 clear_bit(&(byColorBB[us]), kto);
1372 clear_bit(&(byTypeBB[KING]), kto);
1373 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1374 clear_bit(&(byColorBB[us]), rto);
1375 clear_bit(&(byTypeBB[ROOK]), rto);
1376 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1378 // Put pieces on source squares:
1379 set_bit(&(byColorBB[us]), kfrom);
1380 set_bit(&(byTypeBB[KING]), kfrom);
1381 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1382 set_bit(&(byColorBB[us]), rfrom);
1383 set_bit(&(byTypeBB[ROOK]), rfrom);
1384 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1387 board[rto] = board[kto] = PIECE_NONE;
1388 board[rfrom] = make_piece(us, ROOK);
1389 board[kfrom] = make_piece(us, KING);
1391 // Update piece lists
1392 pieceList[us][KING][index[kto]] = kfrom;
1393 pieceList[us][ROOK][index[rto]] = rfrom;
1394 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1395 index[kfrom] = index[kto];
1398 // Finally point our state pointer back to the previous state
1405 /// Position::do_null_move makes() a "null move": It switches the side to move
1406 /// and updates the hash key without executing any move on the board.
1408 void Position::do_null_move(StateInfo& backupSt) {
1411 assert(!in_check());
1413 // Back up the information necessary to undo the null move to the supplied
1414 // StateInfo object.
1415 // Note that differently from normal case here backupSt is actually used as
1416 // a backup storage not as a new state to be used.
1417 backupSt.key = st->key;
1418 backupSt.epSquare = st->epSquare;
1419 backupSt.value = st->value;
1420 backupSt.previous = st->previous;
1421 backupSt.pliesFromNull = st->pliesFromNull;
1422 st->previous = &backupSt;
1424 // Save the current key to the history[] array, in order to be able to
1425 // detect repetition draws.
1426 history[st->gamePly++] = st->key;
1428 // Update the necessary information
1429 if (st->epSquare != SQ_NONE)
1430 st->key ^= zobEp[st->epSquare];
1432 st->key ^= zobSideToMove;
1433 prefetch((char*)TT.first_entry(st->key));
1435 sideToMove = opposite_color(sideToMove);
1436 st->epSquare = SQ_NONE;
1438 st->pliesFromNull = 0;
1439 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1443 /// Position::undo_null_move() unmakes a "null move".
1445 void Position::undo_null_move() {
1448 assert(!in_check());
1450 // Restore information from the our backup StateInfo object
1451 StateInfo* backupSt = st->previous;
1452 st->key = backupSt->key;
1453 st->epSquare = backupSt->epSquare;
1454 st->value = backupSt->value;
1455 st->previous = backupSt->previous;
1456 st->pliesFromNull = backupSt->pliesFromNull;
1458 // Update the necessary information
1459 sideToMove = opposite_color(sideToMove);
1465 /// Position::see() is a static exchange evaluator: It tries to estimate the
1466 /// material gain or loss resulting from a move. There are three versions of
1467 /// this function: One which takes a destination square as input, one takes a
1468 /// move, and one which takes a 'from' and a 'to' square. The function does
1469 /// not yet understand promotions captures.
1471 int Position::see_sign(Move m) const {
1473 assert(move_is_ok(m));
1475 Square from = move_from(m);
1476 Square to = move_to(m);
1478 // Early return if SEE cannot be negative because captured piece value
1479 // is not less then capturing one. Note that king moves always return
1480 // here because king midgame value is set to 0.
1481 if (piece_value_midgame(piece_on(to)) >= piece_value_midgame(piece_on(from)))
1487 int Position::see(Move m) const {
1490 Bitboard occupied, attackers, stmAttackers, b;
1491 int swapList[32], slIndex = 1;
1492 PieceType capturedType, pt;
1495 assert(move_is_ok(m));
1497 // As castle moves are implemented as capturing the rook, they have
1498 // SEE == RookValueMidgame most of the times (unless the rook is under
1500 if (move_is_castle(m))
1503 from = move_from(m);
1505 capturedType = type_of_piece(piece_on(to));
1506 occupied = occupied_squares();
1508 // Handle en passant moves
1509 if (st->epSquare == to && type_of_piece(piece_on(from)) == PAWN)
1511 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1513 assert(capturedType == PIECE_TYPE_NONE);
1514 assert(type_of_piece(piece_on(capQq)) == PAWN);
1516 // Remove the captured pawn
1517 clear_bit(&occupied, capQq);
1518 capturedType = PAWN;
1521 // Find all attackers to the destination square, with the moving piece
1522 // removed, but possibly an X-ray attacker added behind it.
1523 clear_bit(&occupied, from);
1524 attackers = attackers_to(to, occupied);
1526 // If the opponent has no attackers we are finished
1527 stm = opposite_color(color_of_piece_on(from));
1528 stmAttackers = attackers & pieces_of_color(stm);
1530 return PieceValueMidgame[capturedType];
1532 // The destination square is defended, which makes things rather more
1533 // difficult to compute. We proceed by building up a "swap list" containing
1534 // the material gain or loss at each stop in a sequence of captures to the
1535 // destination square, where the sides alternately capture, and always
1536 // capture with the least valuable piece. After each capture, we look for
1537 // new X-ray attacks from behind the capturing piece.
1538 swapList[0] = PieceValueMidgame[capturedType];
1539 capturedType = type_of_piece(piece_on(from));
1542 // Locate the least valuable attacker for the side to move. The loop
1543 // below looks like it is potentially infinite, but it isn't. We know
1544 // that the side to move still has at least one attacker left.
1545 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1548 // Remove the attacker we just found from the 'occupied' bitboard,
1549 // and scan for new X-ray attacks behind the attacker.
1550 b = stmAttackers & pieces(pt);
1551 occupied ^= (b & (~b + 1));
1552 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1553 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1555 attackers &= occupied; // Cut out pieces we've already done
1557 // Add the new entry to the swap list
1558 assert(slIndex < 32);
1559 swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1562 // Remember the value of the capturing piece, and change the side to
1563 // move before beginning the next iteration.
1565 stm = opposite_color(stm);
1566 stmAttackers = attackers & pieces_of_color(stm);
1568 // Stop before processing a king capture
1569 if (capturedType == KING && stmAttackers)
1571 assert(slIndex < 32);
1572 swapList[slIndex++] = QueenValueMidgame*10;
1575 } while (stmAttackers);
1577 // Having built the swap list, we negamax through it to find the best
1578 // achievable score from the point of view of the side to move.
1580 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1586 /// Position::clear() erases the position object to a pristine state, with an
1587 /// empty board, white to move, and no castling rights.
1589 void Position::clear() {
1592 memset(st, 0, sizeof(StateInfo));
1593 st->epSquare = SQ_NONE;
1594 startPosPlyCounter = 0;
1597 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1598 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1599 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1600 memset(index, 0, sizeof(int) * 64);
1602 for (int i = 0; i < 64; i++)
1603 board[i] = PIECE_NONE;
1605 for (int i = 0; i < 8; i++)
1606 for (int j = 0; j < 16; j++)
1607 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1609 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1610 castleRightsMask[sq] = ALL_CASTLES;
1613 initialKFile = FILE_E;
1614 initialKRFile = FILE_H;
1615 initialQRFile = FILE_A;
1619 /// Position::put_piece() puts a piece on the given square of the board,
1620 /// updating the board array, pieces list, bitboards, and piece counts.
1622 void Position::put_piece(Piece p, Square s) {
1624 Color c = color_of_piece(p);
1625 PieceType pt = type_of_piece(p);
1628 index[s] = pieceCount[c][pt]++;
1629 pieceList[c][pt][index[s]] = s;
1631 set_bit(&(byTypeBB[pt]), s);
1632 set_bit(&(byColorBB[c]), s);
1633 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1637 /// Position::compute_key() computes the hash key of the position. The hash
1638 /// key is usually updated incrementally as moves are made and unmade, the
1639 /// compute_key() function is only used when a new position is set up, and
1640 /// to verify the correctness of the hash key when running in debug mode.
1642 Key Position::compute_key() const {
1644 Key result = zobCastle[st->castleRights];
1646 for (Square s = SQ_A1; s <= SQ_H8; s++)
1647 if (square_is_occupied(s))
1648 result ^= zobrist[color_of_piece_on(s)][type_of_piece(piece_on(s))][s];
1650 if (ep_square() != SQ_NONE)
1651 result ^= zobEp[ep_square()];
1653 if (side_to_move() == BLACK)
1654 result ^= zobSideToMove;
1660 /// Position::compute_pawn_key() computes the hash key of the position. The
1661 /// hash key is usually updated incrementally as moves are made and unmade,
1662 /// the compute_pawn_key() function is only used when a new position is set
1663 /// up, and to verify the correctness of the pawn hash key when running in
1666 Key Position::compute_pawn_key() const {
1671 for (Color c = WHITE; c <= BLACK; c++)
1673 b = pieces(PAWN, c);
1675 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1681 /// Position::compute_material_key() computes the hash key of the position.
1682 /// The hash key is usually updated incrementally as moves are made and unmade,
1683 /// the compute_material_key() function is only used when a new position is set
1684 /// up, and to verify the correctness of the material hash key when running in
1687 Key Position::compute_material_key() const {
1692 for (Color c = WHITE; c <= BLACK; c++)
1693 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1695 count = piece_count(c, pt);
1696 for (int i = 0; i < count; i++)
1697 result ^= zobrist[c][pt][i];
1703 /// Position::compute_value() compute the incremental scores for the middle
1704 /// game and the endgame. These functions are used to initialize the incremental
1705 /// scores when a new position is set up, and to verify that the scores are correctly
1706 /// updated by do_move and undo_move when the program is running in debug mode.
1707 Score Position::compute_value() const {
1710 Score result = SCORE_ZERO;
1712 for (Color c = WHITE; c <= BLACK; c++)
1713 for (PieceType pt = PAWN; pt <= KING; pt++)
1717 result += pst(c, pt, pop_1st_bit(&b));
1720 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1725 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1726 /// game material value for the given side. Material values are updated
1727 /// incrementally during the search, this function is only used while
1728 /// initializing a new Position object.
1730 Value Position::compute_non_pawn_material(Color c) const {
1732 Value result = VALUE_ZERO;
1734 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1735 result += piece_count(c, pt) * PieceValueMidgame[pt];
1741 /// Position::is_draw() tests whether the position is drawn by material,
1742 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1743 /// must be done by the search.
1744 template<bool SkipRepetition>
1745 bool Position::is_draw() const {
1747 // Draw by material?
1749 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1752 // Draw by the 50 moves rule?
1753 if (st->rule50 > 99 && !is_mate())
1756 // Draw by repetition?
1757 if (!SkipRepetition)
1758 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1759 if (history[st->gamePly - i] == st->key)
1765 // Explicit template instantiations
1766 template bool Position::is_draw<false>() const;
1767 template bool Position::is_draw<true>() const;
1770 /// Position::is_mate() returns true or false depending on whether the
1771 /// side to move is checkmated.
1773 bool Position::is_mate() const {
1775 MoveStack moves[MAX_MOVES];
1776 return in_check() && generate<MV_LEGAL>(*this, moves) == moves;
1780 /// Position::init() is a static member function which initializes at
1781 /// startup the various arrays used to compute hash keys and the piece
1782 /// square tables. The latter is a two-step operation: First, the white
1783 /// halves of the tables are copied from the MgPST[][] and EgPST[][] arrays.
1784 /// Second, the black halves of the tables are initialized by mirroring
1785 /// and changing the sign of the corresponding white scores.
1787 void Position::init() {
1791 for (Color c = WHITE; c <= BLACK; c++)
1792 for (PieceType pt = PAWN; pt <= KING; pt++)
1793 for (Square s = SQ_A1; s <= SQ_H8; s++)
1794 zobrist[c][pt][s] = rk.rand<Key>();
1796 for (Square s = SQ_A1; s <= SQ_H8; s++)
1797 zobEp[s] = rk.rand<Key>();
1799 for (int i = 0; i < 16; i++)
1800 zobCastle[i] = rk.rand<Key>();
1802 zobSideToMove = rk.rand<Key>();
1803 zobExclusion = rk.rand<Key>();
1805 for (Square s = SQ_A1; s <= SQ_H8; s++)
1806 for (Piece p = WP; p <= WK; p++)
1807 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1809 for (Square s = SQ_A1; s <= SQ_H8; s++)
1810 for (Piece p = BP; p <= BK; p++)
1811 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1815 /// Position::flip() flips position with the white and black sides reversed. This
1816 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1818 void Position::flip() {
1822 // Make a copy of current position before to start changing
1823 const Position pos(*this, threadID);
1826 threadID = pos.thread();
1829 for (Square s = SQ_A1; s <= SQ_H8; s++)
1830 if (!pos.square_is_empty(s))
1831 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1834 sideToMove = opposite_color(pos.side_to_move());
1837 if (pos.can_castle_kingside(WHITE)) set_castle_kingside(BLACK);
1838 if (pos.can_castle_queenside(WHITE)) set_castle_queenside(BLACK);
1839 if (pos.can_castle_kingside(BLACK)) set_castle_kingside(WHITE);
1840 if (pos.can_castle_queenside(BLACK)) set_castle_queenside(WHITE);
1842 initialKFile = pos.initialKFile;
1843 initialKRFile = pos.initialKRFile;
1844 initialQRFile = pos.initialQRFile;
1846 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1847 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1848 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1849 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1850 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1851 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1853 // En passant square
1854 if (pos.st->epSquare != SQ_NONE)
1855 st->epSquare = flip_square(pos.st->epSquare);
1861 st->key = compute_key();
1862 st->pawnKey = compute_pawn_key();
1863 st->materialKey = compute_material_key();
1865 // Incremental scores
1866 st->value = compute_value();
1869 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1870 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1876 /// Position::is_ok() performs some consitency checks for the position object.
1877 /// This is meant to be helpful when debugging.
1879 bool Position::is_ok(int* failedStep) const {
1881 // What features of the position should be verified?
1882 const bool debugAll = false;
1884 const bool debugBitboards = debugAll || false;
1885 const bool debugKingCount = debugAll || false;
1886 const bool debugKingCapture = debugAll || false;
1887 const bool debugCheckerCount = debugAll || false;
1888 const bool debugKey = debugAll || false;
1889 const bool debugMaterialKey = debugAll || false;
1890 const bool debugPawnKey = debugAll || false;
1891 const bool debugIncrementalEval = debugAll || false;
1892 const bool debugNonPawnMaterial = debugAll || false;
1893 const bool debugPieceCounts = debugAll || false;
1894 const bool debugPieceList = debugAll || false;
1895 const bool debugCastleSquares = debugAll || false;
1897 if (failedStep) *failedStep = 1;
1900 if (side_to_move() != WHITE && side_to_move() != BLACK)
1903 // Are the king squares in the position correct?
1904 if (failedStep) (*failedStep)++;
1905 if (piece_on(king_square(WHITE)) != WK)
1908 if (failedStep) (*failedStep)++;
1909 if (piece_on(king_square(BLACK)) != BK)
1913 if (failedStep) (*failedStep)++;
1914 if (!square_is_ok(make_square(initialKRFile, RANK_1)))
1917 if (!square_is_ok(make_square(initialQRFile, RANK_1)))
1920 // Do both sides have exactly one king?
1921 if (failedStep) (*failedStep)++;
1924 int kingCount[2] = {0, 0};
1925 for (Square s = SQ_A1; s <= SQ_H8; s++)
1926 if (type_of_piece(piece_on(s)) == KING)
1927 kingCount[color_of_piece_on(s)]++;
1929 if (kingCount[0] != 1 || kingCount[1] != 1)
1933 // Can the side to move capture the opponent's king?
1934 if (failedStep) (*failedStep)++;
1935 if (debugKingCapture)
1937 Color us = side_to_move();
1938 Color them = opposite_color(us);
1939 Square ksq = king_square(them);
1940 if (attackers_to(ksq) & pieces_of_color(us))
1944 // Is there more than 2 checkers?
1945 if (failedStep) (*failedStep)++;
1946 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1950 if (failedStep) (*failedStep)++;
1953 // The intersection of the white and black pieces must be empty
1954 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1957 // The union of the white and black pieces must be equal to all
1959 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1962 // Separate piece type bitboards must have empty intersections
1963 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1964 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1965 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1969 // En passant square OK?
1970 if (failedStep) (*failedStep)++;
1971 if (ep_square() != SQ_NONE)
1973 // The en passant square must be on rank 6, from the point of view of the
1975 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1980 if (failedStep) (*failedStep)++;
1981 if (debugKey && st->key != compute_key())
1984 // Pawn hash key OK?
1985 if (failedStep) (*failedStep)++;
1986 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1989 // Material hash key OK?
1990 if (failedStep) (*failedStep)++;
1991 if (debugMaterialKey && st->materialKey != compute_material_key())
1994 // Incremental eval OK?
1995 if (failedStep) (*failedStep)++;
1996 if (debugIncrementalEval && st->value != compute_value())
1999 // Non-pawn material OK?
2000 if (failedStep) (*failedStep)++;
2001 if (debugNonPawnMaterial)
2003 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2006 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2011 if (failedStep) (*failedStep)++;
2012 if (debugPieceCounts)
2013 for (Color c = WHITE; c <= BLACK; c++)
2014 for (PieceType pt = PAWN; pt <= KING; pt++)
2015 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2018 if (failedStep) (*failedStep)++;
2020 for (Color c = WHITE; c <= BLACK; c++)
2021 for (PieceType pt = PAWN; pt <= KING; pt++)
2022 for (int i = 0; i < pieceCount[c][pt]; i++)
2024 if (piece_on(piece_list(c, pt, i)) != make_piece(c, pt))
2027 if (index[piece_list(c, pt, i)] != i)
2031 if (failedStep) (*failedStep)++;
2032 if (debugCastleSquares)
2034 for (Color c = WHITE; c <= BLACK; c++)
2036 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != make_piece(c, ROOK))
2039 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != make_piece(c, ROOK))
2042 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2044 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2046 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2048 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2052 if (failedStep) *failedStep = 0;