Enhance postcard puzzles and narration

This commit is contained in:
Hadrian Burkhardt
2026-11-14 08:55:48 +01:00
parent abaab927d9
commit b19295472d
158 changed files with 5257 additions and 1695 deletions
+16 -8
View File
@@ -23,7 +23,7 @@ enum Screen {
enum Mode { daily, classic, campaign, postcard }
Puzzle generatePractice(Map<String, Object> args) => Puzzle.generate(
Puzzle generatePractice(Map<String, Object> args) => Puzzle.generateSeven(
BigInt.parse(args['seed'] as String),
Difficulty.fromStored(args['difficulty'] as String),
);
@@ -93,14 +93,17 @@ class Game extends ChangeNotifier {
IslandPostcard get postcard => islandPostcards[postcardIndex];
int postcardSolved(int index) => List.generate(
IslandPostcard.puzzlesPerOuting,
(slot) => store.flag('done_${islandPostcards[index].puzzleKey(slot)}'),
(slot) =>
store.flag('done_${islandPostcards[index].puzzleKey(slot)}') ||
store.flag('done_${islandPostcards[index].legacyPuzzleKey(slot)}'),
).where((done) => done).length;
int get postcardsCollected => List.generate(
islandPostcards.length,
(i) => postcardSolved(i),
).where((count) => count == 3).length;
bool get todaySolved =>
store.flag('done_d${DateTime.now().toIso8601String().substring(0, 10)}');
bool get todaySolved => store.flag(
'done_d7_${DateTime.now().toIso8601String().substring(0, 10)}',
);
void showPostcards() {
_request++;
@@ -117,7 +120,9 @@ class Game extends ChangeNotifier {
postcardSlot =
slot ??
List.generate(3, (i) => i).firstWhere(
(i) => !store.flag('done_${postcard.puzzleKey(i)}'),
(i) =>
!store.flag('done_${postcard.puzzleKey(i)}') &&
!store.flag('done_${postcard.legacyPuzzleKey(i)}'),
orElse: () => 0,
);
RangeError.checkValidIndex(postcardSlot, const [0, 1, 2]);
@@ -343,8 +348,11 @@ class Game extends ChangeNotifier {
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)}',
Puzzle.generateSeven(
BigInt.from(epochDay(date)) * BigInt.from(7919),
Difficulty.medium,
),
'd7_${date.toIso8601String().substring(0, 10)}',
);
_route(Screen.game);
}
@@ -363,7 +371,7 @@ class Game extends ChangeNotifier {
busy = false;
mode = Mode.classic;
playingLevel = n;
_read(p, 'v2_${d.stored}_$n');
_read(p, 'v3_${d.stored}_$n');
_route(Screen.game);
}
+147 -74
View File
@@ -1,116 +1,189 @@
// Generated by tool/author_postcard_puzzles.dart. Stable v1 save identities.
// Generated by tool/author_postcard_puzzles.dart. Stable v2 identities.
const postcardPatterns = <(String, List<int>)>[
(
'0101111010001010010000000',
[0, 1, 2, 5, 6, 9, 10, 11, 13, 14, 16, 18, 19, 20, 21, 22, 23],
),
('0000000000111111110000010', [9, 12, 14, 16, 18, 19, 21, 24]),
(
'1011010111010101001110011',
[0, 1, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15, 16, 17, 20],
'0100010101011101111000111101100101011011010010000',
[1, 5, 8, 10, 28, 33, 37, 44],
),
(
'0110110011100100011101000',
[0, 3, 4, 6, 7, 11, 12, 14, 15, 18, 19, 20, 22, 23, 24],
'0110110010011101000110111010000001100111111101010',
[1, 2, 4, 25, 27, 36, 42, 46, 48],
),
(
'1010101011010000001111111',
[1, 3, 4, 6, 7, 9, 10, 13, 15, 16, 17, 20, 23, 24],
'1100011110001010001101001010101011111110001101011',
[1, 6, 8, 15, 16, 17, 24, 32, 34, 40, 44, 48],
),
(
'0011010110101010000100101',
[1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 18, 20, 21, 23, 24],
'1001111010100110101101011001111010100001101001001',
[1, 8, 10, 13, 15, 17, 20, 22, 25, 26, 30, 33, 35, 45, 48],
),
(
'1101111010000000111100101',
[0, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 24],
'0011111100101100000000000000110010001110000111010',
[1, 7, 12, 13, 28, 31, 39, 44, 47],
),
('0101101110101100100111010', [4, 11, 19, 22]),
('1100101001111111001101110', [0, 15, 16, 24]),
(
'1001101001010011100000010',
'0010111101110011100000101110111001010000100010001',
[4, 5, 6, 11, 15, 22, 24, 25, 26, 31, 37, 40, 48],
),
(
'0000111011000001000110010010110101110111011100000',
[2, 5, 8, 15, 16, 19, 26, 30, 32, 42, 43],
),
(
'1101110101011010010000011100000100100101000001100',
[1, 5, 10, 21, 34, 35, 38, 42],
),
(
'1111110111100000011111100000000010001111111111110',
[6, 8, 11, 14, 16, 22, 28, 35, 48],
),
(
'0101010100001101100111111111111100000001110001111',
[1, 7, 13, 17, 18, 28, 29, 30, 31, 38],
),
(
'0111011010011110100011001110010001011100000111111',
[0, 4, 7, 9, 14, 20, 21, 23, 24, 30, 32, 39, 40, 42],
),
(
'0110010100110000110111100110001100000110000010011',
[3, 4, 7, 9, 19, 20, 23, 24, 47, 48],
),
(
'1101010010010110010001001110000010101001110100100',
[0, 5, 10, 14, 22, 27, 29, 31, 38, 45],
),
(
'1100000010000001110101001001001100101001011100101',
[3, 7, 10, 14, 18, 27, 30, 34, 36, 39, 41, 45, 48],
),
(
'0010000101001101011010010101000010001110101010111',
[2, 11, 15, 16, 17, 19, 27, 36, 38, 39],
),
(
'0111011010000110100110111001011111011101111111001',
[14, 15, 17, 34, 38, 42],
),
(
'1101011001101100001001000101010011100110111001010',
[1, 6, 7, 8, 11, 14, 17, 19, 21, 25, 27, 28, 31, 37, 41],
),
(
'1111111011000001010011011011110101110010000101010',
[8, 9, 21, 23, 26, 27, 35, 47],
),
(
'1110100100000111110101111011001010100101101001011',
[3, 6, 9, 10, 11, 18, 20, 21, 22, 26, 31, 37, 39, 40, 42, 47],
),
('0001111010110111011110000100001000001010011110111', [8, 25, 30, 36, 45]),
(
'0010011110010000110101110010111110010111111101010',
[0, 6, 8, 11, 14, 24, 25, 33, 41, 43, 45],
),
(
'0101000001101110011100110111001001101001010000101',
[
0,
1,
2,
3,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
17,
16,
18,
20,
21,
22,
23,
24,
19,
25,
26,
27,
29,
31,
37,
38,
39,
46,
48,
],
),
('0110000110111101111010010', [6, 21, 22]),
('0111001101101101001010011', [6, 9, 10, 15, 18, 21, 22]),
(
'0010000101110101111100000',
[2, 3, 4, 6, 8, 9, 11, 12, 15, 16, 17, 18, 19, 21, 22],
'1100101011011111110111110100100111111000000000000',
[1, 4, 6, 7, 10, 24, 25, 26, 32, 34, 38, 40],
),
('0110011001001011001011110', [7, 8, 14, 16, 17]),
('1001101100001110110000100', [0, 3, 4, 11]),
(
'0111110000011101001011010',
[0, 1, 2, 3, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23],
'0110000001000101001111011101011010011101110010001',
[3, 4, 6, 9, 15, 19, 21, 29, 34, 38, 46],
),
('0010111001100011000101001', [2, 21]),
('0111000110011110111010001', [20, 24]),
(
'1010100111010110001010010',
[1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 19, 21, 22, 23],
'0111110001110110100100101100110110001000100010100',
[8, 10, 13, 14, 16, 19, 24, 28, 31, 37, 39, 43],
),
('1101100110100010001011011', [1, 5, 9, 13, 22]),
('1111010100111000111000001', [4, 7, 14, 15, 17, 18, 20, 21]),
(
'0100100001100010000100001',
[1, 2, 3, 6, 7, 8, 12, 13, 14, 15, 17, 19, 21, 23],
'1110011110100100011001001110001110100011111010010',
[1, 2, 6, 8, 12, 17, 18, 25, 28, 33, 35, 44],
),
('0010011110100000010001010', [12, 13, 21, 22]),
('1111101110001011100011011', [8, 9, 12, 17, 19, 20, 23]),
(
'1110001110001110111010011',
[0, 1, 3, 6, 8, 9, 10, 11, 16, 17, 18, 19, 20, 21, 23, 24],
'1111101110100001111010001100001111111010111110110',
[9, 11, 14, 21, 23, 28, 29, 36, 38, 40, 41, 43, 47],
),
('0001010101100110011111110', [3, 7, 15, 24]),
('0110110110110011101011010', [2, 6, 9, 19, 20, 23]),
('0001010010111100111010011', [0, 3, 4, 5, 6, 8, 11, 13, 14, 20, 21, 22, 24]),
('1000110111010010101000101', [10, 12, 13, 16, 18, 22]),
('0111010111011011101001000', [6, 14, 17]),
(
'0111101001000001110010100',
[0, 1, 2, 3, 5, 7, 9, 10, 11, 13, 14, 15, 16, 18, 22, 23],
'0111000110100110001010111100011111010111101000111',
[0, 4, 11, 13, 20, 22, 23, 24, 28, 36, 47, 48],
),
('1011100101111010011111001', [3, 18, 22]),
('0011000100001111001011100', [1, 11, 15, 18, 20]),
(
'1110000100101000101011000',
[0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 14, 15, 16, 17, 18, 19, 24],
'1000101010000001101011010100110101101010110110010',
[2, 8, 14, 30, 32, 35, 37, 39, 43, 47],
),
('1010110010011010011101010', [7, 9, 10, 13, 18, 21, 23]),
('1001111100111110011111001', [3, 9, 17, 18]),
(
'0010001100100011000110001',
[0, 1, 3, 4, 5, 6, 8, 12, 14, 17, 18, 20, 21, 22, 23],
'1101100111100000111111001011110001110010011001100',
[1, 4, 11, 12, 13, 14, 29, 31, 47, 48],
),
('1011100100100001000100110', [7, 22, 23]),
('0001000111101010110110011', [3, 13, 16, 20, 23]),
(
'0000101000011000011010001',
[0, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 14, 15, 17, 20, 21, 23, 24],
'1110010111010010101100010010110000100101111010100',
[6, 12, 13, 15, 20, 21, 23, 33, 35, 37, 39, 44, 46],
),
(
'0100111100010100110001100011011100000001101001101',
[1, 5, 10, 16, 18, 20, 24, 25, 29, 30, 31, 40],
),
(
'0101000101110011011010001000100001010001011001000',
[3, 4, 8, 12, 13, 17, 24, 29, 32, 34, 35, 41, 43, 46, 47, 48],
),
(
'0101111000101101001111111001000110011011110100110',
[5, 10, 12, 16, 17, 21, 25, 31, 32, 37, 47, 48],
),
(
'1011000001000011001011011100100111100110011001001',
[2, 9, 17, 23, 25, 29, 37, 41],
),
(
'1001101000101010001111010100111110101000100100001',
[4, 7, 12, 18, 19, 20, 22, 24, 26, 27, 33, 35, 38, 41, 42, 45],
),
(
'0011101100100110000000101001111010000110111110110',
[3, 9, 11, 16, 18, 20, 22, 24, 31, 33, 34, 35, 39, 43, 47, 48],
),
(
'1001101001100000111010100000000110000101010011011',
[7, 11, 13, 16, 22, 35, 38, 44, 47, 48],
),
(
'1001101101001011001000011111110111110101001101000',
[6, 9, 12, 15, 23, 24, 25, 26, 27, 30, 38, 43, 45],
),
(
'1100100111010010010000111111101011001111101000100',
[1, 6, 13, 17, 18, 20, 22, 23, 24, 26, 33, 34, 35, 41, 48],
),
(
'1111111101010100110100000111010010011010110100000',
[7, 9, 11, 12, 16, 17, 25, 29, 32, 47, 48],
),
(
'0101001110111000100100011001110010111100110000111',
[3, 7, 10, 11, 12, 16, 19, 21, 22, 32, 40, 46, 47, 48],
),
('1011111000010110011011100', [3, 6, 11, 13, 14, 17, 18, 24]),
('0101101111101100111011101', [10, 12, 17, 23]),
];
+72 -3
View File
@@ -1,21 +1,90 @@
import 'postcard_patterns.dart';
import 'puzzle.dart';
/// A separate, unvoiced collection; it never changes a book's saved position.
/// A separate collection; it never changes a book's saved position.
class IslandPostcard {
const IslandPostcard(this.id, this.title, this.invitation, this.message);
final String id, title, invitation, message;
String get illustrationAsset => 'assets/postcards/illustrations/$id.png';
static const puzzlesPerOuting = 3;
String puzzleKey(int slot) => 'postcard_v1_${id}_$slot';
String puzzleKey(int slot) => 'postcard_v2_${id}_$slot';
String legacyPuzzleKey(int slot) => 'postcard_v1_${id}_$slot';
Puzzle puzzle(int slot) {
RangeError.checkValidIndex(slot, const [0, 1, 2]);
final index = islandPostcards.indexOf(this);
final (picture, clues) = postcardPatterns[index * puzzlesPerOuting + slot];
final board = Puzzle(5, picture.split('').map(int.parse).toList());
final board = Puzzle(7, picture.split('').map(int.parse).toList());
// Overlapping area clues add another way to reason about the same picture.
// Keep the picture, givens and puzzle key stable for saved games.
final mirror = (index + slot).isOdd;
int left(int column) => mirror ? 3 - column : column;
board.regions.addAll([
Region('A', 0, left(0), 4, 4),
Region('B', 1, left(3), 4, 4),
Region('C', 3, left(1), 4, 4),
]);
for (final clue in clues) {
board.given[clue] = true;
}
// Introduce the pair on the last pattern of later outings. Pick two
// editable, opposite cells far apart so both lanterns invite a deduction.
if (index >= 2 && slot == 2) {
LanternPair? pair;
var greatestDistance = -1;
for (var a = 0; a < 49; a++) {
for (var b = a + 1; b < 49; b++) {
if (board.given[a] ||
board.given[b] ||
board.solution[a] == board.solution[b] ||
a ~/ 7 == b ~/ 7 ||
a % 7 == b % 7) {
continue;
}
final distance = (a ~/ 7 - b ~/ 7).abs() + (a % 7 - b % 7).abs();
if (distance > greatestDistance) {
pair = LanternPair(a, b);
greatestDistance = distance;
}
}
}
if (pair != null) board.lanternPairs.add(pair);
}
// The missing total is exactly one more than the previous row's total.
if (index >= 4 && slot == 1) {
for (var row = 1; row < 7; row++) {
if (board.rows[row] == board.rows[row - 1] + 1) {
board.hiddenRow = row;
break;
}
}
}
if (index >= 3 && slot == 0) {
for (var row = 0; row < 7 && board.mirrorPairs.isEmpty; row++) {
for (var col = 0; col < 3; col++) {
final a = row * 7 + col, b = row * 7 + 6 - col;
if (!board.given[a] &&
!board.given[b] &&
board.solution[a] == board.solution[b]) {
board.mirrorPairs.add(LanternPair(a, b));
break;
}
}
}
}
if (index >= 5 && slot == 1 && board.hiddenRow == null) {
for (var row = 0; row < 7 && board.footprintTrails.isEmpty; row++) {
for (var col = 0; col < 5; col++) {
final trail = [row * 7 + col, row * 7 + col + 1, row * 7 + col + 2];
if (trail.every((i) => !board.given[i]) &&
board.solution[trail[1]] == 1 &&
board.solution[trail[0]] + board.solution[trail[2]] == 1) {
board.footprintTrails.add(trail);
break;
}
}
}
}
return board;
}
}
+107 -1
View File
@@ -65,10 +65,18 @@ class Region {
}
class Constraint {
Constraint(this.cells, this.total, this.name);
Constraint(this.cells, this.total, this.name, {this.equal = false});
final List<int> cells;
final int total;
final String name;
final bool equal;
}
/// Exactly one of the two cells is lit.
class LanternPair {
const LanternPair(this.first, this.second);
final int first, second;
bool contains(int cell) => cell == first || cell == second;
}
class Hint {
@@ -95,6 +103,19 @@ class LogicSolver {
int _singles(List<int> known) {
var changes = 0;
for (final c in constraints) {
if (c.equal) {
final a = c.cells[0], b = c.cells[1];
if (known[a] >= 0 && known[b] >= 0 && known[a] != known[b]) return -1;
if (known[a] >= 0 && known[b] < 0) {
known[b] = known[a];
changes++;
}
if (known[b] >= 0 && known[a] < 0) {
known[a] = known[b];
changes++;
}
continue;
}
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;
@@ -108,9 +129,43 @@ class LogicSolver {
Hint? nextHint(List<int> known) {
for (final c in constraints) {
if (c.equal) {
final a = c.cells[0], b = c.cells[1];
if (known[a] >= 0 && known[b] < 0) {
return Hint(
b,
known[a],
'The mirrored cells match: both are lit or both are crossed out.',
);
}
if (known[b] >= 0 && known[a] < 0) {
return Hint(
a,
known[b],
'The mirrored cells match: both are lit or both are crossed out.',
);
}
continue;
}
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)) {
if (c.name.startsWith('Footprint trail')) {
return Hint(
unknown.first,
need == 0 ? 0 : 1,
'Two footprints must be lit and touch. The middle footprint is lit, and exactly one end is lit.',
);
}
if (c.name == 'Lantern pair') {
return Hint(
unknown.first,
need == 0 ? 0 : 1,
need == 0
? 'The other lantern is lit, so this lantern must be crossed out. Exactly one lantern in the pair is lit.'
: 'The other lantern is crossed out, so this lantern must be lit. Exactly one lantern in the pair is lit.',
);
}
return Hint(
unknown.first,
need == 0 ? 0 : 1,
@@ -122,8 +177,10 @@ class LogicSolver {
}
for (var a = 0; a < constraints.length; a++) {
final first = constraints[a];
if (first.equal) continue;
for (var b = a + 1; b < constraints.length; b++) {
final second = constraints[b];
if (second.equal) continue;
final onlyA = _unknown(
first,
known,
@@ -209,6 +266,10 @@ class Puzzle {
final List<int> solution;
final List<bool> given;
final List<Region> regions = [];
final List<LanternPair> lanternPairs = [];
final List<LanternPair> mirrorPairs = [];
final List<List<int>> footprintTrails = [];
int? hiddenRow;
List<int> get rows => List.generate(
size,
(r) => List.generate(
@@ -228,6 +289,14 @@ class Puzzle {
(i) => r.contains(i, size) ? solution[i] : 0,
).reduce((a, b) => a + b);
List<Constraint> get constraints => [
for (final trail in footprintTrails) ...[
Constraint([trail[1]], 1, 'Footprint trail centre'),
Constraint([trail[0], trail[2]], 1, 'Footprint trail ends'),
],
for (final pair in mirrorPairs)
Constraint([pair.first, pair.second], 0, 'Mirrored cells', equal: true),
for (final pair in lanternPairs)
Constraint([pair.first, pair.second], 1, 'Lantern pair'),
for (var l = 0; l < size; l++) ...[
Constraint(
List.generate(size, (p) => l * size + p),
@@ -263,6 +332,31 @@ class Puzzle {
}
return puzzle;
}
/// Stable 7×7 boards for daily and practice play. Remove fixed clues only
/// while a unique, deduction-solvable board within the requested grade remains.
static Puzzle generateSeven(BigInt seed, Difficulty difficulty) {
final random = JavaRandom(seed);
Puzzle? best;
for (var attempt = 0; attempt < 32; attempt++) {
final p = Puzzle(7, List.generate(49, (_) => random.next(1)));
p.given.fillRange(0, 49, true);
final order = List.generate(49, (i) => i);
random.shuffle(order);
for (final i in order) {
p.given[i] = false;
if (p.countSolutions() != 1 ||
!LogicSolver(49, p.constraints).analyze(p.initial).solved ||
p.difficulty.index > difficulty.index) {
p.given[i] = true;
}
}
best = p;
if (p.difficulty == difficulty) return p;
}
return best!;
}
static Puzzle generate(BigInt seed, Difficulty difficulty) {
final random = JavaRandom(seed);
for (var i = 0; i < 256; i++) {
@@ -338,6 +432,18 @@ class Puzzle {
final next = List<int>.of(known);
var changed = false;
for (final c in lines) {
if (c.equal) {
final a = c.cells[0], b = c.cells[1];
if (known[a] >= 0 && known[b] < 0) {
next[b] = known[a];
changed = true;
}
if (known[b] >= 0 && known[a] < 0) {
next[a] = known[b];
changed = true;
}
continue;
}
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)) {
+142 -10
View File
@@ -206,6 +206,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
Game get g => widget.game;
Progress get prefs => g.progress;
late final Narrator narrator;
late final Narrator postcardNarrator;
late final Ambience ambience;
late final Ads ads;
late final PlayMetrics metrics;
@@ -220,6 +221,10 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
super.initState();
unawaited(initializeDateFormatting());
narrator = widget.narrator ?? Narrator(g.book.tracks);
postcardNarrator = Narrator({
for (final card in islandPostcards)
card.id: {'asset': 'assets/postcards/audio/${card.id}.wav'},
});
ambience = widget.ambience ?? Ambience();
narrator.addListener(_syncAtmosphere);
metrics = PlayMetrics(g.store)..visit();
@@ -247,6 +252,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
if (_route != route) {
_route = route;
unawaited(narrator.stop());
unawaited(postcardNarrator.stop());
_scheduleAutoplay();
}
_syncAtmosphere();
@@ -317,6 +323,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
if (state != AppLifecycleState.resumed) {
metrics.endVisit();
unawaited(narrator.stop());
unawaited(postcardNarrator.stop());
unawaited(prefs.flushed);
}
}
@@ -328,6 +335,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
narrator.removeListener(_syncAtmosphere);
ambience.dispose();
narrator.dispose();
postcardNarrator.dispose();
ads.dispose();
super.dispose();
}
@@ -926,18 +934,96 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
Future<void> readPostcard(int index, {bool completedNow = false}) async {
if (g.postcardSolved(index) != 3) return;
final card = islandPostcards[index];
postcardNarrator.scheduleAutoplay(
card.id,
prefs.decimal('recording_speed'),
);
final kept = await showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: Text(card.title),
content: SingleChildScrollView(
child: Text(
card.message,
style: const TextStyle(
fontFamily: 'serif',
fontSize: 21,
height: 1.5,
backgroundColor: const Color(0xfffffbef),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(3),
side: const BorderSide(color: Color(0xffc8b797)),
),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Expanded(
child: Text(
'P O S T C A R D',
style: TextStyle(
fontFamily: 'sans-serif',
fontSize: 13,
letterSpacing: 2,
),
),
),
Container(
width: 48,
height: 54,
decoration: BoxDecoration(
border: Border.all(
color: const Color(0xffa78361),
width: 2,
),
color: const Color(0xffdbe7df),
),
child: const Icon(
Icons.light_mode_outlined,
color: Color(0xff8a6a4f),
),
),
],
),
const SizedBox(height: 12),
Text(card.title),
],
),
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
AnimatedBuilder(
animation: postcardNarrator,
builder: (context, _) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
postcardNarrator.status,
style: const TextStyle(
fontFamily: 'sans-serif',
fontSize: 13,
),
),
TextButton.icon(
key: const ValueKey('postcard-play'),
onPressed: () => unawaited(
postcardNarrator.toggle(
card.id,
prefs.decimal('recording_speed'),
),
),
icon: Icon(
postcardNarrator.playing
? Icons.pause
: Icons.play_arrow,
),
label: CopyText(postcardNarrator.label),
),
],
),
),
const Divider(),
SelectableText(
card.message,
key: const ValueKey('postcard-message'),
style: hand(25).copyWith(height: 1.4),
),
],
),
),
actions: [
@@ -948,8 +1034,30 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
],
),
);
if (kept != true ||
!mounted ||
await postcardNarrator.stop();
if (kept != true || !mounted) return;
await showDialog<void>(
context: context,
builder: (c) => AlertDialog(
key: const ValueKey('postcard-reveal'),
backgroundColor: const Color(0xfffffbef),
title: Text(card.title, style: hand(28)),
content: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560),
child: AspectRatio(
aspectRatio: 1.7,
child: PostcardRevealArt(card: card),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(c),
child: const CopyText('Back to collection'),
),
],
),
);
if (!mounted ||
!completedNow ||
g.mode != Mode.postcard ||
g.postcardIndex != index ||
@@ -1425,6 +1533,30 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
}
List<Widget> puzzleNotes() => [
if (g.puzzle?.footprintTrails.isNotEmpty ?? false)
writing(
'Footprints: exactly two marked cells are lit, and they touch.',
size: 19,
color: regionInk,
),
if (g.puzzle?.mirrorPairs.isNotEmpty ?? false)
writing(
'Matching stars are mirrored: both cells match.',
size: 19,
color: regionInk,
),
if (g.puzzle?.hiddenRow case final row?)
writing(
'Row ${row + 1} has one more light than row $row.',
size: 19,
color: regionInk,
),
if (g.puzzle?.lanternPairs.isNotEmpty ?? false)
writing(
'Matching lanterns: exactly one of the two cells is lit.',
size: 19,
color: regionInk,
),
if (g.mode == Mode.campaign)
InkButton('Sound & atmosphere', soundSettings, size: 18),
writing(
+8 -5
View File
@@ -9,8 +9,11 @@ String artworkAsset(String asset) =>
? '${asset.substring(0, asset.length - 4)}.webp'
: asset;
String browserAudioUrl(String asset) => Uri.base
.resolve(
'assets/${optimizedBrowserMedia ? asset.replaceFirst(RegExp(r'\.wav$'), '.mp3') : asset}',
)
.toString();
/// Hash-versioned URLs prevent an older cached recording replacing new audio.
String browserAudioUrl(String asset, {String? version}) {
final url = Uri.base.resolve(
'assets/${optimizedBrowserMedia ? asset.replaceFirst(RegExp(r'\.wav$'), '.mp3') : asset}',
);
if (version == null || version.isEmpty) return url.toString();
return url.replace(queryParameters: {'v': version}).toString();
}
+61 -34
View File
@@ -1,4 +1,6 @@
import 'browser_assets.dart';
import 'web_narration_stub.dart'
if (dart.library.js_interop) 'web_narration_web.dart';
import 'dart:async';
@@ -8,6 +10,7 @@ import 'package:audio_session/audio_session.dart';
class Narrator extends ChangeNotifier {
Narrator(this.tracks) {
if (kIsWeb) _web = WebNarration(_webChanged);
_subscriptions.add(
_player.playerStateStream.listen((_) => notifyListeners()),
);
@@ -21,9 +24,13 @@ class Narrator extends ChangeNotifier {
);
}
(int, String, String)? _positionState;
bool _disposed = false;
WebNarration? _web;
void _webChanged() => notifyListeners();
final ValueNotifier<String> highlightedPassage = ValueNotifier('');
@override
void notifyListeners() {
if (_disposed) return;
highlightedPassage.value = passage;
super.notifyListeners();
}
@@ -41,11 +48,16 @@ class Narrator extends ChangeNotifier {
Timer? _autoplay;
bool get autoplayPending => _autoplay?.isActive ?? false;
int _generation = 0;
bool get playing =>
_player.playing && _player.processingState != ProcessingState.completed;
bool get finished => _player.processingState == ProcessingState.completed;
bool get playing => kIsWeb
? _web!.playing
: _player.playing && _player.processingState != ProcessingState.completed;
bool get finished => kIsWeb
? _web!.finished
: _player.processingState == ProcessingState.completed;
bool get paused => page.isNotEmpty && !playing && !finished && !loading;
Duration get position => _player.position;
Duration get position => kIsWeb ? _web!.position : _player.position;
Duration get duration =>
kIsWeb ? _web!.duration : (_player.duration ?? Duration.zero);
String get label => error.isNotEmpty
? 'Play this reading'
: loading
@@ -67,7 +79,7 @@ class Narrator extends ChangeNotifier {
: '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)}';
: '${playing ? 'Playing' : 'Paused'} · ${_time(position)} / ${_time(duration)}';
String get passage {
if (page.isEmpty || finished) return '';
for (final cue in tracks[page]?['cues'] ?? []) {
@@ -111,45 +123,56 @@ class Narrator extends ChangeNotifier {
cancelAutoplay();
if (loading) return;
if (playing && page == id) {
if (kIsWeb) {
_web!.pause();
return;
}
await _player.pause();
return;
}
final generation = ++_generation;
error = '';
if (kIsWeb) {
final reload = page != id;
final asset =
tracks[id]['asset'] as String? ??
'assets/audio/${tracks[id]['file']}';
page = id;
loading = true;
notifyListeners();
try {
// The JS play() call happens before the first await, so a tap on Play
// retains the browser's transient user activation.
await _web!.play(
browserAudioUrl(asset, version: tracks[id]['wavSha256'] as String?),
speed,
reload: reload,
);
if (generation != _generation) return;
loading = false;
notifyListeners();
} catch (_) {
if (generation != _generation) return;
loading = false;
error = 'Tap Play again to allow audio in your browser.';
notifyListeners();
}
return;
}
try {
if (page != id) {
loading = true;
error = '';
notifyListeners();
if (!kIsWeb) {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
}
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
if (generation != _generation) return;
page = id;
final asset =
tracks[id]['asset'] as String? ??
'assets/audio/${tracks[id]['file']}';
if (kIsWeb) {
final url = browserAudioUrl(asset);
if (_player.audioSources.isEmpty) {
await _player.setUrl(url, initialPosition: Duration.zero);
} else {
// The web backend caches the root playlist by ID. Reusing setUrl
// on an active player can replay its cached first child. Mutate
// the playlist through its API so the browser receives the new
// source, while retaining the already-authorized media element.
await _player.pause();
await _player.clearAudioSources();
if (generation != _generation) return;
await _player.addAudioSource(AudioSource.uri(Uri.parse(url)));
if (generation != _generation) return;
await _player.seek(Duration.zero, index: 0);
}
} else {
// PCM WAV remains the tested format for the Android tablet.
await _player.setAsset(asset);
}
// PCM WAV remains the tested format for the Android tablet.
await _player.setAsset(asset);
if (generation != _generation) return;
} else if (finished) {
await _player.seek(Duration.zero);
@@ -162,7 +185,7 @@ class Narrator extends ChangeNotifier {
_player.play().catchError((Object e) {
if (generation != _generation) return;
unawaited(_player.pause());
error = kIsWeb ? 'Tap Play again to allow audio in your browser.' : 'This recording could not be played. You can still read the entry.';
error = 'This recording could not be played. You can still read the entry.';
notifyListeners();
}),
);
@@ -179,6 +202,10 @@ class Narrator extends ChangeNotifier {
Future<void> pause() async {
cancelAutoplay();
if (kIsWeb) {
_web!.pause();
return;
}
await _player.pause();
}
@@ -190,10 +217,7 @@ class Narrator extends ChangeNotifier {
error = '';
notifyListeners();
if (kIsWeb) {
// Retain the browser media element and its audio permission between pages.
// stop() tears down the web decoder, making the next page start cold.
await _player.pause();
await _player.seek(Duration.zero);
_web!.stop();
} else {
await _player.stop();
}
@@ -201,7 +225,10 @@ class Narrator extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
_generation++;
_autoplay?.cancel();
_web?.dispose();
for (final s in _subscriptions) {
unawaited(s.cancel());
}
+3 -1
View File
@@ -89,7 +89,9 @@ class PlayMetrics {
.where(
(card) => List.generate(
3,
(slot) => store.flag('done_${card.puzzleKey(slot)}'),
(slot) =>
store.flag('done_${card.puzzleKey(slot)}') ||
store.flag('done_${card.legacyPuzzleKey(slot)}'),
).every((done) => done),
)
.length,
+11
View File
@@ -0,0 +1,11 @@
class WebNarration {
WebNarration(void Function() onChange);
bool get playing => false;
bool get finished => false;
Duration get position => Duration.zero;
Duration get duration => Duration.zero;
Future<void> play(String url, double speed, {required bool reload}) async {}
void pause() {}
void stop() {}
void dispose() {}
}
+46
View File
@@ -0,0 +1,46 @@
import 'dart:js_interop';
@JS('lumenNarration.create')
external JSNumber _create(JSFunction onChange);
@JS('lumenNarration.play')
external JSPromise<JSAny?> _play(
JSNumber id,
JSString url,
JSNumber speed,
JSBoolean reload,
);
@JS('lumenNarration.pause')
external void _pause(JSNumber id);
@JS('lumenNarration.stop')
external void _stop(JSNumber id);
@JS('lumenNarration.dispose')
external void _dispose(JSNumber id);
@JS('lumenNarration.playing')
external JSBoolean _playing(JSNumber id);
@JS('lumenNarration.finished')
external JSBoolean _finished(JSNumber id);
@JS('lumenNarration.position')
external JSNumber _position(JSNumber id);
@JS('lumenNarration.duration')
external JSNumber _duration(JSNumber id);
class WebNarration {
WebNarration(void Function() onChange) : _callback = onChange.toJS {
_id = _create(_callback);
}
final JSFunction _callback;
late final JSNumber _id;
bool get playing => _playing(_id).toDart;
bool get finished => _finished(_id).toDart;
Duration get position =>
Duration(milliseconds: _position(_id).toDartDouble.round());
Duration get duration =>
Duration(milliseconds: _duration(_id).toDartDouble.round());
Future<void> play(String url, double speed, {required bool reload}) async {
await _play(_id, url.toJS, speed.toJS, reload.toJS).toDart;
}
void pause() => _pause(_id);
void stop() => _stop(_id);
void dispose() => _dispose(_id);
}
+97 -6
View File
@@ -120,11 +120,14 @@ class Board extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.center,
children: [
clue(
'${puzzle.rows[row]}',
complete(
List.generate(n, (i) => row * n + i),
puzzle.rows[row],
),
puzzle.hiddenRow == row
? '?'
: '${puzzle.rows[row]}',
puzzle.hiddenRow != row &&
complete(
List.generate(n, (i) => row * n + i),
puzzle.rows[row],
),
),
for (var col = 0; col < n; col++)
Builder(
@@ -132,6 +135,16 @@ class Board extends StatelessWidget {
final i = row * n + col,
value = cells[i],
fixed = puzzle.given[i],
lantern = puzzle.lanternPairs.any(
(pair) => pair.contains(i),
),
mirrored = puzzle.mirrorPairs.any(
(pair) => pair.contains(i),
),
footprint = puzzle.footprintTrails
.any(
(trail) => trail.contains(i),
),
inside = r?.contains(i, n) ?? false;
final state = value == 0
? 'empty'
@@ -142,7 +155,7 @@ class Board extends StatelessWidget {
selected: inside,
label: CopyScope.text(
context,
'Row ${row + 1}, column ${col + 1}, $state${fixed ? ', fixed clue' : ''}',
'Row ${row + 1}, column ${col + 1}, $state${fixed ? ', fixed clue' : ''}${lantern ? ', lantern pair: exactly one is lit' : ''}${mirrored ? ', mirrored pair: both cells match' : ''}${footprint ? ', footprint trail: two adjacent cells are lit' : ''}',
),
button: !fixed && !won,
enabled: !fixed && !won,
@@ -199,6 +212,84 @@ class Board extends StatelessWidget {
),
),
),
if (lantern)
Positioned(
left: 1,
top: 1,
child: Container(
key: ValueKey(
'lantern-$i',
),
decoration:
const BoxDecoration(
color: cream,
shape: BoxShape
.circle,
),
padding:
const EdgeInsets.all(
1,
),
child: Icon(
Icons
.lightbulb_outline,
size: u * .31,
color: regionInk,
),
),
),
if (mirrored)
Positioned(
left: 1,
top: 1,
child: Container(
key: ValueKey(
'mirror-$i',
),
decoration:
const BoxDecoration(
color: cream,
shape: BoxShape
.circle,
),
padding:
const EdgeInsets.all(
1,
),
child: Icon(
Icons
.auto_awesome,
size: u * .31,
color: regionInk,
),
),
),
if (footprint)
Positioned(
left: 1,
top: 1,
child: Container(
key: ValueKey(
'footprint-$i',
),
decoration:
const BoxDecoration(
color: cream,
shape: BoxShape
.circle,
),
padding:
const EdgeInsets.all(
1,
),
child: Icon(
Icons
.directions_walk,
size: u * .31,
color: regionInk,
),
),
),
if (fixed)
Positioned(
right: 3,
+228 -45
View File
@@ -1,9 +1,70 @@
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../domain/game.dart';
import '../domain/postcards.dart';
import '../services/browser_assets.dart';
import 'translation.dart';
/// A saved memory comes into focus and regains its colour.
class PostcardRevealArt extends StatelessWidget {
const PostcardRevealArt({super.key, required this.card});
final IslandPostcard card;
@override
Widget build(BuildContext context) => TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: 1),
duration: MediaQuery.disableAnimationsOf(context)
? Duration.zero
: const Duration(milliseconds: 1800),
curve: Curves.easeInOut,
child: Image.asset(
artworkAsset(card.illustrationAsset),
fit: BoxFit.cover,
semanticLabel: 'Watercolour illustration for ${card.title}',
),
builder: (context, progress, child) {
final faded = 1 - progress;
return ClipRect(
child: ColorFiltered(
key: const ValueKey('postcard-reveal-color'),
colorFilter: ColorFilter.matrix([
.2126 * faded + progress,
.7152 * faded,
.0722 * faded,
0,
0,
.2126 * faded,
.7152 * faded + progress,
.0722 * faded,
0,
0,
.2126 * faded,
.7152 * faded,
.0722 * faded + progress,
0,
0,
0,
0,
0,
1,
0,
]),
child: ImageFiltered(
imageFilter: ui.ImageFilter.blur(
sigmaX: 7 * faded,
sigmaY: 7 * faded,
),
enabled: progress < 1,
child: child,
),
),
);
},
);
}
class ShelfActivities extends StatelessWidget {
const ShelfActivities({
super.key,
@@ -114,7 +175,7 @@ class PostcardCollectionView extends StatelessWidget {
),
const SizedBox(height: 8),
const CopyText(
'Written postcards · English · No recorded reading',
'Illustrated postcards · English · Recorded readings',
style: TextStyle(fontFamily: 'sans-serif', fontSize: 13),
),
const SizedBox(height: 16),
@@ -135,51 +196,173 @@ class PostcardCollectionView extends StatelessWidget {
),
const SizedBox(height: 20),
for (var i = 0; i < islandPostcards.length; i++)
Card(
margin: const EdgeInsets.only(bottom: 16),
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'${i + 1}. ${islandPostcards[i].title}',
style: const TextStyle(
fontFamily: 'serif',
fontSize: 25,
),
),
const SizedBox(height: 8),
Text(
islandPostcards[i].invitation,
style: const TextStyle(
fontFamily: 'sans-serif',
fontSize: 16,
height: 1.5,
),
),
const SizedBox(height: 12),
CopyText(
'${game.postcardSolved(i)} / 3 patterns found',
),
const SizedBox(height: 8),
if (game.postcardSolved(i) == 3)
FilledButton.tonal(
key: ValueKey('read-postcard-$i'),
onPressed: () => onRead(i),
child: const CopyText('Read your postcard'),
)
else
OutlinedButton(
key: ValueKey('start-postcard-$i'),
onPressed: () => onOpen(i),
child: CopyText(
game.postcardSolved(i) == 0
? 'Begin outing'
: 'Continue outing',
Semantics(
key: ValueKey('postcard-$i'),
button: true,
label:
'${islandPostcards[i].title}, ${game.postcardSolved(i)} of 3 patterns found. ${game.postcardSolved(i) == 3
? 'Read your postcard'
: game.postcardSolved(i) == 0
? 'Begin outing'
: 'Continue outing'}',
onTap: () =>
game.postcardSolved(i) == 3 ? onRead(i) : onOpen(i),
excludeSemantics: true,
child: Material(
color: Colors.transparent,
child: InkWell(
excludeFromSemantics: true,
onTap: () =>
game.postcardSolved(i) == 3 ? onRead(i) : onOpen(i),
child: Container(
margin: const EdgeInsets.only(bottom: 24),
padding: const EdgeInsets.all(9),
decoration: BoxDecoration(
color: const Color(0xfffffbef),
border: Border.all(color: const Color(0xffd2bf9c)),
boxShadow: const [
BoxShadow(
color: Color(0x253c3124),
blurRadius: 9,
offset: Offset(2, 4),
),
),
],
],
),
child: Column(
children: [
AspectRatio(
aspectRatio: 1.7,
child: Stack(
fit: StackFit.expand,
children: [
ColorFiltered(
key: ValueKey('postcard-art-$i'),
colorFilter: ColorFilter.matrix(
game.postcardSolved(i) == 3
? const <double>[
1,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1,
0,
]
: const <double>[
.2126,
.7152,
.0722,
0,
0,
.2126,
.7152,
.0722,
0,
0,
.2126,
.7152,
.0722,
0,
0,
0,
0,
0,
1,
0,
],
),
child: ClipRect(
child: ImageFiltered(
key: ValueKey('postcard-blur-$i'),
enabled: game.postcardSolved(i) < 3,
imageFilter: ui.ImageFilter.blur(
sigmaX: 7,
sigmaY: 7,
tileMode: TileMode.decal,
),
child: Image.asset(
artworkAsset(
islandPostcards[i]
.illustrationAsset,
),
fit: BoxFit.cover,
semanticLabel:
game.postcardSolved(i) == 3
? 'Watercolour illustration for ${islandPostcards[i].title}'
: 'Postcard artwork locked until all three patterns are solved',
),
),
),
),
if (game.postcardSolved(i) < 3)
const Center(
child: DecoratedBox(
decoration: BoxDecoration(
color: Color(0xaa243a38),
shape: BoxShape.circle,
),
child: Padding(
padding: EdgeInsets.all(12),
child: Icon(
Icons.lock_outline,
color: Colors.white,
),
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
12,
16,
12,
12,
),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.stretch,
children: [
Text(
'${i + 1}. ${islandPostcards[i].title}',
style: const TextStyle(
fontFamily: 'MaraHand',
fontSize: 28,
),
),
const SizedBox(height: 8),
Text(
islandPostcards[i].invitation,
style: const TextStyle(
fontFamily: 'MaraHand',
fontSize: 21,
height: 1.3,
),
),
const SizedBox(height: 12),
CopyText(
'${game.postcardSolved(i)} / 3 patterns found',
),
],
),
),
],
),
),
),
),
),