Open Lumen on a responsive bookshelf and land pending story work
- Start the app on a shelf of every installed book instead of the last book's home. Cards show the cover, translated metadata, available languages, restored patterns and either "Continue reading" or a way in. - Keep each book's saved route: the shelf is never written to flutter_screen, so choosing a book resumes its own leaf. - Lay the shelf out responsively: dense single-column cards on phones, a two-column grid from 720 logical pixels, a centred 860 px column on tablets and a chevron that exists in the bundled handwriting font. - Keep Settings reachable from the shelf and let the home page's story library button open the shelf instead of a dialog. - Add tool/shelf_screenshots_test.dart, which renders the shelf at phone and tablet metrics, checks that every card and Settings stay reachable without overflow, and writes artifacts/library/shelf-*.png. - Commit the pending Midnight Invitation package (campaign, notebook, narration and artwork), cast drama and ambience tooling, region selection, phone/tablet integration coverage and related docs. flutter analyze is clean and all 74 widget/domain tests pass.
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
// Reproducible constraint authoring for the fixed Halloween picture silhouettes.
|
||||
// This never changes the authored pictures or story text.
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:lumen/domain/puzzle.dart';
|
||||
import 'package:lumen/domain/thinking.dart';
|
||||
|
||||
void main() {
|
||||
final file = File('assets/stories/midnight-invitation/campaign.json');
|
||||
final data = jsonDecode(file.readAsStringSync()) as Map<String, dynamic>;
|
||||
final reports = <Map<String, Object?>>[];
|
||||
for (var index = 0; index < (data['levels'] as List).length; index++) {
|
||||
final record = data['levels'][index] as Map<String, dynamic>;
|
||||
final picture = (record['picture'] as String)
|
||||
.split('')
|
||||
.map(int.parse)
|
||||
.toList();
|
||||
final random = Random(0x10312026 + index);
|
||||
Puzzle? best;
|
||||
ThinkingReport? bestReport;
|
||||
var bestScore = double.infinity;
|
||||
final trials = index < 2 ? 180 : 1200;
|
||||
for (var trial = 0; trial < trials; trial++) {
|
||||
final p = Puzzle(7, picture);
|
||||
final regionCount = index < 2
|
||||
? 0
|
||||
: index < 4
|
||||
? 2
|
||||
: 3;
|
||||
while (p.regions.length < regionCount) {
|
||||
final height = 3 + random.nextInt(2), width = 3 + random.nextInt(2);
|
||||
final r = Region(
|
||||
String.fromCharCode(65 + p.regions.length),
|
||||
random.nextInt(8 - height),
|
||||
random.nextInt(8 - width),
|
||||
height,
|
||||
width,
|
||||
);
|
||||
if (p.regions.any(
|
||||
(old) =>
|
||||
old.top == r.top &&
|
||||
old.left == r.left &&
|
||||
old.height == r.height &&
|
||||
old.width == r.width,
|
||||
)) {
|
||||
continue;
|
||||
}
|
||||
if (p.regions.isNotEmpty) {
|
||||
final old = p.regions.last;
|
||||
final common = List.generate(
|
||||
49,
|
||||
(i) => i,
|
||||
).where((i) => old.contains(i, 7) && r.contains(i, 7)).length;
|
||||
if (common < 2 ||
|
||||
common >= min(old.height * old.width, r.height * r.width)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
p.regions.add(r);
|
||||
}
|
||||
final order = List.generate(49, (i) => i)..shuffle(random);
|
||||
for (final cell in order.take(2 + random.nextInt(3))) {
|
||||
p.given[cell] = true;
|
||||
}
|
||||
final solver = LogicSolver(49, p.constraints);
|
||||
var analysis = solver.analyze(p.initial);
|
||||
while (!analysis.solved && p.given.where((v) => v).length < 8) {
|
||||
final candidates = List.generate(
|
||||
49,
|
||||
(i) => i,
|
||||
).where((i) => analysis.cells[i] < 0).toList()..shuffle(random);
|
||||
var selected = candidates.first, mostKnown = -1;
|
||||
for (final cell in candidates.take(8)) {
|
||||
p.given[cell] = true;
|
||||
final a = solver.analyze(p.initial);
|
||||
final known = a.cells.where((v) => v >= 0).length;
|
||||
if (known > mostKnown) {
|
||||
selected = cell;
|
||||
mostKnown = known;
|
||||
}
|
||||
p.given[cell] = false;
|
||||
}
|
||||
p.given[selected] = true;
|
||||
analysis = solver.analyze(p.initial);
|
||||
}
|
||||
if (!analysis.solved) continue;
|
||||
for (final cell in order.where((i) => p.given[i])) {
|
||||
if (p.given.where((v) => v).length <= (index < 2 ? 2 : 0)) break;
|
||||
p.given[cell] = false;
|
||||
if (!solver.analyze(p.initial).solved) p.given[cell] = true;
|
||||
}
|
||||
final singles = solver.analyze(p.initial, useAreas: false);
|
||||
if (index >= 2 && (singles.solved || analysis.areaDeductions == 0)) {
|
||||
continue;
|
||||
}
|
||||
final givens = p.given.where((v) => v).length;
|
||||
final foothold = singles.cells.where((v) => v >= 0).length - givens;
|
||||
if (foothold < 4) continue;
|
||||
final report = ThinkingAnalyzer(
|
||||
49,
|
||||
p.constraints,
|
||||
).analyze(p.initial, maxLookahead: 0);
|
||||
if (report.status != ThinkingStatus.solved || report.assumptionSteps != 0) {
|
||||
continue;
|
||||
}
|
||||
final targetRounds = index < 2 ? 4.0 : 5.0 + index / 4;
|
||||
final targetComparison = index < 2 ? 0 : 2 + index ~/ 3;
|
||||
final score =
|
||||
(report.rounds.length - targetRounds).abs() * 3 +
|
||||
(report.comparisonSteps - targetComparison).abs() * 1.5 +
|
||||
givens * 1.2 +
|
||||
(index >= 4 ? (foothold - 12).abs() * .15 : 0);
|
||||
if (score < bestScore) {
|
||||
bestScore = score;
|
||||
best = p;
|
||||
bestReport = report;
|
||||
}
|
||||
if (score < 3.5) break;
|
||||
}
|
||||
if (best == null || bestReport == null) {
|
||||
throw StateError('No suitable constraints for ${record['id']}');
|
||||
}
|
||||
if (best.countSolutions() != 1) {
|
||||
throw StateError('Non-unique ${record['id']}');
|
||||
}
|
||||
record['clues'] = List.generate(
|
||||
49,
|
||||
(i) => i,
|
||||
).where((i) => best!.given[i]).join(',');
|
||||
record['areas'] = best.regions
|
||||
.map((r) => '${r.top},${r.left},${r.height},${r.width}')
|
||||
.join(';');
|
||||
reports.add({
|
||||
'id': record['id'],
|
||||
'givens': record['clues'],
|
||||
'areas': record['areas'],
|
||||
'report': bestReport.toJson(),
|
||||
});
|
||||
stdout.writeln(
|
||||
'${index + 1}. ${record['id']}: ${bestReport.givens} givens, ${bestReport.rounds.length} rounds, ${bestReport.comparisonSteps} comparisons, no assumptions',
|
||||
);
|
||||
}
|
||||
file.writeAsStringSync(
|
||||
'${const JsonEncoder.withIndent(' ').convert(data)}\n',
|
||||
);
|
||||
File('assets/stories/midnight-invitation/puzzle-report.json')
|
||||
.writeAsStringSync(
|
||||
'${const JsonEncoder.withIndent(' ').convert(reports)}\n',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the editable diary manuscript into stable story pages and cast scripts.
|
||||
|
||||
Puzzle grids, clues, IDs, progress keys and artwork associations are preserved.
|
||||
After running, render narration and run the story package checks before building.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PACKAGE = ROOT / 'assets/stories/midnight-invitation'
|
||||
read = lambda p: json.loads(p.read_text())
|
||||
write = lambda p, data: p.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
|
||||
parts = re.split(r'^## (\S+) \| (.+)\n\n', (PACKAGE/'STORY.md').read_text(), flags=re.M)
|
||||
entries = {parts[i]: (parts[i+1], parts[i+2].strip()) for i in range(1,len(parts),3)}
|
||||
campaign = read(PACKAGE/'campaign.json')
|
||||
notebook = read(PACKAGE/'notebook.json')
|
||||
assert set(entries) == {p['id'] for p in notebook['pages'] if p['type'] != 'puzzle'}
|
||||
chapters = ['I · The road that would not end', 'II · The guest beneath the floor', 'III · Return to sender']
|
||||
campaign['premise'] = 'The private diary of Elias Ward, a Blackthorn postman. On Halloween he carried a letter in his own handwriting to a house with twelve missing guests and a thirteenth place waiting for him. A complete Gothic mystery in three chapters.'
|
||||
for i, level in enumerate(campaign['levels']):
|
||||
prefix = 'midnight.' + level['id']
|
||||
level['title'], level['before'] = entries[prefix+'.entry']
|
||||
level['memoryTitle'], level['after'] = entries[prefix+'.memory']
|
||||
level['chapter'] = chapters[i//4]
|
||||
for page in notebook['pages']:
|
||||
if page['id'] in entries:
|
||||
page['title'], text = entries[page['id']]
|
||||
if page.get('textSource') not in ('before','after'):
|
||||
page['text'] = text
|
||||
page['speaker'] = 'Elias Ward · private delivery diary'
|
||||
else:
|
||||
page['title'] = campaign['levels'][page['campaignIndex']]['title']
|
||||
if 'caption' in page:
|
||||
if page['id'] == 'midnight.opening':
|
||||
page['caption'] = 'Blackthorn. An account written after the Halloween delivery.'
|
||||
else:
|
||||
page['caption'] = chapters[page['campaignIndex']//4]
|
||||
write(PACKAGE/'campaign.json',campaign)
|
||||
write(PACKAGE/'notebook.json',notebook)
|
||||
cast = {
|
||||
'Elias': {'voice':'bm_george','speed':.93,'language':'en-gb',
|
||||
'direction':'A postman recording a night he barely survived. Personal and restrained; fear through careful observation, not theatrical shouting.'},
|
||||
'Iris': {'voice':'bf_emma','speed':.91,'language':'en-gb',
|
||||
'direction':'A tired guardian speaking quietly so the house will not hear. Clear, urgent warnings; fragile relief near the end.'},
|
||||
'Ada': {'voice':'bf_isabella','speed':.94,'language':'en-gb',
|
||||
'direction':'The postmistress. A practical voice with a serious warning.'},
|
||||
'The borrowed voice': {'voice':'bf_isabella','speed':.87,'language':'en-gb',
|
||||
'direction':'An imitation of Ada through a closed door. Do not exaggerate; its familiarity is the threat.'},
|
||||
'The echo': {'voice':'bm_george','speed':.87,'language':'en-gb',
|
||||
'direction':'An imitation of Elias behind a door, slightly slower and distant.'},
|
||||
}
|
||||
write(PACKAGE/'narration/cast.json',cast)
|
||||
roles = {
|
||||
'midnight.opening':['Ada'],
|
||||
'midnight.feather.memory':['Iris','Elias','Iris','Iris'],
|
||||
'midnight.key.entry':['The borrowed voice','Iris'],
|
||||
'midnight.needle.memory':['Iris','Iris','The echo'],
|
||||
}
|
||||
effects = {
|
||||
'midnight.feather.memory':{'At the door I knocked twice.':'door-knock', 'A chair scraped over the floor on the other side.':'chair-shift'},
|
||||
'midnight.candle.entry':{'I spread the paper beneath the lamp.':'paper'},
|
||||
'midnight.ending':{'A few minutes ago, the drawer knocked twice.':'door-knock'},
|
||||
}
|
||||
records=[]
|
||||
for page_id,(title,text) in entries.items():
|
||||
quotes=list(re.finditer('“[^”]+”',text))
|
||||
speakers=roles.get(page_id,['Iris']*len(quotes))
|
||||
assert len(quotes)==len(speakers),(page_id,len(quotes),speakers)
|
||||
spans=[(m.start(),m.end(),speaker) for m,speaker in zip(quotes,speakers)]
|
||||
cuts={0,len(text)}
|
||||
cuts.update(m.end() for m in re.finditer('\n\n',text))
|
||||
for a,b,_ in spans: cuts.update((a,b))
|
||||
actions={}
|
||||
for phrase,name in effects.get(page_id,{}).items():
|
||||
assert phrase in text
|
||||
end=text.index(phrase)+len(phrase)
|
||||
cuts.add(end);actions[end]=name
|
||||
if page_id=='midnight.feather.memory':
|
||||
end=text.index('Silence.')+len('Silence.');cuts.add(end);actions[end]=1500
|
||||
segments=[]
|
||||
bounds=sorted(cuts)
|
||||
for start,end in zip(bounds,bounds[1:]):
|
||||
part=text[start:end]
|
||||
if not part.strip():
|
||||
segments[-1]['text']+=part
|
||||
segments[-1]['pauseMs']=max(segments[-1]['pauseMs'],700)
|
||||
continue
|
||||
speaker=next((s for a,b,s in spans if a<=start<b),'Elias')
|
||||
segment={'speaker':speaker,'text':part,'pauseMs':700 if part.endswith('\n\n') else 220}
|
||||
if speaker in ('The borrowed voice','The echo') or (page_id=='midnight.feather.memory' and speaker=='Iris'):
|
||||
segment['perspective']='behind-door'
|
||||
if speaker=='Iris': segment['direction']=cast['Iris']['direction']
|
||||
action=actions.get(end)
|
||||
if isinstance(action,str): segment.update(afterEffect=action,pauseMs=1350)
|
||||
elif action: segment['pauseMs']=action
|
||||
if part.strip() in ('I kept walking.','It did not strike.','The mouth closed.'):
|
||||
segment['pauseMs']=1200
|
||||
segments.append(segment)
|
||||
assert ''.join(s['text'] for s in segments)==text
|
||||
records.append({'pageId':page_id,'resource':page_id.replace('.','_'),'text':text,
|
||||
'speaker':'Elias','production':'diary-drama-v2','segments':segments})
|
||||
write(PACKAGE/'narration/scripts.json',records)
|
||||
library=read(ROOT/'assets/library.json')
|
||||
story=next(s for s in library['stories'] if s['id']=='midnight-invitation')
|
||||
story['description']='A postman’s Halloween diary: twelve missing guests, a stolen voice, and a letter that must never be delivered.'
|
||||
story['paperAsset']='assets/stories/midnight-invitation/artwork/diary-page-v1.png'
|
||||
write(ROOT/'assets/library.json',library)
|
||||
print(f'Compiled {len(entries)} diary entries, {sum(len(t.split()) for _,t in entries.values())} words; puzzle identity preserved.')
|
||||
@@ -0,0 +1,156 @@
|
||||
// Temporary layout harness: renders the bookshelf at phone/tablet device
|
||||
// metrics and writes PNGs to artifacts/library/. Not part of the normal suite.
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:lumen/domain/game.dart';
|
||||
import 'package:lumen/domain/library.dart';
|
||||
import 'package:lumen/main.dart';
|
||||
import 'package:lumen/services/progress.dart';
|
||||
|
||||
const _screen = ValueKey('screenshot-surface');
|
||||
const _output = 'artifacts/library';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
Future<void> capture(
|
||||
WidgetTester tester, {
|
||||
required String name,
|
||||
required Size logical,
|
||||
required double dpr,
|
||||
double textScale = 1,
|
||||
bool captureEnd = false,
|
||||
}) async {
|
||||
addTearDown(tester.view.reset);
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
await tester.runAsync(() async {
|
||||
final font = FontLoader('MaraHand')
|
||||
..addFont(rootBundle.load('assets/fonts/DancingScript.ttf'));
|
||||
await font.load();
|
||||
});
|
||||
final library = (await tester.runAsync(StoryLibrary.load))!;
|
||||
await tester.runAsync(() async {
|
||||
for (final story in library.stories) {
|
||||
for (final language in story.languages.keys) {
|
||||
await library.open(story.id, language: language);
|
||||
}
|
||||
}
|
||||
});
|
||||
final assets = <String>{
|
||||
'assets/artwork/mara-single-page-v2.png',
|
||||
for (final story in library.stories) ?story.coverAsset,
|
||||
};
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
tester.view.physicalSize = Size(logical.width * dpr, logical.height * dpr);
|
||||
tester.platformDispatcher.textScaleFactorTestValue = textScale;
|
||||
final book = (await tester.runAsync(() => library.open('mara-island')))!;
|
||||
final g = Game(book, Progress.memory({'language': 'en'}), library: library)
|
||||
..showLibrary();
|
||||
await tester.pumpWidget(
|
||||
RepaintBoundary(
|
||||
key: _screen,
|
||||
child: LumenApp(game: g, adsEnabled: false),
|
||||
),
|
||||
);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 20)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
await tester.runAsync(() async {
|
||||
final context = tester.element(find.byKey(_screen));
|
||||
for (final asset in assets) {
|
||||
await precacheImage(AssetImage(asset), context);
|
||||
}
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(g.screen, Screen.library, reason: name);
|
||||
expect(find.text('Choose a book'), findsOneWidget, reason: name);
|
||||
for (final story in library.stories) {
|
||||
expect(
|
||||
find.byKey(ValueKey('library-book-${story.id}')),
|
||||
findsOneWidget,
|
||||
reason: name,
|
||||
);
|
||||
}
|
||||
expect(tester.takeException(), isNull, reason: name);
|
||||
|
||||
Future<void> write(String file) async {
|
||||
await tester.runAsync(() async {
|
||||
final boundary = tester.renderObject<RenderRepaintBoundary>(
|
||||
find.byKey(_screen),
|
||||
);
|
||||
final image = await boundary.toImage(pixelRatio: dpr);
|
||||
final data = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
final target = File('$_output/$file.png');
|
||||
await target.parent.create(recursive: true);
|
||||
await target.writeAsBytes(data!.buffer.asUint8List());
|
||||
image.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
await write(name);
|
||||
// Every book and Settings must remain reachable by scrolling, including on
|
||||
// the smallest phone and at 1.5x text.
|
||||
await tester.ensureVisible(find.text('Settings'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Settings').hitTestable(), findsOneWidget, reason: name);
|
||||
expect(tester.takeException(), isNull, reason: name);
|
||||
if (captureEnd) await write('$name-end');
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
}
|
||||
|
||||
testWidgets('phone 360x640', (tester) async {
|
||||
await capture(
|
||||
tester,
|
||||
name: 'shelf-phone-360x640',
|
||||
logical: const Size(360, 640),
|
||||
dpr: 2,
|
||||
captureEnd: true,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('phone 390x844', (tester) async {
|
||||
await capture(
|
||||
tester,
|
||||
name: 'shelf-phone-390x844',
|
||||
logical: const Size(390, 844),
|
||||
dpr: 3,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('phone 360x640 at 1.5x text', (tester) async {
|
||||
await capture(
|
||||
tester,
|
||||
name: 'shelf-phone-360x640-text-1.5x',
|
||||
logical: const Size(360, 640),
|
||||
dpr: 2,
|
||||
textScale: 1.5,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('tablet portrait 800x1280', (tester) async {
|
||||
await capture(
|
||||
tester,
|
||||
name: 'shelf-tablet-800x1280',
|
||||
logical: const Size(800, 1280),
|
||||
dpr: 1.5,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('tablet landscape 1280x800', (tester) async {
|
||||
await capture(
|
||||
tester,
|
||||
name: 'shelf-tablet-1280x800',
|
||||
logical: const Size(1280, 800),
|
||||
dpr: 2,
|
||||
);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user