This commit is contained in:
2025-11-19 11:17:33 +09:00
parent 3b053530f5
commit 2008c377f4
17 changed files with 1416 additions and 966 deletions
@@ -1,3 +1,4 @@
// packages/feature_game_mathquiz/lib/screens/math_quiz_lobby_screen.dart
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
@@ -5,24 +6,27 @@ import 'package:provider/provider.dart';
// [C] 공통 서비스 (service_api)
import 'package:service_api/service_api.dart';
// [A] 공통 UI (feature_common)
import 'package:feature_common/feature_common.dart';
import 'package:feature_common/feature_common.dart';
// [B] 이 패키지 (mathquiz)
import 'math_quiz_screen.dart';
import '../controllers/math_quiz_controller.dart'; // 👈 [추가] 컨트롤러 임포트
import '../controllers/math_quiz_controller.dart';
import '../models/math_quiz_difficulty.dart'; // 👈 [추가]
class MathQuizLobbyScreen extends StatefulWidget {
const MathQuizLobbyScreen({ super.key });
const MathQuizLobbyScreen({super.key});
@override
State<MathQuizLobbyScreen> createState() => _MathQuizLobbyScreenState();
}
class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
int _maxUnlockedLevel = 1;
int _maxUnlockedLevel = 1;
Map<int, (int, int)> _rankHistory = {};
bool _isLoading = false;
late final SessionNotifier _sessionNotifier;
late final LobbyHelperService _lobbyHelper;
// [🔥 수정] 서비스를 직접 생성 (Provider로 읽지 않음)
final PuzzleService _puzzleService = PuzzleService();
final IdentityService _identityService = IdentityService();
@@ -30,61 +34,61 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
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. (가벼움) 레벨 정보 새로고침
final maxLevel = await _identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
if (mounted) { setState(() { _maxUnlockedLevel = maxLevel; }); }
final maxLevel = await _lobbyHelper.loadMaxLevel('MATH_QUIZ');
if (mounted) {
setState(() {
_maxUnlockedLevel = maxLevel;
});
}
// 2. (무거움) 랭킹 정보 새로고침 (필요할 때만)
if (!forceRefreshRanks) return;
final String? myName = _sessionNotifier.session?.userName;
if (myName == null) return;
if (myName == null) return;
try {
final Map<int, int> oldRankMap = await _identityService.getLastSavedRankMap(gameType: 'MATH_QUIZ');
List<Future<List<GameRankDto>>> rankFutures = [];
for (final level in MathQuizDifficulties.allDifficulties) {
rankFutures.add(_puzzleService.fetchRanks('MATH_QUIZ', level.contextId));
final rankHistory = await _lobbyHelper.loadRankHistory<MathQuizDifficulty>(
gameType: 'MATH_QUIZ',
myName: myName,
allLevels: MathQuizDifficulties.allDifficulties,
getLevelIndex: (level) => level.levelIndex,
);
if (mounted) {
setState(() {
_rankHistory = rankHistory;
});
}
final List<List<GameRankDto>> allRankResults = await Future.wait(rankFutures);
Map<int, int> newRankMapForStorage = {};
Map<int, (int, int)> newRankHistoryForState = {};
for (int i = 0; i < MathQuizDifficulties.allDifficulties.length; i++) {
final level = MathQuizDifficulties.allDifficulties[i];
final currentRanks = allRankResults[i];
final int levelIndex = level.levelIndex;
final int oldRank = oldRankMap[levelIndex] ?? 0;
int currentRank = 0;
int myRankIndex = currentRanks.indexWhere((r) => r.playerName == myName);
if (myRankIndex != -1) { currentRank = myRankIndex + 1; }
newRankMapForStorage[levelIndex] = currentRank;
newRankHistoryForState[levelIndex] = (oldRank, currentRank);
}
await _identityService.saveLastRankMap(newRankMapForStorage, gameType: 'MATH_QUIZ');
if (mounted) { setState(() { _rankHistory = newRankHistoryForState; }); }
log("수학 퀴즈 랭킹 변동 확인 완료. (유저: $myName)");
} catch (e) {
log("MathQuizLobbyScreen: 랭킹 확인 실패: $e");
}
}
/// 🔽 [수정] 게임 시작 함수
/// 🔽 [수정 없음] 게임 시작 함수
Future<void> _startGame(MathQuizDifficulty level) async {
setState(() { _isLoading = true; });
setState(() {
_isLoading = true;
});
try {
final session = _sessionNotifier.session;
if (session == null) {
throw Exception("세션이 로드되지 않았습니다.");
}
// 1. 컨트롤러 생성 및 새 게임 시작 (제너레이터 호출)
final controller = MathQuizController();
controller.startNewGame(level, session.userId, session.userName);
@@ -100,7 +104,7 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
),
),
);
// 3. 게임에서 돌아오면 레벨 잠금 상태만 새로고침
_loadProgress(forceRefreshRanks: false);
}
@@ -112,48 +116,44 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
}
} finally {
if (mounted) {
setState(() { _isLoading = false; });
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
// ... (이하 build 메서드는 이전과 동일) ...
context.watch<ThemeNotifier>();
context.watch<SessionNotifier>();
final bool allLevelsUnlocked = _maxUnlockedLevel >= MathQuizDifficulties.allDifficulties.length;
context.watch<SessionNotifier>();
final bool allLevelsUnlocked =
_maxUnlockedLevel >= MathQuizDifficulties.allDifficulties.length;
final theme = Theme.of(context);
return CommonGameShell(
title: '계산 퀴즈',
title: '계산 퀴즈',
onRankingPressed: () {
final List<GameDifficulty> difficulties = MathQuizDifficulties.allDifficulties
.map((level) => GameDifficulty(
name: level.name,
contextId: level.contextId,
))
.toList();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RankingScreen(
gameType: 'MATH_QUIZ',
difficulties: difficulties,
initialDifficultyName: MathQuizDifficulties.getLevel(_maxUnlockedLevel).name,
difficulties: MathQuizDifficulties.allDifficulties,
initialDifficultyName:
MathQuizDifficulties.getLevel(_maxUnlockedLevel).name,
),
),
);
},
body: LayoutBuilder(
builder: (context, constraints) {
const double maxContentRatio = 0.6;
final double constrainedWidth = (constraints.maxHeight * maxContentRatio) > 500
? 500 : (constraints.maxHeight * maxContentRatio);
final double constrainedWidth =
(constraints.maxHeight * maxContentRatio) > 500
? 500
: (constraints.maxHeight * maxContentRatio);
return Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: constrainedWidth),
@@ -165,14 +165,19 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
child: ListView.builder(
itemCount: MathQuizDifficulties.allDifficulties.length,
itemBuilder: (context, index) {
final MathQuizDifficulty level = MathQuizDifficulties.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;
final MathQuizDifficulty level =
MathQuizDifficulties.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) {
@@ -180,45 +185,71 @@ class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
if (change > 0) {
subtitleText = "$rankStr (▲ $change)";
subtitleColor = Colors.green;
trailingWidget = const Icon(Icons.arrow_circle_up_rounded, color: Colors.green, size: 28);
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);
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);
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);
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);
trailingWidget = const Icon(
Icons.warning_amber_rounded,
color: Colors.orange,
size: 28);
}
}
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
margin: const EdgeInsets.symmetric(
horizontal: 16.0, vertical: 4.0),
child: ListTile(
leading: Icon(
isUnlocked ? Icons.lock_open_rounded : Icons.lock_rounded,
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,
)),
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,
? Text(subtitleText,
style: TextStyle(
color: subtitleColor,
fontWeight: FontWeight.bold))
: null,
trailing: trailingWidget,
onTap: isUnlocked && !_isLoading
? () => _startGame(level)
: null,
@@ -3,6 +3,7 @@ import 'package:provider/provider.dart';
import 'package:service_api/service_api.dart';
import 'package:feature_common/feature_common.dart';
import '../controllers/math_quiz_controller.dart';
import '../models/math_quiz_difficulty.dart';
import '../models/math_quiz_models.dart';
class MathQuizScreen extends StatefulWidget {
@@ -14,24 +15,28 @@ class MathQuizScreen extends StatefulWidget {
class _MathQuizScreenState extends State<MathQuizScreen> {
bool _isDialogShowing = false;
// ( ... _showGameCompletion 메서드는 이전과 동일 ... )
void _showGameCompletion(MathQuizController controller) async {
// ... ( _showGameCompletion 메서드는 이전과 동일 ... )
void _showGameCompletion(MathQuizController controller) async {
String formatMathQuizScore(int primary, int? secondary) {
final problemCount = primary;
final blanksCount = primary;
final time = (secondary ?? 0).toString();
return '${problemCount} (${time}초)';
return '${blanksCount} (${time}초)';
}
Future<void> saveMathQuizProgress(String playerName) async {
final identityService = IdentityService();
final int currentMaxLevel = await identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
final int currentMaxLevel =
await identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
if (currentMaxLevel < 99) {
if (controller.difficulty.levelIndex >= currentMaxLevel) {
int nextLevel = controller.difficulty.levelIndex + 1;
if (nextLevel > MathQuizDifficulties.allDifficulties.length) {
await identityService.saveMaxUnlockedLevel(99, gameType: 'MATH_QUIZ');
await identityService.saveMaxUnlockedLevel(99,
gameType: 'MATH_QUIZ');
} else {
await identityService.saveMaxUnlockedLevel(nextLevel, gameType: 'MATH_QUIZ');
await identityService.saveMaxUnlockedLevel(nextLevel,
gameType: 'MATH_QUIZ');
}
}
}
@@ -41,11 +46,11 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
context,
MaterialPageRoute(
builder: (context) => GameCompletionScreen(
args: GameResultArgs(
args: GameResultArgs(
gameType: 'MATH_QUIZ',
contextId: controller.difficulty.contextId,
primaryScore: controller.puzzle.solutions.length,
secondaryScore: controller.secondsElapsed,
primaryScore: controller.totalBlanksFilled,
secondaryScore: controller.secondsElapsed,
userId: controller.userId,
userName: controller.userName,
scoreFormatter: formatMathQuizScore,
@@ -73,14 +78,30 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
return Scaffold(
appBar: AppBar(
title: Text(controller.difficulty.name),
title: Text('Lv. ${controller.difficulty.levelIndex}'),
actions: [
Padding(
padding: const EdgeInsets.only(right: 20.0),
child: Center(
Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: _buildTriesWidget(controller.remainingTries),
),
),
Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Text(
'${controller.currentPuzzleIndex + 1} / ${controller.totalPuzzlesInLevel}',
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
),
Center(
child: Padding(
padding: const EdgeInsets.only(right: 20.0),
child: Text(
'${(controller.secondsElapsed ~/ 60).toString().padLeft(2, '0')}:${(controller.secondsElapsed % 60).toString().padLeft(2, '0')}',
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
style:
const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
),
@@ -99,15 +120,27 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
);
}
/// 🔽 세로 모드 레이아웃
Widget _buildPortraitLayout(BuildContext context, MathQuizController controller) {
Widget _buildTriesWidget(int tries) {
return Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(3, (index) {
return Icon(
index < tries ? Icons.favorite : Icons.favorite_border,
color: Colors.redAccent,
size: 24,
);
}),
);
}
Widget _buildPortraitLayout(
BuildContext context, MathQuizController controller) {
return Column(
children: [
Expanded(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
// [수정] _buildPuzzleGrid를 항상 호출
child: _buildPuzzleGrid(context, controller),
),
),
@@ -117,38 +150,33 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
);
}
/// 🔽 가로 모드 레이아웃
Widget _buildLandscapeLayout(BuildContext context, MathQuizController controller) {
Widget _buildLandscapeLayout(
BuildContext context, MathQuizController controller) {
return Row(
children: [
Expanded(
flex: 6, // 방정식 영역
flex: 6,
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
// [수정] _buildPuzzleGrid를 항상 호출
child: _buildPuzzleGrid(context, controller),
),
),
),
Expanded(
flex: 4, // 키패드 영역
flex: 4,
child: _buildKeypad(context, controller),
),
],
);
}
// ❌ [삭제] _buildEquationList 메서드 삭제
/// [수정] _buildEquationGrid -> _buildPuzzleGrid
/// (모든 퍼즐을 그리는 유일한 빌더)
Widget _buildPuzzleGrid(BuildContext context, MathQuizController controller) {
final puzzle = controller.puzzle;
final userAnswers = controller.userAnswers;
final int crossAxisCount = puzzle.gridCrossAxisCount;
int blankIndex = 0;
int blankIndex = 0;
return GridView.builder(
shrinkWrap: true,
@@ -159,26 +187,32 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
),
itemBuilder: (context, index) {
final String part = puzzle.gridCells[index];
if (part == "?") {
// 빈칸일 경우
final int currentBlankIndex = blankIndex;
blankIndex++;
return _buildBlankBox(
context,
controller,
currentBlankIndex,
userAnswers[currentBlankIndex],
(currentBlankIndex < userAnswers.length)
? userAnswers[currentBlankIndex]
: null,
);
} else if (part == " ") {
// " " (빈 공간)
return Container();
} else {
// 숫자나 기호일 경우
return Center(
child: Text(
part,
style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
child: FittedBox(
fit: BoxFit.contain,
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
part,
style: const TextStyle(
fontSize: 32, fontWeight: FontWeight.bold),
),
),
),
);
}
@@ -186,38 +220,55 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
);
}
/// [수정] _buildBlankBox (isGrid 파라미터 삭제)
Widget _buildBlankBox(BuildContext context, MathQuizController controller, int index, String? value) {
Widget _buildBlankBox(BuildContext context, MathQuizController controller,
int index, String? value) {
final theme = Theme.of(context);
final bool isSelected = (controller.selectedBlankIndex == index);
final bool isWrong = controller.isWrongAnswer;
final bool isRevealing = controller.isRevealingAnswer;
Color borderColor;
Color textColor;
if (isRevealing) {
borderColor = theme.colorScheme.primary;
textColor = theme.colorScheme.primary;
} else if (isWrong) {
borderColor = theme.colorScheme.error;
textColor = theme.colorScheme.onSurfaceVariant;
} else if (isSelected) {
borderColor = theme.colorScheme.primary;
textColor = theme.colorScheme.onSurfaceVariant;
} else {
borderColor = Colors.transparent;
textColor = theme.colorScheme.onSurfaceVariant;
}
// [수정] 그리드 셀의 크기는 GridView가 결정하므로
// AspectRatio를 사용해 1:1 비율 유지
return AspectRatio(
aspectRatio: 1 / 1,
child: GestureDetector(
onTap: () => controller.onBlankTapped(index),
child: Container(
margin: const EdgeInsets.all(4.0), // 그리드/리스트 공통 여백
margin: const EdgeInsets.all(4.0),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceVariant,
border: Border.all(
color: isSelected ? theme.colorScheme.primary : Colors.transparent,
color: borderColor,
width: 3,
),
borderRadius: BorderRadius.circular(8),
),
child: Center(
// [수정] 폰트 크기를 FittedBox로 자동 조절
child: FittedBox(
fit: BoxFit.contain,
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
value ?? '',
value ?? '',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurfaceVariant,
color: textColor,
),
),
),
@@ -228,13 +279,32 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
);
}
/// 2. 키패드 UI 빌더
/// [🔥 수정됨] 키패드 UI 빌더 (동적 필터링)
Widget _buildKeypad(BuildContext context, MathQuizController controller) {
// ... (이하 키패드 로직은 동일) ...
final puzzle = controller.puzzle;
final theme = Theme.of(context);
final bool isDisabled = controller.isRevealingAnswer;
final PuzzleBlankType? selectedType = controller.currentSelectedBlankType;
// [🔥 최종 확인] 헬퍼 함수
bool isOperator(String val) => ['/', '*', '-', '+'].contains(val);
bool isNumber(String val) => int.tryParse(val) != null;
// [🔥 최종 수정] 타입에 따라 옵션 필터링
List<String> availableOptions = [];
if (selectedType == PuzzleBlankType.number) {
// 숫자가 필요하면 숫자만 필터링
availableOptions = puzzle.options.where((opt) => isNumber(opt)).toList();
} else if (selectedType == PuzzleBlankType.operator) {
// 연산자가 필요하면 연산자만 필터링
availableOptions = puzzle.options.where((opt) => isOperator(opt)).toList();
}
final int totalButtonCount = availableOptions.length + 1; // 필터링된 옵션 + 지우기
return Container(
// ... (GridView.builder 이하 로직은 동일) ...
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: theme.scaffoldBackgroundColor,
@@ -255,19 +325,18 @@ class _MathQuizScreenState extends State<MathQuizScreen> {
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
itemCount: puzzle.options.length + 1, // 옵션 + 지우기 버튼
itemCount: totalButtonCount,
itemBuilder: (context, index) {
if (index == puzzle.options.length) {
if (index == availableOptions.length) {
return FilledButton.tonal(
onPressed: () => controller.onClearTapped(),
onPressed: isDisabled ? null : () => controller.onClearTapped(),
child: const Icon(Icons.backspace_outlined),
);
}
final String option = puzzle.options[index];
final String option = availableOptions[index];
return FilledButton(
onPressed: () => controller.onOptionTapped(option),
onPressed: isDisabled ? null : () => controller.onOptionTapped(option),
child: Text(
option,
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),