2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
38 #include "ucioption.h"
47 Key Position::zobrist[2][8][64];
48 Key Position::zobEp[64];
49 Key Position::zobCastle[16];
50 Key Position::zobSideToMove;
51 Key Position::zobExclusion;
53 Score Position::PieceSquareTable[16][64];
55 static bool RequestPending = false;
60 CheckInfo::CheckInfo(const Position& pos) {
62 Color us = pos.side_to_move();
63 Color them = opposite_color(us);
65 ksq = pos.king_square(them);
66 dcCandidates = pos.discovered_check_candidates(us);
68 checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
69 checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
70 checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
71 checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
72 checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
73 checkSq[KING] = EmptyBoardBB;
77 /// Position c'tors. Here we always create a copy of the original position
78 /// or the FEN string, we want the new born Position object do not depend
79 /// on any external data so we detach state pointer from the source one.
81 Position::Position(int th) : threadID(th) {}
83 Position::Position(const Position& pos, int th) {
85 memcpy(this, &pos, sizeof(Position));
86 detach(); // Always detach() in copy c'tor to avoid surprises
90 Position::Position(const string& fen, int th) {
97 /// Position::detach() copies the content of the current state and castling
98 /// masks inside the position itself. This is needed when the st pointee could
99 /// become stale, as example because the caller is about to going out of scope.
101 void Position::detach() {
105 st->previous = NULL; // as a safe guard
109 /// Position::from_fen() initializes the position object with the given FEN
110 /// string. This function is not very robust - make sure that input FENs are
111 /// correct (this is assumed to be the responsibility of the GUI).
113 void Position::from_fen(const string& fen) {
115 static const string pieceLetters = "KQRBNPkqrbnp";
116 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
124 for ( ; fen[i] != ' '; i++)
128 // Skip the given number of files
129 file += (fen[i] - '1' + 1);
132 else if (fen[i] == '/')
138 size_t idx = pieceLetters.find(fen[i]);
139 if (idx == string::npos)
141 std::cout << "Error in FEN at character " << i << std::endl;
144 Square square = make_square(file, rank);
145 put_piece(pieces[idx], square);
151 if (fen[i] != 'w' && fen[i] != 'b')
153 std::cout << "Error in FEN at character " << i << std::endl;
156 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
162 std::cout << "Error in FEN at character " << i << std::endl;
167 while (strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
173 else if (fen[i] == 'K') allow_oo(WHITE);
174 else if (fen[i] == 'Q') allow_ooo(WHITE);
175 else if (fen[i] == 'k') allow_oo(BLACK);
176 else if (fen[i] == 'q') allow_ooo(BLACK);
177 else if (fen[i] >= 'A' && fen[i] <= 'H') {
178 File rookFile, kingFile = FILE_NONE;
179 for (Square square = SQ_B1; square <= SQ_G1; square++)
180 if (piece_on(square) == WK)
181 kingFile = square_file(square);
182 if (kingFile == FILE_NONE) {
183 std::cout << "Error in FEN at character " << i << std::endl;
186 initialKFile = kingFile;
187 rookFile = File(fen[i] - 'A') + FILE_A;
188 if (rookFile < initialKFile) {
190 initialQRFile = rookFile;
194 initialKRFile = rookFile;
197 else if (fen[i] >= 'a' && fen[i] <= 'h') {
198 File rookFile, kingFile = FILE_NONE;
199 for (Square square = SQ_B8; square <= SQ_G8; square++)
200 if (piece_on(square) == BK)
201 kingFile = square_file(square);
202 if (kingFile == FILE_NONE) {
203 std::cout << "Error in FEN at character " << i << std::endl;
206 initialKFile = kingFile;
207 rookFile = File(fen[i] - 'a') + FILE_A;
208 if (rookFile < initialKFile) {
210 initialQRFile = rookFile;
214 initialKRFile = rookFile;
218 std::cout << "Error in FEN at character " << i << std::endl;
225 while (fen[i] == ' ')
228 // En passant square -- ignore if no capture is possible
229 if ( i <= fen.length() - 2
230 && (fen[i] >= 'a' && fen[i] <= 'h')
231 && (fen[i+1] == '3' || fen[i+1] == '6'))
233 Square fenEpSquare = square_from_string(fen.substr(i, 2));
234 Color them = opposite_color(sideToMove);
235 if (attacks_from<PAWN>(fenEpSquare, them) & this->pieces(PAWN, sideToMove))
236 st->epSquare = square_from_string(fen.substr(i, 2));
239 // Various initialisation
240 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
241 castleRightsMask[sq] = ALL_CASTLES;
243 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
244 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
245 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
246 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
247 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
248 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
252 st->key = compute_key();
253 st->pawnKey = compute_pawn_key();
254 st->materialKey = compute_material_key();
255 st->value = compute_value();
256 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
257 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
261 /// Position::to_fen() converts the position object to a FEN string. This is
262 /// probably only useful for debugging.
264 const string Position::to_fen() const {
266 static const string pieceLetters = " PNBRQK pnbrqk";
270 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
273 for (File file = FILE_A; file <= FILE_H; file++)
275 Square sq = make_square(file, rank);
276 if (!square_is_occupied(sq))
282 fen += (char)skip + '0';
285 fen += pieceLetters[piece_on(sq)];
288 fen += (char)skip + '0';
290 fen += (rank > RANK_1 ? '/' : ' ');
292 fen += (sideToMove == WHITE ? "w " : "b ");
293 if (st->castleRights != NO_CASTLES)
295 if (initialKFile == FILE_E && initialQRFile == FILE_A && initialKRFile == FILE_H)
297 if (can_castle_kingside(WHITE)) fen += 'K';
298 if (can_castle_queenside(WHITE)) fen += 'Q';
299 if (can_castle_kingside(BLACK)) fen += 'k';
300 if (can_castle_queenside(BLACK)) fen += 'q';
304 if (can_castle_kingside(WHITE))
305 fen += char(toupper(file_to_char(initialKRFile)));
306 if (can_castle_queenside(WHITE))
307 fen += char(toupper(file_to_char(initialQRFile)));
308 if (can_castle_kingside(BLACK))
309 fen += file_to_char(initialKRFile);
310 if (can_castle_queenside(BLACK))
311 fen += file_to_char(initialQRFile);
317 if (ep_square() != SQ_NONE)
318 fen += square_to_string(ep_square());
326 /// Position::print() prints an ASCII representation of the position to
327 /// the standard output. If a move is given then also the san is print.
329 void Position::print(Move m) const {
331 static const string pieceLetters = " PNBRQK PNBRQK .";
333 // Check for reentrancy, as example when called from inside
334 // MovePicker that is used also here in move_to_san()
338 RequestPending = true;
340 std::cout << std::endl;
343 Position p(*this, thread());
344 string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
345 std::cout << "Move is: " << col << move_to_san(p, m) << std::endl;
347 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
349 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
350 for (File file = FILE_A; file <= FILE_H; file++)
352 Square sq = make_square(file, rank);
353 Piece piece = piece_on(sq);
354 if (piece == EMPTY && square_color(sq) == WHITE)
357 char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
358 std::cout << '|' << col << pieceLetters[piece] << col;
360 std::cout << '|' << std::endl;
362 std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
363 << "Fen is: " << to_fen() << std::endl
364 << "Key is: " << st->key << std::endl;
366 RequestPending = false;
370 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
371 /// king) pieces for the given color and for the given pinner type. Or, when
372 /// template parameter FindPinned is false, the pieces of the given color
373 /// candidate for a discovery check against the enemy king.
374 /// Bitboard checkersBB must be already updated when looking for pinners.
376 template<bool FindPinned>
377 Bitboard Position::hidden_checkers(Color c) const {
379 Bitboard result = EmptyBoardBB;
380 Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
382 // Pinned pieces protect our king, dicovery checks attack
384 Square ksq = king_square(FindPinned ? c : opposite_color(c));
386 // Pinners are sliders, not checkers, that give check when candidate pinned is removed
387 pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
389 if (FindPinned && pinners)
390 pinners &= ~st->checkersBB;
394 Square s = pop_1st_bit(&pinners);
395 Bitboard b = squares_between(s, ksq) & occupied_squares();
399 if ( !(b & (b - 1)) // Only one bit set?
400 && (b & pieces_of_color(c))) // Is an our piece?
407 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
408 /// king) pieces for the given color. Note that checkersBB bitboard must
409 /// be already updated.
411 Bitboard Position::pinned_pieces(Color c) const {
413 return hidden_checkers<true>(c);
417 /// Position:discovered_check_candidates() returns a bitboard containing all
418 /// pieces for the given side which are candidates for giving a discovered
419 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
420 /// to be already updated.
422 Bitboard Position::discovered_check_candidates(Color c) const {
424 return hidden_checkers<false>(c);
427 /// Position::attackers_to() computes a bitboard containing all pieces which
428 /// attacks a given square.
430 Bitboard Position::attackers_to(Square s) const {
432 return (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
433 | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
434 | (attacks_from<KNIGHT>(s) & pieces(KNIGHT))
435 | (attacks_from<ROOK>(s) & pieces(ROOK, QUEEN))
436 | (attacks_from<BISHOP>(s) & pieces(BISHOP, QUEEN))
437 | (attacks_from<KING>(s) & pieces(KING));
440 /// Position::attacks_from() computes a bitboard of all attacks
441 /// of a given piece put in a given square.
443 Bitboard Position::attacks_from(Piece p, Square s) const {
445 assert(square_is_ok(s));
449 case WP: return attacks_from<PAWN>(s, WHITE);
450 case BP: return attacks_from<PAWN>(s, BLACK);
451 case WN: case BN: return attacks_from<KNIGHT>(s);
452 case WB: case BB: return attacks_from<BISHOP>(s);
453 case WR: case BR: return attacks_from<ROOK>(s);
454 case WQ: case BQ: return attacks_from<QUEEN>(s);
455 case WK: case BK: return attacks_from<KING>(s);
462 /// Position::move_attacks_square() tests whether a move from the current
463 /// position attacks a given square.
465 bool Position::move_attacks_square(Move m, Square s) const {
467 assert(move_is_ok(m));
468 assert(square_is_ok(s));
470 Square f = move_from(m), t = move_to(m);
472 assert(square_is_occupied(f));
474 if (bit_is_set(attacks_from(piece_on(f), t), s))
477 // Move the piece and scan for X-ray attacks behind it
478 Bitboard occ = occupied_squares();
479 Color us = color_of_piece_on(f);
482 Bitboard xray = ( (rook_attacks_bb(s, occ) & pieces(ROOK, QUEEN))
483 |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN))) & pieces_of_color(us);
485 // If we have attacks we need to verify that are caused by our move
486 // and are not already existent ones.
487 return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
491 /// Position::find_checkers() computes the checkersBB bitboard, which
492 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
493 /// currently works by calling Position::attackers_to, which is probably
494 /// inefficient. Consider rewriting this function to use the last move
495 /// played, like in non-bitboard versions of Glaurung.
497 void Position::find_checkers() {
499 Color us = side_to_move();
500 st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
504 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
506 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
509 assert(move_is_ok(m));
510 assert(pinned == pinned_pieces(side_to_move()));
512 // Castling moves are checked for legality during move generation.
513 if (move_is_castle(m))
516 Color us = side_to_move();
517 Square from = move_from(m);
519 assert(color_of_piece_on(from) == us);
520 assert(piece_on(king_square(us)) == piece_of_color_and_type(us, KING));
522 // En passant captures are a tricky special case. Because they are
523 // rather uncommon, we do it simply by testing whether the king is attacked
524 // after the move is made
527 Color them = opposite_color(us);
528 Square to = move_to(m);
529 Square capsq = make_square(square_file(to), square_rank(from));
530 Bitboard b = occupied_squares();
531 Square ksq = king_square(us);
533 assert(to == ep_square());
534 assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
535 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
536 assert(piece_on(to) == EMPTY);
539 clear_bit(&b, capsq);
542 return !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
543 && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
546 // If the moving piece is a king, check whether the destination
547 // square is attacked by the opponent.
548 if (type_of_piece_on(from) == KING)
549 return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
551 // A non-king move is legal if and only if it is not pinned or it
552 // is moving along the ray towards or away from the king.
554 || !bit_is_set(pinned, from)
555 || (direction_between_squares(from, king_square(us)) == direction_between_squares(move_to(m), king_square(us))));
559 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
561 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
565 Color us = side_to_move();
566 Square from = move_from(m);
567 Square to = move_to(m);
569 // King moves and en-passant captures are verified in pl_move_is_legal()
570 if (type_of_piece_on(from) == KING || move_is_ep(m))
571 return pl_move_is_legal(m, pinned);
573 Bitboard target = checkers();
574 Square checksq = pop_1st_bit(&target);
576 if (target) // double check ?
579 // Our move must be a blocking evasion or a capture of the checking piece
580 target = squares_between(checksq, king_square(us)) | checkers();
581 return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
585 /// Position::move_is_check() tests whether a pseudo-legal move is a check
587 bool Position::move_is_check(Move m) const {
589 return move_is_check(m, CheckInfo(*this));
592 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
595 assert(move_is_ok(m));
596 assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
597 assert(color_of_piece_on(move_from(m)) == side_to_move());
598 assert(piece_on(ci.ksq) == piece_of_color_and_type(opposite_color(side_to_move()), KING));
600 Square from = move_from(m);
601 Square to = move_to(m);
602 PieceType pt = type_of_piece_on(from);
605 if (bit_is_set(ci.checkSq[pt], to))
609 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
611 // For pawn and king moves we need to verify also direction
612 if ( (pt != PAWN && pt != KING)
613 ||(direction_between_squares(from, ci.ksq) != direction_between_squares(to, ci.ksq)))
617 // Can we skip the ugly special cases ?
618 if (!move_is_special(m))
621 Color us = side_to_move();
622 Bitboard b = occupied_squares();
624 // Promotion with check ?
625 if (move_is_promotion(m))
629 switch (move_promotion_piece(m))
632 return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
634 return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
636 return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
638 return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
644 // En passant capture with check? We have already handled the case
645 // of direct checks and ordinary discovered check, the only case we
646 // need to handle is the unusual case of a discovered check through the
650 Square capsq = make_square(square_file(to), square_rank(from));
652 clear_bit(&b, capsq);
654 return (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
655 ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
658 // Castling with check ?
659 if (move_is_castle(m))
661 Square kfrom, kto, rfrom, rto;
667 kto = relative_square(us, SQ_G1);
668 rto = relative_square(us, SQ_F1);
670 kto = relative_square(us, SQ_C1);
671 rto = relative_square(us, SQ_D1);
673 clear_bit(&b, kfrom);
674 clear_bit(&b, rfrom);
677 return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
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) {
691 do_move(m, newSt, ci, move_is_check(m, ci));
694 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
697 assert(move_is_ok(m));
701 // Copy some fields of old state to our new StateInfo object except the
702 // ones which are recalculated from scratch anyway, then switch our state
703 // pointer to point to the new, ready to be updated, state.
704 struct ReducedStateInfo {
705 Key pawnKey, materialKey;
706 int castleRights, rule50, gamePly, pliesFromNull;
712 memcpy(&newSt, st, sizeof(ReducedStateInfo));
716 // Save the current key to the history[] array, in order to be able to
717 // detect repetition draws.
718 history[st->gamePly++] = key;
720 // Update side to move
721 key ^= zobSideToMove;
723 // Increment the 50 moves rule draw counter. Resetting it to zero in the
724 // case of non-reversible moves is taken care of later.
728 if (move_is_castle(m))
735 Color us = side_to_move();
736 Color them = opposite_color(us);
737 Square from = move_from(m);
738 Square to = move_to(m);
739 bool ep = move_is_ep(m);
740 bool pm = move_is_promotion(m);
742 Piece piece = piece_on(from);
743 PieceType pt = type_of_piece(piece);
744 PieceType capture = ep ? PAWN : type_of_piece_on(to);
746 assert(color_of_piece_on(from) == us);
747 assert(color_of_piece_on(to) == them || square_is_empty(to));
748 assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
749 assert(!pm || relative_rank(us, to) == RANK_8);
752 do_capture_move(key, capture, them, to, ep);
755 key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
757 // Reset en passant square
758 if (st->epSquare != SQ_NONE)
760 key ^= zobEp[st->epSquare];
761 st->epSquare = SQ_NONE;
764 // Update castle rights, try to shortcut a common case
765 int cm = castleRightsMask[from] & castleRightsMask[to];
766 if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
768 key ^= zobCastle[st->castleRights];
769 st->castleRights &= castleRightsMask[from];
770 st->castleRights &= castleRightsMask[to];
771 key ^= zobCastle[st->castleRights];
774 // Prefetch TT access as soon as we know key is updated
775 prefetch((char*)TT.first_entry(key));
778 Bitboard move_bb = make_move_bb(from, to);
779 do_move_bb(&(byColorBB[us]), move_bb);
780 do_move_bb(&(byTypeBB[pt]), move_bb);
781 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
783 board[to] = board[from];
786 // Update piece lists, note that index[from] is not updated and
787 // becomes stale. This works as long as index[] is accessed just
788 // by known occupied squares.
789 index[to] = index[from];
790 pieceList[us][pt][index[to]] = to;
792 // If the moving piece was a pawn do some special extra work
795 // Reset rule 50 draw counter
798 // Update pawn hash key
799 st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
801 // Set en passant square, only if moved pawn can be captured
802 if ((to ^ from) == 16)
804 if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
806 st->epSquare = Square((int(from) + int(to)) / 2);
807 key ^= zobEp[st->epSquare];
811 if (pm) // promotion ?
813 PieceType promotion = move_promotion_piece(m);
815 assert(promotion >= KNIGHT && promotion <= QUEEN);
817 // Insert promoted piece instead of pawn
818 clear_bit(&(byTypeBB[PAWN]), to);
819 set_bit(&(byTypeBB[promotion]), to);
820 board[to] = piece_of_color_and_type(us, promotion);
822 // Update piece counts
823 pieceCount[us][promotion]++;
824 pieceCount[us][PAWN]--;
826 // Update material key
827 st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
828 st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
830 // Update piece lists, move the last pawn at index[to] position
831 // and shrink the list. Add a new promotion piece to the list.
832 Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
833 index[lastPawnSquare] = index[to];
834 pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
835 pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
836 index[to] = pieceCount[us][promotion] - 1;
837 pieceList[us][promotion][index[to]] = to;
839 // Partially revert hash keys update
840 key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
841 st->pawnKey ^= zobrist[us][PAWN][to];
843 // Partially revert and update incremental scores
844 st->value -= pst(us, PAWN, to);
845 st->value += pst(us, promotion, to);
848 st->npMaterial[us] += piece_value_midgame(promotion);
852 // Update incremental scores
853 st->value += pst_delta(piece, from, to);
856 st->capture = capture;
858 // Update the key with the final value
861 // Update checkers bitboard, piece must be already moved
862 st->checkersBB = EmptyBoardBB;
867 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
871 if (bit_is_set(ci.checkSq[pt], to))
872 st->checkersBB = SetMaskBB[to];
875 if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
878 st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
881 st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
887 sideToMove = opposite_color(sideToMove);
888 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
894 /// Position::do_capture_move() is a private method used to update captured
895 /// piece info. It is called from the main Position::do_move function.
897 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
899 assert(capture != KING);
903 // If the captured piece was a pawn, update pawn hash key,
904 // otherwise update non-pawn material.
907 if (ep) // en passant ?
909 capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
911 assert(to == st->epSquare);
912 assert(relative_rank(opposite_color(them), to) == RANK_6);
913 assert(piece_on(to) == EMPTY);
914 assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
916 board[capsq] = EMPTY;
918 st->pawnKey ^= zobrist[them][PAWN][capsq];
921 st->npMaterial[them] -= piece_value_midgame(capture);
923 // Remove captured piece
924 clear_bit(&(byColorBB[them]), capsq);
925 clear_bit(&(byTypeBB[capture]), capsq);
926 clear_bit(&(byTypeBB[0]), capsq);
929 key ^= zobrist[them][capture][capsq];
931 // Update incremental scores
932 st->value -= pst(them, capture, capsq);
934 // Update piece count
935 pieceCount[them][capture]--;
937 // Update material hash key
938 st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
940 // Update piece list, move the last piece at index[capsq] position
942 // WARNING: This is a not perfectly revresible operation. When we
943 // will reinsert the captured piece in undo_move() we will put it
944 // at the end of the list and not in its original place, it means
945 // index[] and pieceList[] are not guaranteed to be invariant to a
946 // do_move() + undo_move() sequence.
947 Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
948 index[lastPieceSquare] = index[capsq];
949 pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
950 pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
952 // Reset rule 50 counter
957 /// Position::do_castle_move() is a private method used to make a castling
958 /// move. It is called from the main Position::do_move function. Note that
959 /// castling moves are encoded as "king captures friendly rook" moves, for
960 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
962 void Position::do_castle_move(Move m) {
964 assert(move_is_ok(m));
965 assert(move_is_castle(m));
967 Color us = side_to_move();
968 Color them = opposite_color(us);
970 // Reset capture field
971 st->capture = NO_PIECE_TYPE;
973 // Find source squares for king and rook
974 Square kfrom = move_from(m);
975 Square rfrom = move_to(m); // HACK: See comment at beginning of function
978 assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
979 assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
981 // Find destination squares for king and rook
982 if (rfrom > kfrom) // O-O
984 kto = relative_square(us, SQ_G1);
985 rto = relative_square(us, SQ_F1);
987 kto = relative_square(us, SQ_C1);
988 rto = relative_square(us, SQ_D1);
991 // Remove pieces from source squares:
992 clear_bit(&(byColorBB[us]), kfrom);
993 clear_bit(&(byTypeBB[KING]), kfrom);
994 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
995 clear_bit(&(byColorBB[us]), rfrom);
996 clear_bit(&(byTypeBB[ROOK]), rfrom);
997 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
999 // Put pieces on destination squares:
1000 set_bit(&(byColorBB[us]), kto);
1001 set_bit(&(byTypeBB[KING]), kto);
1002 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1003 set_bit(&(byColorBB[us]), rto);
1004 set_bit(&(byTypeBB[ROOK]), rto);
1005 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1007 // Update board array
1008 Piece king = piece_of_color_and_type(us, KING);
1009 Piece rook = piece_of_color_and_type(us, ROOK);
1010 board[kfrom] = board[rfrom] = EMPTY;
1014 // Update piece lists
1015 pieceList[us][KING][index[kfrom]] = kto;
1016 pieceList[us][ROOK][index[rfrom]] = rto;
1017 int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1018 index[kto] = index[kfrom];
1021 // Update incremental scores
1022 st->value += pst_delta(king, kfrom, kto);
1023 st->value += pst_delta(rook, rfrom, rto);
1026 st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1027 st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1029 // Clear en passant square
1030 if (st->epSquare != SQ_NONE)
1032 st->key ^= zobEp[st->epSquare];
1033 st->epSquare = SQ_NONE;
1036 // Update castling rights
1037 st->key ^= zobCastle[st->castleRights];
1038 st->castleRights &= castleRightsMask[kfrom];
1039 st->key ^= zobCastle[st->castleRights];
1041 // Reset rule 50 counter
1044 // Update checkers BB
1045 st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1048 sideToMove = opposite_color(sideToMove);
1049 st->value += (sideToMove == WHITE ? TempoValue : -TempoValue);
1055 /// Position::undo_move() unmakes a move. When it returns, the position should
1056 /// be restored to exactly the same state as before the move was made.
1058 void Position::undo_move(Move m) {
1061 assert(move_is_ok(m));
1063 sideToMove = opposite_color(sideToMove);
1065 if (move_is_castle(m))
1067 undo_castle_move(m);
1071 Color us = side_to_move();
1072 Color them = opposite_color(us);
1073 Square from = move_from(m);
1074 Square to = move_to(m);
1075 bool ep = move_is_ep(m);
1076 bool pm = move_is_promotion(m);
1078 PieceType pt = type_of_piece_on(to);
1080 assert(square_is_empty(from));
1081 assert(color_of_piece_on(to) == us);
1082 assert(!pm || relative_rank(us, to) == RANK_8);
1083 assert(!ep || to == st->previous->epSquare);
1084 assert(!ep || relative_rank(us, to) == RANK_6);
1085 assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1087 if (pm) // promotion ?
1089 PieceType promotion = move_promotion_piece(m);
1092 assert(promotion >= KNIGHT && promotion <= QUEEN);
1093 assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1095 // Replace promoted piece with a pawn
1096 clear_bit(&(byTypeBB[promotion]), to);
1097 set_bit(&(byTypeBB[PAWN]), to);
1099 // Update piece counts
1100 pieceCount[us][promotion]--;
1101 pieceCount[us][PAWN]++;
1103 // Update piece list replacing promotion piece with a pawn
1104 Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1105 index[lastPromotionSquare] = index[to];
1106 pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1107 pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1108 index[to] = pieceCount[us][PAWN] - 1;
1109 pieceList[us][PAWN][index[to]] = to;
1112 // Put the piece back at the source square
1113 Bitboard move_bb = make_move_bb(to, from);
1114 do_move_bb(&(byColorBB[us]), move_bb);
1115 do_move_bb(&(byTypeBB[pt]), move_bb);
1116 do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1118 board[from] = piece_of_color_and_type(us, pt);
1121 // Update piece list
1122 index[from] = index[to];
1123 pieceList[us][pt][index[from]] = from;
1130 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1132 assert(st->capture != KING);
1133 assert(!ep || square_is_empty(capsq));
1135 // Restore the captured piece
1136 set_bit(&(byColorBB[them]), capsq);
1137 set_bit(&(byTypeBB[st->capture]), capsq);
1138 set_bit(&(byTypeBB[0]), capsq);
1140 board[capsq] = piece_of_color_and_type(them, st->capture);
1142 // Update piece count
1143 pieceCount[them][st->capture]++;
1145 // Update piece list, add a new captured piece in capsq square
1146 index[capsq] = pieceCount[them][st->capture] - 1;
1147 pieceList[them][st->capture][index[capsq]] = capsq;
1150 // Finally point our state pointer back to the previous state
1157 /// Position::undo_castle_move() is a private method used to unmake a castling
1158 /// move. It is called from the main Position::undo_move function. Note that
1159 /// castling moves are encoded as "king captures friendly rook" moves, for
1160 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1162 void Position::undo_castle_move(Move m) {
1164 assert(move_is_ok(m));
1165 assert(move_is_castle(m));
1167 // When we have arrived here, some work has already been done by
1168 // Position::undo_move. In particular, the side to move has been switched,
1169 // so the code below is correct.
1170 Color us = side_to_move();
1172 // Find source squares for king and rook
1173 Square kfrom = move_from(m);
1174 Square rfrom = move_to(m); // HACK: See comment at beginning of function
1177 // Find destination squares for king and rook
1178 if (rfrom > kfrom) // O-O
1180 kto = relative_square(us, SQ_G1);
1181 rto = relative_square(us, SQ_F1);
1183 kto = relative_square(us, SQ_C1);
1184 rto = relative_square(us, SQ_D1);
1187 assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1188 assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1190 // Remove pieces from destination squares:
1191 clear_bit(&(byColorBB[us]), kto);
1192 clear_bit(&(byTypeBB[KING]), kto);
1193 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1194 clear_bit(&(byColorBB[us]), rto);
1195 clear_bit(&(byTypeBB[ROOK]), rto);
1196 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1198 // Put pieces on source squares:
1199 set_bit(&(byColorBB[us]), kfrom);
1200 set_bit(&(byTypeBB[KING]), kfrom);
1201 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1202 set_bit(&(byColorBB[us]), rfrom);
1203 set_bit(&(byTypeBB[ROOK]), rfrom);
1204 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1207 board[rto] = board[kto] = EMPTY;
1208 board[rfrom] = piece_of_color_and_type(us, ROOK);
1209 board[kfrom] = piece_of_color_and_type(us, KING);
1211 // Update piece lists
1212 pieceList[us][KING][index[kto]] = kfrom;
1213 pieceList[us][ROOK][index[rto]] = rfrom;
1214 int tmp = index[rto]; // In Chess960 could be rto == kfrom
1215 index[kfrom] = index[kto];
1218 // Finally point our state pointer back to the previous state
1225 /// Position::do_null_move makes() a "null move": It switches the side to move
1226 /// and updates the hash key without executing any move on the board.
1228 void Position::do_null_move(StateInfo& backupSt) {
1231 assert(!is_check());
1233 // Back up the information necessary to undo the null move to the supplied
1234 // StateInfo object.
1235 // Note that differently from normal case here backupSt is actually used as
1236 // a backup storage not as a new state to be used.
1237 backupSt.key = st->key;
1238 backupSt.epSquare = st->epSquare;
1239 backupSt.value = st->value;
1240 backupSt.previous = st->previous;
1241 backupSt.pliesFromNull = st->pliesFromNull;
1242 st->previous = &backupSt;
1244 // Save the current key to the history[] array, in order to be able to
1245 // detect repetition draws.
1246 history[st->gamePly++] = st->key;
1248 // Update the necessary information
1249 if (st->epSquare != SQ_NONE)
1250 st->key ^= zobEp[st->epSquare];
1252 st->key ^= zobSideToMove;
1253 prefetch((char*)TT.first_entry(st->key));
1255 sideToMove = opposite_color(sideToMove);
1256 st->epSquare = SQ_NONE;
1258 st->pliesFromNull = 0;
1259 st->value += (sideToMove == WHITE) ? TempoValue : -TempoValue;
1263 /// Position::undo_null_move() unmakes a "null move".
1265 void Position::undo_null_move() {
1268 assert(!is_check());
1270 // Restore information from the our backup StateInfo object
1271 StateInfo* backupSt = st->previous;
1272 st->key = backupSt->key;
1273 st->epSquare = backupSt->epSquare;
1274 st->value = backupSt->value;
1275 st->previous = backupSt->previous;
1276 st->pliesFromNull = backupSt->pliesFromNull;
1278 // Update the necessary information
1279 sideToMove = opposite_color(sideToMove);
1285 /// Position::see() is a static exchange evaluator: It tries to estimate the
1286 /// material gain or loss resulting from a move. There are three versions of
1287 /// this function: One which takes a destination square as input, one takes a
1288 /// move, and one which takes a 'from' and a 'to' square. The function does
1289 /// not yet understand promotions captures.
1291 int Position::see(Square to) const {
1293 assert(square_is_ok(to));
1294 return see(SQ_NONE, to);
1297 int Position::see(Move m) const {
1299 assert(move_is_ok(m));
1300 return see(move_from(m), move_to(m));
1303 int Position::see_sign(Move m) const {
1305 assert(move_is_ok(m));
1307 Square from = move_from(m);
1308 Square to = move_to(m);
1310 // Early return if SEE cannot be negative because captured piece value
1311 // is not less then capturing one. Note that king moves always return
1312 // here because king midgame value is set to 0.
1313 if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1316 return see(from, to);
1319 int Position::see(Square from, Square to) const {
1322 static const int seeValues[18] = {
1323 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1324 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1325 0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1326 RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1330 Bitboard attackers, stmAttackers, b;
1332 assert(square_is_ok(from) || from == SQ_NONE);
1333 assert(square_is_ok(to));
1335 // Initialize colors
1336 Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1337 Color them = opposite_color(us);
1339 // Initialize pieces
1340 Piece piece = piece_on(from);
1341 Piece capture = piece_on(to);
1342 Bitboard occ = occupied_squares();
1344 // King cannot be recaptured
1345 if (type_of_piece(piece) == KING)
1346 return seeValues[capture];
1348 // Handle en passant moves
1349 if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1351 assert(capture == EMPTY);
1353 Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1354 capture = piece_on(capQq);
1355 assert(type_of_piece_on(capQq) == PAWN);
1357 // Remove the captured pawn
1358 clear_bit(&occ, capQq);
1363 // Find all attackers to the destination square, with the moving piece
1364 // removed, but possibly an X-ray attacker added behind it.
1365 clear_bit(&occ, from);
1366 attackers = (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1367 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN))
1368 | (attacks_from<KNIGHT>(to) & pieces(KNIGHT))
1369 | (attacks_from<KING>(to) & pieces(KING))
1370 | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1371 | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1373 if (from != SQ_NONE)
1376 // If we don't have any attacker we are finished
1377 if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1380 // Locate the least valuable attacker to the destination square
1381 // and use it to initialize from square.
1382 stmAttackers = attackers & pieces_of_color(us);
1384 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1387 from = first_1(stmAttackers & pieces(pt));
1388 piece = piece_on(from);
1391 // If the opponent has no attackers we are finished
1392 stmAttackers = attackers & pieces_of_color(them);
1394 return seeValues[capture];
1396 attackers &= occ; // Remove the moving piece
1398 // The destination square is defended, which makes things rather more
1399 // difficult to compute. We proceed by building up a "swap list" containing
1400 // the material gain or loss at each stop in a sequence of captures to the
1401 // destination square, where the sides alternately capture, and always
1402 // capture with the least valuable piece. After each capture, we look for
1403 // new X-ray attacks from behind the capturing piece.
1404 int lastCapturingPieceValue = seeValues[piece];
1405 int swapList[32], n = 1;
1409 swapList[0] = seeValues[capture];
1412 // Locate the least valuable attacker for the side to move. The loop
1413 // below looks like it is potentially infinite, but it isn't. We know
1414 // that the side to move still has at least one attacker left.
1415 for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1418 // Remove the attacker we just found from the 'attackers' bitboard,
1419 // and scan for new X-ray attacks behind the attacker.
1420 b = stmAttackers & pieces(pt);
1421 occ ^= (b & (~b + 1));
1422 attackers |= (rook_attacks_bb(to, occ) & pieces(ROOK, QUEEN))
1423 | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1427 // Add the new entry to the swap list
1429 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1432 // Remember the value of the capturing piece, and change the side to move
1433 // before beginning the next iteration
1434 lastCapturingPieceValue = seeValues[pt];
1435 c = opposite_color(c);
1436 stmAttackers = attackers & pieces_of_color(c);
1438 // Stop after a king capture
1439 if (pt == KING && stmAttackers)
1442 swapList[n++] = QueenValueMidgame*10;
1445 } while (stmAttackers);
1447 // Having built the swap list, we negamax through it to find the best
1448 // achievable score from the point of view of the side to move
1450 swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1456 /// Position::clear() erases the position object to a pristine state, with an
1457 /// empty board, white to move, and no castling rights.
1459 void Position::clear() {
1462 memset(st, 0, sizeof(StateInfo));
1463 st->epSquare = SQ_NONE;
1465 memset(byColorBB, 0, sizeof(Bitboard) * 2);
1466 memset(byTypeBB, 0, sizeof(Bitboard) * 8);
1467 memset(pieceCount, 0, sizeof(int) * 2 * 8);
1468 memset(index, 0, sizeof(int) * 64);
1470 for (int i = 0; i < 64; i++)
1473 for (int i = 0; i < 8; i++)
1474 for (int j = 0; j < 16; j++)
1475 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1478 initialKFile = FILE_E;
1479 initialKRFile = FILE_H;
1480 initialQRFile = FILE_A;
1484 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1485 /// UCI interface code, whenever a non-reversible move is made in a
1486 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1487 /// for the program to handle games of arbitrary length, as long as the GUI
1488 /// handles draws by the 50 move rule correctly.
1490 void Position::reset_game_ply() {
1496 /// Position::put_piece() puts a piece on the given square of the board,
1497 /// updating the board array, bitboards, and piece counts.
1499 void Position::put_piece(Piece p, Square s) {
1501 Color c = color_of_piece(p);
1502 PieceType pt = type_of_piece(p);
1505 index[s] = pieceCount[c][pt];
1506 pieceList[c][pt][index[s]] = s;
1508 set_bit(&(byTypeBB[pt]), s);
1509 set_bit(&(byColorBB[c]), s);
1510 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1512 pieceCount[c][pt]++;
1516 /// Position::allow_oo() gives the given side the right to castle kingside.
1517 /// Used when setting castling rights during parsing of FEN strings.
1519 void Position::allow_oo(Color c) {
1521 st->castleRights |= (1 + int(c));
1525 /// Position::allow_ooo() gives the given side the right to castle queenside.
1526 /// Used when setting castling rights during parsing of FEN strings.
1528 void Position::allow_ooo(Color c) {
1530 st->castleRights |= (4 + 4*int(c));
1534 /// Position::compute_key() computes the hash key of the position. The hash
1535 /// key is usually updated incrementally as moves are made and unmade, the
1536 /// compute_key() function is only used when a new position is set up, and
1537 /// to verify the correctness of the hash key when running in debug mode.
1539 Key Position::compute_key() const {
1541 Key result = Key(0ULL);
1543 for (Square s = SQ_A1; s <= SQ_H8; s++)
1544 if (square_is_occupied(s))
1545 result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1547 if (ep_square() != SQ_NONE)
1548 result ^= zobEp[ep_square()];
1550 result ^= zobCastle[st->castleRights];
1551 if (side_to_move() == BLACK)
1552 result ^= zobSideToMove;
1558 /// Position::compute_pawn_key() computes the hash key of the position. The
1559 /// hash key is usually updated incrementally as moves are made and unmade,
1560 /// the compute_pawn_key() function is only used when a new position is set
1561 /// up, and to verify the correctness of the pawn hash key when running in
1564 Key Position::compute_pawn_key() const {
1566 Key result = Key(0ULL);
1570 for (Color c = WHITE; c <= BLACK; c++)
1572 b = pieces(PAWN, c);
1575 s = pop_1st_bit(&b);
1576 result ^= zobrist[c][PAWN][s];
1583 /// Position::compute_material_key() computes the hash key of the position.
1584 /// The hash key is usually updated incrementally as moves are made and unmade,
1585 /// the compute_material_key() function is only used when a new position is set
1586 /// up, and to verify the correctness of the material hash key when running in
1589 Key Position::compute_material_key() const {
1591 Key result = Key(0ULL);
1592 for (Color c = WHITE; c <= BLACK; c++)
1593 for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1595 int count = piece_count(c, pt);
1596 for (int i = 0; i < count; i++)
1597 result ^= zobrist[c][pt][i];
1603 /// Position::compute_value() compute the incremental scores for the middle
1604 /// game and the endgame. These functions are used to initialize the incremental
1605 /// scores when a new position is set up, and to verify that the scores are correctly
1606 /// updated by do_move and undo_move when the program is running in debug mode.
1607 Score Position::compute_value() const {
1609 Score result = make_score(0, 0);
1613 for (Color c = WHITE; c <= BLACK; c++)
1614 for (PieceType pt = PAWN; pt <= KING; pt++)
1619 s = pop_1st_bit(&b);
1620 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1621 result += pst(c, pt, s);
1625 result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1630 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1631 /// game material score for the given side. Material scores are updated
1632 /// incrementally during the search, this function is only used while
1633 /// initializing a new Position object.
1635 Value Position::compute_non_pawn_material(Color c) const {
1637 Value result = Value(0);
1639 for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1641 Bitboard b = pieces(pt, c);
1644 assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1646 result += piece_value_midgame(pt);
1653 /// Position::is_draw() tests whether the position is drawn by material,
1654 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1655 /// must be done by the search.
1656 // FIXME: Currently we are not handling 50 move rule correctly when in check
1658 bool Position::is_draw() const {
1660 // Draw by material?
1662 && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1665 // Draw by the 50 moves rule?
1666 if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1669 // Draw by repetition?
1670 for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1671 if (history[st->gamePly - i] == st->key)
1678 /// Position::is_mate() returns true or false depending on whether the
1679 /// side to move is checkmated.
1681 bool Position::is_mate() const {
1683 MoveStack moves[256];
1684 return is_check() && (generate_moves(*this, moves, false) == moves);
1688 /// Position::has_mate_threat() tests whether a given color has a mate in one
1689 /// from the current position.
1691 bool Position::has_mate_threat(Color c) {
1694 Color stm = side_to_move();
1699 // If the input color is not equal to the side to move, do a null move
1703 MoveStack mlist[120];
1704 bool result = false;
1705 Bitboard pinned = pinned_pieces(sideToMove);
1707 // Generate pseudo-legal non-capture and capture check moves
1708 MoveStack* last = generate_non_capture_checks(*this, mlist);
1709 last = generate_captures(*this, last);
1711 // Loop through the moves, and see if one of them is mate
1712 for (MoveStack* cur = mlist; cur != last; cur++)
1714 Move move = cur->move;
1715 if (!pl_move_is_legal(move, pinned))
1725 // Undo null move, if necessary
1733 /// Position::init_zobrist() is a static member function which initializes the
1734 /// various arrays used to compute hash keys.
1736 void Position::init_zobrist() {
1738 for (int i = 0; i < 2; i++)
1739 for (int j = 0; j < 8; j++)
1740 for (int k = 0; k < 64; k++)
1741 zobrist[i][j][k] = Key(genrand_int64());
1743 for (int i = 0; i < 64; i++)
1744 zobEp[i] = Key(genrand_int64());
1746 for (int i = 0; i < 16; i++)
1747 zobCastle[i] = genrand_int64();
1749 zobSideToMove = genrand_int64();
1750 zobExclusion = genrand_int64();
1754 /// Position::init_piece_square_tables() initializes the piece square tables.
1755 /// This is a two-step operation: First, the white halves of the tables are
1756 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1757 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1758 /// Second, the black halves of the tables are initialized by mirroring
1759 /// and changing the sign of the corresponding white scores.
1761 void Position::init_piece_square_tables() {
1763 int r = get_option_value_int("Randomness"), i;
1764 for (Square s = SQ_A1; s <= SQ_H8; s++)
1765 for (Piece p = WP; p <= WK; p++)
1767 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1768 PieceSquareTable[p][s] = make_score(MgPST[p][s] + i, EgPST[p][s] + i);
1771 for (Square s = SQ_A1; s <= SQ_H8; s++)
1772 for (Piece p = BP; p <= BK; p++)
1773 PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1777 /// Position::flipped_copy() makes a copy of the input position, but with
1778 /// the white and black sides reversed. This is only useful for debugging,
1779 /// especially for finding evaluation symmetry bugs.
1781 void Position::flipped_copy(const Position& pos) {
1783 assert(pos.is_ok());
1786 threadID = pos.thread();
1789 for (Square s = SQ_A1; s <= SQ_H8; s++)
1790 if (!pos.square_is_empty(s))
1791 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1794 sideToMove = opposite_color(pos.side_to_move());
1797 if (pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
1798 if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1799 if (pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
1800 if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1802 initialKFile = pos.initialKFile;
1803 initialKRFile = pos.initialKRFile;
1804 initialQRFile = pos.initialQRFile;
1806 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1807 castleRightsMask[sq] = ALL_CASTLES;
1809 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1810 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1811 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
1812 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
1813 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
1814 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
1816 // En passant square
1817 if (pos.st->epSquare != SQ_NONE)
1818 st->epSquare = flip_square(pos.st->epSquare);
1824 st->key = compute_key();
1825 st->pawnKey = compute_pawn_key();
1826 st->materialKey = compute_material_key();
1828 // Incremental scores
1829 st->value = compute_value();
1832 st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1833 st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1839 /// Position::is_ok() performs some consitency checks for the position object.
1840 /// This is meant to be helpful when debugging.
1842 bool Position::is_ok(int* failedStep) const {
1844 // What features of the position should be verified?
1845 static const bool debugBitboards = false;
1846 static const bool debugKingCount = false;
1847 static const bool debugKingCapture = false;
1848 static const bool debugCheckerCount = false;
1849 static const bool debugKey = false;
1850 static const bool debugMaterialKey = false;
1851 static const bool debugPawnKey = false;
1852 static const bool debugIncrementalEval = false;
1853 static const bool debugNonPawnMaterial = false;
1854 static const bool debugPieceCounts = false;
1855 static const bool debugPieceList = false;
1856 static const bool debugCastleSquares = false;
1858 if (failedStep) *failedStep = 1;
1861 if (!color_is_ok(side_to_move()))
1864 // Are the king squares in the position correct?
1865 if (failedStep) (*failedStep)++;
1866 if (piece_on(king_square(WHITE)) != WK)
1869 if (failedStep) (*failedStep)++;
1870 if (piece_on(king_square(BLACK)) != BK)
1874 if (failedStep) (*failedStep)++;
1875 if (!file_is_ok(initialKRFile))
1878 if (!file_is_ok(initialQRFile))
1881 // Do both sides have exactly one king?
1882 if (failedStep) (*failedStep)++;
1885 int kingCount[2] = {0, 0};
1886 for (Square s = SQ_A1; s <= SQ_H8; s++)
1887 if (type_of_piece_on(s) == KING)
1888 kingCount[color_of_piece_on(s)]++;
1890 if (kingCount[0] != 1 || kingCount[1] != 1)
1894 // Can the side to move capture the opponent's king?
1895 if (failedStep) (*failedStep)++;
1896 if (debugKingCapture)
1898 Color us = side_to_move();
1899 Color them = opposite_color(us);
1900 Square ksq = king_square(them);
1901 if (attackers_to(ksq) & pieces_of_color(us))
1905 // Is there more than 2 checkers?
1906 if (failedStep) (*failedStep)++;
1907 if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1911 if (failedStep) (*failedStep)++;
1914 // The intersection of the white and black pieces must be empty
1915 if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1918 // The union of the white and black pieces must be equal to all
1920 if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1923 // Separate piece type bitboards must have empty intersections
1924 for (PieceType p1 = PAWN; p1 <= KING; p1++)
1925 for (PieceType p2 = PAWN; p2 <= KING; p2++)
1926 if (p1 != p2 && (pieces(p1) & pieces(p2)))
1930 // En passant square OK?
1931 if (failedStep) (*failedStep)++;
1932 if (ep_square() != SQ_NONE)
1934 // The en passant square must be on rank 6, from the point of view of the
1936 if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1941 if (failedStep) (*failedStep)++;
1942 if (debugKey && st->key != compute_key())
1945 // Pawn hash key OK?
1946 if (failedStep) (*failedStep)++;
1947 if (debugPawnKey && st->pawnKey != compute_pawn_key())
1950 // Material hash key OK?
1951 if (failedStep) (*failedStep)++;
1952 if (debugMaterialKey && st->materialKey != compute_material_key())
1955 // Incremental eval OK?
1956 if (failedStep) (*failedStep)++;
1957 if (debugIncrementalEval && st->value != compute_value())
1960 // Non-pawn material OK?
1961 if (failedStep) (*failedStep)++;
1962 if (debugNonPawnMaterial)
1964 if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1967 if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1972 if (failedStep) (*failedStep)++;
1973 if (debugPieceCounts)
1974 for (Color c = WHITE; c <= BLACK; c++)
1975 for (PieceType pt = PAWN; pt <= KING; pt++)
1976 if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
1979 if (failedStep) (*failedStep)++;
1982 for (Color c = WHITE; c <= BLACK; c++)
1983 for (PieceType pt = PAWN; pt <= KING; pt++)
1984 for (int i = 0; i < pieceCount[c][pt]; i++)
1986 if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
1989 if (index[piece_list(c, pt, i)] != i)
1994 if (failedStep) (*failedStep)++;
1995 if (debugCastleSquares) {
1996 for (Color c = WHITE; c <= BLACK; c++) {
1997 if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != piece_of_color_and_type(c, ROOK))
1999 if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != piece_of_color_and_type(c, ROOK))
2002 if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
2004 if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
2006 if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
2008 if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
2012 if (failedStep) *failedStep = 0;