Flutter로 단어 퍼즐 빌드

1. 소개

빌드할 항목

세계에서 가장 큰 크로스워드 퍼즐을 만들 수 있는지 묻는 질문을 받았다고 상상해 보세요. 고전적인 AI 검색 기법을 떠올리며 Flutter를 사용하여 계산 집약적인 문제에 대한 알고리즘 솔루션을 탐색하면서도 UI를 60fps로 반응성 있게 유지할 수 있는지 궁금해합니다.

이 Codelab에서는 Google Antigravity와 협력하여 알고리즘 기반 크로스워드 생성기를 빌드하고 이를 플레이 가능한 단어 퍼즐 게임으로 변환합니다. 유효한 크로스워드 퍼즐의 정의는 다양하며, 여기에서 살펴보는 기법은 내 규칙에 맞는 퍼즐을 생성하는 데 도움이 됩니다.

십자말풀이가 생성되는 애니메이션

십자말풀이 생성기를 기반으로 Android, iOS, Windows, macOS, Linux에서 실행되는 대화형 단어 퍼즐 게임을 만듭니다.

Pixel Fold 에뮬레이터에서 십자말풀이를 푸는 모습

학습 여정

이 Codelab에서는 크로스워드 생성기와 퍼즐 게임을 빌드하는 과정을 단계별로 안내합니다.

  1. Flutter 환경 설정 - 대상 플랫폼에 맞게 Flutter SDK와 Google Antigravity를 구성합니다.
  2. 프로젝트 만들기 - Antigravity에 built_value, flutter_riverpod, two_dimensional_scrollables, material_ui를 사용하여 빈 Flutter 프로젝트를 스캐폴딩하라는 프롬프트를 표시합니다.
  3. 단어 추가 - SOWPODS 단어 목록 애셋을 번들로 묶고 비동기 Riverpod 제공자를 사용하여 시작 시 적극적으로 로드합니다.
  4. 그리드에 단어 표시 - 변경할 수 없는 built_value 그리드 모델을 정의하고 Riverpod의 select 필터를 사용하여 2D TableView로 렌더링합니다.
  5. 제약 조건 적용 - compute를 사용하여 연동 십자말풀이 규칙을 검증하고 후보 배치를 UI 스레드에서 이동합니다.
  6. 작업 큐 관리 - 무작위 배치를 열린 교차점을 타겟팅하는 백트래킹 WorkQueue로 대체합니다.
  7. 통계 표시 - 플로팅 HUD 오버레이에서 실시간 생성 측정항목, 경과 시간, 예상 남은 시간을 도출합니다.
  8. 스레드를 사용한 병렬화 - 활성 검색 셀을 시각화하고 구성 가능한 백그라운드 작업자 격리 풀에서 생성을 확장합니다.
  9. 게임으로 변환 - 완성된 십자말풀이를 대화형 객관식 단어 퍼즐 게임으로 변환합니다.

학습할 내용

  • Google Antigravity와 협업하여 컴퓨팅 집약적인 Flutter 애플리케이션과 단어 퍼즐 게임을 반복적으로 빌드하고 맞춤설정하는 방법
  • Flutter의 compute 함수와 Riverpod의 select 리빌드 필터를 사용하여 Flutter의 렌더링 루프를 차단하지 않고 백그라운드 격리를 사용하여 비용이 많이 드는 계산을 실행하는 방법
  • built_value 및 built_collection를 사용하여 변경 불가능한 데이터 구조를 모델링하여 깊이 우선 검색 및 백트래킹과 같은 검색 기반의 전통적인 AI(GOFAI) 기법을 구현하는 방법
  • two_dimensional_scrollables 패키지를 사용하여 대규모 2D 그리드를 원활하게 표시하는 방법

기본 요건

  • Flutter 및 Dart 문법에 관한 기본 지식

2. Flutter 환경 설정

편집자

이 Codelab에서는 Google Antigravity를 AI 우선 개발 환경으로 사용합니다. 각 단계에서 Antigravity에 앱의 모델, 격리, 제공자, 위젯을 생성하거나 발전시키도록 프롬프트를 입력하고, 생성된 코드의 주요 패턴을 검사하고, 원하는 경우 알고리즘 또는 UI 변형을 살펴봅니다.

Flutter 설치

Flutter SDK 설치에 관한 가장 최신 안내는 docs.flutter.dev에서 항상 확인할 수 있습니다.

이 Codelab에서는 다음 소프트웨어를 설치합니다.

  1. Flutter SDK
  2. 공식 Dart 및 Flutter 플러그인이 사용 설정된 Google Antigravity(플러그인 마켓플레이스의 Build with Google 섹션에서 사용 가능)
  3. 선택한 개발 타겟의 컴파일러 소프트웨어(예: Windows를 타겟팅하는 Visual Studio, macOS 또는 iOS를 타겟팅하는 Xcode, Android를 타겟팅하는 Android 스튜디오)

3. 프로젝트 만들기

종속 항목 이해

프로젝트를 만들기 전에 십자말풀이 생성기를 구동하는 핵심 패키지를 검토합니다.

  • built_value 및 built_collection: 파생 인스턴스 간에 메모리를 공유하는 변경 불가능한 값 유형과 컬렉션을 생성합니다. 이는 백트래킹 검색과 격리 간에 상태를 안전하게 전달하는 데 필수적입니다.
  • flutter_riverpod, riverpod, riverpod_annotation: select()를 사용하여 반응형 상태 관리, 스트림 제공자, 세분화된 재빌드 필터링을 제공합니다.
  • two_dimensional_scrollables: TableView.builder를 사용하여 두 축에서 큰 2D 그리드를 지연 렌더링합니다.
  • characters: 문자소 클러스터 문자열 반복을 정확하게 처리합니다.
  • intl: 통계 오버레이에서 큰 단어 및 셀 수를 형식 지정합니다.

