makeMove method

dynamic makeMove(
  1. Move move
)

Implementation

makeMove(Move move) {
  Color us = turn;
  Color them = swapColor(us);
  push(move);

  board[move.to] = board[move.from];
  board[move.from] = null;

  /* if ep capture, remove the captured pawn */
  if ((move.flags & BITS_EP_CAPTURE) != 0) {
    if (turn == BLACK) {
      board[move.to - 16] = null;
    } else {
      board[move.to + 16] = null;
    }
  }

  /* if pawn promotion, replace with new piece */
  if ((move.flags & BITS_PROMOTION) != 0) {
    board[move.to] = Piece(move.promotion!, us);
  }

  /* if we moved the king */
  if (board[move.to]!.type == KING) {
    kings[board[move.to]!.color] = move.to;

    /* if we castled, move the rook next to the king */
    if ((move.flags & BITS_KSIDE_CASTLE) != 0) {
      int castlingTo = move.to - 1;
      int castlingFrom = move.to + 1;
      board[castlingTo] = board[castlingFrom];
      board[castlingFrom] = null;
    } else if ((move.flags & BITS_QSIDE_CASTLE) != 0) {
      int castlingTo = move.to + 1;
      int castlingFrom = move.to - 2;
      board[castlingTo] = board[castlingFrom];
      board[castlingFrom] = null;
    }

    /* turn off castling */
    castling[us] = 0;
  }

  /* turn off castling if we move a rook */
  if (castling[us] != 0) {
    for (int i = 0; i < ROOKS[us]!.length; i++) {
      if (move.from == ROOKS[us]![i]['square'] &&
          ((castling[us] & ROOKS[us]![i]['flag']) != 0)) {
        castling[us] ^= ROOKS[us]![i]['flag'];
        break;
      }
    }
  }

  /* turn off castling if we capture a rook */
  if (castling[them] != 0) {
    for (int i = 0, len = ROOKS[them]!.length; i < len; i++) {
      if (move.to == ROOKS[them]![i]['square'] &&
          ((castling[them] & ROOKS[them]![i]['flag']) != 0)) {
        castling[them] ^= ROOKS[them]![i]['flag'];
        break;
      }
    }
  }

  /* if big pawn move, update the en passant square */
  if ((move.flags & BITS_BIG_PAWN) != 0) {
    if (turn == BLACK) {
      epSquare = move.to - 16;
    } else {
      epSquare = move.to + 16;
    }
  } else {
    epSquare = EMPTY;
  }

  /* reset the 50 move counter if a pawn is moved or a piece is captured */
  if (move.piece == PAWN) {
    halfMoves = 0;
  } else if ((move.flags & (BITS_CAPTURE | BITS_EP_CAPTURE)) != 0) {
    halfMoves = 0;
  } else {
    halfMoves++;
  }

  if (turn == BLACK) {
    moveNumber++;
  }
  turn = swapColor(turn);
}