Files
logic-puzzle/lib/domain/game.dart
T
Hadrian Burkhardt a863b0ca93 Rearrange landscape puzzle layout
Landscape leaves now lay the puzzle out in two columns: the whole grid
keeps one column (square, sized to the page) with the heading, area
totals, hint/undo and notes beside it, and the leaf navigation folds
into a single row. The game leaf also keeps its actions in a compact
bottom bar, so the board and controls are visible without scrolling.

- Leaf gains an optional wideBody used on landscape pages.
- Board gains maxWidth, defaulting to the previous 350.
- Split the puzzle body into area, board and note builders so both
  layouts share the same controls.
- Add a landscape widget regression test and document the layout.

This snapshot also carries the pending 2.0.2 notebook work already in
the tree: read-ahead restore, bundled PCM WAV narration assets, the
audio consistency comment, version 2.0.2+11, and the related unit,
integration and script updates.
2026-10-31 06:21:36 +01:00

306 lines
8.2 KiB
Dart

import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import '../services/progress.dart';
import 'book.dart';
import 'puzzle.dart';
enum Screen { home, story, contents, briefing, game, reveal }
enum Mode { daily, classic, campaign }
Puzzle generatePractice(Map<String, Object> args) => Puzzle.generate(
BigInt.parse(args['seed'] as String),
Difficulty.fromStored(args['difficulty'] as String),
);
class Game extends ChangeNotifier {
Game(this.book, this.progress);
final Book book;
final Progress progress;
Screen screen = Screen.home;
Mode mode = Mode.classic;
Difficulty get difficulty =>
Difficulty.fromStored(progress.text('difficulty', 'EASY'));
int storyIndex = 0, campaignIndex = 0, playingLevel = 1, selectedArea = 0;
DateTime date = DateTime.now();
Puzzle? puzzle;
List<int> cells = [];
final List<List<int>> _undo = [];
String key = '';
bool busy = false;
int _request = 0;
bool get won => progress.flag('done_$key');
bool get canUndo => _undo.isNotEmpty && !won;
int get solved => progress.number('solved');
int get recoveredCount =>
List.generate(12, (i) => recovered(i)).where((v) => v).length;
int get unlocked => progress.number('campaignUnlocked').clamp(0, 11);
int get accessible =>
math.max(unlocked, progress.number('story_access_level').clamp(0, 11));
int get practiceLevel => progress.number('level_${difficulty.stored}', 1);
int get streak => visibleStreak(
progress.number('lastDaily', -99999),
progress.number('streak'),
epochDay(DateTime.now()),
);
bool recovered(int i) => progress.flag('done_story_v1_$i');
Future<void> restore() async {
final saved = progress.text('flutter_screen', 'home');
campaignIndex = progress.number('flutter_campaign').clamp(0, 11);
if (saved == 'story') {
showStory(
book.pages
.indexWhere((p) => p.id == progress.text('notebook_last_page'))
.clamp(0, 5),
);
} else if (saved == 'contents') {
contents();
} else if (saved == 'briefing') {
briefing(campaignIndex);
} else if (saved == 'reveal' &&
(recovered(campaignIndex) || progress.flag('flutter_read_ahead'))) {
reveal(campaignIndex, readAhead: progress.flag('flutter_read_ahead'));
} else if (saved == 'game') {
final mode = progress.text('flutter_mode');
if (mode == 'campaign') {
startCampaign(campaignIndex);
} else if (mode == 'daily') {
startDaily(
DateTime.tryParse(progress.text('flutter_date')) ?? DateTime.now(),
);
} else {
await startPractice(progress.number('flutter_level', 1));
}
}
}
void _route(Screen value) {
screen = value;
unawaited(progress.set('flutter_screen', value.name));
unawaited(
progress.set(
'flutter_read_ahead',
value == Screen.reveal && !recovered(campaignIndex),
),
);
unawaited(progress.set('flutter_campaign', campaignIndex));
unawaited(progress.set('flutter_mode', mode.name));
unawaited(progress.set('flutter_date', date.toIso8601String()));
unawaited(progress.set('flutter_level', playingLevel));
notifyListeners();
}
void home() {
_request++;
busy = false;
_route(Screen.home);
}
void openNotebook() {
final i = book.pages.indexWhere(
(p) => p.id == progress.text('notebook_last_page'),
);
showStory(i < 0 ? 0 : i);
}
void showStory(int i) {
_request++;
busy = false;
storyIndex = i.clamp(0, 5);
mode = Mode.campaign;
campaignIndex = 0;
if (storyIndex == 2 && key != 'story_v1_0') {
_read(book.levels[0].puzzle(), 'story_v1_0');
}
unawaited(progress.set('notebook_last_page', book.pages[storyIndex].id));
unawaited(progress.set('viewed_${book.pages[storyIndex].id}', true));
_route(Screen.story);
}
void contents() {
_request++;
busy = false;
_route(Screen.contents);
}
void briefing(int i) {
campaignIndex = i.clamp(0, accessible);
mode = Mode.campaign;
_route(Screen.briefing);
}
void reveal(int i, {bool readAhead = false}) {
if (!recovered(i) && (!readAhead || i > accessible)) {
briefing(i);
return;
}
campaignIndex = i;
mode = Mode.campaign;
_route(Screen.reveal);
}
void selectDifficulty(Difficulty d) {
unawaited(progress.set('difficulty', d.stored));
notifyListeners();
}
void startDaily(DateTime day) {
_request++;
busy = false;
mode = Mode.daily;
date = DateTime(day.year, day.month, day.day);
_read(
Puzzle.seeded(BigInt.from(epochDay(date)) * BigInt.from(7919)),
'd${date.toIso8601String().substring(0, 10)}',
);
_route(Screen.game);
}
Future<void> startPractice([int? level]) async {
final request = ++_request;
busy = true;
notifyListeners();
final d = difficulty;
final n = level ?? practiceLevel;
final p = await compute(generatePractice, {
'seed': '${1000000 + n}',
'difficulty': d.stored,
});
if (request != _request) return;
busy = false;
mode = Mode.classic;
playingLevel = n;
_read(p, 'v2_${d.stored}_$n');
_route(Screen.game);
}
void startCampaign(int i) {
_request++;
busy = false;
if (i > accessible) return;
if (recovered(i)) {
reveal(i);
return;
}
campaignIndex = i;
mode = Mode.campaign;
_read(book.levels[i].puzzle(), 'story_v1_$i');
_route(Screen.game);
}
void _read(Puzzle p, String id) {
puzzle = p;
key = id;
final saved = progress.text('grid_$id');
cells = List.generate(p.solution.length, (i) {
if (p.given[i]) return p.solution[i] == 1 ? 1 : 2;
final value = saved.length == p.solution.length
? int.tryParse(saved[i]) ?? 0
: 0;
return value >= 0 && value <= 2 ? value : 0;
});
selectedArea = 0;
_undo.clear();
_save();
}
void _save() {
unawaited(progress.set('grid_$key', cells.join()));
}
void mark(int index) {
if (busy || puzzle == null || won || puzzle!.given[index]) return;
_undo.add(List<int>.of(cells));
cells[index] = (cells[index] + 1) % 3;
_save();
check();
notifyListeners();
}
void undo() {
if (!canUndo) return;
cells = _undo.removeLast();
_save();
notifyListeners();
}
void area(int i) {
selectedArea = i;
notifyListeners();
}
Hint? applyHint() {
if (won || puzzle == null) return null;
Hint? hint;
for (var i = 0; i < cells.length; i++) {
if (cells[i] != 0 && cells[i] != (puzzle!.solution[i] == 1 ? 1 : 2)) {
hint = Hint(
i,
puzzle!.solution[i],
'An earlier mark conflicts with the clues. Correct it, then continue comparing the totals.',
);
break;
}
}
hint ??= LogicSolver(cells.length, puzzle!.constraints).nextHint(
cells
.map(
(v) => v == 0
? -1
: v == 1
? 1
: 0,
)
.toList(),
);
if (hint == null) return null;
_undo.add(List<int>.of(cells));
cells[hint.cell] = hint.value == 1 ? 1 : 2;
_save();
notifyListeners();
return hint;
}
void check() {
if (won || puzzle == null || !puzzle!.solved(cells)) return;
unawaited(progress.set('done_$key', true));
unawaited(progress.set('solved', solved + 1));
if (mode == Mode.daily) {
final day = epochDay(date), last = progress.number('lastDaily', -99999);
if (day > last) {
unawaited(
progress.set(
'streak',
completedStreak(last, progress.number('streak'), day),
),
);
unawaited(progress.set('lastDaily', day));
}
} else if (mode == Mode.campaign) {
unawaited(
progress.set(
'campaignUnlocked',
math.max(unlocked, math.min(11, campaignIndex + 1)),
),
);
if (screen == Screen.story) {
showStory(3);
} else {
reveal(campaignIndex);
}
} else {
unawaited(progress.set('level_${difficulty.stored}', playingLevel + 1));
unawaited(
progress.set(
'practiceCompleted',
progress.number('practiceCompleted') + 1,
),
);
}
notifyListeners();
}
}