Board.parseFen constructor

Board.parseFen(
  1. String boardFen
)

Parse the board part of a FEN string and returns a Board.

Throws a FenException if the provided FEN string is not valid.

Implementation

factory Board.parseFen(String boardFen) {
  Board board = Board.empty;
  int rank = 7;
  int file = 0;
  for (int i = 0; i < boardFen.length; i++) {
    final c = boardFen[i];
    if (c == '/' && file == 8) {
      file = 0;
      rank--;
    } else {
      final code = c.codeUnitAt(0);
      if (code < 57) {
        file += code - 48;
      } else {
        if (file >= 8 || rank < 0) {
          throw const FenException(IllegalFenCause.board);
        }
        final square = Square(file + rank * 8);
        final promoted = i + 1 < boardFen.length && boardFen[i + 1] == '~';
        final piece = _charToPiece(c, promoted);
        if (piece == null) throw const FenException(IllegalFenCause.board);
        if (promoted) i++;
        board = board.setPieceAt(square, piece);
        file++;
      }
    }
  }
  if (rank != 0 || file != 8) throw const FenException(IllegalFenCause.board);
  return board;
}