-/// Position::undo_move() unmakes a move. When it returns, the position should
-/// be restored to exactly the same state as before the move was made.
-
-void Position::undo_move(Move m) {
-
- assert(is_ok(m));
-
- sideToMove = flip(sideToMove);
-
- if (is_castle(m))
- {
- do_castle_move<false>(m);
- return;
- }
-
- Color us = side_to_move();
- Color them = flip(us);
- Square from = move_from(m);
- Square to = move_to(m);
- bool ep = is_enpassant(m);
- bool pm = is_promotion(m);
-
- PieceType pt = type_of(piece_on(to));
-
- assert(square_is_empty(from));
- assert(color_of(piece_on(to)) == us);
- assert(!pm || relative_rank(us, to) == RANK_8);
- assert(!ep || to == st->previous->epSquare);
- assert(!ep || relative_rank(us, to) == RANK_6);
- assert(!ep || piece_on(to) == make_piece(us, PAWN));
-
- if (pm) // promotion ?
- {
- PieceType promotion = promotion_piece_type(m);
- pt = PAWN;
-
- assert(promotion >= KNIGHT && promotion <= QUEEN);
- assert(piece_on(to) == make_piece(us, promotion));
-
- // Replace promoted piece with a pawn
- clear_bit(&byTypeBB[promotion], to);
- set_bit(&byTypeBB[PAWN], to);
-
- // Update piece counts
- pieceCount[us][promotion]--;
- pieceCount[us][PAWN]++;
-
- // Update piece list replacing promotion piece with a pawn
- Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
- index[lastPromotionSquare] = index[to];
- pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
- pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
- index[to] = pieceCount[us][PAWN] - 1;
- pieceList[us][PAWN][index[to]] = to;
- }
-
- // Put the piece back at the source square
- Bitboard move_bb = make_move_bb(to, from);
- do_move_bb(&byColorBB[us], move_bb);
- do_move_bb(&byTypeBB[pt], move_bb);
- do_move_bb(&byTypeBB[0], move_bb); // HACK: byTypeBB[0] == occupied squares
-
- board[from] = make_piece(us, pt);
- board[to] = PIECE_NONE;
-
- // Update piece list
- index[from] = index[to];
- pieceList[us][pt][index[from]] = from;
-
- if (st->capturedType)
- {
- Square capsq = to;
-
- if (ep)
- capsq = to - pawn_push(us);
-
- assert(st->capturedType != KING);
- assert(!ep || square_is_empty(capsq));
-
- // Restore the captured piece
- set_bit(&byColorBB[them], capsq);
- set_bit(&byTypeBB[st->capturedType], capsq);
- set_bit(&byTypeBB[0], capsq);
-
- board[capsq] = make_piece(them, st->capturedType);
-
- // Update piece count
- pieceCount[them][st->capturedType]++;
-
- // Update piece list, add a new captured piece in capsq square
- index[capsq] = pieceCount[them][st->capturedType] - 1;
- pieceList[them][st->capturedType][index[capsq]] = capsq;
- }
-
- // Finally point our state pointer back to the previous state
- st = st->previous;
-
- assert(pos_is_ok());
-}
-
-