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/>.
37 #include "ucioption.h"
46 int Position::castleRightsMask[64];
48 Key Position::zobrist[2][8][64];
49 Key Position::zobEp[64];
50 Key Position::zobCastle[16];
51 Key Position::zobMaterial[2][8][16];
52 Key Position::zobSideToMove;
54 Value Position::MgPieceSquareTable[16][64];
55 Value Position::EgPieceSquareTable[16][64];
57 static bool RequestPending = false;
65 Position::Position(const Position& pos) {
69 Position::Position(const string& fen) {
74 /// Position::from_fen() initializes the position object with the given FEN
75 /// string. This function is not very robust - make sure that input FENs are
76 /// correct (this is assumed to be the responsibility of the GUI).
78 void Position::from_fen(const string& fen) {
80 static const string pieceLetters = "KQRBNPkqrbnp";
81 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
89 for ( ; fen[i] != ' '; i++)
93 // Skip the given number of files
94 file += (fen[i] - '1' + 1);
97 else if (fen[i] == '/')
103 size_t idx = pieceLetters.find(fen[i]);
104 if (idx == string::npos)
106 std::cout << "Error in FEN at character " << i << std::endl;
109 Square square = make_square(file, rank);
110 put_piece(pieces[idx], square);
116 if (fen[i] != 'w' && fen[i] != 'b')
118 std::cout << "Error in FEN at character " << i << std::endl;
121 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
127 std::cout << "Error in FEN at character " << i << std::endl;
132 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
138 else if(fen[i] == 'K') allow_oo(WHITE);
139 else if(fen[i] == 'Q') allow_ooo(WHITE);
140 else if(fen[i] == 'k') allow_oo(BLACK);
141 else if(fen[i] == 'q') allow_ooo(BLACK);
142 else if(fen[i] >= 'A' && fen[i] <= 'H') {
143 File rookFile, kingFile = FILE_NONE;
144 for(Square square = SQ_B1; square <= SQ_G1; square++)
145 if(piece_on(square) == WK)
146 kingFile = square_file(square);
147 if(kingFile == FILE_NONE) {
148 std::cout << "Error in FEN at character " << i << std::endl;
151 initialKFile = kingFile;
152 rookFile = File(fen[i] - 'A') + FILE_A;
153 if(rookFile < initialKFile) {
155 initialQRFile = rookFile;
159 initialKRFile = rookFile;
162 else if(fen[i] >= 'a' && fen[i] <= 'h') {
163 File rookFile, kingFile = FILE_NONE;
164 for(Square square = SQ_B8; square <= SQ_G8; square++)
165 if(piece_on(square) == BK)
166 kingFile = square_file(square);
167 if(kingFile == FILE_NONE) {
168 std::cout << "Error in FEN at character " << i << std::endl;
171 initialKFile = kingFile;
172 rookFile = File(fen[i] - 'a') + FILE_A;
173 if(rookFile < initialKFile) {
175 initialQRFile = rookFile;
179 initialKRFile = rookFile;
183 std::cout << "Error in FEN at character " << i << std::endl;
190 while (fen[i] == ' ')
194 if ( i <= fen.length() - 2
195 && (fen[i] >= 'a' && fen[i] <= 'h')
196 && (fen[i+1] == '3' || fen[i+1] == '6'))
197 st->epSquare = square_from_string(fen.substr(i, 2));
199 // Various initialisation
200 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
201 castleRightsMask[sq] = ALL_CASTLES;
203 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
204 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
205 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
206 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
207 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
208 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
212 st->key = compute_key();
213 st->pawnKey = compute_pawn_key();
214 st->materialKey = compute_material_key();
215 st->mgValue = compute_value<MidGame>();
216 st->egValue = compute_value<EndGame>();
217 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
218 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
222 /// Position::to_fen() converts the position object to a FEN string. This is
223 /// probably only useful for debugging.
225 const string Position::to_fen() const {
227 static const string pieceLetters = " PNBRQK pnbrqk";
231 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
234 for (File file = FILE_A; file <= FILE_H; file++)
236 Square sq = make_square(file, rank);
237 if (!square_is_occupied(sq))
243 fen += (char)skip + '0';
246 fen += pieceLetters[piece_on(sq)];
249 fen += (char)skip + '0';
251 fen += (rank > RANK_1 ? '/' : ' ');
253 fen += (sideToMove == WHITE ? "w " : "b ");
254 if (st->castleRights != NO_CASTLES)
256 if (can_castle_kingside(WHITE)) fen += 'K';
257 if (can_castle_queenside(WHITE)) fen += 'Q';
258 if (can_castle_kingside(BLACK)) fen += 'k';
259 if (can_castle_queenside(BLACK)) fen += 'q';
264 if (ep_square() != SQ_NONE)
265 fen += square_to_string(ep_square());
273 /// Position::print() prints an ASCII representation of the position to
274 /// the standard output. If a move is given then also the san is print.
276 void Position::print(Move m) const {
278 static const string pieceLetters = " PNBRQK PNBRQK .";
280 // Check for reentrancy, as example when called from inside
281 // MovePicker that is used also here in move_to_san()
285 RequestPending = true;
287 std::cout << std::endl;
290 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
291 std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
293 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
295 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
296 for (File file = FILE_A; file <= FILE_H; file++)
298 Square sq = make_square(file, rank);
299 Piece piece = piece_on(sq);
300 if (piece == EMPTY && square_color(sq) == WHITE)
303 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
304 std::cout << '|' << col << pieceLetters[piece] << col;
306 std::cout << '|' << std::endl;
308 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
309 << "Fen is: " << to_fen() << std::endl
310 << "Key is: " << st->key << std::endl;
312 RequestPending = false;
316 /// Position::copy() creates a copy of the input position.
318 void Position::copy(const Position &pos) {
320 memcpy(this, &pos, sizeof(Position));
324 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
325 /// king) pieces for the given color and for the given pinner type. Or, when
326 /// template parameter FindPinned is false, the pieces of the given color
327 /// candidate for a discovery check against the enemy king.
328 /// Note that checkersBB bitboard must be already updated.
330 template<bool FindPinned>
331 Bitboard Position::hidden_checkers(Color c) const {
333 Bitboard pinners, result = EmptyBoardBB;
335 // Pinned pieces protect our king, dicovery checks attack
337 Square ksq = king_square(FindPinned ? c : opposite_color(c));
339 // Pinners are sliders, not checkers, that give check when
340 // candidate pinned is removed.
341 pinners = (rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
342 | (bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq]);
344 if (FindPinned && pinners)
345 pinners &= ~st->checkersBB;
349 Square s = pop_1st_bit(&pinners);
350 Bitboard b = squares_between(s, ksq) & occupied_squares();
354 if ( !(b & (b - 1)) // Only one bit set?
355 && (b & pieces_of_color(c))) // Is an our piece?
362 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
363 /// king) pieces for the given color.
365 Bitboard Position::pinned_pieces(Color c) const {
367 return hidden_checkers<true>(c);
371 /// Position:discovered_check_candidates() returns a bitboard containing all
372 /// pieces for the given side which are candidates for giving a discovered
375 Bitboard Position::discovered_check_candidates(Color c) const {
377 return hidden_checkers<false>(c);
380 /// Position::attacks_to() computes a bitboard containing all pieces which
381 /// attacks a given square.
383 Bitboard Position::attacks_to(Square s) const {
385 return (pawn_attacks(BLACK, s) & pawns(WHITE))
386 | (pawn_attacks(WHITE, s) & pawns(BLACK))
387 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
388 | (piece_attacks<ROOK>(s) & rooks_and_queens())
389 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
390 | (piece_attacks<KING>(s) & pieces_of_type(KING));
393 /// Position::piece_attacks_square() tests whether the piece on square f
394 /// attacks square t.
396 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
398 assert(square_is_ok(f));
399 assert(square_is_ok(t));
403 case WP: return pawn_attacks_square(WHITE, f, t);
404 case BP: return pawn_attacks_square(BLACK, f, t);
405 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
406 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
407 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
408 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
409 case WK: case BK: return piece_attacks_square<KING>(f, t);
416 /// Position::move_attacks_square() tests whether a move from the current
417 /// position attacks a given square.
419 bool Position::move_attacks_square(Move m, Square s) const {
421 assert(move_is_ok(m));
422 assert(square_is_ok(s));
424 Square f = move_from(m), t = move_to(m);
426 assert(square_is_occupied(f));
428 if (piece_attacks_square(piece_on(f), t, s))
431 // Move the piece and scan for X-ray attacks behind it
432 Bitboard occ = occupied_squares();
433 Color us = color_of_piece_on(f);
436 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
437 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
439 // If we have attacks we need to verify that are caused by our move
440 // and are not already existent ones.
441 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
445 /// Position::find_checkers() computes the checkersBB bitboard, which
446 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
447 /// currently works by calling Position::attacks_to, which is probably
448 /// inefficient. Consider rewriting this function to use the last move
449 /// played, like in non-bitboard versions of Glaurung.
451 void Position::find_checkers() {
453 Color us = side_to_move();
454 st->checkersBB = attacks_to(king_square(us), opposite_color(us));
458 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
460 bool Position::pl_move_is_legal(Move m) const {
462 // If we're in check, all pseudo-legal moves are legal, because our
463 // check evasion generator only generates true legal moves.
464 return is_check() || pl_move_is_legal(m, pinned_pieces(side_to_move()));
467 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
470 assert(move_is_ok(m));
471 assert(pinned == pinned_pieces(side_to_move()));
474 // Castling moves are checked for legality during move generation.
475 if (move_is_castle(m))
478 Color us = side_to_move();
479 Square from = move_from(m);
480 Square ksq = king_square(us);
482 assert(color_of_piece_on(from) == us);
483 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
485 // En passant captures are a tricky special case. Because they are
486 // rather uncommon, we do it simply by testing whether the king is attacked
487 // after the move is made
490 Color them = opposite_color(us);
491 Square to = move_to(m);
492 Square capsq = make_square(square_file(to), square_rank(from));
493 Bitboard b = occupied_squares();
495 assert(to == ep_square());
496 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
497 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
498 assert(piece_on(to) == EMPTY);
501 clear_bit(&b, capsq);
504 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
505 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
508 // If the moving piece is a king, check whether the destination
509 // square is attacked by the opponent.
511 return !(square_is_attacked(move_to(m), opposite_color(us)));
513 // A non-king move is legal if and only if it is not pinned or it
514 // is moving along the ray towards or away from the king.
516 || !bit_is_set(pinned, from)
517 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
521 /// Position::move_is_check() tests whether a pseudo-legal move is a check
523 bool Position::move_is_check(Move m) const {
525 Bitboard dc = discovered_check_candidates(side_to_move());
526 return move_is_check(m, dc);
529 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
532 assert(move_is_ok(m));
533 assert(dcCandidates == discovered_check_candidates(side_to_move()));
535 Color us = side_to_move();
536 Color them = opposite_color(us);
537 Square from = move_from(m);
538 Square to = move_to(m);
539 Square ksq = king_square(them);
541 assert(color_of_piece_on(from) == us);
542 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
544 // Proceed according to the type of the moving piece
545 switch (type_of_piece_on(from))
549 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
552 if ( dcCandidates // Discovered check?
553 && bit_is_set(dcCandidates, from)
554 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
557 if (move_promotion(m)) // Promotion with check?
559 Bitboard b = occupied_squares();
562 switch (move_promotion(m))
565 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
567 return bit_is_set(bishop_attacks_bb(to, b), ksq);
569 return bit_is_set(rook_attacks_bb(to, b), ksq);
571 return bit_is_set(queen_attacks_bb(to, b), ksq);
576 // En passant capture with check? We have already handled the case
577 // of direct checks and ordinary discovered check, the only case we
578 // need to handle is the unusual case of a discovered check through the
580 else if (move_is_ep(m))
582 Square capsq = make_square(square_file(to), square_rank(from));
583 Bitboard b = occupied_squares();
585 clear_bit(&b, capsq);
587 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
588 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
592 // Test discovered check and normal check according to piece type
594 return (dcCandidates && bit_is_set(dcCandidates, from))
595 || bit_is_set(piece_attacks<KNIGHT>(ksq), to);
598 return (dcCandidates && bit_is_set(dcCandidates, from))
599 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to));
602 return (dcCandidates && bit_is_set(dcCandidates, from))
603 || (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to));
606 // Discovered checks are impossible!
607 assert(!bit_is_set(dcCandidates, from));
608 return ( (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to))
609 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to)));
613 if ( bit_is_set(dcCandidates, from)
614 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
617 // Castling with check?
618 if (move_is_castle(m))
620 Square kfrom, kto, rfrom, rto;
621 Bitboard b = occupied_squares();
627 kto = relative_square(us, SQ_G1);
628 rto = relative_square(us, SQ_F1);
630 kto = relative_square(us, SQ_C1);
631 rto = relative_square(us, SQ_D1);
633 clear_bit(&b, kfrom);
634 clear_bit(&b, rfrom);
637 return bit_is_set(rook_attacks_bb(rto, b), ksq);
641 default: // NO_PIECE_TYPE
649 /// Position::update_checkers() udpates chekers info given the move. It is called
650 /// in do_move() and is faster then find_checkers().
652 template<PieceType Piece>
653 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
654 Square to, Bitboard dcCandidates) {
656 const bool Bishop = (Piece == QUEEN || Piece == BISHOP);
657 const bool Rook = (Piece == QUEEN || Piece == ROOK);
658 const bool Slider = Bishop || Rook;
661 if ( ( (Bishop && bit_is_set(BishopPseudoAttacks[ksq], to))
662 || (Rook && bit_is_set(RookPseudoAttacks[ksq], to)))
663 && bit_is_set(piece_attacks<Piece>(ksq), to)) // slow, try to early skip
664 set_bit(pCheckersBB, to);
666 else if ( Piece != KING
668 && bit_is_set(piece_attacks<Piece>(ksq), to))
669 set_bit(pCheckersBB, to);
672 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
675 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
678 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
683 /// Position::do_move() makes a move, and saves all information necessary
684 /// to a StateInfo object. The move is assumed to be legal.
685 /// Pseudo-legal moves should be filtered out before this function is called.
687 void Position::do_move(Move m, StateInfo& newSt) {
689 do_move(m, newSt, discovered_check_candidates(side_to_move()));
692 void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
695 assert(move_is_ok(m));
697 // Copy some fields of old state to our new StateInfo object except the
698 // ones which are recalculated from scratch anyway, then switch our state
699 // pointer to point to the new, ready to be updated, state.
700 struct ReducedStateInfo {
701 Key key, pawnKey, materialKey;
702 int castleRights, rule50;
704 Value mgValue, egValue;
708 memcpy(&newSt, st, sizeof(ReducedStateInfo));
709 newSt.capture = NO_PIECE_TYPE;
713 // Save the current key to the history[] array, in order to be able to
714 // detect repetition draws.
715 history[gamePly] = st->key;
717 // Increment the 50 moves rule draw counter. Resetting it to zero in the
718 // case of non-reversible moves is taken care of later.
721 if (move_is_castle(m))
723 else if (move_promotion(m))
724 do_promotion_move(m);
725 else if (move_is_ep(m))
729 Color us = side_to_move();
730 Color them = opposite_color(us);
731 Square from = move_from(m);
732 Square to = move_to(m);
734 assert(color_of_piece_on(from) == us);
735 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
737 PieceType piece = type_of_piece_on(from);
739 st->capture = type_of_piece_on(to);
742 do_capture_move(st->capture, them, to);
745 Bitboard move_bb = make_move_bb(from, to);
746 do_move_bb(&(byColorBB[us]), move_bb);
747 do_move_bb(&(byTypeBB[piece]), move_bb);
748 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
750 board[to] = board[from];
754 st->key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
756 // Update incremental scores
757 st->mgValue -= pst<MidGame>(us, piece, from);
758 st->mgValue += pst<MidGame>(us, piece, to);
759 st->egValue -= pst<EndGame>(us, piece, from);
760 st->egValue += pst<EndGame>(us, piece, to);
762 // If the moving piece was a king, update the king square
766 // Reset en passant square
767 if (st->epSquare != SQ_NONE)
769 st->key ^= zobEp[st->epSquare];
770 st->epSquare = SQ_NONE;
773 // If the moving piece was a pawn do some special extra work
776 // Reset rule 50 draw counter
779 // Update pawn hash key
780 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
782 // Set en passant square, only if moved pawn can be captured
783 if (abs(int(to) - int(from)) == 16)
785 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
786 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
788 st->epSquare = Square((int(from) + int(to)) / 2);
789 st->key ^= zobEp[st->epSquare];
794 // Update piece lists
795 pieceList[us][piece][index[from]] = to;
796 index[to] = index[from];
798 // Update castle rights
799 st->key ^= zobCastle[st->castleRights];
800 st->castleRights &= castleRightsMask[from];
801 st->castleRights &= castleRightsMask[to];
802 st->key ^= zobCastle[st->castleRights];
804 // Update checkers bitboard, piece must be already moved
805 st->checkersBB = EmptyBoardBB;
806 Square ksq = king_square(them);
809 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
810 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
811 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
812 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
813 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
814 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
815 default: assert(false); break;
820 st->key ^= zobSideToMove;
821 sideToMove = opposite_color(sideToMove);
824 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
825 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
831 /// Position::do_capture_move() is a private method used to update captured
832 /// piece info. It is called from the main Position::do_move function.
834 void Position::do_capture_move(PieceType capture, Color them, Square to) {
836 assert(capture != KING);
838 // Remove captured piece
839 clear_bit(&(byColorBB[them]), to);
840 clear_bit(&(byTypeBB[capture]), to);
841 clear_bit(&(byTypeBB[0]), to);
844 st->key ^= zobrist[them][capture][to];
846 // If the captured piece was a pawn, update pawn hash key
848 st->pawnKey ^= zobrist[them][PAWN][to];
850 // Update incremental scores
851 st->mgValue -= pst<MidGame>(them, capture, to);
852 st->egValue -= pst<EndGame>(them, capture, to);
856 st->npMaterial[them] -= piece_value_midgame(capture);
858 // Update material hash key
859 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
861 // Update piece count
862 pieceCount[them][capture]--;
865 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
866 index[pieceList[them][capture][index[to]]] = index[to];
868 // Reset rule 50 counter
873 /// Position::do_castle_move() is a private method used to make a castling
874 /// move. It is called from the main Position::do_move function. Note that
875 /// castling moves are encoded as "king captures friendly rook" moves, for
876 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
878 void Position::do_castle_move(Move m) {
881 assert(move_is_ok(m));
882 assert(move_is_castle(m));
884 Color us = side_to_move();
885 Color them = opposite_color(us);
887 // Find source squares for king and rook
888 Square kfrom = move_from(m);
889 Square rfrom = move_to(m); // HACK: See comment at beginning of function
892 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
893 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
895 // Find destination squares for king and rook
896 if (rfrom > kfrom) // O-O
898 kto = relative_square(us, SQ_G1);
899 rto = relative_square(us, SQ_F1);
901 kto = relative_square(us, SQ_C1);
902 rto = relative_square(us, SQ_D1);
905 // Remove pieces from source squares
906 clear_bit(&(byColorBB[us]), kfrom);
907 clear_bit(&(byTypeBB[KING]), kfrom);
908 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
909 clear_bit(&(byColorBB[us]), rfrom);
910 clear_bit(&(byTypeBB[ROOK]), rfrom);
911 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
913 // Put pieces on destination squares
914 set_bit(&(byColorBB[us]), kto);
915 set_bit(&(byTypeBB[KING]), kto);
916 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
917 set_bit(&(byColorBB[us]), rto);
918 set_bit(&(byTypeBB[ROOK]), rto);
919 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
921 // Update board array
922 board[kfrom] = board[rfrom] = EMPTY;
923 board[kto] = piece_of_color_and_type(us, KING);
924 board[rto] = piece_of_color_and_type(us, ROOK);
926 // Update king square
927 kingSquare[us] = kto;
929 // Update piece lists
930 pieceList[us][KING][index[kfrom]] = kto;
931 pieceList[us][ROOK][index[rfrom]] = rto;
932 int tmp = index[rfrom];
933 index[kto] = index[kfrom];
936 // Update incremental scores
937 st->mgValue -= pst<MidGame>(us, KING, kfrom);
938 st->mgValue += pst<MidGame>(us, KING, kto);
939 st->egValue -= pst<EndGame>(us, KING, kfrom);
940 st->egValue += pst<EndGame>(us, KING, kto);
941 st->mgValue -= pst<MidGame>(us, ROOK, rfrom);
942 st->mgValue += pst<MidGame>(us, ROOK, rto);
943 st->egValue -= pst<EndGame>(us, ROOK, rfrom);
944 st->egValue += pst<EndGame>(us, ROOK, rto);
947 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
948 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
950 // Clear en passant square
951 if (st->epSquare != SQ_NONE)
953 st->key ^= zobEp[st->epSquare];
954 st->epSquare = SQ_NONE;
957 // Update castling rights
958 st->key ^= zobCastle[st->castleRights];
959 st->castleRights &= castleRightsMask[kfrom];
960 st->key ^= zobCastle[st->castleRights];
962 // Reset rule 50 counter
965 // Update checkers BB
966 st->checkersBB = attacks_to(king_square(them), us);
970 /// Position::do_promotion_move() is a private method used to make a promotion
971 /// move. It is called from the main Position::do_move function.
973 void Position::do_promotion_move(Move m) {
980 assert(move_is_ok(m));
981 assert(move_promotion(m));
984 them = opposite_color(us);
988 assert(relative_rank(us, to) == RANK_8);
989 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
990 assert(color_of_piece_on(to) == them || square_is_empty(to));
992 st->capture = type_of_piece_on(to);
995 do_capture_move(st->capture, them, to);
998 clear_bit(&(byColorBB[us]), from);
999 clear_bit(&(byTypeBB[PAWN]), from);
1000 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1001 board[from] = EMPTY;
1003 // Insert promoted piece
1004 promotion = move_promotion(m);
1005 assert(promotion >= KNIGHT && promotion <= QUEEN);
1006 set_bit(&(byColorBB[us]), to);
1007 set_bit(&(byTypeBB[promotion]), to);
1008 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1009 board[to] = piece_of_color_and_type(us, promotion);
1012 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1014 // Update pawn hash key
1015 st->pawnKey ^= zobrist[us][PAWN][from];
1017 // Update material key
1018 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1019 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1021 // Update piece counts
1022 pieceCount[us][PAWN]--;
1023 pieceCount[us][promotion]++;
1025 // Update piece lists
1026 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1027 index[pieceList[us][PAWN][index[from]]] = index[from];
1028 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1029 index[to] = pieceCount[us][promotion] - 1;
1031 // Update incremental scores
1032 st->mgValue -= pst<MidGame>(us, PAWN, from);
1033 st->mgValue += pst<MidGame>(us, promotion, to);
1034 st->egValue -= pst<EndGame>(us, PAWN, from);
1035 st->egValue += pst<EndGame>(us, promotion, to);
1038 st->npMaterial[us] += piece_value_midgame(promotion);
1040 // Clear the en passant square
1041 if (st->epSquare != SQ_NONE)
1043 st->key ^= zobEp[st->epSquare];
1044 st->epSquare = SQ_NONE;
1047 // Update castle rights
1048 st->key ^= zobCastle[st->castleRights];
1049 st->castleRights &= castleRightsMask[to];
1050 st->key ^= zobCastle[st->castleRights];
1052 // Reset rule 50 counter
1055 // Update checkers BB
1056 st->checkersBB = attacks_to(king_square(them), us);
1060 /// Position::do_ep_move() is a private method used to make an en passant
1061 /// capture. It is called from the main Position::do_move function.
1063 void Position::do_ep_move(Move m) {
1066 Square from, to, capsq;
1069 assert(move_is_ok(m));
1070 assert(move_is_ep(m));
1072 us = side_to_move();
1073 them = opposite_color(us);
1074 from = move_from(m);
1076 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1078 assert(to == st->epSquare);
1079 assert(relative_rank(us, to) == RANK_6);
1080 assert(piece_on(to) == EMPTY);
1081 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1082 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1084 // Remove captured pawn
1085 clear_bit(&(byColorBB[them]), capsq);
1086 clear_bit(&(byTypeBB[PAWN]), capsq);
1087 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1088 board[capsq] = EMPTY;
1090 // Move capturing pawn
1091 Bitboard move_bb = make_move_bb(from, to);
1092 do_move_bb(&(byColorBB[us]), move_bb);
1093 do_move_bb(&(byTypeBB[PAWN]), move_bb);
1094 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1095 board[to] = board[from];
1096 board[from] = EMPTY;
1098 // Update material hash key
1099 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1101 // Update piece count
1102 pieceCount[them][PAWN]--;
1104 // Update piece list
1105 pieceList[us][PAWN][index[from]] = to;
1106 index[to] = index[from];
1107 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1108 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1111 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1112 st->key ^= zobrist[them][PAWN][capsq];
1113 st->key ^= zobEp[st->epSquare];
1115 // Update pawn hash key
1116 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1117 st->pawnKey ^= zobrist[them][PAWN][capsq];
1119 // Update incremental scores
1120 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1121 st->mgValue -= pst<MidGame>(us, PAWN, from);
1122 st->mgValue += pst<MidGame>(us, PAWN, to);
1123 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1124 st->egValue -= pst<EndGame>(us, PAWN, from);
1125 st->egValue += pst<EndGame>(us, PAWN, to);
1127 // Reset en passant square
1128 st->epSquare = SQ_NONE;
1130 // Reset rule 50 counter
1133 // Update checkers BB
1134 st->checkersBB = attacks_to(king_square(them), us);
1138 /// Position::undo_move() unmakes a move. When it returns, the position should
1139 /// be restored to exactly the same state as before the move was made.
1141 void Position::undo_move(Move m) {
1144 assert(move_is_ok(m));
1147 sideToMove = opposite_color(sideToMove);
1149 if (move_is_castle(m))
1150 undo_castle_move(m);
1151 else if (move_promotion(m))
1152 undo_promotion_move(m);
1153 else if (move_is_ep(m))
1161 us = side_to_move();
1162 them = opposite_color(us);
1163 from = move_from(m);
1166 assert(piece_on(from) == EMPTY);
1167 assert(color_of_piece_on(to) == us);
1169 // Put the piece back at the source square
1170 Bitboard move_bb = make_move_bb(to, from);
1171 piece = type_of_piece_on(to);
1172 do_move_bb(&(byColorBB[us]), move_bb);
1173 do_move_bb(&(byTypeBB[piece]), move_bb);
1174 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1175 board[from] = piece_of_color_and_type(us, piece);
1177 // If the moving piece was a king, update the king square
1179 kingSquare[us] = from;
1181 // Update piece list
1182 pieceList[us][piece][index[to]] = from;
1183 index[from] = index[to];
1187 assert(st->capture != KING);
1189 // Restore the captured piece
1190 set_bit(&(byColorBB[them]), to);
1191 set_bit(&(byTypeBB[st->capture]), to);
1192 set_bit(&(byTypeBB[0]), to);
1193 board[to] = piece_of_color_and_type(them, st->capture);
1195 // Update piece list
1196 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1197 index[to] = pieceCount[them][st->capture];
1199 // Update piece count
1200 pieceCount[them][st->capture]++;
1205 // Finally point our state pointer back to the previous state
1212 /// Position::undo_castle_move() is a private method used to unmake a castling
1213 /// move. It is called from the main Position::undo_move function. Note that
1214 /// castling moves are encoded as "king captures friendly rook" moves, for
1215 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1217 void Position::undo_castle_move(Move m) {
1219 assert(move_is_ok(m));
1220 assert(move_is_castle(m));
1222 // When we have arrived here, some work has already been done by
1223 // Position::undo_move. In particular, the side to move has been switched,
1224 // so the code below is correct.
1225 Color us = side_to_move();
1227 // Find source squares for king and rook
1228 Square kfrom = move_from(m);
1229 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1232 // Find destination squares for king and rook
1233 if (rfrom > kfrom) // O-O
1235 kto = relative_square(us, SQ_G1);
1236 rto = relative_square(us, SQ_F1);
1238 kto = relative_square(us, SQ_C1);
1239 rto = relative_square(us, SQ_D1);
1242 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1243 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1245 // Remove pieces from destination squares
1246 clear_bit(&(byColorBB[us]), kto);
1247 clear_bit(&(byTypeBB[KING]), kto);
1248 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1249 clear_bit(&(byColorBB[us]), rto);
1250 clear_bit(&(byTypeBB[ROOK]), rto);
1251 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1253 // Put pieces on source squares
1254 set_bit(&(byColorBB[us]), kfrom);
1255 set_bit(&(byTypeBB[KING]), kfrom);
1256 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1257 set_bit(&(byColorBB[us]), rfrom);
1258 set_bit(&(byTypeBB[ROOK]), rfrom);
1259 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1262 board[rto] = board[kto] = EMPTY;
1263 board[rfrom] = piece_of_color_and_type(us, ROOK);
1264 board[kfrom] = piece_of_color_and_type(us, KING);
1266 // Update king square
1267 kingSquare[us] = kfrom;
1269 // Update piece lists
1270 pieceList[us][KING][index[kto]] = kfrom;
1271 pieceList[us][ROOK][index[rto]] = rfrom;
1272 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1273 index[kfrom] = index[kto];
1278 /// Position::undo_promotion_move() is a private method used to unmake a
1279 /// promotion move. It is called from the main Position::do_move
1282 void Position::undo_promotion_move(Move m) {
1286 PieceType promotion;
1288 assert(move_is_ok(m));
1289 assert(move_promotion(m));
1291 // When we have arrived here, some work has already been done by
1292 // Position::undo_move. In particular, the side to move has been switched,
1293 // so the code below is correct.
1294 us = side_to_move();
1295 them = opposite_color(us);
1296 from = move_from(m);
1299 assert(relative_rank(us, to) == RANK_8);
1300 assert(piece_on(from) == EMPTY);
1302 // Remove promoted piece
1303 promotion = move_promotion(m);
1304 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1305 assert(promotion >= KNIGHT && promotion <= QUEEN);
1306 clear_bit(&(byColorBB[us]), to);
1307 clear_bit(&(byTypeBB[promotion]), to);
1308 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1310 // Insert pawn at source square
1311 set_bit(&(byColorBB[us]), from);
1312 set_bit(&(byTypeBB[PAWN]), from);
1313 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1314 board[from] = piece_of_color_and_type(us, PAWN);
1316 // Update piece list
1317 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1318 index[from] = pieceCount[us][PAWN];
1319 pieceList[us][promotion][index[to]] =
1320 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1321 index[pieceList[us][promotion][index[to]]] = index[to];
1323 // Update piece counts
1324 pieceCount[us][promotion]--;
1325 pieceCount[us][PAWN]++;
1329 assert(st->capture != KING);
1331 // Insert captured piece:
1332 set_bit(&(byColorBB[them]), to);
1333 set_bit(&(byTypeBB[st->capture]), to);
1334 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1335 board[to] = piece_of_color_and_type(them, st->capture);
1337 // Update piece list
1338 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1339 index[to] = pieceCount[them][st->capture];
1341 // Update piece count
1342 pieceCount[them][st->capture]++;
1348 /// Position::undo_ep_move() is a private method used to unmake an en passant
1349 /// capture. It is called from the main Position::undo_move function.
1351 void Position::undo_ep_move(Move m) {
1353 assert(move_is_ok(m));
1354 assert(move_is_ep(m));
1356 // When we have arrived here, some work has already been done by
1357 // Position::undo_move. In particular, the side to move has been switched,
1358 // so the code below is correct.
1359 Color us = side_to_move();
1360 Color them = opposite_color(us);
1361 Square from = move_from(m);
1362 Square to = move_to(m);
1363 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1365 assert(to == st->previous->epSquare);
1366 assert(relative_rank(us, to) == RANK_6);
1367 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1368 assert(piece_on(from) == EMPTY);
1369 assert(piece_on(capsq) == EMPTY);
1371 // Restore captured pawn
1372 set_bit(&(byColorBB[them]), capsq);
1373 set_bit(&(byTypeBB[PAWN]), capsq);
1374 set_bit(&(byTypeBB[0]), capsq);
1375 board[capsq] = piece_of_color_and_type(them, PAWN);
1377 // Move capturing pawn back to source square
1378 Bitboard move_bb = make_move_bb(to, from);
1379 do_move_bb(&(byColorBB[us]), move_bb);
1380 do_move_bb(&(byTypeBB[PAWN]), move_bb);
1381 do_move_bb(&(byTypeBB[0]), move_bb);
1383 board[from] = piece_of_color_and_type(us, PAWN);
1385 // Update piece list
1386 pieceList[us][PAWN][index[to]] = from;
1387 index[from] = index[to];
1388 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1389 index[capsq] = pieceCount[them][PAWN];
1391 // Update piece count
1392 pieceCount[them][PAWN]++;
1396 /// Position::do_null_move makes() a "null move": It switches the side to move
1397 /// and updates the hash key without executing any move on the board.
1399 void Position::do_null_move(StateInfo& backupSt) {
1402 assert(!is_check());
1404 // Back up the information necessary to undo the null move to the supplied
1405 // StateInfo object.
1406 // Note that differently from normal case here backupSt is actually used as
1407 // a backup storage not as a new state to be used.
1408 backupSt.epSquare = st->epSquare;
1409 backupSt.key = st->key;
1410 backupSt.mgValue = st->mgValue;
1411 backupSt.egValue = st->egValue;
1412 backupSt.previous = st->previous;
1413 st->previous = &backupSt;
1415 // Save the current key to the history[] array, in order to be able to
1416 // detect repetition draws.
1417 history[gamePly] = st->key;
1419 // Update the necessary information
1420 sideToMove = opposite_color(sideToMove);
1421 if (st->epSquare != SQ_NONE)
1422 st->key ^= zobEp[st->epSquare];
1424 st->epSquare = SQ_NONE;
1427 st->key ^= zobSideToMove;
1429 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1430 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1436 /// Position::undo_null_move() unmakes a "null move".
1438 void Position::undo_null_move() {
1441 assert(!is_check());
1443 // Restore information from the our backup StateInfo object
1444 st->epSquare = st->previous->epSquare;
1445 st->key = st->previous->key;
1446 st->mgValue = st->previous->mgValue;
1447 st->egValue = st->previous->egValue;
1448 st->previous = st->previous->previous;
1450 // Update the necessary information
1451 sideToMove = opposite_color(sideToMove);
1459 /// Position::see() is a static exchange evaluator: It tries to estimate the
1460 /// material gain or loss resulting from a move. There are three versions of
1461 /// this function: One which takes a destination square as input, one takes a
1462 /// move, and one which takes a 'from' and a 'to' square. The function does
1463 /// not yet understand promotions captures.
1465 int Position::see(Square to) const {
1467 assert(square_is_ok(to));
1468 return see(SQ_NONE, to);
1471 int Position::see(Move m) const {
1473 assert(move_is_ok(m));
1474 return see(move_from(m), move_to(m));
1477 int Position::see(Square from, Square to) const {
1480 static const int seeValues[18] = {
1481 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1482 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1483 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1484 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1488 Bitboard attackers, stmAttackers, occ, b;
1490 assert(square_is_ok(from) || from == SQ_NONE);
1491 assert(square_is_ok(to));
1493 // Initialize colors
1494 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1495 Color them = opposite_color(us);
1497 // Initialize pieces
1498 Piece piece = piece_on(from);
1499 Piece capture = piece_on(to);
1501 // Find all attackers to the destination square, with the moving piece
1502 // removed, but possibly an X-ray attacker added behind it.
1503 occ = occupied_squares();
1505 // Handle en passant moves
1506 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1508 assert(capture == EMPTY);
1510 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1511 capture = piece_on(capQq);
1512 assert(type_of_piece_on(capQq) == PAWN);
1514 // Remove the captured pawn
1515 clear_bit(&occ, capQq);
1520 clear_bit(&occ, from);
1521 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1522 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1523 | (piece_attacks<KNIGHT>(to) & knights())
1524 | (piece_attacks<KING>(to) & kings())
1525 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1526 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1528 if (from != SQ_NONE)
1531 // If we don't have any attacker we are finished
1532 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1535 // Locate the least valuable attacker to the destination square
1536 // and use it to initialize from square.
1538 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1541 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1542 piece = piece_on(from);
1545 // If the opponent has no attackers we are finished
1546 stmAttackers = attackers & pieces_of_color(them);
1548 return seeValues[capture];
1550 attackers &= occ; // Remove the moving piece
1552 // The destination square is defended, which makes things rather more
1553 // difficult to compute. We proceed by building up a "swap list" containing
1554 // the material gain or loss at each stop in a sequence of captures to the
1555 // destination square, where the sides alternately capture, and always
1556 // capture with the least valuable piece. After each capture, we look for
1557 // new X-ray attacks from behind the capturing piece.
1558 int lastCapturingPieceValue = seeValues[piece];
1559 int swapList[32], n = 1;
1563 swapList[0] = seeValues[capture];
1566 // Locate the least valuable attacker for the side to move. The loop
1567 // below looks like it is potentially infinite, but it isn't. We know
1568 // that the side to move still has at least one attacker left.
1569 for (pt = PAWN; !(stmAttackers & pieces_of_type(pt)); pt++)
1572 // Remove the attacker we just found from the 'attackers' bitboard,
1573 // and scan for new X-ray attacks behind the attacker.
1574 b = stmAttackers & pieces_of_type(pt);
1575 occ ^= (b & (~b + 1));
1576 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1577 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1581 // Add the new entry to the swap list
1583 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1586 // Remember the value of the capturing piece, and change the side to move
1587 // before beginning the next iteration
1588 lastCapturingPieceValue = seeValues[pt];
1589 c = opposite_color(c);
1590 stmAttackers = attackers & pieces_of_color(c);
1592 // Stop after a king capture
1593 if (pt == KING && stmAttackers)
1596 swapList[n++] = 100;
1599 } while (stmAttackers);
1601 // Having built the swap list, we negamax through it to find the best
1602 // achievable score from the point of view of the side to move
1604 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1610 /// Position::setStartState() copies the content of the argument
1611 /// inside startState and makes st point to it. This is needed
1612 /// when the st pointee could become stale, as example because
1613 /// the caller is about to going out of scope.
1615 void Position::setStartState(const StateInfo& s) {
1622 /// Position::clear() erases the position object to a pristine state, with an
1623 /// empty board, white to move, and no castling rights.
1625 void Position::clear() {
1628 memset(st, 0, sizeof(StateInfo));
1629 st->epSquare = SQ_NONE;
1631 memset(index, 0, sizeof(int) * 64);
1632 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1634 for (int i = 0; i < 64; i++)
1637 for (int i = 0; i < 7; i++)
1639 byTypeBB[i] = EmptyBoardBB;
1640 pieceCount[0][i] = pieceCount[1][i] = 0;
1641 for (int j = 0; j < 8; j++)
1642 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1647 initialKFile = FILE_E;
1648 initialKRFile = FILE_H;
1649 initialQRFile = FILE_A;
1653 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1654 /// UCI interface code, whenever a non-reversible move is made in a
1655 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1656 /// for the program to handle games of arbitrary length, as long as the GUI
1657 /// handles draws by the 50 move rule correctly.
1659 void Position::reset_game_ply() {
1665 /// Position::put_piece() puts a piece on the given square of the board,
1666 /// updating the board array, bitboards, and piece counts.
1668 void Position::put_piece(Piece p, Square s) {
1670 Color c = color_of_piece(p);
1671 PieceType pt = type_of_piece(p);
1674 index[s] = pieceCount[c][pt];
1675 pieceList[c][pt][index[s]] = s;
1677 set_bit(&(byTypeBB[pt]), s);
1678 set_bit(&(byColorBB[c]), s);
1679 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1681 pieceCount[c][pt]++;
1688 /// Position::allow_oo() gives the given side the right to castle kingside.
1689 /// Used when setting castling rights during parsing of FEN strings.
1691 void Position::allow_oo(Color c) {
1693 st->castleRights |= (1 + int(c));
1697 /// Position::allow_ooo() gives the given side the right to castle queenside.
1698 /// Used when setting castling rights during parsing of FEN strings.
1700 void Position::allow_ooo(Color c) {
1702 st->castleRights |= (4 + 4*int(c));
1706 /// Position::compute_key() computes the hash key of the position. The hash
1707 /// key is usually updated incrementally as moves are made and unmade, the
1708 /// compute_key() function is only used when a new position is set up, and
1709 /// to verify the correctness of the hash key when running in debug mode.
1711 Key Position::compute_key() const {
1713 Key result = Key(0ULL);
1715 for (Square s = SQ_A1; s <= SQ_H8; s++)
1716 if (square_is_occupied(s))
1717 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1719 if (ep_square() != SQ_NONE)
1720 result ^= zobEp[ep_square()];
1722 result ^= zobCastle[st->castleRights];
1723 if (side_to_move() == BLACK)
1724 result ^= zobSideToMove;
1730 /// Position::compute_pawn_key() computes the hash key of the position. The
1731 /// hash key is usually updated incrementally as moves are made and unmade,
1732 /// the compute_pawn_key() function is only used when a new position is set
1733 /// up, and to verify the correctness of the pawn hash key when running in
1736 Key Position::compute_pawn_key() const {
1738 Key result = Key(0ULL);
1742 for (Color c = WHITE; c <= BLACK; c++)
1747 s = pop_1st_bit(&b);
1748 result ^= zobrist[c][PAWN][s];
1755 /// Position::compute_material_key() computes the hash key of the position.
1756 /// The hash key is usually updated incrementally as moves are made and unmade,
1757 /// the compute_material_key() function is only used when a new position is set
1758 /// up, and to verify the correctness of the material hash key when running in
1761 Key Position::compute_material_key() const {
1763 Key result = Key(0ULL);
1764 for (Color c = WHITE; c <= BLACK; c++)
1765 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1767 int count = piece_count(c, pt);
1768 for (int i = 0; i <= count; i++)
1769 result ^= zobMaterial[c][pt][i];
1775 /// Position::compute_value() compute the incremental scores for the middle
1776 /// game and the endgame. These functions are used to initialize the incremental
1777 /// scores when a new position is set up, and to verify that the scores are correctly
1778 /// updated by do_move and undo_move when the program is running in debug mode.
1779 template<Position::GamePhase Phase>
1780 Value Position::compute_value() const {
1782 Value result = Value(0);
1786 for (Color c = WHITE; c <= BLACK; c++)
1787 for (PieceType pt = PAWN; pt <= KING; pt++)
1789 b = pieces_of_color_and_type(c, pt);
1792 s = pop_1st_bit(&b);
1793 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1794 result += pst<Phase>(c, pt, s);
1798 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1799 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1804 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1805 /// game material score for the given side. Material scores are updated
1806 /// incrementally during the search, this function is only used while
1807 /// initializing a new Position object.
1809 Value Position::compute_non_pawn_material(Color c) const {
1811 Value result = Value(0);
1813 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1815 Bitboard b = pieces_of_color_and_type(c, pt);
1818 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1820 result += piece_value_midgame(pt);
1827 /// Position::is_draw() tests whether the position is drawn by material,
1828 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1829 /// must be done by the search.
1831 bool Position::is_draw() const {
1833 // Draw by material?
1835 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1838 // Draw by the 50 moves rule?
1839 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1842 // Draw by repetition?
1843 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1844 if (history[gamePly - i] == st->key)
1851 /// Position::is_mate() returns true or false depending on whether the
1852 /// side to move is checkmated.
1854 bool Position::is_mate() const {
1856 MoveStack moves[256];
1858 return is_check() && !generate_evasions(*this, moves, pinned_pieces(sideToMove));
1862 /// Position::has_mate_threat() tests whether a given color has a mate in one
1863 /// from the current position.
1865 bool Position::has_mate_threat(Color c) {
1868 Color stm = side_to_move();
1873 // If the input color is not equal to the side to move, do a null move
1877 MoveStack mlist[120];
1879 bool result = false;
1880 Bitboard dc = discovered_check_candidates(sideToMove);
1881 Bitboard pinned = pinned_pieces(sideToMove);
1883 // Generate pseudo-legal non-capture and capture check moves
1884 count = generate_non_capture_checks(*this, mlist, dc);
1885 count += generate_captures(*this, mlist + count);
1887 // Loop through the moves, and see if one of them is mate
1888 for (int i = 0; i < count; i++)
1890 Move move = mlist[i].move;
1892 if (!pl_move_is_legal(move, pinned))
1902 // Undo null move, if necessary
1910 /// Position::init_zobrist() is a static member function which initializes the
1911 /// various arrays used to compute hash keys.
1913 void Position::init_zobrist() {
1915 for (int i = 0; i < 2; i++)
1916 for (int j = 0; j < 8; j++)
1917 for (int k = 0; k < 64; k++)
1918 zobrist[i][j][k] = Key(genrand_int64());
1920 for (int i = 0; i < 64; i++)
1921 zobEp[i] = Key(genrand_int64());
1923 for (int i = 0; i < 16; i++)
1924 zobCastle[i] = genrand_int64();
1926 zobSideToMove = genrand_int64();
1928 for (int i = 0; i < 2; i++)
1929 for (int j = 0; j < 8; j++)
1930 for (int k = 0; k < 16; k++)
1931 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1933 for (int i = 0; i < 16; i++)
1934 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1938 /// Position::init_piece_square_tables() initializes the piece square tables.
1939 /// This is a two-step operation: First, the white halves of the tables are
1940 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1941 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1942 /// Second, the black halves of the tables are initialized by mirroring
1943 /// and changing the sign of the corresponding white scores.
1945 void Position::init_piece_square_tables() {
1947 int r = get_option_value_int("Randomness"), i;
1948 for (Square s = SQ_A1; s <= SQ_H8; s++)
1949 for (Piece p = WP; p <= WK; p++)
1951 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1952 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1953 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1956 for (Square s = SQ_A1; s <= SQ_H8; s++)
1957 for (Piece p = BP; p <= BK; p++)
1959 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1960 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
1965 /// Position::flipped_copy() makes a copy of the input position, but with
1966 /// the white and black sides reversed. This is only useful for debugging,
1967 /// especially for finding evaluation symmetry bugs.
1969 void Position::flipped_copy(const Position &pos) {
1971 assert(pos.is_ok());
1976 for (Square s = SQ_A1; s <= SQ_H8; s++)
1977 if (!pos.square_is_empty(s))
1978 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1981 sideToMove = opposite_color(pos.side_to_move());
1984 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1985 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1986 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1987 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1989 initialKFile = pos.initialKFile;
1990 initialKRFile = pos.initialKRFile;
1991 initialQRFile = pos.initialQRFile;
1993 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1994 castleRightsMask[sq] = ALL_CASTLES;
1996 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1997 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1998 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1999 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2000 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2001 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2003 // En passant square
2004 if (pos.st->epSquare != SQ_NONE)
2005 st->epSquare = flip_square(pos.st->epSquare);
2011 st->key = compute_key();
2012 st->pawnKey = compute_pawn_key();
2013 st->materialKey = compute_material_key();
2015 // Incremental scores
2016 st->mgValue = compute_value<MidGame>();
2017 st->egValue = compute_value<EndGame>();
2020 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2021 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2027 /// Position::is_ok() performs some consitency checks for the position object.
2028 /// This is meant to be helpful when debugging.
2030 bool Position::is_ok(int* failedStep) const {
2032 // What features of the position should be verified?
2033 static const bool debugBitboards = false;
2034 static const bool debugKingCount = false;
2035 static const bool debugKingCapture = false;
2036 static const bool debugCheckerCount = false;
2037 static const bool debugKey = false;
2038 static const bool debugMaterialKey = false;
2039 static const bool debugPawnKey = false;
2040 static const bool debugIncrementalEval = false;
2041 static const bool debugNonPawnMaterial = false;
2042 static const bool debugPieceCounts = false;
2043 static const bool debugPieceList = false;
2045 if (failedStep) *failedStep = 1;
2048 if (!color_is_ok(side_to_move()))
2051 // Are the king squares in the position correct?
2052 if (failedStep) (*failedStep)++;
2053 if (piece_on(king_square(WHITE)) != WK)
2056 if (failedStep) (*failedStep)++;
2057 if (piece_on(king_square(BLACK)) != BK)
2061 if (failedStep) (*failedStep)++;
2062 if (!file_is_ok(initialKRFile))
2065 if (!file_is_ok(initialQRFile))
2068 // Do both sides have exactly one king?
2069 if (failedStep) (*failedStep)++;
2072 int kingCount[2] = {0, 0};
2073 for (Square s = SQ_A1; s <= SQ_H8; s++)
2074 if (type_of_piece_on(s) == KING)
2075 kingCount[color_of_piece_on(s)]++;
2077 if (kingCount[0] != 1 || kingCount[1] != 1)
2081 // Can the side to move capture the opponent's king?
2082 if (failedStep) (*failedStep)++;
2083 if (debugKingCapture)
2085 Color us = side_to_move();
2086 Color them = opposite_color(us);
2087 Square ksq = king_square(them);
2088 if (square_is_attacked(ksq, us))
2092 // Is there more than 2 checkers?
2093 if (failedStep) (*failedStep)++;
2094 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2098 if (failedStep) (*failedStep)++;
2101 // The intersection of the white and black pieces must be empty
2102 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2105 // The union of the white and black pieces must be equal to all
2107 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2110 // Separate piece type bitboards must have empty intersections
2111 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2112 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2113 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2117 // En passant square OK?
2118 if (failedStep) (*failedStep)++;
2119 if (ep_square() != SQ_NONE)
2121 // The en passant square must be on rank 6, from the point of view of the
2123 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2128 if (failedStep) (*failedStep)++;
2129 if (debugKey && st->key != compute_key())
2132 // Pawn hash key OK?
2133 if (failedStep) (*failedStep)++;
2134 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2137 // Material hash key OK?
2138 if (failedStep) (*failedStep)++;
2139 if (debugMaterialKey && st->materialKey != compute_material_key())
2142 // Incremental eval OK?
2143 if (failedStep) (*failedStep)++;
2144 if (debugIncrementalEval)
2146 if (st->mgValue != compute_value<MidGame>())
2149 if (st->egValue != compute_value<EndGame>())
2153 // Non-pawn material OK?
2154 if (failedStep) (*failedStep)++;
2155 if (debugNonPawnMaterial)
2157 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2160 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2165 if (failedStep) (*failedStep)++;
2166 if (debugPieceCounts)
2167 for (Color c = WHITE; c <= BLACK; c++)
2168 for (PieceType pt = PAWN; pt <= KING; pt++)
2169 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2172 if (failedStep) (*failedStep)++;
2175 for(Color c = WHITE; c <= BLACK; c++)
2176 for(PieceType pt = PAWN; pt <= KING; pt++)
2177 for(int i = 0; i < pieceCount[c][pt]; i++)
2179 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2182 if (index[piece_list(c, pt, i)] != i)
2186 if (failedStep) *failedStep = 0;