Antigravity에 프로젝트를 만들라는 프롬프트 입력

  1. Google Antigravity를 실행하고 프로젝트를 빌드할 빈 디렉터리를 엽니다. 홈 디렉터리의 폴더 또는 C:\src\와 같이 승격된 권한이 필요하지 않거나 공백이 포함되지 않은 경로를 선택합니다.
  2. Antigravity 에이전트 채팅 패널에서 다음 프롬프트를 전송하여 Flutter 프로젝트를 만들고, 종속 항목을 추가하고, 초기 앱을 연결합니다.
Create a new empty Flutter project named `generate_crossword` targeting `macos,linux,windows,ios,android`. Add the dependencies `built_collection`, `built_value`, `characters`, `flutter_riverpod`, `intl`, `material_ui`, `riverpod`, `riverpod_annotation`, and `two_dimensional_scrollables`, along with the dev dependencies `build_runner`, `built_value_generator`, and `riverpod_generator`. Configure `analysis_options.yaml` to disable `strict-inference` and `prefer_const_constructors` and exclude `lib/*.g.dart`. Finally, update `lib/main.dart` (importing `package:material_ui/material_ui.dart`) to run a `MaterialApp` inside a `ProviderScope` with a `Colors.blueGrey` seed light theme, `debugShowCheckedModeBanner: false`, and a `Scaffold` showing `'Hello, World!'` centered in 24px text.

생성된 코드 이해

Antigravity는 flutter create --empty를 사용하여 프로젝트를 스캐폴딩하고, pubspec.yaml에 런타임 및 코드 생성 패키지를 설치하고, lib/main.dart의 Riverpod ProviderScope에 MaterialApp를 래핑합니다.

void main() {
  runApp(
    ProviderScope(
      child: MaterialApp(
        title: 'Crossword Builder',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          colorSchemeSeed: Colors.blueGrey,
          brightness: Brightness.light,
        ),
        home: Scaffold(
          body: Center(
            child: Text('Hello, World!', style: TextStyle(fontSize: 24)),
          ),
        ),
      ),
    ),
  );
}

앱 실행 및 테스트

선택한 대상 기기에서 앱을 실행합니다. 화면 중앙에 Hello, World!가 표시된 창이 나타납니다.

중앙에 'Hello, World!'라는 단어가 있는 앱 창

4. 단어 추가

십자말풀이 구성요소

십자말풀이는 기본적으로 격자판에 가로세로로 맞물리도록 배열된 단어 목록입니다. 한 단어를 풀면 교차하는 단어에 대한 힌트를 얻을 수 있습니다. 시작 단어 목록으로 좋은 것은 Peter Norvig의 자연어 코퍼스 데이터 페이지에 있는 SOWPODS 목록(267,750개 단어)입니다.

이 단계에서는 Antigravity에 단어 목록을 assets/words.txt에 다운로드하고, lib/providers.dart에서 생성된 Riverpod 제공자를 사용하여 노출하고, 앱 시작 시 해당 제공자를 적극적으로 초기화하고, 스크롤하는 ListView에 267,750개 이상의 모든 단어를 렌더링하라는 프롬프트를 표시합니다.

Antigravity에 단어 목록을 로드하고 표시하라는 프롬프트 입력

Antigravity에서 다음 프롬프트를 전송합니다.

Download the SOWPODS word list from `https://norvig.com/ngrams/sowpods.txt` into `assets/words.txt` and declare `assets/words.txt` under `flutter: assets:` in `pubspec.yaml`. Create `lib/providers.dart` (importing `package:riverpod_annotation/riverpod_annotation.dart` with `part 'providers.g.dart';`) and define a `@riverpod Future<BuiltSet<String>> wordList(Ref ref)` provider that loads `assets/words.txt` using `rootBundle.loadString`, splits lines with `LineSplitter`, and rebuilds a `BuiltSet<String>` of lowercase trimmed `[a-z]` words longer than 2 characters. Run `build_runner` to generate `lib/providers.g.dart`. Then create `CrosswordGeneratorApp` in `lib/widgets/crossword_generator_app.dart` (importing `package:material_ui/material_ui.dart`) wrapped in a private `_EagerInitialization` `ConsumerWidget` that watches `wordListProvider`, with an `AppBar` titled `'Crossword Generator'` and a `Consumer` body that uses `wordListAsync.when` to display a `ListView.builder` of words, an error message, or a `CircularProgressIndicator`. Update `lib/main.dart` to use `CrosswordGeneratorApp()` as `home`.

생성된 코드 이해

단어 목록을 변경 불가능한 BuiltSet로 필터링

lib/providers.dart에서 @riverpod 주석은 riverpod_generator의 코드 생성을 위해 wordList를 표시합니다. assets/words.txt를 비동기식으로 로드하고 항목을 두 글자보다 긴 소문자 a-z 문자열로 정규화합니다.

@riverpod
Future<BuiltSet<String>> wordList(Ref ref) async {
  final re = RegExp(r'^[a-z]+$');
  final words = await rootBundle.loadString('assets/words.txt');
  return const LineSplitter()
      .convert(words)
      .toBuiltSet()
      .rebuild(
        (b) => b
          ..map((word) => word.toLowerCase().trim())
          ..where((word) => word.length > 2)
          ..where((word) => re.hasMatch(word)),
      );
}

