Migrate Lumen to Dart and Flutter 2.0
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'puzzle.dart';
|
||||
|
||||
class CampaignLevel {
|
||||
CampaignLevel(Map<String, dynamic> data)
|
||||
: chapter = data['chapter'],
|
||||
title = data['title'],
|
||||
object = data['object'],
|
||||
before = data['before'],
|
||||
after = data['after'],
|
||||
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 List<int> picture;
|
||||
Puzzle puzzle() {
|
||||
final p = Puzzle(7, picture);
|
||||
if (clues.isNotEmpty) {
|
||||
for (final c in clues.split(',')) {
|
||||
p.given[int.parse(c)] = true;
|
||||
}
|
||||
}
|
||||
if (areas.isNotEmpty) {
|
||||
var i = 0;
|
||||
for (final a in areas.split(';')) {
|
||||
final v = a.split(',').map(int.parse).toList();
|
||||
p.regions.add(
|
||||
Region(String.fromCharCode(65 + i++), v[0], v[1], v[2], v[3]),
|
||||
);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
class StoryPage {
|
||||
const StoryPage(this.id, this.title, this.text);
|
||||
final String id, title, text;
|
||||
}
|
||||
|
||||
class Book {
|
||||
Book(this.premise, this.levels, this.pages, this.tracks);
|
||||
final String premise;
|
||||
final List<CampaignLevel> levels;
|
||||
final List<StoryPage> pages;
|
||||
final Map<String, dynamic> tracks;
|
||||
static Future<Book> load() async {
|
||||
final campaign = jsonDecode(
|
||||
await rootBundle.loadString('assets/campaign.json'),
|
||||
) as Map<String, dynamic>;
|
||||
final scripts = jsonDecode(
|
||||
await rootBundle.loadString('assets/narration/scripts.json'),
|
||||
) as List;
|
||||
final tracks =
|
||||
jsonDecode(
|
||||
await rootBundle.loadString(
|
||||
'assets/audio/narration_manifest.json',
|
||||
),
|
||||
)['tracks']
|
||||
as Map<String, dynamic>;
|
||||
const ids = [
|
||||
'cottage.dedication',
|
||||
'cottage.window',
|
||||
'cottage.match.puzzle',
|
||||
'cottage.match.memory',
|
||||
'cottage.folded.note',
|
||||
'cottage.lantern.sketch',
|
||||
];
|
||||
const titles = [
|
||||
'For you, when you are ready',
|
||||
'By the cottage window',
|
||||
'A spark in the drawer',
|
||||
'One small light',
|
||||
'A note I nearly forgot',
|
||||
'The handle, carefully mended',
|
||||
];
|
||||
return Book(
|
||||
campaign['premise'],
|
||||
(campaign['levels'] as List).map((e) => CampaignLevel(e)).toList(),
|
||||
List.generate(
|
||||
6,
|
||||
(i) => StoryPage(
|
||||
ids[i],
|
||||
titles[i],
|
||||
scripts
|
||||
.where((s) => s['pageId'] == ids[i])
|
||||
.map((s) => s['text'] as String)
|
||||
.firstOrNull ??
|
||||
'',
|
||||
),
|
||||
),
|
||||
tracks,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../services/progress.dart';
|
||||
import 'book.dart';
|
||||
import 'puzzle.dart';
|
||||
|
||||
enum Screen { home, story, contents, briefing, game, reveal }
|
||||
|
||||
enum Mode { daily, classic, campaign }
|
||||
|
||||
Puzzle generatePractice(Map<String, Object> args) => Puzzle.generate(
|
||||
BigInt.parse(args['seed'] as String),
|
||||
Difficulty.fromStored(args['difficulty'] as String),
|
||||
);
|
||||
|
||||
class Game extends ChangeNotifier {
|
||||
Game(this.book, this.progress);
|
||||
final Book book;
|
||||
final Progress progress;
|
||||
Screen screen = Screen.home;
|
||||
Mode mode = Mode.classic;
|
||||
Difficulty get difficulty =>
|
||||
Difficulty.fromStored(progress.text('difficulty', 'EASY'));
|
||||
int storyIndex = 0, campaignIndex = 0, playingLevel = 1, selectedArea = 0;
|
||||
DateTime date = DateTime.now();
|
||||
Puzzle? puzzle;
|
||||
List<int> cells = [];
|
||||
final List<List<int>> _undo = [];
|
||||
String key = '';
|
||||
bool busy = false;
|
||||
int _request = 0;
|
||||
bool get won => progress.flag('done_$key');
|
||||
bool get canUndo => _undo.isNotEmpty && !won;
|
||||
int get solved => progress.number('solved');
|
||||
int get recoveredCount =>
|
||||
List.generate(12, (i) => recovered(i)).where((v) => v).length;
|
||||
int get unlocked => progress.number('campaignUnlocked').clamp(0, 11);
|
||||
int get accessible =>
|
||||
math.max(unlocked, progress.number('story_access_level').clamp(0, 11));
|
||||
int get practiceLevel => progress.number('level_${difficulty.stored}', 1);
|
||||
int get streak => visibleStreak(
|
||||
progress.number('lastDaily', -99999),
|
||||
progress.number('streak'),
|
||||
epochDay(DateTime.now()),
|
||||
);
|
||||
bool recovered(int i) => progress.flag('done_story_v1_$i');
|
||||
Future<void> restore() async {
|
||||
final saved = progress.text('flutter_screen', 'home');
|
||||
campaignIndex = progress.number('flutter_campaign').clamp(0, 11);
|
||||
if (saved == 'story') {
|
||||
showStory(
|
||||
book.pages
|
||||
.indexWhere((p) => p.id == progress.text('notebook_last_page'))
|
||||
.clamp(0, 5),
|
||||
);
|
||||
} else if (saved == 'contents') {
|
||||
contents();
|
||||
} else if (saved == 'briefing') {
|
||||
briefing(campaignIndex);
|
||||
} else if (saved == 'reveal' && recovered(campaignIndex)) {
|
||||
reveal(campaignIndex);
|
||||
} else if (saved == 'game') {
|
||||
final mode = progress.text('flutter_mode');
|
||||
if (mode == 'campaign') {
|
||||
startCampaign(campaignIndex);
|
||||
} else if (mode == 'daily') {
|
||||
startDaily(
|
||||
DateTime.tryParse(progress.text('flutter_date')) ?? DateTime.now(),
|
||||
);
|
||||
} else {
|
||||
await startPractice(progress.number('flutter_level', 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _route(Screen value) {
|
||||
screen = value;
|
||||
unawaited(progress.set('flutter_screen', value.name));
|
||||
unawaited(progress.set('flutter_campaign', campaignIndex));
|
||||
unawaited(progress.set('flutter_mode', mode.name));
|
||||
unawaited(progress.set('flutter_date', date.toIso8601String()));
|
||||
unawaited(progress.set('flutter_level', playingLevel));
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void home() {
|
||||
_request++;
|
||||
busy = false;
|
||||
_route(Screen.home);
|
||||
}
|
||||
|
||||
void openNotebook() {
|
||||
final i = book.pages.indexWhere(
|
||||
(p) => p.id == progress.text('notebook_last_page'),
|
||||
);
|
||||
showStory(i < 0 ? 0 : i);
|
||||
}
|
||||
|
||||
void showStory(int i) {
|
||||
_request++;
|
||||
busy = false;
|
||||
storyIndex = i.clamp(0, 5);
|
||||
mode = Mode.campaign;
|
||||
campaignIndex = 0;
|
||||
if (storyIndex == 2 && key != 'story_v1_0') {
|
||||
_read(book.levels[0].puzzle(), 'story_v1_0');
|
||||
}
|
||||
unawaited(progress.set('notebook_last_page', book.pages[storyIndex].id));
|
||||
unawaited(progress.set('viewed_${book.pages[storyIndex].id}', true));
|
||||
_route(Screen.story);
|
||||
}
|
||||
|
||||
void contents() {
|
||||
_request++;
|
||||
busy = false;
|
||||
_route(Screen.contents);
|
||||
}
|
||||
|
||||
void briefing(int i) {
|
||||
campaignIndex = i.clamp(0, accessible);
|
||||
mode = Mode.campaign;
|
||||
_route(Screen.briefing);
|
||||
}
|
||||
|
||||
void reveal(int i) {
|
||||
if (!recovered(i)) {
|
||||
briefing(i);
|
||||
return;
|
||||
}
|
||||
campaignIndex = i;
|
||||
mode = Mode.campaign;
|
||||
_route(Screen.reveal);
|
||||
}
|
||||
|
||||
void selectDifficulty(Difficulty d) {
|
||||
unawaited(progress.set('difficulty', d.stored));
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void startDaily(DateTime day) {
|
||||
_request++;
|
||||
busy = false;
|
||||
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)}',
|
||||
);
|
||||
_route(Screen.game);
|
||||
}
|
||||
|
||||
Future<void> startPractice([int? level]) async {
|
||||
final request = ++_request;
|
||||
busy = true;
|
||||
notifyListeners();
|
||||
final d = difficulty;
|
||||
final n = level ?? practiceLevel;
|
||||
final p = await compute(generatePractice, {
|
||||
'seed': '${1000000 + n}',
|
||||
'difficulty': d.stored,
|
||||
});
|
||||
if (request != _request) return;
|
||||
busy = false;
|
||||
mode = Mode.classic;
|
||||
playingLevel = n;
|
||||
_read(p, 'v2_${d.stored}_$n');
|
||||
_route(Screen.game);
|
||||
}
|
||||
|
||||
void startCampaign(int i) {
|
||||
_request++;
|
||||
busy = false;
|
||||
if (i > accessible) return;
|
||||
if (recovered(i)) {
|
||||
reveal(i);
|
||||
return;
|
||||
}
|
||||
campaignIndex = i;
|
||||
mode = Mode.campaign;
|
||||
_read(book.levels[i].puzzle(), 'story_v1_$i');
|
||||
_route(Screen.game);
|
||||
}
|
||||
|
||||
void _read(Puzzle p, String id) {
|
||||
puzzle = p;
|
||||
key = id;
|
||||
final saved = progress.text('grid_$id');
|
||||
cells = List.generate(p.solution.length, (i) {
|
||||
if (p.given[i]) return p.solution[i] == 1 ? 1 : 2;
|
||||
final value = saved.length == p.solution.length
|
||||
? int.tryParse(saved[i]) ?? 0
|
||||
: 0;
|
||||
return value >= 0 && value <= 2 ? value : 0;
|
||||
});
|
||||
selectedArea = 0;
|
||||
_undo.clear();
|
||||
_save();
|
||||
}
|
||||
|
||||
void _save() {
|
||||
unawaited(progress.set('grid_$key', cells.join()));
|
||||
}
|
||||
|
||||
void mark(int index) {
|
||||
if (busy || puzzle == null || won || puzzle!.given[index]) return;
|
||||
_undo.add(List<int>.of(cells));
|
||||
cells[index] = (cells[index] + 1) % 3;
|
||||
_save();
|
||||
check();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void undo() {
|
||||
if (!canUndo) return;
|
||||
cells = _undo.removeLast();
|
||||
_save();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void area(int i) {
|
||||
selectedArea = i;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Hint? applyHint() {
|
||||
if (won || puzzle == null) return null;
|
||||
Hint? hint;
|
||||
for (var i = 0; i < cells.length; i++) {
|
||||
if (cells[i] != 0 && cells[i] != (puzzle!.solution[i] == 1 ? 1 : 2)) {
|
||||
hint = Hint(
|
||||
i,
|
||||
puzzle!.solution[i],
|
||||
'An earlier mark conflicts with the clues. Correct it, then continue comparing the totals.',
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
hint ??= LogicSolver(cells.length, puzzle!.constraints).nextHint(
|
||||
cells
|
||||
.map(
|
||||
(v) => v == 0
|
||||
? -1
|
||||
: v == 1
|
||||
? 1
|
||||
: 0,
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
if (hint == null) return null;
|
||||
_undo.add(List<int>.of(cells));
|
||||
cells[hint.cell] = hint.value == 1 ? 1 : 2;
|
||||
_save();
|
||||
notifyListeners();
|
||||
return hint;
|
||||
}
|
||||
|
||||
void check() {
|
||||
if (won || puzzle == null || !puzzle!.solved(cells)) return;
|
||||
unawaited(progress.set('done_$key', true));
|
||||
unawaited(progress.set('solved', solved + 1));
|
||||
if (mode == Mode.daily) {
|
||||
final day = epochDay(date), last = progress.number('lastDaily', -99999);
|
||||
if (day > last) {
|
||||
unawaited(
|
||||
progress.set(
|
||||
'streak',
|
||||
completedStreak(last, progress.number('streak'), day),
|
||||
),
|
||||
);
|
||||
unawaited(progress.set('lastDaily', day));
|
||||
}
|
||||
} else if (mode == Mode.campaign) {
|
||||
unawaited(
|
||||
progress.set(
|
||||
'campaignUnlocked',
|
||||
math.max(unlocked, math.min(11, campaignIndex + 1)),
|
||||
),
|
||||
);
|
||||
if (screen == Screen.story) {
|
||||
showStory(3);
|
||||
} else {
|
||||
reveal(campaignIndex);
|
||||
}
|
||||
} else {
|
||||
unawaited(progress.set('level_${difficulty.stored}', playingLevel + 1));
|
||||
unawaited(
|
||||
progress.set(
|
||||
'practiceCompleted',
|
||||
progress.number('practiceCompleted') + 1,
|
||||
),
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
enum Difficulty {
|
||||
easy('Easy', 'Short deductions. A gentle place to begin.'),
|
||||
medium('Medium', 'Link deductions across rows and columns.'),
|
||||
hard('Hard', 'Follow longer chains to uncover the pattern.');
|
||||
|
||||
const Difficulty(this.label, this.description);
|
||||
final String label, description;
|
||||
String get stored => name.toUpperCase();
|
||||
static Difficulty fromStored(String value) =>
|
||||
values.firstWhere((d) => d.stored == value, orElse: () => easy);
|
||||
static Difficulty fromRounds(int n) => n <= 2
|
||||
? easy
|
||||
: n <= 4
|
||||
? medium
|
||||
: hard;
|
||||
}
|
||||
|
||||
/// Explicit Java-compatible PRNG keeps generated boards stable across platforms.
|
||||
class JavaRandom {
|
||||
JavaRandom(BigInt seed) : _seed = (seed ^ _multiplier) & _mask;
|
||||
static final _multiplier = BigInt.from(0x5DEECE66D);
|
||||
static final _mask = (BigInt.one << 48) - BigInt.one;
|
||||
BigInt _seed;
|
||||
int next(int bits) {
|
||||
_seed = (_seed * _multiplier + BigInt.from(11)) & _mask;
|
||||
return (_seed >> (48 - bits)).toInt();
|
||||
}
|
||||
|
||||
int nextInt(int bound) {
|
||||
if ((bound & -bound) == bound) {
|
||||
return ((BigInt.from(bound) * BigInt.from(next(31))) >> 31).toInt();
|
||||
}
|
||||
while (true) {
|
||||
final bits = next(31), value = bits % bound;
|
||||
if (bits - value + bound - 1 < 0x80000000) return value;
|
||||
}
|
||||
}
|
||||
|
||||
BigInt nextLong() {
|
||||
final high = BigInt.from(next(32)).toSigned(32);
|
||||
final low = BigInt.from(next(32)).toSigned(32);
|
||||
return ((high << 32) + low).toSigned(64);
|
||||
}
|
||||
|
||||
void shuffle<T>(List<T> list) {
|
||||
for (var i = list.length; i > 1; i--) {
|
||||
final j = nextInt(i), old = list[i - 1];
|
||||
list[i - 1] = list[j];
|
||||
list[j] = old;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Region {
|
||||
const Region(this.label, this.top, this.left, this.height, this.width);
|
||||
final String label;
|
||||
final int top, left, height, width;
|
||||
bool contains(int index, int size) =>
|
||||
index ~/ size >= top &&
|
||||
index ~/ size < top + height &&
|
||||
index % size >= left &&
|
||||
index % size < left + width;
|
||||
}
|
||||
|
||||
class Constraint {
|
||||
Constraint(this.cells, this.total, this.name);
|
||||
final List<int> cells;
|
||||
final int total;
|
||||
final String name;
|
||||
}
|
||||
|
||||
class Hint {
|
||||
const Hint(this.cell, this.value, this.explanation);
|
||||
final int cell, value;
|
||||
final String explanation;
|
||||
}
|
||||
|
||||
class Analysis {
|
||||
const Analysis(this.solved, this.areaDeductions, this.cells);
|
||||
final bool solved;
|
||||
final int areaDeductions;
|
||||
final List<int> cells;
|
||||
}
|
||||
|
||||
class LogicSolver {
|
||||
LogicSolver(this.cellCount, this.constraints);
|
||||
final int cellCount;
|
||||
final List<Constraint> constraints;
|
||||
int _need(Constraint c, List<int> known) =>
|
||||
c.total - c.cells.where((i) => known[i] == 1).length;
|
||||
List<int> _unknown(Constraint c, List<int> known) =>
|
||||
c.cells.where((i) => known[i] < 0).toList();
|
||||
int _singles(List<int> known) {
|
||||
var changes = 0;
|
||||
for (final c in constraints) {
|
||||
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;
|
||||
for (final i in unknown) {
|
||||
known[i] = need == 0 ? 0 : 1;
|
||||
changes++;
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
Hint? nextHint(List<int> known) {
|
||||
for (final c in constraints) {
|
||||
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)) {
|
||||
return Hint(
|
||||
unknown.first,
|
||||
need == 0 ? 0 : 1,
|
||||
need == 0
|
||||
? '${c.name} already has all its lights. Every remaining cell in it must be crossed out.'
|
||||
: '${c.name} needs $need more lights and has exactly ${unknown.length} empty cells. They must all be lit.',
|
||||
);
|
||||
}
|
||||
}
|
||||
for (var a = 0; a < constraints.length; a++) {
|
||||
final first = constraints[a];
|
||||
for (var b = a + 1; b < constraints.length; b++) {
|
||||
final second = constraints[b];
|
||||
final onlyA = _unknown(
|
||||
first,
|
||||
known,
|
||||
).where((i) => !second.cells.contains(i)).toList();
|
||||
final onlyB = _unknown(
|
||||
second,
|
||||
known,
|
||||
).where((i) => !first.cells.contains(i)).toList();
|
||||
final needA = _need(first, known),
|
||||
needB = _need(second, known),
|
||||
diff = needA - needB;
|
||||
if (onlyA.isEmpty && onlyB.isEmpty ||
|
||||
(diff != onlyA.length && diff != -onlyB.length)) {
|
||||
continue;
|
||||
}
|
||||
final valueA = diff == onlyA.length ? 1 : 0;
|
||||
final explanation =
|
||||
'Compare ${first.name} ($needA more lights) with ${second.name} ($needB more). Shared empty cells cancel. The difference forces the cells outside their overlap.';
|
||||
return onlyA.isNotEmpty
|
||||
? Hint(onlyA.first, valueA, explanation)
|
||||
: Hint(onlyB.first, 1 - valueA, explanation);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Analysis analyze(List<int> initial, {bool useAreas = true}) {
|
||||
final known = List<int>.of(initial);
|
||||
var areas = 0;
|
||||
while (true) {
|
||||
final changed = _singles(known);
|
||||
if (changed < 0) return Analysis(false, areas, known);
|
||||
if (changed > 0) continue;
|
||||
if (useAreas) {
|
||||
final hint = nextHint(known);
|
||||
if (hint != null) {
|
||||
known[hint.cell] = hint.value;
|
||||
areas++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return Analysis(!known.contains(-1), areas, known);
|
||||
}
|
||||
}
|
||||
|
||||
int countSolutions(List<int> initial) {
|
||||
int search(List<int> known) {
|
||||
int changed;
|
||||
do {
|
||||
changed = _singles(known);
|
||||
if (changed < 0) return 0;
|
||||
} while (changed > 0);
|
||||
var choice = -1, degree = -1;
|
||||
for (var i = 0; i < cellCount; i++) {
|
||||
if (known[i] >= 0) continue;
|
||||
final d = constraints.where((c) => c.cells.contains(i)).length;
|
||||
if (d > degree) {
|
||||
choice = i;
|
||||
degree = d;
|
||||
}
|
||||
}
|
||||
if (choice < 0) return 1;
|
||||
final branch = List<int>.of(known)..[choice] = 0;
|
||||
final count = search(branch);
|
||||
if (count >= 2) return 2;
|
||||
known[choice] = 1;
|
||||
return math.min(2, count + search(known));
|
||||
}
|
||||
|
||||
return search(List<int>.of(initial));
|
||||
}
|
||||
}
|
||||
|
||||
class Puzzle {
|
||||
Puzzle(this.size, List<int> picture)
|
||||
: solution = List<int>.of(picture),
|
||||
given = List<bool>.filled(size * size, false) {
|
||||
if (picture.length != size * size || picture.any((v) => v != 0 && v != 1)) {
|
||||
throw ArgumentError('Invalid picture');
|
||||
}
|
||||
}
|
||||
final int size;
|
||||
final List<int> solution;
|
||||
final List<bool> given;
|
||||
final List<Region> regions = [];
|
||||
List<int> get rows => List.generate(
|
||||
size,
|
||||
(r) => List.generate(
|
||||
size,
|
||||
(c) => solution[r * size + c],
|
||||
).reduce((a, b) => a + b),
|
||||
);
|
||||
List<int> get cols => List.generate(
|
||||
size,
|
||||
(c) => List.generate(
|
||||
size,
|
||||
(r) => solution[r * size + c],
|
||||
).reduce((a, b) => a + b),
|
||||
);
|
||||
int regionTotal(Region r) => List.generate(
|
||||
solution.length,
|
||||
(i) => r.contains(i, size) ? solution[i] : 0,
|
||||
).reduce((a, b) => a + b);
|
||||
List<Constraint> get constraints => [
|
||||
for (var l = 0; l < size; l++) ...[
|
||||
Constraint(
|
||||
List.generate(size, (p) => l * size + p),
|
||||
rows[l],
|
||||
'Row ${l + 1}',
|
||||
),
|
||||
Constraint(
|
||||
List.generate(size, (p) => p * size + l),
|
||||
cols[l],
|
||||
'Column ${l + 1}',
|
||||
),
|
||||
],
|
||||
for (final r in regions)
|
||||
Constraint(
|
||||
[
|
||||
for (var y = r.top; y < r.top + r.height; y++)
|
||||
for (var x = r.left; x < r.left + r.width; x++) y * size + x,
|
||||
],
|
||||
regionTotal(r),
|
||||
'Area ${r.label}',
|
||||
),
|
||||
];
|
||||
List<int> get initial =>
|
||||
List.generate(solution.length, (i) => given[i] ? solution[i] : -1);
|
||||
factory Puzzle.seeded(BigInt seed) {
|
||||
final random = JavaRandom(seed);
|
||||
final puzzle = Puzzle(5, List.generate(25, (_) => random.next(1)));
|
||||
final order = List.generate(25, (i) => i);
|
||||
random.shuffle(order);
|
||||
for (final i in order) {
|
||||
if (puzzle.countSolutions() == 1) break;
|
||||
puzzle.given[i] = true;
|
||||
}
|
||||
return puzzle;
|
||||
}
|
||||
static Puzzle generate(BigInt seed, Difficulty difficulty) {
|
||||
final random = JavaRandom(seed);
|
||||
for (var i = 0; i < 256; i++) {
|
||||
final p = Puzzle.seeded(random.nextLong());
|
||||
if (difficulty != Difficulty.easy) p._removeRedundant();
|
||||
if (p.difficulty == difficulty) return p;
|
||||
}
|
||||
final p = Puzzle.seeded(BigInt.from(difficulty == Difficulty.hard ? 2 : 0));
|
||||
if (difficulty != Difficulty.easy) p._removeRedundant();
|
||||
final r = List.generate(5, (i) => i), c = List.generate(5, (i) => i);
|
||||
random.shuffle(r);
|
||||
random.shuffle(c);
|
||||
final old = List<int>.of(p.solution), g = List<bool>.of(p.given);
|
||||
for (var i = 0; i < 25; i++) {
|
||||
final from = r[i ~/ 5] * 5 + c[i % 5];
|
||||
p.solution[i] = old[from];
|
||||
p.given[i] = g[from];
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
void _removeRedundant() {
|
||||
for (var i = 0; i < 25; i++) {
|
||||
if (!given[i]) continue;
|
||||
given[i] = false;
|
||||
if (countSolutions() != 1) given[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
int countSolutions() {
|
||||
if (size != 5 || regions.isNotEmpty) {
|
||||
return LogicSolver(solution.length, constraints).countSolutions(initial);
|
||||
}
|
||||
final rs = rows, cs = cols;
|
||||
int search(int row, List<int> totals) {
|
||||
if (row == 5) {
|
||||
return List.generate(5, (i) => totals[i] == cs[i]).every((v) => v)
|
||||
? 1
|
||||
: 0;
|
||||
}
|
||||
var count = 0;
|
||||
for (var mask = 0; mask < 32; mask++) {
|
||||
var bits = 0;
|
||||
for (var c = 0; c < 5; c++) {
|
||||
bits += (mask >> c) & 1;
|
||||
}
|
||||
if (bits != rs[row]) continue;
|
||||
final next = List<int>.of(totals);
|
||||
var ok = true;
|
||||
for (var c = 0; c < 5; c++) {
|
||||
final v = (mask >> c) & 1, i = row * 5 + c;
|
||||
next[c] += v;
|
||||
if (given[i] && solution[i] != v ||
|
||||
next[c] > cs[c] ||
|
||||
next[c] + 4 - row < cs[c]) {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
if (ok) count += search(row + 1, next);
|
||||
if (count >= 2) return 2;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
return search(0, List.filled(5, 0));
|
||||
}
|
||||
|
||||
int get deductionRounds {
|
||||
var known = initial;
|
||||
var rounds = 0;
|
||||
final lines = constraints;
|
||||
while (known.contains(-1)) {
|
||||
final next = List<int>.of(known);
|
||||
var changed = false;
|
||||
for (final c in lines) {
|
||||
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)) {
|
||||
for (final i in unknown) {
|
||||
next[i] = need == 0 ? 0 : 1;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!changed) throw StateError('Puzzle requires guessing');
|
||||
known = next;
|
||||
rounds++;
|
||||
}
|
||||
return rounds;
|
||||
}
|
||||
|
||||
Difficulty get difficulty => Difficulty.fromRounds(deductionRounds);
|
||||
bool solved(List<int> cells) =>
|
||||
cells.length == solution.length &&
|
||||
List.generate(
|
||||
cells.length,
|
||||
(i) => cells[i] == (solution[i] == 1 ? 1 : 2),
|
||||
).every((v) => v);
|
||||
}
|
||||
|
||||
int epochDay(DateTime date) =>
|
||||
DateTime.utc(date.year, date.month, date.day).millisecondsSinceEpoch ~/
|
||||
Duration.millisecondsPerDay;
|
||||
int visibleStreak(int last, int count, int today) =>
|
||||
last >= today - 1 ? count : 0;
|
||||
int completedStreak(int last, int count, int day) => day <= last
|
||||
? count
|
||||
: last == day - 1
|
||||
? count + 1
|
||||
: 1;
|
||||
Reference in New Issue
Block a user