...
This commit is contained in:
+334
-167
@@ -1,21 +1,31 @@
|
||||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:sudoku_app/models/sudoku_game_dto.dart';
|
||||
import 'package:sudoku_app/models/sudoku_theme.dart';
|
||||
import 'package:sudoku_app/models/unified_rank_dto.dart';
|
||||
import 'package:sudoku_app/services/puzzle_service.dart';
|
||||
import 'package:sudoku_app/services/identity_service.dart';
|
||||
import 'package:sudoku_app/widgets/ad_banner_widget.dart';
|
||||
import 'package:sudoku_app/widgets/number_pad.dart';
|
||||
import 'package:sudoku_app/widgets/sudoku_board.dart';
|
||||
import 'package:sudoku_app/models/game_rank_dto.dart';
|
||||
|
||||
// 랭킹 팝업의 2단계 UI 상태를 관리하기 위한 enum
|
||||
enum _RankSubmissionStep { enterName, submitting, showList }
|
||||
|
||||
class GameScreen extends StatefulWidget {
|
||||
final SudokuGameDto gameData;
|
||||
final String themeName;
|
||||
final String userId;
|
||||
final String? userName;
|
||||
|
||||
const GameScreen({
|
||||
super.key,
|
||||
required this.gameData,
|
||||
required this.themeName,
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -24,6 +34,7 @@ class GameScreen extends StatefulWidget {
|
||||
|
||||
class _GameScreenState extends State<GameScreen> {
|
||||
final PuzzleService _puzzleService = PuzzleService();
|
||||
final IdentityService _identityService = IdentityService();
|
||||
|
||||
late final int blockSize;
|
||||
late final int gridSize;
|
||||
@@ -41,6 +52,11 @@ class _GameScreenState extends State<GameScreen> {
|
||||
Set<int> incorrectCells = {};
|
||||
bool isValidating = false;
|
||||
|
||||
_RankSubmissionStep _rankStep = _RankSubmissionStep.enterName;
|
||||
List<GameRankDto> _rankingList = [];
|
||||
String _submittedPlayerName = "";
|
||||
|
||||
|
||||
// "A" -> 10 (파싱용)
|
||||
int _charToInt(String char) {
|
||||
if (char == '0') return 0;
|
||||
@@ -96,7 +112,6 @@ class _GameScreenState extends State<GameScreen> {
|
||||
|
||||
if (selectedNumberPad != null) {
|
||||
|
||||
// 오답 블로킹
|
||||
if (incorrectCells.isNotEmpty && !incorrectCells.contains(index)) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
@@ -104,15 +119,13 @@ class _GameScreenState extends State<GameScreen> {
|
||||
duration: Duration(seconds: 1),
|
||||
),
|
||||
);
|
||||
return; // 입력 처리 중단
|
||||
return;
|
||||
}
|
||||
|
||||
final int numberValue = selectedNumberPad!;
|
||||
puzzleCells[index] = numberValue;
|
||||
|
||||
// 정답과 비교
|
||||
if (numberValue != solutionCells[index]) {
|
||||
// 점수 차감
|
||||
if (!incorrectCells.contains(index)) {
|
||||
if (score > 0) {
|
||||
score--;
|
||||
@@ -160,16 +173,38 @@ class _GameScreenState extends State<GameScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
void _onRestartGameTapped() {
|
||||
setState(() {
|
||||
puzzleCells = originalCells.toList();
|
||||
incorrectCells.clear();
|
||||
selectedIndex = null;
|
||||
selectedNumberPad = null;
|
||||
score = 5;
|
||||
|
||||
timer?.cancel();
|
||||
secondsElapsed = 0;
|
||||
startTimer();
|
||||
});
|
||||
}
|
||||
|
||||
void _onQuitGameTapped() {
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
|
||||
Future<void> _validateGame() async {
|
||||
// ... (기존과 동일)
|
||||
if (isValidating) return;
|
||||
setState(() { isValidating = true; });
|
||||
|
||||
timer?.cancel();
|
||||
String currentAnswer = puzzleCells.map(_intToChar).join('');
|
||||
|
||||
try {
|
||||
final bool result = await _puzzleService.validateSolution(
|
||||
widget.gameData.question, currentAnswer, blockSize,
|
||||
widget.gameData.puzzleId,
|
||||
currentAnswer,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
if(mounted) _showRankingDialog();
|
||||
} else {
|
||||
@@ -194,36 +229,144 @@ class _GameScreenState extends State<GameScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
// 랭킹 등록 팝업 (2단계 UI)
|
||||
void _showRankingDialog() {
|
||||
// ... (기존과 동일)
|
||||
final nameController = TextEditingController();
|
||||
final nameController = TextEditingController(text: widget.userName);
|
||||
bool isSubmitting = false;
|
||||
final bool hasExistingName = widget.userName != null;
|
||||
|
||||
_rankStep = _RankSubmissionStep.enterName;
|
||||
_rankingList = [];
|
||||
_submittedPlayerName = "";
|
||||
String? dialogErrorMessage; // 👈 [신규] 팝업 내부 에러 메시지
|
||||
|
||||
final String contextId = "SUDOKU_${gridSize}x${gridSize}_L${_difficultyLevel(widget.gameData.question)}";
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (ctx) {
|
||||
return StatefulBuilder(
|
||||
builder: (context, setDialogState) {
|
||||
return AlertDialog(
|
||||
title: const Text('🎉 성공! 기록을 남겨주세요.'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('($contextId)'),
|
||||
Text('완료 시간: $secondsElapsed 초'),
|
||||
const SizedBox(height: 20),
|
||||
TextField(
|
||||
controller: nameController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '이름 (10자 이내)',
|
||||
border: OutlineInputBorder(),
|
||||
|
||||
Widget closeButton = TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(ctx).pop();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text('닫기'),
|
||||
);
|
||||
|
||||
Widget rankListWidget = Expanded(
|
||||
child: _rankingList.isEmpty
|
||||
? const Center(child: Text("현재 랭킹이 없습니다."))
|
||||
: ListView.builder(
|
||||
itemCount: _rankingList.length,
|
||||
shrinkWrap: true,
|
||||
itemBuilder: (context, index) {
|
||||
final rank = _rankingList[index];
|
||||
final bool isMe = rank.playerName == _submittedPlayerName;
|
||||
int displayScore = 5 - (rank.secondaryScore ?? 5);
|
||||
|
||||
final min = (rank.primaryScore ~/ 60).toString().padLeft(2, '0');
|
||||
final sec = (rank.primaryScore % 60).toString().padLeft(2, '0');
|
||||
final time = '$min:$sec';
|
||||
|
||||
return ListTile(
|
||||
selected: isMe,
|
||||
selectedTileColor: Colors.blue.shade100,
|
||||
leading: Text('${index + 1}.', style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
title: Text(rank.playerName, style: TextStyle(fontWeight: isMe ? FontWeight.bold : FontWeight.normal)),
|
||||
trailing: Text('$time (Score: $displayScore)', style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.black87)),
|
||||
);
|
||||
},
|
||||
),
|
||||
maxLength: 10,
|
||||
);
|
||||
|
||||
Widget nameEntryWidget = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('완료 시간: $secondsElapsed 초 / 남은 점수: $score 점'),
|
||||
const SizedBox(height: 20),
|
||||
TextField(
|
||||
controller: nameController,
|
||||
readOnly: hasExistingName,
|
||||
decoration: InputDecoration(
|
||||
labelText: hasExistingName ? '등록된 이름' : '이름 (10자 이내)',
|
||||
border: const OutlineInputBorder(),
|
||||
// 🔽 [신규] 에러 메시지가 있으면 TextField에 에러 스타일 적용
|
||||
errorText: dialogErrorMessage,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
maxLength: 10,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Widget submitButton = ElevatedButton(
|
||||
onPressed: () async {
|
||||
final playerName = nameController.text.trim();
|
||||
if (playerName.isEmpty) {
|
||||
// SnackBar 대신 팝업 내부 에러로 변경
|
||||
setDialogState(() {
|
||||
dialogErrorMessage = "이름을 입력해주세요.";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setDialogState(() {
|
||||
_rankStep = _RankSubmissionStep.submitting;
|
||||
_submittedPlayerName = playerName;
|
||||
dialogErrorMessage = null; // 👈 [신규] 에러 메시지 초기화
|
||||
});
|
||||
|
||||
final rankDto = UnifiedRankDto(
|
||||
userId: widget.userId,
|
||||
gameType: 'SUDOKU',
|
||||
contextId: contextId,
|
||||
playerName: playerName,
|
||||
primaryScore: secondsElapsed,
|
||||
secondaryScore: (5 - score),
|
||||
);
|
||||
|
||||
try {
|
||||
await _puzzleService.submitRank(rankDto);
|
||||
|
||||
if (!hasExistingName) {
|
||||
await _identityService.saveUserName(playerName);
|
||||
}
|
||||
|
||||
final ranks = await _puzzleService.fetchRanks('SUDOKU', contextId);
|
||||
|
||||
setDialogState(() {
|
||||
_rankingList = ranks;
|
||||
_rankStep = _RankSubmissionStep.showList;
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
// 🔽 [수정] 랭킹 등록 실패 시 (이름 중복 등)
|
||||
log("!!! 랭킹 등록 실패 !!!", error: e);
|
||||
|
||||
setDialogState(() {
|
||||
_rankStep = _RankSubmissionStep.enterName; // 1단계(이름 입력)로 복귀
|
||||
// 👈 [신규] 서버 에러 메시지를 팝업에 표시
|
||||
dialogErrorMessage = e.toString().replaceFirst("Exception: ", "");
|
||||
});
|
||||
// ❌ SnackBar 제거
|
||||
}
|
||||
},
|
||||
child: const Text('랭킹 등록'),
|
||||
);
|
||||
|
||||
Widget dialogContent;
|
||||
if (_rankStep == _RankSubmissionStep.showList) {
|
||||
dialogContent = rankListWidget;
|
||||
} else {
|
||||
dialogContent = nameEntryWidget;
|
||||
}
|
||||
|
||||
List<Widget> dialogActions;
|
||||
if (_rankStep == _RankSubmissionStep.enterName) {
|
||||
dialogActions = [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(ctx).pop();
|
||||
@@ -231,53 +374,31 @@ class _GameScreenState extends State<GameScreen> {
|
||||
},
|
||||
child: const Text('닫기'),
|
||||
),
|
||||
isSubmitting
|
||||
? const Padding(
|
||||
padding: EdgeInsets.all(8.0),
|
||||
child: CircularProgressIndicator(),
|
||||
)
|
||||
: ElevatedButton(
|
||||
onPressed: () async {
|
||||
final playerName = nameController.text.trim();
|
||||
if (playerName.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('이름을 입력해주세요.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setDialogState(() { isSubmitting = true; });
|
||||
final rankDto = UnifiedRankDto(
|
||||
gameType: 'SUDOKU',
|
||||
contextId: contextId,
|
||||
playerName: playerName,
|
||||
primaryScore: secondsElapsed,
|
||||
secondaryScore: null,
|
||||
);
|
||||
try {
|
||||
await _puzzleService.submitRank(rankDto);
|
||||
if (!mounted) return;
|
||||
Navigator.of(ctx).pop();
|
||||
Navigator.of(context).pop();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('랭킹이 등록되었습니다!')),
|
||||
);
|
||||
} catch (e) {
|
||||
setDialogState(() { isSubmitting = false; });
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(e.toString())),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: const Text('랭킹 등록'),
|
||||
),
|
||||
],
|
||||
submitButton
|
||||
];
|
||||
} else if (_rankStep == _RankSubmissionStep.submitting) {
|
||||
dialogActions = [const CircularProgressIndicator()];
|
||||
} else {
|
||||
dialogActions = [closeButton];
|
||||
}
|
||||
|
||||
return AlertDialog(
|
||||
title: Text(_rankStep == _RankSubmissionStep.showList
|
||||
? '🏆 상위 10개 랭킹 ($contextId)'
|
||||
: '🎉 성공! 기록을 남겨주세요.'),
|
||||
content: SizedBox(
|
||||
width: 400,
|
||||
height: _rankStep == _RankSubmissionStep.showList ? 400 : null,
|
||||
child: dialogContent,
|
||||
),
|
||||
actions: dialogActions,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
int _difficultyLevel(String question) {
|
||||
int holes = question.split('').where((c) => c == '0').length;
|
||||
double holeRatio = holes / (gridSize * gridSize);
|
||||
@@ -290,7 +411,6 @@ class _GameScreenState extends State<GameScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 🔽 [수정] 타이머 텍스트를 AppBar로 이동시키기 위해 build 메서드 상단으로 이동
|
||||
String formattedTime =
|
||||
'${(secondsElapsed ~/ 60).toString().padLeft(2, '0')}:${(secondsElapsed % 60).toString().padLeft(2, '0')}';
|
||||
|
||||
@@ -303,94 +423,107 @@ class _GameScreenState extends State<GameScreen> {
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Sudoku'), // 👈 [수정] 테마 이름 제거
|
||||
actions: [
|
||||
// 🔽 [수정] AppBar 우측에 타이머 추가
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
formattedTime,
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
body: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
bool isLandscape = constraints.maxWidth > constraints.maxHeight;
|
||||
if (isLandscape) {
|
||||
return _buildLandscapeLayout(context, numberCounts, constraints, formattedTime);
|
||||
} else {
|
||||
return _buildPortraitLayout(context, numberCounts, constraints, formattedTime);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
// 1. 게임 콘텐츠 영역
|
||||
Expanded(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
bool isLandscape = constraints.maxWidth > constraints.maxHeight;
|
||||
if (isLandscape) {
|
||||
return _buildLandscapeLayout(context, numberCounts);
|
||||
} else {
|
||||
return _buildPortraitLayout(context, numberCounts);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
// 2. 광고 배너
|
||||
const AdBannerWidget(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 🔽 [수정] formattedTime 파라미터 제거
|
||||
Widget _buildPortraitLayout(BuildContext context, Map<int, int> numberCounts) {
|
||||
return Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 600),
|
||||
child: SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
children: [
|
||||
_buildGameInfoWidget(), // 👈 [수정] 파라미터 제거
|
||||
const SizedBox(height: 15),
|
||||
_buildSudokuBoardWidget(),
|
||||
const SizedBox(height: 15),
|
||||
_buildNumberPadWidget(context, numberCounts, isLandscape: false),
|
||||
],
|
||||
),
|
||||
),
|
||||
const AdBannerWidget(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 🔽 [수정] formattedTime 파라미터 제거
|
||||
Widget _buildLandscapeLayout(BuildContext context, Map<int, int> numberCounts) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 6,
|
||||
child: Center(
|
||||
child: AspectRatio(
|
||||
aspectRatio: 1.0,
|
||||
child: _buildSudokuBoardWidget(),
|
||||
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),
|
||||
child: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0),
|
||||
child: _buildGameInfoWidget(formattedTime),
|
||||
),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
_buildSudokuBoardWidget(),
|
||||
const SizedBox(height: 15),
|
||||
_buildNumberPadWidget(context, numberCounts, isLandscape: false, boardWidth: boardWidth),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLandscapeLayout(BuildContext context, Map<int, int> numberCounts, BoxConstraints constraints, String formattedTime) {
|
||||
|
||||
const double infoBarHeight = 60.0;
|
||||
double boardWidth = constraints.maxHeight - infoBarHeight - 32.0;
|
||||
|
||||
const double numberPadScaleRatio = 0.6;
|
||||
double padWidth = boardWidth * numberPadScaleRatio;
|
||||
|
||||
if (padWidth < 200) padWidth = 200;
|
||||
if (padWidth > 350) padWidth = 350;
|
||||
|
||||
double totalWidth = boardWidth + (padWidth + 100) + 16.0;
|
||||
if (totalWidth > (constraints.maxWidth - 32.0)) {
|
||||
double scale = (constraints.maxWidth - 32.0) / totalWidth;
|
||||
boardWidth *= scale;
|
||||
padWidth *= scale;
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
children: [
|
||||
_buildGameInfoWidget(formattedTime),
|
||||
Expanded(
|
||||
flex: 4,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
_buildGameInfoWidget(), // 👈 [수정] 파라미터 제거
|
||||
const SizedBox(height: 20),
|
||||
_buildNumberPadWidget(context, numberCounts, isLandscape: true),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: boardWidth,
|
||||
child: _buildSudokuBoardWidget(),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
SizedBox(
|
||||
width: padWidth + 100,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
_buildNumberPadWidget(context, numberCounts, isLandscape: true, boardWidth: boardWidth),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -398,16 +531,13 @@ class _GameScreenState extends State<GameScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// 🔽 [수정] 상단 정보 (점수, 힌트, 되돌리기) - 타이머 제거
|
||||
Widget _buildGameInfoWidget() {
|
||||
Widget _buildGameInfoWidget(String formattedTime) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
// 1. 점수
|
||||
Text('SCORE: $score', style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
|
||||
// 2. 버튼 그룹 (힌트, 되돌리기)
|
||||
Text(formattedTime, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@@ -427,7 +557,6 @@ class _GameScreenState extends State<GameScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// 게임 보드 (변경 없음)
|
||||
Widget _buildSudokuBoardWidget() {
|
||||
return SudokuBoard(
|
||||
blockSize: blockSize,
|
||||
@@ -441,24 +570,62 @@ class _GameScreenState extends State<GameScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// 숫자 패드 (변경 없음)
|
||||
Widget _buildNumberPadWidget(BuildContext context, Map<int, int> numberCounts, {required bool isLandscape}) {
|
||||
double? maxWidth = !isLandscape
|
||||
? 600 * 0.6
|
||||
: null;
|
||||
Widget _buildNumberPadWidget(BuildContext context, Map<int, int> numberCounts, {required bool isLandscape, required double boardWidth}) {
|
||||
const double numberPadScaleRatio = 0.6;
|
||||
double? padMaxWidth;
|
||||
|
||||
if (!isLandscape) {
|
||||
padMaxWidth = boardWidth * numberPadScaleRatio;
|
||||
} else {
|
||||
padMaxWidth = null;
|
||||
}
|
||||
|
||||
return Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: maxWidth ?? double.infinity),
|
||||
child: NumberPad(
|
||||
blockSize: blockSize,
|
||||
theme: activeTheme,
|
||||
numberCounts: numberCounts,
|
||||
selectedNumber: selectedNumberPad,
|
||||
onNumberTapped: onNumberTapped,
|
||||
isLandscape: isLandscape,
|
||||
),
|
||||
Widget numberPadGrid = ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: padMaxWidth ?? double.infinity),
|
||||
child: NumberPad(
|
||||
blockSize: blockSize,
|
||||
theme: activeTheme,
|
||||
numberCounts: numberCounts,
|
||||
selectedNumber: selectedNumberPad,
|
||||
onNumberTapped: onNumberTapped,
|
||||
isLandscape: isLandscape,
|
||||
),
|
||||
);
|
||||
|
||||
Widget quitButton = IconButton(
|
||||
icon: Icon(Icons.close, color: Colors.red.shade700, size: 30),
|
||||
onPressed: _onQuitGameTapped,
|
||||
tooltip: "게임 종료",
|
||||
);
|
||||
|
||||
Widget restartButton = IconButton(
|
||||
icon: Icon(Icons.refresh, color: Colors.blue.shade700, size: 30),
|
||||
onPressed: _onRestartGameTapped,
|
||||
tooltip: "다시하기",
|
||||
);
|
||||
|
||||
if (isLandscape) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
numberPadGrid,
|
||||
const SizedBox(height: 10),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [quitButton, restartButton],
|
||||
)
|
||||
],
|
||||
);
|
||||
} else {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
quitButton,
|
||||
Expanded(child: numberPadGrid),
|
||||
restartButton,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import 'package:sudoku_app/models/sudoku_theme.dart';
|
||||
import 'package:sudoku_app/screens/game_screen.dart';
|
||||
import 'package:sudoku_app/screens/ranking_screen.dart';
|
||||
import 'package:sudoku_app/services/puzzle_service.dart';
|
||||
import 'package:sudoku_app/services/identity_service.dart'; // 👈 ID 서비스 임포트
|
||||
import 'package:sudoku_app/widgets/ad_banner_widget.dart';
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
@@ -14,38 +15,39 @@ class HomeScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> {
|
||||
// 난이도
|
||||
double _difficultyLevel = 2.0;
|
||||
final List<String> levelLabels = ["Easy", "Normal", "Medium", "Hard", "Expert"];
|
||||
// 8단계 난이도
|
||||
double _difficultyLevel = 4.0; // 1.0 ~ 8.0 (기본값 Level 4: 중급 9x9)
|
||||
final List<String> levelLabels = [
|
||||
"입문 (4x4)", "초급 (4x4)",
|
||||
"쉬움 (9x9)", "중급 (9x9)", "어려움 (9x9)",
|
||||
"전문가 (16x16)", "마스터 (16x16)", "지옥 (16x16)"
|
||||
];
|
||||
|
||||
// 그리드 크기
|
||||
double _blockSize = 3.0;
|
||||
// 🔽 [수정] 16x16, 25x25 옵션 제거
|
||||
final List<String> sizeLabels = ["4x4", "9x9"];
|
||||
|
||||
// 테마 이름
|
||||
late String _selectedThemeName;
|
||||
|
||||
bool isLoading = false;
|
||||
final PuzzleService _puzzleService = PuzzleService();
|
||||
final IdentityService _identityService = IdentityService(); // 👈 ID 서비스 초기화
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 기본 테마를 '랜덤' 이름으로 설정
|
||||
_selectedThemeName = AppThemes.random;
|
||||
_selectedThemeName = AppThemes.random; // 기본 테마 '랜덤'
|
||||
}
|
||||
|
||||
Future<void> _startGame() async {
|
||||
setState(() { isLoading = true; });
|
||||
|
||||
try {
|
||||
final String level = _difficultyLevel.round().toString();
|
||||
final String blockSize = _blockSize.round().toString();
|
||||
// 1. 난이도 값(String) 전달
|
||||
final String difficulty = _difficultyLevel.round().toString();
|
||||
|
||||
final SudokuGameDto gameData = await _puzzleService.startGame(level, blockSize);
|
||||
// 2. 서버에서 게임 데이터 가져오기
|
||||
final SudokuGameDto gameData = await _puzzleService.startGame(difficulty);
|
||||
|
||||
// 3. 로컬에서 앱-고유 ID와 저장된 이름 가져오기
|
||||
final String userId = await _identityService.getOrCreateUserId();
|
||||
final String? userName = await _identityService.getSavedUserName();
|
||||
|
||||
// 선택된 '테마 이름(String)'을 그대로 전달
|
||||
if (mounted) {
|
||||
Navigator.push(
|
||||
context,
|
||||
@@ -53,6 +55,8 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
builder: (context) => GameScreen(
|
||||
gameData: gameData,
|
||||
themeName: _selectedThemeName,
|
||||
userId: userId, // 👈 ID 전달
|
||||
userName: userName, // 👈 이름 전달
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -76,6 +80,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
appBar: AppBar(title: const Text('스도쿠 게임')),
|
||||
body: LayoutBuilder( // 비율 기반 레이아웃
|
||||
builder: (context, constraints) {
|
||||
// 너비/높이 비율 변수 (0.6 = 너비가 높이의 60%를 넘지 않도록 함)
|
||||
const double maxContentRatio = 0.6;
|
||||
final double constrainedWidth = constraints.maxHeight * maxContentRatio;
|
||||
|
||||
@@ -91,36 +96,22 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
// 1. 난이도 선택
|
||||
// 1. 난이도 선택 (8단계)
|
||||
const Text("난이도", style: TextStyle(fontSize: 18)),
|
||||
Text(
|
||||
levelLabels[_difficultyLevel.round() - 1],
|
||||
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Colors.blue),
|
||||
),
|
||||
Slider(
|
||||
value: _difficultyLevel,
|
||||
min: 1.0, max: 5.0, divisions: 4,
|
||||
min: 1.0, max: 8.0, divisions: 7, // 8단계
|
||||
label: levelLabels[_difficultyLevel.round() - 1],
|
||||
onChanged: (newValue) => setState(() { _difficultyLevel = newValue; }),
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 2. 그리드 크기 선택
|
||||
const Text("그리드 크기", style: TextStyle(fontSize: 18)),
|
||||
Text(
|
||||
// 🔽 [수정] 인덱스 매핑 변경 (2.0 -> index 0)
|
||||
sizeLabels[_blockSize.round() - 2],
|
||||
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Colors.deepOrange),
|
||||
),
|
||||
Slider(
|
||||
value: _blockSize,
|
||||
// 🔽 [수정] 최대값을 3.0으로, divisions를 1로 변경
|
||||
min: 2.0, max: 3.0, divisions: 1,
|
||||
label: sizeLabels[_blockSize.round() - 2],
|
||||
activeColor: Colors.deepOrange,
|
||||
onChanged: (newValue) => setState(() { _blockSize = newValue; }),
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 3. 테마 선택 (String 기반)
|
||||
// 2. 테마 선택 (String 기반)
|
||||
const Text("테마", style: TextStyle(fontSize: 18)),
|
||||
DropdownButton<String>(
|
||||
value: _selectedThemeName,
|
||||
@@ -150,11 +141,19 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// "랭킹 보기" 버튼
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
// 현재 슬라이더의 난이도 이름(String)을 가져옴
|
||||
final String currentDifficultyName = levelLabels[_difficultyLevel.round() - 1];
|
||||
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => const RankingScreen()),
|
||||
MaterialPageRoute(
|
||||
builder: (context) => RankingScreen(
|
||||
initialDifficultyName: currentDifficultyName,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: const Text('랭킹 보기'),
|
||||
|
||||
+114
-46
@@ -3,7 +3,13 @@ import 'package:sudoku_app/models/game_rank_dto.dart';
|
||||
import 'package:sudoku_app/services/puzzle_service.dart';
|
||||
|
||||
class RankingScreen extends StatefulWidget {
|
||||
const RankingScreen({super.key});
|
||||
// 🔽 [추가] 홈 화면에서 전달받을 초기 난이도 이름
|
||||
final String? initialDifficultyName;
|
||||
|
||||
const RankingScreen({
|
||||
super.key,
|
||||
this.initialDifficultyName, // 👈 생성자에 추가
|
||||
});
|
||||
|
||||
@override
|
||||
State<RankingScreen> createState() => _RankingScreenState();
|
||||
@@ -11,67 +17,129 @@ class RankingScreen extends StatefulWidget {
|
||||
|
||||
class _RankingScreenState extends State<RankingScreen> {
|
||||
final PuzzleService _puzzleService = PuzzleService();
|
||||
// FutureBuilder를 사용하여 비동기 데이터를 쉽게 처리
|
||||
late Future<List<GameRankDto>> _rankingFuture;
|
||||
|
||||
// 8단계 난이도에 맞는 Context ID 맵
|
||||
final Map<String, String> difficultyContexts = {
|
||||
"입문 (4x4)": "SUDOKU_4x4_L1",
|
||||
"초급 (4x4)": "SUDOKU_4x4_L2",
|
||||
"쉬움 (9x9)": "SUDOKU_9x9_L3",
|
||||
"중급 (9x9)": "SUDOKU_9x9_L4",
|
||||
"어려움 (9x9)": "SUDOKU_9x9_L5",
|
||||
"전문가 (16x16)": "SUDOKU_16x16_L6",
|
||||
"마스터 (16x16)": "SUDOKU_16x16_L7",
|
||||
"지옥 (16x16)": "SUDOKU_16x16_L8",
|
||||
};
|
||||
late String _selectedDifficulty;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 화면이 로드될 때 스도쿠의 전체 랭킹을 가져옴 (contextId = null)
|
||||
_rankingFuture = _puzzleService.fetchRanks('SUDOKU', null);
|
||||
// 🔽 [수정]
|
||||
// 1. HomeScreen에서 전달받은 값이 있는지 확인
|
||||
String defaultDifficulty = widget.initialDifficultyName ?? "중급 (9x9)";
|
||||
|
||||
// 2. (안전장치) 전달받은 값이 맵에 없으면(예: 향후 변경) 기본값 사용
|
||||
if (!difficultyContexts.containsKey(defaultDifficulty)) {
|
||||
defaultDifficulty = "중급 (9x9)";
|
||||
}
|
||||
|
||||
// 3. 랭킹 조회
|
||||
_fetchRanksForDifficulty(defaultDifficulty);
|
||||
}
|
||||
|
||||
// 점수(초)를 'mm:ss' 형식으로 변환
|
||||
String _formatScore(int seconds) {
|
||||
void _fetchRanksForDifficulty(String difficultyName) {
|
||||
setState(() {
|
||||
_selectedDifficulty = difficultyName;
|
||||
_rankingFuture = _puzzleService.fetchRanks('SUDOKU', difficultyContexts[_selectedDifficulty]);
|
||||
});
|
||||
}
|
||||
|
||||
// 시간(초)을 'mm:ss' 형식으로 변환
|
||||
String _formatTime(int seconds) {
|
||||
final min = (seconds ~/ 60).toString().padLeft(2, '0');
|
||||
final sec = (seconds % 60).toString().padLeft(2, '0');
|
||||
return '$min:$sec';
|
||||
}
|
||||
|
||||
// (5 - score)로 저장된 값을 -> "SCORE: 5"로 변환
|
||||
String _formatScore(int? storedScore) {
|
||||
int score = 5 - (storedScore ?? 5);
|
||||
return 'SCORE: $score';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('스도쿠 전체 랭킹')),
|
||||
body: FutureBuilder<List<GameRankDto>>(
|
||||
future: _rankingFuture,
|
||||
builder: (context, snapshot) {
|
||||
// 로딩 중일 때
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
// 에러 발생 시
|
||||
if (snapshot.hasError) {
|
||||
return Center(child: Text('랭킹 로딩 실패: ${snapshot.error}'));
|
||||
}
|
||||
// 데이터가 없거나 비어있을 때
|
||||
if (!snapshot.hasData || snapshot.data!.isEmpty) {
|
||||
return const Center(child: Text('등록된 랭킹이 없습니다.'));
|
||||
}
|
||||
appBar: AppBar(title: const Text('스도쿠 랭킹')),
|
||||
body: Column(
|
||||
children: [
|
||||
// 1. 난이도 선택 Dropdown
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: DropdownButton<String>(
|
||||
value: _selectedDifficulty, // 👈 initState에서 설정된 값으로 시작
|
||||
isExpanded: true,
|
||||
items: difficultyContexts.keys.map((String difficultyName) {
|
||||
return DropdownMenuItem<String>(
|
||||
value: difficultyName,
|
||||
child: Text(difficultyName),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (String? newValue) {
|
||||
if (newValue != null) {
|
||||
_fetchRanksForDifficulty(newValue);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
// 2. 랭킹 리스트
|
||||
Expanded(
|
||||
child: FutureBuilder<List<GameRankDto>>(
|
||||
future: _rankingFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snapshot.hasError) {
|
||||
return Center(child: Text('랭킹 로딩 실패: ${snapshot.error}'));
|
||||
}
|
||||
if (!snapshot.hasData || snapshot.data!.isEmpty) {
|
||||
return const Center(child: Text('등록된 랭킹이 없습니다.'));
|
||||
}
|
||||
|
||||
// 성공적으로 데이터를 가져왔을 때
|
||||
final ranks = snapshot.data!;
|
||||
return ListView.builder(
|
||||
itemCount: ranks.length,
|
||||
itemBuilder: (context, index) {
|
||||
final rank = ranks[index];
|
||||
return ListTile(
|
||||
leading: Text(
|
||||
'${index + 1}.',
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
title: Text(rank.playerName, style: const TextStyle(fontSize: 18)),
|
||||
trailing: Text(
|
||||
_formatScore(rank.primaryScore), // 시간(초)을 mm:ss로 표시
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.blue,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
final ranks = snapshot.data!;
|
||||
return ListView.builder(
|
||||
itemCount: ranks.length,
|
||||
itemBuilder: (context, index) {
|
||||
final rank = ranks[index];
|
||||
return ListTile(
|
||||
leading: Text(
|
||||
'${index + 1}.',
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
title: Text(rank.playerName, style: const TextStyle(fontSize: 18)),
|
||||
trailing: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
_formatTime(rank.primaryScore),
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue),
|
||||
),
|
||||
Text(
|
||||
_formatScore(rank.secondaryScore),
|
||||
style: const TextStyle(fontSize: 12, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user