Files
logic-puzzle/lib/domain/game.dart
T
Hadrian Burkhardt 0718e3f252 Open Lumen on a responsive bookshelf and land pending story work
- Start the app on a shelf of every installed book instead of the last
  book's home. Cards show the cover, translated metadata, available
  languages, restored patterns and either "Continue reading" or a way in.
- Keep each book's saved route: the shelf is never written to
  flutter_screen, so choosing a book resumes its own leaf.
- Lay the shelf out responsively: dense single-column cards on phones,
  a two-column grid from 720 logical pixels, a centred 860 px column on
  tablets and a chevron that exists in the bundled handwriting font.
- Keep Settings reachable from the shelf and let the home page's story
  library button open the shelf instead of a dialog.
- Add tool/shelf_screenshots_test.dart, which renders the shelf at phone
  and tablet metrics, checks that every card and Settings stay reachable
  without overflow, and writes artifacts/library/shelf-*.png.
- Commit the pending Midnight Invitation package (campaign, notebook,
  narration and artwork), cast drama and ambience tooling, region
  selection, phone/tablet integration coverage and related docs.

flutter analyze is clean and all 74 widget/domain tests pass.
2026-11-05 14:29:50 +01:00

421 lines
12 KiB
Dart

import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import '../services/progress.dart';
import 'book.dart';
import 'library.dart';
import 'puzzle.dart';
enum Screen { library, 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.store, {this.library});
Book book;
final Progress store;
final StoryLibrary? library;
Progress get progress => store.forStory(book.id);
String get languagePreference => store.text('language', 'system');
String get requestedLanguage =>
languagePreference == 'system' ? deviceLanguage : languagePreference;
String deviceLanguage = 'en';
int _bookRequest = 0;
Future<void> selectStory(String id) async {
final catalogue = library;
if (catalogue == null) return;
final request = ++_bookRequest;
final next = await catalogue.open(id, language: requestedLanguage);
if (request != _bookRequest) return;
_request++;
book = next;
puzzle = null;
key = '';
cells = [];
_undo.clear();
storyIndex = campaignIndex = contentsChapter = 0;
busy = false;
screen = Screen.home;
unawaited(store.set('selected_story', book.id));
await restore();
if (request == _bookRequest) notifyListeners();
}
Future<void> selectLanguage(String preference) async {
final catalogue = library;
if (catalogue == null) return;
final request = ++_bookRequest;
final next = await catalogue.open(
book.id,
language: preference == 'system' ? deviceLanguage : preference,
);
if (request != _bookRequest) return;
unawaited(store.set('language', preference));
// Identity and puzzle data are unchanged: keep the live grid and undo stack.
book = next;
notifyListeners();
}
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;
int contentsChapter = 0;
StoryPage get storyPage => book.pages[storyIndex];
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(
book.levels.length,
(i) => recovered(i),
).where((v) => v).length;
int get unlocked =>
progress.number('campaignUnlocked').clamp(0, book.levels.length - 1);
int get accessible => math.max(
book.initiallyAccessible,
math.max(
unlocked,
progress.number('story_access_level').clamp(0, book.levels.length - 1),
),
);
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_${book.puzzleKey(i)}');
Future<void> restore() async {
final saved = progress.text('flutter_screen', 'home');
campaignIndex = progress
.number('flutter_campaign')
.clamp(0, book.levels.length - 1);
if (saved == 'story') {
showStory(
book.pages
.indexWhere((p) => p.id == progress.text('notebook_last_page'))
.clamp(0, book.pages.length - 1),
);
} else if (saved == 'contents') {
contents(progress.number('notebook_contents_chapter'));
} 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();
}
/// Claim one of three reading breaks, persisted independently for each book.
/// Existing chapter-ad records count toward the same lifetime cap.
bool claimBookAd(int position, int total) {
final oldCount = List.generate(
book.levels.length,
(i) => i,
).where((i) => progress.flag('storyAd_$i')).length;
final used = List.generate(
3,
(i) => i + 1,
).where((slot) => progress.flag('storyAd_break_$slot')).length;
if (oldCount + used >= 3) return false;
final slot = (position * 3 ~/ total).clamp(0, 3);
if (slot == 0 || progress.flag('storyAd_break_$slot')) return false;
unawaited(progress.set('storyAd_break_$slot', true));
return true;
}
/// The shelf is the app's first window. It is deliberately not written to a
/// story's saved route (`flutter_screen`), so every book keeps its own reading
/// position and the next launch still opens the shelf.
void showLibrary() {
if (library == null) return;
_request++;
busy = false;
screen = Screen.library;
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, book.pages.length - 1);
mode = Mode.campaign;
campaignIndex = storyPage.campaignIndex ?? 0;
if (campaignIndex > accessible) {
unawaited(progress.set('story_access_level', campaignIndex));
}
if (storyPage.type == StoryPageType.puzzle &&
key != book.puzzleKey(campaignIndex)) {
_read(book.levels[campaignIndex].puzzle(), book.puzzleKey(campaignIndex));
}
unawaited(progress.set('notebook_last_page', book.pages[storyIndex].id));
unawaited(progress.set('viewed_${book.pages[storyIndex].id}', true));
_route(Screen.story);
}
void contents([int? chapter]) {
_request++;
busy = false;
contentsChapter = (chapter ?? book.chapterFor(campaignIndex)).clamp(
0,
book.chapterFor(accessible),
);
unawaited(progress.set('notebook_contents_chapter', contentsChapter));
_route(Screen.contents);
}
void leaveCottage() {
final next = book.continueAt;
if (next == null) {
contents();
return;
}
unawaited(progress.set('story_access_level', math.max(accessible, next)));
briefing(next);
}
void briefing(int i) {
campaignIndex = i.clamp(0, accessible);
final page = book.pageFor(campaignIndex, StoryPageType.entry);
if (page >= 0) {
showStory(page);
return;
}
mode = Mode.campaign;
_route(Screen.briefing);
}
void reveal(int i, {bool readAhead = false}) {
if (!recovered(i) && (!readAhead || i > accessible)) {
briefing(i);
return;
}
campaignIndex = i;
final page = book.pageFor(i, StoryPageType.memory);
if (page >= 0) {
showStory(page);
return;
}
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 < 0 || i >= book.levels.length || i > accessible) return;
campaignIndex = i;
mode = Mode.campaign;
final page = book.pageFor(i, StoryPageType.puzzle);
if (page >= 0) {
showStory(page);
return;
}
_read(book.levels[i].puzzle(), book.puzzleKey(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 (progress.flag('done_$id')) return p.solution[i] == 1 ? 1 : 2;
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(book.levels.length - 1, campaignIndex + 1),
),
),
);
reveal(campaignIndex);
} else {
unawaited(progress.set('level_${difficulty.stored}', playingLevel + 1));
unawaited(
progress.set(
'practiceCompleted',
progress.number('practiceCompleted') + 1,
),
);
}
notifyListeners();
}
}