FlutterAdvanced 4 min read

AI level generation for Flutter games: validate layouts before playing

Turn generated game-level JSON into a bounded, reachable grid with a safe fallback, using a complete Dart validation example.

On this page

A generated level is proposed data. It becomes playable only after the game validates its dimensions, supported tiles, start and exit positions, and a path between them. Whether the proposal comes from a language model, a procedural generator or a level editor, the same validator should run.

For this exercise, a level is a small grid: # means wall, . means open ground, S means start and E means exit. Movement uses four directions. There are no keys or teleporters, so reachability is a simple breadth-first search.

Step 1: request a constrained format

Ask your assistant or backend model for a JSON object with only a rows array, at most 12 rows and at most 20 columns. Specify one start and one exit. Do not ask for executable Dart code or allow the response to select files and package names. Requesting JSON helps consistency, but validation is still required.

For a server-backed generator, enforce a request/response size limit before decoding. The following program uses a fixed sample so it can run in the browser without an account or network request.

Step 2: validate the proposed grid

main.dart
import 'dart:convert';

bool playable(Object? input) {
  if (input is! Map<String, dynamic> || input['rows'] is! List) return false;
  final raw = input['rows'] as List;
  if (raw.isEmpty || raw.length > 12 || raw.any((r) => r is! String)) return false;
  final rows = raw.cast<String>();
  final width = rows.first.length;
  if (width == 0 || width > 20 || rows.any((r) => r.length != width)) return false;
  int? start, exit;
  for (var y = 0; y < rows.length; y++) {
    for (var x = 0; x < width; x++) {
      final tile = rows[y][x];
      if (!['#', '.', 'S', 'E'].contains(tile)) return false;
      if (tile == 'S') { if (start != null) return false; start = y * width + x; }
      if (tile == 'E') { if (exit != null) return false; exit = y * width + x; }
    }
  }
  if (start == null || exit == null) return false;
  final queue = <int>[start];
  final seen = <int>{start};
  for (var head = 0; head < queue.length; head++) {
    final current = queue[head];
    if (current == exit) return true;
    final x = current % width, y = current ~/ width;
    for (final (nx, ny) in [(x+1,y), (x-1,y), (x,y+1), (x,y-1)]) {
      if (nx < 0 || ny < 0 || nx >= width || ny >= rows.length) continue;
      final next = ny * width + nx;
      if (rows[ny][nx] != '#' && seen.add(next)) queue.add(next);
    }
  }
  return false;
}

void main() {
  final candidates = [
    '{"rows":["S..","##.","..E"]}',
    '{"rows":["S#E","###","..."]}',
    '{"rows":["SS.","..E"]}'
  ];
  for (final source in candidates) {
    final accepted = playable(jsonDecode(source));
    print(accepted ? 'Use generated level' : 'Use reviewed fallback');
  }
}

Only the first candidate is accepted. The second has an unreachable exit. The third has two starts. The queue explores each reachable cell once because seen.add rejects repeats. The dimension limits bound the search to at most 240 cells.

Step 3: turn accepted data into game components

Create walls and the player only after the validator returns true. Convert a cell (x, y) to world coordinates using one tile size and the same origin for rendering and collision. The coordinates lesson explains this conversion. Keep a reviewed local level ready when generation fails, times out or exceeds a quota.

Reachability alone does not prove fun or fairness. A narrow corridor might be impossible for the player’s actual collision radius, and enemy placement can block an otherwise open path. Validate those constraints against your game’s movement model before shipping generated levels.

Practice and verification

Add cases with an unknown tile, uneven row lengths, a missing exit and an oversized level. Confirm they all select the fallback. Then add a minimum path-length rule and explain why it changes game difficulty. If using runtime generation, perform it between rounds rather than inside update(dt), and connect the tested timeout pattern before adding a real service.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.