...
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
import 'dart:developer';
|
||||
import 'package:flutter/material.dart';
|
||||
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';
|
||||
// [B] 이 패키지 (mathquiz)
|
||||
import 'math_quiz_screen.dart';
|
||||
import '../controllers/math_quiz_controller.dart'; // 👈 [추가] 컨트롤러 임포트
|
||||
|
||||
class MathQuizLobbyScreen extends StatefulWidget {
|
||||
const MathQuizLobbyScreen({ super.key });
|
||||
|
||||
@override
|
||||
State<MathQuizLobbyScreen> createState() => _MathQuizLobbyScreenState();
|
||||
}
|
||||
|
||||
class _MathQuizLobbyScreenState extends State<MathQuizLobbyScreen> {
|
||||
int _maxUnlockedLevel = 1;
|
||||
Map<int, (int, int)> _rankHistory = {};
|
||||
bool _isLoading = false;
|
||||
|
||||
late final SessionNotifier _sessionNotifier;
|
||||
final PuzzleService _puzzleService = PuzzleService();
|
||||
final IdentityService _identityService = IdentityService();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_sessionNotifier = context.read<SessionNotifier>();
|
||||
_loadProgress(forceRefreshRanks: true);
|
||||
}
|
||||
|
||||
/// 랭킹 및 레벨 진행 상황 로드
|
||||
Future<void> _loadProgress({bool forceRefreshRanks = false}) async {
|
||||
// 1. (가벼움) 레벨 정보 새로고침
|
||||
final maxLevel = await _identityService.getMaxUnlockedLevel(gameType: 'MATH_QUIZ');
|
||||
if (mounted) { setState(() { _maxUnlockedLevel = maxLevel; }); }
|
||||
|
||||
// 2. (무거움) 랭킹 정보 새로고침 (필요할 때만)
|
||||
if (!forceRefreshRanks) return;
|
||||
|
||||
final String? myName = _sessionNotifier.session?.userName;
|
||||
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 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; });
|
||||
|
||||
try {
|
||||
final session = _sessionNotifier.session;
|
||||
if (session == null) {
|
||||
throw Exception("세션이 로드되지 않았습니다.");
|
||||
}
|
||||
|
||||
// 1. 컨트롤러 생성 및 새 게임 시작 (제너레이터 호출)
|
||||
final controller = MathQuizController();
|
||||
controller.startNewGame(level, session.userId, session.userName);
|
||||
|
||||
if (mounted) {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
// 2. 컨트롤러를 게임 화면에 주입
|
||||
builder: (context) => ChangeNotifierProvider.value(
|
||||
value: controller,
|
||||
child: const MathQuizScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// 3. 게임에서 돌아오면 레벨 잠금 상태만 새로고침
|
||||
_loadProgress(forceRefreshRanks: false);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('게임 로딩/생성 실패: $e')),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() { _isLoading = false; });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// ... (이하 build 메서드는 이전과 동일) ...
|
||||
context.watch<ThemeNotifier>();
|
||||
context.watch<SessionNotifier>();
|
||||
|
||||
final bool allLevelsUnlocked = _maxUnlockedLevel >= MathQuizDifficulties.allDifficulties.length;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return CommonGameShell(
|
||||
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,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
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: 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;
|
||||
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,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
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/math_quiz_controller.dart';
|
||||
import '../models/math_quiz_models.dart';
|
||||
|
||||
class MathQuizScreen extends StatefulWidget {
|
||||
const MathQuizScreen({super.key});
|
||||
|
||||
@override
|
||||
State<MathQuizScreen> createState() => _MathQuizScreenState();
|
||||
}
|
||||
|
||||
class _MathQuizScreenState extends State<MathQuizScreen> {
|
||||
bool _isDialogShowing = false;
|
||||
|
||||
// ( ... _showGameCompletion 메서드는 이전과 동일 ... )
|
||||
void _showGameCompletion(MathQuizController controller) async {
|
||||
String formatMathQuizScore(int primary, int? secondary) {
|
||||
final problemCount = primary;
|
||||
final time = (secondary ?? 0).toString();
|
||||
return '${problemCount}개 (${time}초)';
|
||||
}
|
||||
Future<void> saveMathQuizProgress(String playerName) async {
|
||||
final identityService = IdentityService();
|
||||
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');
|
||||
} else {
|
||||
await identityService.saveMaxUnlockedLevel(nextLevel, gameType: 'MATH_QUIZ');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => GameCompletionScreen(
|
||||
args: GameResultArgs(
|
||||
gameType: 'MATH_QUIZ',
|
||||
contextId: controller.difficulty.contextId,
|
||||
primaryScore: controller.puzzle.solutions.length,
|
||||
secondaryScore: controller.secondsElapsed,
|
||||
userId: controller.userId,
|
||||
userName: controller.userName,
|
||||
scoreFormatter: formatMathQuizScore,
|
||||
onProgressSave: saveMathQuizProgress,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (mounted && Navigator.canPop(context)) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final controller = context.watch<MathQuizController>();
|
||||
|
||||
if (controller.isGameCompleted && !_isDialogShowing) {
|
||||
_isDialogShowing = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_showGameCompletion(controller);
|
||||
});
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(controller.difficulty.name),
|
||||
actions: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'${(controller.secondsElapsed ~/ 60).toString().padLeft(2, '0')}:${(controller.secondsElapsed % 60).toString().padLeft(2, '0')}',
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
bool isLandscape = constraints.maxWidth > constraints.maxHeight;
|
||||
if (isLandscape) {
|
||||
return _buildLandscapeLayout(context, controller);
|
||||
} else {
|
||||
return _buildPortraitLayout(context, controller);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 🔽 세로 모드 레이아웃
|
||||
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),
|
||||
),
|
||||
),
|
||||
),
|
||||
_buildKeypad(context, controller),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// 🔽 가로 모드 레이아웃
|
||||
Widget _buildLandscapeLayout(BuildContext context, MathQuizController controller) {
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 6, // 방정식 영역
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
// [수정] _buildPuzzleGrid를 항상 호출
|
||||
child: _buildPuzzleGrid(context, controller),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
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;
|
||||
|
||||
return GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: puzzle.gridCells.length,
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: crossAxisCount,
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final String part = puzzle.gridCells[index];
|
||||
|
||||
if (part == "?") {
|
||||
// 빈칸일 경우
|
||||
final int currentBlankIndex = blankIndex;
|
||||
blankIndex++;
|
||||
return _buildBlankBox(
|
||||
context,
|
||||
controller,
|
||||
currentBlankIndex,
|
||||
userAnswers[currentBlankIndex],
|
||||
);
|
||||
} else if (part == " ") {
|
||||
// " " (빈 공간)
|
||||
return Container();
|
||||
} else {
|
||||
// 숫자나 기호일 경우
|
||||
return Center(
|
||||
child: Text(
|
||||
part,
|
||||
style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// [수정] _buildBlankBox (isGrid 파라미터 삭제)
|
||||
Widget _buildBlankBox(BuildContext context, MathQuizController controller, int index, String? value) {
|
||||
final theme = Theme.of(context);
|
||||
final bool isSelected = (controller.selectedBlankIndex == index);
|
||||
|
||||
// [수정] 그리드 셀의 크기는 GridView가 결정하므로
|
||||
// AspectRatio를 사용해 1:1 비율 유지
|
||||
return AspectRatio(
|
||||
aspectRatio: 1 / 1,
|
||||
child: GestureDetector(
|
||||
onTap: () => controller.onBlankTapped(index),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(4.0), // 그리드/리스트 공통 여백
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceVariant,
|
||||
border: Border.all(
|
||||
color: isSelected ? theme.colorScheme.primary : Colors.transparent,
|
||||
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 ?? '',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 2. 키패드 UI 빌더
|
||||
Widget _buildKeypad(BuildContext context, MathQuizController controller) {
|
||||
// ... (이하 키패드 로직은 동일) ...
|
||||
final puzzle = controller.puzzle;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.scaffoldBackgroundColor,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, -2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 5, // 5열
|
||||
childAspectRatio: 1.5,
|
||||
mainAxisSpacing: 8,
|
||||
crossAxisSpacing: 8,
|
||||
),
|
||||
itemCount: puzzle.options.length + 1, // 옵션 + 지우기 버튼
|
||||
itemBuilder: (context, index) {
|
||||
|
||||
if (index == puzzle.options.length) {
|
||||
return FilledButton.tonal(
|
||||
onPressed: () => controller.onClearTapped(),
|
||||
child: const Icon(Icons.backspace_outlined),
|
||||
);
|
||||
}
|
||||
|
||||
final String option = puzzle.options[index];
|
||||
return FilledButton(
|
||||
onPressed: () => controller.onOptionTapped(option),
|
||||
child: Text(
|
||||
option,
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user