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/>.
34 #include "ucioption.h"
40 Key Position::zobrist[2][8][64];
41 Key Position::zobEp[64];
42 Key Position::zobCastle[16];
43 Key Position::zobSideToMove;
44 Key Position::zobExclusion;
46 Score Position::PieceSquareTable[16][64];
48 // Material values arrays, indexed by Piece
49 const Value Position::PieceValueMidgame[17] = {
51 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
52 RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
53 VALUE_ZERO, VALUE_ZERO,
54 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
55 RookValueMidgame, QueenValueMidgame
58 const Value Position::PieceValueEndgame[17] = {
60 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
61 RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
62 VALUE_ZERO, VALUE_ZERO,
63 PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
64 RookValueEndgame, QueenValueEndgame
67 // Material values array used by SEE, indexed by PieceType
68 const Value Position::seeValues[] = {
70 PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
71 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
77 // Bonus for having the side to move (modified by Joona Kiiski)
78 const Score TempoValue = make_score(48, 22);
80 struct PieceLetters : public std::map<char, Piece> {
84 operator[]('K') = WK; operator[]('k') = BK;
85 operator[]('Q') = WQ; operator[]('q') = BQ;
86 operator[]('R') = WR; operator[]('r') = BR;
87 operator[]('B') = WB; operator[]('b') = BB;
88 operator[]('N') = WN; operator[]('n') = BN;
89 operator[]('P') = WP; operator[]('p') = BP;
90 operator[](' ') = PIECE_NONE;
91 operator[]('.') = PIECE_NONE_DARK_SQ;
94 char from_piece(Piece p) const {
96 std::map<char, Piece>::const_iterator it;
97 for (it = begin(); it != end(); ++it)
106 PieceLetters pieceLetters;
112 CheckInfo::CheckInfo(const Position& pos) {
114 Color us = pos.side_to_move();
115 Color them = opposite_color(us);
117 ksq = pos.king_square(them);
118 dcCandidates = pos.discovered_check_candidates(us);
120 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
121 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
122 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
123 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
124 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
125 checkSq[KING] = EmptyBoardBB;
129 /// Position c'tors. Here we always create a copy of the original position
130 /// or the FEN string, we want the new born Position object do not depend
131 /// on any external data so we detach state pointer from the source one.
133 Position::Position(const Position& pos, int th) {
135 memcpy(this, &pos, sizeof(Position));
136 detach(); // Always detach() in copy c'tor to avoid surprises
141 Position::Position(const string& fen, bool isChess960, int th) {
143 from_fen(fen, isChess960);
148 /// Position::detach() copies the content of the current state and castling
149 /// masks inside the position itself. This is needed when the st pointee could
150 /// become stale, as example because the caller is about to going out of scope.
152 void Position::detach() {
156 st->previous = NULL; // as a safe guard
160 /// Position::from_fen() initializes the position object with the given FEN
161 /// string. This function is not very robust - make sure that input FENs are
162 /// correct (this is assumed to be the responsibility of the GUI).
164 void Position::from_fen(const string& fen, bool isChess960) {
166 A FEN string defines a particular position using only the ASCII character set.
168 A FEN string contains six fields. The separator between fields is a space. The fields are:
170 1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
171 with rank 1; within each rank, the contents of each square are described from file A through file H.
172 Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
173 from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
174 while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
175 of blank squares), and "/" separate ranks.
177 2) Active color. "w" means white moves next, "b" means black.
179 3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
180 letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
181 kingside), and/or "q" (Black can castle queenside).
183 4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
184 If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
185 regardless of whether there is a pawn in position to make an en passant capture.
187 5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
188 to determine if a draw can be claimed under the fifty-move rule.
190 6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
195 std::istringstream ss(fen);
200 // 1. Piece placement field
201 while (ss.get(token) && token != ' ')
203 if (pieceLetters.find(token) != pieceLetters.end())
205 put_piece(pieceLetters[token], sq);
208 else if (isdigit(token))
209 sq += Square(token - '0'); // Skip the given number of files
210 else if (token == '/')
211 sq -= SQ_A3; // Jump back of 2 rows
217 if (!ss.get(token) || (token != 'w' && token != 'b'))
220 sideToMove = (token == 'w' ? WHITE : BLACK);
222 if (!ss.get(token) || token != ' ')
225 // 3. Castling availability
226 while (ss.get(token) && token != ' ')
227 if (!set_castling_rights(token))
230 // 4. En passant square
232 if ( (ss.get(col) && (col >= 'a' && col <= 'h'))
233 && (ss.get(row) && (row == '3' || row == '6')))
235 st->epSquare = make_square(file_from_char(col), rank_from_char(row));
237 // Ignore if no capture is possible
238 Color them = opposite_color(sideToMove);
239 if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
240 st->epSquare = SQ_NONE;
247 // 6. Fullmove number
249 startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
251 // Various initialisations
252 castleRightsMask[make_square(initialKFile, RANK_1)] ^= WHITE_OO | WHITE_OOO;
253 castleRightsMask[make_square(initialKFile, RANK_8)] ^= BLACK_OO | BLACK_OOO;
254 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
255 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
256 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
257 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
259 chess960 = isChess960;
262 st->key = compute_key();
263 st->pawnKey = compute_pawn_key();
264 st->materialKey = compute_material_key();
265 st->value = compute_value();
266 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
267 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
271 cout << "Error in FEN string: " << fen << endl;
275 /// Position::set_castling_rights() sets castling parameters castling avaiability.
276 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
277 /// that uses the letters of the columns on which the rooks began the game instead
278 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
279 /// associated with the castling right, the traditional castling tag will be replaced
280 /// by the file letter of the involved rook as for the Shredder-FEN.
282 bool Position::set_castling_rights(char token) {
284 Color c = token >= 'a' ? BLACK : WHITE;
285 Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
286 Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
287 Piece rook = (c == WHITE ? WR : BR);
289 initialKFile = square_file(king_square(c));
290 token = char(toupper(token));
294 for (Square sq = sqH; sq >= sqA; sq--)
295 if (piece_on(sq) == rook)
298 initialKRFile = square_file(sq);
302 else if (token == 'Q')
304 for (Square sq = sqA; sq <= sqH; sq++)
305 if (piece_on(sq) == rook)
308 initialQRFile = square_file(sq);
312 else if (token >= 'A' && token <= 'H')
314 File rookFile = File(token - 'A') + FILE_A;
315 if (rookFile < initialKFile)
318 initialQRFile = rookFile;
323 initialKRFile = rookFile;
333 /// Position::to_fen() returns a FEN representation of the position. In case
334 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
336 const string Position::to_fen() const {
342 for (Rank rank = RANK_8; rank >= RANK_1; rank--, fen += '/')
344 for (File file = FILE_A; file <= FILE_H; file++)
346 sq = make_square(file, rank);
348 if (square_is_occupied(sq))
355 fen += pieceLetters.from_piece(piece_on(sq));
367 fen += (sideToMove == WHITE ? " w " : " b ");
369 if (st->castleRights != CASTLES_NONE)
371 if (can_castle_kingside(WHITE))
372 fen += chess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
374 if (can_castle_queenside(WHITE))
375 fen += chess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
377 if (can_castle_kingside(BLACK))
378 fen += chess960 ? file_to_char(initialKRFile) : 'k';
380 if (can_castle_queenside(BLACK))
381 fen += chess960 ? file_to_char(initialQRFile) : 'q';
385 fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
390 /// Position::print() prints an ASCII representation of the position to
391 /// the standard output. If a move is given then also the san is printed.
393 void Position::print(Move move) const {
395 const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
399 Position p(*this, thread());
400 string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
401 cout << "\nMove is: " << dd << move_to_san(p, move);
404 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
406 cout << dottedLine << '|';
407 for (File file = FILE_A; file <= FILE_H; file++)
409 Square sq = make_square(file, rank);
410 Piece piece = piece_on(sq);
412 if (piece == PIECE_NONE && square_color(sq) == DARK)
413 piece = PIECE_NONE_DARK_SQ;
415 char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
416 cout << c << pieceLetters.from_piece(piece) << c << '|';
419 cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
423 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
424 /// king) pieces for the given color and for the given pinner type. Or, when
425 /// template parameter FindPinned is false, the pieces of the given color
426 /// candidate for a discovery check against the enemy king.
427 /// Bitboard checkersBB must be already updated when looking for pinners.
429 template<bool FindPinned>
430 Bitboard Position::hidden_checkers(Color c) const {
432 Bitboard result = EmptyBoardBB;
433 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
435 // Pinned pieces protect our king, dicovery checks attack
437 Square ksq = king_square(FindPinned ? c : opposite_color(c));
439 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
440 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
442 if (FindPinned && pinners)
443 pinners &= ~st->checkersBB;
447 Square s = pop_1st_bit(&pinners);
448 Bitboard b = squares_between(s, ksq) & occupied_squares();
452 if ( !(b & (b - 1)) // Only one bit set?
453 && (b & pieces_of_color(c))) // Is an our piece?
460 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
461 /// king) pieces for the given color. Note that checkersBB bitboard must
462 /// be already updated.
464 Bitboard Position::pinned_pieces(Color c) const {
466 return hidden_checkers<true>(c);
470 /// Position:discovered_check_candidates() returns a bitboard containing all
471 /// pieces for the given side which are candidates for giving a discovered
472 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
473 /// to be already updated.
475 Bitboard Position::discovered_check_candidates(Color c) const {
477 return hidden_checkers<false>(c);
480 /// Position::attackers_to() computes a bitboard containing all pieces which
481 /// attacks a given square.
483 Bitboard Position::attackers_to(Square s) const {
485 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
486 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
487 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
488 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
489 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
490 | (attacks_from<KING>(s) & pieces(KING));
493 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
495 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
496 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
497 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
498 | (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
499 | (bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))
500 | (attacks_from<KING>(s) & pieces(KING));
503 /// Position::attacks_from() computes a bitboard of all attacks
504 /// of a given piece put in a given square.
506 Bitboard Position::attacks_from(Piece p, Square s) const {
508 assert(square_is_ok(s));
512 case WB: case BB: return attacks_from<BISHOP>(s);
513 case WR: case BR: return attacks_from<ROOK>(s);
514 case WQ: case BQ: return attacks_from<QUEEN>(s);
515 default: return StepAttacksBB[p][s];
519 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
521 assert(square_is_ok(s));
525 case WB: case BB: return bishop_attacks_bb(s, occ);
526 case WR: case BR: return rook_attacks_bb(s, occ);
527 case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
528 default: return StepAttacksBB[p][s];
533 /// Position::move_attacks_square() tests whether a move from the current
534 /// position attacks a given square.
536 bool Position::move_attacks_square(Move m, Square s) const {
538 assert(move_is_ok(m));
539 assert(square_is_ok(s));
542 Square f = move_from(m), t = move_to(m);
544 assert(square_is_occupied(f));
546 if (bit_is_set(attacks_from(piece_on(f), t), s))
549 // Move the piece and scan for X-ray attacks behind it
550 occ = occupied_squares();
551 do_move_bb(&occ, make_move_bb(f, t));
552 xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
553 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
554 & pieces_of_color(color_of_piece_on(f));
556 // If we have attacks we need to verify that are caused by our move
557 // and are not already existent ones.
558 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
562 /// Position::find_checkers() computes the checkersBB bitboard, which
563 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
564 /// currently works by calling Position::attackers_to, which is probably
565 /// inefficient. Consider rewriting this function to use the last move
566 /// played, like in non-bitboard versions of Glaurung.
568 void Position::find_checkers() {
570 Color us = side_to_move();
571 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
575 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
577 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
580 assert(move_is_ok(m));
581 assert(pinned == pinned_pieces(side_to_move()));
583 Color us = side_to_move();
584 Square from = move_from(m);
586 assert(color_of_piece_on(from) == us);
587 assert(piece_on(king_square(us)) == make_piece(us, KING));
589 // En passant captures are a tricky special case. Because they are
590 // rather uncommon, we do it simply by testing whether the king is attacked
591 // after the move is made
594 Color them = opposite_color(us);
595 Square to = move_to(m);
596 Square capsq = make_square(square_file(to), square_rank(from));
597 Square ksq = king_square(us);
598 Bitboard b = occupied_squares();
600 assert(to == ep_square());
601 assert(piece_on(from) == make_piece(us, PAWN));
602 assert(piece_on(capsq) == make_piece(them, PAWN));
603 assert(piece_on(to) == PIECE_NONE);
606 clear_bit(&b, capsq);
609 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
610 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
613 // If the moving piece is a king, check whether the destination
614 // square is attacked by the opponent. Castling moves are checked
615 // for legality during move generation.
616 if (type_of_piece_on(from) == KING)
617 return move_is_castle(m) || !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
619 // A non-king move is legal if and only if it is not pinned or it
620 // is moving along the ray towards or away from the king.
622 || !bit_is_set(pinned, from)
623 || squares_aligned(from, move_to(m), king_square(us));
627 /// Position::move_is_pl_slow() takes a position and a move and tests whether
628 /// the move is pseudo legal. This version is not very fast and should be used
629 /// only in non time-critical paths.
631 bool Position::move_is_pl_slow(const Move m) const {
633 MoveStack mlist[MAX_MOVES];
634 MoveStack *cur, *last;
636 last = in_check() ? generate<MV_EVASION>(*this, mlist)
637 : generate<MV_NON_EVASION>(*this, mlist);
639 for (cur = mlist; cur != last; cur++)
647 /// Fast version of Position::move_is_pl() that takes a position a move and a
648 /// bitboard of pinned pieces as input, and tests whether the move is pseudo legal.
650 bool Position::move_is_pl(const Move m) const {
654 Color us = sideToMove;
655 Color them = opposite_color(sideToMove);
656 Square from = move_from(m);
657 Square to = move_to(m);
658 Piece pc = piece_on(from);
660 // Use a slower but simpler function for uncommon cases
661 if (move_is_special(m))
662 return move_is_pl_slow(m);
664 // Is not a promotion, so promotion piece must be empty
665 if (move_promotion_piece(m) - 2 != PIECE_TYPE_NONE)
668 // If the from square is not occupied by a piece belonging to the side to
669 // move, the move is obviously not legal.
670 if (pc == PIECE_NONE || color_of_piece(pc) != us)
673 // The destination square cannot be occupied by a friendly piece
674 if (color_of_piece_on(to) == us)
677 // Handle the special case of a pawn move
678 if (type_of_piece(pc) == PAWN)
680 // Move direction must be compatible with pawn color
681 int direction = to - from;
682 if ((us == WHITE) != (direction > 0))
685 // We have already handled promotion moves, so destination
686 // cannot be on the 8/1th rank.
687 if (square_rank(to) == RANK_8 || square_rank(to) == RANK_1)
690 // Proceed according to the square delta between the origin and
691 // destination squares.
698 // Capture. The destination square must be occupied by an enemy
699 // piece (en passant captures was handled earlier).
700 if (color_of_piece_on(to) != them)
703 // From and to files must be one file apart, avoids a7h5
704 if (abs(square_file(from) - square_file(to)) != 1)
710 // Pawn push. The destination square must be empty.
711 if (!square_is_empty(to))
716 // Double white pawn push. The destination square must be on the fourth
717 // rank, and both the destination square and the square between the
718 // source and destination squares must be empty.
719 if ( square_rank(to) != RANK_4
720 || !square_is_empty(to)
721 || !square_is_empty(from + DELTA_N))
726 // Double black pawn push. The destination square must be on the fifth
727 // rank, and both the destination square and the square between the
728 // source and destination squares must be empty.
729 if ( square_rank(to) != RANK_5
730 || !square_is_empty(to)
731 || !square_is_empty(from + DELTA_S))
739 else if (!bit_is_set(attacks_from(pc, from), to))
744 // In case of king moves under check we have to remove king so to catch
745 // as invalid moves like b1a1 when opposite queen is on c1.
746 if (type_of_piece_on(from) == KING)
748 Bitboard b = occupied_squares();
750 if (attackers_to(move_to(m), b) & pieces_of_color(opposite_color(us)))
755 Bitboard target = checkers();
756 Square checksq = pop_1st_bit(&target);
758 if (target) // double check ? In this case a king move is required
761 // Our move must be a blocking evasion or a capture of the checking piece
762 target = squares_between(checksq, king_square(us)) | checkers();
763 if (!bit_is_set(target, move_to(m)))
772 /// Position::move_gives_check() tests whether a pseudo-legal move is a check
774 bool Position::move_gives_check(Move m) const {
776 return move_gives_check(m, CheckInfo(*this));
779 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
782 assert(move_is_ok(m));
783 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
784 assert(color_of_piece_on(move_from(m)) == side_to_move());
785 assert(piece_on(ci.ksq) == make_piece(opposite_color(side_to_move()), KING));
787 Square from = move_from(m);
788 Square to = move_to(m);
789 PieceType pt = type_of_piece_on(from);
792 if (bit_is_set(ci.checkSq[pt], to))
796 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
798 // For pawn and king moves we need to verify also direction
799 if ( (pt != PAWN && pt != KING)
800 || !squares_aligned(from, to, ci.ksq))
804 // Can we skip the ugly special cases ?
805 if (!move_is_special(m))
808 Color us = side_to_move();
809 Bitboard b = occupied_squares();
811 // Promotion with check ?
812 if (move_is_promotion(m))
816 switch (move_promotion_piece(m))
819 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
821 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
823 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
825 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
831 // En passant capture with check ? We have already handled the case
832 // of direct checks and ordinary discovered check, the only case we
833 // need to handle is the unusual case of a discovered check through
834 // the captured pawn.
837 Square capsq = make_square(square_file(to), square_rank(from));
839 clear_bit(&b, capsq);
841 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
842 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
845 // Castling with check ?
846 if (move_is_castle(m))
848 Square kfrom, kto, rfrom, rto;
854 kto = relative_square(us, SQ_G1);
855 rto = relative_square(us, SQ_F1);
857 kto = relative_square(us, SQ_C1);
858 rto = relative_square(us, SQ_D1);
860 clear_bit(&b, kfrom);
861 clear_bit(&b, rfrom);
864 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
871 /// Position::do_setup_move() makes a permanent move on the board. It should
872 /// be used when setting up a position on board. You can't undo the move.
874 void Position::do_setup_move(Move m) {
880 // Reset "game ply" in case we made a non-reversible move.
881 // "game ply" is used for repetition detection.
885 // Update the number of plies played from the starting position
886 startPosPlyCounter++;
888 // Our StateInfo newSt is about going out of scope so copy
889 // its content before it disappears.
894 /// Position::do_move() makes a move, and saves all information necessary
895 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
896 /// moves should be filtered out before this function is called.
898 void Position::do_move(Move m, StateInfo& newSt) {
901 do_move(m, newSt, ci, move_gives_check(m, ci));
904 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
907 assert(move_is_ok(m));
908 assert(&newSt != st);
913 // Copy some fields of old state to our new StateInfo object except the
914 // ones which are recalculated from scratch anyway, then switch our state
915 // pointer to point to the new, ready to be updated, state.
916 struct ReducedStateInfo {
917 Key pawnKey, materialKey;
918 int castleRights, rule50, gamePly, pliesFromNull;
924 memcpy(&newSt, st, sizeof(ReducedStateInfo));
929 // Save the current key to the history[] array, in order to be able to
930 // detect repetition draws.
931 history[st->gamePly++] = key;
933 // Update side to move
934 key ^= zobSideToMove;
936 // Increment the 50 moves rule draw counter. Resetting it to zero in the
937 // case of non-reversible moves is taken care of later.
941 if (move_is_castle(m))
948 Color us = side_to_move();
949 Color them = opposite_color(us);
950 Square from = move_from(m);
951 Square to = move_to(m);
952 bool ep = move_is_ep(m);
953 bool pm = move_is_promotion(m);
955 Piece piece = piece_on(from);
956 PieceType pt = type_of_piece(piece);
957 PieceType capture = ep ? PAWN : type_of_piece_on(to);
959 assert(color_of_piece_on(from) == us);
960 assert(color_of_piece_on(to) == them || square_is_empty(to));
961 assert(!(ep || pm) || piece == make_piece(us, PAWN));
962 assert(!pm || relative_rank(us, to) == RANK_8);
965 do_capture_move(key, capture, them, to, ep);
968 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
970 // Reset en passant square
971 if (st->epSquare != SQ_NONE)
973 key ^= zobEp[st->epSquare];
974 st->epSquare = SQ_NONE;
977 // Update castle rights, try to shortcut a common case
978 int cm = castleRightsMask[from] & castleRightsMask[to];
979 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
981 key ^= zobCastle[st->castleRights];
982 st->castleRights &= castleRightsMask[from];
983 st->castleRights &= castleRightsMask[to];
984 key ^= zobCastle[st->castleRights];
987 // Prefetch TT access as soon as we know key is updated
988 prefetch((char*)TT.first_entry(key));
991 Bitboard move_bb = make_move_bb(from, to);
992 do_move_bb(&(byColorBB[us]), move_bb);
993 do_move_bb(&(byTypeBB[pt]), move_bb);
994 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
996 board[to] = board[from];
997 board[from] = PIECE_NONE;
999 // Update piece lists, note that index[from] is not updated and
1000 // becomes stale. This works as long as index[] is accessed just
1001 // by known occupied squares.
1002 index[to] = index[from];
1003 pieceList[us][pt][index[to]] = to;
1005 // If the moving piece was a pawn do some special extra work
1008 // Reset rule 50 draw counter
1011 // Update pawn hash key and prefetch in L1/L2 cache
1012 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1014 // Set en passant square, only if moved pawn can be captured
1015 if ((to ^ from) == 16)
1017 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
1019 st->epSquare = Square((int(from) + int(to)) / 2);
1020 key ^= zobEp[st->epSquare];
1024 if (pm) // promotion ?
1026 PieceType promotion = move_promotion_piece(m);
1028 assert(promotion >= KNIGHT && promotion <= QUEEN);
1030 // Insert promoted piece instead of pawn
1031 clear_bit(&(byTypeBB[PAWN]), to);
1032 set_bit(&(byTypeBB[promotion]), to);
1033 board[to] = make_piece(us, promotion);
1035 // Update piece counts
1036 pieceCount[us][promotion]++;
1037 pieceCount[us][PAWN]--;
1039 // Update material key
1040 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
1041 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
1043 // Update piece lists, move the last pawn at index[to] position
1044 // and shrink the list. Add a new promotion piece to the list.
1045 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
1046 index[lastPawnSquare] = index[to];
1047 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
1048 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
1049 index[to] = pieceCount[us][promotion] - 1;
1050 pieceList[us][promotion][index[to]] = to;
1052 // Partially revert hash keys update
1053 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
1054 st->pawnKey ^= zobrist[us][PAWN][to];
1056 // Partially revert and update incremental scores
1057 st->value -= pst(us, PAWN, to);
1058 st->value += pst(us, promotion, to);
1061 st->npMaterial[us] += PieceValueMidgame[promotion];
1065 // Prefetch pawn and material hash tables
1066 Threads[threadID].pawnTable.prefetch(st->pawnKey);
1067 Threads[threadID].materialTable.prefetch(st->materialKey);
1069 // Update incremental scores
1070 st->value += pst_delta(piece, from, to);
1072 // Set capture piece
1073 st->capturedType = capture;
1075 // Update the key with the final value
1078 // Update checkers bitboard, piece must be already moved
1079 st->checkersBB = EmptyBoardBB;
1084 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1088 if (bit_is_set(ci.checkSq[pt], to))
1089 st->checkersBB = SetMaskBB[to];
1092 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1095 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
1098 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
1104 sideToMove = opposite_color(sideToMove);
1105 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1111 /// Position::do_capture_move() is a private method used to update captured
1112 /// piece info. It is called from the main Position::do_move function.
1114 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1116 assert(capture != KING);
1120 // If the captured piece was a pawn, update pawn hash key,
1121 // otherwise update non-pawn material.
1122 if (capture == PAWN)
1124 if (ep) // en passant ?
1126 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1128 assert(to == st->epSquare);
1129 assert(relative_rank(opposite_color(them), to) == RANK_6);
1130 assert(piece_on(to) == PIECE_NONE);
1131 assert(piece_on(capsq) == make_piece(them, PAWN));
1133 board[capsq] = PIECE_NONE;
1135 st->pawnKey ^= zobrist[them][PAWN][capsq];
1138 st->npMaterial[them] -= PieceValueMidgame[capture];
1140 // Remove captured piece
1141 clear_bit(&(byColorBB[them]), capsq);
1142 clear_bit(&(byTypeBB[capture]), capsq);
1143 clear_bit(&(byTypeBB[0]), capsq);
1146 key ^= zobrist[them][capture][capsq];
1148 // Update incremental scores
1149 st->value -= pst(them, capture, capsq);
1151 // Update piece count
1152 pieceCount[them][capture]--;
1154 // Update material hash key
1155 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1157 // Update piece list, move the last piece at index[capsq] position
1159 // WARNING: This is a not perfectly revresible operation. When we
1160 // will reinsert the captured piece in undo_move() we will put it
1161 // at the end of the list and not in its original place, it means
1162 // index[] and pieceList[] are not guaranteed to be invariant to a
1163 // do_move() + undo_move() sequence.
1164 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1165 index[lastPieceSquare] = index[capsq];
1166 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1167 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1169 // Reset rule 50 counter
1174 /// Position::do_castle_move() is a private method used to make a castling
1175 /// move. It is called from the main Position::do_move function. Note that
1176 /// castling moves are encoded as "king captures friendly rook" moves, for
1177 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1179 void Position::do_castle_move(Move m) {
1181 assert(move_is_ok(m));
1182 assert(move_is_castle(m));
1184 Color us = side_to_move();
1185 Color them = opposite_color(us);
1187 // Reset capture field
1188 st->capturedType = PIECE_TYPE_NONE;
1190 // Find source squares for king and rook
1191 Square kfrom = move_from(m);
1192 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1195 assert(piece_on(kfrom) == make_piece(us, KING));
1196 assert(piece_on(rfrom) == make_piece(us, ROOK));
1198 // Find destination squares for king and rook
1199 if (rfrom > kfrom) // O-O
1201 kto = relative_square(us, SQ_G1);
1202 rto = relative_square(us, SQ_F1);
1204 kto = relative_square(us, SQ_C1);
1205 rto = relative_square(us, SQ_D1);
1208 // Remove pieces from source squares:
1209 clear_bit(&(byColorBB[us]), kfrom);
1210 clear_bit(&(byTypeBB[KING]), kfrom);
1211 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1212 clear_bit(&(byColorBB[us]), rfrom);
1213 clear_bit(&(byTypeBB[ROOK]), rfrom);
1214 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1216 // Put pieces on destination squares:
1217 set_bit(&(byColorBB[us]), kto);
1218 set_bit(&(byTypeBB[KING]), kto);
1219 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1220 set_bit(&(byColorBB[us]), rto);
1221 set_bit(&(byTypeBB[ROOK]), rto);
1222 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1224 // Update board array
1225 Piece king = make_piece(us, KING);
1226 Piece rook = make_piece(us, ROOK);
1227 board[kfrom] = board[rfrom] = PIECE_NONE;
1231 // Update piece lists
1232 pieceList[us][KING][index[kfrom]] = kto;
1233 pieceList[us][ROOK][index[rfrom]] = rto;
1234 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1235 index[kto] = index[kfrom];
1238 // Update incremental scores
1239 st->value += pst_delta(king, kfrom, kto);
1240 st->value += pst_delta(rook, rfrom, rto);
1243 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1244 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1246 // Clear en passant square
1247 if (st->epSquare != SQ_NONE)
1249 st->key ^= zobEp[st->epSquare];
1250 st->epSquare = SQ_NONE;
1253 // Update castling rights
1254 st->key ^= zobCastle[st->castleRights];
1255 st->castleRights &= castleRightsMask[kfrom];
1256 st->key ^= zobCastle[st->castleRights];
1258 // Reset rule 50 counter
1261 // Update checkers BB
1262 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1265 sideToMove = opposite_color(sideToMove);
1266 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1272 /// Position::undo_move() unmakes a move. When it returns, the position should
1273 /// be restored to exactly the same state as before the move was made.
1275 void Position::undo_move(Move m) {
1278 assert(move_is_ok(m));
1280 sideToMove = opposite_color(sideToMove);
1282 if (move_is_castle(m))
1284 undo_castle_move(m);
1288 Color us = side_to_move();
1289 Color them = opposite_color(us);
1290 Square from = move_from(m);
1291 Square to = move_to(m);
1292 bool ep = move_is_ep(m);
1293 bool pm = move_is_promotion(m);
1295 PieceType pt = type_of_piece_on(to);
1297 assert(square_is_empty(from));
1298 assert(color_of_piece_on(to) == us);
1299 assert(!pm || relative_rank(us, to) == RANK_8);
1300 assert(!ep || to == st->previous->epSquare);
1301 assert(!ep || relative_rank(us, to) == RANK_6);
1302 assert(!ep || piece_on(to) == make_piece(us, PAWN));
1304 if (pm) // promotion ?
1306 PieceType promotion = move_promotion_piece(m);
1309 assert(promotion >= KNIGHT && promotion <= QUEEN);
1310 assert(piece_on(to) == make_piece(us, promotion));
1312 // Replace promoted piece with a pawn
1313 clear_bit(&(byTypeBB[promotion]), to);
1314 set_bit(&(byTypeBB[PAWN]), to);
1316 // Update piece counts
1317 pieceCount[us][promotion]--;
1318 pieceCount[us][PAWN]++;
1320 // Update piece list replacing promotion piece with a pawn
1321 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1322 index[lastPromotionSquare] = index[to];
1323 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1324 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1325 index[to] = pieceCount[us][PAWN] - 1;
1326 pieceList[us][PAWN][index[to]] = to;
1329 // Put the piece back at the source square
1330 Bitboard move_bb = make_move_bb(to, from);
1331 do_move_bb(&(byColorBB[us]), move_bb);
1332 do_move_bb(&(byTypeBB[pt]), move_bb);
1333 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1335 board[from] = make_piece(us, pt);
1336 board[to] = PIECE_NONE;
1338 // Update piece list
1339 index[from] = index[to];
1340 pieceList[us][pt][index[from]] = from;
1342 if (st->capturedType)
1347 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1349 assert(st->capturedType != KING);
1350 assert(!ep || square_is_empty(capsq));
1352 // Restore the captured piece
1353 set_bit(&(byColorBB[them]), capsq);
1354 set_bit(&(byTypeBB[st->capturedType]), capsq);
1355 set_bit(&(byTypeBB[0]), capsq);
1357 board[capsq] = make_piece(them, st->capturedType);
1359 // Update piece count
1360 pieceCount[them][st->capturedType]++;
1362 // Update piece list, add a new captured piece in capsq square
1363 index[capsq] = pieceCount[them][st->capturedType] - 1;
1364 pieceList[them][st->capturedType][index[capsq]] = capsq;
1367 // Finally point our state pointer back to the previous state
1374 /// Position::undo_castle_move() is a private method used to unmake a castling
1375 /// move. It is called from the main Position::undo_move function. Note that
1376 /// castling moves are encoded as "king captures friendly rook" moves, for
1377 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1379 void Position::undo_castle_move(Move m) {
1381 assert(move_is_ok(m));
1382 assert(move_is_castle(m));
1384 // When we have arrived here, some work has already been done by
1385 // Position::undo_move. In particular, the side to move has been switched,
1386 // so the code below is correct.
1387 Color us = side_to_move();
1389 // Find source squares for king and rook
1390 Square kfrom = move_from(m);
1391 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1394 // Find destination squares for king and rook
1395 if (rfrom > kfrom) // O-O
1397 kto = relative_square(us, SQ_G1);
1398 rto = relative_square(us, SQ_F1);
1400 kto = relative_square(us, SQ_C1);
1401 rto = relative_square(us, SQ_D1);
1404 assert(piece_on(kto) == make_piece(us, KING));
1405 assert(piece_on(rto) == make_piece(us, ROOK));
1407 // Remove pieces from destination squares:
1408 clear_bit(&(byColorBB[us]), kto);
1409 clear_bit(&(byTypeBB[KING]), kto);
1410 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1411 clear_bit(&(byColorBB[us]), rto);
1412 clear_bit(&(byTypeBB[ROOK]), rto);
1413 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1415 // Put pieces on source squares:
1416 set_bit(&(byColorBB[us]), kfrom);
1417 set_bit(&(byTypeBB[KING]), kfrom);
1418 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1419 set_bit(&(byColorBB[us]), rfrom);
1420 set_bit(&(byTypeBB[ROOK]), rfrom);
1421 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1424 board[rto] = board[kto] = PIECE_NONE;
1425 board[rfrom] = make_piece(us, ROOK);
1426 board[kfrom] = make_piece(us, KING);
1428 // Update piece lists
1429 pieceList[us][KING][index[kto]] = kfrom;
1430 pieceList[us][ROOK][index[rto]] = rfrom;
1431 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1432 index[kfrom] = index[kto];
1435 // Finally point our state pointer back to the previous state
1442 /// Position::do_null_move makes() a "null move": It switches the side to move
1443 /// and updates the hash key without executing any move on the board.
1445 void Position::do_null_move(StateInfo& backupSt) {
1448 assert(!in_check());
1450 // Back up the information necessary to undo the null move to the supplied
1451 // StateInfo object.
1452 // Note that differently from normal case here backupSt is actually used as
1453 // a backup storage not as a new state to be used.
1454 backupSt.key = st->key;
1455 backupSt.epSquare = st->epSquare;
1456 backupSt.value = st->value;
1457 backupSt.previous = st->previous;
1458 backupSt.pliesFromNull = st->pliesFromNull;
1459 st->previous = &backupSt;
1461 // Save the current key to the history[] array, in order to be able to
1462 // detect repetition draws.
1463 history[st->gamePly++] = st->key;
1465 // Update the necessary information
1466 if (st->epSquare != SQ_NONE)
1467 st->key ^= zobEp[st->epSquare];
1469 st->key ^= zobSideToMove;
1470 prefetch((char*)TT.first_entry(st->key));
1472 sideToMove = opposite_color(sideToMove);
1473 st->epSquare = SQ_NONE;
1475 st->pliesFromNull = 0;
1476 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1480 /// Position::undo_null_move() unmakes a "null move".
1482 void Position::undo_null_move() {
1485 assert(!in_check());
1487 // Restore information from the our backup StateInfo object
1488 StateInfo* backupSt = st->previous;
1489 st->key = backupSt->key;
1490 st->epSquare = backupSt->epSquare;
1491 st->value = backupSt->value;
1492 st->previous = backupSt->previous;
1493 st->pliesFromNull = backupSt->pliesFromNull;
1495 // Update the necessary information
1496 sideToMove = opposite_color(sideToMove);
1502 /// Position::see() is a static exchange evaluator: It tries to estimate the
1503 /// material gain or loss resulting from a move. There are three versions of
1504 /// this function: One which takes a destination square as input, one takes a
1505 /// move, and one which takes a 'from' and a 'to' square. The function does
1506 /// not yet understand promotions captures.
1508 int Position::see_sign(Move m) const {
1510 assert(move_is_ok(m));
1512 Square from = move_from(m);
1513 Square to = move_to(m);
1515 // Early return if SEE cannot be negative because captured piece value
1516 // is not less then capturing one. Note that king moves always return
1517 // here because king midgame value is set to 0.
1518 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1524 int Position::see(Move m) const {
1527 Bitboard occupied, attackers, stmAttackers, b;
1528 int swapList[32], slIndex = 1;
1529 PieceType capturedType, pt;
1532 assert(move_is_ok(m));
1534 // As castle moves are implemented as capturing the rook, they have
1535 // SEE == RookValueMidgame most of the times (unless the rook is under
1537 if (move_is_castle(m))
1540 from = move_from(m);
1542 capturedType = type_of_piece_on(to);
1543 occupied = occupied_squares();
1545 // Handle en passant moves
1546 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1548 Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1550 assert(capturedType == PIECE_TYPE_NONE);
1551 assert(type_of_piece_on(capQq) == PAWN);
1553 // Remove the captured pawn
1554 clear_bit(&occupied, capQq);
1555 capturedType = PAWN;
1558 // Find all attackers to the destination square, with the moving piece
1559 // removed, but possibly an X-ray attacker added behind it.
1560 clear_bit(&occupied, from);
1561 attackers = attackers_to(to, occupied);
1563 // If the opponent has no attackers we are finished
1564 stm = opposite_color(color_of_piece_on(from));
1565 stmAttackers = attackers & pieces_of_color(stm);
1567 return seeValues[capturedType];
1569 // The destination square is defended, which makes things rather more
1570 // difficult to compute. We proceed by building up a "swap list" containing
1571 // the material gain or loss at each stop in a sequence of captures to the
1572 // destination square, where the sides alternately capture, and always
1573 // capture with the least valuable piece. After each capture, we look for
1574 // new X-ray attacks from behind the capturing piece.
1575 swapList[0] = seeValues[capturedType];
1576 capturedType = type_of_piece_on(from);
1579 // Locate the least valuable attacker for the side to move. The loop
1580 // below looks like it is potentially infinite, but it isn't. We know
1581 // that the side to move still has at least one attacker left.
1582 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1585 // Remove the attacker we just found from the 'occupied' bitboard,
1586 // and scan for new X-ray attacks behind the attacker.
1587 b = stmAttackers & pieces(pt);
1588 occupied ^= (b & (~b + 1));
1589 attackers |= (rook_attacks_bb(to, occupied) & pieces(ROOK, QUEEN))
1590 | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1592 attackers &= occupied; // Cut out pieces we've already done
1594 // Add the new entry to the swap list
1595 assert(slIndex < 32);
1596 swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1599 // Remember the value of the capturing piece, and change the side to
1600 // move before beginning the next iteration.
1602 stm = opposite_color(stm);
1603 stmAttackers = attackers & pieces_of_color(stm);
1605 // Stop before processing a king capture
1606 if (capturedType == KING && stmAttackers)
1608 assert(slIndex < 32);
1609 swapList[slIndex++] = QueenValueMidgame*10;
1612 } while (stmAttackers);
1614 // Having built the swap list, we negamax through it to find the best
1615 // achievable score from the point of view of the side to move.
1617 swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1623 /// Position::clear() erases the position object to a pristine state, with an
1624 /// empty board, white to move, and no castling rights.
1626 void Position::clear() {
1629 memset(st, 0, sizeof(StateInfo));
1630 st->epSquare = SQ_NONE;
1631 startPosPlyCounter = 0;
1634 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1635 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1636 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1637 memset(index, 0, sizeof(int) * 64);
1639 for (int i = 0; i < 64; i++)
1640 board[i] = PIECE_NONE;
1642 for (int i = 0; i < 8; i++)
1643 for (int j = 0; j < 16; j++)
1644 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1646 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1647 castleRightsMask[sq] = ALL_CASTLES;
1650 initialKFile = FILE_E;
1651 initialKRFile = FILE_H;
1652 initialQRFile = FILE_A;
1656 /// Position::put_piece() puts a piece on the given square of the board,
1657 /// updating the board array, pieces list, bitboards, and piece counts.
1659 void Position::put_piece(Piece p, Square s) {
1661 Color c = color_of_piece(p);
1662 PieceType pt = type_of_piece(p);
1665 index[s] = pieceCount[c][pt]++;
1666 pieceList[c][pt][index[s]] = s;
1668 set_bit(&(byTypeBB[pt]), s);
1669 set_bit(&(byColorBB[c]), s);
1670 set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1674 /// Position::compute_key() computes the hash key of the position. The hash
1675 /// key is usually updated incrementally as moves are made and unmade, the
1676 /// compute_key() function is only used when a new position is set up, and
1677 /// to verify the correctness of the hash key when running in debug mode.
1679 Key Position::compute_key() const {
1681 Key result = zobCastle[st->castleRights];
1683 for (Square s = SQ_A1; s <= SQ_H8; s++)
1684 if (square_is_occupied(s))
1685 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1687 if (ep_square() != SQ_NONE)
1688 result ^= zobEp[ep_square()];
1690 if (side_to_move() == BLACK)
1691 result ^= zobSideToMove;
1697 /// Position::compute_pawn_key() computes the hash key of the position. The
1698 /// hash key is usually updated incrementally as moves are made and unmade,
1699 /// the compute_pawn_key() function is only used when a new position is set
1700 /// up, and to verify the correctness of the pawn hash key when running in
1703 Key Position::compute_pawn_key() const {
1708 for (Color c = WHITE; c <= BLACK; c++)
1710 b = pieces(PAWN, c);
1712 result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1718 /// Position::compute_material_key() computes the hash key of the position.
1719 /// The hash key is usually updated incrementally as moves are made and unmade,
1720 /// the compute_material_key() function is only used when a new position is set
1721 /// up, and to verify the correctness of the material hash key when running in
1724 Key Position::compute_material_key() const {
1729 for (Color c = WHITE; c <= BLACK; c++)
1730 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1732 count = piece_count(c, pt);
1733 for (int i = 0; i < count; i++)
1734 result ^= zobrist[c][pt][i];
1740 /// Position::compute_value() compute the incremental scores for the middle
1741 /// game and the endgame. These functions are used to initialize the incremental
1742 /// scores when a new position is set up, and to verify that the scores are correctly
1743 /// updated by do_move and undo_move when the program is running in debug mode.
1744 Score Position::compute_value() const {
1747 Score result = SCORE_ZERO;
1749 for (Color c = WHITE; c <= BLACK; c++)
1750 for (PieceType pt = PAWN; pt <= KING; pt++)
1754 result += pst(c, pt, pop_1st_bit(&b));
1757 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1762 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1763 /// game material value for the given side. Material values are updated
1764 /// incrementally during the search, this function is only used while
1765 /// initializing a new Position object.
1767 Value Position::compute_non_pawn_material(Color c) const {
1769 Value result = VALUE_ZERO;
1771 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1772 result += piece_count(c, pt) * PieceValueMidgame[pt];
1778 /// Position::is_draw() tests whether the position is drawn by material,
1779 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1780 /// must be done by the search.
1781 template<bool SkipRepetition>
1782 bool Position::is_draw() const {
1784 // Draw by material?
1786 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1789 // Draw by the 50 moves rule?
1790 if (st->rule50 > 99 && !is_mate())
1793 // Draw by repetition?
1794 if (!SkipRepetition)
1795 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1796 if (history[st->gamePly - i] == st->key)
1802 // Explicit template instantiations
1803 template bool Position::is_draw<false>() const;
1804 template bool Position::is_draw<true>() const;
1807 /// Position::is_mate() returns true or false depending on whether the
1808 /// side to move is checkmated.
1810 bool Position::is_mate() const {
1812 MoveStack moves[MAX_MOVES];
1813 return in_check() && generate<MV_LEGAL>(*this, moves) == moves;
1817 /// Position::init_zobrist() is a static member function which initializes at
1818 /// startup the various arrays used to compute hash keys.
1820 void Position::init_zobrist() {
1825 for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1826 zobrist[i][j][k] = rk.rand<Key>();
1828 for (i = 0; i < 64; i++)
1829 zobEp[i] = rk.rand<Key>();
1831 for (i = 0; i < 16; i++)
1832 zobCastle[i] = rk.rand<Key>();
1834 zobSideToMove = rk.rand<Key>();
1835 zobExclusion = rk.rand<Key>();
1839 /// Position::init_piece_square_tables() initializes the piece square tables.
1840 /// This is a two-step operation: First, the white halves of the tables are
1841 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1842 /// of the tables are initialized by mirroring and changing the sign of the
1843 /// corresponding white scores.
1845 void Position::init_piece_square_tables() {
1847 for (Square s = SQ_A1; s <= SQ_H8; s++)
1848 for (Piece p = WP; p <= WK; p++)
1849 PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1851 for (Square s = SQ_A1; s <= SQ_H8; s++)
1852 for (Piece p = BP; p <= BK; p++)
1853 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1857 /// Position::flip() flips position with the white and black sides reversed. This
1858 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1860 void Position::flip() {
1864 // Make a copy of current position before to start changing
1865 const Position pos(*this, threadID);
1868 threadID = pos.thread();
1871 for (Square s = SQ_A1; s <= SQ_H8; s++)
1872 if (!pos.square_is_empty(s))
1873 put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1876 sideToMove = opposite_color(pos.side_to_move());
1879 if (pos.can_castle_kingside(WHITE)) do_allow_oo(BLACK);
1880 if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1881 if (pos.can_castle_kingside(BLACK)) do_allow_oo(WHITE);
1882 if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1884 initialKFile = pos.initialKFile;
1885 initialKRFile = pos.initialKRFile;
1886 initialQRFile = pos.initialQRFile;
1888 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1889 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1890 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1891 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1892 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1893 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1895 // En passant square
1896 if (pos.st->epSquare != SQ_NONE)
1897 st->epSquare = flip_square(pos.st->epSquare);
1903 st->key = compute_key();
1904 st->pawnKey = compute_pawn_key();
1905 st->materialKey = compute_material_key();
1907 // Incremental scores
1908 st->value = compute_value();
1911 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1912 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1918 /// Position::is_ok() performs some consitency checks for the position object.
1919 /// This is meant to be helpful when debugging.
1921 bool Position::is_ok(int* failedStep) const {
1923 // What features of the position should be verified?
1924 const bool debugAll = false;
1926 const bool debugBitboards = debugAll || false;
1927 const bool debugKingCount = debugAll || false;
1928 const bool debugKingCapture = debugAll || false;
1929 const bool debugCheckerCount = debugAll || false;
1930 const bool debugKey = debugAll || false;
1931 const bool debugMaterialKey = debugAll || false;
1932 const bool debugPawnKey = debugAll || false;
1933 const bool debugIncrementalEval = debugAll || false;
1934 const bool debugNonPawnMaterial = debugAll || false;
1935 const bool debugPieceCounts = debugAll || false;
1936 const bool debugPieceList = debugAll || false;
1937 const bool debugCastleSquares = debugAll || false;
1939 if (failedStep) *failedStep = 1;
1942 if (!color_is_ok(side_to_move()))
1945 // Are the king squares in the position correct?
1946 if (failedStep) (*failedStep)++;
1947 if (piece_on(king_square(WHITE)) != WK)
1950 if (failedStep) (*failedStep)++;
1951 if (piece_on(king_square(BLACK)) != BK)
1955 if (failedStep) (*failedStep)++;
1956 if (!file_is_ok(initialKRFile))
1959 if (!file_is_ok(initialQRFile))
1962 // Do both sides have exactly one king?
1963 if (failedStep) (*failedStep)++;
1966 int kingCount[2] = {0, 0};
1967 for (Square s = SQ_A1; s <= SQ_H8; s++)
1968 if (type_of_piece_on(s) == KING)
1969 kingCount[color_of_piece_on(s)]++;
1971 if (kingCount[0] != 1 || kingCount[1] != 1)
1975 // Can the side to move capture the opponent's king?
1976 if (failedStep) (*failedStep)++;
1977 if (debugKingCapture)
1979 Color us = side_to_move();
1980 Color them = opposite_color(us);
1981 Square ksq = king_square(them);
1982 if (attackers_to(ksq) & pieces_of_color(us))
1986 // Is there more than 2 checkers?
1987 if (failedStep) (*failedStep)++;
1988 if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1992 if (failedStep) (*failedStep)++;
1995 // The intersection of the white and black pieces must be empty
1996 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1999 // The union of the white and black pieces must be equal to all
2001 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2004 // Separate piece type bitboards must have empty intersections
2005 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2006 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2007 if (p1 != p2 && (pieces(p1) & pieces(p2)))
2011 // En passant square OK?
2012 if (failedStep) (*failedStep)++;
2013 if (ep_square() != SQ_NONE)
2015 // The en passant square must be on rank 6, from the point of view of the
2017 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2022 if (failedStep) (*failedStep)++;
2023 if (debugKey && st->key != compute_key())
2026 // Pawn hash key OK?
2027 if (failedStep) (*failedStep)++;
2028 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2031 // Material hash key OK?
2032 if (failedStep) (*failedStep)++;
2033 if (debugMaterialKey && st->materialKey != compute_material_key())
2036 // Incremental eval OK?
2037 if (failedStep) (*failedStep)++;
2038 if (debugIncrementalEval && st->value != compute_value())
2041 // Non-pawn material OK?
2042 if (failedStep) (*failedStep)++;
2043 if (debugNonPawnMaterial)
2045 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2048 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2053 if (failedStep) (*failedStep)++;
2054 if (debugPieceCounts)
2055 for (Color c = WHITE; c <= BLACK; c++)
2056 for (PieceType pt = PAWN; pt <= KING; pt++)
2057 if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
2060 if (failedStep) (*failedStep)++;
2062 for (Color c = WHITE; c <= BLACK; c++)
2063 for (PieceType pt = PAWN; pt <= KING; pt++)
2064 for (int i = 0; i < pieceCount[c][pt]; i++)
2066 if (piece_on(piece_list(c, pt, i)) != make_piece(c, pt))
2069 if (index[piece_list(c, pt, i)] != i)
2073 if (failedStep) (*failedStep)++;
2074 if (debugCastleSquares)
2076 for (Color c = WHITE; c <= BLACK; c++)
2078 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != make_piece(c, ROOK))
2081 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != make_piece(c, ROOK))
2084 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2086 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2088 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2090 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2094 if (failedStep) *failedStep = 0;