This commit is contained in:
2025-11-17 18:21:49 +09:00
parent 13ed537b23
commit 86611ce092
160 changed files with 7829 additions and 452 deletions
@@ -1,22 +1,15 @@
// packages/feature_game_sudoku/lib/screens/game_screen.dart
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// [C] 서비스 import
import 'package:service_api/service_api.dart';
// [A] 공통 위젯 import
import 'package:feature_common/feature_common.dart';
// [B] 같은 패키지 내의 위젯 import
import '../widgets/number_pad.dart';
import '../widgets/sudoku_board.dart';
import '../models/game_level.dart';
// ❌ [삭제] enum _RankSubmissionStep
class GameScreen extends StatefulWidget {
final SudokuGameDto gameData;
final String themeName;
@@ -57,18 +50,12 @@ class _GameScreenState extends State<GameScreen> {
int? selectedNumberPad;
Set<int> incorrectCells = {};
bool isValidating = false;
// ❌ [삭제] 랭킹 다이얼로그 전용 상태 변수
// _RankSubmissionStep _rankStep = _RankSubmissionStep.enterName;
// List<GameRankDto> _rankingList = [];
// GameRankWithRankNumber? _myRankResult;
// String _submittedPlayerName = "";
late final TransformationController _transformationController;
// ... ( _charToInt, _intToChar, initState, dispose, startTimer, onCellTapped, _checkIfBoardIsFull ... )
// ... ( onNumberTapped, onUndoTapped, onHintTapped, _onRestartGameTapped, _onQuitGameTapped, _resetBoardZoom ... )
// ... ( 이 함수들은 모두 동일합니다 )
// ( ... _charToInt, _intToChar, initState, dispose, startTimer ... )
// ( ... onCellTapped, _checkIfBoardIsFull, onNumberTapped, onUndoTapped ... )
// ( ... onHintTapped, _onRestartGameTapped, _onQuitGameTapped, _resetBoardZoom ... )
int _charToInt(String char) {
if (char == '0') return 0;
if (char.codeUnitAt(0) >= '1'.codeUnitAt(0) && char.codeUnitAt(0) <= '9'.codeUnitAt(0)) {
@@ -79,103 +66,74 @@ class _GameScreenState extends State<GameScreen> {
}
return -1;
}
String _intToChar(int num) {
if (num == 0) return '0';
if (num >= 1 && num <= 9) return num.toString();
if (num >= 10 && num <= 35) return String.fromCharCode('A'.codeUnitAt(0) + (num - 10));
return '?';
}
@override
void initState() {
super.initState();
currentLevel = AppLevels.getLevel(widget.levelIndex);
blockSize = currentLevel.blockSize;
gridSize = blockSize * blockSize;
_transformationController = TransformationController();
String themeForThisGame = widget.themeName;
bool isEasyMode = currentLevel.isSequentialNumbers || currentLevel.isSequentialLetters;
if (currentLevel.isSequentialNumbers) {
themeForThisGame = AppThemes.numbers;
} else if (currentLevel.isSequentialLetters) {
themeForThisGame = AppThemes.letters;
}
activeTheme = AppThemes.buildGameTheme(
themeForThisGame,
gridSize,
isEasyMode: isEasyMode,
);
activeTheme = AppThemes.buildGameTheme(themeForThisGame, gridSize, isEasyMode: isEasyMode);
puzzleCells = widget.gameData.question.split('').map(_charToInt).toList();
solutionCells = widget.gameData.solution.split('').map(_charToInt).toList();
originalCells = widget.gameData.question.split('').map(_charToInt).toList();
startTimer();
}
@override
void dispose() {
timer?.cancel();
_transformationController.dispose();
super.dispose();
}
void startTimer() {
timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
secondsElapsed++;
});
setState(() { secondsElapsed++; });
});
}
void onCellTapped(int index) {
if (originalCells[index] == 0) {
if (incorrectCells.isNotEmpty && !incorrectCells.contains(index)) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('틀린 값을 먼저 수정해주세요. (되돌리기 ↩)'),
duration: Duration(seconds: 1),
),
const SnackBar(content: Text('틀린 값을 먼저 수정해주세요. (되돌리기 ↩)'), duration: Duration(seconds: 1)),
);
return;
}
setState(() {
selectedIndex = index;
if (selectedNumberPad != null) {
final int numberValue = selectedNumberPad!;
puzzleCells[index] = numberValue;
if (numberValue != solutionCells[index]) {
if (!incorrectCells.contains(index)) {
if (score > 0) {
score--;
}
if (score > 0) { score--; }
incorrectCells.add(index);
}
} else {
incorrectCells.remove(index);
}
_checkIfBoardIsFull();
}
});
}
}
void _checkIfBoardIsFull() {
if (!puzzleCells.contains(0) && !isValidating) {
_validateGame();
}
}
void onNumberTapped(int numberValue) {
setState(() {
if (selectedNumberPad == numberValue) {
@@ -185,7 +143,6 @@ class _GameScreenState extends State<GameScreen> {
}
});
}
void onUndoTapped() {
if (incorrectCells.isNotEmpty) {
int errorIndex = incorrectCells.first;
@@ -196,18 +153,14 @@ class _GameScreenState extends State<GameScreen> {
});
}
else if (selectedIndex != null && originalCells[selectedIndex!] == 0) {
setState(() {
puzzleCells[selectedIndex!] = 0;
});
setState(() { puzzleCells[selectedIndex!] = 0; });
}
}
void onHintTapped() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('힌트 기능은 준비 중입니다.')),
);
}
void _onRestartGameTapped() {
setState(() {
puzzleCells = originalCells.toList();
@@ -216,21 +169,19 @@ class _GameScreenState extends State<GameScreen> {
selectedNumberPad = null;
score = 5;
_resetBoardZoom();
timer?.cancel();
secondsElapsed = 0;
startTimer();
});
}
void _onQuitGameTapped() {
Navigator.of(context).pop();
}
void _resetBoardZoom() {
_transformationController.value = Matrix4.identity();
}
/// 🔽 [수정] _validateGame (Navigation 로직 변경)
Future<void> _validateGame() async {
if (isValidating) return;
setState(() { isValidating = true; });
@@ -246,9 +197,6 @@ class _GameScreenState extends State<GameScreen> {
if (result) {
if(mounted) {
// 🔽 [수정] _showRankingDialog() 호출 대신
// 공통 게임 완료 화면(GameCompletionScreen)으로 이동
// 1. 점수 포맷터 정의
String formatSudokuScore(int primary, int? secondary) {
final min = (primary ~/ 60).toString().padLeft(2, '0');
@@ -260,8 +208,6 @@ class _GameScreenState extends State<GameScreen> {
// 2. 레벨 저장 콜백 정의
Future<void> saveSudokuProgress(String playerName) async {
// (playerName은 공통 화면이 IdentityService로 저장하므로 여기선 사용 안 함)
final int currentMaxLevel = await _identityService.getMaxUnlockedLevel();
if (currentMaxLevel < 99) {
if (widget.levelIndex >= currentMaxLevel) {
@@ -275,8 +221,8 @@ class _GameScreenState extends State<GameScreen> {
}
}
// 3. 화면 이동
Navigator.pushReplacement(
// 3. [수정] 'pushReplacement' 대신 'await push' 사용
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GameCompletionScreen(
@@ -289,16 +235,16 @@ class _GameScreenState extends State<GameScreen> {
userName: widget.userName,
scoreFormatter: formatSudokuScore,
onProgressSave: saveSudokuProgress,
onScreenClose: () {
// 공통 화면에서 '닫기'를 누르면 게임 화면도 닫힘
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
// ❌ onScreenClose 제거
),
),
),
);
// 4. [추가] 랭킹 화면에서 돌아오면, 게임 화면(self)을 닫고 로비로 돌아감
if (mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
}
} else {
if(mounted) {
@@ -322,15 +268,13 @@ class _GameScreenState extends State<GameScreen> {
}
}
// ❌ [삭제] _showRankingDialog() 메서드 전체 (약 150줄) 삭제
// ( ... build, _buildPortraitLayout, _buildLandscapeLayout ... )
// ( ... _buildGameInfoWidget, _buildSudokuBoardWidget, _buildControlPanelWidget ... )
// ( ... 이 메서드들은 모두 동일합니다 ... )
@override
Widget build(BuildContext context) {
context.watch<ThemeNotifier>();
String formattedTime =
'${(secondsElapsed ~/ 60).toString().padLeft(2, '0')}:${(secondsElapsed % 60).toString().padLeft(2, '0')}';
String formattedTime = '${(secondsElapsed ~/ 60).toString().padLeft(2, '0')}:${(secondsElapsed % 60).toString().padLeft(2, '0')}';
final Map<int, int> numberCounts = {};
for (int i = 1; i <= gridSize; i++) { numberCounts[i] = 0; }
for (int cellValue in puzzleCells) {
@@ -338,7 +282,6 @@ class _GameScreenState extends State<GameScreen> {
numberCounts[cellValue] = (numberCounts[cellValue] ?? 0) + 1;
}
}
return Scaffold(
body: SafeArea(
child: Column(
@@ -355,16 +298,14 @@ class _GameScreenState extends State<GameScreen> {
},
),
),
const AdBannerWidget(), // 👈 [A] feature_common의 AdBannerWidget
const AdBannerWidget(),
],
),
),
);
}
Widget _buildPortraitLayout(BuildContext context, Map<int, int> numberCounts, BoxConstraints constraints, String formattedTime) {
final double boardWidth = (constraints.maxWidth > 600) ? 600 : constraints.maxWidth;
return Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: boardWidth),
@@ -399,26 +340,21 @@ class _GameScreenState extends State<GameScreen> {
),
);
}
Widget _buildLandscapeLayout(BuildContext context, Map<int, int> numberCounts, BoxConstraints constraints, String formattedTime) {
const double infoBarHeight = 60.0;
double boardWidth = constraints.maxHeight - infoBarHeight - 32.0;
double controlPanelWidth;
const double numberPadScaleRatio = 0.6;
double padWidth = boardWidth * numberPadScaleRatio;
if (padWidth < 200) padWidth = 200;
if (padWidth > 350) padWidth = 350;
controlPanelWidth = padWidth + 100;
double totalWidth = boardWidth + controlPanelWidth + 16.0;
if (totalWidth > (constraints.maxWidth - 32.0)) {
double scale = (constraints.maxWidth - 32.0) / totalWidth;
boardWidth *= scale;
controlPanelWidth *= scale;
}
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
@@ -451,7 +387,6 @@ class _GameScreenState extends State<GameScreen> {
),
);
}
Widget _buildGameInfoWidget(String formattedTime) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
@@ -462,7 +397,6 @@ class _GameScreenState extends State<GameScreen> {
],
);
}
Widget _buildSudokuBoardWidget() {
return GestureDetector(
onLongPress: _resetBoardZoom,
@@ -484,21 +418,16 @@ class _GameScreenState extends State<GameScreen> {
),
);
}
Widget _buildControlPanelWidget(BuildContext context, Map<int, int> numberCounts, {required bool isLandscape, required double boardWidth}) {
final ThemeData themeData = Theme.of(context);
const double numberPadScaleRatio = 0.6;
double? padMaxWidth;
if (!isLandscape) {
padMaxWidth = boardWidth * numberPadScaleRatio;
} else {
padMaxWidth = boardWidth * numberPadScaleRatio;
if (padMaxWidth < 200) padMaxWidth = 200;
}
Widget numberPadGrid = ConstrainedBox(
constraints: BoxConstraints(maxWidth: padMaxWidth ?? double.infinity),
child: NumberPad(
@@ -510,7 +439,6 @@ class _GameScreenState extends State<GameScreen> {
isLandscape: isLandscape,
),
);
Widget leftButtons = Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
@@ -527,7 +455,6 @@ class _GameScreenState extends State<GameScreen> {
),
],
);
Widget rightButtons = Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
@@ -544,7 +471,6 @@ class _GameScreenState extends State<GameScreen> {
),
],
);
if (isLandscape) {
return Column(
mainAxisSize: MainAxisSize.min,
@@ -21,25 +21,40 @@ class SudokuLobbyScreen extends StatefulWidget {
class _SudokuLobbyScreenState extends State<SudokuLobbyScreen> {
int _maxUnlockedLevel = 1;
Map<int, (int, int)> _rankHistory = {};
String? _userName;
// ❌ String? _userName; (SessionNotifier가 관리)
late String _selectedThemeName;
bool _isLoading = false;
// 🔽 [수정] SessionNotifier를 사용하기 위해 IdentityService 대신 추가
late final SessionNotifier _sessionNotifier;
final PuzzleService _puzzleService = PuzzleService();
final IdentityService _identityService = IdentityService();
final IdentityService _identityService = IdentityService(); // 👈 (save/load progress를 위해 유지)
@override
void initState() {
super.initState();
_selectedThemeName = AppThemes.random;
_loadProgress();
// 🔽 [수정] initState에서 SessionNotifier를 read
_sessionNotifier = context.read<SessionNotifier>();
// 🔽 [수정] _loadProgress가 랭킹까지 모두 새로고침 (최초 1회)
_loadProgress(forceRefreshRanks: true);
}
Future<void> _loadProgress() async {
/// 🔽 [수정] _loadProgress 메서드 (SessionNotifier 사용 및 로직 분리)
Future<void> _loadProgress({bool forceRefreshRanks = false}) async {
// 1. (가벼움) 레벨 정보 새로고침
final maxLevel = await _identityService.getMaxUnlockedLevel();
final String? myName = await _identityService.getSavedUserName();
if (mounted) { setState(() { _maxUnlockedLevel = maxLevel; _userName = myName; }); }
if (myName == null) return;
if (mounted) { setState(() { _maxUnlockedLevel = maxLevel; }); }
// 2. (무거움) 랭킹 정보 새로고침 (필요할 때만)
if (!forceRefreshRanks) return;
// 🔽 [수정] _sessionNotifier에서 유저 이름을 가져옴
final String? myName = _sessionNotifier.session?.userName;
if (myName == null) return; // 게스트이거나 아직 이름 저장을 안 함
try {
final Map<int, int> oldRankMap = await _identityService.getLastSavedRankMap();
List<Future<List<GameRankDto>>> rankFutures = [];
@@ -68,13 +83,23 @@ class _SudokuLobbyScreenState extends State<SudokuLobbyScreen> {
}
}
/// 🔽 [수정] _startGame 메서드 (SessionNotifier 사용)
Future<void> _startGame(GameLevel level) async {
setState(() { _isLoading = true; });
try {
// 1. [수정] SessionNotifier에서 유저 정보 가져오기
final session = _sessionNotifier.session;
if (session == null) {
throw Exception("세션이 로드되지 않았습니다.");
}
final String difficulty = level.levelIndex.toString();
final SudokuGameDto gameData = await _puzzleService.startGame(difficulty);
final String userId = await _identityService.getOrCreateUserId();
final String? userName = _userName;
final String userId = session.userId;
final String? userName = session.userName;
if (mounted) {
await Navigator.push(
context,
@@ -88,7 +113,11 @@ class _SudokuLobbyScreenState extends State<SudokuLobbyScreen> {
),
),
);
_loadProgress(); // 게임 끝나고 돌아오면 랭킹 새로고침
// 🔽 [핵심 수정]
// 랭킹(forceRefreshRanks: true)은 새로고침하지 않고,
// 레벨 잠금 상태(forceRefreshRanks: false)만 새로고침합니다.
_loadProgress(forceRefreshRanks: false);
}
} catch (e) {
if (mounted) {
@@ -105,7 +134,10 @@ class _SudokuLobbyScreenState extends State<SudokuLobbyScreen> {
@override
Widget build(BuildContext context) {
// 🔽 [수정] ThemeNotifier와 SessionNotifier를 모두 watch
context.watch<ThemeNotifier>(); // 테마 감지
context.watch<SessionNotifier>(); // 👈 세션 변경(로그인/로그아웃) 감지
final bool allLevelsUnlocked = _maxUnlockedLevel >= 99;
final theme = Theme.of(context);
@@ -174,68 +206,73 @@ class _SudokuLobbyScreenState extends State<SudokuLobbyScreen> {
),
// 레벨 목록 ListView
Expanded(
child: ListView.builder(
itemCount: AppLevels.allLevels.length,
itemBuilder: (context, index) {
final GameLevel level = AppLevels.allLevels[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);
// 🔽 [수정] RefreshIndicator 추가 (당겨서 랭킹 새로고침)
child: RefreshIndicator(
onRefresh: () => _loadProgress(forceRefreshRanks: true),
child: ListView.builder(
itemCount: AppLevels.allLevels.length,
itemBuilder: (context, index) {
// ... (이하 ListTile 로직은 모두 동일)
final GameLevel level = AppLevels.allLevels[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.grey;
trailingWidget = const Icon(Icons.check_circle_outline_rounded, color: Colors.grey, size: 28);
subtitleText = "$rankStr (신규 진입)";
subtitleColor = Colors.blue;
trailingWidget = const Icon(Icons.new_releases_rounded, color: Colors.blue, size: 28);
}
} else {
subtitleText = "$rankStr (신규 진입)";
subtitleColor = Colors.blue;
trailingWidget = const Icon(Icons.new_releases_rounded, color: Colors.blue, size: 28);
if (oldRank > 0) {
subtitleText = "랭킹 이탈 (이전 ${oldRank}위)";
subtitleColor = Colors.orange;
trailingWidget = const Icon(Icons.warning_amber_rounded, color: Colors.orange, 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)
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,
),
);
},
),
),
),
],