import 'dart:async'; import 'dart:math' as math; 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/ambience.dart'; import 'services/narrator.dart'; import 'services/progress.dart'; import 'ui/board.dart'; import 'ui/discovery.dart'; import 'ui/paper.dart'; Future 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 createState() => _NotebookState(); } class _NotebookState extends State 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}'; @override 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(); }); } void _changed() { if (_route != route) { _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); } } @override void dispose() { WidgetsBinding.instance.removeObserver(this); g.removeListener(_changed); narrator.removeListener(_syncAtmosphere); ambience.dispose(); 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 confirm( String title, String text, String yes, { String no = 'Keep reading', }) async => await showDialog( 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 message( String title, String text, { String close = 'Keep going', }) async { await showDialog( 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 turn(int direction) async { if (direction > 0 && g.storyIndex == g.book.pages.length - 1) { crossToHarbour(); return; } final next = (g.storyIndex + direction).clamp(0, g.book.pages.length - 1); if (next == g.storyIndex) return; final pageId = g.storyPage.id; if (g.storyPage.type == StoryPageType.puzzle && 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); } if (mounted && g.storyPage.id == pageId) g.showStory(next); } void crossToHarbour() { g.leaveCottage(); } Future turnCampaign(int direction) async { final index = g.campaignIndex; switch (g.screen) { case Screen.briefing: if (direction > 0) { g.startCampaign(index); } else if (index > 0) { if (index == 4) { g.showStory(g.book.pages.length - 1); } else { g.reveal(index - 1, readAhead: true); } } else { g.contents(); } case Screen.game: if (direction < 0) { g.briefing(index); return; } if (!g.won && !await confirm( 'Leave a ribbon here?', 'Your puzzle marks are saved. You can read the memory now and return to this pattern whenever you like.', 'Read ahead', no: 'Keep solving', )) { return; } if (mounted) g.reveal(index, readAhead: true); case Screen.reveal: if (direction < 0) { g.startCampaign(index); } else { nextCampaign(); } default: break; } } void nextCampaign() { final index = g.campaignIndex; if (index == 11) { g.contents(); return; } // Reading access is distinct from completed puzzles and their awards. unawaited( prefs.set('story_access_level', math.max(g.accessible, index + 1)), ); void next() { if (mounted) g.briefing(index + 1); } if (g.recovered(index) && (index + 1) % 4 == 0 && !prefs.flag('storyAd_$index')) { unawaited(prefs.set('storyAd_$index', true)); ads.between(next); } else { 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.reveal: g.startCampaign(g.campaignIndex); case Screen.briefing: 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 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('Sound & atmosphere', soundSettings), 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), ), ]), ), ), ), ), ); void bookmark() { unawaited( prefs.set('notebook_manual_bookmark', g.book.pages[g.storyIndex].id), ); toast('A ribbon marks this page.'); } Widget navigation() { final wide = MediaQuery.orientationOf(context) == Orientation.landscape; final previous = InkButton( '← Previous leaf', g.storyIndex > 0 ? () => turn(-1) : null, size: wide ? 19 : 21, ); final next = InkButton( g.storyIndex == g.book.pages.length - 1 ? 'Across the tide →' : 'Next leaf →', () => turn(1), size: wide ? 19 : 21, ); if (wide) { // One row keeps the shorter landscape page free for the illustration // and the puzzle beside it. return Row( children: [ Expanded(child: InkButton('Contents', g.contents, size: 19)), const SizedBox(width: 6), Expanded(child: InkButton('Bookmark', bookmark, size: 19)), const SizedBox(width: 6), Expanded(child: InkButton('Close book', g.home, size: 19)), const SizedBox(width: 6), Expanded(child: previous), const SizedBox(width: 6), Expanded(child: next), ], ); } return column([ Row( children: [ Expanded(child: InkButton('Contents', g.contents, size: 20)), const SizedBox(width: 6), Expanded(child: InkButton('Bookmark', bookmark, size: 20)), const SizedBox(width: 6), Expanded(child: InkButton('Close book', g.home, size: 20)), ], ), Row( children: [ Expanded(child: previous), const SizedBox(width: 8), Expanded(child: next), ], ), ]); } String get recordingId => g.screen == Screen.story ? g.storyPage.id : 'campaign.${g.campaignIndex}.${g.screen == Screen.briefing ? 'before' : 'after'}'; Widget reading(String text, {double? size}) => 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(size ?? (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([ writing( (narrator.page == recordingId ? narrator.speaker : g.book.tracks[recordingId]?['speaker']) == 'Narrator' ? 'Narrator · recorded story' : 'Mara · diary reading', size: 17, color: muted, ), Row( children: [ Expanded( flex: 3, child: InkButton( narrator.label, narrator.loading ? null : () => narrator.toggle( recordingId, 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), InkButton('Sound & atmosphere', soundSettings, size: 18), ]), ); Widget story() { final p = g.book.pages[g.storyIndex]; final heading = [ folio('THE COTTAGE / ${g.storyIndex + 1} OF ${g.book.pages.length}'), writing(p.title, size: 31), ]; final body = [...heading]; Widget? wideBody; switch (p.type) { case StoryPageType.dedication: body.addAll([ writing('A few things worth keeping', size: 20, color: muted), divider(), reading(p.text), audio(), ]); case StoryPageType.entry: body.addAll([ if (p.illustrationAsset case final asset?) Image.asset( asset, height: 155, fit: BoxFit.contain, semanticLabel: 'Watercolour of Gran’s stone cottage, blue door and warm window.', ), 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)), ]); case StoryPageType.puzzle: final intro = writing( g.campaignIndex < 2 ? 'Restore a small light, or leave a bookmark and read on.' : 'Compare the shared areas. Each cell counts in every area it belongs to.', size: 21, color: muted, ); body.addAll([intro, puzzleBody()]); wideBody = splitPuzzle( side: [...heading, intro, areaPicker(), ...puzzleNotes()], ); case StoryPageType.memory: body.addAll([ discoveryArt(g.book.levels[p.campaignIndex!], height: 155), writing( g.recovered(p.campaignIndex!) ? 'A pattern restored · a memory kept' : 'A memory to read · your puzzle can wait', size: 17, color: muted, ), reading(p.text), if (p.continuation.isNotEmpty) reading(p.continuation), if (g.book.tracks.containsKey(p.id)) audio(), 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')) { 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 StoryPageType.inspection: body.addAll([ writing( prefs.flag('notebook_handle_seen') ? 'A repair made to keep small fingers safe.' : 'A repair note, tucked into the margin.', size: 20, color: muted, ), reading(p.text), audio(), action('Read Gran’s margin note', inspect), action('Follow the lantern into the next entry →', () => turn(1)), ]); case StoryPageType.closing: body.addAll([ reading(p.text), if (g.book.tracks.containsKey(p.id)) audio(), writing( 'Four memories in the cottage · ${List.generate(4, (i) => g.recovered(i)).where((v) => v).length} patterns restored', size: 19, color: muted, ), action( 'Take the path to the harbour →', crossToHarbour, primary: true, ), writing( 'Your unfinished patterns will wait here for you.', size: 19, color: muted, ), ]); } return Leaf( key: ValueKey('story-${g.storyIndex}'), onTurn: (d) => turn(d), body: column(body), wideBody: wideBody, footer: navigation(), ); } void openLetter() { unawaited(prefs.set('notebook_note_open', true)); setState(() {}); } Future 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 speed() async { await narrator.pause(); if (!mounted) return; await showDialog( 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)), ), ], ), ); } Future soundSettings() => showDialog( 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; final savedId = prefs.text('notebook_last_page'); final saved = g.book.pages.where((p) => p.id == savedId).firstOrNull; final bookmarkId = prefs.text('notebook_manual_bookmark'); final ribbon = g.book.pages.where((p) => p.id == bookmarkId).firstOrNull; return Leaf( key: ValueKey('contents-$chapter'), body: column([ folio('MARA’S NOTEBOOK · CONTENTS'), writing(g.book.levels[first].chapter, size: 34), if (chapter == 0) ...[ writing( 'For you, when you are ready. With all my love, Gran.', color: const Color(0xff70503b), ), action('Open the dedication', () => g.showStory(0)), if (saved != null) action('Continue reading · ${saved.title}', g.openNotebook), if (ribbon != null) action( 'Return to my ribbon bookmark', () => g.showStory(g.book.pages.indexOf(ribbon)), ), divider(), ], for (var i = first; i < first + 4; i++) ...[ InkButton( '${i + 1} · ${g.book.levels[i].title}${g.recovered(i) ? ' ✓' : ''}${chapter == 0 && ribbon?.campaignIndex == i ? ' · ribbon' : ''}', i <= g.accessible ? () { if (g.recovered(i)) { g.reveal(i); } else { g.briefing(i); } } : null, ), ], if (chapter == 0) ...[ divider(), action('The folded note', () => g.showStory(4)), action('Gran’s repair note', () => g.showStory(5)), action( 'Before you leave', () => g.showStory(g.book.pages.length - 1), ), ], writing( '${g.recoveredCount} / 12 memories restored', size: 20, color: muted, ), ]), footer: column([ Row( children: [ Expanded( child: InkButton( '← Previous chapter', chapter > 0 ? () => g.contents(chapter - 1) : null, size: 19, ), ), Expanded( child: InkButton( 'Next chapter →', chapter < 2 && (chapter + 1) * 4 <= g.accessible ? () => g.contents(chapter + 1) : null, size: 19, ), ), ], ), InkButton('Close the notebook', g.home, size: 19), ]), ); } Widget briefing() { final l = g.book.levels[g.campaignIndex]; return Leaf( key: ValueKey('briefing-${g.campaignIndex}'), onTurn: (d) => turnCampaign(d), body: column([ folio('MARA’S NOTEBOOK / LEAF ${g.campaignIndex + 1}'), writing(l.chapter, size: 20, color: blue), 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( 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( 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), primary: true, ), action('Back to notebook', g.contents), ]), ); } Widget puzzleBody() => column([areaPicker(), board(), ...puzzleNotes()]); Widget areaPicker() { final p = g.puzzle; if (p == null || p.regions.isEmpty) return const SizedBox.shrink(); return column([ 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), ]); } Widget board({double maxWidth = 350}) { final p = g.puzzle; if (p == null) return const SizedBox.shrink(); return Board( puzzle: p, cells: g.cells, onMark: g.mark, selectedArea: g.selectedArea, won: g.won, maxWidth: maxWidth, ); } List puzzleNotes() => [ if (g.mode == Mode.campaign) InkButton('Sound & atmosphere', soundSettings, size: 18), 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( g.mode == Mode.campaign ? 'Hint · free' : prefs.flag('hint_${g.key}') ? 'Hint · rewarded ad' : 'Hint · free', hint, size: 22, ), ), ], ), ]; /// Landscape puzzle leaf: the grid keeps the left column at its full height /// while the heading, area clues and notes sit beside it, so nothing has to /// be scrolled into view before the board can be played. Widget splitPuzzle({required List side}) => LayoutBuilder( builder: (context, c) { final width = math.min(c.maxWidth, 980.0), height = c.maxHeight.isFinite ? c.maxHeight : c.maxWidth, // Keep a readable column for the notes, then give the rest to the // grid, which stays a square no taller than the page. panel = math.min( math.min(280.0, math.max(200.0, width * .40)), width * .55, ), grid = math.min(math.min(height, width - panel - 18), 520.0); return Align( alignment: Alignment.center, child: SizedBox( width: width, height: height, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( width: grid, child: Center(child: board(maxWidth: grid)), ), const SizedBox(width: 18), Expanded( child: SingleChildScrollView( key: const PageStorageKey('leaf-side-scroll'), padding: const EdgeInsets.fromLTRB(2, 0, 2, 8), child: column(side), ), ), ], ), ), ); }, ); Widget game() { List heading({bool compact = false}) => [ 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: compact ? 27 : 32, ), writing( g.puzzle?.regions.isEmpty ?? true ? 'Match the totals. Let the pattern emerge.' : 'Compare rows, columns and overlapping areas.', size: compact ? 18 : 21, color: muted, ), ]; final actions = <({String label, VoidCallback run, bool primary})>[ if (g.won) ( 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 : g.mode == Mode.campaign ? () => g.reveal(g.campaignIndex) : nextPractice, primary: true, ), (label: 'How to play', run: rules, primary: false), ( label: 'Back to notebook', run: g.mode == Mode.campaign ? g.contents : g.home, primary: false, ), ]; final clarity = writing('A moment of clarity.', size: 29); return Leaf( key: ValueKey('game-${g.key}'), onTurn: g.mode == Mode.campaign ? (d) => turnCampaign(d) : null, body: column([ ...heading(), puzzleBody(), if (g.won) clarity, for (final a in actions) action(a.label, a.run, primary: a.primary), ]), // Landscape: the heading and notes sit beside the grid while the leaf's // actions stay in a compact bar that does not take room from the board. wideBody: Column( children: [ Expanded( child: splitPuzzle( side: [ ...heading(compact: true), areaPicker(), ...puzzleNotes(), if (g.won) writing('A moment of clarity.', size: 23), ], ), ), Padding( padding: const EdgeInsets.only(top: 6, bottom: 4), child: Row( children: [ for (var i = 0; i < actions.length; i++) ...[ if (i > 0) const SizedBox(width: 8), Expanded( child: InkButton( actions[i].label, actions[i].run, size: 20, primary: actions[i].primary, ), ), ], ], ), ), ], ), ); } Future 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.storyPage.type == StoryPageType.puzzle)) { 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.screen == Screen.game || g.screen == Screen.story && g.storyPage.type == StoryPageType.puzzle)) { g.check(); } } if (g.mode == Mode.campaign || !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 discoveryArt(CampaignLevel level, {double height = 190}) { // Discovery images belong only to the leaf after the puzzle, even when // revisiting an earlier page with a completed save. if (!(g.screen == Screen.reveal || g.screen == Screen.story && g.storyPage.type == StoryPageType.memory)) { return const SizedBox.shrink(); } if (!g.recovered(g.book.levels.indexOf(level))) { return writing( 'The picture will appear once you restore the pattern.', size: 19, color: muted, ); } if (level.illustrationAsset case final asset?) { return Discovery( key: ValueKey('discovery-${g.campaignIndex}'), picture: 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); } Widget reveal() { final i = g.campaignIndex, l = g.book.levels[i]; return Leaf( key: ValueKey('reveal-$i'), onTurn: (d) => turnCampaign(d), body: column([ folio('MARA’S NOTEBOOK / LEAF ${i + 1}'), writing( g.recovered(i) ? 'Something found. Something remembered.' : 'A memory to read · your pattern can wait', size: 23, color: muted, ), 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(), action( g.recovered(i) ? 'View the solved pattern' : 'Return to this pattern', () => g.startCampaign(i), ), gap(), writing( g.recovered(i) ? 'Kept safe, between these pages. — M.' : 'Your pattern is saved for another day.', size: 23, color: const Color(0xff70503b), ), divider(), if (i == 11) ...[ folio( g.recoveredCount == 12 ? 'THE END · YOUR WATCH HAS BEGUN' : 'THE LAST PAGE · COME BACK WHENEVER YOU LIKE', ), writing( g.recoveredCount == 12 ? 'Twelve patterns. One light brought home. The daily puzzle will be here whenever you return.' : 'A light kept in these pages. Your unfinished patterns 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 →', nextCampaign, primary: true), action('Back to notebook', g.contents), ]), ); } Future chooseDifficulty() async { await showDialog( 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\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 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', ); } } }