Files
logic-puzzle/lib/domain/book.dart
T
2026-11-03 17:15:15 +01:00

307 lines
10 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:convert';
import 'package:flutter/services.dart';
import 'puzzle.dart';
import 'library.dart';
class CampaignLevel {
CampaignLevel(Map<String, dynamic> data)
: id = data['id'] as String? ?? '',
chapterId = data['chapterId'] as String? ?? data['chapter'],
size = data['size'] as int? ?? 7,
chapter = data['chapter'],
title = data['title'],
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 id, chapterId;
final int size;
final String chapter, title, object, before, after, clues, areas;
final String beforeContinuation, afterContinuation;
final String? illustrationAsset;
final List<int> picture;
Puzzle puzzle() {
final p = Puzzle(size, picture);
if (clues.isNotEmpty) {
for (final c in clues.split(',')) {
final index = int.parse(c);
if (index < 0 || index >= picture.length) {
throw FormatException('Invalid fixed clue: $id: $index');
}
p.given[index] = true;
}
}
if (areas.isNotEmpty) {
var i = 0;
for (final a in areas.split(';')) {
final v = a.split(',').map(int.parse).toList();
if (v.length != 4) {
throw FormatException('Invalid region: $id');
}
p.regions.add(
Region(String.fromCharCode(65 + i++), v[0], v[1], v[2], v[3]),
);
}
}
return p;
}
}
enum StoryPageType {
dedication,
entry,
puzzle,
memory,
note,
inspection,
closing,
}
class StoryPage {
const StoryPage(
this.id,
this.title,
this.text, {
this.type = StoryPageType.entry,
this.campaignIndex,
this.speaker = '',
this.illustrationAsset,
this.continuation = '',
this.caption = '',
});
final String id, title, text;
final String continuation, caption;
final StoryPageType type;
final int? campaignIndex;
final String speaker;
final String? illustrationAsset;
}
class Book {
Book(
this.premise,
this.levels,
this.pages,
this.tracks, {
this.id = 'mara-island',
this.title = 'Mara’s notebook',
this.description = '',
this.language = 'en',
this.defaultLanguage = 'en',
this.presentation = 'mara',
this.coverAsset = 'assets/artwork/home-notebook-cover-v2.png',
this.continueAt = 4,
this.initiallyAccessible = 3,
this.fontFamily = 'MaraHand',
this.copy = const {},
});
final String id, title, description, language, defaultLanguage, presentation;
final String? coverAsset, fontFamily;
final int? continueAt;
final int initiallyAccessible;
final Map<String, String> copy;
final String premise;
final List<CampaignLevel> levels;
final List<StoryPage> pages;
final Map<String, dynamic> tracks;
bool get isMara => presentation == 'mara';
List<String> get chapters => levels.map((l) => l.chapterId).toSet().toList();
List<int> chapterLevels(int chapter) => [
for (var i = 0; i < levels.length; i++)
if (levels[i].chapterId == chapters[chapter]) i,
];
int chapterFor(int level) => chapters.indexOf(levels[level].chapterId);
String puzzleKey(int index) => id == 'mara-island'
? 'story_v1_$index'
: 'story_${id}_${levels[index].id}';
int pageFor(int campaignIndex, StoryPageType type) => pages.indexWhere(
(p) => p.campaignIndex == campaignIndex && p.type == type,
);
static Future<Book> load() async =>
(await StoryLibrary.load()).open('mara-island');
static Future<Book> loadDefinition(
StoryDefinition definition, {
String language = 'en',
AssetBundle? bundle,
}) async {
final assets = bundle ?? rootBundle;
Future<dynamic> read(String path) async =>
jsonDecode(await assets.loadString(path));
final campaign = Map<String, dynamic>.from(
await read(definition.campaignAsset),
);
final notebook = await read(definition.notebookAsset);
final scripts = definition.scriptsAsset == null
? <dynamic>[]
: await read(definition.scriptsAsset!) as List;
final actualLanguage = definition.languageFor(language);
final locale = definition.languages[actualLanguage] as Map;
final translation = locale['asset'] == null
? <String, dynamic>{}
: Map<String, dynamic>.from(await read(locale['asset']));
final translatedLevels = translation['levels'] as Map? ?? {};
final translatedPages = translation['pages'] as Map? ?? {};
// Translations may only replace presentation fields, never puzzle identity
// or rules. A missing field falls back to the original text.
const levelText = [
'chapter',
'title',
'object',
'before',
'after',
'beforeContinuation',
'afterContinuation',
'illustrationAsset',
];
const pageText = [
'title',
'text',
'speaker',
'continuation',
'caption',
'illustrationAsset',
];
Map<String, dynamic> overlay(
Map<String, dynamic> base,
Map? translated,
List<String> fields,
) => {
...base,
for (final field in fields)
if (translated?[field] is String) field: translated![field],
};
final levels = (campaign['levels'] as List).map((record) {
final base = Map<String, dynamic>.from(record);
base['chapterId'] ??= base['chapter'];
return CampaignLevel(
overlay(base, translatedLevels[base['id']], levelText),
);
}).toList();
final pages = (notebook['pages'] as List).map((record) {
final index = record['campaignIndex'] as int?;
if (index != null && (index < 0 || index >= levels.length)) {
throw FormatException('Unknown puzzle on page ${record['id']}');
}
final text = switch (record['textSource']) {
'before' => levels[index!].before,
'after' => levels[index!].after,
'recording' =>
scripts
.where((s) => s['pageId'] == record['id'])
.map((s) => (s['baseText'] ?? s['text']) as String)
.firstOrNull ??
'',
_ => record['text'] as String? ?? '',
};
final base = <String, dynamic>{
...record,
'text': text,
'continuation':
record['continuation'] ??
switch (record['textSource']) {
'before' => levels[index!].beforeContinuation,
'after' => levels[index!].afterContinuation,
_ => '',
},
};
final page = overlay(base, translatedPages[record['id']], pageText);
return StoryPage(
page['id'],
page['title'],
page['text'],
type: StoryPageType.values.byName(page['type']),
campaignIndex: index,
speaker: page['speaker'] as String? ?? '',
illustrationAsset: page['illustrationAsset'] as String?,
continuation: page['continuation'] as String? ?? '',
caption: page['caption'] as String? ?? '',
);
}).toList();
if (levels.isEmpty ||
pages.isEmpty ||
levels.any(
(l) =>
!RegExp(r'^[a-z0-9._-]+$').hasMatch(l.id) ||
l.size < 2 ||
l.size > 10 ||
l.picture.length != l.size * l.size ||
l.picture.any((v) => v != 0 && v != 1),
) ||
levels.map((l) => l.id).toSet().length != levels.length ||
pages.map((p) => p.id).toSet().length != pages.length ||
pages.any((p) => p.id.isEmpty) ||
definition.continueAt != null &&
(definition.continueAt! < 0 ||
definition.continueAt! >= levels.length) ||
pages.any(
(p) =>
[StoryPageType.puzzle, StoryPageType.memory].contains(p.type) &&
p.campaignIndex == null,
)) {
throw FormatException('Invalid story content: ${definition.id}');
}
final seenChapters = <String>{};
String? lastChapter;
for (final level in levels) {
if (level.chapterId != lastChapter &&
!seenChapters.add(level.chapterId)) {
throw FormatException(
'Chapter levels must be contiguous: ${level.chapterId}',
);
}
lastChapter = level.chapterId;
final puzzle = level.puzzle();
if (puzzle.regions.any(
(r) =>
r.top < 0 ||
r.left < 0 ||
r.width <= 0 ||
r.height <= 0 ||
r.top + r.height > puzzle.size ||
r.left + r.width > puzzle.size,
)) {
throw FormatException('Invalid puzzle region: ${level.id}');
}
}
// Never play original-language narration over translated text. A locale
// supplies its own manifest, or remains readable without a recording.
final trackPath =
locale['tracksAsset'] as String? ??
(actualLanguage == definition.defaultLanguage
? definition.tracksAsset
: null);
final tracks = trackPath == null
? <String, dynamic>{}
: Map<String, dynamic>.from((await read(trackPath))['tracks']);
return Book(
translation['premise'] as String? ?? campaign['premise'],
levels,
pages,
tracks,
id: definition.id,
title: translation['title'] as String? ?? definition.title,
description:
translation['description'] as String? ?? definition.description,
language: actualLanguage,
defaultLanguage: definition.defaultLanguage,
presentation: definition.presentation,
coverAsset: translation['coverAsset'] as String? ?? definition.coverAsset,
continueAt: definition.continueAt,
initiallyAccessible: definition.initiallyAccessible.clamp(
0,
levels.length - 1,
),
fontFamily: locale['fontFamily'] as String?,
copy: Map<String, String>.from(translation['copy'] as Map? ?? {}),
);
}
}