diff --git a/lib/data/content_repository.dart b/lib/data/content_repository.dart new file mode 100644 index 0000000..c5ec6f3 --- /dev/null +++ b/lib/data/content_repository.dart @@ -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 loadBundledSeason(String seasonId) async { + final raw = + await rootBundle.loadString('assets/seasons/$seasonId/pack.json'); + return SeasonPack.fromJson(jsonDecode(raw) as Map); + } + + Future> availableSeasons() async => [ + for (final id in bundledSeasonIds) await loadBundledSeason(id), + ]; +} diff --git a/lib/data/save_repository.dart b/lib/data/save_repository.dart new file mode 100644 index 0000000..227961a --- /dev/null +++ b/lib/data/save_repository.dart @@ -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; + final progress = json['progress'] as Map? ?? {}; + for (final entry in progress.entries) { + final value = entry.value as Map; + _progress[entry.key] = StageProgress( + stars: value['stars'] as int, + bestScore: value['bestScore'] as int, + ); + } + } + } + + static const _key = 'save_v1'; + + static Future open() async => + SaveRepository(await SharedPreferences.getInstance()); + + final SharedPreferences _prefs; + final Map _progress = {}; + + static String _id(String seasonId, String stageId) => '$seasonId/$stageId'; + + /// Immutable copy of all progress, keyed `seasonId/stageId`. + Map snapshot() => Map.unmodifiable(_progress); + + StageProgress? progressFor(String seasonId, String stageId) => + _progress[_id(seasonId, stageId)]; + + Future 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 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 _flush() => _prefs.setString( + _key, + jsonEncode({ + 'saveVersion': 1, + 'progress': { + for (final entry in _progress.entries) + entry.key: { + 'stars': entry.value.stars, + 'bestScore': entry.value.bestScore, + }, + }, + }), + ); +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 9368c9d..eaf884f 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -11,5 +11,6 @@ "watchAdContinue": "Continue (ad)", "plusFiveMoves": "+5 moves (ad)", "giveUp": "Give up", - "playAgain": "Play again" + "playAgain": "Play again", + "nextStage": "Next stage" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 4f55308..844900c 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -11,5 +11,6 @@ "watchAdContinue": "광고 보고 이어하기", "plusFiveMoves": "+5 이동 (광고)", "giveUp": "포기하기", - "playAgain": "다시 하기" + "playAgain": "다시 하기", + "nextStage": "다음 스테이지" } diff --git a/lib/main.dart b/lib/main.dart index dff0f3d..dfa6cdf 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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 main() async { WidgetsFlutterBinding.ensureInitialized(); - runApp(const ProviderScope(child: BlockSeasonsApp())); + final saveRepository = await SaveRepository.open(); + runApp( + ProviderScope( + overrides: [saveRepositoryProvider.overrideWithValue(saveRepository)], + child: const BlockSeasonsApp(), + ), + ); } diff --git a/lib/state/progress_notifier.dart b/lib/state/progress_notifier.dart new file mode 100644 index 0000000..6c68d29 --- /dev/null +++ b/lib/state/progress_notifier.dart @@ -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> { + @override + Map build() => + ref.read(saveRepositoryProvider).snapshot(); + + Future 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(); + } +} diff --git a/lib/state/providers.dart b/lib/state/providers.dart index f11cb2a..acdf6ef 100644 --- a/lib/state/providers.dart +++ b/lib/state/providers.dart @@ -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( @@ -13,3 +18,24 @@ final audioServiceProvider = Provider((ref) { ref.onDispose(service.dispose); return service; }); + +/// Overridden with the opened repository in main() (and in tests). +final saveRepositoryProvider = Provider( + (ref) => throw UnimplementedError('override with an opened SaveRepository'), +); + +final progressProvider = + NotifierProvider>( + ProgressNotifier.new, +); + +final seasonFlowProvider = NotifierProvider( + SeasonFlowNotifier.new, +); + +final contentRepositoryProvider = + Provider((ref) => ContentRepository()); + +final seasonsProvider = FutureProvider>( + (ref) => ref.read(contentRepositoryProvider).availableSeasons(), +); diff --git a/lib/state/season_flow_notifier.dart b/lib/state/season_flow_notifier.dart new file mode 100644 index 0000000..749cbd4 --- /dev/null +++ b/lib/state/season_flow_notifier.dart @@ -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 { + @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 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); + } +} diff --git a/lib/ui/screens/game_screen.dart b/lib/ui/screens/game_screen.dart index da3a196..d30ae88 100644 --- a/lib/ui/screens/game_screen.dart +++ b/lib/ui/screens/game_screen.dart @@ -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 { /// 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 { } } - 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 { } } 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(gameSessionProvider, _playSfx); + ref.listen(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 { _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 { 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), ), diff --git a/lib/ui/screens/home_screen.dart b/lib/ui/screens/home_screen.dart index 119ce79..dc6389b 100644 --- a/lib/ui/screens/home_screen.dart +++ b/lib/ui/screens/home_screen.dart @@ -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(), ), ); }, diff --git a/lib/ui/screens/season_map_screen.dart b/lib/ui/screens/season_map_screen.dart new file mode 100644 index 0000000..9bd26dd --- /dev/null +++ b/lib/ui/screens/season_map_screen.dart @@ -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), + ), + ), + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 98d7eb9..c1f5c9f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -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: diff --git a/test/data/content_repository_test.dart b/test/data/content_repository_test.dart new file mode 100644 index 0000000..f49baa7 --- /dev/null +++ b/test/data/content_repository_test.dart @@ -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')); + }); +} diff --git a/test/data/save_repository_test.dart b/test/data/save_repository_test.dart new file mode 100644 index 0000000..7b2ec3c --- /dev/null +++ b/test/data/save_repository_test.dart @@ -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 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); + }); +} diff --git a/test/state/season_flow_test.dart b/test/state/season_flow_test.dart new file mode 100644 index 0000000..53bc8e3 --- /dev/null +++ b/test/state/season_flow_test.dart @@ -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 >[], + 'objectives': [ + {'type': 'reachScore', 'target': 999999}, + ], + 'stars': { + 'two': {'movesLeft': 5}, + 'three': {'movesLeft': 10}, + }, + 'generatorProfile': 'mid', + }, + ], + }); + +Future _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); + }); +} diff --git a/test/ui/season_map_screen_test.dart b/test/ui/season_map_screen_test.dart new file mode 100644 index 0000000..2f28a98 --- /dev/null +++ b/test/ui/season_map_screen_test.dart @@ -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 >[], + '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'); + }); +}