즉시 제공자 초기화 및 AsyncValue.when

Riverpod 제공자는 기본적으로 지연 로드됩니다. 처음 읽을 때만 로드를 시작합니다. lib/widgets/crossword_generator_app.dart에서 _EagerInitialization는 위젯 트리의 루트 근처에서 wordListProvider를 감시하므로 시작 시 사전이 즉시 로드되기 시작합니다(제공자의 즉시 초기화 참고).

Scaffold 본문 내에서 wordListProvider를 감시하면 AsyncValue>가 반환됩니다. when 메서드는 data, error, loading 상태를 처리하여 비동기 Future와 동기 build 메서드를 연결합니다.

final wordListAsync = ref.watch(wordListProvider);
return wordListAsync.when(
  data: (wordList) => ListView.builder(
    itemCount: wordList.length,
    itemBuilder: (context, index) {
      return ListTile(title: Text(wordList.elementAt(index)));
    },
  ),
  error: (error, stackTrace) => Center(child: Text('$error')),
  loading: () => Center(child: CircularProgressIndicator()),
);

앱 실행 및 테스트

새 애셋을 추가하고 main()를 업데이트했으므로 핫 다시 시작을 실행합니다. 267,000개가 넘는 사전 단어가 스크롤 가능한 목록으로 표시됩니다.

'Crossword Generator'라는 제목과 스크롤 가능한 단어 목록이 있는 앱 창

5. 단어를 그리드로 표시하기

이 단계에서는 built_value 및 built_collection를 사용하여 lib/model.dart에서 십자말풀이의 핵심 변경 불가능한 데이터 구조를 정의하고, lib/providers.dart에서 무작위로 배치된 단어를 스트리밍하고, two_dimensional_scrollables에서 TableView.builder를 사용하여 2D 문자 그리드를 렌더링합니다.

Antigravity에 프롬프트를 입력하여 그리드 모델과 TableView UI 빌드

Antigravity에서 다음 프롬프트를 전송합니다.

Create `lib/model.dart` (with `part 'model.g.dart';`) defining immutable `built_value` classes for the crossword grid:
- `Location`: 0-based `x` and `y` getters, directional getters (`left`, `right`, `up`, `down`), offset methods (`leftOffset`, `rightOffset`, `upOffset`, `downOffset`), `prettyPrint()`, and `Location.at(int x, int y)`.
- `Direction`: enum with `across` and `down` (`toString() => name`).
- `CrosswordWord`: `word`, `location`, `direction`, `static int locationComparator(CrosswordWord a, CrosswordWord b)`, and `CrosswordWord.word(...)` factory.
- `CrosswordCharacter`: `character`, optional `acrossWord` and `downWord`, and `CrosswordCharacter.character(...)` factory.
- `Crossword`: `width`, `height`, `BuiltList<CrosswordWord> get words`, `BuiltMap<Location, CrosswordCharacter> get characters`, `Crossword addWord({required Location location, required String word, required Direction direction})`, a `@BuiltValueHook(finalizeBuilder: true) static void _fillCharacters(CrosswordBuilder b)` hook that populates `characters` from `words`, `prettyPrintCrossword()`, and `Crossword.crossword(...)` factory.
- Top-level `@SerializersFor([Location, Crossword, CrosswordWord, CrosswordCharacter]) final Serializers serializers = _$serializers;`.

