This commit is contained in:
2025-11-19 18:00:41 +09:00
parent 64f3fb8adf
commit ef584cae10
144 changed files with 5819 additions and 0 deletions
@@ -0,0 +1,208 @@
// packages/feature_game_finddiff/lib/screens/finddiff_game_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:service_api/service_api.dart';
import 'package:feature_common/feature_common.dart';
import '../controllers/finddiff_controller.dart';
import '../models/finddiff_models.dart';
class FindDiffGameScreen extends StatefulWidget {
const FindDiffGameScreen({super.key});
@override
State<FindDiffGameScreen> createState() => _FindDiffGameScreenState();
}
class _FindDiffGameScreenState extends State<FindDiffGameScreen> {
bool _isDialogShowing = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_showGameGuide();
});
}
void _showGameGuide() {
final controller = context.read<FindDiffController>();
String message = "화면에 있는 그림들 중\n나머지와 '다른 하나'를 찾으세요.";
if (controller.difficulty.diffType == FindDiffType.color) {
message += "\n(색상이 다릅니다)";
} else if (controller.difficulty.diffType == FindDiffType.icon) {
message += "\n(모양이 다릅니다)";
} else {
message += "\n(각도가 다릅니다)";
}
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: const Text("게임 방법", style: TextStyle(fontWeight: FontWeight.bold)),
content: Text(message, textAlign: TextAlign.center, style: const TextStyle(fontSize: 16)),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
controller.startGameTimer();
},
child: const Text("시작하기"),
),
],
),
);
}
void _showGameCompletion(FindDiffController controller) async {
String formatScore(int primary, int? secondary) {
return '성공: $primary문제 / 오답: ${secondary ?? 0}';
}
Future<void> saveProgress(String playerName) async {
// 10문제 이상 맞춰야 성공으로 인정
if (controller.score < 10) return;
final identityService = IdentityService();
final int currentMaxLevel = await identityService.getMaxUnlockedLevel(gameType: 'FIND_DIFF'); // IdentityService에 키 추가 필요
if (currentMaxLevel < 99) {
if (controller.difficulty.levelIndex >= currentMaxLevel) {
int nextLevel = controller.difficulty.levelIndex + 1;
if (nextLevel > FindDiffDifficulties.allDifficulties.length) {
await identityService.saveMaxUnlockedLevel(99, gameType: 'FIND_DIFF');
} else {
await identityService.saveMaxUnlockedLevel(nextLevel, gameType: 'FIND_DIFF');
}
}
}
}
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GameCompletionScreen(
args: GameResultArgs(
gameType: 'FIND_DIFF',
contextId: controller.difficulty.contextId,
primaryScore: controller.score,
secondaryScore: controller.incorrectCount,
userId: controller.userId,
userName: controller.userName,
scoreFormatter: formatScore,
onProgressSave: saveProgress,
),
),
),
);
if (mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
}
@override
Widget build(BuildContext context) {
final controller = context.watch<FindDiffController>();
final theme = Theme.of(context);
if (controller.isGameCompleted && !_isDialogShowing) {
_isDialogShowing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_showGameCompletion(controller);
});
}
// 시간 임박 경고 색상
final Color timeColor = controller.remainingTime <= 3 ? theme.colorScheme.error : theme.colorScheme.onSurface;
return Scaffold(
appBar: AppBar(
title: Text(controller.difficulty.name),
actions: [
Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Center(
child: Text(
'${controller.remainingTime}s',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: timeColor),
),
),
),
],
),
body: Column(
children: [
// 정보 바
Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text("목표: ${controller.score}/10", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: theme.primaryColor)),
Text("오답: ${controller.incorrectCount}", style: const TextStyle(fontSize: 16, color: Colors.grey)),
],
),
),
// 피드백 오버레이
if (controller.showFeedback)
Expanded(
child: Center(
child: Icon(
controller.isLastAnswerCorrect ? Icons.check_circle : Icons.cancel,
size: 100,
color: controller.isLastAnswerCorrect ? Colors.green : theme.colorScheme.error,
),
),
)
else
// 게임 그리드
Expanded(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: LayoutBuilder(
builder: (context, constraints) {
return GridView.builder(
itemCount: controller.items.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: controller.difficulty.cols,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: 1.0,
),
itemBuilder: (context, index) {
return _buildItem(controller.items[index], controller);
},
);
},
),
),
),
],
),
);
}
Widget _buildItem(FindDiffItem item, FindDiffController controller) {
return GestureDetector(
onTap: () => controller.onItemTapped(item),
child: Container(
decoration: BoxDecoration(
color: Colors.grey.shade200,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.black12),
),
child: Transform.rotate(
angle: item.angle,
child: Icon(
item.icon,
size: 40, // 동적 크기 조절이 필요하면 LayoutBuilder 활용 가능
color: item.color,
),
),
),
);
}
}
@@ -0,0 +1,267 @@
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// [C] 공통 서비스
import 'package:service_api/service_api.dart';
// [A] 공통 UI 셸
import 'package:feature_common/feature_common.dart';
// [B] 다른 그림 찾기 모델/컨트롤러
import '../models/finddiff_models.dart';
import '../controllers/finddiff_controller.dart';
import 'finddiff_game_screen.dart';
class FindDiffLobbyScreen extends StatefulWidget {
const FindDiffLobbyScreen({super.key});
@override
State<FindDiffLobbyScreen> createState() => _FindDiffLobbyScreenState();
}
class _FindDiffLobbyScreenState extends State<FindDiffLobbyScreen> {
int _maxUnlockedLevel = 1;
Map<int, (int, int)> _rankHistory = {};
bool _isLoading = false;
late final SessionNotifier _sessionNotifier;
late final LobbyHelperService _lobbyHelper;
final PuzzleService _puzzleService = PuzzleService();
final IdentityService _identityService = IdentityService();
@override
void initState() {
super.initState();
_sessionNotifier = context.read<SessionNotifier>();
// 헬퍼 서비스 초기화
_lobbyHelper = LobbyHelperService(
identityService: _identityService,
puzzleService: _puzzleService,
);
_loadProgress(forceRefreshRanks: true);
}
/// [공통 로직] 레벨 잠금 상태 및 랭킹 이력 로드
Future<void> _loadProgress({bool forceRefreshRanks = false}) async {
// 1. 최대 레벨 로드 ('FIND_DIFF' 키 사용)
final maxLevel = await _lobbyHelper.loadMaxLevel('FIND_DIFF');
if (mounted) {
setState(() {
_maxUnlockedLevel = maxLevel;
});
}
// 2. 랭킹 이력 로드
if (!forceRefreshRanks) return;
final String? myName = _sessionNotifier.session?.userName;
if (myName == null) return;
try {
final rankHistory = await _lobbyHelper.loadRankHistory<FindDiffDifficulty>(
gameType: 'FIND_DIFF',
myName: myName,
allLevels: FindDiffDifficulties.allDifficulties,
getLevelIndex: (level) => level.levelIndex,
);
if (mounted) {
setState(() {
_rankHistory = rankHistory;
});
}
} catch (e) {
log("FindDiffLobbyScreen: 랭킹 확인 실패: $e");
}
}
/// [게임 시작] 컨트롤러 생성 및 화면 이동
Future<void> _startGame(FindDiffDifficulty level) async {
setState(() {
_isLoading = true;
});
final session = _sessionNotifier.session;
if (session == null) {
log("세션이 로드되지 않아 게임을 시작할 수 없습니다.");
setState(() {
_isLoading = false;
});
return;
}
final String userId = session.userId;
final String? userName = session.userName;
// 1. 컨트롤러 생성 및 시작
final gameController = FindDiffController();
gameController.setUserInfo(userId, userName);
gameController.startNewGame(level);
setState(() {
_isLoading = false;
});
if (!mounted) return;
// 2. 게임 화면으로 이동
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider.value(
value: gameController,
child: const FindDiffGameScreen(),
),
),
);
// 3. 복귀 후 레벨 상태 갱신
_loadProgress(forceRefreshRanks: false);
}
@override
Widget build(BuildContext context) {
context.watch<ThemeNotifier>();
context.watch<SessionNotifier>();
final bool allLevelsUnlocked =
_maxUnlockedLevel >= FindDiffDifficulties.allDifficulties.length;
final theme = Theme.of(context);
return CommonGameShell(
title: '다른 그림 찾기',
onRankingPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RankingScreen(
gameType: 'FIND_DIFF',
difficulties: FindDiffDifficulties.allDifficulties,
initialDifficultyName:
FindDiffDifficulties.getLevel(_maxUnlockedLevel).name,
),
),
);
},
body: LayoutBuilder(
builder: (context, constraints) {
const double maxContentRatio = 0.6;
final double constrainedWidth =
(constraints.maxHeight * maxContentRatio) > 500
? 500
: (constraints.maxHeight * maxContentRatio);
return Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: constrainedWidth),
child: Column(
children: [
Expanded(
child: RefreshIndicator(
onRefresh: () => _loadProgress(forceRefreshRanks: true),
child: ListView.builder(
itemCount: FindDiffDifficulties.allDifficulties.length,
itemBuilder: (context, index) {
final FindDiffDifficulty level =
FindDiffDifficulties.allDifficulties[index];
final bool isUnlocked = allLevelsUnlocked ||
level.levelIndex <= _maxUnlockedLevel;
final (int oldRank, int currentRank) =
_rankHistory[level.levelIndex] ?? (0, 0);
Widget? trailingWidget = isUnlocked
? const Icon(Icons.play_arrow_rounded)
: null;
String? subtitleText;
Color? subtitleColor;
// 랭킹 변동 표시
if (currentRank > 0) {
String rankStr = "${currentRank}";
if (oldRank > 0) {
int change = oldRank - currentRank;
if (change > 0) {
subtitleText = "$rankStr (▲ $change)";
subtitleColor = Colors.green;
trailingWidget = const Icon(
Icons.arrow_circle_up_rounded,
color: Colors.green,
size: 28);
} else if (change < 0) {
subtitleText = "$rankStr (▼ ${change.abs()})";
subtitleColor = Colors.red;
trailingWidget = const Icon(
Icons.arrow_circle_down_rounded,
color: Colors.red,
size: 28);
} else {
subtitleText = "$rankStr (유지)";
subtitleColor = Colors.grey;
trailingWidget = const Icon(
Icons.check_circle_outline_rounded,
color: Colors.grey,
size: 28);
}
} else {
subtitleText = "$rankStr (신규 진입)";
subtitleColor = Colors.blue;
trailingWidget = const Icon(
Icons.new_releases_rounded,
color: Colors.blue,
size: 28);
}
} else {
if (oldRank > 0) {
subtitleText = "랭킹 이탈 (이전 ${oldRank}위)";
subtitleColor = Colors.orange;
trailingWidget = const Icon(
Icons.warning_amber_rounded,
color: Colors.orange,
size: 28);
}
}
return Card(
margin: const EdgeInsets.symmetric(
horizontal: 16.0, vertical: 4.0),
child: ListTile(
leading: Icon(
isUnlocked
? Icons.lock_open_rounded
: Icons.lock_rounded,
color: isUnlocked
? theme.primaryColor
: Colors.grey,
),
title: Text(level.name,
style: TextStyle(
fontSize: 18,
fontWeight: isUnlocked
? FontWeight.bold
: FontWeight.normal,
color: isUnlocked
? theme.textTheme.bodyLarge?.color
: Colors.grey,
)),
subtitle: subtitleText != null
? Text(subtitleText,
style: TextStyle(
color: subtitleColor,
fontWeight: FontWeight.bold))
: null,
trailing: trailingWidget,
onTap: isUnlocked && !_isLoading
? () => _startGame(level)
: null,
),
);
},
),
),
),
],
),
),
);
},
),
);
}
}