Wire season flow: map screen, progress save, win recording, next stage
SaveRepository (versioned JSON over prefs) with best-result merging and unlock walking; ContentRepository loads the bundled pack; SeasonFlow/ Progress notifiers orchestrate stage start -> win record -> advance. Season map grid with stars/locks, Home -> Map -> Game navigation, close button, next-stage action on the win overlay. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../game/models/season.dart';
|
||||
|
||||
/// Resolves season content. Phase 3: bundled assets only; remote download
|
||||
/// and caching land in Phase 4.
|
||||
class ContentRepository {
|
||||
static const bundledSeasonIds = ['season_001'];
|
||||
|
||||
Future<SeasonPack> loadBundledSeason(String seasonId) async {
|
||||
final raw =
|
||||
await rootBundle.loadString('assets/seasons/$seasonId/pack.json');
|
||||
return SeasonPack.fromJson(jsonDecode(raw) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<List<SeasonPack>> availableSeasons() async => [
|
||||
for (final id in bundledSeasonIds) await loadBundledSeason(id),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class StageProgress {
|
||||
const StageProgress({required this.stars, required this.bestScore});
|
||||
|
||||
final int stars;
|
||||
final int bestScore;
|
||||
}
|
||||
|
||||
/// Versioned JSON-over-prefs persistence for progress. Total payload stays
|
||||
/// tiny (<100 KB), so a key-value blob beats a database here.
|
||||
class SaveRepository {
|
||||
SaveRepository(this._prefs) {
|
||||
final raw = _prefs.getString(_key);
|
||||
if (raw != null) {
|
||||
final json = jsonDecode(raw) as Map<String, dynamic>;
|
||||
final progress = json['progress'] as Map<String, dynamic>? ?? {};
|
||||
for (final entry in progress.entries) {
|
||||
final value = entry.value as Map<String, dynamic>;
|
||||
_progress[entry.key] = StageProgress(
|
||||
stars: value['stars'] as int,
|
||||
bestScore: value['bestScore'] as int,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static const _key = 'save_v1';
|
||||
|
||||
static Future<SaveRepository> open() async =>
|
||||
SaveRepository(await SharedPreferences.getInstance());
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
final Map<String, StageProgress> _progress = {};
|
||||
|
||||
static String _id(String seasonId, String stageId) => '$seasonId/$stageId';
|
||||
|
||||
/// Immutable copy of all progress, keyed `seasonId/stageId`.
|
||||
Map<String, StageProgress> snapshot() => Map.unmodifiable(_progress);
|
||||
|
||||
StageProgress? progressFor(String seasonId, String stageId) =>
|
||||
_progress[_id(seasonId, stageId)];
|
||||
|
||||
Future<void> recordResult({
|
||||
required String seasonId,
|
||||
required String stageId,
|
||||
required int stars,
|
||||
required int score,
|
||||
}) async {
|
||||
final id = _id(seasonId, stageId);
|
||||
final old = _progress[id];
|
||||
_progress[id] = StageProgress(
|
||||
stars: old == null || stars > old.stars ? stars : old.stars,
|
||||
bestScore:
|
||||
old == null || score > old.bestScore ? score : old.bestScore,
|
||||
);
|
||||
await _flush();
|
||||
}
|
||||
|
||||
int totalStars(String seasonId) {
|
||||
var total = 0;
|
||||
for (final entry in _progress.entries) {
|
||||
if (entry.key.startsWith('$seasonId/')) total += entry.value.stars;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/// Index of the furthest playable stage: the first without a star, or the
|
||||
/// last stage when everything is starred.
|
||||
int highestUnlockedIndex(String seasonId, List<String> stageIds) {
|
||||
for (var i = 0; i < stageIds.length; i++) {
|
||||
final progress = progressFor(seasonId, stageIds[i]);
|
||||
if (progress == null || progress.stars == 0) return i;
|
||||
}
|
||||
return stageIds.length - 1;
|
||||
}
|
||||
|
||||
Future<void> _flush() => _prefs.setString(
|
||||
_key,
|
||||
jsonEncode({
|
||||
'saveVersion': 1,
|
||||
'progress': {
|
||||
for (final entry in _progress.entries)
|
||||
entry.key: {
|
||||
'stars': entry.value.stars,
|
||||
'bestScore': entry.value.bestScore,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
+2
-1
@@ -11,5 +11,6 @@
|
||||
"watchAdContinue": "Continue (ad)",
|
||||
"plusFiveMoves": "+5 moves (ad)",
|
||||
"giveUp": "Give up",
|
||||
"playAgain": "Play again"
|
||||
"playAgain": "Play again",
|
||||
"nextStage": "Next stage"
|
||||
}
|
||||
|
||||
+2
-1
@@ -11,5 +11,6 @@
|
||||
"watchAdContinue": "광고 보고 이어하기",
|
||||
"plusFiveMoves": "+5 이동 (광고)",
|
||||
"giveUp": "포기하기",
|
||||
"playAgain": "다시 하기"
|
||||
"playAgain": "다시 하기",
|
||||
"nextStage": "다음 스테이지"
|
||||
}
|
||||
|
||||
+10
-2
@@ -2,8 +2,16 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'app.dart';
|
||||
import 'data/save_repository.dart';
|
||||
import 'state/providers.dart';
|
||||
|
||||
void main() {
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
runApp(const ProviderScope(child: BlockSeasonsApp()));
|
||||
final saveRepository = await SaveRepository.open();
|
||||
runApp(
|
||||
ProviderScope(
|
||||
overrides: [saveRepositoryProvider.overrideWithValue(saveRepository)],
|
||||
child: const BlockSeasonsApp(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../data/save_repository.dart';
|
||||
import 'providers.dart';
|
||||
|
||||
/// Exposes saved progress as immutable state so screens rebuild when stars
|
||||
/// land; persistence goes through [SaveRepository].
|
||||
class ProgressNotifier extends Notifier<Map<String, StageProgress>> {
|
||||
@override
|
||||
Map<String, StageProgress> build() =>
|
||||
ref.read(saveRepositoryProvider).snapshot();
|
||||
|
||||
Future<void> record({
|
||||
required String seasonId,
|
||||
required String stageId,
|
||||
required int stars,
|
||||
required int score,
|
||||
}) async {
|
||||
final repo = ref.read(saveRepositoryProvider);
|
||||
await repo.recordResult(
|
||||
seasonId: seasonId,
|
||||
stageId: stageId,
|
||||
stars: stars,
|
||||
score: score,
|
||||
);
|
||||
state = repo.snapshot();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../data/content_repository.dart';
|
||||
import '../data/save_repository.dart';
|
||||
import '../game/models/season.dart';
|
||||
import '../services/audio_service.dart';
|
||||
import 'game_session_notifier.dart';
|
||||
import 'progress_notifier.dart';
|
||||
import 'season_flow_notifier.dart';
|
||||
|
||||
final gameSessionProvider =
|
||||
NotifierProvider<GameSessionNotifier, GameViewState?>(
|
||||
@@ -13,3 +18,24 @@ final audioServiceProvider = Provider<AudioService>((ref) {
|
||||
ref.onDispose(service.dispose);
|
||||
return service;
|
||||
});
|
||||
|
||||
/// Overridden with the opened repository in main() (and in tests).
|
||||
final saveRepositoryProvider = Provider<SaveRepository>(
|
||||
(ref) => throw UnimplementedError('override with an opened SaveRepository'),
|
||||
);
|
||||
|
||||
final progressProvider =
|
||||
NotifierProvider<ProgressNotifier, Map<String, StageProgress>>(
|
||||
ProgressNotifier.new,
|
||||
);
|
||||
|
||||
final seasonFlowProvider = NotifierProvider<SeasonFlowNotifier, SeasonFlow?>(
|
||||
SeasonFlowNotifier.new,
|
||||
);
|
||||
|
||||
final contentRepositoryProvider =
|
||||
Provider<ContentRepository>((ref) => ContentRepository());
|
||||
|
||||
final seasonsProvider = FutureProvider<List<SeasonPack>>(
|
||||
(ref) => ref.read(contentRepositoryProvider).availableSeasons(),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../game/models/season.dart';
|
||||
import '../game/models/stage.dart';
|
||||
import 'providers.dart';
|
||||
|
||||
class SeasonFlow {
|
||||
const SeasonFlow({required this.pack, required this.index});
|
||||
|
||||
final SeasonPack pack;
|
||||
final int index;
|
||||
|
||||
StageConfig get stage => pack.stages[index];
|
||||
bool get hasNext => index + 1 < pack.stages.length;
|
||||
}
|
||||
|
||||
/// Orchestrates which season stage is being played: starting stages,
|
||||
/// recording wins, advancing to the next stage.
|
||||
class SeasonFlowNotifier extends Notifier<SeasonFlow?> {
|
||||
@override
|
||||
SeasonFlow? build() => null;
|
||||
|
||||
void startSeasonStage(SeasonPack pack, int index) {
|
||||
state = SeasonFlow(pack: pack, index: index);
|
||||
ref.read(gameSessionProvider.notifier).startStage(pack.stages[index]);
|
||||
}
|
||||
|
||||
Future<void> recordWin({required int stars, required int score}) async {
|
||||
final flow = state;
|
||||
if (flow == null) return;
|
||||
await ref.read(progressProvider.notifier).record(
|
||||
seasonId: flow.pack.seasonId,
|
||||
stageId: flow.stage.id,
|
||||
stars: stars,
|
||||
score: score,
|
||||
);
|
||||
}
|
||||
|
||||
void nextStage() {
|
||||
final flow = state;
|
||||
if (flow == null || !flow.hasNext) return;
|
||||
startSeasonStage(flow.pack, flow.index + 1);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../game/engine/game_engine.dart';
|
||||
import '../../game/models/stage.dart';
|
||||
import '../../l10n/gen/app_localizations.dart';
|
||||
import '../../services/audio_service.dart';
|
||||
import '../../state/game_session_notifier.dart';
|
||||
@@ -15,29 +14,8 @@ import '../widgets/hud_widget.dart';
|
||||
import '../widgets/piece_painter.dart';
|
||||
import '../widgets/tray_widget.dart';
|
||||
|
||||
/// Demo stage until the season map lands in Phase 3.
|
||||
final _demoStage = StageConfig.fromJson({
|
||||
'id': 'demo_001',
|
||||
'seed': 20260611,
|
||||
'moveLimit': 25,
|
||||
'preset': [
|
||||
{'x': 2, 'y': 2, 't': 'gem'},
|
||||
{'x': 5, 'y': 2, 't': 'gem'},
|
||||
{'x': 2, 'y': 5, 't': 'gem'},
|
||||
{'x': 5, 'y': 5, 't': 'gem'},
|
||||
{'x': 3, 'y': 7, 't': 'filled', 'c': 1},
|
||||
{'x': 4, 'y': 7, 't': 'filled', 'c': 1},
|
||||
],
|
||||
'objectives': [
|
||||
{'type': 'clearGems', 'count': 4},
|
||||
],
|
||||
'stars': {
|
||||
'two': {'movesLeft': 6},
|
||||
'three': {'movesLeft': 12},
|
||||
},
|
||||
'generatorProfile': 'mid',
|
||||
});
|
||||
|
||||
/// Renders whatever session [gameSessionProvider] holds; callers start the
|
||||
/// stage (via SeasonFlowNotifier) before navigating here.
|
||||
class GameScreen extends ConsumerStatefulWidget {
|
||||
const GameScreen({super.key});
|
||||
|
||||
@@ -55,16 +33,6 @@ class _GameScreenState extends ConsumerState<GameScreen> {
|
||||
/// How far the dragged piece floats above the finger so it stays visible.
|
||||
static const double _lift = 70;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (ref.read(gameSessionProvider) == null) {
|
||||
ref.read(gameSessionProvider.notifier).startStage(_demoStage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
RenderBox? get _boardBox =>
|
||||
_boardKey.currentContext?.findRenderObject() as RenderBox?;
|
||||
|
||||
@@ -125,7 +93,7 @@ class _GameScreenState extends ConsumerState<GameScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
void _playSfx(GameViewState? prev, GameViewState? next) {
|
||||
void _onSessionChange(GameViewState? prev, GameViewState? next) {
|
||||
if (next == null) return;
|
||||
final audio = ref.read(audioServiceProvider);
|
||||
if (prev?.fxTick != next.fxTick && next.lastPlacement != null) {
|
||||
@@ -137,14 +105,20 @@ class _GameScreenState extends ConsumerState<GameScreen> {
|
||||
}
|
||||
}
|
||||
if (prev?.phase != next.phase) {
|
||||
if (next.phase == GamePhase.won) audio.play(Sfx.win);
|
||||
if (next.phase == GamePhase.won) {
|
||||
audio.play(Sfx.win);
|
||||
// recordResult keeps the best run, so re-entry is harmless.
|
||||
ref
|
||||
.read(seasonFlowProvider.notifier)
|
||||
.recordWin(stars: next.starsEarned, score: next.score);
|
||||
}
|
||||
if (next.phase == GamePhase.lost) audio.play(Sfx.lose);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.listen<GameViewState?>(gameSessionProvider, _playSfx);
|
||||
ref.listen<GameViewState?>(gameSessionProvider, _onSessionChange);
|
||||
final view = ref.watch(gameSessionProvider);
|
||||
if (view == null) {
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
@@ -193,6 +167,15 @@ class _GameScreenState extends ConsumerState<GameScreen> {
|
||||
_dragIndex! < view.tray.length)
|
||||
_draggedPieceOverlay(view, draggedTopLeft, boardBox),
|
||||
if (view.phase != GamePhase.playing) _resultOverlay(view),
|
||||
if (Navigator.of(context).canPop())
|
||||
Positioned(
|
||||
top: 4,
|
||||
left: 4,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.close, color: Colors.white54),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -219,11 +202,18 @@ class _GameScreenState extends ConsumerState<GameScreen> {
|
||||
final notifier = ref.read(gameSessionProvider.notifier);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final flow = ref.read(seasonFlowProvider);
|
||||
final (title, actions) = switch ((view.phase, view.stuckReason)) {
|
||||
(GamePhase.won, _) => (
|
||||
l10n.stageClear,
|
||||
[
|
||||
FilledButton(
|
||||
if (flow != null && flow.hasNext)
|
||||
FilledButton(
|
||||
onPressed:
|
||||
ref.read(seasonFlowProvider.notifier).nextStage,
|
||||
child: Text(l10n.nextStage),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: notifier.restart,
|
||||
child: Text(l10n.playAgain),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/gen/app_localizations.dart';
|
||||
import 'game_screen.dart';
|
||||
import 'season_map_screen.dart';
|
||||
|
||||
class HomeScreen extends StatelessWidget {
|
||||
const HomeScreen({super.key});
|
||||
@@ -33,7 +33,7 @@ class HomeScreen extends StatelessWidget {
|
||||
onPressed: () {
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => const GameScreen(),
|
||||
builder: (_) => const SeasonMapScreen(),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../game/models/season.dart';
|
||||
import '../../state/providers.dart';
|
||||
import '../theme/palette.dart';
|
||||
import 'game_screen.dart';
|
||||
|
||||
/// Stage selection for the active season. Themed map art lands in Phase 6;
|
||||
/// for now a clean node grid with stars and locks.
|
||||
class SeasonMapScreen extends ConsumerWidget {
|
||||
const SeasonMapScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final seasons = ref.watch(seasonsProvider);
|
||||
return seasons.when(
|
||||
loading: () =>
|
||||
const Scaffold(body: Center(child: CircularProgressIndicator())),
|
||||
error: (e, _) => Scaffold(body: Center(child: Text('$e'))),
|
||||
data: (list) => _Map(pack: list.first),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Map extends ConsumerWidget {
|
||||
const _Map({required this.pack});
|
||||
|
||||
final SeasonPack pack;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
// Watching progress keeps stars/locks fresh after each win.
|
||||
ref.watch(progressProvider);
|
||||
final repo = ref.read(saveRepositoryProvider);
|
||||
final ids = [for (final stage in pack.stages) stage.id];
|
||||
final unlocked = repo.highestUnlockedIndex(pack.seasonId, ids);
|
||||
final totalStars = repo.totalStars(pack.seasonId);
|
||||
final locale = Localizations.localeOf(context).languageCode;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(pack.titleFor(locale)),
|
||||
actions: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 16),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'★ $totalStars/${pack.stages.length * 3}',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleMedium
|
||||
?.copyWith(color: Colors.amber),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: GridView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 4,
|
||||
mainAxisSpacing: 12,
|
||||
crossAxisSpacing: 12,
|
||||
),
|
||||
itemCount: pack.stages.length,
|
||||
itemBuilder: (context, i) {
|
||||
final progress = repo.progressFor(pack.seasonId, ids[i]);
|
||||
final isUnlocked = i <= unlocked;
|
||||
return _StageNode(
|
||||
number: i + 1,
|
||||
stars: progress?.stars ?? 0,
|
||||
unlocked: isUnlocked,
|
||||
onTap: !isUnlocked
|
||||
? null
|
||||
: () {
|
||||
ref
|
||||
.read(seasonFlowProvider.notifier)
|
||||
.startSeasonStage(pack, i);
|
||||
Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const GameScreen()),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StageNode extends StatelessWidget {
|
||||
const _StageNode({
|
||||
required this.number,
|
||||
required this.stars,
|
||||
required this.unlocked,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final int number;
|
||||
final int stars;
|
||||
final bool unlocked;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Material(
|
||||
color: unlocked ? GamePalette.emptyCell : GamePalette.boardBackground,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
onTap: onTap,
|
||||
child: unlocked
|
||||
? Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
'$number',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleLarge
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
for (var s = 0; s < 3; s++)
|
||||
Icon(
|
||||
Icons.star,
|
||||
size: 14,
|
||||
color: s < stars ? Colors.amber : Colors.white24,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
: const Center(
|
||||
child: Icon(Icons.lock, color: Colors.white24, size: 22),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ flutter:
|
||||
|
||||
assets:
|
||||
- assets/audio/
|
||||
- assets/seasons/season_001/
|
||||
|
||||
# To add assets to your application, add an assets section, like this:
|
||||
# assets:
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import 'package:block_seasons/data/content_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test('loads the bundled Season 1 pack with 60 calibrated stages', () async {
|
||||
final repo = ContentRepository();
|
||||
final pack = await repo.loadBundledSeason('season_001');
|
||||
expect(pack.seasonId, 'season_001');
|
||||
expect(pack.stages, hasLength(60));
|
||||
expect(pack.titleFor('ko'), '첫 개화');
|
||||
|
||||
// Sanity: every stage has a positive budget and at least one objective.
|
||||
for (final stage in pack.stages) {
|
||||
expect(stage.moveLimit, greaterThan(0), reason: stage.id);
|
||||
expect(stage.objectives, isNotEmpty, reason: stage.id);
|
||||
expect(stage.stars.threeMovesLeft, greaterThan(stage.stars.twoMovesLeft),
|
||||
reason: stage.id);
|
||||
}
|
||||
});
|
||||
|
||||
test('availableSeasons returns the bundled season', () async {
|
||||
final repo = ContentRepository();
|
||||
final seasons = await repo.availableSeasons();
|
||||
expect(seasons.map((s) => s.seasonId), contains('season_001'));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'package:block_seasons/data/save_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
Future<SaveRepository> freshRepo() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
return SaveRepository(await SharedPreferences.getInstance());
|
||||
}
|
||||
|
||||
test('starts empty: no progress, zero stars, first stage unlocked', () async {
|
||||
final repo = await freshRepo();
|
||||
expect(repo.progressFor('season_001', 's1'), isNull);
|
||||
expect(repo.totalStars('season_001'), 0);
|
||||
expect(repo.highestUnlockedIndex('season_001', ['s1', 's2', 's3']), 0);
|
||||
});
|
||||
|
||||
test('records results and keeps the best', () async {
|
||||
final repo = await freshRepo();
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's1', stars: 2, score: 500);
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's1', stars: 1, score: 900);
|
||||
final progress = repo.progressFor('season_001', 's1')!;
|
||||
expect(progress.stars, 2, reason: 'stars never downgrade');
|
||||
expect(progress.bestScore, 900, reason: 'best score upgrades');
|
||||
});
|
||||
|
||||
test('unlock walks forward through starred stages', () async {
|
||||
final repo = await freshRepo();
|
||||
final ids = ['s1', 's2', 's3', 's4'];
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's1', stars: 1, score: 100);
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's2', stars: 3, score: 300);
|
||||
expect(repo.highestUnlockedIndex('season_001', ids), 2);
|
||||
// Completing the last stage caps the index at the end of the list.
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's3', stars: 1, score: 1);
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's4', stars: 1, score: 1);
|
||||
expect(repo.highestUnlockedIndex('season_001', ids), 3);
|
||||
});
|
||||
|
||||
test('totals stars per season independently', () async {
|
||||
final repo = await freshRepo();
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's1', stars: 2, score: 1);
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001', stageId: 's2', stars: 3, score: 1);
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_002', stageId: 's1', stars: 1, score: 1);
|
||||
expect(repo.totalStars('season_001'), 5);
|
||||
expect(repo.totalStars('season_002'), 1);
|
||||
});
|
||||
|
||||
test('persists across repository instances', () async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final first = SaveRepository(prefs);
|
||||
await first.recordResult(
|
||||
seasonId: 'season_001', stageId: 's1', stars: 3, score: 777);
|
||||
|
||||
final second = SaveRepository(prefs);
|
||||
expect(second.progressFor('season_001', 's1')!.stars, 3);
|
||||
expect(second.progressFor('season_001', 's1')!.bestScore, 777);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'package:block_seasons/data/save_repository.dart';
|
||||
import 'package:block_seasons/game/engine/game_engine.dart';
|
||||
import 'package:block_seasons/game/models/season.dart';
|
||||
import 'package:block_seasons/state/providers.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
SeasonPack _pack() => SeasonPack.fromJson({
|
||||
'schemaVersion': 1,
|
||||
'seasonId': 'season_test',
|
||||
'version': 1,
|
||||
'title': {'en': 'T', 'ko': 'T'},
|
||||
'theme': {'tileSet': 'spring', 'background': 'bg.webp'},
|
||||
'stages': [
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
'id': 'st_$i',
|
||||
'seed': 100 + i,
|
||||
'moveLimit': 20,
|
||||
'preset': const <Map<String, dynamic>>[],
|
||||
'objectives': [
|
||||
{'type': 'reachScore', 'target': 999999},
|
||||
],
|
||||
'stars': {
|
||||
'two': {'movesLeft': 5},
|
||||
'three': {'movesLeft': 10},
|
||||
},
|
||||
'generatorProfile': 'mid',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Future<ProviderContainer> _container() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final repo = SaveRepository(await SharedPreferences.getInstance());
|
||||
final container = ProviderContainer(
|
||||
overrides: [saveRepositoryProvider.overrideWithValue(repo)],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
return container;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test('starting a season stage spins up the game session', () async {
|
||||
final container = await _container();
|
||||
final flow = container.read(seasonFlowProvider.notifier);
|
||||
flow.startSeasonStage(_pack(), 0);
|
||||
|
||||
expect(container.read(seasonFlowProvider)!.index, 0);
|
||||
expect(container.read(seasonFlowProvider)!.hasNext, isTrue);
|
||||
final session = container.read(gameSessionProvider)!;
|
||||
expect(session.phase, GamePhase.playing);
|
||||
expect(session.movesLeft, 20);
|
||||
});
|
||||
|
||||
test('recordWin persists stars through the progress notifier', () async {
|
||||
final container = await _container();
|
||||
final flow = container.read(seasonFlowProvider.notifier);
|
||||
flow.startSeasonStage(_pack(), 1);
|
||||
await flow.recordWin(stars: 3, score: 1234);
|
||||
|
||||
final repo = container.read(saveRepositoryProvider);
|
||||
expect(repo.progressFor('season_test', 'st_1')!.stars, 3);
|
||||
expect(container.read(progressProvider)['season_test/st_1']!.stars, 3);
|
||||
});
|
||||
|
||||
test('nextStage advances and starts the following stage', () async {
|
||||
final container = await _container();
|
||||
final flow = container.read(seasonFlowProvider.notifier);
|
||||
flow.startSeasonStage(_pack(), 1);
|
||||
flow.nextStage();
|
||||
|
||||
expect(container.read(seasonFlowProvider)!.index, 2);
|
||||
expect(container.read(seasonFlowProvider)!.hasNext, isFalse);
|
||||
expect(container.read(gameSessionProvider)!.phase, GamePhase.playing);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import 'package:block_seasons/data/save_repository.dart';
|
||||
import 'package:block_seasons/game/engine/game_engine.dart';
|
||||
import 'package:block_seasons/game/models/season.dart';
|
||||
import 'package:block_seasons/l10n/gen/app_localizations.dart';
|
||||
import 'package:block_seasons/state/providers.dart';
|
||||
import 'package:block_seasons/ui/screens/game_screen.dart';
|
||||
import 'package:block_seasons/ui/screens/season_map_screen.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
// The real 60-stage bundled pack is covered by the content repository
|
||||
// tests; the widget test uses a small pack because the bundled one is big
|
||||
// enough that loadString decodes on an isolate, which fake-async test time
|
||||
// never completes.
|
||||
SeasonPack _pack() => SeasonPack.fromJson({
|
||||
'schemaVersion': 1,
|
||||
'seasonId': 'season_001',
|
||||
'version': 1,
|
||||
'title': {'en': 'First Bloom', 'ko': '첫 개화'},
|
||||
'theme': {'tileSet': 'spring', 'background': 'bg.webp'},
|
||||
'stages': [
|
||||
for (var i = 1; i <= 3; i++)
|
||||
{
|
||||
'id': 'season_001_00$i',
|
||||
'seed': 100 + i,
|
||||
'moveLimit': 20,
|
||||
'preset': const <Map<String, dynamic>>[],
|
||||
'objectives': [
|
||||
{'type': 'reachScore', 'target': 999999},
|
||||
],
|
||||
'stars': {
|
||||
'two': {'movesLeft': 5},
|
||||
'three': {'movesLeft': 10},
|
||||
},
|
||||
'generatorProfile': 'mid',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
void main() {
|
||||
testWidgets('map shows stars, locks ahead, and starts unlocked stages',
|
||||
(tester) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final repo = SaveRepository(await SharedPreferences.getInstance());
|
||||
await repo.recordResult(
|
||||
seasonId: 'season_001',
|
||||
stageId: 'season_001_001',
|
||||
stars: 2,
|
||||
score: 300,
|
||||
);
|
||||
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
saveRepositoryProvider.overrideWithValue(repo),
|
||||
seasonsProvider.overrideWith((ref) async => [_pack()]),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: const MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: SeasonMapScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('★ 2/9'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.lock), findsOneWidget); // stage 3 locked
|
||||
expect(find.text('1'), findsOneWidget);
|
||||
expect(find.text('2'), findsOneWidget);
|
||||
|
||||
// Stage 1 is starred, so stage 2 is unlocked and playable.
|
||||
await tester.tap(find.text('2'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(GameScreen), findsOneWidget);
|
||||
final session = container.read(gameSessionProvider);
|
||||
expect(session, isNotNull);
|
||||
expect(session!.phase, GamePhase.playing);
|
||||
expect(container.read(seasonFlowProvider)!.stage.id, 'season_001_002');
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user