Next, create `lib/utils.dart` with a `RandomElements<E> on BuiltSet<E>` extension (`E randomElement()`). In `lib/providers.dart`, add a `CrosswordSize` enum (`small` 20x11, `medium` 40x22, `large` 80x44, `xlarge` 160x88, `xxlarge` 500x500 with `label => '$width x $height'`), a `@Riverpod(keepAlive: true) class Size` notifier defaulting to `CrosswordSize.medium` with `setSize(CrosswordSize size)`, and a `@riverpod Stream<model.Crossword> crossword(Ref ref)` generator that places random words at random locations and directions every 100ms until 80% of cells are filled. Run `build_runner`. Finally, create `CrosswordWidget` in `lib/widgets/crossword_widget.dart` (importing `package:material_ui/material_ui.dart`) using `TableView.builder` (with 32px `FixedTableSpanExtent` spans and per-cell `Consumer`s watching `crosswordProvider.select(...)` for that cell's `Location`), and update `lib/widgets/crossword_generator_app.dart` to display `CrosswordWidget` in the body and a `_CrosswordGeneratorMenu` (`MenuAnchor`) in `AppBar.actions` to switch `CrosswordSize`.

생성된 코드 이해

@BuiltValueHook로 문자 맵 마무리

lib/model.dart에서 Crossword는 UI에서 빠른 (x, y) 조회를 위해 BuiltList 및 BuiltMap를 저장합니다. @BuiltValueHook(finalizeBuilder: true)로 주석이 지정된 _fillCharacters은 CrosswordBuilder가 새 Crossword 인스턴스를 빌드할 때마다 characters 맵을 자동으로 채웁니다.

@BuiltValueHook(finalizeBuilder: true)
static void _fillCharacters(CrosswordBuilder b) {
  b.characters.clear();

  for (final word in b.words.build()) {
    for (final (idx, character) in word.word.characters.indexed) {
      switch (word.direction) {
        case Direction.across:
          b.characters.updateValue(
            word.location.rightOffset(idx),
            (b) => b.rebuild((bInner) => bInner.acrossWord.replace(word)),
            ifAbsent: () => CrosswordCharacter.character(
              acrossWord: word,
              character: character,
            ),
          );
        case Direction.down:
          b.characters.updateValue(
            word.location.downOffset(idx),
            (b) => b.rebuild((bInner) => bInner.downWord.replace(word)),
            ifAbsent: () => CrosswordCharacter.character(
              downWord: word,
              character: character,
            ),
          );
      }
    }
  }
}

async*로 중간 결과 스트리밍

lib/providers.dart에서 crossword는 Stream를 반환하는 async* 생성기 함수입니다. 함수 상단에서 sizeProvider와 wordListProvider를 모두 감시하므로 사용자가 메뉴에서 새 그리드 크기를 선택할 때마다 Riverpod가 자동으로 스트림을 취소하고 다시 시작합니다.

Consumer 및 select()를 사용한 셀 수준 재빌드 필터링

lib/widgets/crossword_widget.dart에서 단어가 추가될 때마다 전체 TableView를 다시 빌드하면 CPU 주기가 크게 낭비됩니다. 대신 각 TableViewCell는 하위 요소를 Consumer로 래핑하고 crosswordProvider.select(...)를 사용하여 특정 location에서 CrosswordCharacter?만 감시합니다.

TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) {
  final location = Location.at(vicinity.column, vicinity.row);

  return TableViewCell(
    child: Consumer(
      builder: (context, ref, _) {
        final character = ref.watch(
          crosswordProvider.select(
            (crosswordAsync) => crosswordAsync.when(
              data: (crossword) => crossword.characters[location],
              error: (error, stackTrace) => null,
              loading: () => null,
            ),
          ),
        );
        // ...

새 Crossword가 생성될 때 문자가 실제로 변경된 셀만 다시 빌드됩니다.

앱 실행 및 테스트

앱을 핫 리스타트합니다. 그리드를 채우는 문자와 그리드 크기를 전환할 수 있는 오른쪽 상단의 설정 톱니바퀴 메뉴가 표시됩니다.

Crossword Generator라는 제목의 앱 창과 겹치는 단어로 배치된 문자 그리드

현재 단어는 검증 없이 무작위 좌표에 배치되므로 서로 혼란스럽게 덮어씁니다. 다음 단계에서는 실제 크로스워드 규칙을 적용합니다.

6. 제약조건 적용

변경하는 사항 및 이유

현재 Crossword.addWord는 모든 좌표에서 모든 단어를 허용합니다. 유효한 영어 스타일 크로스워드를 생성하려면 Crossword에서 다음을 확인해야 합니다.

  1. 그리드에 중복된 단어가 없습니다.
  2. 모든 문자는 [0, width)~[0, height)자(영문 기준)여야 합니다.
  3. 모든 문자는 가로 단어, 세로 단어 또는 두 단어가 동일한 문자를 공유하는 유효한 교차점에 속합니다.
  4. 세로로 인접한 문자는 동일한 downWord에 속하고 가로로 인접한 문자는 동일한 acrossWord에 속합니다(의도하지 않은 두 글자 충돌 방지).
  5. 첫 번째 단어 이후의 모든 새 단어는 하나 이상의 기존 단어와 겹칩니다.

기본 isolate에서 이러한 제약 조건을 수천 번 확인하면 Flutter의 60fps 렌더링 루프가 차단됩니다. 전용 lib/isolates.dart 라이브러리에서 Flutter의 compute 함수를 사용하여 후보 평가를 백그라운드 격리로 오프로드합니다.

Antigravity에 백그라운드 격리에서 단어 배치를 검증하라는 메시지 표시

Antigravity에서 다음 프롬프트를 전송합니다.

Update `Crossword` in `lib/model.dart` to add a `bool get valid` getter that enforces English crossword constraints (no duplicate words, all characters within grid bounds and part of at least one word, vertical neighbors sharing the same `downWord`, and horizontal neighbors sharing the same `acrossWord`). Update `Crossword.addWord` to return `Crossword?`, returning `null` if the word is already in the crossword, conflicts with an existing character or same-direction word, fails to overlap an existing word when `words.isNotEmpty`, or produces an invalid candidate `Crossword`. Then create `lib/isolates.dart` with `Stream<Crossword> exploreCrosswordSolutions({required Crossword crossword, required BuiltSet<String> wordList}) async*` that uses `compute` to test random candidate word placements in a background isolate and yields valid `Crossword` updates until 80% of cells are filled. Update `crossword` in `lib/providers.dart` to delegate to `exploreCrosswordSolutions`, and run `build_runner`.

생성된 코드 이해

Crossword.addWord에서 후보 단어 검증 중

lib/model.dart에서 addWord는 이제 Crossword?를 반환합니다. Crossword를 다시 빌드하기 전에 모든 문자가 빈 셀에 배치되거나 수직 방향으로 교차하는 단어의 문자와 일치하는지 확인하고 candidate.valid를 확인합니다.

final candidate = rebuild(
  (b) => b
    ..words.add(
      CrosswordWord.word(
        word: word,
        direction: direction,
        location: location,
      ),
    ),
);

if (candidate.valid) {
  return candidate;
} else {
  return null;
}

lib/isolates.dart가 lib/providers.dart에서 분리된 이유

백그라운드 isolate는 Riverpod의 Ref 또는 StreamProviderElement와 같이 기본 isolate에 연결된 변경 가능한 객체를 공유할 수 없습니다. @riverpod Stream crossword(Ref ref) 제공자 함수 내에서 직접 클로저를 사용하여 compute를 호출하면 Dart는 주변 제공자 컨텍스트를 캡처하고 전송할 수 없는 객체 오류를 발생시킵니다.

Invalid argument(s): Illegal argument in isolate message: object is unsendable - Library:'dart:async' Class: _Future
 <- Instance of 'AutoDisposeStreamProviderElement<Crossword>'

exploreCrosswordSolutions를 lib/isolates.dart로 추출하면 compute에 전달된 클로저가 변경 불가능하고 isolate-sendable 값(Crossword 및 Dart 레코드 (word, direction, location))만 캡처합니다.

var candidate = await compute(((String, Direction, Location) wordToAdd) {
  final (word, direction, location) = wordToAdd;
  return crossword.addWord(
    word: word,
    direction: direction,
    location: location,
  );
}, (word, direction, location));

앱 실행 및 테스트

앱을 핫 리스타트합니다. 이제 UI가 반응형으로 유지되면서 단어가 그리드에서 가로 및 세로로 올바르게 연동됩니다.

가로 및 세로로 단어가 배치되어 유효한 지점에서 교차하는 십자말풀이 생성기 앱 창

생성기는 여전히 무작위 좌표와 무작위 단어를 추측하므로 단어를 천천히 배치합니다. 다음 단계에서는 작업 대기열을 사용하여 검색을 안내합니다.

7. 작업 대기열 관리

검색 전략 이해하기

전체 보드에서 무작위 좌표를 추측하는 대신 십자말풀이 생성을 가이드형 백트래킹 검색으로 전환할 수 있습니다.

  1. WorkQueue에서 단일 단어에만 속하고 수직 배치를 차단하는 평행 인접 셀이 없는 열린 문자 셀을 추적합니다.
  2. locationsToTry에서 후보 위치를 선택하고 해당 교차점에 이미 있는 문자가 포함된 단어로 candidateWords를 필터링합니다.
  3. 교차점에 일치하는 단어를 배치해 보세요. 단어가 맞으면 새 십자말풀이로 WorkQueue를 업데이트합니다. 1,000번 시도한 후에도 맞는 단어가 없으면 해당 위치를 알려진 badLocation로 표시하고 큐에서 삭제합니다.

Antigravity에서 다음 프롬프트를 전송합니다.

Add a `WorkQueue` `built_value` class to `lib/model.dart` (and register it in `@SerializersFor`) with `Crossword get crossword`, `BuiltMap<Location, Direction> get locationsToTry`, `BuiltSet<Location> get badLocations`, `BuiltSet<String> get candidateWords`, `bool get isCompleted => locationsToTry.isEmpty || candidateWords.isEmpty`, a `static WorkQueue from({required Crossword crossword, required Iterable<String> candidateWords, required Location startLocation})` builder that seeds `(0, 0)` when empty or finds eligible single-word intersection cells when non-empty, `WorkQueue remove(Location location)`, and `WorkQueue updateFrom(Crossword crossword)`. Add a `DurationFormat on Duration` extension (`String get formatted`) in `lib/utils.dart` using a record pattern switch. Finally, update `exploreCrosswordSolutions` in `lib/isolates.dart` to drive generation using `WorkQueue`, filtering `candidateWords` to those containing the target character at the chosen location (trying up to 1,000 shuffled words per `compute` call) and logging the total generation time with `formatted`. Run `build_runner`.

생성된 코드 이해

WorkQueue.from에서 열린 교차점 식별

lib/model.dart에서 십자말풀이에 단어가 추가될 때마다 WorkQueue.from는 배치된 문자를 스캔하고, 이미 두 개의 교차 단어에 속하거나 평행 단어에 인접한 셀을 삭제하고, 나머지 셀을 교차 단어에 필요한 수직 Direction에 매핑합니다.

b.locationsToTry.addAll({
  location: switch ((character.acrossWord, character.downWord)) {
    (null, null) => throw StateError('Character is not part of a word'),
    (null, _) => Direction.across,
    (_, null) => Direction.down,
    (_, _) => throw StateError('Character is part of two words'),
  },
});

Dart 3 레코드 및 패턴 일치를 사용한 기간 형식 지정

lib/utils.dart에서 DurationFormat는 4개 요소 레코드 (inDays, inHours, inMinutes, inSeconds)에 대한 switch 표현식을 사용하여 인간이 읽을 수 있는 소요 시간 문자열을 생성합니다.

extension DurationFormat on Duration {
  String get formatted {
    final hours = inHours.remainder(24).toString().padLeft(2, '0');
    final minutes = inMinutes.remainder(60).toString().padLeft(2, '0');
    final seconds = inSeconds.remainder(60).toString().padLeft(2, '0');
    return switch ((inDays, inHours, inMinutes, inSeconds)) {
      (0, 0, 0, _) => '${inSeconds}s',
      (0, 0, _, _) => '$inMinutes:$seconds',
      (0, _, _, _) => '$inHours:$minutes:$seconds',
      _ => '$inDays days, $hours:$minutes:$seconds',
    };
  }
}

앱 실행 및 테스트

앱을 핫 리스타트합니다. 이제 십자말풀이 생성기가 유효한 교차점을 타겟팅하고 막다른 길을 정리하여 그리드를 훨씬 더 빠르게 채웁니다.

80x44 크로스워드 그리드가 빽빽하게 채워진 크로스워드 생성기

더 빠르게 만들 수 있나요? 먼저 알고리즘이 시간을 소비하는 위치를 확인할 수 있도록 실시간 원격 분석을 표시합니다.

8. 통계 표시

통계를 추가하는 이유

알고리즘을 최적화할 때 실시간 원격 분석을 사용하면 그리드가 얼마나 빨리 채워지는지, 후보 위치가 얼마나 남아 있는지, 병목 현상이 발생하는 위치를 확인할 수 있습니다. 이 단계에서는 lib/isolates.dart에서 Stream를 노출하고, lib/providers.dart에서 실시간 통계와 예상 남은 시간을 계산하고, 프레임별 TickerBuilder로 구동되는 전환 가능한 헤드업 디스플레이(CrosswordInfoWidget)를 렌더링합니다.

Antigravity에 생성 통계를 표시하라는 프롬프트 입력

Antigravity에서 다음 프롬프트를 전송합니다.

Add a `DisplayInfo` `built_value` class to `lib/model.dart` (and add it to `@SerializersFor`) with `wordsInGridCount`, `candidateWordsCount`, `locationsToExploreCount`, `knownBadLocationsCount`, `gridFilledPercentage`, a `DisplayInfo.from({required WorkQueue workQueue})` factory using `NumberFormat.decimalPattern()` from `package:intl/intl.dart`, and `static DisplayInfo get empty`. Update `exploreCrosswordSolutions` in `lib/isolates.dart` to return `Stream<WorkQueue>` and yield `workQueue` on each iteration. In `lib/providers.dart` (importing `package:riverpod/riverpod.dart` for `select`), replace `crossword` with `@riverpod Stream<model.WorkQueue> workQueue(Ref ref)` and add `@Riverpod(keepAlive: true)` notifiers `StartTime`, `EndTime`, and `ShowDisplayInfo`, plus `@riverpod Duration expectedRemainingTime(Ref ref)` (using `_estimatedTotalCoverage = 0.54`) and `@riverpod class DisplayInfo` (watching `workQueueProvider.select(...)` and returning `model.DisplayInfo.from(workQueue: workQueue)` on `data` or `model.DisplayInfo.empty` on `error` or `loading`). Update `CrosswordWidget` to watch `workQueueProvider`. Then create `TickerBuilder` (`lib/widgets/ticker_builder.dart`) and `CrosswordInfoWidget` (`lib/widgets/crossword_info_widget.dart`, importing `package:material_ui/material_ui.dart`), and update `lib/widgets/crossword_generator_app.dart` to overlay `CrosswordInfoWidget` in a `Stack` when `showDisplayInfoProvider` is true and add a `'Display Info'` toggle to `_CrosswordGeneratorMenu`. Run `build_runner`.

생성된 코드 이해

@Riverpod(keepAlive: true)로 타이밍 상태 유지

사용자가 CrosswordInfoWidget를 숨기면 위젯 트리의 어떤 항목도 startTimeProvider 또는 endTimeProvider를 감시하지 않습니다. lib/providers.dart에서 StartTime, EndTime, ShowDisplayInfo에 @Riverpod(keepAlive: true) 주석을 추가하면 오버레이가 숨겨질 때 Riverpod가 상태를 자동으로 삭제하지 않습니다.

@Riverpod(keepAlive: true)
class StartTime extends _$StartTime {
  @override
  DateTime? build() => _start;

  DateTime? _start;

  void start() {
    _start = DateTime.now();
    ref.invalidateSelf();
  }
}

TickerBuilder를 사용하여 실시간 경과 시간 표시

lib/widgets/ticker_builder.dart에서 TickerBuilder는 SingleTickerProviderStateMixin를 사용하여 생성이 진행되는 동안 모든 프레임에서 재빌드를 트리거합니다. lib/widgets/crossword_info_widget.dart에서 (startTime, endTime)에 대한 switch 표현식은 TickerBuilder를 패턴 일치와 페어링하므로 활성 생성 중에만 경과 시간 텍스트가 표시되고 endTime가 기록되면 자동으로 중지됩니다.

switch ((startTime, endTime)) {
  (null, _) => _CrosswordInfoRichText(
    label: 'Time elapsed',
    value: 'Not started yet',
  ),
  (DateTime start, null) => TickerBuilder(
    builder: (context) => _CrosswordInfoRichText(
      label: 'Time elapsed',
      value: DateTime.now().difference(start).formatted,
    ),
  ),
  (DateTime start, DateTime end) => _CrosswordInfoRichText(
    label: 'Completed in',
    value: end.difference(start).formatted,
  ),
},

앱 실행 및 테스트

앱을 핫 리스타트합니다. 이제 오른쪽 하단에 플로팅 통계 오버레이가 있고 설정 메뉴에 Display Info 전환 버튼이 있습니다.

오른쪽 하단에 플로팅 통계 오버레이가 있는 십자말풀이 생성기 앱 창

실행이 끝날 무렵에는 그리드가 거의 업데이트되지 않는 동안 숫자가 계속 변경됩니다. 단일 작업자가 남은 막다른 위치를 하나씩 제거하는 데 시간을 소비하고 있습니다. 다음으로 여러 격리에서 검색을 병렬화합니다.

9. 스레드로 병렬화

그리드가 채워지면 유효한 단어 배치가 부족해지고 단일 작업자 격리는 대부분의 시간을 막다른 길을 확인하는 데 보냅니다. 이 단계에서는 다음을 수행합니다.

  1. CrosswordWidget에서 AnimatedContainer 및 AnimatedDefaultTextStyle를 사용하여 현재 workQueue.locationsToTry(explorationCell)에 있는 셀을 강조 표시하여 검색 경계를 실시간으로 관찰할 수 있습니다.
  2. compute 및 candidateGeneratorFutures.wait를 사용하여 maxWorkerCount개의 동시 작업자 격리 풀에서 후보 검색을 팬아웃하도록 lib/isolates.dart를 리팩터링합니다.
  3. 설정 메뉴와 통계 오버레이에 BackgroundWorkers 선택기를 추가하여 1부터 128까지의 작업자 수를 실험할 수 있습니다.

Antigravity에 검색 셀을 강조 표시하고 작업자 격리를 병렬화하라는 프롬프트 작성

Antigravity에서 다음 프롬프트를 전송합니다.

Update `CrosswordWidget` in `lib/widgets/crossword_widget.dart` to watch whether each cell's `location` is in `workQueue.locationsToTry.keys` (`explorationCell`) and animate cell background and text colors using `AnimatedContainer` and `AnimatedDefaultTextStyle` (`Durations.extralong1`, `Curves.easeInOut`, inverting `primary` and `onPrimary` colors for exploration cells). Refactor `lib/isolates.dart` so `exploreCrosswordSolutions` accepts `required int maxWorkerCount` and calls `compute(_generate, (workQueue, maxWorkerCount))`, where top-level `_generate` dispatches up to `maxWorkerCount` parallel `compute(_generateCandidate, ...)` calls across shuffled locations, awaits `candidateGeneratorFutures.wait`, applies valid words, and removes failed locations (stopping each worker after 1,000 tries or 10 seconds). In `lib/providers.dart`, add the `BackgroundWorkers` enum (`one(1)` through `oneTwentyEight(128)`) and `@Riverpod(keepAlive: true) class WorkerCount` defaulting to `BackgroundWorkers.four`, pass `workers.count` to `exploreCrosswordSolutions`, display `'Max worker count'` in `CrosswordInfoWidget`, and add worker count radio options to `_CrosswordGeneratorMenu`. Run `build_runner`.

생성된 코드 이해

CrosswordWidget에서 검색의 새로운 지평을 열다

lib/widgets/crossword_widget.dart에서 각 셀은 두 번째 선택적 불리언(location가 현재 workQueue.locationsToTry.keys에 있는지 여부)을 감시하고 AnimatedContainer 및 AnimatedDefaultTextStyle를 사용하여 색상을 부드럽게 애니메이션 처리합니다.

실행 중인 Crossword Generator에서 탐색 대기 중인 위치를 나타내는 진한 파란색으로 강조 표시된 셀이 표시됩니다.

최상위 compute 함수를 사용한 팬아웃 및 팬인

lib/isolates.dart에서 _generate 및 _generateCandidate는 최상위 함수로 정의되므로 전송할 수 없는 상태를 캡처하지 않습니다. _generate는 최대 maxWorkerCount개의 셔플된 위치를 가져와 각 위치에 대해 compute(_generateCandidate, ...) future를 실행하고 candidateGeneratorFutures.wait를 사용하여 모든 future를 동시에 기다립니다.

for (final location in locations) {
  final direction = workQueue.locationsToTry[location]!;

  candidateGeneratorFutures.add(
    compute(_generateCandidate, (
      workQueue.crossword,
      workQueue.candidateWords,
      location,
      direction,
    )),
  );
}

final results = await candidateGeneratorFutures.wait;

(workQueue.crossword, workQueue.candidateWords, location, direction)과 같은 Dart 레코드를 전달하고 (Location, Direction, String?)를 전달하면 여러 매개변수가 compute의 단일 메시지 서명에 깔끔하게 조정됩니다.

앱 실행 및 테스트

앱을 핫 재시작하고 오른쪽 상단의 설정 메뉴를 열어 그리드 크기를 조정하고 통계 오버레이를 전환하고 백그라운드 작업자 격리 수를 전환합니다.

격자 크기, 정보 표시 전환, 작업자 수가 포함된 설정 메뉴가 표시된 Crossword Generator 생성 윈도우

10. 게임으로 만들기

빌드할 항목: 플레이 가능한 십자말풀이

이 마지막 단계에서는 크로스워드 생성기를 플레이 가능한 객관식 단어 퍼즐 게임으로 변환합니다.

  1. 퍼즐 생성: 다중 격리 생성기를 사용하여 백그라운드에서 완성된 크로스워드를 빌드하는 동시에 숨겨진 '•' 셀(CrosswordGeneratorWidget)의 펄스 그리드를 표시합니다.
  2. 대체 단어 선택 생성: 완성된 크로스워드의 각 단어에 대해 CrosswordPuzzleGame.from는 나머지 사전에서 정확히 동일한 길이의 무작위 오답 단어 4개를 선택합니다.
  3. 대화형 단어 배치: 셀을 탭하면 가로 및 세로 단어 후보가 나열된 MenuAnchor 컨텍스트 메뉴(CrosswordPuzzleWidget)가 열립니다. 플레이어는 어떤 순서로든 단어를 배치할 수 있으며(requireOverlap: false), 충돌하는 선택은 canSelectWord를 사용하여 자동으로 사용 중지됩니다.
  4. 승리 감지: 플레이어가 선택한 단어가 생성된 퍼즐의 단어 수와 일치하는 유효한 크로스워드를 형성하면 앱이 PuzzleCompletedWidget로 전환됩니다.

Antigravity에 프롬프트를 입력하여 생성기를 플레이 가능한 게임으로 변환하기

Antigravity에서 다음 프롬프트를 전송합니다.

Update `Crossword.addWord` in `lib/model.dart` to add `bool requireOverlap = true` (only requiring overlap when `requireOverlap` is true). Add the `CrosswordPuzzleGame` `built_value` class to `lib/model.dart` (and `@SerializersFor`) with `Crossword get crossword`, `BuiltMap<Location, BuiltMap<Direction, BuiltList<String>>> get alternateWords`, `BuiltList<CrosswordWord> get selectedWords`, `canSelectWord`, `selectWord`, `Crossword get crosswordFromSelectedWords`, `bool get solved`, and `factory CrosswordPuzzleGame.from({required Crossword crossword, required BuiltSet<String> candidateWords})` that picks 4 sorted alternate words of matching length for each word in the crossword.

Update `lib/providers.dart` to use `const backgroundWorkerCount = 4;` in `workQueue`, remove the statistics/timer/worker-count providers (and the `package:riverpod/riverpod.dart` import), and add `@riverpod class Puzzle extends _$Puzzle` (with top-level `_puzzleFromCrosswordTrampoline` and `_puzzleSelectWordTrampoline` functions for `compute`). Replace the files in `lib/widgets/` (importing `package:material_ui/material_ui.dart`) with `CrosswordPuzzleApp` (`lib/widgets/crossword_puzzle_app.dart`), `CrosswordGeneratorWidget` (`lib/widgets/crossword_generator_widget.dart`, displaying `'•'` for occupied cells while generating), `CrosswordPuzzleWidget` (`lib/widgets/crossword_puzzle_widget.dart`, with `MenuAnchor` and `_WordSelectMenuItem` per cell), and `PuzzleCompletedWidget` (`lib/widgets/puzzle_completed_widget.dart`). Finally, update `lib/main.dart` to run `CrosswordPuzzleApp()` with title `'Crossword Puzzle'`, and run `build_runner`.

생성된 코드 이해

트램펄린 함수를 사용하여 게임 상태 전환 오프로드

CrosswordPuzzleGame.from(사전에서 방해 단어를 검색)를 구성하고 selectWord를 검증하는 작업은 모두 CPU를 많이 사용하는 작업입니다. lib/providers.dart에서 Puzzle 알림은 최상위 트램펄린 함수를 사용하여 두 호출을 모두 compute에 오프로드하므로 Puzzle의 this 참조가 격리 클로저에 의해 캡처되지 않습니다.

Future<model.CrosswordPuzzleGame> _puzzleFromCrosswordTrampoline(
  (model.Crossword, BuiltSet<String>) args,
) async =>
    model.CrosswordPuzzleGame.from(crossword: args.$1, candidateWords: args.$2);

model.CrosswordPuzzleGame? _puzzleSelectWordTrampoline(
  (model.CrosswordPuzzleGame, model.Location, String, model.Direction) args,
) => args.$1.selectWord(location: args.$2, word: args.$3, direction: args.$4);

CrosswordPuzzleWidget의 대화형 셀 메뉴

lib/widgets/crossword_puzzle_widget.dart에서 채워진 각 셀은 정답인 가로 또는 세로 단어와 네 가지 대체 단어를 결합하여 MenuAnchor 내에 정렬된 BuiltList 메뉴로 표시합니다. 각 _WordSelectMenuItem는 puzzleProvider.select(...)를 사용하여 해당 단어가 현재 플레이어가 이미 배치한 단어와 일치하는지 여부에 따라 버튼을 사용 설정하거나 사용 중지합니다.

return MenuItemButton(
  onPressed:
      ref.watch(
        puzzleProvider.select(
          (puzzle) => puzzle.canSelectWord(
            location: location,
            word: word,
            direction: direction,
          ),
        ),
      )
      ? () => notifier.selectWord(
          location: location,
          word: word,
          direction: direction,
        )
      : null,
  // ...

앱 실행 및 테스트

앱을 핫 리스타트합니다. 생성기가 '•' 마커로 퍼즐 레이아웃에 애니메이션을 적용하는 것을 확인한 다음 빈 크로스워드 그리드의 셀을 탭하여 가로 및 세로 단어를 선택합니다(빠른 해결을 위해 설정 메뉴에서 20 x 11 작은 그리드로 전환해 보세요). 모든 단어가 올바르게 배치되면 앱에 완료 화면이 표시됩니다.

'Puzzle Completed!'라는 텍스트가 표시된 십자말풀이 앱 창

11. 마무리

수고하셨습니다 Google Antigravity와 협력하여 Flutter에서 멀티 격리 크로스워드 생성기 및 단어 퍼즐 게임을 빌드했습니다.

빌드한 항목

  • 즉시 Riverpod 제공자 초기화를 사용하여 267,750개 이상의 단어 사전을 로드하고 필터링했습니다.
  • built_value 및 built_collection를 사용하여 변경 불가능한 크로스워드 그리드, 작업 큐, 게임 상태를 모델링했습니다.
  • 백트래킹 제약 조건 만족 알고리즘을 구현하고 compute를 사용하여 백그라운드 작업자 격리 풀 전반에서 확장했습니다.
  • two_dimensional_scrollables의 TableView.builder 및 셀 범위 select() 재빌드 필터를 사용하여 60fps로 대형 2D 그리드를 렌더링했습니다.

자세히 알아보기