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-2009 Marco Costalba
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/>.
38 #include "ucioption.h"
47 int Position::castleRightsMask[64];
49 Key Position::zobrist[2][8][64];
50 Key Position::zobEp[64];
51 Key Position::zobCastle[16];
52 Key Position::zobMaterial[2][8][16];
53 Key Position::zobSideToMove;
55 Value Position::MgPieceSquareTable[16][64];
56 Value Position::EgPieceSquareTable[16][64];
58 static bool RequestPending = false;
66 Position::Position(const Position& pos) {
70 Position::Position(const string& fen) {
75 /// Position::setTranspositionTable() is used by search functions to pass
76 /// the pointer to the used TT so that do_move() will prefetch TT access.
78 void Position::setTranspositionTable(TranspositionTable* tt) {
83 /// Position::from_fen() initializes the position object with the given FEN
84 /// string. This function is not very robust - make sure that input FENs are
85 /// correct (this is assumed to be the responsibility of the GUI).
87 void Position::from_fen(const string& fen) {
89 static const string pieceLetters = "KQRBNPkqrbnp";
90 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
98 for ( ; fen[i] != ' '; i++)
102 // Skip the given number of files
103 file += (fen[i] - '1' + 1);
106 else if (fen[i] == '/')
112 size_t idx = pieceLetters.find(fen[i]);
113 if (idx == string::npos)
115 std::cout << "Error in FEN at character " << i << std::endl;
118 Square square = make_square(file, rank);
119 put_piece(pieces[idx], square);
125 if (fen[i] != 'w' && fen[i] != 'b')
127 std::cout << "Error in FEN at character " << i << std::endl;
130 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
136 std::cout << "Error in FEN at character " << i << std::endl;
141 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
147 else if(fen[i] == 'K') allow_oo(WHITE);
148 else if(fen[i] == 'Q') allow_ooo(WHITE);
149 else if(fen[i] == 'k') allow_oo(BLACK);
150 else if(fen[i] == 'q') allow_ooo(BLACK);
151 else if(fen[i] >= 'A' && fen[i] <= 'H') {
152 File rookFile, kingFile = FILE_NONE;
153 for(Square square = SQ_B1; square <= SQ_G1; square++)
154 if(piece_on(square) == WK)
155 kingFile = square_file(square);
156 if(kingFile == FILE_NONE) {
157 std::cout << "Error in FEN at character " << i << std::endl;
160 initialKFile = kingFile;
161 rookFile = File(fen[i] - 'A') + FILE_A;
162 if(rookFile < initialKFile) {
164 initialQRFile = rookFile;
168 initialKRFile = rookFile;
171 else if(fen[i] >= 'a' && fen[i] <= 'h') {
172 File rookFile, kingFile = FILE_NONE;
173 for(Square square = SQ_B8; square <= SQ_G8; square++)
174 if(piece_on(square) == BK)
175 kingFile = square_file(square);
176 if(kingFile == FILE_NONE) {
177 std::cout << "Error in FEN at character " << i << std::endl;
180 initialKFile = kingFile;
181 rookFile = File(fen[i] - 'a') + FILE_A;
182 if(rookFile < initialKFile) {
184 initialQRFile = rookFile;
188 initialKRFile = rookFile;
192 std::cout << "Error in FEN at character " << i << std::endl;
199 while (fen[i] == ' ')
203 if ( i <= fen.length() - 2
204 && (fen[i] >= 'a' && fen[i] <= 'h')
205 && (fen[i+1] == '3' || fen[i+1] == '6'))
206 st->epSquare = square_from_string(fen.substr(i, 2));
208 // Various initialisation
209 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
210 castleRightsMask[sq] = ALL_CASTLES;
212 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
213 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
214 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
215 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
216 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
217 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
221 st->key = compute_key();
222 st->pawnKey = compute_pawn_key();
223 st->materialKey = compute_material_key();
224 st->mgValue = compute_value<MidGame>();
225 st->egValue = compute_value<EndGame>();
226 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
227 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
231 /// Position::to_fen() converts the position object to a FEN string. This is
232 /// probably only useful for debugging.
234 const string Position::to_fen() const {
236 static const string pieceLetters = " PNBRQK pnbrqk";
240 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
243 for (File file = FILE_A; file <= FILE_H; file++)
245 Square sq = make_square(file, rank);
246 if (!square_is_occupied(sq))
252 fen += (char)skip + '0';
255 fen += pieceLetters[piece_on(sq)];
258 fen += (char)skip + '0';
260 fen += (rank > RANK_1 ? '/' : ' ');
262 fen += (sideToMove == WHITE ? "w " : "b ");
263 if (st->castleRights != NO_CASTLES)
265 if (can_castle_kingside(WHITE)) fen += 'K';
266 if (can_castle_queenside(WHITE)) fen += 'Q';
267 if (can_castle_kingside(BLACK)) fen += 'k';
268 if (can_castle_queenside(BLACK)) fen += 'q';
273 if (ep_square() != SQ_NONE)
274 fen += square_to_string(ep_square());
282 /// Position::print() prints an ASCII representation of the position to
283 /// the standard output. If a move is given then also the san is print.
285 void Position::print(Move m) const {
287 static const string pieceLetters = " PNBRQK PNBRQK .";
289 // Check for reentrancy, as example when called from inside
290 // MovePicker that is used also here in move_to_san()
294 RequestPending = true;
296 std::cout << std::endl;
299 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
300 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
302 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
304 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
305 for (File file = FILE_A; file <= FILE_H; file++)
307 Square sq = make_square(file, rank);
308 Piece piece = piece_on(sq);
309 if (piece == EMPTY && square_color(sq) == WHITE)
312 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
313 std::cout << '|' << col << pieceLetters[piece] << col;
315 std::cout << '|' << std::endl;
317 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
318 << "Fen is: " << to_fen() << std::endl
319 << "Key is: " << st->key << std::endl;
321 RequestPending = false;
325 /// Position::copy() creates a copy of the input position.
327 void Position::copy(const Position& pos) {
329 memcpy(this, &pos, sizeof(Position));
330 saveState(); // detach and copy state info
334 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
335 /// king) pieces for the given color and for the given pinner type. Or, when
336 /// template parameter FindPinned is false, the pieces of the given color
337 /// candidate for a discovery check against the enemy king.
338 /// Note that checkersBB bitboard must be already updated.
340 template<bool FindPinned>
341 Bitboard Position::hidden_checkers(Color c) const {
343 Bitboard pinners, result = EmptyBoardBB;
345 // Pinned pieces protect our king, dicovery checks attack
347 Square ksq = king_square(FindPinned ? c : opposite_color(c));
349 // Pinners are sliders, not checkers, that give check when
350 // candidate pinned is removed.
351 pinners = (rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
352 | (bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq]);
354 if (FindPinned && pinners)
355 pinners &= ~st->checkersBB;
359 Square s = pop_1st_bit(&pinners);
360 Bitboard b = squares_between(s, ksq) & occupied_squares();
364 if ( !(b & (b - 1)) // Only one bit set?
365 && (b & pieces_of_color(c))) // Is an our piece?
372 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
373 /// king) pieces for the given color.
375 Bitboard Position::pinned_pieces(Color c) const {
377 return hidden_checkers<true>(c);
381 /// Position:discovered_check_candidates() returns a bitboard containing all
382 /// pieces for the given side which are candidates for giving a discovered
385 Bitboard Position::discovered_check_candidates(Color c) const {
387 return hidden_checkers<false>(c);
390 /// Position::attacks_to() computes a bitboard containing all pieces which
391 /// attacks a given square.
393 Bitboard Position::attacks_to(Square s) const {
395 return (pawn_attacks(BLACK, s) & pawns(WHITE))
396 | (pawn_attacks(WHITE, s) & pawns(BLACK))
397 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
398 | (piece_attacks<ROOK>(s) & rooks_and_queens())
399 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
400 | (piece_attacks<KING>(s) & pieces_of_type(KING));
403 /// Position::piece_attacks_square() tests whether the piece on square f
404 /// attacks square t.
406 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
408 assert(square_is_ok(f));
409 assert(square_is_ok(t));
413 case WP: return pawn_attacks_square(WHITE, f, t);
414 case BP: return pawn_attacks_square(BLACK, f, t);
415 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
416 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
417 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
418 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
419 case WK: case BK: return piece_attacks_square<KING>(f, t);
426 /// Position::move_attacks_square() tests whether a move from the current
427 /// position attacks a given square.
429 bool Position::move_attacks_square(Move m, Square s) const {
431 assert(move_is_ok(m));
432 assert(square_is_ok(s));
434 Square f = move_from(m), t = move_to(m);
436 assert(square_is_occupied(f));
438 if (piece_attacks_square(piece_on(f), t, s))
441 // Move the piece and scan for X-ray attacks behind it
442 Bitboard occ = occupied_squares();
443 Color us = color_of_piece_on(f);
446 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
447 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
449 // If we have attacks we need to verify that are caused by our move
450 // and are not already existent ones.
451 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
455 /// Position::find_checkers() computes the checkersBB bitboard, which
456 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
457 /// currently works by calling Position::attacks_to, which is probably
458 /// inefficient. Consider rewriting this function to use the last move
459 /// played, like in non-bitboard versions of Glaurung.
461 void Position::find_checkers() {
463 Color us = side_to_move();
464 st->checkersBB = attacks_to(king_square(us), opposite_color(us));
468 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
470 bool Position::pl_move_is_legal(Move m) const {
472 // If we're in check, all pseudo-legal moves are legal, because our
473 // check evasion generator only generates true legal moves.
474 return is_check() || pl_move_is_legal(m, pinned_pieces(side_to_move()));
477 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
480 assert(move_is_ok(m));
481 assert(pinned == pinned_pieces(side_to_move()));
484 // Castling moves are checked for legality during move generation.
485 if (move_is_castle(m))
488 Color us = side_to_move();
489 Square from = move_from(m);
490 Square ksq = king_square(us);
492 assert(color_of_piece_on(from) == us);
493 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
495 // En passant captures are a tricky special case. Because they are
496 // rather uncommon, we do it simply by testing whether the king is attacked
497 // after the move is made
500 Color them = opposite_color(us);
501 Square to = move_to(m);
502 Square capsq = make_square(square_file(to), square_rank(from));
503 Bitboard b = occupied_squares();
505 assert(to == ep_square());
506 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
507 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
508 assert(piece_on(to) == EMPTY);
511 clear_bit(&b, capsq);
514 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
515 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
518 // If the moving piece is a king, check whether the destination
519 // square is attacked by the opponent.
521 return !(square_is_attacked(move_to(m), opposite_color(us)));
523 // A non-king move is legal if and only if it is not pinned or it
524 // is moving along the ray towards or away from the king.
526 || !bit_is_set(pinned, from)
527 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
531 /// Position::move_is_check() tests whether a pseudo-legal move is a check
533 bool Position::move_is_check(Move m) const {
535 Bitboard dc = discovered_check_candidates(side_to_move());
536 return move_is_check(m, dc);
539 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
542 assert(move_is_ok(m));
543 assert(dcCandidates == discovered_check_candidates(side_to_move()));
545 Color us = side_to_move();
546 Color them = opposite_color(us);
547 Square from = move_from(m);
548 Square to = move_to(m);
549 Square ksq = king_square(them);
551 assert(color_of_piece_on(from) == us);
552 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
554 // Proceed according to the type of the moving piece
555 switch (type_of_piece_on(from))
559 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
562 if ( dcCandidates // Discovered check?
563 && bit_is_set(dcCandidates, from)
564 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
567 if (move_is_promotion(m)) // Promotion with check?
569 Bitboard b = occupied_squares();
572 switch (move_promotion_piece(m))
575 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
577 return bit_is_set(bishop_attacks_bb(to, b), ksq);
579 return bit_is_set(rook_attacks_bb(to, b), ksq);
581 return bit_is_set(queen_attacks_bb(to, b), ksq);
586 // En passant capture with check? We have already handled the case
587 // of direct checks and ordinary discovered check, the only case we
588 // need to handle is the unusual case of a discovered check through the
590 else if (move_is_ep(m))
592 Square capsq = make_square(square_file(to), square_rank(from));
593 Bitboard b = occupied_squares();
595 clear_bit(&b, capsq);
597 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
598 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
602 // Test discovered check and normal check according to piece type
604 return (dcCandidates && bit_is_set(dcCandidates, from))
605 || bit_is_set(piece_attacks<KNIGHT>(ksq), to);
608 return (dcCandidates && bit_is_set(dcCandidates, from))
609 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to));
612 return (dcCandidates && bit_is_set(dcCandidates, from))
613 || (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to));
616 // Discovered checks are impossible!
617 assert(!bit_is_set(dcCandidates, from));
618 return ( (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to))
619 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to)));
623 if ( bit_is_set(dcCandidates, from)
624 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
627 // Castling with check?
628 if (move_is_castle(m))
630 Square kfrom, kto, rfrom, rto;
631 Bitboard b = occupied_squares();
637 kto = relative_square(us, SQ_G1);
638 rto = relative_square(us, SQ_F1);
640 kto = relative_square(us, SQ_C1);
641 rto = relative_square(us, SQ_D1);
643 clear_bit(&b, kfrom);
644 clear_bit(&b, rfrom);
647 return bit_is_set(rook_attacks_bb(rto, b), ksq);
651 default: // NO_PIECE_TYPE
659 /// Position::update_checkers() udpates chekers info given the move. It is called
660 /// in do_move() and is faster then find_checkers().
662 template<PieceType Piece>
663 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
664 Square to, Bitboard dcCandidates) {
666 const bool Bishop = (Piece == QUEEN || Piece == BISHOP);
667 const bool Rook = (Piece == QUEEN || Piece == ROOK);
668 const bool Slider = Bishop || Rook;
671 if ( ( (Bishop && bit_is_set(BishopPseudoAttacks[ksq], to))
672 || (Rook && bit_is_set(RookPseudoAttacks[ksq], to)))
673 && bit_is_set(piece_attacks<Piece>(ksq), to)) // slow, try to early skip
674 set_bit(pCheckersBB, to);
676 else if ( Piece != KING
678 && bit_is_set(piece_attacks<Piece>(ksq), to))
679 set_bit(pCheckersBB, to);
682 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
685 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
688 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
693 /// Position::do_move() makes a move, and saves all information necessary
694 /// to a StateInfo object. The move is assumed to be legal.
695 /// Pseudo-legal moves should be filtered out before this function is called.
697 void Position::do_move(Move m, StateInfo& newSt) {
699 do_move(m, newSt, discovered_check_candidates(side_to_move()));
702 void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
705 assert(move_is_ok(m));
707 // Copy some fields of old state to our new StateInfo object except the
708 // ones which are recalculated from scratch anyway, then switch our state
709 // pointer to point to the new, ready to be updated, state.
710 struct ReducedStateInfo {
711 Key key, pawnKey, materialKey;
712 int castleRights, rule50;
714 Value mgValue, egValue;
718 memcpy(&newSt, st, sizeof(ReducedStateInfo));
719 newSt.capture = NO_PIECE_TYPE;
723 // Save the current key to the history[] array, in order to be able to
724 // detect repetition draws.
725 history[gamePly] = st->key;
727 // Increment the 50 moves rule draw counter. Resetting it to zero in the
728 // case of non-reversible moves is taken care of later.
731 if (move_is_castle(m))
733 else if (move_is_promotion(m))
734 do_promotion_move(m);
735 else if (move_is_ep(m))
739 Color us = side_to_move();
740 Color them = opposite_color(us);
741 Square from = move_from(m);
742 Square to = move_to(m);
744 assert(color_of_piece_on(from) == us);
745 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
747 Piece piece = piece_on(from);
748 PieceType pt = type_of_piece(piece);
750 st->capture = type_of_piece_on(to);
753 do_capture_move(st->capture, them, to);
756 st->key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
757 st->key ^= zobSideToMove;
759 // Reset en passant square
760 if (st->epSquare != SQ_NONE)
762 st->key ^= zobEp[st->epSquare];
763 st->epSquare = SQ_NONE;
766 // Update castle rights, try to shortcut a common case
767 if ((castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
769 st->key ^= zobCastle[st->castleRights];
770 st->castleRights &= castleRightsMask[from];
771 st->castleRights &= castleRightsMask[to];
772 st->key ^= zobCastle[st->castleRights];
775 bool checkEpSquare = (pt == PAWN && abs(int(to) - int(from)) == 16);
777 // Prefetch TT access as soon as we know key is updated
778 if (!checkEpSquare && TT)
779 TT->prefetch(st->key);
782 Bitboard move_bb = make_move_bb(from, to);
783 do_move_bb(&(byColorBB[us]), move_bb);
784 do_move_bb(&(byTypeBB[pt]), move_bb);
785 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
787 board[to] = board[from];
790 // If the moving piece was a pawn do some special extra work
793 // Reset rule 50 draw counter
796 // Update pawn hash key
797 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
799 // Set en passant square, only if moved pawn can be captured
802 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
803 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
805 st->epSquare = Square((int(from) + int(to)) / 2);
806 st->key ^= zobEp[st->epSquare];
811 // Prefetch only here in the few cases we needed zobEp[] to update the key
812 if (checkEpSquare && TT)
813 TT->prefetch(st->key);
815 // Update incremental scores
816 st->mgValue += pst_delta<MidGame>(piece, from, to);
817 st->egValue += pst_delta<EndGame>(piece, from, to);
819 // If the moving piece was a king, update the king square
823 // Update piece lists
824 pieceList[us][pt][index[from]] = to;
825 index[to] = index[from];
827 // Update checkers bitboard, piece must be already moved
828 st->checkersBB = EmptyBoardBB;
829 Square ksq = king_square(them);
832 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
833 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
834 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
835 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
836 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
837 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
838 default: assert(false); break;
843 sideToMove = opposite_color(sideToMove);
846 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
847 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
853 /// Position::do_capture_move() is a private method used to update captured
854 /// piece info. It is called from the main Position::do_move function.
856 void Position::do_capture_move(PieceType capture, Color them, Square to) {
858 assert(capture != KING);
860 // Remove captured piece
861 clear_bit(&(byColorBB[them]), to);
862 clear_bit(&(byTypeBB[capture]), to);
863 clear_bit(&(byTypeBB[0]), to);
866 st->key ^= zobrist[them][capture][to];
868 // If the captured piece was a pawn, update pawn hash key
870 st->pawnKey ^= zobrist[them][PAWN][to];
872 // Update incremental scores
873 st->mgValue -= pst<MidGame>(them, capture, to);
874 st->egValue -= pst<EndGame>(them, capture, to);
878 st->npMaterial[them] -= piece_value_midgame(capture);
880 // Update material hash key
881 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
883 // Update piece count
884 pieceCount[them][capture]--;
887 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
888 index[pieceList[them][capture][index[to]]] = index[to];
890 // Reset rule 50 counter
895 /// Position::do_castle_move() is a private method used to make a castling
896 /// move. It is called from the main Position::do_move function. Note that
897 /// castling moves are encoded as "king captures friendly rook" moves, for
898 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
900 void Position::do_castle_move(Move m) {
903 assert(move_is_ok(m));
904 assert(move_is_castle(m));
906 Color us = side_to_move();
907 Color them = opposite_color(us);
909 // Find source squares for king and rook
910 Square kfrom = move_from(m);
911 Square rfrom = move_to(m); // HACK: See comment at beginning of function
914 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
915 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
917 // Find destination squares for king and rook
918 if (rfrom > kfrom) // O-O
920 kto = relative_square(us, SQ_G1);
921 rto = relative_square(us, SQ_F1);
923 kto = relative_square(us, SQ_C1);
924 rto = relative_square(us, SQ_D1);
928 Bitboard kmove_bb = make_move_bb(kfrom, kto);
929 do_move_bb(&(byColorBB[us]), kmove_bb);
930 do_move_bb(&(byTypeBB[KING]), kmove_bb);
931 do_move_bb(&(byTypeBB[0]), kmove_bb); // HACK: byTypeBB[0] == occupied squares
933 Bitboard rmove_bb = make_move_bb(rfrom, rto);
934 do_move_bb(&(byColorBB[us]), rmove_bb);
935 do_move_bb(&(byTypeBB[ROOK]), rmove_bb);
936 do_move_bb(&(byTypeBB[0]), rmove_bb); // HACK: byTypeBB[0] == occupied squares
938 // Update board array
939 Piece king = piece_of_color_and_type(us, KING);
940 Piece rook = piece_of_color_and_type(us, ROOK);
941 board[kfrom] = board[rfrom] = EMPTY;
945 // Update king square
946 kingSquare[us] = kto;
948 // Update piece lists
949 pieceList[us][KING][index[kfrom]] = kto;
950 pieceList[us][ROOK][index[rfrom]] = rto;
951 int tmp = index[rfrom];
952 index[kto] = index[kfrom];
955 // Update incremental scores
956 st->mgValue += pst_delta<MidGame>(king, kfrom, kto);
957 st->egValue += pst_delta<EndGame>(king, kfrom, kto);
958 st->mgValue += pst_delta<MidGame>(rook, rfrom, rto);
959 st->egValue += pst_delta<EndGame>(rook, rfrom, rto);
962 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
963 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
965 // Clear en passant square
966 if (st->epSquare != SQ_NONE)
968 st->key ^= zobEp[st->epSquare];
969 st->epSquare = SQ_NONE;
972 // Update castling rights
973 st->key ^= zobCastle[st->castleRights];
974 st->castleRights &= castleRightsMask[kfrom];
975 st->key ^= zobCastle[st->castleRights];
977 // Reset rule 50 counter
980 // Update checkers BB
981 st->checkersBB = attacks_to(king_square(them), us);
983 st->key ^= zobSideToMove;
987 /// Position::do_promotion_move() is a private method used to make a promotion
988 /// move. It is called from the main Position::do_move function.
990 void Position::do_promotion_move(Move m) {
997 assert(move_is_ok(m));
998 assert(move_is_promotion(m));
1000 us = side_to_move();
1001 them = opposite_color(us);
1002 from = move_from(m);
1005 assert(relative_rank(us, to) == RANK_8);
1006 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1007 assert(color_of_piece_on(to) == them || square_is_empty(to));
1009 st->capture = type_of_piece_on(to);
1012 do_capture_move(st->capture, them, to);
1015 clear_bit(&(byColorBB[us]), from);
1016 clear_bit(&(byTypeBB[PAWN]), from);
1017 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1018 board[from] = EMPTY;
1020 // Insert promoted piece
1021 promotion = move_promotion_piece(m);
1022 assert(promotion >= KNIGHT && promotion <= QUEEN);
1023 set_bit(&(byColorBB[us]), to);
1024 set_bit(&(byTypeBB[promotion]), to);
1025 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1026 board[to] = piece_of_color_and_type(us, promotion);
1029 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1031 // Update pawn hash key
1032 st->pawnKey ^= zobrist[us][PAWN][from];
1034 // Update material key
1035 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1036 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1038 // Update piece counts
1039 pieceCount[us][PAWN]--;
1040 pieceCount[us][promotion]++;
1042 // Update piece lists
1043 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1044 index[pieceList[us][PAWN][index[from]]] = index[from];
1045 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1046 index[to] = pieceCount[us][promotion] - 1;
1048 // Update incremental scores
1049 st->mgValue -= pst<MidGame>(us, PAWN, from);
1050 st->mgValue += pst<MidGame>(us, promotion, to);
1051 st->egValue -= pst<EndGame>(us, PAWN, from);
1052 st->egValue += pst<EndGame>(us, promotion, to);
1055 st->npMaterial[us] += piece_value_midgame(promotion);
1057 // Clear the en passant square
1058 if (st->epSquare != SQ_NONE)
1060 st->key ^= zobEp[st->epSquare];
1061 st->epSquare = SQ_NONE;
1064 // Update castle rights
1065 st->key ^= zobCastle[st->castleRights];
1066 st->castleRights &= castleRightsMask[to];
1067 st->key ^= zobCastle[st->castleRights];
1069 // Reset rule 50 counter
1072 // Update checkers BB
1073 st->checkersBB = attacks_to(king_square(them), us);
1075 st->key ^= zobSideToMove;
1079 /// Position::do_ep_move() is a private method used to make an en passant
1080 /// capture. It is called from the main Position::do_move function.
1082 void Position::do_ep_move(Move m) {
1085 Square from, to, capsq;
1088 assert(move_is_ok(m));
1089 assert(move_is_ep(m));
1091 us = side_to_move();
1092 them = opposite_color(us);
1093 from = move_from(m);
1095 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1097 assert(to == st->epSquare);
1098 assert(relative_rank(us, to) == RANK_6);
1099 assert(piece_on(to) == EMPTY);
1100 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1101 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1103 // Remove captured pawn
1104 clear_bit(&(byColorBB[them]), capsq);
1105 clear_bit(&(byTypeBB[PAWN]), capsq);
1106 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1107 board[capsq] = EMPTY;
1109 // Move capturing pawn
1110 Bitboard move_bb = make_move_bb(from, to);
1111 do_move_bb(&(byColorBB[us]), move_bb);
1112 do_move_bb(&(byTypeBB[PAWN]), move_bb);
1113 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1114 board[to] = board[from];
1115 board[from] = EMPTY;
1117 // Update material hash key
1118 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1120 // Update piece count
1121 pieceCount[them][PAWN]--;
1123 // Update piece list
1124 pieceList[us][PAWN][index[from]] = to;
1125 index[to] = index[from];
1126 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1127 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1130 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1131 st->key ^= zobrist[them][PAWN][capsq];
1132 st->key ^= zobEp[st->epSquare];
1134 // Update pawn hash key
1135 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1136 st->pawnKey ^= zobrist[them][PAWN][capsq];
1138 // Update incremental scores
1139 Piece pawn = piece_of_color_and_type(us, PAWN);
1140 st->mgValue += pst_delta<MidGame>(pawn, from, to);
1141 st->egValue += pst_delta<EndGame>(pawn, from, to);
1142 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1143 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1145 // Reset en passant square
1146 st->epSquare = SQ_NONE;
1148 // Reset rule 50 counter
1151 // Update checkers BB
1152 st->checkersBB = attacks_to(king_square(them), us);
1154 st->key ^= zobSideToMove;
1158 /// Position::undo_move() unmakes a move. When it returns, the position should
1159 /// be restored to exactly the same state as before the move was made.
1161 void Position::undo_move(Move m) {
1164 assert(move_is_ok(m));
1167 sideToMove = opposite_color(sideToMove);
1169 if (move_is_castle(m))
1170 undo_castle_move(m);
1171 else if (move_is_promotion(m))
1172 undo_promotion_move(m);
1173 else if (move_is_ep(m))
1181 us = side_to_move();
1182 them = opposite_color(us);
1183 from = move_from(m);
1186 assert(piece_on(from) == EMPTY);
1187 assert(color_of_piece_on(to) == us);
1189 // Put the piece back at the source square
1190 Bitboard move_bb = make_move_bb(to, from);
1191 piece = type_of_piece_on(to);
1192 do_move_bb(&(byColorBB[us]), move_bb);
1193 do_move_bb(&(byTypeBB[piece]), move_bb);
1194 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1195 board[from] = piece_of_color_and_type(us, piece);
1197 // If the moving piece was a king, update the king square
1199 kingSquare[us] = from;
1201 // Update piece list
1202 pieceList[us][piece][index[to]] = from;
1203 index[from] = index[to];
1207 assert(st->capture != KING);
1209 // Restore the captured piece
1210 set_bit(&(byColorBB[them]), to);
1211 set_bit(&(byTypeBB[st->capture]), to);
1212 set_bit(&(byTypeBB[0]), to);
1213 board[to] = piece_of_color_and_type(them, st->capture);
1215 // Update piece list
1216 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1217 index[to] = pieceCount[them][st->capture];
1219 // Update piece count
1220 pieceCount[them][st->capture]++;
1225 // Finally point our state pointer back to the previous state
1232 /// Position::undo_castle_move() is a private method used to unmake a castling
1233 /// move. It is called from the main Position::undo_move function. Note that
1234 /// castling moves are encoded as "king captures friendly rook" moves, for
1235 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1237 void Position::undo_castle_move(Move m) {
1239 assert(move_is_ok(m));
1240 assert(move_is_castle(m));
1242 // When we have arrived here, some work has already been done by
1243 // Position::undo_move. In particular, the side to move has been switched,
1244 // so the code below is correct.
1245 Color us = side_to_move();
1247 // Find source squares for king and rook
1248 Square kfrom = move_from(m);
1249 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1252 // Find destination squares for king and rook
1253 if (rfrom > kfrom) // O-O
1255 kto = relative_square(us, SQ_G1);
1256 rto = relative_square(us, SQ_F1);
1258 kto = relative_square(us, SQ_C1);
1259 rto = relative_square(us, SQ_D1);
1262 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1263 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1265 // Put the pieces back at the source square
1266 Bitboard kmove_bb = make_move_bb(kto, kfrom);
1267 do_move_bb(&(byColorBB[us]), kmove_bb);
1268 do_move_bb(&(byTypeBB[KING]), kmove_bb);
1269 do_move_bb(&(byTypeBB[0]), kmove_bb); // HACK: byTypeBB[0] == occupied squares
1271 Bitboard rmove_bb = make_move_bb(rto, rfrom);
1272 do_move_bb(&(byColorBB[us]), rmove_bb);
1273 do_move_bb(&(byTypeBB[ROOK]), rmove_bb);
1274 do_move_bb(&(byTypeBB[0]), rmove_bb); // HACK: byTypeBB[0] == occupied squares
1277 board[rto] = board[kto] = EMPTY;
1278 board[rfrom] = piece_of_color_and_type(us, ROOK);
1279 board[kfrom] = piece_of_color_and_type(us, KING);
1281 // Update king square
1282 kingSquare[us] = kfrom;
1284 // Update piece lists
1285 pieceList[us][KING][index[kto]] = kfrom;
1286 pieceList[us][ROOK][index[rto]] = rfrom;
1287 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1288 index[kfrom] = index[kto];
1293 /// Position::undo_promotion_move() is a private method used to unmake a
1294 /// promotion move. It is called from the main Position::do_move
1297 void Position::undo_promotion_move(Move m) {
1301 PieceType promotion;
1303 assert(move_is_ok(m));
1304 assert(move_is_promotion(m));
1306 // When we have arrived here, some work has already been done by
1307 // Position::undo_move. In particular, the side to move has been switched,
1308 // so the code below is correct.
1309 us = side_to_move();
1310 them = opposite_color(us);
1311 from = move_from(m);
1314 assert(relative_rank(us, to) == RANK_8);
1315 assert(piece_on(from) == EMPTY);
1317 // Remove promoted piece
1318 promotion = move_promotion_piece(m);
1319 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1320 assert(promotion >= KNIGHT && promotion <= QUEEN);
1321 clear_bit(&(byColorBB[us]), to);
1322 clear_bit(&(byTypeBB[promotion]), to);
1323 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1325 // Insert pawn at source square
1326 set_bit(&(byColorBB[us]), from);
1327 set_bit(&(byTypeBB[PAWN]), from);
1328 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1329 board[from] = piece_of_color_and_type(us, PAWN);
1331 // Update piece list
1332 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1333 index[from] = pieceCount[us][PAWN];
1334 pieceList[us][promotion][index[to]] =
1335 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1336 index[pieceList[us][promotion][index[to]]] = index[to];
1338 // Update piece counts
1339 pieceCount[us][promotion]--;
1340 pieceCount[us][PAWN]++;
1344 assert(st->capture != KING);
1346 // Insert captured piece:
1347 set_bit(&(byColorBB[them]), to);
1348 set_bit(&(byTypeBB[st->capture]), to);
1349 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1350 board[to] = piece_of_color_and_type(them, st->capture);
1352 // Update piece list
1353 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1354 index[to] = pieceCount[them][st->capture];
1356 // Update piece count
1357 pieceCount[them][st->capture]++;
1363 /// Position::undo_ep_move() is a private method used to unmake an en passant
1364 /// capture. It is called from the main Position::undo_move function.
1366 void Position::undo_ep_move(Move m) {
1368 assert(move_is_ok(m));
1369 assert(move_is_ep(m));
1371 // When we have arrived here, some work has already been done by
1372 // Position::undo_move. In particular, the side to move has been switched,
1373 // so the code below is correct.
1374 Color us = side_to_move();
1375 Color them = opposite_color(us);
1376 Square from = move_from(m);
1377 Square to = move_to(m);
1378 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1380 assert(to == st->previous->epSquare);
1381 assert(relative_rank(us, to) == RANK_6);
1382 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1383 assert(piece_on(from) == EMPTY);
1384 assert(piece_on(capsq) == EMPTY);
1386 // Restore captured pawn
1387 set_bit(&(byColorBB[them]), capsq);
1388 set_bit(&(byTypeBB[PAWN]), capsq);
1389 set_bit(&(byTypeBB[0]), capsq);
1390 board[capsq] = piece_of_color_and_type(them, PAWN);
1392 // Move capturing pawn back to source square
1393 Bitboard move_bb = make_move_bb(to, from);
1394 do_move_bb(&(byColorBB[us]), move_bb);
1395 do_move_bb(&(byTypeBB[PAWN]), move_bb);
1396 do_move_bb(&(byTypeBB[0]), move_bb);
1398 board[from] = piece_of_color_and_type(us, PAWN);
1400 // Update piece list
1401 pieceList[us][PAWN][index[to]] = from;
1402 index[from] = index[to];
1403 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1404 index[capsq] = pieceCount[them][PAWN];
1406 // Update piece count
1407 pieceCount[them][PAWN]++;
1411 /// Position::do_null_move makes() a "null move": It switches the side to move
1412 /// and updates the hash key without executing any move on the board.
1414 void Position::do_null_move(StateInfo& backupSt) {
1417 assert(!is_check());
1419 // Back up the information necessary to undo the null move to the supplied
1420 // StateInfo object.
1421 // Note that differently from normal case here backupSt is actually used as
1422 // a backup storage not as a new state to be used.
1423 backupSt.epSquare = st->epSquare;
1424 backupSt.key = st->key;
1425 backupSt.mgValue = st->mgValue;
1426 backupSt.egValue = st->egValue;
1427 backupSt.previous = st->previous;
1428 st->previous = &backupSt;
1430 // Save the current key to the history[] array, in order to be able to
1431 // detect repetition draws.
1432 history[gamePly] = st->key;
1434 // Update the necessary information
1435 if (st->epSquare != SQ_NONE)
1436 st->key ^= zobEp[st->epSquare];
1438 st->key ^= zobSideToMove;
1439 TT->prefetch(st->key);
1440 sideToMove = opposite_color(sideToMove);
1441 st->epSquare = SQ_NONE;
1445 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1446 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1452 /// Position::undo_null_move() unmakes a "null move".
1454 void Position::undo_null_move() {
1457 assert(!is_check());
1459 // Restore information from the our backup StateInfo object
1460 st->epSquare = st->previous->epSquare;
1461 st->key = st->previous->key;
1462 st->mgValue = st->previous->mgValue;
1463 st->egValue = st->previous->egValue;
1464 st->previous = st->previous->previous;
1466 // Update the necessary information
1467 sideToMove = opposite_color(sideToMove);
1475 /// Position::see() is a static exchange evaluator: It tries to estimate the
1476 /// material gain or loss resulting from a move. There are three versions of
1477 /// this function: One which takes a destination square as input, one takes a
1478 /// move, and one which takes a 'from' and a 'to' square. The function does
1479 /// not yet understand promotions captures.
1481 int Position::see(Square to) const {
1483 assert(square_is_ok(to));
1484 return see(SQ_NONE, to);
1487 int Position::see(Move m) const {
1489 assert(move_is_ok(m));
1490 return see(move_from(m), move_to(m));
1493 int Position::see_sign(Move m) const {
1495 assert(move_is_ok(m));
1497 Square from = move_from(m);
1498 Square to = move_to(m);
1500 // Early return if SEE cannot be negative because capturing piece value
1501 // is not bigger then captured one.
1502 if ( midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1503 && type_of_piece_on(from) != KING)
1506 return see(from, to);
1509 int Position::see(Square from, Square to) const {
1512 static const int seeValues[18] = {
1513 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1514 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1515 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1516 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1520 Bitboard attackers, stmAttackers, occ, b;
1522 assert(square_is_ok(from) || from == SQ_NONE);
1523 assert(square_is_ok(to));
1525 // Initialize colors
1526 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1527 Color them = opposite_color(us);
1529 // Initialize pieces
1530 Piece piece = piece_on(from);
1531 Piece capture = piece_on(to);
1533 // Find all attackers to the destination square, with the moving piece
1534 // removed, but possibly an X-ray attacker added behind it.
1535 occ = occupied_squares();
1537 // Handle en passant moves
1538 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1540 assert(capture == EMPTY);
1542 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1543 capture = piece_on(capQq);
1544 assert(type_of_piece_on(capQq) == PAWN);
1546 // Remove the captured pawn
1547 clear_bit(&occ, capQq);
1552 clear_bit(&occ, from);
1553 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1554 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1555 | (piece_attacks<KNIGHT>(to) & knights())
1556 | (piece_attacks<KING>(to) & kings())
1557 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1558 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1560 if (from != SQ_NONE)
1563 // If we don't have any attacker we are finished
1564 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1567 // Locate the least valuable attacker to the destination square
1568 // and use it to initialize from square.
1570 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1573 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1574 piece = piece_on(from);
1577 // If the opponent has no attackers we are finished
1578 stmAttackers = attackers & pieces_of_color(them);
1580 return seeValues[capture];
1582 attackers &= occ; // Remove the moving piece
1584 // The destination square is defended, which makes things rather more
1585 // difficult to compute. We proceed by building up a "swap list" containing
1586 // the material gain or loss at each stop in a sequence of captures to the
1587 // destination square, where the sides alternately capture, and always
1588 // capture with the least valuable piece. After each capture, we look for
1589 // new X-ray attacks from behind the capturing piece.
1590 int lastCapturingPieceValue = seeValues[piece];
1591 int swapList[32], n = 1;
1595 swapList[0] = seeValues[capture];
1598 // Locate the least valuable attacker for the side to move. The loop
1599 // below looks like it is potentially infinite, but it isn't. We know
1600 // that the side to move still has at least one attacker left.
1601 for (pt = PAWN; !(stmAttackers & pieces_of_type(pt)); pt++)
1604 // Remove the attacker we just found from the 'attackers' bitboard,
1605 // and scan for new X-ray attacks behind the attacker.
1606 b = stmAttackers & pieces_of_type(pt);
1607 occ ^= (b & (~b + 1));
1608 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1609 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1613 // Add the new entry to the swap list
1615 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1618 // Remember the value of the capturing piece, and change the side to move
1619 // before beginning the next iteration
1620 lastCapturingPieceValue = seeValues[pt];
1621 c = opposite_color(c);
1622 stmAttackers = attackers & pieces_of_color(c);
1624 // Stop after a king capture
1625 if (pt == KING && stmAttackers)
1628 swapList[n++] = QueenValueMidgame*10;
1631 } while (stmAttackers);
1633 // Having built the swap list, we negamax through it to find the best
1634 // achievable score from the point of view of the side to move
1636 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1642 /// Position::saveState() copies the content of the current state
1643 /// inside startState and makes st point to it. This is needed
1644 /// when the st pointee could become stale, as example because
1645 /// the caller is about to going out of scope.
1647 void Position::saveState() {
1651 st->previous = NULL; // as a safe guard
1655 /// Position::clear() erases the position object to a pristine state, with an
1656 /// empty board, white to move, and no castling rights.
1658 void Position::clear() {
1661 memset(st, 0, sizeof(StateInfo));
1662 st->epSquare = SQ_NONE;
1664 memset(index, 0, sizeof(int) * 64);
1665 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1667 for (int i = 0; i < 64; i++)
1670 for (int i = 0; i < 7; i++)
1672 byTypeBB[i] = EmptyBoardBB;
1673 pieceCount[0][i] = pieceCount[1][i] = 0;
1674 for (int j = 0; j < 8; j++)
1675 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1680 initialKFile = FILE_E;
1681 initialKRFile = FILE_H;
1682 initialQRFile = FILE_A;
1687 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1688 /// UCI interface code, whenever a non-reversible move is made in a
1689 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1690 /// for the program to handle games of arbitrary length, as long as the GUI
1691 /// handles draws by the 50 move rule correctly.
1693 void Position::reset_game_ply() {
1699 /// Position::put_piece() puts a piece on the given square of the board,
1700 /// updating the board array, bitboards, and piece counts.
1702 void Position::put_piece(Piece p, Square s) {
1704 Color c = color_of_piece(p);
1705 PieceType pt = type_of_piece(p);
1708 index[s] = pieceCount[c][pt];
1709 pieceList[c][pt][index[s]] = s;
1711 set_bit(&(byTypeBB[pt]), s);
1712 set_bit(&(byColorBB[c]), s);
1713 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1715 pieceCount[c][pt]++;
1722 /// Position::allow_oo() gives the given side the right to castle kingside.
1723 /// Used when setting castling rights during parsing of FEN strings.
1725 void Position::allow_oo(Color c) {
1727 st->castleRights |= (1 + int(c));
1731 /// Position::allow_ooo() gives the given side the right to castle queenside.
1732 /// Used when setting castling rights during parsing of FEN strings.
1734 void Position::allow_ooo(Color c) {
1736 st->castleRights |= (4 + 4*int(c));
1740 /// Position::compute_key() computes the hash key of the position. The hash
1741 /// key is usually updated incrementally as moves are made and unmade, the
1742 /// compute_key() function is only used when a new position is set up, and
1743 /// to verify the correctness of the hash key when running in debug mode.
1745 Key Position::compute_key() const {
1747 Key result = Key(0ULL);
1749 for (Square s = SQ_A1; s <= SQ_H8; s++)
1750 if (square_is_occupied(s))
1751 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1753 if (ep_square() != SQ_NONE)
1754 result ^= zobEp[ep_square()];
1756 result ^= zobCastle[st->castleRights];
1757 if (side_to_move() == BLACK)
1758 result ^= zobSideToMove;
1764 /// Position::compute_pawn_key() computes the hash key of the position. The
1765 /// hash key is usually updated incrementally as moves are made and unmade,
1766 /// the compute_pawn_key() function is only used when a new position is set
1767 /// up, and to verify the correctness of the pawn hash key when running in
1770 Key Position::compute_pawn_key() const {
1772 Key result = Key(0ULL);
1776 for (Color c = WHITE; c <= BLACK; c++)
1781 s = pop_1st_bit(&b);
1782 result ^= zobrist[c][PAWN][s];
1789 /// Position::compute_material_key() computes the hash key of the position.
1790 /// The hash key is usually updated incrementally as moves are made and unmade,
1791 /// the compute_material_key() function is only used when a new position is set
1792 /// up, and to verify the correctness of the material hash key when running in
1795 Key Position::compute_material_key() const {
1797 Key result = Key(0ULL);
1798 for (Color c = WHITE; c <= BLACK; c++)
1799 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1801 int count = piece_count(c, pt);
1802 for (int i = 0; i <= count; i++)
1803 result ^= zobMaterial[c][pt][i];
1809 /// Position::compute_value() compute the incremental scores for the middle
1810 /// game and the endgame. These functions are used to initialize the incremental
1811 /// scores when a new position is set up, and to verify that the scores are correctly
1812 /// updated by do_move and undo_move when the program is running in debug mode.
1813 template<Position::GamePhase Phase>
1814 Value Position::compute_value() const {
1816 Value result = Value(0);
1820 for (Color c = WHITE; c <= BLACK; c++)
1821 for (PieceType pt = PAWN; pt <= KING; pt++)
1823 b = pieces_of_color_and_type(c, pt);
1826 s = pop_1st_bit(&b);
1827 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1828 result += pst<Phase>(c, pt, s);
1832 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1833 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1838 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1839 /// game material score for the given side. Material scores are updated
1840 /// incrementally during the search, this function is only used while
1841 /// initializing a new Position object.
1843 Value Position::compute_non_pawn_material(Color c) const {
1845 Value result = Value(0);
1847 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1849 Bitboard b = pieces_of_color_and_type(c, pt);
1852 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1854 result += piece_value_midgame(pt);
1861 /// Position::is_draw() tests whether the position is drawn by material,
1862 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1863 /// must be done by the search.
1865 bool Position::is_draw() const {
1867 // Draw by material?
1869 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1872 // Draw by the 50 moves rule?
1873 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1876 // Draw by repetition?
1877 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1878 if (history[gamePly - i] == st->key)
1885 /// Position::is_mate() returns true or false depending on whether the
1886 /// side to move is checkmated.
1888 bool Position::is_mate() const {
1890 MoveStack moves[256];
1892 return is_check() && !generate_evasions(*this, moves, pinned_pieces(sideToMove));
1896 /// Position::has_mate_threat() tests whether a given color has a mate in one
1897 /// from the current position.
1899 bool Position::has_mate_threat(Color c) {
1902 Color stm = side_to_move();
1907 // If the input color is not equal to the side to move, do a null move
1911 MoveStack mlist[120];
1913 bool result = false;
1914 Bitboard dc = discovered_check_candidates(sideToMove);
1915 Bitboard pinned = pinned_pieces(sideToMove);
1917 // Generate pseudo-legal non-capture and capture check moves
1918 count = generate_non_capture_checks(*this, mlist, dc);
1919 count += generate_captures(*this, mlist + count);
1921 // Loop through the moves, and see if one of them is mate
1922 for (int i = 0; i < count; i++)
1924 Move move = mlist[i].move;
1926 if (!pl_move_is_legal(move, pinned))
1936 // Undo null move, if necessary
1944 /// Position::init_zobrist() is a static member function which initializes the
1945 /// various arrays used to compute hash keys.
1947 void Position::init_zobrist() {
1949 for (int i = 0; i < 2; i++)
1950 for (int j = 0; j < 8; j++)
1951 for (int k = 0; k < 64; k++)
1952 zobrist[i][j][k] = Key(genrand_int64());
1954 for (int i = 0; i < 64; i++)
1955 zobEp[i] = Key(genrand_int64());
1957 for (int i = 0; i < 16; i++)
1958 zobCastle[i] = genrand_int64();
1960 zobSideToMove = genrand_int64();
1962 for (int i = 0; i < 2; i++)
1963 for (int j = 0; j < 8; j++)
1964 for (int k = 0; k < 16; k++)
1965 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1967 for (int i = 0; i < 16; i++)
1968 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1972 /// Position::init_piece_square_tables() initializes the piece square tables.
1973 /// This is a two-step operation: First, the white halves of the tables are
1974 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1975 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1976 /// Second, the black halves of the tables are initialized by mirroring
1977 /// and changing the sign of the corresponding white scores.
1979 void Position::init_piece_square_tables() {
1981 int r = get_option_value_int("Randomness"), i;
1982 for (Square s = SQ_A1; s <= SQ_H8; s++)
1983 for (Piece p = WP; p <= WK; p++)
1985 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1986 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1987 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1990 for (Square s = SQ_A1; s <= SQ_H8; s++)
1991 for (Piece p = BP; p <= BK; p++)
1993 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1994 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
1999 /// Position::flipped_copy() makes a copy of the input position, but with
2000 /// the white and black sides reversed. This is only useful for debugging,
2001 /// especially for finding evaluation symmetry bugs.
2003 void Position::flipped_copy(const Position& pos) {
2005 assert(pos.is_ok());
2010 for (Square s = SQ_A1; s <= SQ_H8; s++)
2011 if (!pos.square_is_empty(s))
2012 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2015 sideToMove = opposite_color(pos.side_to_move());
2018 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2019 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2020 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2021 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2023 initialKFile = pos.initialKFile;
2024 initialKRFile = pos.initialKRFile;
2025 initialQRFile = pos.initialQRFile;
2027 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2028 castleRightsMask[sq] = ALL_CASTLES;
2030 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2031 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2032 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2033 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2034 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2035 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2037 // En passant square
2038 if (pos.st->epSquare != SQ_NONE)
2039 st->epSquare = flip_square(pos.st->epSquare);
2045 st->key = compute_key();
2046 st->pawnKey = compute_pawn_key();
2047 st->materialKey = compute_material_key();
2049 // Incremental scores
2050 st->mgValue = compute_value<MidGame>();
2051 st->egValue = compute_value<EndGame>();
2054 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2055 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2061 /// Position::is_ok() performs some consitency checks for the position object.
2062 /// This is meant to be helpful when debugging.
2064 bool Position::is_ok(int* failedStep) const {
2066 // What features of the position should be verified?
2067 static const bool debugBitboards = false;
2068 static const bool debugKingCount = false;
2069 static const bool debugKingCapture = false;
2070 static const bool debugCheckerCount = false;
2071 static const bool debugKey = false;
2072 static const bool debugMaterialKey = false;
2073 static const bool debugPawnKey = false;
2074 static const bool debugIncrementalEval = false;
2075 static const bool debugNonPawnMaterial = false;
2076 static const bool debugPieceCounts = false;
2077 static const bool debugPieceList = false;
2079 if (failedStep) *failedStep = 1;
2082 if (!color_is_ok(side_to_move()))
2085 // Are the king squares in the position correct?
2086 if (failedStep) (*failedStep)++;
2087 if (piece_on(king_square(WHITE)) != WK)
2090 if (failedStep) (*failedStep)++;
2091 if (piece_on(king_square(BLACK)) != BK)
2095 if (failedStep) (*failedStep)++;
2096 if (!file_is_ok(initialKRFile))
2099 if (!file_is_ok(initialQRFile))
2102 // Do both sides have exactly one king?
2103 if (failedStep) (*failedStep)++;
2106 int kingCount[2] = {0, 0};
2107 for (Square s = SQ_A1; s <= SQ_H8; s++)
2108 if (type_of_piece_on(s) == KING)
2109 kingCount[color_of_piece_on(s)]++;
2111 if (kingCount[0] != 1 || kingCount[1] != 1)
2115 // Can the side to move capture the opponent's king?
2116 if (failedStep) (*failedStep)++;
2117 if (debugKingCapture)
2119 Color us = side_to_move();
2120 Color them = opposite_color(us);
2121 Square ksq = king_square(them);
2122 if (square_is_attacked(ksq, us))
2126 // Is there more than 2 checkers?
2127 if (failedStep) (*failedStep)++;
2128 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2132 if (failedStep) (*failedStep)++;
2135 // The intersection of the white and black pieces must be empty
2136 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2139 // The union of the white and black pieces must be equal to all
2141 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2144 // Separate piece type bitboards must have empty intersections
2145 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2146 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2147 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2151 // En passant square OK?
2152 if (failedStep) (*failedStep)++;
2153 if (ep_square() != SQ_NONE)
2155 // The en passant square must be on rank 6, from the point of view of the
2157 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2162 if (failedStep) (*failedStep)++;
2163 if (debugKey && st->key != compute_key())
2166 // Pawn hash key OK?
2167 if (failedStep) (*failedStep)++;
2168 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2171 // Material hash key OK?
2172 if (failedStep) (*failedStep)++;
2173 if (debugMaterialKey && st->materialKey != compute_material_key())
2176 // Incremental eval OK?
2177 if (failedStep) (*failedStep)++;
2178 if (debugIncrementalEval)
2180 if (st->mgValue != compute_value<MidGame>())
2183 if (st->egValue != compute_value<EndGame>())
2187 // Non-pawn material OK?
2188 if (failedStep) (*failedStep)++;
2189 if (debugNonPawnMaterial)
2191 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2194 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2199 if (failedStep) (*failedStep)++;
2200 if (debugPieceCounts)
2201 for (Color c = WHITE; c <= BLACK; c++)
2202 for (PieceType pt = PAWN; pt <= KING; pt++)
2203 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2206 if (failedStep) (*failedStep)++;
2209 for(Color c = WHITE; c <= BLACK; c++)
2210 for(PieceType pt = PAWN; pt <= KING; pt++)
2211 for(int i = 0; i < pieceCount[c][pt]; i++)
2213 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2216 if (index[piece_list(c, pt, i)] != i)
2220 if (failedStep) *failedStep = 0;