1. 簡介
建構項目
想像一下,如果有人問你是否能製作出世界上最大的填字遊戲,您想起一些經典的 AI 搜尋技術,並想知道是否能使用 Flutter 探索演算法解決方案,解決需要大量運算的問題,同時讓 UI 保持 60 fps 的回應速度。
在本程式碼實驗室中,您將與 Google Antigravity 合作,建構演算法填字遊戲產生器,並將其轉換為可玩的文字益智遊戲。有效的填字遊戲有許多定義,您在這裡探索的技術可協助您生成符合您規則的遊戲。

以填字遊戲產生器為基礎,您將打造一款互動式文字益智遊戲,可在 Android、iOS、Windows、macOS 和 Linux 上執行:

學習旅程
本程式碼實驗室會逐步引導您建構填字遊戲生成器和益智遊戲:
- 設定 Flutter 環境:為目標平台設定 Flutter SDK 和 Google Antigravity。
- 建立專案:提示 Antigravity 使用
built_value、flutter_riverpod、two_dimensional_scrollables和material_ui建立空白 Flutter 專案。 - 新增字詞:繫結 SOWPODS 字詞清單素材資源,並在啟動時使用非同步 Riverpod 供應器預先載入。
- 在格線中顯示字詞:定義不可變更的
built_value格線模型,並使用 Riverpod 的select篩選器,在 2DTableView中算繪。 - 強制執行限制 - 驗證連鎖填字遊戲規則,並使用
compute將候選位置移出 UI 執行緒。 - 管理工作佇列:將隨機放置替換為回溯
WorkQueue,指定開放的交點。 - 顯示統計資料:在浮動 HUD 疊加層中,衍生即時生成指標、經過時間和預估剩餘時間。
- 使用執行緒平行處理:以視覺化方式呈現活躍的搜尋單元,並透過可設定的背景工作隔離集區,擴充生成作業。
- 變成遊戲:將完成的填字遊戲轉換成互動式選擇題文字益智遊戲。
課程內容
- 如何與 Google Antigravity 協作,反覆建構及自訂需要大量運算資源的 Flutter 應用程式和益智遊戲。
- 如何使用背景隔離區執行耗費大量資源的運算,而不使用 Flutter 的
compute函式和 Riverpod 的select重建篩選器封鎖 Flutter 的轉譯迴圈。 - 如何使用
built_value和built_collection建立不可變資料結構的模型,以實作深度優先搜尋和回溯等搜尋式傳統 AI (GOFAI) 技術。 - 如何使用
two_dimensional_scrollables套件,流暢顯示大型 2D 格線。
必要條件
- 對 Flutter 和 Dart 語法有基本瞭解。
2. 設定 Flutter 環境
編輯者
本程式碼實驗室會使用 Google Antigravity 做為 AI 優先開發環境。在每個步驟中,您會提示 Antigravity 生成或演進應用程式的模型、隔離區、供應器和 Widget,檢查生成程式碼中的重要模式,並視需要探索演算法或 UI 變化版本。
安裝 Flutter
如需安裝 Flutter SDK 的最新操作說明,請前往 docs.flutter.dev。
請安裝下列軟體,以便進行本程式碼實驗室:
- Flutter SDK
- Google Antigravity,並啟用官方 Dart 和 Flutter 外掛程式 (可在外掛程式市集的「Build with Google」部分找到)。
- 所選開發目標的編譯器軟體 (例如:Visual Studio 適用於 Windows、Xcode 適用於 macOS 或 iOS,或 Android Studio 適用於 Android)。
3. 建立專案
瞭解依附元件
建立專案前,請先查看填字遊戲產生器的核心套件:
built_value和built_collection:產生不可變動的值類型和集合,在衍生執行個體之間共用記憶體,這對於回溯搜尋和在隔離區之間安全傳遞狀態至關重要。flutter_riverpod、riverpod和riverpod_annotation:透過select()提供反應式狀態管理、串流供應器和精細的重建篩選功能。two_dimensional_scrollables:使用TableView.builder在兩個軸上延遲轉譯大型 2D 格線。characters:準確處理字元叢集字串疊代。intl:在統計資料疊加層中,設定大量字數和儲存格數的格式。
提示 Antigravity 建立專案
- 啟動 Google Antigravity,然後開啟要建構專案的空白目錄 (請選擇不需進階權限或不含空格的路徑,例如主目錄或
C:\src\中的資料夾)。 - 在 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 中將 MaterialApp 包裝在 Riverpod ProviderScope 中:
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! 顯示在畫面中央:

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 註解會標記 wordList,以便由 riverpod_generator 產生程式碼。這個函式會以非同步方式載入 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 個字典字詞的可捲動清單:

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 會儲存 BuiltList 和 BuiltMap,以便 UI 快速查詢 (x, y)。_fillCharacters 加上 @BuiltValueHook(finalizeBuilder: true) 註解後,每當 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* 產生器函式。由於 Riverpod 會監控函式頂端的 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 時,只有字元實際變更的儲存格會重新建構。
執行及測試應用程式
熱重新啟動應用程式。您會看到字元填滿格線,右上角則有設定齒輪選單,可讓您切換格線大小:

