random_start_pieces method Null safety

List<PieceType> random_start_pieces()

Implementation

static List<PieceType> random_start_pieces() {
  List<int> squares = Iterable<int>.generate(8).toList();
  List<PieceType?> pieces = List.filled(8, null);
  Random r = Random();

  void placePiece(int sq, PieceType pt) {
    pieces[sq] = pt;
    squares.remove(sq);
  }

  int randomSquare() => squares[r.nextInt(squares.length)];

  // Place bishops
  List<int> bishops = [r.nextInt(4) * 2, r.nextInt(4) * 2 +1 ];
  for(int x in bishops) placePiece(x, PieceType.BISHOP);

  // Place queen
  placePiece(randomSquare(), PieceType.QUEEN);

  // Place knights
  for(int _ in [0,0]) placePiece(randomSquare(), PieceType.KNIGHT);

  // Place rooks and king
  placePiece(squares.first, PieceType.ROOK);
  placePiece(squares.first, PieceType.KING);
  placePiece(squares.first, PieceType.ROOK);

  return pieces.map<PieceType>((p) => p!).toList();
}