2 Glaurung, a UCI chess playing engine.
3 Copyright (C) 2004-2008 Tord Romstad
5 Glaurung is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Glaurung is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
33 #include "ucioption.h"
40 int Position::castleRightsMask[64];
42 Key Position::zobrist[2][8][64];
43 Key Position::zobEp[64];
44 Key Position::zobCastle[16];
45 Key Position::zobMaterial[2][8][16];
46 Key Position::zobSideToMove;
48 Value Position::MgPieceSquareTable[16][64];
49 Value Position::EgPieceSquareTable[16][64];
51 Piece_attacks_fn piece_attacks_fn[7];
57 void init_piece_attacks_fn() {
59 piece_attacks_fn[KNIGHT] = &Position::knight_attacks;
60 piece_attacks_fn[BISHOP] = &Position::bishop_attacks;
61 piece_attacks_fn[ROOK] = &Position::rook_attacks;
62 piece_attacks_fn[QUEEN] = &Position::queen_attacks;
63 piece_attacks_fn[KING] = &Position::king_attacks;
68 Position::Position(const Position &pos) {
72 Position::Position(const std::string &fen) {
77 /// Position::from_fen() initializes the position object with the given FEN
78 /// string. This function is not very robust - make sure that input FENs are
79 /// correct (this is assumed to be the responsibility of the GUI).
81 void Position::from_fen(const std::string &fen) {
83 static const std::string pieceLetters = "KQRBNPkqrbnp";
84 static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
92 for ( ; fen[i] != ' '; i++)
96 // Skip the given number of files
97 file += (fen[i] - '1' + 1);
100 else if (fen[i] == '/')
106 size_t idx = pieceLetters.find(fen[i]);
107 if (idx == std::string::npos)
109 std::cout << "Error in FEN at character " << i << std::endl;
112 Square square = make_square(file, rank);
113 put_piece(pieces[idx], square);
119 if (fen[i] != 'w' && fen[i] != 'b')
121 std::cout << "Error in FEN at character " << i << std::endl;
124 sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
130 std::cout << "Error in FEN at character " << i << std::endl;
135 while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
139 else if(fen[i] == 'K') allow_oo(WHITE);
140 else if(fen[i] == 'Q') allow_ooo(WHITE);
141 else if(fen[i] == 'k') allow_oo(BLACK);
142 else if(fen[i] == 'q') allow_ooo(BLACK);
143 else if(fen[i] >= 'A' && fen[i] <= 'H') {
144 File rookFile, kingFile = FILE_NONE;
145 for(Square square = SQ_B1; square <= SQ_G1; square++)
146 if(piece_on(square) == WK)
147 kingFile = square_file(square);
148 if(kingFile == FILE_NONE) {
149 std::cout << "Error in FEN at character " << i << std::endl;
152 initialKFile = kingFile;
153 rookFile = File(fen[i] - 'A') + FILE_A;
154 if(rookFile < initialKFile) {
156 initialQRFile = rookFile;
160 initialKRFile = rookFile;
163 else if(fen[i] >= 'a' && fen[i] <= 'h') {
164 File rookFile, kingFile = FILE_NONE;
165 for(Square square = SQ_B8; square <= SQ_G8; square++)
166 if(piece_on(square) == BK)
167 kingFile = square_file(square);
168 if(kingFile == FILE_NONE) {
169 std::cout << "Error in FEN at character " << i << std::endl;
172 initialKFile = kingFile;
173 rookFile = File(fen[i] - 'a') + FILE_A;
174 if(rookFile < initialKFile) {
176 initialQRFile = rookFile;
180 initialKRFile = rookFile;
184 std::cout << "Error in FEN at character " << i << std::endl;
191 while (fen[i] == ' ')
195 if ( i < fen.length() - 2
196 && (fen[i] >= 'a' && fen[i] <= 'h')
197 && (fen[i+1] == '3' || fen[i+1] == '6'))
198 epSquare = square_from_string(fen.substr(i, 2));
200 // Various initialisation
201 for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
202 castleRightsMask[sq] = ALL_CASTLES;
204 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
205 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
206 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
207 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
208 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
209 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
214 pawnKey = compute_pawn_key();
215 materialKey = compute_material_key();
216 mgValue = compute_mg_value();
217 egValue = compute_eg_value();
218 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
219 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
223 /// Position::to_fen() converts the position object to a FEN string. This is
224 /// probably only useful for debugging.
226 const std::string Position::to_fen() const {
228 static const std::string pieceLetters = " PNBRQK pnbrqk";
232 for (Rank rank = RANK_8; rank >= RANK_1; rank--)
235 for (File file = FILE_A; file <= FILE_H; file++)
237 Square sq = make_square(file, rank);
238 if (!square_is_occupied(sq))
244 fen += (char)skip + '0';
247 fen += pieceLetters[piece_on(sq)];
250 fen += (char)skip + '0';
252 fen += (rank > RANK_1 ? '/' : ' ');
254 fen += (sideToMove == WHITE ? 'w' : 'b') + ' ';
255 if (castleRights != NO_CASTLES)
257 if (can_castle_kingside(WHITE)) fen += 'K';
258 if (can_castle_queenside(WHITE)) fen += 'Q';
259 if (can_castle_kingside(BLACK)) fen += 'k';
260 if (can_castle_queenside(BLACK)) fen += 'q';
265 if (ep_square() != SQ_NONE)
266 fen += square_to_string(ep_square());
274 /// Position::print() prints an ASCII representation of the position to
275 /// the standard output.
277 void Position::print() const {
278 char pieceStrings[][8] =
279 {"| ? ", "| P ", "| N ", "| B ", "| R ", "| Q ", "| K ", "| ? ",
280 "| ? ", "|=P=", "|=N=", "|=B=", "|=R=", "|=Q=", "|=K="
283 for(Rank rank = RANK_8; rank >= RANK_1; rank--) {
284 std::cout << "+---+---+---+---+---+---+---+---+\n";
285 for(File file = FILE_A; file <= FILE_H; file++) {
286 Square sq = make_square(file, rank);
287 Piece piece = piece_on(sq);
289 std::cout << ((square_color(sq) == WHITE)? "| " : "| . ");
291 std::cout << pieceStrings[piece];
295 std::cout << "+---+---+---+---+---+---+---+---+\n";
296 std::cout << to_fen() << std::endl;
297 std::cout << key << std::endl;
301 /// Position::copy() creates a copy of the input position.
303 void Position::copy(const Position &pos) {
304 memcpy(this, &pos, sizeof(Position));
308 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
309 /// king) pieces for the given color.
311 Bitboard Position::pinned_pieces(Color c) const {
312 Bitboard b1, b2, pinned, pinners, sliders;
313 Square ksq = king_square(c), s;
314 Color them = opposite_color(c);
316 pinned = EmptyBoardBB;
317 b1 = occupied_squares();
319 sliders = rooks_and_queens(them) & ~checkers();
320 if(sliders & RookPseudoAttacks[ksq]) {
321 b2 = rook_attacks(ksq) & pieces_of_color(c);
322 pinners = rook_attacks_bb(ksq, b1 ^ b2) & sliders;
324 s = pop_1st_bit(&pinners);
325 pinned |= (squares_between(s, ksq) & b2);
329 sliders = bishops_and_queens(them) & ~checkers();
330 if(sliders & BishopPseudoAttacks[ksq]) {
331 b2 = bishop_attacks(ksq) & pieces_of_color(c);
332 pinners = bishop_attacks_bb(ksq, b1 ^ b2) & sliders;
334 s = pop_1st_bit(&pinners);
335 pinned |= (squares_between(s, ksq) & b2);
342 /// Position:discovered_check_candidates() returns a bitboard containing all
343 /// pieces for the given side which are candidates for giving a discovered
344 /// check. The code is almost the same as the function for finding pinned
347 Bitboard Position::discovered_check_candidates(Color c) const {
348 Bitboard b1, b2, dc, checkers, sliders;
349 Square ksq = king_square(opposite_color(c)), s;
352 b1 = occupied_squares();
354 sliders = rooks_and_queens(c);
355 if(sliders & RookPseudoAttacks[ksq]) {
356 b2 = rook_attacks(ksq) & pieces_of_color(c);
357 checkers = rook_attacks_bb(ksq, b1 ^ b2) & sliders;
359 s = pop_1st_bit(&checkers);
360 dc |= (squares_between(s, ksq) & b2);
364 sliders = bishops_and_queens(c);
365 if(sliders & BishopPseudoAttacks[ksq]) {
366 b2 = bishop_attacks(ksq) & pieces_of_color(c);
367 checkers = bishop_attacks_bb(ksq, b1 ^ b2) & sliders;
369 s = pop_1st_bit(&checkers);
370 dc |= (squares_between(s, ksq) & b2);
378 /// Position::square_is_attacked() checks whether the given side attacks the
381 bool Position::square_is_attacked(Square s, Color c) const {
383 (pawn_attacks(opposite_color(c), s) & pawns(c)) ||
384 (knight_attacks(s) & knights(c)) ||
385 (king_attacks(s) & kings(c)) ||
386 (rook_attacks(s) & rooks_and_queens(c)) ||
387 (bishop_attacks(s) & bishops_and_queens(c));
391 /// Position::attacks_to() computes a bitboard containing all pieces which
392 /// attacks a given square. There are two versions of this function: One
393 /// which finds attackers of both colors, and one which only finds the
394 /// attackers for one side.
396 Bitboard Position::attacks_to(Square s) const {
398 (black_pawn_attacks(s) & pawns(WHITE)) |
399 (white_pawn_attacks(s) & pawns(BLACK)) |
400 (knight_attacks(s) & pieces_of_type(KNIGHT)) |
401 (rook_attacks(s) & rooks_and_queens()) |
402 (bishop_attacks(s) & bishops_and_queens()) |
403 (king_attacks(s) & pieces_of_type(KING));
406 Bitboard Position::attacks_to(Square s, Color c) const {
407 return attacks_to(s) & pieces_of_color(c);
411 /// Position::piece_attacks_square() tests whether the piece on square f
412 /// attacks square t.
414 bool Position::piece_attacks_square(Square f, Square t) const {
415 assert(square_is_ok(f));
416 assert(square_is_ok(t));
418 switch(piece_on(f)) {
419 case WP: return white_pawn_attacks_square(f, t);
420 case BP: return black_pawn_attacks_square(f, t);
421 case WN: case BN: return knight_attacks_square(f, t);
422 case WB: case BB: return bishop_attacks_square(f, t);
423 case WR: case BR: return rook_attacks_square(f, t);
424 case WQ: case BQ: return queen_attacks_square(f, t);
425 case WK: case BK: return king_attacks_square(f, t);
426 default: return false;
433 /// Position::find_checkers() computes the checkersBB bitboard, which
434 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
435 /// currently works by calling Position::attacks_to, which is probably
436 /// inefficient. Consider rewriting this function to use the last move
437 /// played, like in non-bitboard versions of Glaurung.
439 void Position::find_checkers() {
440 checkersBB = attacks_to(king_square(side_to_move()),
441 opposite_color(side_to_move()));
445 /// Position::move_is_legal() tests whether a pseudo-legal move is legal.
446 /// There are two versions of this function: One which takes only a
447 /// move as input, and one which takes a move and a bitboard of pinned
448 /// pieces. The latter function is faster, and should always be preferred
449 /// when a pinned piece bitboard has already been computed.
451 bool Position::move_is_legal(Move m) const {
452 return move_is_legal(m, pinned_pieces(side_to_move()));
456 bool Position::move_is_legal(Move m, Bitboard pinned) const {
461 assert(move_is_ok(m));
462 assert(pinned == pinned_pieces(side_to_move()));
464 // If we're in check, all pseudo-legal moves are legal, because our
465 // check evasion generator only generates true legal moves.
466 if(is_check()) return true;
468 // Castling moves are checked for legality during move generation.
469 if(move_is_castle(m)) return true;
472 them = opposite_color(us);
475 ksq = king_square(us);
477 assert(color_of_piece_on(from) == us);
478 assert(piece_on(ksq) == king_of_color(us));
480 // En passant captures are a tricky special case. Because they are
481 // rather uncommon, we do it simply by testing whether the king is attacked
482 // after the move is made:
484 Square to = move_to(m);
485 Square capsq = make_square(square_file(to), square_rank(from));
486 Bitboard b = occupied_squares();
488 assert(to == ep_square());
489 assert(piece_on(from) == pawn_of_color(us));
490 assert(piece_on(capsq) == pawn_of_color(them));
491 assert(piece_on(to) == EMPTY);
493 clear_bit(&b, from); clear_bit(&b, capsq); set_bit(&b, to);
495 (!(rook_attacks_bb(ksq, b) & rooks_and_queens(them)) &&
496 !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them)));
499 // If the moving piece is a king, check whether the destination
500 // square is attacked by the opponent.
501 if(from == ksq) return !(square_is_attacked(move_to(m), them));
503 // A non-king move is legal if and only if it is not pinned or it
504 // is moving along the ray towards or away from the king.
505 if(!bit_is_set(pinned, from)) return true;
506 if(direction_between_squares(from, ksq) ==
507 direction_between_squares(move_to(m), ksq))
514 /// Position::move_is_check() tests whether a pseudo-legal move is a check.
515 /// There are two versions of this function: One which takes only a move as
516 /// input, and one which takes a move and a bitboard of discovered check
517 /// candidates. The latter function is faster, and should always be preferred
518 /// when a discovered check candidates bitboard has already been computed.
520 bool Position::move_is_check(Move m) const {
521 Bitboard dc = discovered_check_candidates(side_to_move());
522 return move_is_check(m, dc);
526 bool Position::move_is_check(Move m, Bitboard dcCandidates) const {
528 Square ksq, from, to;
531 assert(move_is_ok(m));
532 assert(dcCandidates ==
533 discovered_check_candidates(side_to_move()));
536 them = opposite_color(us);
540 ksq = king_square(them);
541 assert(color_of_piece_on(from) == us);
542 assert(piece_on(ksq) == king_of_color(them));
544 // Proceed according to the type of the moving piece:
545 switch(type_of_piece_on(from)) {
548 if(bit_is_set(pawn_attacks(them, ksq), to))
551 else if(bit_is_set(dcCandidates, from) &&
552 direction_between_squares(from, ksq) !=
553 direction_between_squares(to, ksq))
555 // Promotion with check?
556 else if(move_promotion(m)) {
557 Bitboard b = occupied_squares();
560 switch(move_promotion(m)) {
562 return knight_attacks_square(to, ksq);
564 return bit_is_set(bishop_attacks_bb(to, b), ksq);
566 return bit_is_set(rook_attacks_bb(to, b), ksq);
568 return bit_is_set(queen_attacks_bb(to, b), ksq);
573 // En passant capture with check? We have already handled the case
574 // of direct checks and ordinary discovered check, the only case we
575 // need to handle is the unusual case of a discovered check through the
577 else if(move_is_ep(m)) {
578 Square capsq = make_square(square_file(to), square_rank(from));
579 Bitboard b = occupied_squares();
581 clear_bit(&b, from); clear_bit(&b, capsq); set_bit(&b, to);
583 ((rook_attacks_bb(ksq, b) & rooks_and_queens(us)) ||
584 (bishop_attacks_bb(ksq, b) & bishops_and_queens(us)));
590 if(bit_is_set(dcCandidates, from))
594 return bit_is_set(knight_attacks(ksq), to);
598 if(bit_is_set(dcCandidates, from))
602 return bit_is_set(bishop_attacks(ksq), to);
606 if(bit_is_set(dcCandidates, from))
610 return bit_is_set(rook_attacks(ksq), to);
613 // Discovered checks are impossible!
614 assert(!bit_is_set(dcCandidates, from));
616 return bit_is_set(queen_attacks(ksq), to);
620 if(bit_is_set(dcCandidates, from) &&
621 direction_between_squares(from, ksq) !=
622 direction_between_squares(to, ksq))
624 // Castling with check?
625 if(move_is_castle(m)) {
626 Square kfrom, kto, rfrom, rto;
627 Bitboard b = occupied_squares();
632 kto = relative_square(us, SQ_G1);
633 rto = relative_square(us, SQ_F1);
636 kto = relative_square(us, SQ_C1);
637 rto = relative_square(us, SQ_D1);
640 clear_bit(&b, kfrom); clear_bit(&b, rfrom);
641 set_bit(&b, rto); set_bit(&b, kto);
643 return bit_is_set(rook_attacks_bb(rto, b), ksq);
658 /// Position::move_is_capture() tests whether a move from the current
659 /// position is a capture.
661 bool Position::move_is_capture(Move m) const {
663 color_of_piece_on(move_to(m)) == opposite_color(side_to_move())
668 /// Position::move_attacks_square() tests whether a move from the current
669 /// position attacks a given square. Only attacks by the moving piece are
670 /// considered; the function does not handle X-ray attacks.
672 bool Position::move_attacks_square(Move m, Square s) const {
673 assert(move_is_ok(m));
674 assert(square_is_ok(s));
676 Square f = move_from(m), t = move_to(m);
678 assert(square_is_occupied(f));
680 switch(piece_on(f)) {
681 case WP: return white_pawn_attacks_square(t, s);
682 case BP: return black_pawn_attacks_square(t, s);
683 case WN: case BN: return knight_attacks_square(t, s);
684 case WB: case BB: return bishop_attacks_square(t, s);
685 case WR: case BR: return rook_attacks_square(t, s);
686 case WQ: case BQ: return queen_attacks_square(t, s);
687 case WK: case BK: return king_attacks_square(t, s);
688 default: assert(false);
696 /// Position::backup() is called when making a move. All information
697 /// necessary to restore the position when the move is later unmade
698 /// is saved to an UndoInfo object. The function Position::restore
699 /// does the reverse operation: When one does a backup followed by
700 /// a restore with the same UndoInfo object, the position is restored
701 /// to the state before backup was called.
703 void Position::backup(UndoInfo &u) const {
704 u.castleRights = castleRights;
705 u.epSquare = epSquare;
706 u.checkersBB = checkersBB;
709 u.materialKey = materialKey;
711 u.lastMove = lastMove;
712 u.capture = NO_PIECE_TYPE;
718 /// Position::restore() is called when unmaking a move. It copies back
719 /// the information backed up during a previous call to Position::backup.
721 void Position::restore(const UndoInfo &u) {
722 castleRights = u.castleRights;
723 epSquare = u.epSquare;
724 checkersBB = u.checkersBB;
727 materialKey = u.materialKey;
729 lastMove = u.lastMove;
735 /// Position::do_move() makes a move, and backs up all information necessary
736 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
737 /// Pseudo-legal moves should be filtered out before this function is called.
738 /// There are two versions of this function, one which takes only the move and
739 /// the UndoInfo as input, and one which takes a third parameter, a bitboard of
740 /// discovered check candidates. The second version is faster, because knowing
741 /// the discovered check candidates makes it easier to update the checkersBB
742 /// member variable in the position object.
744 void Position::do_move(Move m, UndoInfo &u) {
745 do_move(m, u, discovered_check_candidates(side_to_move()));
748 void Position::do_move(Move m, UndoInfo &u, Bitboard dcCandidates) {
750 assert(move_is_ok(m));
752 // Back up the necessary information to our UndoInfo object (except the
753 // captured piece, which is taken care of later:
756 // Save the current key to the history[] array, in order to be able to
757 // detect repetition draws:
758 history[gamePly] = key;
760 // Increment the 50 moves rule draw counter. Resetting it to zero in the
761 // case of non-reversible moves is taken care of later.
764 if(move_is_castle(m))
766 else if(move_promotion(m))
767 do_promotion_move(m, u);
768 else if(move_is_ep(m))
773 PieceType piece, capture;
776 them = opposite_color(us);
781 assert(color_of_piece_on(from) == us);
782 assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
784 piece = type_of_piece_on(from);
785 capture = type_of_piece_on(to);
788 assert(capture != KING);
790 // Remove captured piece:
791 clear_bit(&(byColorBB[them]), to);
792 clear_bit(&(byTypeBB[capture]), to);
795 key ^= zobrist[them][capture][to];
797 // If the captured piece was a pawn, update pawn hash key:
799 pawnKey ^= zobrist[them][PAWN][to];
801 // Update incremental scores:
802 mgValue -= mg_pst(them, capture, to);
803 egValue -= eg_pst(them, capture, to);
807 npMaterial[them] -= piece_value_midgame(capture);
809 // Update material hash key:
810 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
812 // Update piece count:
813 pieceCount[them][capture]--;
815 // Update piece list:
816 pieceList[them][capture][index[to]] =
817 pieceList[them][capture][pieceCount[them][capture]];
818 index[pieceList[them][capture][index[to]]] = index[to];
820 // Remember the captured piece, in order to be able to undo the move
824 // Reset rule 50 counter:
829 clear_bit(&(byColorBB[us]), from);
830 clear_bit(&(byTypeBB[piece]), from);
831 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
832 set_bit(&(byColorBB[us]), to);
833 set_bit(&(byTypeBB[piece]), to);
834 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
835 board[to] = board[from];
839 key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
841 // Update incremental scores:
842 mgValue -= mg_pst(us, piece, from);
843 mgValue += mg_pst(us, piece, to);
844 egValue -= eg_pst(us, piece, from);
845 egValue += eg_pst(us, piece, to);
847 // If the moving piece was a king, update the king square:
851 // If the move was a double pawn push, set the en passant square.
852 // This code is a bit ugly right now, and should be cleaned up later.
854 if(epSquare != SQ_NONE) {
855 key ^= zobEp[epSquare];
859 if(abs(int(to) - int(from)) == 16) {
860 if((us == WHITE && (white_pawn_attacks(from + DELTA_N) &
862 (us == BLACK && (black_pawn_attacks(from + DELTA_S) &
864 epSquare = Square((int(from) + int(to)) / 2);
865 key ^= zobEp[epSquare];
868 // Reset rule 50 draw counter.
870 // Update pawn hash key:
871 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
874 // Update piece lists:
875 pieceList[us][piece][index[from]] = to;
876 index[to] = index[from];
878 // Update castle rights:
879 key ^= zobCastle[castleRights];
880 castleRights &= castleRightsMask[from];
881 castleRights &= castleRightsMask[to];
882 key ^= zobCastle[castleRights];
884 // Update checkers bitboard:
885 checkersBB = EmptyBoardBB;
886 Square ksq = king_square(them);
891 if(bit_is_set(pawn_attacks(them, ksq), to))
892 set_bit(&checkersBB, to);
893 if(bit_is_set(dcCandidates, from))
895 ((rook_attacks(ksq) & rooks_and_queens(us)) |
896 (bishop_attacks(ksq) & bishops_and_queens(us)));
900 if(bit_is_set(knight_attacks(ksq), to))
901 set_bit(&checkersBB, to);
902 if(bit_is_set(dcCandidates, from))
904 ((rook_attacks(ksq) & rooks_and_queens(us)) |
905 (bishop_attacks(ksq) & bishops_and_queens(us)));
909 if(bit_is_set(bishop_attacks(ksq), to))
910 set_bit(&checkersBB, to);
911 if(bit_is_set(dcCandidates, from))
913 (rook_attacks(ksq) & rooks_and_queens(us));
917 if(bit_is_set(rook_attacks(ksq), to))
918 set_bit(&checkersBB, to);
919 if(bit_is_set(dcCandidates, from))
921 (bishop_attacks(ksq) & bishops_and_queens(us));
925 if(bit_is_set(queen_attacks(ksq), to))
926 set_bit(&checkersBB, to);
930 if(bit_is_set(dcCandidates, from))
932 ((rook_attacks(ksq) & rooks_and_queens(us)) |
933 (bishop_attacks(ksq) & bishops_and_queens(us)));
943 key ^= zobSideToMove;
944 sideToMove = opposite_color(sideToMove);
947 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
948 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
954 /// Position::do_castle_move() is a private method used to make a castling
955 /// move. It is called from the main Position::do_move function. Note that
956 /// castling moves are encoded as "king captures friendly rook" moves, for
957 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
959 void Position::do_castle_move(Move m) {
961 Square kfrom, kto, rfrom, rto;
964 assert(move_is_ok(m));
965 assert(move_is_castle(m));
968 them = opposite_color(us);
970 // Find source squares for king and rook:
971 kfrom = move_from(m);
972 rfrom = move_to(m); // HACK: See comment at beginning of function.
974 assert(piece_on(kfrom) == king_of_color(us));
975 assert(piece_on(rfrom) == rook_of_color(us));
977 // Find destination squares for king and rook:
978 if(rfrom > kfrom) { // O-O
979 kto = relative_square(us, SQ_G1);
980 rto = relative_square(us, SQ_F1);
983 kto = relative_square(us, SQ_C1);
984 rto = relative_square(us, SQ_D1);
987 // Remove pieces from source squares:
988 clear_bit(&(byColorBB[us]), kfrom);
989 clear_bit(&(byTypeBB[KING]), kfrom);
990 clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
991 clear_bit(&(byColorBB[us]), rfrom);
992 clear_bit(&(byTypeBB[ROOK]), rfrom);
993 clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
995 // Put pieces on destination squares:
996 set_bit(&(byColorBB[us]), kto);
997 set_bit(&(byTypeBB[KING]), kto);
998 set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
999 set_bit(&(byColorBB[us]), rto);
1000 set_bit(&(byTypeBB[ROOK]), rto);
1001 set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1003 // Update board array:
1004 board[kfrom] = board[rfrom] = EMPTY;
1005 board[kto] = king_of_color(us);
1006 board[rto] = rook_of_color(us);
1008 // Update king square:
1009 kingSquare[us] = kto;
1011 // Update piece lists:
1012 pieceList[us][KING][index[kfrom]] = kto;
1013 pieceList[us][ROOK][index[rfrom]] = rto;
1014 int tmp = index[rfrom];
1015 index[kto] = index[kfrom];
1018 // Update incremental scores:
1019 mgValue -= mg_pst(us, KING, kfrom);
1020 mgValue += mg_pst(us, KING, kto);
1021 egValue -= eg_pst(us, KING, kfrom);
1022 egValue += eg_pst(us, KING, kto);
1023 mgValue -= mg_pst(us, ROOK, rfrom);
1024 mgValue += mg_pst(us, ROOK, rto);
1025 egValue -= eg_pst(us, ROOK, rfrom);
1026 egValue += eg_pst(us, ROOK, rto);
1029 key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1030 key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1032 // Clear en passant square:
1033 if(epSquare != SQ_NONE) {
1034 key ^= zobEp[epSquare];
1038 // Update castling rights:
1039 key ^= zobCastle[castleRights];
1040 castleRights &= castleRightsMask[kfrom];
1041 key ^= zobCastle[castleRights];
1043 // Reset rule 50 counter:
1046 // Update checkers BB:
1047 checkersBB = attacks_to(king_square(them), us);
1051 /// Position::do_promotion_move() is a private method used to make a promotion
1052 /// move. It is called from the main Position::do_move function. The
1053 /// UndoInfo object, which has been initialized in Position::do_move, is
1054 /// used to store the captured piece (if any).
1056 void Position::do_promotion_move(Move m, UndoInfo &u) {
1059 PieceType capture, promotion;
1062 assert(move_is_ok(m));
1063 assert(move_promotion(m));
1065 us = side_to_move();
1066 them = opposite_color(us);
1068 from = move_from(m);
1071 assert(relative_rank(us, to) == RANK_8);
1072 assert(piece_on(from) == pawn_of_color(us));
1073 assert(color_of_piece_on(to) == them || square_is_empty(to));
1075 capture = type_of_piece_on(to);
1078 assert(capture != KING);
1080 // Remove captured piece:
1081 clear_bit(&(byColorBB[them]), to);
1082 clear_bit(&(byTypeBB[capture]), to);
1085 key ^= zobrist[them][capture][to];
1087 // Update incremental scores:
1088 mgValue -= mg_pst(them, capture, to);
1089 egValue -= eg_pst(them, capture, to);
1091 // Update material. Because our move is a promotion, we know that the
1092 // captured piece is not a pawn.
1093 assert(capture != PAWN);
1094 npMaterial[them] -= piece_value_midgame(capture);
1096 // Update material hash key:
1097 materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
1099 // Update piece count:
1100 pieceCount[them][capture]--;
1102 // Update piece list:
1103 pieceList[them][capture][index[to]] =
1104 pieceList[them][capture][pieceCount[them][capture]];
1105 index[pieceList[them][capture][index[to]]] = index[to];
1107 // Remember the captured piece, in order to be able to undo the move
1109 u.capture = capture;
1113 clear_bit(&(byColorBB[us]), from);
1114 clear_bit(&(byTypeBB[PAWN]), from);
1115 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1116 board[from] = EMPTY;
1118 // Insert promoted piece:
1119 promotion = move_promotion(m);
1120 assert(promotion >= KNIGHT && promotion <= QUEEN);
1121 set_bit(&(byColorBB[us]), to);
1122 set_bit(&(byTypeBB[promotion]), to);
1123 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1124 board[to] = piece_of_color_and_type(us, promotion);
1127 key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1129 // Update pawn hash key:
1130 pawnKey ^= zobrist[us][PAWN][from];
1132 // Update material key:
1133 materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1134 materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1136 // Update piece counts:
1137 pieceCount[us][PAWN]--;
1138 pieceCount[us][promotion]++;
1140 // Update piece lists:
1141 pieceList[us][PAWN][index[from]] =
1142 pieceList[us][PAWN][pieceCount[us][PAWN]];
1143 index[pieceList[us][PAWN][index[from]]] = index[from];
1144 pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1145 index[to] = pieceCount[us][promotion] - 1;
1147 // Update incremental scores:
1148 mgValue -= mg_pst(us, PAWN, from);
1149 mgValue += mg_pst(us, promotion, to);
1150 egValue -= eg_pst(us, PAWN, from);
1151 egValue += eg_pst(us, promotion, to);
1154 npMaterial[us] += piece_value_midgame(promotion);
1156 // Clear the en passant square:
1157 if(epSquare != SQ_NONE) {
1158 key ^= zobEp[epSquare];
1162 // Update castle rights:
1163 key ^= zobCastle[castleRights];
1164 castleRights &= castleRightsMask[to];
1165 key ^= zobCastle[castleRights];
1167 // Reset rule 50 counter:
1170 // Update checkers BB:
1171 checkersBB = attacks_to(king_square(them), us);
1175 /// Position::do_ep_move() is a private method used to make an en passant
1176 /// capture. It is called from the main Position::do_move function. Because
1177 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1178 /// object in which to store the captured piece.
1180 void Position::do_ep_move(Move m) {
1182 Square from, to, capsq;
1185 assert(move_is_ok(m));
1186 assert(move_is_ep(m));
1188 us = side_to_move();
1189 them = opposite_color(us);
1191 // Find from, to and capture squares:
1192 from = move_from(m);
1194 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1196 assert(to == epSquare);
1197 assert(relative_rank(us, to) == RANK_6);
1198 assert(piece_on(to) == EMPTY);
1199 assert(piece_on(from) == pawn_of_color(us));
1200 assert(piece_on(capsq) == pawn_of_color(them));
1202 // Remove captured piece:
1203 clear_bit(&(byColorBB[them]), capsq);
1204 clear_bit(&(byTypeBB[PAWN]), capsq);
1205 clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1206 board[capsq] = EMPTY;
1208 // Remove moving piece from source square:
1209 clear_bit(&(byColorBB[us]), from);
1210 clear_bit(&(byTypeBB[PAWN]), from);
1211 clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1213 // Put moving piece on destination square:
1214 set_bit(&(byColorBB[us]), to);
1215 set_bit(&(byTypeBB[PAWN]), to);
1216 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1217 board[to] = board[from];
1218 board[from] = EMPTY;
1220 // Update material hash key:
1221 materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1223 // Update piece count:
1224 pieceCount[them][PAWN]--;
1226 // Update piece list:
1227 pieceList[us][PAWN][index[from]] = to;
1228 index[to] = index[from];
1229 pieceList[them][PAWN][index[capsq]] =
1230 pieceList[them][PAWN][pieceCount[them][PAWN]];
1231 index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1234 key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1235 key ^= zobrist[them][PAWN][capsq];
1236 key ^= zobEp[epSquare];
1238 // Update pawn hash key:
1239 pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1240 pawnKey ^= zobrist[them][PAWN][capsq];
1242 // Update incremental scores:
1243 mgValue -= mg_pst(them, PAWN, capsq);
1244 mgValue -= mg_pst(us, PAWN, from);
1245 mgValue += mg_pst(us, PAWN, to);
1246 egValue -= eg_pst(them, PAWN, capsq);
1247 egValue -= eg_pst(us, PAWN, from);
1248 egValue += eg_pst(us, PAWN, to);
1250 // Reset en passant square:
1253 // Reset rule 50 counter:
1256 // Update checkers BB:
1257 checkersBB = attacks_to(king_square(them), us);
1261 /// Position::undo_move() unmakes a move. When it returns, the position should
1262 /// be restored to exactly the same state as before the move was made. It is
1263 /// important that Position::undo_move is called with the same move and UndoInfo
1264 /// object as the earlier call to Position::do_move.
1266 void Position::undo_move(Move m, const UndoInfo &u) {
1268 assert(move_is_ok(m));
1271 sideToMove = opposite_color(sideToMove);
1273 // Restore information from our UndoInfo object (except the captured piece,
1274 // which is taken care of later):
1277 if(move_is_castle(m))
1278 undo_castle_move(m);
1279 else if(move_promotion(m))
1280 undo_promotion_move(m, u);
1281 else if(move_is_ep(m))
1286 PieceType piece, capture;
1288 us = side_to_move();
1289 them = opposite_color(us);
1291 from = move_from(m);
1294 assert(piece_on(from) == EMPTY);
1295 assert(color_of_piece_on(to) == us);
1297 // Put the piece back at the source square:
1298 piece = type_of_piece_on(to);
1299 set_bit(&(byColorBB[us]), from);
1300 set_bit(&(byTypeBB[piece]), from);
1301 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1302 board[from] = piece_of_color_and_type(us, piece);
1304 // Clear the destination square
1305 clear_bit(&(byColorBB[us]), to);
1306 clear_bit(&(byTypeBB[piece]), to);
1307 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1309 // If the moving piece was a king, update the king square:
1311 kingSquare[us] = from;
1313 // Update piece list:
1314 pieceList[us][piece][index[to]] = from;
1315 index[from] = index[to];
1317 capture = u.capture;
1320 assert(capture != KING);
1321 // Replace the captured piece:
1322 set_bit(&(byColorBB[them]), to);
1323 set_bit(&(byTypeBB[capture]), to);
1324 set_bit(&(byTypeBB[0]), to);
1325 board[to] = piece_of_color_and_type(them, capture);
1329 npMaterial[them] += piece_value_midgame(capture);
1331 // Update piece list:
1332 pieceList[them][capture][pieceCount[them][capture]] = to;
1333 index[to] = pieceCount[them][capture];
1335 // Update piece count:
1336 pieceCount[them][capture]++;
1346 /// Position::undo_castle_move() is a private method used to unmake a castling
1347 /// move. It is called from the main Position::undo_move function. Note that
1348 /// castling moves are encoded as "king captures friendly rook" moves, for
1349 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1351 void Position::undo_castle_move(Move m) {
1353 Square kfrom, kto, rfrom, rto;
1355 assert(move_is_ok(m));
1356 assert(move_is_castle(m));
1358 // When we have arrived here, some work has already been done by
1359 // Position::undo_move. In particular, the side to move has been switched,
1360 // so the code below is correct.
1361 us = side_to_move();
1362 them = opposite_color(us);
1364 // Find source squares for king and rook:
1365 kfrom = move_from(m);
1366 rfrom = move_to(m); // HACK: See comment at beginning of function.
1368 // Find destination squares for king and rook:
1369 if(rfrom > kfrom) { // O-O
1370 kto = relative_square(us, SQ_G1);
1371 rto = relative_square(us, SQ_F1);
1374 kto = relative_square(us, SQ_C1);
1375 rto = relative_square(us, SQ_D1);
1378 assert(piece_on(kto) == king_of_color(us));
1379 assert(piece_on(rto) == rook_of_color(us));
1381 // Remove pieces from destination squares:
1382 clear_bit(&(byColorBB[us]), kto);
1383 clear_bit(&(byTypeBB[KING]), kto);
1384 clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1385 clear_bit(&(byColorBB[us]), rto);
1386 clear_bit(&(byTypeBB[ROOK]), rto);
1387 clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1389 // Put pieces on source squares:
1390 set_bit(&(byColorBB[us]), kfrom);
1391 set_bit(&(byTypeBB[KING]), kfrom);
1392 set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1393 set_bit(&(byColorBB[us]), rfrom);
1394 set_bit(&(byTypeBB[ROOK]), rfrom);
1395 set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1398 board[rto] = board[kto] = EMPTY;
1399 board[rfrom] = rook_of_color(us);
1400 board[kfrom] = king_of_color(us);
1402 // Update king square:
1403 kingSquare[us] = kfrom;
1405 // Update piece lists:
1406 pieceList[us][KING][index[kto]] = kfrom;
1407 pieceList[us][ROOK][index[rto]] = rfrom;
1408 int tmp = index[rto]; // Necessary because we may have rto == kfrom in FRC.
1409 index[kfrom] = index[kto];
1414 /// Position::undo_promotion_move() is a private method used to unmake a
1415 /// promotion move. It is called from the main Position::do_move
1416 /// function. The UndoInfo object, which has been initialized in
1417 /// Position::do_move, is used to put back the captured piece (if any).
1419 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1422 PieceType capture, promotion;
1424 assert(move_is_ok(m));
1425 assert(move_promotion(m));
1427 // When we have arrived here, some work has already been done by
1428 // Position::undo_move. In particular, the side to move has been switched,
1429 // so the code below is correct.
1430 us = side_to_move();
1431 them = opposite_color(us);
1433 from = move_from(m);
1436 assert(relative_rank(us, to) == RANK_8);
1437 assert(piece_on(from) == EMPTY);
1439 // Remove promoted piece:
1440 promotion = move_promotion(m);
1441 assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1442 assert(promotion >= KNIGHT && promotion <= QUEEN);
1443 clear_bit(&(byColorBB[us]), to);
1444 clear_bit(&(byTypeBB[promotion]), to);
1445 clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1447 // Insert pawn at source square:
1448 set_bit(&(byColorBB[us]), from);
1449 set_bit(&(byTypeBB[PAWN]), from);
1450 set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1451 board[from] = pawn_of_color(us);
1454 npMaterial[us] -= piece_value_midgame(promotion);
1456 // Update piece list:
1457 pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1458 index[from] = pieceCount[us][PAWN];
1459 pieceList[us][promotion][index[to]] =
1460 pieceList[us][promotion][pieceCount[us][promotion] - 1];
1461 index[pieceList[us][promotion][index[to]]] = index[to];
1463 // Update piece counts:
1464 pieceCount[us][promotion]--;
1465 pieceCount[us][PAWN]++;
1467 capture = u.capture;
1469 assert(capture != KING);
1471 // Insert captured piece:
1472 set_bit(&(byColorBB[them]), to);
1473 set_bit(&(byTypeBB[capture]), to);
1474 set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1475 board[to] = piece_of_color_and_type(them, capture);
1477 // Update material. Because the move is a promotion move, we know
1478 // that the captured piece cannot be a pawn.
1479 assert(capture != PAWN);
1480 npMaterial[them] += piece_value_midgame(capture);
1482 // Update piece list:
1483 pieceList[them][capture][pieceCount[them][capture]] = to;
1484 index[to] = pieceCount[them][capture];
1486 // Update piece count:
1487 pieceCount[them][capture]++;
1494 /// Position::undo_ep_move() is a private method used to unmake an en passant
1495 /// capture. It is called from the main Position::undo_move function. Because
1496 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1497 /// object from which to retrieve the captured piece.
1499 void Position::undo_ep_move(Move m) {
1501 Square from, to, capsq;
1503 assert(move_is_ok(m));
1504 assert(move_is_ep(m));
1506 // When we have arrived here, some work has already been done by
1507 // Position::undo_move. In particular, the side to move has been switched,
1508 // so the code below is correct.
1509 us = side_to_move();
1510 them = opposite_color(us);
1512 // Find from, to and captures squares:
1513 from = move_from(m);
1515 capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1517 assert(to == ep_square());
1518 assert(relative_rank(us, to) == RANK_6);
1519 assert(piece_on(to) == pawn_of_color(us));
1520 assert(piece_on(from) == EMPTY);
1521 assert(piece_on(capsq) == EMPTY);
1523 // Replace captured piece:
1524 set_bit(&(byColorBB[them]), capsq);
1525 set_bit(&(byTypeBB[PAWN]), capsq);
1526 set_bit(&(byTypeBB[0]), capsq);
1527 board[capsq] = pawn_of_color(them);
1529 // Remove moving piece from destination square:
1530 clear_bit(&(byColorBB[us]), to);
1531 clear_bit(&(byTypeBB[PAWN]), to);
1532 clear_bit(&(byTypeBB[0]), to);
1535 // Replace moving piece at source square:
1536 set_bit(&(byColorBB[us]), from);
1537 set_bit(&(byTypeBB[PAWN]), from);
1538 set_bit(&(byTypeBB[0]), from);
1539 board[from] = pawn_of_color(us);
1541 // Update piece list:
1542 pieceList[us][PAWN][index[to]] = from;
1543 index[from] = index[to];
1544 pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1545 index[capsq] = pieceCount[them][PAWN];
1547 // Update piece count:
1548 pieceCount[them][PAWN]++;
1552 /// Position::do_null_move makes() a "null move": It switches the side to move
1553 /// and updates the hash key without executing any move on the board.
1555 void Position::do_null_move(UndoInfo &u) {
1557 assert(!is_check());
1559 // Back up the information necessary to undo the null move to the supplied
1560 // UndoInfo object. In the case of a null move, the only thing we need to
1561 // remember is the last move made and the en passant square.
1562 u.lastMove = lastMove;
1563 u.epSquare = epSquare;
1565 // Save the current key to the history[] array, in order to be able to
1566 // detect repetition draws:
1567 history[gamePly] = key;
1569 // Update the necessary information.
1570 sideToMove = opposite_color(sideToMove);
1571 if(epSquare != SQ_NONE)
1572 key ^= zobEp[epSquare];
1576 key ^= zobSideToMove;
1578 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1579 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1585 /// Position::undo_null_move() unmakes a "null move".
1587 void Position::undo_null_move(const UndoInfo &u) {
1589 assert(!is_check());
1591 // Restore information from the supplied UndoInfo object:
1592 lastMove = u.lastMove;
1593 epSquare = u.epSquare;
1594 if(epSquare != SQ_NONE)
1595 key ^= zobEp[epSquare];
1597 // Update the necessary information.
1598 sideToMove = opposite_color(sideToMove);
1601 key ^= zobSideToMove;
1603 mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1604 egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1610 /// Position::see() is a static exchange evaluator: It tries to estimate the
1611 /// material gain or loss resulting from a move. There are two versions of
1612 /// this function: One which takes a move as input, and one which takes a
1613 /// 'from' and a 'to' square. The function does not yet understand promotions
1614 /// or en passant captures.
1616 int Position::see(Square from, Square to) const {
1617 // Approximate material values, with pawn = 1:
1618 static const int seeValues[18] = {
1619 0, 1, 3, 3, 5, 10, 100, 0, 0, 1, 3, 3, 5, 10, 100, 0, 0, 0
1622 Piece piece, capture;
1623 Bitboard attackers, occ, b;
1625 assert(square_is_ok(from));
1626 assert(square_is_ok(to));
1628 // Initialize colors:
1629 us = color_of_piece_on(from);
1630 them = opposite_color(us);
1632 // Initialize pieces:
1633 piece = piece_on(from);
1634 capture = piece_on(to);
1636 // Find all attackers to the destination square, with the moving piece
1637 // removed, but possibly an X-ray attacker added behind it:
1638 occ = occupied_squares();
1639 clear_bit(&occ, from);
1641 (rook_attacks_bb(to, occ) & rooks_and_queens()) |
1642 (bishop_attacks_bb(to, occ) & bishops_and_queens()) |
1643 (knight_attacks(to) & knights()) |
1644 (king_attacks(to) & kings()) |
1645 (white_pawn_attacks(to) & pawns(BLACK)) |
1646 (black_pawn_attacks(to) & pawns(WHITE));
1649 // If the opponent has no attackers, we are finished:
1650 if((attackers & pieces_of_color(them)) == EmptyBoardBB)
1651 return seeValues[capture];
1653 // The destination square is defended, which makes things rather more
1654 // difficult to compute. We proceed by building up a "swap list" containing
1655 // the material gain or loss at each stop in a sequence of captures to the
1656 // destianation square, where the sides alternately capture, and always
1657 // capture with the least valuable piece. After each capture, we look for
1658 // new X-ray attacks from behind the capturing piece.
1659 int lastCapturingPieceValue = seeValues[piece];
1660 int swapList[32], n = 1;
1664 swapList[0] = seeValues[capture];
1667 // Locate the least valuable attacker for the side to move. The loop
1668 // below looks like it is potentially infinite, but it isn't. We know
1669 // that the side to move still has at least one attacker left.
1670 for(pt = PAWN; !(attackers&pieces_of_color_and_type(c, pt)); pt++)
1673 // Remove the attacker we just found from the 'attackers' bitboard,
1674 // and scan for new X-ray attacks behind the attacker:
1675 b = attackers & pieces_of_color_and_type(c, pt);
1678 (rook_attacks_bb(to, occ) & rooks_and_queens()) |
1679 (bishop_attacks_bb(to, occ) & bishops_and_queens());
1682 // Add the new entry to the swap list:
1684 swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1687 // Remember the value of the capturing piece, and change the side to move
1688 // before beginning the next iteration:
1689 lastCapturingPieceValue = seeValues[pt];
1690 c = opposite_color(c);
1692 // Stop after a king capture:
1693 if(pt == KING && (attackers & pieces_of_color(c))) {
1695 swapList[n++] = 100;
1698 } while(attackers & pieces_of_color(c));
1700 // Having built the swap list, we negamax through it to find the best
1701 // achievable score from the point of view of the side to move:
1702 while(--n) swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1708 int Position::see(Move m) const {
1709 assert(move_is_ok(m));
1710 return see(move_from(m), move_to(m));
1714 /// Position::clear() erases the position object to a pristine state, with an
1715 /// empty board, white to move, and no castling rights.
1717 void Position::clear() {
1720 for(i = 0; i < 64; i++) {
1725 for(i = 0; i < 2; i++)
1726 byColorBB[i] = EmptyBoardBB;
1728 for(i = 0; i < 7; i++) {
1729 byTypeBB[i] = EmptyBoardBB;
1730 pieceCount[0][i] = pieceCount[1][i] = 0;
1731 for(j = 0; j < 8; j++)
1732 pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1735 checkersBB = EmptyBoardBB;
1737 lastMove = MOVE_NONE;
1740 castleRights = NO_CASTLES;
1741 initialKFile = FILE_E;
1742 initialKRFile = FILE_H;
1743 initialQRFile = FILE_A;
1750 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1751 /// UCI interface code, whenever a non-reversible move is made in a
1752 /// 'position fen <fen> moves m1 m2 ...' command. This makes it possible
1753 /// for the program to handle games of arbitrary length, as long as the GUI
1754 /// handles draws by the 50 move rule correctly.
1756 void Position::reset_game_ply() {
1761 /// Position::put_piece() puts a piece on the given square of the board,
1762 /// updating the board array, bitboards, and piece counts.
1764 void Position::put_piece(Piece p, Square s) {
1765 Color c = color_of_piece(p);
1766 PieceType pt = type_of_piece(p);
1769 index[s] = pieceCount[c][pt];
1770 pieceList[c][pt][index[s]] = s;
1772 set_bit(&(byTypeBB[pt]), s);
1773 set_bit(&(byColorBB[c]), s);
1774 set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1776 pieceCount[c][pt]++;
1783 /// Position::allow_oo() gives the given side the right to castle kingside.
1784 /// Used when setting castling rights during parsing of FEN strings.
1786 void Position::allow_oo(Color c) {
1787 castleRights |= (1 + int(c));
1791 /// Position::allow_ooo() gives the given side the right to castle queenside.
1792 /// Used when setting castling rights during parsing of FEN strings.
1794 void Position::allow_ooo(Color c) {
1795 castleRights |= (4 + 4*int(c));
1799 /// Position::compute_key() computes the hash key of the position. The hash
1800 /// key is usually updated incrementally as moves are made and unmade, the
1801 /// compute_key() function is only used when a new position is set up, and
1802 /// to verify the correctness of the hash key when running in debug mode.
1804 Key Position::compute_key() const {
1805 Key result = Key(0ULL);
1807 for(Square s = SQ_A1; s <= SQ_H8; s++)
1808 if(square_is_occupied(s))
1810 zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1812 if(ep_square() != SQ_NONE)
1813 result ^= zobEp[ep_square()];
1814 result ^= zobCastle[castleRights];
1815 if(side_to_move() == BLACK) result ^= zobSideToMove;
1821 /// Position::compute_pawn_key() computes the hash key of the position. The
1822 /// hash key is usually updated incrementally as moves are made and unmade,
1823 /// the compute_pawn_key() function is only used when a new position is set
1824 /// up, and to verify the correctness of the pawn hash key when running in
1827 Key Position::compute_pawn_key() const {
1828 Key result = Key(0ULL);
1832 for(Color c = WHITE; c <= BLACK; c++) {
1835 s = pop_1st_bit(&b);
1836 result ^= zobrist[c][PAWN][s];
1843 /// Position::compute_material_key() computes the hash key of the position.
1844 /// The hash key is usually updated incrementally as moves are made and unmade,
1845 /// the compute_material_key() function is only used when a new position is set
1846 /// up, and to verify the correctness of the material hash key when running in
1849 Key Position::compute_material_key() const {
1850 Key result = Key(0ULL);
1851 for(Color c = WHITE; c <= BLACK; c++)
1852 for(PieceType pt = PAWN; pt <= QUEEN; pt++) {
1853 int count = piece_count(c, pt);
1854 for(int i = 0; i <= count; i++)
1855 result ^= zobMaterial[c][pt][i];
1861 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1862 /// incremental scores for the middle game and the endgame. These functions
1863 /// are used to initialize the incremental scores when a new position is set
1864 /// up, and to verify that the scores are correctly updated by do_move
1865 /// and undo_move when the program is running in debug mode.
1867 Value Position::compute_mg_value() const {
1868 Value result = Value(0);
1872 for(Color c = WHITE; c <= BLACK; c++)
1873 for(PieceType pt = PAWN; pt <= KING; pt++) {
1874 b = pieces_of_color_and_type(c, pt);
1876 s = pop_1st_bit(&b);
1877 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1878 result += mg_pst(c, pt, s);
1881 result += (side_to_move() == WHITE)?
1882 (TempoValueMidgame / 2) : -(TempoValueMidgame / 2);
1886 Value Position::compute_eg_value() const {
1887 Value result = Value(0);
1891 for(Color c = WHITE; c <= BLACK; c++)
1892 for(PieceType pt = PAWN; pt <= KING; pt++) {
1893 b = pieces_of_color_and_type(c, pt);
1895 s = pop_1st_bit(&b);
1896 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1897 result += eg_pst(c, pt, s);
1900 result += (side_to_move() == WHITE)?
1901 (TempoValueEndgame / 2) : -(TempoValueEndgame / 2);
1906 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1907 /// game material score for the given side. Material scores are updated
1908 /// incrementally during the search, this function is only used while
1909 /// initializing a new Position object.
1911 Value Position::compute_non_pawn_material(Color c) const {
1912 Value result = Value(0);
1915 for(PieceType pt = KNIGHT; pt <= QUEEN; pt++) {
1916 Bitboard b = pieces_of_color_and_type(c, pt);
1918 s = pop_1st_bit(&b);
1919 assert(piece_on(s) == piece_of_color_and_type(c, pt));
1920 result += piece_value_midgame(pt);
1927 /// Position::is_mate() returns true or false depending on whether the
1928 /// side to move is checkmated. Note that this function is currently very
1929 /// slow, and shouldn't be used frequently inside the search.
1931 bool Position::is_mate() {
1933 MovePicker mp = MovePicker(*this, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1934 MOVE_NONE, Depth(0));
1935 return mp.get_next_move() == MOVE_NONE;
1942 /// Position::is_draw() tests whether the position is drawn by material,
1943 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1944 /// must be done by the search.
1946 bool Position::is_draw() const {
1947 // Draw by material?
1949 non_pawn_material(WHITE) + non_pawn_material(BLACK)
1950 <= BishopValueMidgame)
1953 // Draw by the 50 moves rule?
1954 if(rule50 > 100 || (rule50 == 100 && !is_check()))
1957 // Draw by repetition?
1958 for(int i = 2; i < Min(gamePly, rule50); i += 2)
1959 if(history[gamePly - i] == key)
1966 /// Position::has_mate_threat() tests whether a given color has a mate in one
1967 /// from the current position. This function is quite slow, but it doesn't
1968 /// matter, because it is currently only called from PV nodes, which are rare.
1970 bool Position::has_mate_threat(Color c) {
1972 Color stm = side_to_move();
1974 // The following lines are useless and silly, but prevents gcc from
1975 // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1976 // be used uninitialized.
1977 u1.lastMove = lastMove;
1978 u1.epSquare = epSquare;
1983 // If the input color is not equal to the side to move, do a null move
1984 if(c != stm) do_null_move(u1);
1986 MoveStack mlist[120];
1988 bool result = false;
1990 // Generate legal moves
1991 count = generate_legal_moves(*this, mlist);
1993 // Loop through the moves, and see if one of them is mate.
1994 for(int i = 0; i < count; i++) {
1995 do_move(mlist[i].move, u2);
1996 if(is_mate()) result = true;
1997 undo_move(mlist[i].move, u2);
2000 // Undo null move, if necessary
2001 if(c != stm) undo_null_move(u1);
2007 /// Position::init_zobrist() is a static member function which initializes the
2008 /// various arrays used to compute hash keys.
2010 void Position::init_zobrist() {
2012 for(int i = 0; i < 2; i++)
2013 for(int j = 0; j < 8; j++)
2014 for(int k = 0; k < 64; k++)
2015 zobrist[i][j][k] = Key(genrand_int64());
2017 for(int i = 0; i < 64; i++)
2018 zobEp[i] = Key(genrand_int64());
2020 for(int i = 0; i < 16; i++)
2021 zobCastle[i] = genrand_int64();
2023 zobSideToMove = genrand_int64();
2025 for(int i = 0; i < 2; i++)
2026 for(int j = 0; j < 8; j++)
2027 for(int k = 0; k < 16; k++)
2028 zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2030 for(int i = 0; i < 16; i++)
2031 zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2035 /// Position::init_piece_square_tables() initializes the piece square tables.
2036 /// This is a two-step operation: First, the white halves of the tables are
2037 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2038 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2039 /// Second, the black halves of the tables are initialized by mirroring
2040 /// and changing the sign of the corresponding white scores.
2042 void Position::init_piece_square_tables() {
2043 int r = get_option_value_int("Randomness"), i;
2044 for(Square s = SQ_A1; s <= SQ_H8; s++) {
2045 for(Piece p = WP; p <= WK; p++) {
2046 i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2047 MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2048 EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2051 for(Square s = SQ_A1; s <= SQ_H8; s++)
2052 for(Piece p = BP; p <= BK; p++) {
2053 MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2054 EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2059 /// Position::flipped_copy() makes a copy of the input position, but with
2060 /// the white and black sides reversed. This is only useful for debugging,
2061 /// especially for finding evaluation symmetry bugs.
2063 void Position::flipped_copy(const Position &pos) {
2064 assert(pos.is_ok());
2069 for(Square s = SQ_A1; s <= SQ_H8; s++)
2070 if(!pos.square_is_empty(s))
2071 put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2074 sideToMove = opposite_color(pos.side_to_move());
2077 if(pos.can_castle_kingside(WHITE)) allow_oo(BLACK);
2078 if(pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2079 if(pos.can_castle_kingside(BLACK)) allow_oo(WHITE);
2080 if(pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2082 initialKFile = pos.initialKFile;
2083 initialKRFile = pos.initialKRFile;
2084 initialQRFile = pos.initialQRFile;
2086 for(Square sq = SQ_A1; sq <= SQ_H8; sq++)
2087 castleRightsMask[sq] = ALL_CASTLES;
2088 castleRightsMask[make_square(initialKFile, RANK_1)] ^= (WHITE_OO|WHITE_OOO);
2089 castleRightsMask[make_square(initialKFile, RANK_8)] ^= (BLACK_OO|BLACK_OOO);
2090 castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
2091 castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
2092 castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
2093 castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
2095 // En passant square
2096 if(pos.epSquare != SQ_NONE)
2097 epSquare = flip_square(pos.epSquare);
2103 key = compute_key();
2104 pawnKey = compute_pawn_key();
2105 materialKey = compute_material_key();
2107 // Incremental scores
2108 mgValue = compute_mg_value();
2109 egValue = compute_eg_value();
2112 npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2113 npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2119 /// Position::is_ok() performs some consitency checks for the position object.
2120 /// This is meant to be helpful when debugging.
2122 bool Position::is_ok() const {
2124 // What features of the position should be verified?
2125 static const bool debugBitboards = false;
2126 static const bool debugKingCount = false;
2127 static const bool debugKingCapture = false;
2128 static const bool debugCheckerCount = false;
2129 static const bool debugKey = false;
2130 static const bool debugMaterialKey = false;
2131 static const bool debugPawnKey = false;
2132 static const bool debugIncrementalEval = false;
2133 static const bool debugNonPawnMaterial = false;
2134 static const bool debugPieceCounts = false;
2135 static const bool debugPieceList = false;
2138 if(!color_is_ok(side_to_move()))
2141 // Are the king squares in the position correct?
2142 if(piece_on(king_square(WHITE)) != WK)
2144 if(piece_on(king_square(BLACK)) != BK)
2148 if(!file_is_ok(initialKRFile))
2150 if(!file_is_ok(initialQRFile))
2153 // Do both sides have exactly one king?
2154 if(debugKingCount) {
2155 int kingCount[2] = {0, 0};
2156 for(Square s = SQ_A1; s <= SQ_H8; s++)
2157 if(type_of_piece_on(s) == KING)
2158 kingCount[color_of_piece_on(s)]++;
2159 if(kingCount[0] != 1 || kingCount[1] != 1)
2163 // Can the side to move capture the opponent's king?
2164 if(debugKingCapture) {
2165 Color us = side_to_move();
2166 Color them = opposite_color(us);
2167 Square ksq = king_square(them);
2168 if(square_is_attacked(ksq, us))
2172 // Is there more than 2 checkers?
2173 if(debugCheckerCount && count_1s(checkersBB) > 2)
2177 if(debugBitboards) {
2178 // The intersection of the white and black pieces must be empty:
2179 if((pieces_of_color(WHITE) & pieces_of_color(BLACK))
2183 // The union of the white and black pieces must be equal to all
2184 // occupied squares:
2185 if((pieces_of_color(WHITE) | pieces_of_color(BLACK))
2186 != occupied_squares())
2189 // Separate piece type bitboards must have empty intersections:
2190 for(PieceType p1 = PAWN; p1 <= KING; p1++)
2191 for(PieceType p2 = PAWN; p2 <= KING; p2++)
2192 if(p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2196 // En passant square OK?
2197 if(ep_square() != SQ_NONE) {
2198 // The en passant square must be on rank 6, from the point of view of the
2200 if(relative_rank(side_to_move(), ep_square()) != RANK_6)
2205 if(debugKey && key != compute_key())
2208 // Pawn hash key OK?
2209 if(debugPawnKey && pawnKey != compute_pawn_key())
2212 // Material hash key OK?
2213 if(debugMaterialKey && materialKey != compute_material_key())
2216 // Incremental eval OK?
2217 if(debugIncrementalEval) {
2218 if(mgValue != compute_mg_value())
2220 if(egValue != compute_eg_value())
2224 // Non-pawn material OK?
2225 if(debugNonPawnMaterial) {
2226 if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2228 if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2233 if(debugPieceCounts)
2234 for(Color c = WHITE; c <= BLACK; c++)
2235 for(PieceType pt = PAWN; pt <= KING; pt++)
2236 if(pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2239 if(debugPieceList) {
2240 for(Color c = WHITE; c <= BLACK; c++)
2241 for(PieceType pt = PAWN; pt <= KING; pt++)
2242 for(int i = 0; i < pieceCount[c][pt]; i++) {
2243 if(piece_on(piece_list(c, pt, i)) !=
2244 piece_of_color_and_type(c, pt))
2246 if(index[piece_list(c, pt, i)] != i)