目前,文字會放在隨機座標上,且不經過驗證,因此會雜亂地互相覆寫。在下一個步驟中,您將強制執行實際的填字遊戲規則。
6. 強制執行限制
異動內容和原因
目前,Crossword.addWord 接受任何座標上的任何字詞。為生成有效的英式填字遊戲,Crossword 必須驗證:
- 格線中沒有重複的字詞。
- 每個字元都介於
[0, width)和[0, height)之間。 - 每個字元都屬於橫向字詞、直向字詞,或兩個字詞共用相同字母的有效交集。
- 垂直相鄰的字元屬於同一個
downWord,水平相鄰的字元則屬於同一個acrossWord(避免兩個字母並排時意外重疊)。 - 第一個字詞之後的每個新字詞,都至少與一個現有字詞重疊。
在主要隔離區中檢查這些限制數千次,會阻礙 Flutter 的 60 fps 轉譯迴圈。您將使用 Flutter 的 compute 函式,在專屬的 lib/isolates.dart 程式庫中,將候選評估作業卸載至背景隔離區。
提示 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」分開
背景隔離區無法共用與主要隔離區繫結的可變動物件,例如 Riverpod 的 Ref 或 StreamProviderElement。如果您在 @riverpod Stream 供應器函式中直接使用閉包呼叫 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 的值 (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. 管理工作佇列
瞭解搜尋策略
與其在整個棋盤上隨機猜測座標,不如將填字遊戲生成轉換為引導式回溯搜尋:
- 在
WorkQueue中,追蹤僅屬於單一字詞的開放字元格 (且沒有平行相鄰的字元格阻擋垂直放置)。 - 從
locationsToTry中挑選候選位置,並篩選candidateWords,找出包含該交集處字母的字詞。 - 試著在交叉點填入相符的字詞。如果字詞符合,請以新的填字遊戲更新
WorkQueue;如果嘗試 1,000 次後仍沒有符合的字詞,請將該位置標示為已知的badLocation,並從佇列中移除。
提示 Antigravity 新增WorkQueue和引導式搜尋
在 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) 使用切換運算式,產生人類可讀的時間長度字串:
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',
};
}
}
執行及測試應用程式
熱重新啟動應用程式。填字遊戲產生器現在會鎖定有效的交叉點,並刪除死路,因此填滿格子的速度會大幅提升:

可以再快一點嗎?首先,顯示即時遙測資料,查看演算法耗費時間的位置。
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 中,使用 @Riverpod(keepAlive: true) 註解 StartTime、EndTime 和 ShowDisplayInfo,可防止 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) 的切換運算式會將 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」切換鈕:

請注意,在執行作業接近尾聲時,數字會不斷變化,但格線幾乎不會更新,因為單一 worker 正在花時間逐一消除剩餘的死路位置。接著,您將在多個隔離區中平行處理該搜尋。
9. 使用執行緒平行處理
以視覺化方式呈現搜尋並平行處理
隨著格線填滿,有效的字詞位置會越來越少,單一工作站隔離區會花費大部分時間檢查死路。在這個步驟中,您會:
- 使用
CrosswordWidget中的AnimatedContainer和AnimatedDefaultTextStyle,醒目顯示目前位於workQueue.locationsToTry(explorationCell) 的儲存格,以便即時查看搜尋邊界。 - 重構
lib/isolates.dart,使用compute和candidateGeneratorFutures.wait,將候選搜尋分散到maxWorkerCount個平行 worker isolate 集區。 - 在設定選單和統計資料疊加層中新增
BackgroundWorkers選取器,以便測試1到128的 worker 數量。
提示 Antigravity 醒目顯示搜尋儲存格,並平行處理 worker 隔離區
在 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 流暢地為顏色加上動畫效果:

使用頂層 compute 函式進行扇出和扇入
在 lib/isolates.dart 中,_generate 和 _generateCandidate 定義為頂層函式,因此絕不會擷取無法傳送的狀態。_generate 最多可接受 maxWorkerCount 個隨機位置,為每個位置啟動 compute(_generateCandidate, ...) 未來,並使用 candidateGeneratorFutures.wait 同時等待所有位置:
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;
傳入 Dart 記錄 (例如 (workQueue.crossword, workQueue.candidateWords, location, direction)) 並傳出 (Location, Direction, String?),可將多個參數乾淨地調整為 compute 的單一訊息簽章。
執行及測試應用程式
熱重新啟動應用程式,然後開啟右上角的設定選單,調整格線大小、切換統計資料疊加層,以及切換背景工作站隔離區數量:

10. 將學習變成遊戲
建構項目:可玩的填字遊戲
在最後一個步驟中,您要將填字遊戲產生器轉換成可玩的選擇題文字益智遊戲:
- 生成謎題:使用多重隔離生成器在背景建立完整的填字遊戲,同時顯示隱藏
'•'儲存格 (CrosswordGeneratorWidget) 的脈動網格。 - 生成替代字詞選項:針對已解開填字遊戲中的每個字詞,
CrosswordPuzzleGame.from會從剩餘的字典中隨機選取四個長度完全相同的干擾字詞。 - 互動式填字:輕觸任何格子會開啟
MenuAnchor內容選單 (CrosswordPuzzleWidget),列出橫向和直向的候選字詞。玩家可以依任何順序放置字詞 (requireOverlap: false),系統會使用canSelectWord自動停用衝突的選項。 - 偵測勝利:當玩家選取的字詞形成有效的填字遊戲,且符合生成的謎題字數時,應用程式會轉換至
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 小型格線,以便快速解決)。所有字詞都正確放置後,應用程式會顯示完成畫面:

11. 恭喜
恭喜!您與 Google Antigravity 合作,在 Flutter 中建構多隔離區填字遊戲生成器和字謎遊戲。
建構內容
- 使用積極的 Riverpod 供應器初始化,載入並篩選超過 267,750 個字詞的字典。
- 使用
built_value和built_collection建立不可變更的填字遊戲格、工作佇列和遊戲狀態模型。 - 實作回溯約束滿足演算法,並使用
compute將其擴充至背景 worker 隔離集區。 - 使用
two_dimensional_scrollables的TableView.builder和儲存格範圍select()重建篩選器,以 60 fps 的速度算繪大型 2D 網格。