Expand narrated story, preserve solved patterns, and add ambience

Connect the island story with new character memories and narrative transitions.
Blend each solved symbol into its artwork and retain a replayable pattern stamp.
Allow completed grids to be inspected after navigation and app restarts.
Reduce campaign difficulty spikes and keep explained story hints free.

Append 24 narrated continuations while preserving original PCM takes. Add
four offline environmental loops with saved mute/volume controls, scene
fades, narration ducking and lifecycle handling.

Validation: 31 unit/widget tests, Flutter analysis, narration and soundscape
asset checks, tablet discovery layouts and extended-audio integration,
including simultaneous active voice and ambience mixer tracks.
This commit is contained in:
Hadrian Burkhardt
2026-11-02 05:04:57 +01:00
parent 6bd14a9e20
commit 68871ec573
102 changed files with 2322 additions and 520 deletions
+13 -1
View File
@@ -11,11 +11,14 @@ class CampaignLevel {
object = data['object'],
before = data['before'],
after = data['after'],
beforeContinuation = data['beforeContinuation'] as String? ?? '',
afterContinuation = data['afterContinuation'] as String? ?? '',
illustrationAsset = data['illustrationAsset'] as String?,
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 String beforeContinuation, afterContinuation;
final String? illustrationAsset;
final List<int> picture;
Puzzle puzzle() {
@@ -57,8 +60,10 @@ class StoryPage {
this.campaignIndex,
this.speaker = '',
this.illustrationAsset,
this.continuation = '',
});
final String id, title, text;
final String continuation;
final StoryPageType type;
final int? campaignIndex;
final String speaker;
@@ -105,7 +110,7 @@ class Book {
'recording' =>
scripts
.where((s) => s['pageId'] == record['id'])
.map((s) => s['text'] as String)
.map((s) => (s['baseText'] ?? s['text']) as String)
.firstOrNull ??
'',
_ => record['text'] as String? ?? '',
@@ -118,6 +123,13 @@ class Book {
campaignIndex: index,
speaker: record['speaker'] as String? ?? '',
illustrationAsset: record['illustrationAsset'] as String?,
continuation:
record['continuation'] as String? ??
switch (record['textSource']) {
'before' => levels[index!].beforeContinuation,
'after' => levels[index!].afterContinuation,
_ => '',
},
);
}).toList(),
tracks,
+1 -4
View File
@@ -201,10 +201,6 @@ class Game extends ChangeNotifier {
_request++;
busy = false;
if (i > accessible) return;
if (recovered(i)) {
reveal(i);
return;
}
campaignIndex = i;
mode = Mode.campaign;
if (i < 4) {
@@ -220,6 +216,7 @@ class Game extends ChangeNotifier {
key = id;
final saved = progress.text('grid_$id');
cells = List.generate(p.solution.length, (i) {
if (progress.flag('done_$id')) return p.solution[i] == 1 ? 1 : 2;
if (p.given[i]) return p.solution[i] == 1 ? 1 : 2;
final value = saved.length == p.solution.length
? int.tryParse(saved[i]) ?? 0
+146 -23
View File
@@ -10,9 +10,11 @@ import 'domain/book.dart';
import 'domain/game.dart';
import 'domain/puzzle.dart';
import 'services/ads.dart';
import 'services/ambience.dart';
import 'services/narrator.dart';
import 'services/progress.dart';
import 'ui/board.dart';
import 'ui/discovery.dart';
import 'ui/paper.dart';
Future<void> main() async {
@@ -73,7 +75,9 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
Game get g => widget.game;
Progress get prefs => g.progress;
late final Narrator narrator;
late final Ambience ambience;
late final Ads ads;
bool _foreground = true;
String _route = '';
String get route =>
'${g.screen.name}:${g.screen == Screen.story ? g.storyIndex : g.campaignIndex}';
@@ -81,12 +85,15 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
void initState() {
super.initState();
narrator = Narrator(g.book.tracks);
ambience = Ambience();
narrator.addListener(_syncAtmosphere);
ads = Ads(enabled: widget.adsEnabled);
g.addListener(_changed);
_route = route;
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(ads.start());
_syncAtmosphere();
});
}
@@ -95,11 +102,35 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
_route = route;
unawaited(narrator.stop());
}
_syncAtmosphere();
if (mounted) setState(() {});
}
bool get atmosphereEnabled =>
!prefs.contains('ambience_enabled') || prefs.flag('ambience_enabled');
void _syncAtmosphere() {
final inStory =
g.mode == Mode.campaign &&
[
Screen.story,
Screen.briefing,
Screen.game,
Screen.reveal,
].contains(g.screen);
ambience.update(
scene: inStory ? soundscapeFor(g.campaignIndex) : null,
enabled: atmosphereEnabled,
foreground: _foreground,
narrating: narrator.playing || narrator.loading,
volume: prefs.decimal('ambience_volume', .7),
);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
_foreground = state == AppLifecycleState.resumed;
_syncAtmosphere();
if (state != AppLifecycleState.resumed) {
unawaited(narrator.stop());
unawaited(prefs.flushed);
@@ -110,6 +141,8 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
void dispose() {
WidgetsBinding.instance.removeObserver(this);
g.removeListener(_changed);
narrator.removeListener(_syncAtmosphere);
ambience.dispose();
narrator.dispose();
ads.dispose();
super.dispose();
@@ -225,7 +258,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
if (mounted) g.reveal(index, readAhead: true);
case Screen.reveal:
if (direction < 0) {
g.briefing(index);
g.startCampaign(index);
} else {
nextCampaign();
}
@@ -270,8 +303,9 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
} else {
g.home();
}
case Screen.briefing:
case Screen.reveal:
g.startCampaign(g.campaignIndex);
case Screen.briefing:
g.contents();
case Screen.game:
if (g.mode == Mode.campaign) {
@@ -415,6 +449,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
() => unawaited(g.startPractice()),
),
action('How to play', rules),
action('Sound & atmosphere', soundSettings),
action('Privacy & advertising', privacy),
action(
'Open-source licenses',
@@ -526,7 +561,10 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
listenable: narrator,
builder: (context, _) => column([
writing(
g.book.tracks[recordingId]?['speaker'] == 'Narrator'
(narrator.page == recordingId
? narrator.speaker
: g.book.tracks[recordingId]?['speaker']) ==
'Narrator'
? 'Narrator · recorded story'
: 'Mara · diary reading',
size: 17,
@@ -554,6 +592,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
],
),
writing(narrator.status, size: 17, color: muted),
InkButton('Sound & atmosphere', soundSettings, size: 18),
]),
);
Widget story() {
@@ -583,6 +622,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
),
writing(p.speaker, size: 17, color: muted),
reading(p.text),
if (p.continuation.isNotEmpty) reading(p.continuation),
if (g.book.tracks.containsKey(p.id)) audio(),
if (p.campaignIndex != 0)
action('Turn to the pattern →', () => turn(1)),
@@ -610,14 +650,16 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
color: muted,
),
reading(p.text),
if (p.continuation.isNotEmpty) reading(p.continuation),
if (g.book.tracks.containsKey(p.id)) audio(),
if (!g.recovered(p.campaignIndex!))
action(
'Return to this pattern',
() => g.showStory(
g.book.pageFor(p.campaignIndex!, StoryPageType.puzzle),
),
action(
g.recovered(p.campaignIndex!)
? 'View the solved pattern'
: 'Return to this pattern',
() => g.showStory(
g.book.pageFor(p.campaignIndex!, StoryPageType.puzzle),
),
),
]);
case StoryPageType.note:
if (!prefs.flag('notebook_note_open')) {
@@ -734,6 +776,65 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
);
}
Future<void> soundSettings() => showDialog<void>(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (context, refresh) {
void save(String key, Object value) {
unawaited(prefs.set(key, value));
_syncAtmosphere();
if (mounted) setState(() {});
refresh(() {});
}
return AlertDialog(
title: Text('Sound & atmosphere', style: hand(29)),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text('Environmental sounds', style: hand(23)),
value: atmosphereEnabled,
onChanged: (value) => save('ambience_enabled', value),
),
writing(
'Water at the harbour and bridge, wind around the tower. The atmosphere grows quieter while the story is read.',
size: 20,
),
writing('Atmosphere volume', size: 20),
Slider(
label:
'${(prefs.decimal('ambience_volume', .7) * 100).round()}%',
value: prefs.decimal('ambience_volume', .7).clamp(0.0, 1.0),
divisions: 10,
onChanged: atmosphereEnabled
? (value) => save('ambience_volume', value)
: null,
),
writing(
'Readings play when you press Play. Your device volume controls the voice.',
size: 18,
color: muted,
),
if (ambience.error.isNotEmpty)
writing(ambience.error, size: 18),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('Keep going'),
),
],
);
},
),
);
Widget contents() {
final chapter = g.contentsChapter;
final first = chapter * 4;
@@ -827,6 +928,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
writing(l.title, size: 33),
gap(),
reading(l.before, size: 25),
if (l.beforeContinuation.isNotEmpty) reading(l.beforeContinuation),
if (g.book.tracks.containsKey(recordingId)) audio(),
divider(),
writing(
@@ -837,7 +939,9 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
color: muted,
),
action(
prefs.contains('grid_story_v1_${g.campaignIndex}')
g.recovered(g.campaignIndex)
? 'View the solved pattern →'
: prefs.contains('grid_story_v1_${g.campaignIndex}')
? 'Continue this pattern →'
: 'Restore the pattern →',
() => g.startCampaign(g.campaignIndex),
@@ -884,6 +988,8 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
}
List<Widget> puzzleNotes() => [
if (g.mode == Mode.campaign)
InkButton('Sound & atmosphere', soundSettings, size: 18),
writing(
g.won
? 'Already restored. Turn the leaf to revisit the memory.'
@@ -904,7 +1010,9 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
const SizedBox(width: 8),
Expanded(
child: InkButton(
prefs.flag('hint_${g.key}')
g.mode == Mode.campaign
? 'Hint · free'
: prefs.flag('hint_${g.key}')
? 'Hint · rewarded ad'
: 'Hint · free',
hint,
@@ -984,8 +1092,14 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
(
label: g.mode == Mode.daily
? 'Return to the notebook'
: g.mode == Mode.campaign
? 'Revisit the memory →'
: 'Next puzzle →',
run: g.mode == Mode.daily ? g.home : nextPractice,
run: g.mode == Mode.daily
? g.home
: g.mode == Mode.campaign
? () => g.reveal(g.campaignIndex)
: nextPractice,
primary: true,
),
(label: 'How to play', run: rules, primary: false),
@@ -1068,7 +1182,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
}
}
if (!prefs.flag('hint_$requested')) {
if (g.mode == Mode.campaign || !prefs.flag('hint_$requested')) {
await prefs.set('hint_$requested', true);
give();
return;
@@ -1110,14 +1224,20 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
);
}
if (level.illustrationAsset case final asset?) {
return Image.asset(
asset,
return Discovery(
key: ValueKey('discovery-${g.campaignIndex}'),
picture: level.picture,
label: level.object,
height: height,
width: double.infinity,
fit: BoxFit.contain,
semanticLabel: 'Watercolour illustration: ${level.object}',
errorBuilder: (_, _, _) =>
PixelPicture(level.picture, label: level.object, height: height),
artwork: Image.asset(
asset,
height: height,
width: double.infinity,
fit: BoxFit.contain,
semanticLabel: 'Watercolour illustration: ${level.object}',
errorBuilder: (_, _, _) =>
PixelPicture(level.picture, label: level.object, height: height),
),
);
}
return PixelPicture(level.picture, label: level.object, height: height);
@@ -1140,9 +1260,12 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
writing(l.object, size: 35),
discoveryArt(l),
reading(l.after, size: 25),
if (l.afterContinuation.isNotEmpty) reading(l.afterContinuation),
if (g.book.tracks.containsKey(recordingId)) audio(),
if (!g.recovered(i))
action('Return to this pattern', () => g.startCampaign(i)),
action(
g.recovered(i) ? 'View the solved pattern' : 'Return to this pattern',
() => g.startCampaign(i),
),
gap(),
writing(
g.recovered(i)
@@ -1193,7 +1316,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
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.',
'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\nStory hints are always free and explained. Daily and classic puzzles offer one free hint, then optional rewarded hints. Streaks count consecutive daily completions on this device.',
close: 'Got it',
);
Future<void> privacy() async {
+145
View File
@@ -0,0 +1,145 @@
import 'dart:async';
import 'package:audio_session/audio_session.dart';
import 'package:flutter/foundation.dart';
import 'package:just_audio/just_audio.dart';
enum Soundscape { cottage, harbour, bridge, tower }
Soundscape soundscapeFor(int campaignIndex) => switch (campaignIndex) {
4 || 5 || 7 => Soundscape.harbour,
6 => Soundscape.bridge,
8 || 9 || 10 => Soundscape.tower,
_ => Soundscape.cottage,
};
/// Small output boundary lets tests exercise races and fades without a device.
abstract interface class AmbienceOutput {
Future<void> load(Soundscape scene);
Future<void> volume(double value);
Future<void> play();
Future<void> stop();
Future<void> dispose();
}
class _AudioOutput implements AmbienceOutput {
// One shared speech session; this layer must not steal focus from the voice.
final _player = AudioPlayer(handleAudioSessionActivation: false);
@override
Future<void> load(Soundscape scene) async {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
if (!await session.setActive(true)) {
throw StateError('Audio focus unavailable');
}
await _player.setLoopMode(LoopMode.one);
await _player.setAsset('assets/audio/ambience_${scene.name}.wav');
}
@override
Future<void> volume(double value) => _player.setVolume(value);
@override
Future<void> play() => _player.play();
@override
Future<void> stop() => _player.stop();
@override
Future<void> dispose() => _player.dispose();
}
/// Serialises scene changes, fading out old audio before loading the next loop.
/// The newest request wins, including mute/background requests during loading.
class Ambience extends ChangeNotifier {
Ambience({AmbienceOutput? output}) : _output = output ?? _AudioOutput();
final AmbienceOutput _output;
Future<void> _pending = Future.value();
int _revision = 0;
bool _disposed = false;
Soundscape? _desired, _loaded;
double _target = 0, _volume = 0;
String error = '';
Future<void> get settled => _pending;
void update({
required Soundscape? scene,
required bool enabled,
required bool foreground,
required bool narrating,
required double volume,
}) {
if (_disposed) return;
final desired = enabled && foreground ? scene : null;
final target = desired == null
? 0.0
: .4 * volume.clamp(0.0, 1.0) * (narrating ? .25 : 1);
if (_desired == desired && _target == target) return;
_desired = desired;
_target = target;
final revision = ++_revision;
_pending = _pending.then((_) => _apply(revision));
}
bool _current(int revision) => !_disposed && revision == _revision;
Future<void> _fade(double target, int revision) async {
final start = _volume;
for (var i = 1; i <= 8 && _current(revision); i++) {
_volume = start + (target - start) * i / 8;
await _output.volume(_volume);
await Future<void>.delayed(const Duration(milliseconds: 30));
}
}
Future<void> _apply(int revision) async {
if (!_current(revision)) return;
try {
final scene = _desired;
if (scene != _loaded || scene == null) {
// Muting/backgrounding stops immediately; scene changes fade gently.
if (scene != null && _loaded != null) await _fade(0, revision);
if (!_current(revision)) return;
await _output.stop();
_loaded = null;
_volume = 0;
await _output.volume(0);
if (scene == null || !_current(revision)) return;
await _output.load(scene);
if (!_current(revision)) return;
error = '';
_loaded = scene;
unawaited(
_output.play().catchError((Object _) {
if (_current(revision)) _failed();
}),
);
}
await _fade(_target, revision);
} catch (_) {
if (!_disposed) {
try {
await _output.stop();
} catch (_) {
// A missing or unavailable audio backend must not break the book.
}
_loaded = null;
_failed();
}
}
}
void _failed() {
if (_disposed) return;
error =
'The atmosphere could not be played. Your reading is still available.';
notifyListeners();
}
@override
void dispose() {
_disposed = true;
++_revision;
unawaited(_pending.whenComplete(_output.dispose));
super.dispose();
}
}
+10
View File
@@ -51,6 +51,16 @@ class Narrator extends ChangeNotifier {
return '';
}
String get speaker {
for (final cue in tracks[page]?['cues'] ?? []) {
if (position.inMilliseconds >= cue['startMs'] &&
position.inMilliseconds < cue['endMs']) {
return cue['speaker'] ?? tracks[page]?['speaker'] ?? '';
}
}
return tracks[page]?['speaker'] ?? '';
}
Future<void> toggle(String id, double speed) async {
if (loading) return;
if (playing && page == id) {
+22
View File
@@ -293,6 +293,28 @@ class PixelPicture extends StatelessWidget {
);
}
class PatternStamp extends StatelessWidget {
const PatternStamp(
this.picture, {
super.key,
required this.label,
required this.height,
});
final List<int> picture;
final String label;
final double height;
@override
Widget build(BuildContext context) => Semantics(
image: true,
label: 'Your restored seven by seven pattern: $label',
child: SizedBox.square(
dimension: height,
child: CustomPaint(painter: _Pixels(picture)),
),
);
}
class _Pixels extends CustomPainter {
_Pixels(this.picture);
final List<int> picture;
+108
View File
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import 'board.dart';
import 'paper.dart';
/// The exact solved symbol becomes the illustration, and stays on the page.
class Discovery extends StatefulWidget {
const Discovery({
super.key,
required this.picture,
required this.label,
required this.artwork,
required this.height,
});
final List<int> picture;
final String label;
final Widget artwork;
final double height;
@override
State<Discovery> createState() => _DiscoveryState();
}
class _DiscoveryState extends State<Discovery>
with SingleTickerProviderStateMixin {
late final AnimationController _animation = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 2800),
);
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (MediaQuery.disableAnimationsOf(context)) {
_animation.value = 1;
} else if (_animation.isDismissed) {
_animation.forward();
}
}
@override
void dispose() {
_animation.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Column(
children: [
AnimatedBuilder(
animation: _animation,
builder: (context, _) {
final art = const Interval(
.3,
.85,
curve: Curves.easeInOut,
).transform(_animation.value);
final pattern =
1 -
const Interval(
.45,
.95,
curve: Curves.easeInOut,
).transform(_animation.value);
return SizedBox(
height: widget.height,
child: Stack(
alignment: Alignment.center,
children: [
Opacity(opacity: art, child: widget.artwork),
ExcludeSemantics(
child: Opacity(
opacity: pattern,
child: PatternStamp(
widget.picture,
label: widget.label,
height: widget.height,
),
),
),
],
),
);
},
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
PatternStamp(widget.picture, label: widget.label, height: 56),
const SizedBox(width: 14),
Flexible(
child: Text(
'Your restored pattern\n${widget.label}',
style: hand(18, color: muted),
),
),
],
),
if (!MediaQuery.disableAnimationsOf(context))
InkButton(
'See the transformation again',
() => _animation.forward(from: 0),
size: 18,
),
],
);
}