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));
321 saveState(); // detach and copy state info
325 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
326 /// king) pieces for the given color and for the given pinner type. Or, when
327 /// template parameter FindPinned is false, the pieces of the given color
328 /// candidate for a discovery check against the enemy king.
329 /// Note that checkersBB bitboard must be already updated.
331 template<bool FindPinned>
332 Bitboard Position::hidden_checkers(Color c) const {
334 Bitboard pinners, result = EmptyBoardBB;
336 // Pinned pieces protect our king, dicovery checks attack
338 Square ksq = king_square(FindPinned ? c : opposite_color(c));
340 // Pinners are sliders, not checkers, that give check when
341 // candidate pinned is removed.
342 pinners = (rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq])
343 | (bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq]);
345 if (FindPinned && pinners)
346 pinners &= ~st->checkersBB;
350 Square s = pop_1st_bit(&pinners);
351 Bitboard b = squares_between(s, ksq) & occupied_squares();
355 if ( !(b & (b - 1)) // Only one bit set?
356 && (b & pieces_of_color(c))) // Is an our piece?
363 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
364 /// king) pieces for the given color.
366 Bitboard Position::pinned_pieces(Color c) const {
368 return hidden_checkers<true>(c);
372 /// Position:discovered_check_candidates() returns a bitboard containing all
373 /// pieces for the given side which are candidates for giving a discovered
376 Bitboard Position::discovered_check_candidates(Color c) const {
378 return hidden_checkers<false>(c);
381 /// Position::attacks_to() computes a bitboard containing all pieces which
382 /// attacks a given square.
384 Bitboard Position::attacks_to(Square s) const {
386 return (pawn_attacks(BLACK, s) & pawns(WHITE))
387 | (pawn_attacks(WHITE, s) & pawns(BLACK))
388 | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
389 | (piece_attacks<ROOK>(s) & rooks_and_queens())
390 | (piece_attacks<BISHOP>(s) & bishops_and_queens())
391 | (piece_attacks<KING>(s) & pieces_of_type(KING));
394 /// Position::piece_attacks_square() tests whether the piece on square f
395 /// attacks square t.
397 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
399 assert(square_is_ok(f));
400 assert(square_is_ok(t));
404 case WP: return pawn_attacks_square(WHITE, f, t);
405 case BP: return pawn_attacks_square(BLACK, f, t);
406 case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
407 case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
408 case WR: case BR: return piece_attacks_square<ROOK>(f, t);
409 case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
410 case WK: case BK: return piece_attacks_square<KING>(f, t);
417 /// Position::move_attacks_square() tests whether a move from the current
418 /// position attacks a given square.
420 bool Position::move_attacks_square(Move m, Square s) const {
422 assert(move_is_ok(m));
423 assert(square_is_ok(s));
425 Square f = move_from(m), t = move_to(m);
427 assert(square_is_occupied(f));
429 if (piece_attacks_square(piece_on(f), t, s))
432 // Move the piece and scan for X-ray attacks behind it
433 Bitboard occ = occupied_squares();
434 Color us = color_of_piece_on(f);
437 Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
438 |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
440 // If we have attacks we need to verify that are caused by our move
441 // and are not already existent ones.
442 return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
446 /// Position::find_checkers() computes the checkersBB bitboard, which
447 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
448 /// currently works by calling Position::attacks_to, which is probably
449 /// inefficient. Consider rewriting this function to use the last move
450 /// played, like in non-bitboard versions of Glaurung.
452 void Position::find_checkers() {
454 Color us = side_to_move();
455 st->checkersBB = attacks_to(king_square(us), opposite_color(us));
459 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
461 bool Position::pl_move_is_legal(Move m) const {
463 // If we're in check, all pseudo-legal moves are legal, because our
464 // check evasion generator only generates true legal moves.
465 return is_check() || pl_move_is_legal(m, pinned_pieces(side_to_move()));
468 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
471 assert(move_is_ok(m));
472 assert(pinned == pinned_pieces(side_to_move()));
475 // Castling moves are checked for legality during move generation.
476 if (move_is_castle(m))
479 Color us = side_to_move();
480 Square from = move_from(m);
481 Square ksq = king_square(us);
483 assert(color_of_piece_on(from) == us);
484 assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
486 // En passant captures are a tricky special case. Because they are
487 // rather uncommon, we do it simply by testing whether the king is attacked
488 // after the move is made
491 Color them = opposite_color(us);
492 Square to = move_to(m);
493 Square capsq = make_square(square_file(to), square_rank(from));
494 Bitboard b = occupied_squares();
496 assert(to == ep_square());
497 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
498 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
499 assert(piece_on(to) == EMPTY);
502 clear_bit(&b, capsq);
505 return !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
506 && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
509 // If the moving piece is a king, check whether the destination
510 // square is attacked by the opponent.
512 return !(square_is_attacked(move_to(m), opposite_color(us)));
514 // A non-king move is legal if and only if it is not pinned or it
515 // is moving along the ray towards or away from the king.
517 || !bit_is_set(pinned, from)
518 || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
522 /// Position::move_is_check() tests whether a pseudo-legal move is a check
524 bool Position::move_is_check(Move m) const {
526 Bitboard dc = discovered_check_candidates(side_to_move());
527 return move_is_check(m, dc);
530 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
533 assert(move_is_ok(m));
534 assert(dcCandidates == discovered_check_candidates(side_to_move()));
536 Color us = side_to_move();
537 Color them = opposite_color(us);
538 Square from = move_from(m);
539 Square to = move_to(m);
540 Square ksq = king_square(them);
542 assert(color_of_piece_on(from) == us);
543 assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
545 // Proceed according to the type of the moving piece
546 switch (type_of_piece_on(from))
550 if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
553 if ( dcCandidates // Discovered check?
554 && bit_is_set(dcCandidates, from)
555 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
558 if (move_promotion(m)) // Promotion with check?
560 Bitboard b = occupied_squares();
563 switch (move_promotion(m))
566 return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
568 return bit_is_set(bishop_attacks_bb(to, b), ksq);
570 return bit_is_set(rook_attacks_bb(to, b), ksq);
572 return bit_is_set(queen_attacks_bb(to, b), ksq);
577 // En passant capture with check? We have already handled the case
578 // of direct checks and ordinary discovered check, the only case we
579 // need to handle is the unusual case of a discovered check through the
581 else if (move_is_ep(m))
583 Square capsq = make_square(square_file(to), square_rank(from));
584 Bitboard b = occupied_squares();
586 clear_bit(&b, capsq);
588 return (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
589 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
593 // Test discovered check and normal check according to piece type
595 return (dcCandidates && bit_is_set(dcCandidates, from))
596 || bit_is_set(piece_attacks<KNIGHT>(ksq), to);
599 return (dcCandidates && bit_is_set(dcCandidates, from))
600 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to));
603 return (dcCandidates && bit_is_set(dcCandidates, from))
604 || (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to));
607 // Discovered checks are impossible!
608 assert(!bit_is_set(dcCandidates, from));
609 return ( (direction_is_straight(ksq, to) && bit_is_set(piece_attacks<ROOK>(ksq), to))
610 || (direction_is_diagonal(ksq, to) && bit_is_set(piece_attacks<BISHOP>(ksq), to)));
614 if ( bit_is_set(dcCandidates, from)
615 && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
618 // Castling with check?
619 if (move_is_castle(m))
621 Square kfrom, kto, rfrom, rto;
622 Bitboard b = occupied_squares();
628 kto = relative_square(us, SQ_G1);
629 rto = relative_square(us, SQ_F1);
631 kto = relative_square(us, SQ_C1);
632 rto = relative_square(us, SQ_D1);
634 clear_bit(&b, kfrom);
635 clear_bit(&b, rfrom);
638 return bit_is_set(rook_attacks_bb(rto, b), ksq);
642 default: // NO_PIECE_TYPE
650 /// Position::update_checkers() udpates chekers info given the move. It is called
651 /// in do_move() and is faster then find_checkers().
653 template<PieceType Piece>
654 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
655 Square to, Bitboard dcCandidates) {
657 const bool Bishop = (Piece == QUEEN || Piece == BISHOP);
658 const bool Rook = (Piece == QUEEN || Piece == ROOK);
659 const bool Slider = Bishop || Rook;
662 if ( ( (Bishop && bit_is_set(BishopPseudoAttacks[ksq], to))
663 || (Rook && bit_is_set(RookPseudoAttacks[ksq], to)))
664 && bit_is_set(piece_attacks<Piece>(ksq), to)) // slow, try to early skip
665 set_bit(pCheckersBB, to);
667 else if ( Piece != KING
669 && bit_is_set(piece_attacks<Piece>(ksq), to))
670 set_bit(pCheckersBB, to);
673 if (Piece != QUEEN && bit_is_set(dcCandidates, from))
676 (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
679 (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
684 /// Position::do_move() makes a move, and saves all information necessary
685 /// to a StateInfo object. The move is assumed to be legal.
686 /// Pseudo-legal moves should be filtered out before this function is called.
688 void Position::do_move(Move m, StateInfo& newSt) {
690 do_move(m, newSt, discovered_check_candidates(side_to_move()));
693 void Position::do_move(Move m, StateInfo& newSt, Bitboard dcCandidates) {
696 assert(move_is_ok(m));
698 // Copy some fields of old state to our new StateInfo object except the
699 // ones which are recalculated from scratch anyway, then switch our state
700 // pointer to point to the new, ready to be updated, state.
701 struct ReducedStateInfo {
702 Key key, pawnKey, materialKey;
703 int castleRights, rule50;
705 Value mgValue, egValue;
709 memcpy(&newSt, st, sizeof(ReducedStateInfo));
710 newSt.capture = NO_PIECE_TYPE;
714 // Save the current key to the history[] array, in order to be able to
715 // detect repetition draws.
716 history[gamePly] = st->key;
718 // Increment the 50 moves rule draw counter. Resetting it to zero in the
719 // case of non-reversible moves is taken care of later.
722 if (move_is_castle(m))
724 else if (move_promotion(m))
725 do_promotion_move(m);
726 else if (move_is_ep(m))
730 Color us = side_to_move();
731 Color them = opposite_color(us);
732 Square from = move_from(m);
733 Square to = move_to(m);
735 assert(color_of_piece_on(from) == us);
736 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
738 PieceType piece = type_of_piece_on(from);
740 st->capture = type_of_piece_on(to);
743 do_capture_move(st->capture, them, to);
746 Bitboard move_bb = make_move_bb(from, to);
747 do_move_bb(&(byColorBB[us]), move_bb);
748 do_move_bb(&(byTypeBB[piece]), move_bb);
749 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
751 board[to] = board[from];
755 st->key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
757 // Update incremental scores
758 st->mgValue -= pst<MidGame>(us, piece, from);
759 st->mgValue += pst<MidGame>(us, piece, to);
760 st->egValue -= pst<EndGame>(us, piece, from);
761 st->egValue += pst<EndGame>(us, piece, to);
763 // If the moving piece was a king, update the king square
767 // Reset en passant square
768 if (st->epSquare != SQ_NONE)
770 st->key ^= zobEp[st->epSquare];
771 st->epSquare = SQ_NONE;
774 // If the moving piece was a pawn do some special extra work
777 // Reset rule 50 draw counter
780 // Update pawn hash key
781 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
783 // Set en passant square, only if moved pawn can be captured
784 if (abs(int(to) - int(from)) == 16)
786 if ( (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
787 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
789 st->epSquare = Square((int(from) + int(to)) / 2);
790 st->key ^= zobEp[st->epSquare];
795 // Update piece lists
796 pieceList[us][piece][index[from]] = to;
797 index[to] = index[from];
799 // Update castle rights
800 st->key ^= zobCastle[st->castleRights];
801 st->castleRights &= castleRightsMask[from];
802 st->castleRights &= castleRightsMask[to];
803 st->key ^= zobCastle[st->castleRights];
805 // Update checkers bitboard, piece must be already moved
806 st->checkersBB = EmptyBoardBB;
807 Square ksq = king_square(them);
810 case PAWN: update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
811 case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
812 case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
813 case ROOK: update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
814 case QUEEN: update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
815 case KING: update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
816 default: assert(false); break;
821 st->key ^= zobSideToMove;
822 sideToMove = opposite_color(sideToMove);
825 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
826 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
832 /// Position::do_capture_move() is a private method used to update captured
833 /// piece info. It is called from the main Position::do_move function.
835 void Position::do_capture_move(PieceType capture, Color them, Square to) {
837 assert(capture != KING);
839 // Remove captured piece
840 clear_bit(&(byColorBB[them]), to);
841 clear_bit(&(byTypeBB[capture]), to);
842 clear_bit(&(byTypeBB[0]), to);
845 st->key ^= zobrist[them][capture][to];
847 // If the captured piece was a pawn, update pawn hash key
849 st->pawnKey ^= zobrist[them][PAWN][to];
851 // Update incremental scores
852 st->mgValue -= pst<MidGame>(them, capture, to);
853 st->egValue -= pst<EndGame>(them, capture, to);
857 st->npMaterial[them] -= piece_value_midgame(capture);
859 // Update material hash key
860 st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
862 // Update piece count
863 pieceCount[them][capture]--;
866 pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
867 index[pieceList[them][capture][index[to]]] = index[to];
869 // Reset rule 50 counter
874 /// Position::do_castle_move() is a private method used to make a castling
875 /// move. It is called from the main Position::do_move function. Note that
876 /// castling moves are encoded as "king captures friendly rook" moves, for
877 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
879 void Position::do_castle_move(Move m) {
882 assert(move_is_ok(m));
883 assert(move_is_castle(m));
885 Color us = side_to_move();
886 Color them = opposite_color(us);
888 // Find source squares for king and rook
889 Square kfrom = move_from(m);
890 Square rfrom = move_to(m); // HACK: See comment at beginning of function
893 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
894 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
896 // Find destination squares for king and rook
897 if (rfrom > kfrom) // O-O
899 kto = relative_square(us, SQ_G1);
900 rto = relative_square(us, SQ_F1);
902 kto = relative_square(us, SQ_C1);
903 rto = relative_square(us, SQ_D1);
906 // Remove pieces from source squares
907 clear_bit(&(byColorBB[us]), kfrom);
908 clear_bit(&(byTypeBB[KING]), kfrom);
909 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
910 clear_bit(&(byColorBB[us]), rfrom);
911 clear_bit(&(byTypeBB[ROOK]), rfrom);
912 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
914 // Put pieces on destination squares
915 set_bit(&(byColorBB[us]), kto);
916 set_bit(&(byTypeBB[KING]), kto);
917 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
918 set_bit(&(byColorBB[us]), rto);
919 set_bit(&(byTypeBB[ROOK]), rto);
920 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
922 // Update board array
923 board[kfrom] = board[rfrom] = EMPTY;
924 board[kto] = piece_of_color_and_type(us, KING);
925 board[rto] = piece_of_color_and_type(us, ROOK);
927 // Update king square
928 kingSquare[us] = kto;
930 // Update piece lists
931 pieceList[us][KING][index[kfrom]] = kto;
932 pieceList[us][ROOK][index[rfrom]] = rto;
933 int tmp = index[rfrom];
934 index[kto] = index[kfrom];
937 // Update incremental scores
938 st->mgValue -= pst<MidGame>(us, KING, kfrom);
939 st->mgValue += pst<MidGame>(us, KING, kto);
940 st->egValue -= pst<EndGame>(us, KING, kfrom);
941 st->egValue += pst<EndGame>(us, KING, kto);
942 st->mgValue -= pst<MidGame>(us, ROOK, rfrom);
943 st->mgValue += pst<MidGame>(us, ROOK, rto);
944 st->egValue -= pst<EndGame>(us, ROOK, rfrom);
945 st->egValue += pst<EndGame>(us, ROOK, rto);
948 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
949 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
951 // Clear en passant square
952 if (st->epSquare != SQ_NONE)
954 st->key ^= zobEp[st->epSquare];
955 st->epSquare = SQ_NONE;
958 // Update castling rights
959 st->key ^= zobCastle[st->castleRights];
960 st->castleRights &= castleRightsMask[kfrom];
961 st->key ^= zobCastle[st->castleRights];
963 // Reset rule 50 counter
966 // Update checkers BB
967 st->checkersBB = attacks_to(king_square(them), us);
971 /// Position::do_promotion_move() is a private method used to make a promotion
972 /// move. It is called from the main Position::do_move function.
974 void Position::do_promotion_move(Move m) {
981 assert(move_is_ok(m));
982 assert(move_promotion(m));
985 them = opposite_color(us);
989 assert(relative_rank(us, to) == RANK_8);
990 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
991 assert(color_of_piece_on(to) == them || square_is_empty(to));
993 st->capture = type_of_piece_on(to);
996 do_capture_move(st->capture, them, to);
999 clear_bit(&(byColorBB[us]), from);
1000 clear_bit(&(byTypeBB[PAWN]), from);
1001 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1002 board[from] = EMPTY;
1004 // Insert promoted piece
1005 promotion = move_promotion(m);
1006 assert(promotion >= KNIGHT && promotion <= QUEEN);
1007 set_bit(&(byColorBB[us]), to);
1008 set_bit(&(byTypeBB[promotion]), to);
1009 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1010 board[to] = piece_of_color_and_type(us, promotion);
1013 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1015 // Update pawn hash key
1016 st->pawnKey ^= zobrist[us][PAWN][from];
1018 // Update material key
1019 st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1020 st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1022 // Update piece counts
1023 pieceCount[us][PAWN]--;
1024 pieceCount[us][promotion]++;
1026 // Update piece lists
1027 pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1028 index[pieceList[us][PAWN][index[from]]] = index[from];
1029 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1030 index[to] = pieceCount[us][promotion] - 1;
1032 // Update incremental scores
1033 st->mgValue -= pst<MidGame>(us, PAWN, from);
1034 st->mgValue += pst<MidGame>(us, promotion, to);
1035 st->egValue -= pst<EndGame>(us, PAWN, from);
1036 st->egValue += pst<EndGame>(us, promotion, to);
1039 st->npMaterial[us] += piece_value_midgame(promotion);
1041 // Clear the en passant square
1042 if (st->epSquare != SQ_NONE)
1044 st->key ^= zobEp[st->epSquare];
1045 st->epSquare = SQ_NONE;
1048 // Update castle rights
1049 st->key ^= zobCastle[st->castleRights];
1050 st->castleRights &= castleRightsMask[to];
1051 st->key ^= zobCastle[st->castleRights];
1053 // Reset rule 50 counter
1056 // Update checkers BB
1057 st->checkersBB = attacks_to(king_square(them), us);
1061 /// Position::do_ep_move() is a private method used to make an en passant
1062 /// capture. It is called from the main Position::do_move function.
1064 void Position::do_ep_move(Move m) {
1067 Square from, to, capsq;
1070 assert(move_is_ok(m));
1071 assert(move_is_ep(m));
1073 us = side_to_move();
1074 them = opposite_color(us);
1075 from = move_from(m);
1077 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1079 assert(to == st->epSquare);
1080 assert(relative_rank(us, to) == RANK_6);
1081 assert(piece_on(to) == EMPTY);
1082 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1083 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1085 // Remove captured pawn
1086 clear_bit(&(byColorBB[them]), capsq);
1087 clear_bit(&(byTypeBB[PAWN]), capsq);
1088 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1089 board[capsq] = EMPTY;
1091 // Move capturing pawn
1092 Bitboard move_bb = make_move_bb(from, to);
1093 do_move_bb(&(byColorBB[us]), move_bb);
1094 do_move_bb(&(byTypeBB[PAWN]), move_bb);
1095 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1096 board[to] = board[from];
1097 board[from] = EMPTY;
1099 // Update material hash key
1100 st->materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1102 // Update piece count
1103 pieceCount[them][PAWN]--;
1105 // Update piece list
1106 pieceList[us][PAWN][index[from]] = to;
1107 index[to] = index[from];
1108 pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1109 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1112 st->key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1113 st->key ^= zobrist[them][PAWN][capsq];
1114 st->key ^= zobEp[st->epSquare];
1116 // Update pawn hash key
1117 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1118 st->pawnKey ^= zobrist[them][PAWN][capsq];
1120 // Update incremental scores
1121 st->mgValue -= pst<MidGame>(them, PAWN, capsq);
1122 st->mgValue -= pst<MidGame>(us, PAWN, from);
1123 st->mgValue += pst<MidGame>(us, PAWN, to);
1124 st->egValue -= pst<EndGame>(them, PAWN, capsq);
1125 st->egValue -= pst<EndGame>(us, PAWN, from);
1126 st->egValue += pst<EndGame>(us, PAWN, to);
1128 // Reset en passant square
1129 st->epSquare = SQ_NONE;
1131 // Reset rule 50 counter
1134 // Update checkers BB
1135 st->checkersBB = attacks_to(king_square(them), us);
1139 /// Position::undo_move() unmakes a move. When it returns, the position should
1140 /// be restored to exactly the same state as before the move was made.
1142 void Position::undo_move(Move m) {
1145 assert(move_is_ok(m));
1148 sideToMove = opposite_color(sideToMove);
1150 if (move_is_castle(m))
1151 undo_castle_move(m);
1152 else if (move_promotion(m))
1153 undo_promotion_move(m);
1154 else if (move_is_ep(m))
1162 us = side_to_move();
1163 them = opposite_color(us);
1164 from = move_from(m);
1167 assert(piece_on(from) == EMPTY);
1168 assert(color_of_piece_on(to) == us);
1170 // Put the piece back at the source square
1171 Bitboard move_bb = make_move_bb(to, from);
1172 piece = type_of_piece_on(to);
1173 do_move_bb(&(byColorBB[us]), move_bb);
1174 do_move_bb(&(byTypeBB[piece]), move_bb);
1175 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1176 board[from] = piece_of_color_and_type(us, piece);
1178 // If the moving piece was a king, update the king square
1180 kingSquare[us] = from;
1182 // Update piece list
1183 pieceList[us][piece][index[to]] = from;
1184 index[from] = index[to];
1188 assert(st->capture != KING);
1190 // Restore the captured piece
1191 set_bit(&(byColorBB[them]), to);
1192 set_bit(&(byTypeBB[st->capture]), to);
1193 set_bit(&(byTypeBB[0]), to);
1194 board[to] = piece_of_color_and_type(them, st->capture);
1196 // Update piece list
1197 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1198 index[to] = pieceCount[them][st->capture];
1200 // Update piece count
1201 pieceCount[them][st->capture]++;
1206 // Finally point our state pointer back to the previous state
1213 /// Position::undo_castle_move() is a private method used to unmake a castling
1214 /// move. It is called from the main Position::undo_move function. Note that
1215 /// castling moves are encoded as "king captures friendly rook" moves, for
1216 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1218 void Position::undo_castle_move(Move m) {
1220 assert(move_is_ok(m));
1221 assert(move_is_castle(m));
1223 // When we have arrived here, some work has already been done by
1224 // Position::undo_move. In particular, the side to move has been switched,
1225 // so the code below is correct.
1226 Color us = side_to_move();
1228 // Find source squares for king and rook
1229 Square kfrom = move_from(m);
1230 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1233 // Find destination squares for king and rook
1234 if (rfrom > kfrom) // O-O
1236 kto = relative_square(us, SQ_G1);
1237 rto = relative_square(us, SQ_F1);
1239 kto = relative_square(us, SQ_C1);
1240 rto = relative_square(us, SQ_D1);
1243 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1244 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1246 // Remove pieces from destination squares
1247 clear_bit(&(byColorBB[us]), kto);
1248 clear_bit(&(byTypeBB[KING]), kto);
1249 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1250 clear_bit(&(byColorBB[us]), rto);
1251 clear_bit(&(byTypeBB[ROOK]), rto);
1252 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1254 // Put pieces on source squares
1255 set_bit(&(byColorBB[us]), kfrom);
1256 set_bit(&(byTypeBB[KING]), kfrom);
1257 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1258 set_bit(&(byColorBB[us]), rfrom);
1259 set_bit(&(byTypeBB[ROOK]), rfrom);
1260 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1263 board[rto] = board[kto] = EMPTY;
1264 board[rfrom] = piece_of_color_and_type(us, ROOK);
1265 board[kfrom] = piece_of_color_and_type(us, KING);
1267 // Update king square
1268 kingSquare[us] = kfrom;
1270 // Update piece lists
1271 pieceList[us][KING][index[kto]] = kfrom;
1272 pieceList[us][ROOK][index[rto]] = rfrom;
1273 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1274 index[kfrom] = index[kto];
1279 /// Position::undo_promotion_move() is a private method used to unmake a
1280 /// promotion move. It is called from the main Position::do_move
1283 void Position::undo_promotion_move(Move m) {
1287 PieceType promotion;
1289 assert(move_is_ok(m));
1290 assert(move_promotion(m));
1292 // When we have arrived here, some work has already been done by
1293 // Position::undo_move. In particular, the side to move has been switched,
1294 // so the code below is correct.
1295 us = side_to_move();
1296 them = opposite_color(us);
1297 from = move_from(m);
1300 assert(relative_rank(us, to) == RANK_8);
1301 assert(piece_on(from) == EMPTY);
1303 // Remove promoted piece
1304 promotion = move_promotion(m);
1305 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1306 assert(promotion >= KNIGHT && promotion <= QUEEN);
1307 clear_bit(&(byColorBB[us]), to);
1308 clear_bit(&(byTypeBB[promotion]), to);
1309 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1311 // Insert pawn at source square
1312 set_bit(&(byColorBB[us]), from);
1313 set_bit(&(byTypeBB[PAWN]), from);
1314 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1315 board[from] = piece_of_color_and_type(us, PAWN);
1317 // Update piece list
1318 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1319 index[from] = pieceCount[us][PAWN];
1320 pieceList[us][promotion][index[to]] =
1321 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1322 index[pieceList[us][promotion][index[to]]] = index[to];
1324 // Update piece counts
1325 pieceCount[us][promotion]--;
1326 pieceCount[us][PAWN]++;
1330 assert(st->capture != KING);
1332 // Insert captured piece:
1333 set_bit(&(byColorBB[them]), to);
1334 set_bit(&(byTypeBB[st->capture]), to);
1335 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1336 board[to] = piece_of_color_and_type(them, st->capture);
1338 // Update piece list
1339 pieceList[them][st->capture][pieceCount[them][st->capture]] = to;
1340 index[to] = pieceCount[them][st->capture];
1342 // Update piece count
1343 pieceCount[them][st->capture]++;
1349 /// Position::undo_ep_move() is a private method used to unmake an en passant
1350 /// capture. It is called from the main Position::undo_move function.
1352 void Position::undo_ep_move(Move m) {
1354 assert(move_is_ok(m));
1355 assert(move_is_ep(m));
1357 // When we have arrived here, some work has already been done by
1358 // Position::undo_move. In particular, the side to move has been switched,
1359 // so the code below is correct.
1360 Color us = side_to_move();
1361 Color them = opposite_color(us);
1362 Square from = move_from(m);
1363 Square to = move_to(m);
1364 Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1366 assert(to == st->previous->epSquare);
1367 assert(relative_rank(us, to) == RANK_6);
1368 assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1369 assert(piece_on(from) == EMPTY);
1370 assert(piece_on(capsq) == EMPTY);
1372 // Restore captured pawn
1373 set_bit(&(byColorBB[them]), capsq);
1374 set_bit(&(byTypeBB[PAWN]), capsq);
1375 set_bit(&(byTypeBB[0]), capsq);
1376 board[capsq] = piece_of_color_and_type(them, PAWN);
1378 // Move capturing pawn back to source square
1379 Bitboard move_bb = make_move_bb(to, from);
1380 do_move_bb(&(byColorBB[us]), move_bb);
1381 do_move_bb(&(byTypeBB[PAWN]), move_bb);
1382 do_move_bb(&(byTypeBB[0]), move_bb);
1384 board[from] = piece_of_color_and_type(us, PAWN);
1386 // Update piece list
1387 pieceList[us][PAWN][index[to]] = from;
1388 index[from] = index[to];
1389 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1390 index[capsq] = pieceCount[them][PAWN];
1392 // Update piece count
1393 pieceCount[them][PAWN]++;
1397 /// Position::do_null_move makes() a "null move": It switches the side to move
1398 /// and updates the hash key without executing any move on the board.
1400 void Position::do_null_move(StateInfo& backupSt) {
1403 assert(!is_check());
1405 // Back up the information necessary to undo the null move to the supplied
1406 // StateInfo object.
1407 // Note that differently from normal case here backupSt is actually used as
1408 // a backup storage not as a new state to be used.
1409 backupSt.epSquare = st->epSquare;
1410 backupSt.key = st->key;
1411 backupSt.mgValue = st->mgValue;
1412 backupSt.egValue = st->egValue;
1413 backupSt.previous = st->previous;
1414 st->previous = &backupSt;
1416 // Save the current key to the history[] array, in order to be able to
1417 // detect repetition draws.
1418 history[gamePly] = st->key;
1420 // Update the necessary information
1421 sideToMove = opposite_color(sideToMove);
1422 if (st->epSquare != SQ_NONE)
1423 st->key ^= zobEp[st->epSquare];
1425 st->epSquare = SQ_NONE;
1428 st->key ^= zobSideToMove;
1430 st->mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1431 st->egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1437 /// Position::undo_null_move() unmakes a "null move".
1439 void Position::undo_null_move() {
1442 assert(!is_check());
1444 // Restore information from the our backup StateInfo object
1445 st->epSquare = st->previous->epSquare;
1446 st->key = st->previous->key;
1447 st->mgValue = st->previous->mgValue;
1448 st->egValue = st->previous->egValue;
1449 st->previous = st->previous->previous;
1451 // Update the necessary information
1452 sideToMove = opposite_color(sideToMove);
1460 /// Position::see() is a static exchange evaluator: It tries to estimate the
1461 /// material gain or loss resulting from a move. There are three versions of
1462 /// this function: One which takes a destination square as input, one takes a
1463 /// move, and one which takes a 'from' and a 'to' square. The function does
1464 /// not yet understand promotions captures.
1466 int Position::see(Square to) const {
1468 assert(square_is_ok(to));
1469 return see(SQ_NONE, to);
1472 int Position::see(Move m) const {
1474 assert(move_is_ok(m));
1475 return see(move_from(m), move_to(m));
1478 int Position::see(Square from, Square to) const {
1481 static const int seeValues[18] = {
1482 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1483 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1484 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1485 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1489 Bitboard attackers, stmAttackers, occ, b;
1491 assert(square_is_ok(from) || from == SQ_NONE);
1492 assert(square_is_ok(to));
1494 // Initialize colors
1495 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1496 Color them = opposite_color(us);
1498 // Initialize pieces
1499 Piece piece = piece_on(from);
1500 Piece capture = piece_on(to);
1502 // Find all attackers to the destination square, with the moving piece
1503 // removed, but possibly an X-ray attacker added behind it.
1504 occ = occupied_squares();
1506 // Handle en passant moves
1507 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1509 assert(capture == EMPTY);
1511 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1512 capture = piece_on(capQq);
1513 assert(type_of_piece_on(capQq) == PAWN);
1515 // Remove the captured pawn
1516 clear_bit(&occ, capQq);
1521 clear_bit(&occ, from);
1522 attackers = (rook_attacks_bb(to, occ) & rooks_and_queens())
1523 | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1524 | (piece_attacks<KNIGHT>(to) & knights())
1525 | (piece_attacks<KING>(to) & kings())
1526 | (pawn_attacks(WHITE, to) & pawns(BLACK))
1527 | (pawn_attacks(BLACK, to) & pawns(WHITE));
1529 if (from != SQ_NONE)
1532 // If we don't have any attacker we are finished
1533 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1536 // Locate the least valuable attacker to the destination square
1537 // and use it to initialize from square.
1539 for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1542 from = first_1(attackers & pieces_of_color_and_type(us, pt));
1543 piece = piece_on(from);
1546 // If the opponent has no attackers we are finished
1547 stmAttackers = attackers & pieces_of_color(them);
1549 return seeValues[capture];
1551 attackers &= occ; // Remove the moving piece
1553 // The destination square is defended, which makes things rather more
1554 // difficult to compute. We proceed by building up a "swap list" containing
1555 // the material gain or loss at each stop in a sequence of captures to the
1556 // destination square, where the sides alternately capture, and always
1557 // capture with the least valuable piece. After each capture, we look for
1558 // new X-ray attacks from behind the capturing piece.
1559 int lastCapturingPieceValue = seeValues[piece];
1560 int swapList[32], n = 1;
1564 swapList[0] = seeValues[capture];
1567 // Locate the least valuable attacker for the side to move. The loop
1568 // below looks like it is potentially infinite, but it isn't. We know
1569 // that the side to move still has at least one attacker left.
1570 for (pt = PAWN; !(stmAttackers & pieces_of_type(pt)); pt++)
1573 // Remove the attacker we just found from the 'attackers' bitboard,
1574 // and scan for new X-ray attacks behind the attacker.
1575 b = stmAttackers & pieces_of_type(pt);
1576 occ ^= (b & (~b + 1));
1577 attackers |= (rook_attacks_bb(to, occ) & rooks_and_queens())
1578 | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1582 // Add the new entry to the swap list
1584 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1587 // Remember the value of the capturing piece, and change the side to move
1588 // before beginning the next iteration
1589 lastCapturingPieceValue = seeValues[pt];
1590 c = opposite_color(c);
1591 stmAttackers = attackers & pieces_of_color(c);
1593 // Stop after a king capture
1594 if (pt == KING && stmAttackers)
1597 swapList[n++] = 100;
1600 } while (stmAttackers);
1602 // Having built the swap list, we negamax through it to find the best
1603 // achievable score from the point of view of the side to move
1605 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1611 /// Position::saveState() copies the content of the current state
1612 /// inside startState and makes st point to it. This is needed
1613 /// when the st pointee could become stale, as example because
1614 /// the caller is about to going out of scope.
1616 void Position::saveState() {
1620 st->previous = NULL; // as a safe guard
1624 /// Position::clear() erases the position object to a pristine state, with an
1625 /// empty board, white to move, and no castling rights.
1627 void Position::clear() {
1630 memset(st, 0, sizeof(StateInfo));
1631 st->epSquare = SQ_NONE;
1633 memset(index, 0, sizeof(int) * 64);
1634 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1636 for (int i = 0; i < 64; i++)
1639 for (int i = 0; i < 7; i++)
1641 byTypeBB[i] = EmptyBoardBB;
1642 pieceCount[0][i] = pieceCount[1][i] = 0;
1643 for (int j = 0; j < 8; j++)
1644 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1649 initialKFile = FILE_E;
1650 initialKRFile = FILE_H;
1651 initialQRFile = FILE_A;
1655 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1656 /// UCI interface code, whenever a non-reversible move is made in a
1657 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1658 /// for the program to handle games of arbitrary length, as long as the GUI
1659 /// handles draws by the 50 move rule correctly.
1661 void Position::reset_game_ply() {
1667 /// Position::put_piece() puts a piece on the given square of the board,
1668 /// updating the board array, bitboards, and piece counts.
1670 void Position::put_piece(Piece p, Square s) {
1672 Color c = color_of_piece(p);
1673 PieceType pt = type_of_piece(p);
1676 index[s] = pieceCount[c][pt];
1677 pieceList[c][pt][index[s]] = s;
1679 set_bit(&(byTypeBB[pt]), s);
1680 set_bit(&(byColorBB[c]), s);
1681 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1683 pieceCount[c][pt]++;
1690 /// Position::allow_oo() gives the given side the right to castle kingside.
1691 /// Used when setting castling rights during parsing of FEN strings.
1693 void Position::allow_oo(Color c) {
1695 st->castleRights |= (1 + int(c));
1699 /// Position::allow_ooo() gives the given side the right to castle queenside.
1700 /// Used when setting castling rights during parsing of FEN strings.
1702 void Position::allow_ooo(Color c) {
1704 st->castleRights |= (4 + 4*int(c));
1708 /// Position::compute_key() computes the hash key of the position. The hash
1709 /// key is usually updated incrementally as moves are made and unmade, the
1710 /// compute_key() function is only used when a new position is set up, and
1711 /// to verify the correctness of the hash key when running in debug mode.
1713 Key Position::compute_key() const {
1715 Key result = Key(0ULL);
1717 for (Square s = SQ_A1; s <= SQ_H8; s++)
1718 if (square_is_occupied(s))
1719 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1721 if (ep_square() != SQ_NONE)
1722 result ^= zobEp[ep_square()];
1724 result ^= zobCastle[st->castleRights];
1725 if (side_to_move() == BLACK)
1726 result ^= zobSideToMove;
1732 /// Position::compute_pawn_key() computes the hash key of the position. The
1733 /// hash key is usually updated incrementally as moves are made and unmade,
1734 /// the compute_pawn_key() function is only used when a new position is set
1735 /// up, and to verify the correctness of the pawn hash key when running in
1738 Key Position::compute_pawn_key() const {
1740 Key result = Key(0ULL);
1744 for (Color c = WHITE; c <= BLACK; c++)
1749 s = pop_1st_bit(&b);
1750 result ^= zobrist[c][PAWN][s];
1757 /// Position::compute_material_key() computes the hash key of the position.
1758 /// The hash key is usually updated incrementally as moves are made and unmade,
1759 /// the compute_material_key() function is only used when a new position is set
1760 /// up, and to verify the correctness of the material hash key when running in
1763 Key Position::compute_material_key() const {
1765 Key result = Key(0ULL);
1766 for (Color c = WHITE; c <= BLACK; c++)
1767 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1769 int count = piece_count(c, pt);
1770 for (int i = 0; i <= count; i++)
1771 result ^= zobMaterial[c][pt][i];
1777 /// Position::compute_value() compute the incremental scores for the middle
1778 /// game and the endgame. These functions are used to initialize the incremental
1779 /// scores when a new position is set up, and to verify that the scores are correctly
1780 /// updated by do_move and undo_move when the program is running in debug mode.
1781 template<Position::GamePhase Phase>
1782 Value Position::compute_value() const {
1784 Value result = Value(0);
1788 for (Color c = WHITE; c <= BLACK; c++)
1789 for (PieceType pt = PAWN; pt <= KING; pt++)
1791 b = pieces_of_color_and_type(c, pt);
1794 s = pop_1st_bit(&b);
1795 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1796 result += pst<Phase>(c, pt, s);
1800 const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1801 result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1806 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1807 /// game material score for the given side. Material scores are updated
1808 /// incrementally during the search, this function is only used while
1809 /// initializing a new Position object.
1811 Value Position::compute_non_pawn_material(Color c) const {
1813 Value result = Value(0);
1815 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1817 Bitboard b = pieces_of_color_and_type(c, pt);
1820 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1822 result += piece_value_midgame(pt);
1829 /// Position::is_draw() tests whether the position is drawn by material,
1830 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1831 /// must be done by the search.
1833 bool Position::is_draw() const {
1835 // Draw by material?
1837 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1840 // Draw by the 50 moves rule?
1841 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1844 // Draw by repetition?
1845 for (int i = 2; i < Min(gamePly, st->rule50); i += 2)
1846 if (history[gamePly - i] == st->key)
1853 /// Position::is_mate() returns true or false depending on whether the
1854 /// side to move is checkmated.
1856 bool Position::is_mate() const {
1858 MoveStack moves[256];
1860 return is_check() && !generate_evasions(*this, moves, pinned_pieces(sideToMove));
1864 /// Position::has_mate_threat() tests whether a given color has a mate in one
1865 /// from the current position.
1867 bool Position::has_mate_threat(Color c) {
1870 Color stm = side_to_move();
1875 // If the input color is not equal to the side to move, do a null move
1879 MoveStack mlist[120];
1881 bool result = false;
1882 Bitboard dc = discovered_check_candidates(sideToMove);
1883 Bitboard pinned = pinned_pieces(sideToMove);
1885 // Generate pseudo-legal non-capture and capture check moves
1886 count = generate_non_capture_checks(*this, mlist, dc);
1887 count += generate_captures(*this, mlist + count);
1889 // Loop through the moves, and see if one of them is mate
1890 for (int i = 0; i < count; i++)
1892 Move move = mlist[i].move;
1894 if (!pl_move_is_legal(move, pinned))
1904 // Undo null move, if necessary
1912 /// Position::init_zobrist() is a static member function which initializes the
1913 /// various arrays used to compute hash keys.
1915 void Position::init_zobrist() {
1917 for (int i = 0; i < 2; i++)
1918 for (int j = 0; j < 8; j++)
1919 for (int k = 0; k < 64; k++)
1920 zobrist[i][j][k] = Key(genrand_int64());
1922 for (int i = 0; i < 64; i++)
1923 zobEp[i] = Key(genrand_int64());
1925 for (int i = 0; i < 16; i++)
1926 zobCastle[i] = genrand_int64();
1928 zobSideToMove = genrand_int64();
1930 for (int i = 0; i < 2; i++)
1931 for (int j = 0; j < 8; j++)
1932 for (int k = 0; k < 16; k++)
1933 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1935 for (int i = 0; i < 16; i++)
1936 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1940 /// Position::init_piece_square_tables() initializes the piece square tables.
1941 /// This is a two-step operation: First, the white halves of the tables are
1942 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1943 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1944 /// Second, the black halves of the tables are initialized by mirroring
1945 /// and changing the sign of the corresponding white scores.
1947 void Position::init_piece_square_tables() {
1949 int r = get_option_value_int("Randomness"), i;
1950 for (Square s = SQ_A1; s <= SQ_H8; s++)
1951 for (Piece p = WP; p <= WK; p++)
1953 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1954 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1955 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1958 for (Square s = SQ_A1; s <= SQ_H8; s++)
1959 for (Piece p = BP; p <= BK; p++)
1961 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
1962 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
1967 /// Position::flipped_copy() makes a copy of the input position, but with
1968 /// the white and black sides reversed. This is only useful for debugging,
1969 /// especially for finding evaluation symmetry bugs.
1971 void Position::flipped_copy(const Position& pos) {
1973 assert(pos.is_ok());
1978 for (Square s = SQ_A1; s <= SQ_H8; s++)
1979 if (!pos.square_is_empty(s))
1980 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1983 sideToMove = opposite_color(pos.side_to_move());
1986 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1987 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1988 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1989 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1991 initialKFile = pos.initialKFile;
1992 initialKRFile = pos.initialKRFile;
1993 initialQRFile = pos.initialQRFile;
1995 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1996 castleRightsMask[sq] = ALL_CASTLES;
1998 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1999 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2000 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2001 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2002 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2003 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2005 // En passant square
2006 if (pos.st->epSquare != SQ_NONE)
2007 st->epSquare = flip_square(pos.st->epSquare);
2013 st->key = compute_key();
2014 st->pawnKey = compute_pawn_key();
2015 st->materialKey = compute_material_key();
2017 // Incremental scores
2018 st->mgValue = compute_value<MidGame>();
2019 st->egValue = compute_value<EndGame>();
2022 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2023 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2029 /// Position::is_ok() performs some consitency checks for the position object.
2030 /// This is meant to be helpful when debugging.
2032 bool Position::is_ok(int* failedStep) const {
2034 // What features of the position should be verified?
2035 static const bool debugBitboards = false;
2036 static const bool debugKingCount = false;
2037 static const bool debugKingCapture = false;
2038 static const bool debugCheckerCount = false;
2039 static const bool debugKey = false;
2040 static const bool debugMaterialKey = false;
2041 static const bool debugPawnKey = false;
2042 static const bool debugIncrementalEval = false;
2043 static const bool debugNonPawnMaterial = false;
2044 static const bool debugPieceCounts = false;
2045 static const bool debugPieceList = false;
2047 if (failedStep) *failedStep = 1;
2050 if (!color_is_ok(side_to_move()))
2053 // Are the king squares in the position correct?
2054 if (failedStep) (*failedStep)++;
2055 if (piece_on(king_square(WHITE)) != WK)
2058 if (failedStep) (*failedStep)++;
2059 if (piece_on(king_square(BLACK)) != BK)
2063 if (failedStep) (*failedStep)++;
2064 if (!file_is_ok(initialKRFile))
2067 if (!file_is_ok(initialQRFile))
2070 // Do both sides have exactly one king?
2071 if (failedStep) (*failedStep)++;
2074 int kingCount[2] = {0, 0};
2075 for (Square s = SQ_A1; s <= SQ_H8; s++)
2076 if (type_of_piece_on(s) == KING)
2077 kingCount[color_of_piece_on(s)]++;
2079 if (kingCount[0] != 1 || kingCount[1] != 1)
2083 // Can the side to move capture the opponent's king?
2084 if (failedStep) (*failedStep)++;
2085 if (debugKingCapture)
2087 Color us = side_to_move();
2088 Color them = opposite_color(us);
2089 Square ksq = king_square(them);
2090 if (square_is_attacked(ksq, us))
2094 // Is there more than 2 checkers?
2095 if (failedStep) (*failedStep)++;
2096 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
2100 if (failedStep) (*failedStep)++;
2103 // The intersection of the white and black pieces must be empty
2104 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2107 // The union of the white and black pieces must be equal to all
2109 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2112 // Separate piece type bitboards must have empty intersections
2113 for (PieceType p1 = PAWN; p1 <= KING; p1++)
2114 for (PieceType p2 = PAWN; p2 <= KING; p2++)
2115 if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2119 // En passant square OK?
2120 if (failedStep) (*failedStep)++;
2121 if (ep_square() != SQ_NONE)
2123 // The en passant square must be on rank 6, from the point of view of the
2125 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2130 if (failedStep) (*failedStep)++;
2131 if (debugKey && st->key != compute_key())
2134 // Pawn hash key OK?
2135 if (failedStep) (*failedStep)++;
2136 if (debugPawnKey && st->pawnKey != compute_pawn_key())
2139 // Material hash key OK?
2140 if (failedStep) (*failedStep)++;
2141 if (debugMaterialKey && st->materialKey != compute_material_key())
2144 // Incremental eval OK?
2145 if (failedStep) (*failedStep)++;
2146 if (debugIncrementalEval)
2148 if (st->mgValue != compute_value<MidGame>())
2151 if (st->egValue != compute_value<EndGame>())
2155 // Non-pawn material OK?
2156 if (failedStep) (*failedStep)++;
2157 if (debugNonPawnMaterial)
2159 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2162 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2167 if (failedStep) (*failedStep)++;
2168 if (debugPieceCounts)
2169 for (Color c = WHITE; c <= BLACK; c++)
2170 for (PieceType pt = PAWN; pt <= KING; pt++)
2171 if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2174 if (failedStep) (*failedStep)++;
2177 for(Color c = WHITE; c <= BLACK; c++)
2178 for(PieceType pt = PAWN; pt <= KING; pt++)
2179 for(int i = 0; i < pieceCount[c][pt]; i++)
2181 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2184 if (index[piece_list(c, pt, i)] != i)
2188 if (failedStep) *failedStep = 0;