generateFen method Null safety

String generateFen()

Returns a FEN String representing the current position

Implementation

String generateFen() {
  int empty = 0;
  String fen = '';

  for (int i = SQUARES_A8; i <= SQUARES_H1; i++) {
    if (board[i] == null) {
      empty++;
    } else {
      if (empty > 0) {
        fen += empty.toString();
        empty = 0;
      }
      Color color = board[i]!.color;
      PieceType type = board[i]!.type;

      fen += (color == WHITE) ? type.toUpperCase() : type.toLowerCase();
    }

    if (((i + 1) & 0x88) != 0) {
      if (empty > 0) {
        fen += empty.toString();
      }

      if (i != SQUARES_H1) {
        fen += '/';
      }

      empty = 0;
      i += 8;
    }
  }

  String cflags = '';
  if ((castling[WHITE] & BITS_KSIDE_CASTLE) != 0) {
    cflags += 'K';
  }
  if ((castling[WHITE] & BITS_QSIDE_CASTLE) != 0) {
    cflags += 'Q';
  }
  if ((castling[BLACK] & BITS_KSIDE_CASTLE) != 0) {
    cflags += 'k';
  }
  if ((castling[BLACK] & BITS_QSIDE_CASTLE) != 0) {
    cflags += 'q';
  }

  /* do we have an empty castling flag? */
  if (cflags == "") {
    cflags = '-';
  }
  String epflags = (epSquare == EMPTY) ? '-' : algebraic(epSquare);
  String turnStr = (turn == Color.WHITE) ? 'w' : 'b';

  return [fen, turnStr, cflags, epflags, halfMoves, moveNumber].join(' ');
}