Migrate Lumen to Dart and Flutter 2.0
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'puzzle.dart';
|
||||
|
||||
class CampaignLevel {
|
||||
CampaignLevel(Map<String, dynamic> data)
|
||||
: chapter = data['chapter'],
|
||||
title = data['title'],
|
||||
object = data['object'],
|
||||
before = data['before'],
|
||||
after = data['after'],
|
||||
picture = (data['picture'] as String).split('').map(int.parse).toList(),
|
||||
clues = data['clues'],
|
||||
areas = data['areas'];
|
||||
final String chapter, title, object, before, after, clues, areas;
|
||||
final List<int> picture;
|
||||
Puzzle puzzle() {
|
||||
final p = Puzzle(7, picture);
|
||||
if (clues.isNotEmpty) {
|
||||
for (final c in clues.split(',')) {
|
||||
p.given[int.parse(c)] = true;
|
||||
}
|
||||
}
|
||||
if (areas.isNotEmpty) {
|
||||
var i = 0;
|
||||
for (final a in areas.split(';')) {
|
||||
final v = a.split(',').map(int.parse).toList();
|
||||
p.regions.add(
|
||||
Region(String.fromCharCode(65 + i++), v[0], v[1], v[2], v[3]),
|
||||
);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
class StoryPage {
|
||||
const StoryPage(this.id, this.title, this.text);
|
||||
final String id, title, text;
|
||||
}
|
||||
|
||||
class Book {
|
||||
Book(this.premise, this.levels, this.pages, this.tracks);
|
||||
final String premise;
|
||||
final List<CampaignLevel> levels;
|
||||
final List<StoryPage> pages;
|
||||
final Map<String, dynamic> tracks;
|
||||
static Future<Book> load() async {
|
||||
final campaign = jsonDecode(
|
||||
await rootBundle.loadString('assets/campaign.json'),
|
||||
) as Map<String, dynamic>;
|
||||
final scripts = jsonDecode(
|
||||
await rootBundle.loadString('assets/narration/scripts.json'),
|
||||
) as List;
|
||||
final tracks =
|
||||
jsonDecode(
|
||||
await rootBundle.loadString(
|
||||
'assets/audio/narration_manifest.json',
|
||||
),
|
||||
)['tracks']
|
||||
as Map<String, dynamic>;
|
||||
const ids = [
|
||||
'cottage.dedication',
|
||||
'cottage.window',
|
||||
'cottage.match.puzzle',
|
||||
'cottage.match.memory',
|
||||
'cottage.folded.note',
|
||||
'cottage.lantern.sketch',
|
||||
];
|
||||
const titles = [
|
||||
'For you, when you are ready',
|
||||
'By the cottage window',
|
||||
'A spark in the drawer',
|
||||
'One small light',
|
||||
'A note I nearly forgot',
|
||||
'The handle, carefully mended',
|
||||
];
|
||||
return Book(
|
||||
campaign['premise'],
|
||||
(campaign['levels'] as List).map((e) => CampaignLevel(e)).toList(),
|
||||
List.generate(
|
||||
6,
|
||||
(i) => StoryPage(
|
||||
ids[i],
|
||||
titles[i],
|
||||
scripts
|
||||
.where((s) => s['pageId'] == ids[i])
|
||||
.map((s) => s['text'] as String)
|
||||
.firstOrNull ??
|
||||
'',
|
||||
),
|
||||
),
|
||||
tracks,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
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)) {
|
||||
reveal(campaignIndex);
|
||||
} 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_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) {
|
||||
if (!recovered(i)) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
enum Difficulty {
|
||||
easy('Easy', 'Short deductions. A gentle place to begin.'),
|
||||
medium('Medium', 'Link deductions across rows and columns.'),
|
||||
hard('Hard', 'Follow longer chains to uncover the pattern.');
|
||||
|
||||
const Difficulty(this.label, this.description);
|
||||
final String label, description;
|
||||
String get stored => name.toUpperCase();
|
||||
static Difficulty fromStored(String value) =>
|
||||
values.firstWhere((d) => d.stored == value, orElse: () => easy);
|
||||
static Difficulty fromRounds(int n) => n <= 2
|
||||
? easy
|
||||
: n <= 4
|
||||
? medium
|
||||
: hard;
|
||||
}
|
||||
|
||||
/// Explicit Java-compatible PRNG keeps generated boards stable across platforms.
|
||||
class JavaRandom {
|
||||
JavaRandom(BigInt seed) : _seed = (seed ^ _multiplier) & _mask;
|
||||
static final _multiplier = BigInt.from(0x5DEECE66D);
|
||||
static final _mask = (BigInt.one << 48) - BigInt.one;
|
||||
BigInt _seed;
|
||||
int next(int bits) {
|
||||
_seed = (_seed * _multiplier + BigInt.from(11)) & _mask;
|
||||
return (_seed >> (48 - bits)).toInt();
|
||||
}
|
||||
|
||||
int nextInt(int bound) {
|
||||
if ((bound & -bound) == bound) {
|
||||
return ((BigInt.from(bound) * BigInt.from(next(31))) >> 31).toInt();
|
||||
}
|
||||
while (true) {
|
||||
final bits = next(31), value = bits % bound;
|
||||
if (bits - value + bound - 1 < 0x80000000) return value;
|
||||
}
|
||||
}
|
||||
|
||||
BigInt nextLong() {
|
||||
final high = BigInt.from(next(32)).toSigned(32);
|
||||
final low = BigInt.from(next(32)).toSigned(32);
|
||||
return ((high << 32) + low).toSigned(64);
|
||||
}
|
||||
|
||||
void shuffle<T>(List<T> list) {
|
||||
for (var i = list.length; i > 1; i--) {
|
||||
final j = nextInt(i), old = list[i - 1];
|
||||
list[i - 1] = list[j];
|
||||
list[j] = old;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Region {
|
||||
const Region(this.label, this.top, this.left, this.height, this.width);
|
||||
final String label;
|
||||
final int top, left, height, width;
|
||||
bool contains(int index, int size) =>
|
||||
index ~/ size >= top &&
|
||||
index ~/ size < top + height &&
|
||||
index % size >= left &&
|
||||
index % size < left + width;
|
||||
}
|
||||
|
||||
class Constraint {
|
||||
Constraint(this.cells, this.total, this.name);
|
||||
final List<int> cells;
|
||||
final int total;
|
||||
final String name;
|
||||
}
|
||||
|
||||
class Hint {
|
||||
const Hint(this.cell, this.value, this.explanation);
|
||||
final int cell, value;
|
||||
final String explanation;
|
||||
}
|
||||
|
||||
class Analysis {
|
||||
const Analysis(this.solved, this.areaDeductions, this.cells);
|
||||
final bool solved;
|
||||
final int areaDeductions;
|
||||
final List<int> cells;
|
||||
}
|
||||
|
||||
class LogicSolver {
|
||||
LogicSolver(this.cellCount, this.constraints);
|
||||
final int cellCount;
|
||||
final List<Constraint> constraints;
|
||||
int _need(Constraint c, List<int> known) =>
|
||||
c.total - c.cells.where((i) => known[i] == 1).length;
|
||||
List<int> _unknown(Constraint c, List<int> known) =>
|
||||
c.cells.where((i) => known[i] < 0).toList();
|
||||
int _singles(List<int> known) {
|
||||
var changes = 0;
|
||||
for (final c in constraints) {
|
||||
final need = _need(c, known), unknown = _unknown(c, known);
|
||||
if (need < 0 || need > unknown.length) return -1;
|
||||
if (unknown.isEmpty || (need != 0 && need != unknown.length)) continue;
|
||||
for (final i in unknown) {
|
||||
known[i] = need == 0 ? 0 : 1;
|
||||
changes++;
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
Hint? nextHint(List<int> known) {
|
||||
for (final c in constraints) {
|
||||
final need = _need(c, known), unknown = _unknown(c, known);
|
||||
if (need < 0 || need > unknown.length) return null;
|
||||
if (unknown.isNotEmpty && (need == 0 || need == unknown.length)) {
|
||||
return Hint(
|
||||
unknown.first,
|
||||
need == 0 ? 0 : 1,
|
||||
need == 0
|
||||
? '${c.name} already has all its lights. Every remaining cell in it must be crossed out.'
|
||||
: '${c.name} needs $need more lights and has exactly ${unknown.length} empty cells. They must all be lit.',
|
||||
);
|
||||
}
|
||||
}
|
||||
for (var a = 0; a < constraints.length; a++) {
|
||||
final first = constraints[a];
|
||||
for (var b = a + 1; b < constraints.length; b++) {
|
||||
final second = constraints[b];
|
||||
final onlyA = _unknown(
|
||||
first,
|
||||
known,
|
||||
).where((i) => !second.cells.contains(i)).toList();
|
||||
final onlyB = _unknown(
|
||||
second,
|
||||
known,
|
||||
).where((i) => !first.cells.contains(i)).toList();
|
||||
final needA = _need(first, known),
|
||||
needB = _need(second, known),
|
||||
diff = needA - needB;
|
||||
if (onlyA.isEmpty && onlyB.isEmpty ||
|
||||
(diff != onlyA.length && diff != -onlyB.length)) {
|
||||
continue;
|
||||
}
|
||||
final valueA = diff == onlyA.length ? 1 : 0;
|
||||
final explanation =
|
||||
'Compare ${first.name} ($needA more lights) with ${second.name} ($needB more). Shared empty cells cancel. The difference forces the cells outside their overlap.';
|
||||
return onlyA.isNotEmpty
|
||||
? Hint(onlyA.first, valueA, explanation)
|
||||
: Hint(onlyB.first, 1 - valueA, explanation);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Analysis analyze(List<int> initial, {bool useAreas = true}) {
|
||||
final known = List<int>.of(initial);
|
||||
var areas = 0;
|
||||
while (true) {
|
||||
final changed = _singles(known);
|
||||
if (changed < 0) return Analysis(false, areas, known);
|
||||
if (changed > 0) continue;
|
||||
if (useAreas) {
|
||||
final hint = nextHint(known);
|
||||
if (hint != null) {
|
||||
known[hint.cell] = hint.value;
|
||||
areas++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return Analysis(!known.contains(-1), areas, known);
|
||||
}
|
||||
}
|
||||
|
||||
int countSolutions(List<int> initial) {
|
||||
int search(List<int> known) {
|
||||
int changed;
|
||||
do {
|
||||
changed = _singles(known);
|
||||
if (changed < 0) return 0;
|
||||
} while (changed > 0);
|
||||
var choice = -1, degree = -1;
|
||||
for (var i = 0; i < cellCount; i++) {
|
||||
if (known[i] >= 0) continue;
|
||||
final d = constraints.where((c) => c.cells.contains(i)).length;
|
||||
if (d > degree) {
|
||||
choice = i;
|
||||
degree = d;
|
||||
}
|
||||
}
|
||||
if (choice < 0) return 1;
|
||||
final branch = List<int>.of(known)..[choice] = 0;
|
||||
final count = search(branch);
|
||||
if (count >= 2) return 2;
|
||||
known[choice] = 1;
|
||||
return math.min(2, count + search(known));
|
||||
}
|
||||
|
||||
return search(List<int>.of(initial));
|
||||
}
|
||||
}
|
||||
|
||||
class Puzzle {
|
||||
Puzzle(this.size, List<int> picture)
|
||||
: solution = List<int>.of(picture),
|
||||
given = List<bool>.filled(size * size, false) {
|
||||
if (picture.length != size * size || picture.any((v) => v != 0 && v != 1)) {
|
||||
throw ArgumentError('Invalid picture');
|
||||
}
|
||||
}
|
||||
final int size;
|
||||
final List<int> solution;
|
||||
final List<bool> given;
|
||||
final List<Region> regions = [];
|
||||
List<int> get rows => List.generate(
|
||||
size,
|
||||
(r) => List.generate(
|
||||
size,
|
||||
(c) => solution[r * size + c],
|
||||
).reduce((a, b) => a + b),
|
||||
);
|
||||
List<int> get cols => List.generate(
|
||||
size,
|
||||
(c) => List.generate(
|
||||
size,
|
||||
(r) => solution[r * size + c],
|
||||
).reduce((a, b) => a + b),
|
||||
);
|
||||
int regionTotal(Region r) => List.generate(
|
||||
solution.length,
|
||||
(i) => r.contains(i, size) ? solution[i] : 0,
|
||||
).reduce((a, b) => a + b);
|
||||
List<Constraint> get constraints => [
|
||||
for (var l = 0; l < size; l++) ...[
|
||||
Constraint(
|
||||
List.generate(size, (p) => l * size + p),
|
||||
rows[l],
|
||||
'Row ${l + 1}',
|
||||
),
|
||||
Constraint(
|
||||
List.generate(size, (p) => p * size + l),
|
||||
cols[l],
|
||||
'Column ${l + 1}',
|
||||
),
|
||||
],
|
||||
for (final r in regions)
|
||||
Constraint(
|
||||
[
|
||||
for (var y = r.top; y < r.top + r.height; y++)
|
||||
for (var x = r.left; x < r.left + r.width; x++) y * size + x,
|
||||
],
|
||||
regionTotal(r),
|
||||
'Area ${r.label}',
|
||||
),
|
||||
];
|
||||
List<int> get initial =>
|
||||
List.generate(solution.length, (i) => given[i] ? solution[i] : -1);
|
||||
factory Puzzle.seeded(BigInt seed) {
|
||||
final random = JavaRandom(seed);
|
||||
final puzzle = Puzzle(5, List.generate(25, (_) => random.next(1)));
|
||||
final order = List.generate(25, (i) => i);
|
||||
random.shuffle(order);
|
||||
for (final i in order) {
|
||||
if (puzzle.countSolutions() == 1) break;
|
||||
puzzle.given[i] = true;
|
||||
}
|
||||
return puzzle;
|
||||
}
|
||||
static Puzzle generate(BigInt seed, Difficulty difficulty) {
|
||||
final random = JavaRandom(seed);
|
||||
for (var i = 0; i < 256; i++) {
|
||||
final p = Puzzle.seeded(random.nextLong());
|
||||
if (difficulty != Difficulty.easy) p._removeRedundant();
|
||||
if (p.difficulty == difficulty) return p;
|
||||
}
|
||||
final p = Puzzle.seeded(BigInt.from(difficulty == Difficulty.hard ? 2 : 0));
|
||||
if (difficulty != Difficulty.easy) p._removeRedundant();
|
||||
final r = List.generate(5, (i) => i), c = List.generate(5, (i) => i);
|
||||
random.shuffle(r);
|
||||
random.shuffle(c);
|
||||
final old = List<int>.of(p.solution), g = List<bool>.of(p.given);
|
||||
for (var i = 0; i < 25; i++) {
|
||||
final from = r[i ~/ 5] * 5 + c[i % 5];
|
||||
p.solution[i] = old[from];
|
||||
p.given[i] = g[from];
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
void _removeRedundant() {
|
||||
for (var i = 0; i < 25; i++) {
|
||||
if (!given[i]) continue;
|
||||
given[i] = false;
|
||||
if (countSolutions() != 1) given[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
int countSolutions() {
|
||||
if (size != 5 || regions.isNotEmpty) {
|
||||
return LogicSolver(solution.length, constraints).countSolutions(initial);
|
||||
}
|
||||
final rs = rows, cs = cols;
|
||||
int search(int row, List<int> totals) {
|
||||
if (row == 5) {
|
||||
return List.generate(5, (i) => totals[i] == cs[i]).every((v) => v)
|
||||
? 1
|
||||
: 0;
|
||||
}
|
||||
var count = 0;
|
||||
for (var mask = 0; mask < 32; mask++) {
|
||||
var bits = 0;
|
||||
for (var c = 0; c < 5; c++) {
|
||||
bits += (mask >> c) & 1;
|
||||
}
|
||||
if (bits != rs[row]) continue;
|
||||
final next = List<int>.of(totals);
|
||||
var ok = true;
|
||||
for (var c = 0; c < 5; c++) {
|
||||
final v = (mask >> c) & 1, i = row * 5 + c;
|
||||
next[c] += v;
|
||||
if (given[i] && solution[i] != v ||
|
||||
next[c] > cs[c] ||
|
||||
next[c] + 4 - row < cs[c]) {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
if (ok) count += search(row + 1, next);
|
||||
if (count >= 2) return 2;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
return search(0, List.filled(5, 0));
|
||||
}
|
||||
|
||||
int get deductionRounds {
|
||||
var known = initial;
|
||||
var rounds = 0;
|
||||
final lines = constraints;
|
||||
while (known.contains(-1)) {
|
||||
final next = List<int>.of(known);
|
||||
var changed = false;
|
||||
for (final c in lines) {
|
||||
final unknown = c.cells.where((i) => known[i] < 0).toList();
|
||||
final need = c.total - c.cells.where((i) => known[i] == 1).length;
|
||||
if (unknown.isNotEmpty && (need == 0 || need == unknown.length)) {
|
||||
for (final i in unknown) {
|
||||
next[i] = need == 0 ? 0 : 1;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!changed) throw StateError('Puzzle requires guessing');
|
||||
known = next;
|
||||
rounds++;
|
||||
}
|
||||
return rounds;
|
||||
}
|
||||
|
||||
Difficulty get difficulty => Difficulty.fromRounds(deductionRounds);
|
||||
bool solved(List<int> cells) =>
|
||||
cells.length == solution.length &&
|
||||
List.generate(
|
||||
cells.length,
|
||||
(i) => cells[i] == (solution[i] == 1 ? 1 : 2),
|
||||
).every((v) => v);
|
||||
}
|
||||
|
||||
int epochDay(DateTime date) =>
|
||||
DateTime.utc(date.year, date.month, date.day).millisecondsSinceEpoch ~/
|
||||
Duration.millisecondsPerDay;
|
||||
int visibleStreak(int last, int count, int today) =>
|
||||
last >= today - 1 ? count : 0;
|
||||
int completedStreak(int last, int count, int day) => day <= last
|
||||
? count
|
||||
: last == day - 1
|
||||
? count + 1
|
||||
: 1;
|
||||
+925
@@ -0,0 +1,925 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import 'domain/book.dart';
|
||||
import 'domain/game.dart';
|
||||
import 'domain/puzzle.dart';
|
||||
import 'services/ads.dart';
|
||||
import 'services/narrator.dart';
|
||||
import 'services/progress.dart';
|
||||
import 'ui/board.dart';
|
||||
import 'ui/paper.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
LicenseRegistry.addLicense(() async* {
|
||||
yield LicenseEntryWithLineBreaks([
|
||||
'Dancing Script',
|
||||
], await rootBundle.loadString('assets/fonts/OFL.txt'));
|
||||
});
|
||||
SystemChrome.setSystemUIOverlayStyle(
|
||||
const SystemUiOverlayStyle(
|
||||
statusBarColor: cream,
|
||||
statusBarIconBrightness: Brightness.dark,
|
||||
systemNavigationBarColor: Color(0xff314345),
|
||||
),
|
||||
);
|
||||
final book = await Book.load(), progress = await Progress.load();
|
||||
final game = Game(book, progress);
|
||||
await game.restore();
|
||||
runApp(LumenApp(game: game));
|
||||
}
|
||||
|
||||
class LumenApp extends StatelessWidget {
|
||||
const LumenApp({super.key, required this.game, this.adsEnabled = true});
|
||||
final Game game;
|
||||
final bool adsEnabled;
|
||||
@override
|
||||
Widget build(BuildContext context) => MaterialApp(
|
||||
title: 'Lumen',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: blue, surface: cream),
|
||||
scaffoldBackgroundColor: cream,
|
||||
fontFamily: 'MaraHand',
|
||||
textTheme: ThemeData.light().textTheme.apply(
|
||||
fontFamily: 'MaraHand',
|
||||
bodyColor: ink,
|
||||
displayColor: ink,
|
||||
),
|
||||
dialogTheme: const DialogThemeData(backgroundColor: cream),
|
||||
textButtonTheme: TextButtonThemeData(
|
||||
style: TextButton.styleFrom(textStyle: hand(22), foregroundColor: blue),
|
||||
),
|
||||
),
|
||||
home: Notebook(game: game, adsEnabled: adsEnabled),
|
||||
);
|
||||
}
|
||||
|
||||
class Notebook extends StatefulWidget {
|
||||
const Notebook({super.key, required this.game, required this.adsEnabled});
|
||||
final Game game;
|
||||
final bool adsEnabled;
|
||||
@override
|
||||
State<Notebook> createState() => _NotebookState();
|
||||
}
|
||||
|
||||
class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
Game get g => widget.game;
|
||||
Progress get prefs => g.progress;
|
||||
late final Narrator narrator;
|
||||
late final Ads ads;
|
||||
String _route = '';
|
||||
String get route =>
|
||||
'${g.screen.name}:${g.screen == Screen.story ? g.storyIndex : g.campaignIndex}';
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
narrator = Narrator(g.book.tracks);
|
||||
ads = Ads(enabled: widget.adsEnabled);
|
||||
g.addListener(_changed);
|
||||
_route = route;
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
unawaited(ads.start());
|
||||
});
|
||||
}
|
||||
|
||||
void _changed() {
|
||||
if (_route != route) {
|
||||
_route = route;
|
||||
unawaited(narrator.stop());
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state != AppLifecycleState.resumed) {
|
||||
unawaited(narrator.stop());
|
||||
unawaited(prefs.flushed);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
g.removeListener(_changed);
|
||||
narrator.dispose();
|
||||
ads.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void toast(String text) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(text, style: hand(20, color: cream)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> confirm(
|
||||
String title,
|
||||
String text,
|
||||
String yes, {
|
||||
String no = 'Keep reading',
|
||||
}) async =>
|
||||
await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: Text(title, style: hand(29)),
|
||||
content: Text(text, style: hand(23)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c, false),
|
||||
child: Text(no),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c, true),
|
||||
child: Text(yes),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
Future<void> message(
|
||||
String title,
|
||||
String text, {
|
||||
String close = 'Keep going',
|
||||
}) async {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: Text(title, style: hand(29)),
|
||||
content: SingleChildScrollView(child: Text(text, style: hand(23))),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(c), child: Text(close)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> turn(int direction) async {
|
||||
final next = (g.storyIndex + direction).clamp(0, 5);
|
||||
if (next == g.storyIndex) return;
|
||||
if (g.storyIndex == 2 && direction > 0 && !g.won) {
|
||||
unawaited(narrator.stop());
|
||||
if (!await confirm(
|
||||
'Leave a ribbon here?',
|
||||
'Your puzzle marks are saved. You can read the memory now and come back to solve the pattern whenever you like.',
|
||||
'Read ahead',
|
||||
no: 'Keep solving',
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
await prefs.set('notebook_read_ahead', true);
|
||||
}
|
||||
g.showStory(next);
|
||||
}
|
||||
|
||||
void back() {
|
||||
if (g.busy) {
|
||||
g.home();
|
||||
return;
|
||||
}
|
||||
switch (g.screen) {
|
||||
case Screen.story:
|
||||
if (g.storyIndex > 0) {
|
||||
turn(-1);
|
||||
} else {
|
||||
g.home();
|
||||
}
|
||||
case Screen.briefing:
|
||||
case Screen.reveal:
|
||||
g.contents();
|
||||
case Screen.game:
|
||||
if (g.mode == Mode.campaign) {
|
||||
g.contents();
|
||||
} else {
|
||||
g.home();
|
||||
}
|
||||
case Screen.contents:
|
||||
g.home();
|
||||
case Screen.home:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => PopScope(
|
||||
canPop: g.screen == Screen.home && !g.busy,
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
if (!didPop) back();
|
||||
},
|
||||
child: Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
switch (g.screen) {
|
||||
Screen.home => home(),
|
||||
Screen.story => story(),
|
||||
Screen.contents => contents(),
|
||||
Screen.briefing => briefing(),
|
||||
Screen.game => game(),
|
||||
Screen.reveal => reveal(),
|
||||
},
|
||||
if (g.busy)
|
||||
Positioned.fill(
|
||||
child: ColoredBox(
|
||||
color: cream.withValues(alpha: .9),
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const CircularProgressIndicator(color: blue),
|
||||
writing('Finding a fresh pattern…'),
|
||||
InkButton('Back to the notebook', g.home),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget column(List<Widget> children) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: children,
|
||||
);
|
||||
Widget action(String title, VoidCallback run, {bool primary = false}) =>
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: InkButton(title, run, primary: primary),
|
||||
);
|
||||
Widget gap([double n = 16]) => SizedBox(height: n);
|
||||
Widget divider() => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 18),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Divider(color: muted.withValues(alpha: .3))),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
child: Text('❦', style: hand(27, color: muted)),
|
||||
),
|
||||
Expanded(child: Divider(color: muted.withValues(alpha: .3))),
|
||||
],
|
||||
),
|
||||
);
|
||||
Widget folio(String text) => writing(text, size: 15, color: blue);
|
||||
Widget home() => ColoredBox(
|
||||
color: cream,
|
||||
child: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
key: const ValueKey('home-scroll'),
|
||||
padding: const EdgeInsets.fromLTRB(28, 26, 28, 36),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 650),
|
||||
child: column([
|
||||
folio('L U M E N / AN ISLAND STORY'),
|
||||
writing('A light to come\nhome to.', size: 40),
|
||||
Image.asset(
|
||||
'assets/artwork/home-harbour-v2.png',
|
||||
height: 220,
|
||||
fit: BoxFit.contain,
|
||||
semanticLabel: 'Watercolour of the island at dusk, with the lighthouse and Gran’s cottage.',
|
||||
),
|
||||
writing(
|
||||
'Some things are worth keeping. — Gran',
|
||||
size: 25,
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
Cover(onTap: g.openNotebook),
|
||||
action(
|
||||
'Open Mara’s notebook · ${g.recoveredCount} / 12',
|
||||
g.openNotebook,
|
||||
primary: true,
|
||||
),
|
||||
gap(),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
Text(
|
||||
'${g.streak}\nDAY STREAK',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(18, color: blue),
|
||||
),
|
||||
Text(
|
||||
'${g.solved}\nPATTERNS FOUND',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(18, color: blue),
|
||||
),
|
||||
],
|
||||
),
|
||||
divider(),
|
||||
folio('A SMALL DAILY RITUAL'),
|
||||
writing(
|
||||
DateFormat('EEEE, d MMMM').format(DateTime.now()),
|
||||
size: 27,
|
||||
),
|
||||
action(
|
||||
'Play today’s puzzle →',
|
||||
() => g.startDaily(DateTime.now()),
|
||||
),
|
||||
gap(),
|
||||
folio('BY THE COTTAGE WINDOW'),
|
||||
writing(
|
||||
'A few spare pages for practice. For overlapping-area puzzles, follow the notebook’s story.',
|
||||
size: 22,
|
||||
color: muted,
|
||||
),
|
||||
action('Difficulty · ${g.difficulty.label} ▾', chooseDifficulty),
|
||||
action(
|
||||
'Practice · ${g.difficulty.label} · Level ${g.practiceLevel}',
|
||||
() => unawaited(g.startPractice()),
|
||||
),
|
||||
action('How to play', rules),
|
||||
action('Privacy & advertising', privacy),
|
||||
action(
|
||||
'Open-source licenses',
|
||||
() =>
|
||||
showLicensePage(context: context, applicationName: 'Lumen'),
|
||||
),
|
||||
gap(),
|
||||
writing(
|
||||
'Leave a light in the window.',
|
||||
size: 26,
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget navigation() => column([
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: InkButton('Contents', g.contents, size: 20)),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: InkButton('Bookmark', () {
|
||||
unawaited(
|
||||
prefs.set(
|
||||
'notebook_manual_bookmark',
|
||||
g.book.pages[g.storyIndex].id,
|
||||
),
|
||||
);
|
||||
toast('A ribbon marks this page.');
|
||||
}, size: 20),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(child: InkButton('Close book', g.home, size: 20)),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: InkButton(
|
||||
'← Previous leaf',
|
||||
g.storyIndex > 0 ? () => turn(-1) : null,
|
||||
size: 21,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: InkButton(
|
||||
g.storyIndex == 5 ? 'End of this trail' : 'Next leaf →',
|
||||
g.storyIndex < 5 ? () => turn(1) : null,
|
||||
size: 21,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
]);
|
||||
Widget reading(String text) => ListenableBuilder(
|
||||
listenable: narrator,
|
||||
builder: (context, _) {
|
||||
final passage = narrator.passage,
|
||||
index = passage.isEmpty ? -1 : text.indexOf(passage);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
style: hand(g.storyIndex == 0 ? 22 : 21),
|
||||
children: index < 0
|
||||
? [TextSpan(text: text)]
|
||||
: [
|
||||
TextSpan(text: text.substring(0, index)),
|
||||
TextSpan(
|
||||
text: passage,
|
||||
style: TextStyle(
|
||||
backgroundColor: amber.withValues(alpha: .35),
|
||||
),
|
||||
),
|
||||
TextSpan(text: text.substring(index + passage.length)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
Widget audio() => ListenableBuilder(
|
||||
listenable: narrator,
|
||||
builder: (context, _) => column([
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: InkButton(
|
||||
narrator.label,
|
||||
narrator.loading
|
||||
? null
|
||||
: () => narrator.toggle(
|
||||
g.book.pages[g.storyIndex].id,
|
||||
prefs.decimal('recording_speed'),
|
||||
),
|
||||
size: 21,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 5),
|
||||
Expanded(child: InkButton('Stop', () => narrator.stop(), size: 21)),
|
||||
const SizedBox(width: 5),
|
||||
Expanded(child: InkButton('Speed', speed, size: 21)),
|
||||
],
|
||||
),
|
||||
writing(narrator.status, size: 17, color: muted),
|
||||
]),
|
||||
);
|
||||
Widget illustration(
|
||||
String asset,
|
||||
String description, {
|
||||
VoidCallback? onTap,
|
||||
}) => Semantics(
|
||||
image: true,
|
||||
button: onTap != null,
|
||||
label: description,
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Image.asset(
|
||||
'assets/artwork/$asset',
|
||||
height: 155,
|
||||
fit: BoxFit.contain,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget story() {
|
||||
final p = g.book.pages[g.storyIndex];
|
||||
final body = <Widget>[
|
||||
folio('MARA’S NOTEBOOK / ${g.storyIndex + 1} OF 6'),
|
||||
writing(p.title, size: 31),
|
||||
];
|
||||
switch (g.storyIndex) {
|
||||
case 0:
|
||||
body.addAll([
|
||||
writing('A few things worth keeping', size: 20, color: muted),
|
||||
divider(),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
]);
|
||||
case 1:
|
||||
body.addAll([
|
||||
illustration(
|
||||
'cottage-vignette-v1.png',
|
||||
'Watercolour of Gran’s stone cottage, blue door and warm window.',
|
||||
),
|
||||
writing('A note beside the window · Mara', size: 17, color: muted),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
]);
|
||||
case 2:
|
||||
body.addAll([
|
||||
writing(
|
||||
'Restore a small light, or leave a bookmark and read on.',
|
||||
size: 21,
|
||||
color: muted,
|
||||
),
|
||||
puzzleBody(),
|
||||
]);
|
||||
case 3:
|
||||
body.addAll([
|
||||
const Sketch('match'),
|
||||
writing(
|
||||
g.recovered(0)
|
||||
? 'A pattern restored · a memory kept'
|
||||
: 'A memory to read · your puzzle can wait',
|
||||
size: 17,
|
||||
color: muted,
|
||||
),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
]);
|
||||
case 4:
|
||||
if (!prefs.flag('notebook_note_open')) {
|
||||
body.addAll([
|
||||
writing('A folded scrap, tucked between the leaves.'),
|
||||
GestureDetector(
|
||||
onTap: openLetter,
|
||||
child: const Sketch('envelope', height: 190),
|
||||
),
|
||||
action('Unfold Gran’s note', openLetter),
|
||||
writing(
|
||||
'You don’t have to solve anything to discover this.',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
body.addAll([
|
||||
writing(
|
||||
'For the crossing',
|
||||
size: 28,
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
action('Fold the note again', () {
|
||||
unawaited(narrator.stop());
|
||||
unawaited(prefs.set('notebook_note_open', false));
|
||||
setState(() {});
|
||||
}),
|
||||
]);
|
||||
}
|
||||
case 5:
|
||||
body.addAll([
|
||||
illustration(
|
||||
'lantern-vignette-v1.png',
|
||||
'Watercolour of Mara’s blue storm lantern. Tap to examine the repaired handle.',
|
||||
onTap: inspect,
|
||||
),
|
||||
writing(
|
||||
prefs.flag('notebook_handle_seen')
|
||||
? 'A repair made to keep small fingers safe.'
|
||||
: 'Tap the lantern to look a little closer.',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
action('Follow the lantern into the next entry →', () {
|
||||
unawaited(
|
||||
prefs.set(
|
||||
'story_access_level',
|
||||
g.accessible < 1 ? 1 : g.accessible,
|
||||
),
|
||||
);
|
||||
g.briefing(1);
|
||||
}),
|
||||
]);
|
||||
}
|
||||
return Leaf(
|
||||
key: ValueKey('story-${g.storyIndex}'),
|
||||
onTurn: (d) => turn(d),
|
||||
body: column(body),
|
||||
footer: navigation(),
|
||||
);
|
||||
}
|
||||
|
||||
void openLetter() {
|
||||
unawaited(prefs.set('notebook_note_open', true));
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> inspect() async {
|
||||
await prefs.set('notebook_handle_seen', true);
|
||||
await message(
|
||||
'A careful repair',
|
||||
'The wire is hidden under a strip of cloth. In the margin, Gran has written: “The light matters. So do the hands carrying it.”',
|
||||
close: 'Keep that thought',
|
||||
);
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
Future<void> speed() async {
|
||||
await narrator.pause();
|
||||
if (!mounted) return;
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (c) => SimpleDialog(
|
||||
title: Text('Recording speed', style: hand(29)),
|
||||
children: [
|
||||
for (final entry in [
|
||||
(0.85, 'Unhurried · 0.85×'),
|
||||
(1.0, 'Original reading · 1.0×'),
|
||||
(1.15, 'A little faster · 1.15×'),
|
||||
])
|
||||
SimpleDialogOption(
|
||||
onPressed: () {
|
||||
unawaited(prefs.set('recording_speed', entry.$1));
|
||||
Navigator.pop(c);
|
||||
},
|
||||
child: Text(entry.$2, style: hand(23)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget contents() => Leaf(
|
||||
key: const ValueKey('contents'),
|
||||
body: column([
|
||||
folio('THE NOTEBOOK BELONGS TO'),
|
||||
writing('Mara Wren', size: 40),
|
||||
writing('The Last Light', size: 33),
|
||||
writing(
|
||||
'For you, when you are ready.\nWith all my love, Gran.',
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
divider(),
|
||||
folio('THE COTTAGE · OPENING LEAVES'),
|
||||
for (var i = 0; i < 6; i++)
|
||||
action('${i + 1} · ${g.book.pages[i].title}', () => g.showStory(i)),
|
||||
action('Return to my ribbon bookmark', () {
|
||||
final i = g.book.pages.indexWhere(
|
||||
(p) => p.id == prefs.text('notebook_manual_bookmark'),
|
||||
);
|
||||
g.showStory(i < 0 ? 0 : i);
|
||||
}),
|
||||
divider(),
|
||||
writing(g.book.premise),
|
||||
writing(
|
||||
'${g.recoveredCount} / 12 memories tucked between these pages',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
for (var i = 0; i < 12; i++) ...[
|
||||
if (i % 4 == 0) ...[
|
||||
gap(24),
|
||||
writing(g.book.levels[i].chapter, size: 28, color: blue),
|
||||
],
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: InkButton(
|
||||
'${(i + 1).toString().padLeft(2, '0')} · ${g.recovered(i) ? '${g.book.levels[i].object} ✓' : g.book.levels[i].title}${i > g.accessible ? ' · not yet' : ''}',
|
||||
i <= g.accessible
|
||||
? () {
|
||||
if (g.recovered(i)) {
|
||||
g.reveal(i);
|
||||
} else {
|
||||
g.briefing(i);
|
||||
}
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
action('Close the notebook', g.home),
|
||||
]),
|
||||
);
|
||||
Widget briefing() {
|
||||
final l = g.book.levels[g.campaignIndex];
|
||||
return Leaf(
|
||||
key: ValueKey('briefing-${g.campaignIndex}'),
|
||||
body: column([
|
||||
folio('MARA’S NOTEBOOK / LEAF ${g.campaignIndex + 1}'),
|
||||
writing(l.chapter, size: 20, color: blue),
|
||||
writing(l.title, size: 33),
|
||||
gap(),
|
||||
writing(l.before, size: 25),
|
||||
divider(),
|
||||
writing(
|
||||
g.campaignIndex < 2
|
||||
? 'Light the cells to match each row and column total. Cross out the cells that stay dark. The finished grid is a picture from the story.'
|
||||
: 'A, B and C are outlined areas with their own light totals. Shared cells count in each area they belong to. Compare clues and subtract their shared parts to find new deductions.',
|
||||
size: 22,
|
||||
color: muted,
|
||||
),
|
||||
action(
|
||||
prefs.contains('grid_story_v1_${g.campaignIndex}')
|
||||
? 'Continue this pattern →'
|
||||
: 'Restore the pattern →',
|
||||
() => g.startCampaign(g.campaignIndex),
|
||||
primary: true,
|
||||
),
|
||||
action('Back to notebook', g.contents),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Widget puzzleBody() {
|
||||
final p = g.puzzle;
|
||||
if (p == null) return const SizedBox.shrink();
|
||||
return column([
|
||||
if (p.regions.isNotEmpty) ...[
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
children: [
|
||||
for (var i = 0; i < p.regions.length; i++)
|
||||
InkButton(
|
||||
'${p.regions[i].label} · ${List.generate(g.cells.length, (j) => j).where((j) => p.regions[i].contains(j, p.size) && g.cells[j] == 1).length} / ${p.regionTotal(p.regions[i])}',
|
||||
() => g.area(i),
|
||||
size: 21,
|
||||
primary: i == g.selectedArea,
|
||||
),
|
||||
],
|
||||
),
|
||||
writing('Tap A, B or C to highlight its area', size: 17, color: muted),
|
||||
],
|
||||
Board(
|
||||
puzzle: p,
|
||||
cells: g.cells,
|
||||
onMark: g.mark,
|
||||
selectedArea: g.selectedArea,
|
||||
won: g.won,
|
||||
),
|
||||
writing(
|
||||
g.won
|
||||
? 'Already restored. Turn the leaf to revisit the memory.'
|
||||
: 'Tap: light → cross → clear. Mark every cell.',
|
||||
size: 18,
|
||||
color: muted,
|
||||
),
|
||||
if (!g.won)
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: InkButton(
|
||||
'Undo a mark',
|
||||
g.canUndo ? g.undo : null,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: InkButton(
|
||||
prefs.flag('hint_${g.key}')
|
||||
? 'Hint · rewarded ad'
|
||||
: 'Hint · free',
|
||||
hint,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
Widget game() => Leaf(
|
||||
key: ValueKey('game-${g.key}'),
|
||||
body: column([
|
||||
folio(
|
||||
g.mode == Mode.daily
|
||||
? 'DAILY / ${DateFormat('d MMMM').format(g.date)}'
|
||||
: g.mode == Mode.campaign
|
||||
? 'THE LAST LIGHT / ${g.campaignIndex + 1} OF 12'
|
||||
: 'CLASSIC / ${g.difficulty.label} / LEVEL ${g.playingLevel}',
|
||||
),
|
||||
writing(
|
||||
g.mode == Mode.campaign
|
||||
? g.book.levels[g.campaignIndex].title
|
||||
: 'Find the light.',
|
||||
size: 32,
|
||||
),
|
||||
writing(
|
||||
g.puzzle!.regions.isEmpty
|
||||
? 'Match the totals. Let the pattern emerge.'
|
||||
: 'Compare rows, columns and overlapping areas.',
|
||||
size: 21,
|
||||
color: muted,
|
||||
),
|
||||
puzzleBody(),
|
||||
if (g.won) ...[
|
||||
writing('A moment of clarity.', size: 29),
|
||||
action(
|
||||
g.mode == Mode.daily ? 'Return to the notebook' : 'Next puzzle →',
|
||||
g.mode == Mode.daily ? g.home : nextPractice,
|
||||
primary: true,
|
||||
),
|
||||
],
|
||||
action('How to play', rules),
|
||||
action('Back to notebook', g.mode == Mode.campaign ? g.contents : g.home),
|
||||
]),
|
||||
);
|
||||
Future<void> hint() async {
|
||||
final requested = g.key;
|
||||
void give() async {
|
||||
if (!mounted ||
|
||||
g.key != requested ||
|
||||
g.won ||
|
||||
!(g.screen == Screen.game ||
|
||||
g.screen == Screen.story && g.storyIndex == 2)) {
|
||||
return;
|
||||
}
|
||||
final h = g.applyHint();
|
||||
if (h == null) return;
|
||||
await message(
|
||||
'Row ${h.cell ~/ g.puzzle!.size + 1}, column ${h.cell % g.puzzle!.size + 1}',
|
||||
'${h.explanation}\n\n${h.value == 1 ? 'This cell is lit.' : 'This cell stays dark.'}',
|
||||
);
|
||||
if (mounted && g.key == requested) g.check();
|
||||
}
|
||||
|
||||
if (!prefs.flag('hint_$requested')) {
|
||||
await prefs.set('hint_$requested', true);
|
||||
give();
|
||||
return;
|
||||
}
|
||||
if (!await confirm(
|
||||
'A little nudge?',
|
||||
'Watch a rewarded ad for one explained hint.',
|
||||
'Watch ad',
|
||||
no: 'Keep thinking',
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
if (!await ads.hint(give)) {
|
||||
toast('No ad available. Please try again later.');
|
||||
}
|
||||
}
|
||||
|
||||
void nextPractice() {
|
||||
final n = prefs.number('practiceCompleted');
|
||||
if (n > 0 && n % 4 == 0) {
|
||||
ads.between(() => unawaited(g.startPractice()));
|
||||
} else {
|
||||
unawaited(g.startPractice());
|
||||
}
|
||||
}
|
||||
|
||||
Widget reveal() {
|
||||
final i = g.campaignIndex, l = g.book.levels[i];
|
||||
return Leaf(
|
||||
key: ValueKey('reveal-$i'),
|
||||
body: column([
|
||||
folio('MARA’S NOTEBOOK / LEAF ${i + 1}'),
|
||||
writing(
|
||||
'Something found. Something remembered.',
|
||||
size: 23,
|
||||
color: muted,
|
||||
),
|
||||
writing(l.object, size: 35),
|
||||
PixelPicture(l.picture, label: l.object),
|
||||
writing(l.after, size: 25),
|
||||
gap(),
|
||||
writing(
|
||||
'Kept safe, between these pages. — M.',
|
||||
size: 23,
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
divider(),
|
||||
if (i == 11) ...[
|
||||
folio('THE END · YOUR WATCH HAS BEGUN'),
|
||||
writing(
|
||||
'Twelve patterns. One light brought home. The daily puzzle will be here whenever you return.',
|
||||
),
|
||||
action('Return to the notebook', g.contents, primary: true),
|
||||
action('Today’s puzzle', () => g.startDaily(DateTime.now())),
|
||||
] else
|
||||
action('Turn the page →', () {
|
||||
void next() {
|
||||
if (mounted) g.briefing(i + 1);
|
||||
}
|
||||
|
||||
if ((i + 1) % 4 == 0 && !prefs.flag('storyAd_$i')) {
|
||||
unawaited(prefs.set('storyAd_$i', true));
|
||||
ads.between(next);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
}, primary: true),
|
||||
action('Back to notebook', g.contents),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> chooseDifficulty() async {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (c) => SimpleDialog(
|
||||
title: Text('Classic practice pace', style: hand(29)),
|
||||
children: [
|
||||
for (final d in Difficulty.values)
|
||||
SimpleDialogOption(
|
||||
onPressed: () {
|
||||
g.selectDifficulty(d);
|
||||
Navigator.pop(c);
|
||||
},
|
||||
child: Text('${d.label} — ${d.description}', style: hand(23)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void rules() => message(
|
||||
'Find the light',
|
||||
'Light exactly as many cells as the number beside each row and above each column.\n\nTap to cycle: empty → light → crossed out → empty. Mark every cell to finish. Small dots mark fixed clues.\n\nA, B and C are overlapping areas with their own totals. Shared cells count in both areas. Compare clues and subtract their shared parts to find new deductions.\n\nEvery story grid reveals an object. Later pages require area comparisons; all are solvable without guessing. Classic practice grades the length of simpler row and column chains.\n\nOne free explained hint per puzzle, then optional rewarded hints. Streaks count consecutive daily completions on this device.',
|
||||
close: 'Got it',
|
||||
);
|
||||
Future<void> privacy() async {
|
||||
if (!await ads.privacy()) {
|
||||
await message(
|
||||
'Privacy & advertising',
|
||||
'Game progress stays on this device. No account or game backend is used. Google advertising services may process device and ad interaction data when ads are available.\n\nNo advertising privacy options are currently required or available for your region.',
|
||||
close: 'Close',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:google_mobile_ads/google_mobile_ads.dart';
|
||||
|
||||
class Ads {
|
||||
Ads({this.enabled = true});
|
||||
final bool enabled;
|
||||
RewardedAd? _reward;
|
||||
InterstitialAd? _interstitial;
|
||||
bool _started = false,
|
||||
_rewardLoading = false,
|
||||
_interstitialLoading = false,
|
||||
_disposed = false;
|
||||
DateTime? _rewardAt, _interstitialAt;
|
||||
bool get supported =>
|
||||
enabled &&
|
||||
!kIsWeb &&
|
||||
(defaultTargetPlatform == TargetPlatform.android ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS);
|
||||
Future<void> start() async {
|
||||
if (!supported) return;
|
||||
ConsentInformation.instance.requestConsentInfoUpdate(
|
||||
ConsentRequestParameters(),
|
||||
() {
|
||||
ConsentForm.loadAndShowConsentFormIfRequired((_) => _initialize());
|
||||
},
|
||||
(_) => _initialize(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _initialize() async {
|
||||
if (_disposed ||
|
||||
_started ||
|
||||
!await ConsentInformation.instance.canRequestAds()) {
|
||||
return;
|
||||
}
|
||||
_started = true;
|
||||
await MobileAds.instance.initialize();
|
||||
await _load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
if (_disposed ||
|
||||
!supported ||
|
||||
!await ConsentInformation.instance.canRequestAds()) {
|
||||
return;
|
||||
}
|
||||
final ios = defaultTargetPlatform == TargetPlatform.iOS;
|
||||
if (_reward == null && !_rewardLoading) {
|
||||
_rewardLoading = true;
|
||||
RewardedAd.load(
|
||||
adUnitId: const String.fromEnvironment('ADMOB_REWARDED_ID').isNotEmpty
|
||||
? const String.fromEnvironment('ADMOB_REWARDED_ID')
|
||||
: ios
|
||||
? 'ca-app-pub-3940256099942544/1712485313'
|
||||
: 'ca-app-pub-3940256099942544/5224354917',
|
||||
request: const AdRequest(),
|
||||
rewardedAdLoadCallback: RewardedAdLoadCallback(
|
||||
onAdLoaded: (a) {
|
||||
_rewardLoading = false;
|
||||
if (_disposed) {
|
||||
a.dispose();
|
||||
return;
|
||||
}
|
||||
_reward = a;
|
||||
_rewardAt = DateTime.now();
|
||||
},
|
||||
onAdFailedToLoad: (_) {
|
||||
_rewardLoading = false;
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
if (_interstitial == null && !_interstitialLoading) {
|
||||
_interstitialLoading = true;
|
||||
InterstitialAd.load(
|
||||
adUnitId:
|
||||
const String.fromEnvironment('ADMOB_INTERSTITIAL_ID').isNotEmpty
|
||||
? const String.fromEnvironment('ADMOB_INTERSTITIAL_ID')
|
||||
: ios
|
||||
? 'ca-app-pub-3940256099942544/4411468910'
|
||||
: 'ca-app-pub-3940256099942544/1033173712',
|
||||
request: const AdRequest(),
|
||||
adLoadCallback: InterstitialAdLoadCallback(
|
||||
onAdLoaded: (a) {
|
||||
_interstitialLoading = false;
|
||||
if (_disposed) {
|
||||
a.dispose();
|
||||
return;
|
||||
}
|
||||
_interstitial = a;
|
||||
_interstitialAt = DateTime.now();
|
||||
},
|
||||
onAdFailedToLoad: (_) {
|
||||
_interstitialLoading = false;
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> hint(VoidCallback earned) async {
|
||||
if (!supported || !await ConsentInformation.instance.canRequestAds()) {
|
||||
return false;
|
||||
}
|
||||
final a = _reward;
|
||||
_reward = null;
|
||||
if (a == null ||
|
||||
_rewardAt == null ||
|
||||
DateTime.now().difference(_rewardAt!).inMinutes >= 58) {
|
||||
a?.dispose();
|
||||
unawaited(_load());
|
||||
return false;
|
||||
}
|
||||
a.fullScreenContentCallback = FullScreenContentCallback(
|
||||
onAdDismissedFullScreenContent: (ad) {
|
||||
ad.dispose();
|
||||
_load();
|
||||
},
|
||||
onAdFailedToShowFullScreenContent: (ad, e) {
|
||||
ad.dispose();
|
||||
_load();
|
||||
},
|
||||
);
|
||||
a.show(
|
||||
onUserEarnedReward: (ad, reward) {
|
||||
earned();
|
||||
},
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> between(VoidCallback next) async {
|
||||
if (!supported || !await ConsentInformation.instance.canRequestAds()) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
final a = _interstitial;
|
||||
_interstitial = null;
|
||||
if (a == null ||
|
||||
_interstitialAt == null ||
|
||||
DateTime.now().difference(_interstitialAt!).inMinutes >= 58) {
|
||||
a?.dispose();
|
||||
next();
|
||||
unawaited(_load());
|
||||
return;
|
||||
}
|
||||
var routed = false;
|
||||
void finish() {
|
||||
if (routed) return;
|
||||
routed = true;
|
||||
a.dispose();
|
||||
next();
|
||||
_load();
|
||||
}
|
||||
|
||||
a.fullScreenContentCallback = FullScreenContentCallback(
|
||||
onAdDismissedFullScreenContent: (_) => finish(),
|
||||
onAdFailedToShowFullScreenContent: (_, e) => finish(),
|
||||
);
|
||||
a.show();
|
||||
}
|
||||
|
||||
Future<bool> privacy() async {
|
||||
if (!supported) return false;
|
||||
if (await ConsentInformation.instance
|
||||
.getPrivacyOptionsRequirementStatus() !=
|
||||
PrivacyOptionsRequirementStatus.required) {
|
||||
return false;
|
||||
}
|
||||
ConsentForm.showPrivacyOptionsForm((_) {});
|
||||
return true;
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_reward?.dispose();
|
||||
_interstitial?.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:audio_session/audio_session.dart';
|
||||
|
||||
class Narrator extends ChangeNotifier {
|
||||
Narrator(this.tracks) {
|
||||
_subscriptions.add(
|
||||
_player.playerStateStream.listen((_) => notifyListeners()),
|
||||
);
|
||||
_subscriptions.add(_player.positionStream.listen((_) => notifyListeners()));
|
||||
}
|
||||
final Map<String, dynamic> tracks;
|
||||
final _player = AudioPlayer();
|
||||
final List<StreamSubscription<dynamic>> _subscriptions = [];
|
||||
String page = '', error = '';
|
||||
bool loading = false;
|
||||
int _generation = 0;
|
||||
bool get playing =>
|
||||
_player.playing && _player.processingState != ProcessingState.completed;
|
||||
bool get finished => _player.processingState == ProcessingState.completed;
|
||||
bool get paused => page.isNotEmpty && !playing && !finished && !loading;
|
||||
Duration get position => _player.position;
|
||||
String get label => loading
|
||||
? 'Opening recording…'
|
||||
: playing
|
||||
? 'Pause recording'
|
||||
: finished
|
||||
? 'Replay recording'
|
||||
: paused
|
||||
? 'Resume recording'
|
||||
: 'Play this reading';
|
||||
String _time(Duration d) =>
|
||||
'${d.inMinutes}:${(d.inSeconds % 60).toString().padLeft(2, '0')}';
|
||||
String get status => error.isNotEmpty
|
||||
? error
|
||||
: page.isEmpty
|
||||
? 'A recorded reading, kept with this page'
|
||||
: finished
|
||||
? 'End of the reading · listen again whenever you like'
|
||||
: '${playing ? 'Playing' : 'Paused'} · ${_time(position)} / ${_time(_player.duration ?? Duration.zero)}';
|
||||
String get passage {
|
||||
if (page.isEmpty || finished) return '';
|
||||
for (final cue in tracks[page]?['cues'] ?? []) {
|
||||
if (position.inMilliseconds >= cue['startMs'] &&
|
||||
position.inMilliseconds < cue['endMs']) {
|
||||
return cue['text'];
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
Future<void> toggle(String id, double speed) async {
|
||||
if (loading) return;
|
||||
if (playing && page == id) {
|
||||
await _player.pause();
|
||||
return;
|
||||
}
|
||||
final generation = ++_generation;
|
||||
try {
|
||||
if (page != id) {
|
||||
loading = true;
|
||||
error = '';
|
||||
notifyListeners();
|
||||
final session = await AudioSession.instance;
|
||||
await session.configure(const AudioSessionConfiguration.speech());
|
||||
if (generation != _generation) return;
|
||||
page = id;
|
||||
await _player.setAsset('assets/audio/${tracks[id]['file']}');
|
||||
if (generation != _generation) return;
|
||||
} else if (finished) {
|
||||
await _player.seek(Duration.zero);
|
||||
}
|
||||
await _player.setSpeed(speed);
|
||||
if (generation != _generation) return;
|
||||
loading = false;
|
||||
notifyListeners();
|
||||
unawaited(
|
||||
_player.play().catchError((Object e) {
|
||||
error = 'This recording could not be played. You can still read the entry.';
|
||||
notifyListeners();
|
||||
}),
|
||||
);
|
||||
} catch (e) {
|
||||
if (generation == _generation) {
|
||||
error =
|
||||
'This recording could not be played. You can still read the entry.';
|
||||
loading = false;
|
||||
page = '';
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> pause() async {
|
||||
await _player.pause();
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
++_generation;
|
||||
page = '';
|
||||
loading = false;
|
||||
error = '';
|
||||
notifyListeners();
|
||||
await _player.stop();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final s in _subscriptions) {
|
||||
unawaited(s.cancel());
|
||||
}
|
||||
unawaited(_player.dispose());
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Flutter has its own store; the former Android `lumen.xml` is never imported.
|
||||
class Progress {
|
||||
Progress._(this._disk, this._values);
|
||||
final SharedPreferencesAsync? _disk;
|
||||
final Map<String, Object> _values;
|
||||
static Future<Progress> load() async {
|
||||
final disk = SharedPreferencesAsync();
|
||||
return Progress._(disk, (await disk.getAll()).cast<String, Object>());
|
||||
}
|
||||
|
||||
factory Progress.memory([Map<String, Object> values = const {}]) =>
|
||||
Progress._(null, Map.of(values));
|
||||
int number(String key, [int fallback = 0]) =>
|
||||
(_values[key] as num?)?.toInt() ?? fallback;
|
||||
double decimal(String key, [double fallback = 1]) =>
|
||||
(_values[key] as num?)?.toDouble() ?? fallback;
|
||||
bool flag(String key) => _values[key] == true;
|
||||
String text(String key, [String fallback = '']) =>
|
||||
_values[key] as String? ?? fallback;
|
||||
bool contains(String key) => _values.containsKey(key);
|
||||
Map<String, Object> get snapshot => Map.unmodifiable(_values);
|
||||
Future<void> _writes = Future.value();
|
||||
Future<void> set(String key, Object value) {
|
||||
_values[key] = value;
|
||||
final disk = _disk;
|
||||
if (disk == null) return Future.value();
|
||||
_writes = _writes.then((_) async {
|
||||
switch (value) {
|
||||
case bool v:
|
||||
await disk.setBool(key, v);
|
||||
case int v:
|
||||
await disk.setInt(key, v);
|
||||
case double v:
|
||||
await disk.setDouble(key, v);
|
||||
case String v:
|
||||
await disk.setString(key, v);
|
||||
default:
|
||||
throw ArgumentError('Unsupported preference');
|
||||
}
|
||||
});
|
||||
return _writes;
|
||||
}
|
||||
|
||||
Future<void> get flushed => _writes;
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/puzzle.dart';
|
||||
import 'paper.dart';
|
||||
|
||||
class Board extends StatelessWidget {
|
||||
const Board({
|
||||
super.key,
|
||||
required this.puzzle,
|
||||
required this.cells,
|
||||
required this.onMark,
|
||||
this.selectedArea = 0,
|
||||
this.won = false,
|
||||
});
|
||||
final Puzzle puzzle;
|
||||
final List<int> cells;
|
||||
final ValueChanged<int> onMark;
|
||||
final int selectedArea;
|
||||
final bool won;
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 350),
|
||||
child: AspectRatio(
|
||||
aspectRatio: 1,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, c) {
|
||||
final n = puzzle.size,
|
||||
u = c.maxWidth / (n + 1.3),
|
||||
r = puzzle.regions.isEmpty
|
||||
? null
|
||||
: puzzle.regions[selectedArea];
|
||||
Widget clue(String text, bool complete) => SizedBox(
|
||||
width: u,
|
||||
height: u,
|
||||
child: Center(
|
||||
child: Text(
|
||||
text,
|
||||
style: hand(
|
||||
(u * .42).clamp(16, 23),
|
||||
color: complete ? blue : muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
bool complete(Iterable<int> indices, int total) =>
|
||||
indices.where((i) => cells[i] == 1).length == total;
|
||||
return Align(
|
||||
alignment: Alignment.center,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
SizedBox(width: u, height: u),
|
||||
for (var col = 0; col < n; col++)
|
||||
clue(
|
||||
'${puzzle.cols[col]}',
|
||||
complete(
|
||||
List.generate(n, (i) => i * n + col),
|
||||
puzzle.cols[col],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
for (var row = 0; row < n; row++)
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
clue(
|
||||
'${puzzle.rows[row]}',
|
||||
complete(
|
||||
List.generate(n, (i) => row * n + i),
|
||||
puzzle.rows[row],
|
||||
),
|
||||
),
|
||||
for (var col = 0; col < n; col++)
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final i = row * n + col,
|
||||
value = cells[i],
|
||||
fixed = puzzle.given[i],
|
||||
inside = r?.contains(i, n) ?? false;
|
||||
final state = value == 0
|
||||
? 'empty'
|
||||
: value == 1
|
||||
? 'lit'
|
||||
: 'crossed out';
|
||||
return Semantics(
|
||||
label:
|
||||
'Row ${row + 1}, column ${col + 1}, $state${fixed ? ', fixed clue' : ''}',
|
||||
button: !fixed && !won,
|
||||
enabled: !fixed && !won,
|
||||
onTap: fixed || won ? null : () => onMark(i),
|
||||
excludeSemantics: true,
|
||||
child: GestureDetector(
|
||||
key: ValueKey('cell-$i'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: fixed || won ? null : () => onMark(i),
|
||||
child: SizedBox(
|
||||
width: u,
|
||||
height: u,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(2),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: value == 1
|
||||
? blue
|
||||
: inside
|
||||
? amber.withValues(alpha: .22)
|
||||
: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(
|
||||
2,
|
||||
),
|
||||
border: Border.all(
|
||||
color: inside
|
||||
? const Color(0xffaa5b2a)
|
||||
: muted.withValues(alpha: .48),
|
||||
width: inside ? 1.4 : .65,
|
||||
),
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
if (value == 2)
|
||||
Center(
|
||||
child: Text(
|
||||
'×',
|
||||
style: hand(
|
||||
u * .62,
|
||||
color: muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (fixed)
|
||||
Positioned(
|
||||
right: 3,
|
||||
bottom: 3,
|
||||
child: Container(
|
||||
width: 4,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: value == 1
|
||||
? cream
|
||||
: muted,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class PixelPicture extends StatelessWidget {
|
||||
const PixelPicture(
|
||||
this.picture, {
|
||||
super.key,
|
||||
required this.label,
|
||||
this.height = 230,
|
||||
});
|
||||
final List<int> picture;
|
||||
final String label;
|
||||
final double height;
|
||||
@override
|
||||
Widget build(BuildContext context) => Semantics(
|
||||
image: true,
|
||||
label: 'Recovered pixel picture: $label',
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: height,
|
||||
height: height,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xfffaf1d8),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: ink.withValues(alpha: .15),
|
||||
offset: const Offset(3, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: CustomPaint(painter: _Pixels(picture)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Pixels extends CustomPainter {
|
||||
_Pixels(this.picture);
|
||||
final List<int> picture;
|
||||
@override
|
||||
void paint(Canvas c, Size s) {
|
||||
final p = Paint()..color = blue, u = s.width / 7;
|
||||
for (var i = 0; i < 49; i++) {
|
||||
if (picture[i] == 1) {
|
||||
c.drawRect(Rect.fromLTWH(i % 7 * u, i ~/ 7 * u, u + .3, u + .3), p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_Pixels old) => old.picture != picture;
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
const ink = Color(0xff36413c),
|
||||
blue = Color(0xff274956),
|
||||
muted = Color(0xff796b55),
|
||||
cream = Color(0xfff3e7cc),
|
||||
amber = Color(0xffe0b568);
|
||||
TextStyle hand(double size, {Color color = ink}) => TextStyle(
|
||||
fontFamily: 'MaraHand',
|
||||
fontSize: size,
|
||||
height: 1.30,
|
||||
color: color,
|
||||
);
|
||||
Widget writing(String value, {double size = 23, Color color = ink}) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: Text(value, style: hand(size, color: color)),
|
||||
);
|
||||
|
||||
class InkButton extends StatelessWidget {
|
||||
const InkButton(
|
||||
this.label,
|
||||
this.onPressed, {
|
||||
super.key,
|
||||
this.size = 23,
|
||||
this.primary = false,
|
||||
});
|
||||
final String label;
|
||||
final VoidCallback? onPressed;
|
||||
final double size;
|
||||
final bool primary;
|
||||
@override
|
||||
Widget build(BuildContext context) => DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
border: Border(
|
||||
bottom: BorderSide(color: blue.withValues(alpha: primary ? .5 : .18)),
|
||||
),
|
||||
),
|
||||
child: TextButton(
|
||||
onPressed: onPressed,
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: blue,
|
||||
disabledForegroundColor: muted.withValues(alpha: .4),
|
||||
textStyle: hand(size),
|
||||
minimumSize: const Size(48, 48),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
|
||||
shape: const RoundedRectangleBorder(),
|
||||
),
|
||||
child: Text(label, textAlign: TextAlign.center),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class Paper extends StatefulWidget {
|
||||
const Paper({super.key, required this.child, this.onTurn});
|
||||
final Widget child;
|
||||
final ValueChanged<int>? onTurn;
|
||||
@override
|
||||
State<Paper> createState() => _PaperState();
|
||||
}
|
||||
|
||||
class _PaperState extends State<Paper> {
|
||||
Offset? start;
|
||||
@override
|
||||
Widget build(BuildContext context) => ColoredBox(
|
||||
color: const Color(0xff314345),
|
||||
child: SafeArea(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, c) {
|
||||
final landscape = c.maxWidth > c.maxHeight;
|
||||
final scale = landscape
|
||||
? c.maxWidth / 1024
|
||||
: math.min(c.maxWidth / 1024, c.maxHeight / 1536);
|
||||
final w = 1024 * scale,
|
||||
h = 1536 * scale,
|
||||
left = (c.maxWidth - w) / 2,
|
||||
top = (c.maxHeight - h) / 2;
|
||||
final narrow = c.maxWidth < 480;
|
||||
final content = landscape
|
||||
? Rect.fromLTRB(
|
||||
c.maxWidth * .10,
|
||||
c.maxHeight * .06,
|
||||
c.maxWidth * .83,
|
||||
c.maxHeight * .94,
|
||||
)
|
||||
: Rect.fromLTRB(
|
||||
left + w * (narrow ? .08 : .11),
|
||||
top + h * .12,
|
||||
left + w * (narrow ? .91 : .83),
|
||||
top + h * .91,
|
||||
);
|
||||
return Listener(
|
||||
onPointerDown: (e) {
|
||||
start =
|
||||
(e.localPosition.dx < content.left ||
|
||||
e.localPosition.dx > content.right)
|
||||
? e.localPosition
|
||||
: null;
|
||||
},
|
||||
onPointerUp: (e) {
|
||||
final origin = start;
|
||||
start = null;
|
||||
if (origin == null) return;
|
||||
final d = e.localPosition - origin;
|
||||
if (d.dx.abs() > 55 && d.dx.abs() > d.dy.abs() * 1.5) {
|
||||
widget.onTurn?.call(d.dx < 0 ? 1 : -1);
|
||||
}
|
||||
},
|
||||
child: Stack(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
children: [
|
||||
Positioned(
|
||||
left: left,
|
||||
top: top,
|
||||
width: w,
|
||||
height: h,
|
||||
child: Image.asset(
|
||||
'assets/artwork/mara-single-page-v2.png',
|
||||
fit: BoxFit.fill,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
Positioned.fromRect(rect: content, child: widget.child),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class Leaf extends StatelessWidget {
|
||||
const Leaf({super.key, required this.body, this.footer, this.onTurn});
|
||||
final Widget body;
|
||||
final Widget? footer;
|
||||
final ValueChanged<int>? onTurn;
|
||||
@override
|
||||
Widget build(BuildContext context) => Paper(
|
||||
onTurn: onTurn,
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
key: const PageStorageKey('leaf-scroll'),
|
||||
padding: const EdgeInsets.fromLTRB(4, 0, 4, 8),
|
||||
child: body,
|
||||
),
|
||||
),
|
||||
?footer,
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class Cover extends StatelessWidget {
|
||||
const Cover({super.key, required this.onTap});
|
||||
final VoidCallback onTap;
|
||||
@override
|
||||
Widget build(BuildContext context) => Semantics(
|
||||
button: true,
|
||||
label: 'Open Mara’s cloth-bound island notebook',
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
child: SizedBox(
|
||||
height: 230,
|
||||
child: Center(
|
||||
child: AspectRatio(
|
||||
aspectRatio: 1.5,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, c) => Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: Image.asset(
|
||||
'assets/artwork/home-notebook-cover-v2.png',
|
||||
fit: BoxFit.fill,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
left: c.maxWidth * .27,
|
||||
top: c.maxHeight * .32,
|
||||
width: c.maxWidth * .49,
|
||||
height: c.maxHeight * .34,
|
||||
child: Center(
|
||||
child: Transform.rotate(
|
||||
angle: -.044,
|
||||
child: Text(
|
||||
'Mara’s\nisland notebook',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(28),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class Sketch extends StatelessWidget {
|
||||
const Sketch(this.kind, {super.key, this.height = 140});
|
||||
final String kind;
|
||||
final double height;
|
||||
@override
|
||||
Widget build(BuildContext context) => Semantics(
|
||||
image: true,
|
||||
label: kind == 'match'
|
||||
? 'A pencil sketch of a match and a small amber flame'
|
||||
: 'A folded note sealed with red wax',
|
||||
child: SizedBox(
|
||||
height: height,
|
||||
width: double.infinity,
|
||||
child: CustomPaint(painter: _SketchPainter(kind)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _SketchPainter extends CustomPainter {
|
||||
_SketchPainter(this.kind);
|
||||
final String kind;
|
||||
@override
|
||||
void paint(Canvas c, Size s) {
|
||||
final p = Paint()..isAntiAlias = true;
|
||||
final x = s.width * .51, h = s.height;
|
||||
if (kind == 'match') {
|
||||
p
|
||||
..color = const Color(0xff997445)
|
||||
..strokeWidth = h * .045;
|
||||
c.drawLine(Offset(x - 25, h * .88), Offset(x + 12, h * .36), p);
|
||||
p.color = const Color(0xff654539);
|
||||
c.drawOval(Rect.fromLTRB(x + 2, h * .27, x + 26, h * .41), p);
|
||||
p.color = amber;
|
||||
final f = Path()
|
||||
..moveTo(x + 12, h * .33)
|
||||
..cubicTo(x - 24, h * .17, x + 30, h * .19, x + 17, h * .05)
|
||||
..cubicTo(x + 56, h * .20, x + 32, h * .33, x + 12, h * .33);
|
||||
c.drawPath(f, p);
|
||||
} else {
|
||||
final r = Rect.fromLTRB(s.width * .10, h * .15, s.width * .90, h * .86);
|
||||
p.color = const Color(0xffead9b2);
|
||||
c.drawRect(r, p);
|
||||
p
|
||||
..color = const Color(0xffb8a17c)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5;
|
||||
c.drawRect(r, p);
|
||||
c.drawPath(
|
||||
Path()
|
||||
..moveTo(r.left, r.top)
|
||||
..lineTo(s.width * .5, h * .59)
|
||||
..lineTo(r.right, r.top),
|
||||
p,
|
||||
);
|
||||
c.drawLine(r.bottomLeft, Offset(s.width * .4, h * .5), p);
|
||||
c.drawLine(r.bottomRight, Offset(s.width * .6, h * .5), p);
|
||||
p
|
||||
..style = PaintingStyle.fill
|
||||
..color = const Color(0xff9e5f49);
|
||||
c.drawCircle(Offset(s.width * .5, h * .57), h * .075, p);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_SketchPainter old) => old.kind != kind;
|
||||
}
|
||||
Reference in New Issue
Block a user