This commit is contained in:
2025-11-07 17:07:22 +09:00
parent db5bb090f4
commit 9225ee6026
138 changed files with 6041 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart'; // 👈 [추가]
import 'package:sudoku_app/screens/home_screen.dart';
// 🔽 [수정] main 함수를 async로 변경
void main() async {
// 🔽 [추가] Flutter 바인딩 초기화
WidgetsFlutterBinding.ensureInitialized();
// 🔽 [추가] 애드몹 SDK 초기화
await MobileAds.instance.initialize();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Sudoku',
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true,
),
home: const HomeScreen(),
);
}
}
+15
View File
@@ -0,0 +1,15 @@
// lib/models/game_rank_dto.dart
class GameRankDto {
final String playerName;
final int primaryScore; // 스도쿠에서는 시간(초)
GameRankDto({required this.playerName, required this.primaryScore});
factory GameRankDto.fromJson(Map<String, dynamic> json) {
return GameRankDto(
playerName: json['playerName'],
primaryScore: (json['primaryScore'] as num).toInt(),
);
}
}
+26
View File
@@ -0,0 +1,26 @@
// lib/models/sudoku_game_dto.dart
// 🔽 [수정] PuzzleData.kt의 새 DTO (puzzleId -> blockSize)
class SudokuGameDto {
final String question;
final String solution;
final int blockSize; // 예: 3 (3x3 블록)
// 🔽 [추가] blockSize로부터 gridSize 계산 (예: 9)
final int gridSize;
SudokuGameDto({
required this.question,
required this.solution,
required this.blockSize,
}) : gridSize = blockSize * blockSize; // 생성 시 gridSize 자동 계산
factory SudokuGameDto.fromJson(Map<String, dynamic> json) {
int bs = json['blockSize'] ?? 3;
return SudokuGameDto(
question: json['question'],
solution: json['solution'],
blockSize: bs,
);
}
}
+112
View File
@@ -0,0 +1,112 @@
// lib/models/sudoku_theme.dart
import 'package:flutter/material.dart';
// 1. SudokuTheme 클래스
// '게임 시작' 시점에 동적으로 생성될 객체입니다.
class SudokuTheme {
final String name; // "숫자", "알파벳", "과일"
final List<String> symbols; // 👈 '게임에 실제 사용할' 무작위로 뽑힌 기호 리스트
const SudokuTheme({required this.name, required this.symbols});
// 1-based 정수(1)를 테마 기호("🍎")로 변환
String getSymbol(int value) {
if (value > 0 && value <= symbols.length) {
return symbols[value - 1]; // 1 -> index 0
}
return '?';
}
// 테마 기호("🍎")를 1-based 정수(1)로 변환
int getValue(String symbol) {
int index = symbols.indexOf(symbol);
if (index != -1) {
return index + 1; // index 0 -> 1
}
return 0;
}
}
// 2. AppThemes 클래스 (테마 저장소 역할)
class AppThemes {
// --- 테마 이름 정의 ---
static const String random = "랜덤";
static const String numbers = "숫자";
static const String letters = "알파벳";
static const String fruits = "과일";
static const String korean = "한글";
static const String animals = "동물";
// --- 1. 거대한 '상징 풀' 정의 (25개 이상) ---
static const List<String> _numberPool = [
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"
];
static const List<String> _letterPool = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
];
static const List<String> _fruitPool = [
"🍎", "🍌", "🍇", "🍓", "🍊", "🍋", "🍉", "🍑", "🍒", "🥝", "🥥", "🍍", "🥑", "🍆", "🍅", "🌽",
"🥕", "🫑", "🌶️", "🥦", "🥬", "🥒", "🍄", "🥜", "🫘", "🍏", "🍐", "🍈", "🥭", "🫒"
];
static const List<String> _koreanPool = [
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", ""
];
static const List<String> _animalPool = [
"🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨", "🐯", "🦁", "🐮", "🐷", "🐸", "🐵", "🐔",
"🐧", "🐦", "🐤", "🦆", "🦅", "🦉", "🦇", "🐺", "🐗", "🐴", "🦄", "🐝", "🐛", "🦋"
];
// --- 2. 홈 화면 '선택' 메뉴에 표시될 이름 리스트 ---
static final List<String> selectableThemeNames = [
random,
numbers,
letters,
fruits,
korean,
animals
];
// --- 3. 테마 이름과 실제 '상징 풀'을 매핑 ---
static final Map<String, List<String>> _themePools = {
numbers: _numberPool,
letters: _letterPool,
fruits: _fruitPool,
korean: _koreanPool,
animals: _animalPool,
};
// --- 4. [핵심] 게임 시작 시 호출될 테마 '빌더' 함수 ---
static SudokuTheme buildGameTheme(String themeName, int gridSize) {
String effectiveThemeName = themeName;
// 1. "랜덤"이 선택된 경우
if (themeName == random) {
// "랜덤"을 제외한 실제 테마 이름 리스트에서 무작위로 하나 선택
final actualThemes = _themePools.keys.toList();
effectiveThemeName = (actualThemes..shuffle()).first;
}
// 2. 해당 테마의 '거대 풀'을 가져옴 (없으면 숫자로 대체)
final List<String> pool = _themePools[effectiveThemeName] ?? _numberPool;
// 3. 거대 풀을 섞은 뒤, 게임에 필요한 만큼(gridSize)만 뽑음
if (pool.length < gridSize) {
throw Exception("$effectiveThemeName 테마의 상징이 ${pool.length}개뿐입니다. $gridSize개가 필요합니다.");
}
final List<String> selectedSymbols = (pool.toList()..shuffle()).sublist(0, gridSize);
// 4. 이 게임만을 위한 '일회용' SudokuTheme 객체를 생성하여 반환
return SudokuTheme(
name: effectiveThemeName, // 실제 사용된 테마 이름 (예: "과일")
symbols: selectedSymbols, // 무작위로 뽑힌 기호 리스트
);
}
}
+28
View File
@@ -0,0 +1,28 @@
// lib/models/unified_rank_dto.dart
class UnifiedRankDto {
final String gameType;
final String? contextId;
final String playerName;
final int primaryScore;
final int? secondaryScore;
UnifiedRankDto({
required this.gameType,
this.contextId,
required this.playerName,
required this.primaryScore,
this.secondaryScore,
});
// Dart 객체를 JSON으로 변환 (서버 전송용)
Map<String, dynamic> toJson() {
return {
'gameType': gameType,
'contextId': contextId,
'playerName': playerName,
'primaryScore': primaryScore,
'secondaryScore': secondaryScore,
};
}
}
+11
View File
@@ -0,0 +1,11 @@
class ValidateResultDto {
final bool isCorrect;
ValidateResultDto({required this.isCorrect});
factory ValidateResultDto.fromJson(Map<String, dynamic> json) {
return ValidateResultDto(
isCorrect: json['correct'] ?? false,
);
}
}
+464
View File
@@ -0,0 +1,464 @@
import 'dart:async';
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/widgets/ad_banner_widget.dart';
import 'package:sudoku_app/widgets/number_pad.dart';
import 'package:sudoku_app/widgets/sudoku_board.dart';
class GameScreen extends StatefulWidget {
final SudokuGameDto gameData;
final String themeName;
const GameScreen({
super.key,
required this.gameData,
required this.themeName,
});
@override
State<GameScreen> createState() => _GameScreenState();
}
class _GameScreenState extends State<GameScreen> {
final PuzzleService _puzzleService = PuzzleService();
late final int blockSize;
late final int gridSize;
late final SudokuTheme activeTheme;
late List<int> puzzleCells;
late List<int> solutionCells;
late List<int> originalCells;
int? selectedIndex;
int score = 5;
int secondsElapsed = 0;
Timer? timer;
int? selectedNumberPad;
Set<int> incorrectCells = {};
bool isValidating = false;
// "A" -> 10 (파싱용)
int _charToInt(String char) {
if (char == '0') return 0;
if (char.codeUnitAt(0) >= '1'.codeUnitAt(0) && char.codeUnitAt(0) <= '9'.codeUnitAt(0)) {
return int.parse(char);
}
if (char.codeUnitAt(0) >= 'A'.codeUnitAt(0) && char.codeUnitAt(0) <= 'Z'.codeUnitAt(0)) {
return char.codeUnitAt(0) - 'A'.codeUnitAt(0) + 10;
}
return -1;
}
// 10 -> "A" (전송용)
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();
blockSize = widget.gameData.blockSize;
gridSize = widget.gameData.gridSize;
activeTheme = AppThemes.buildGameTheme(widget.themeName, gridSize);
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();
super.dispose();
}
void startTimer() {
timer = Timer.periodic(const Duration(seconds: 1), (timer) {
setState(() {
secondsElapsed++;
});
});
}
void onCellTapped(int index) {
if (originalCells[index] == 0) {
setState(() {
selectedIndex = index;
if (selectedNumberPad != null) {
// 오답 블로킹
if (incorrectCells.isNotEmpty && !incorrectCells.contains(index)) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('틀린 값을 먼저 수정해주세요. (되돌리기 ↩)'),
duration: Duration(seconds: 1),
),
);
return; // 입력 처리 중단
}
final int numberValue = selectedNumberPad!;
puzzleCells[index] = numberValue;
// 정답과 비교
if (numberValue != solutionCells[index]) {
// 점수 차감
if (!incorrectCells.contains(index)) {
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) {
selectedNumberPad = null;
} else {
selectedNumberPad = numberValue;
}
});
}
void onUndoTapped() {
setState(() {
if (selectedIndex != null && originalCells[selectedIndex!] == 0) {
puzzleCells[selectedIndex!] = 0;
incorrectCells.remove(selectedIndex);
}
});
}
void onHintTapped() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('힌트 기능은 준비 중입니다.')),
);
}
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,
);
if (result) {
if(mounted) _showRankingDialog();
} else {
if(mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('🤔 틀린 부분이 있습니다.')),
);
}
startTimer();
}
} catch (e) {
if(mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('오류: $e')),
);
}
startTimer();
} finally {
if(mounted) {
setState(() { isValidating = false; });
}
}
}
void _showRankingDialog() {
// ... (기존과 동일)
final nameController = TextEditingController();
bool isSubmitting = false;
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(),
),
maxLength: 10,
),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
Navigator.of(context).pop();
},
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('랭킹 등록'),
),
],
);
},
);
},
);
}
int _difficultyLevel(String question) {
int holes = question.split('').where((c) => c == '0').length;
double holeRatio = holes / (gridSize * gridSize);
if (holeRatio <= 0.51) return 1;
if (holeRatio <= 0.58) return 2;
if (holeRatio <= 0.63) return 3;
if (holeRatio <= 0.68) return 4;
return 5;
}
@override
Widget build(BuildContext context) {
// 🔽 [수정] 타이머 텍스트를 AppBar로 이동시키기 위해 build 메서드 상단으로 이동
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) {
if (cellValue > 0) {
numberCounts[cellValue] = (numberCounts[cellValue] ?? 0) + 1;
}
}
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: 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),
],
),
),
),
),
);
}
// 🔽 [수정] 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(),
),
),
),
const SizedBox(width: 16),
Expanded(
flex: 4,
child: SingleChildScrollView(
child: Column(
children: [
_buildGameInfoWidget(), // 👈 [수정] 파라미터 제거
const SizedBox(height: 20),
_buildNumberPadWidget(context, numberCounts, isLandscape: true),
],
),
),
),
],
),
);
}
// 🔽 [수정] 상단 정보 (점수, 힌트, 되돌리기) - 타이머 제거
Widget _buildGameInfoWidget() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// 1. 점수
Text('SCORE: $score', style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
// 2. 버튼 그룹 (힌트, 되돌리기)
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: onHintTapped,
icon: const Icon(Icons.lightbulb_outline, color: Colors.orange),
iconSize: 30,
),
IconButton(
onPressed: onUndoTapped,
icon: const Icon(Icons.undo, color: Colors.red),
iconSize: 30,
),
],
)
],
);
}
// 게임 보드 (변경 없음)
Widget _buildSudokuBoardWidget() {
return SudokuBoard(
blockSize: blockSize,
theme: activeTheme,
cells: puzzleCells,
originalCells: originalCells,
selectedIndex: selectedIndex,
selectedNumberPad: selectedNumberPad,
incorrectCells: incorrectCells,
onCellTapped: onCellTapped,
);
}
// 숫자 패드 (변경 없음)
Widget _buildNumberPadWidget(BuildContext context, Map<int, int> numberCounts, {required bool isLandscape}) {
double? maxWidth = !isLandscape
? 600 * 0.6
: 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,
),
),
);
}
}
+176
View File
@@ -0,0 +1,176 @@
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/screens/game_screen.dart';
import 'package:sudoku_app/screens/ranking_screen.dart';
import 'package:sudoku_app/services/puzzle_service.dart';
import 'package:sudoku_app/widgets/ad_banner_widget.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
// 난이도
double _difficultyLevel = 2.0;
final List<String> levelLabels = ["Easy", "Normal", "Medium", "Hard", "Expert"];
// 그리드 크기
double _blockSize = 3.0;
// 🔽 [수정] 16x16, 25x25 옵션 제거
final List<String> sizeLabels = ["4x4", "9x9"];
// 테마 이름
late String _selectedThemeName;
bool isLoading = false;
final PuzzleService _puzzleService = PuzzleService();
@override
void initState() {
super.initState();
// 기본 테마를 '랜덤' 이름으로 설정
_selectedThemeName = AppThemes.random;
}
Future<void> _startGame() async {
setState(() { isLoading = true; });
try {
final String level = _difficultyLevel.round().toString();
final String blockSize = _blockSize.round().toString();
final SudokuGameDto gameData = await _puzzleService.startGame(level, blockSize);
// 선택된 '테마 이름(String)'을 그대로 전달
if (mounted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GameScreen(
gameData: gameData,
themeName: _selectedThemeName,
),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('게임 로딩 실패: $e')),
);
}
} finally {
if (mounted) {
setState(() { isLoading = false; });
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('스도쿠 게임')),
body: LayoutBuilder( // 비율 기반 레이아웃
builder: (context, constraints) {
const double maxContentRatio = 0.6;
final double constrainedWidth = constraints.maxHeight * maxContentRatio;
return Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: constrainedWidth),
child: Column(
children: [
Expanded(
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 1. 난이도 선택
const Text("난이도", style: TextStyle(fontSize: 18)),
Slider(
value: _difficultyLevel,
min: 1.0, max: 5.0, divisions: 4,
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 기반)
const Text("테마", style: TextStyle(fontSize: 18)),
DropdownButton<String>(
value: _selectedThemeName,
items: AppThemes.selectableThemeNames.map((themeName) {
return DropdownMenuItem<String>(
value: themeName,
child: Text(themeName, style: const TextStyle(fontSize: 20)),
);
}).toList(),
onChanged: (themeName) {
if (themeName != null) {
setState(() { _selectedThemeName = themeName; });
}
},
),
const SizedBox(height: 30),
if (isLoading)
const CircularProgressIndicator()
else
ElevatedButton(
onPressed: _startGame,
style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 15)),
child: const Text('게임 시작', style: TextStyle(fontSize: 18)),
),
const SizedBox(height: 10),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const RankingScreen()),
);
},
child: const Text('랭킹 보기'),
),
],
),
),
),
),
const AdBannerWidget(),
],
),
),
);
},
),
);
}
}
+78
View File
@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
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});
@override
State<RankingScreen> createState() => _RankingScreenState();
}
class _RankingScreenState extends State<RankingScreen> {
final PuzzleService _puzzleService = PuzzleService();
// FutureBuilder를 사용하여 비동기 데이터를 쉽게 처리
late Future<List<GameRankDto>> _rankingFuture;
@override
void initState() {
super.initState();
// 화면이 로드될 때 스도쿠의 전체 랭킹을 가져옴 (contextId = null)
_rankingFuture = _puzzleService.fetchRanks('SUDOKU', null);
}
// 점수(초)를 'mm:ss' 형식으로 변환
String _formatScore(int seconds) {
final min = (seconds ~/ 60).toString().padLeft(2, '0');
final sec = (seconds % 60).toString().padLeft(2, '0');
return '$min:$sec';
}
@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('등록된 랭킹이 없습니다.'));
}
// 성공적으로 데이터를 가져왔을 때
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,
),
),
);
},
);
},
),
);
}
}
+85
View File
@@ -0,0 +1,85 @@
import 'dart:convert';
import 'dart:developer';
import 'package:http/http.dart' as http;
import 'package:sudoku_app/models/sudoku_game_dto.dart';
import 'package:sudoku_app/models/unified_rank_dto.dart';
import 'package:sudoku_app/models/game_rank_dto.dart';
class PuzzleService {
final String _baseUrl = "https://lunaticbum.kr"; // 👈 HTTPS 확인
// 🔽 [수정] 'blockSize' 파라미터 추가
Future<SudokuGameDto> startGame(String level, String blockSize) async {
final response = await http.get(
Uri.parse('$_baseUrl/puzzle/sudoku/start?level=$level&blockSizeStr=$blockSize'),
);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
return SudokuGameDto.fromJson(data);
} else {
throw Exception('게임 로딩 실패: ${response.statusCode}');
}
}
// 🔽 [수정] puzzleId 대신 question, answer, blockSize를 전송
Future<bool> validateSolution(String question, String answer, int blockSize) async {
final response = await http.post(
Uri.parse('$_baseUrl/puzzle/sudoku/validate'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'question': question, // 👈 [수정]
'answer': answer,
'blockSize': blockSize, // 👈 [수정]
}),
);
if (response.statusCode == 200) {
return jsonDecode(response.body)['correct'] ?? false;
} else {
log("정답 확인 실패: ${response.statusCode}");
log("응답 본문: ${response.body}");
throw Exception('정답 확인 실패: ${response.statusCode}');
}
}
// POST /api/ranks/submit
Future<void> submitRank(UnifiedRankDto rankDto) async {
final response = await http.post(
Uri.parse('$_baseUrl/api/ranks/submit'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(rankDto.toJson()),
);
if (response.statusCode != 200) {
try {
final errorBody = utf8.decode(response.bodyBytes);
throw Exception(errorBody);
} catch (e) {
throw Exception('랭킹 등록 실패: ${response.reasonPhrase}');
}
}
}
Future<List<GameRankDto>> fetchRanks(String gameType, String? contextId) async {
final queryParams = {
'gameType': gameType,
if (contextId != null) 'contextId': contextId,
};
// 쿼리 파라미터를 포함하여 URI 생성
final uri = Uri.parse('$_baseUrl/api/ranks/list').replace(queryParameters: queryParams);
final response = await http.get(uri);
if (response.statusCode == 200) {
// 서버에서 [ ... ] 형태의 JSON 배열을 받음
final List<dynamic> data = jsonDecode(utf8.decode(response.bodyBytes));
// 각 JSON 객체를 GameRankDto로 변환
return data.map((json) => GameRankDto.fromJson(json)).toList();
} else {
throw Exception('랭킹 로딩 실패');
}
}
}
+68
View File
@@ -0,0 +1,68 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
class AdBannerWidget extends StatefulWidget {
const AdBannerWidget({super.key});
@override
State<AdBannerWidget> createState() => _AdBannerWidgetState();
}
class _AdBannerWidgetState extends State<AdBannerWidget> {
BannerAd? _bannerAd;
bool _isAdLoaded = false;
// TODO: 릴리스 시 실제 Ad Unit ID로 교체하세요.
final String _androidAdUnitId = 'ca-app-pub-3940256099942544/6300978111'; // 테스트 ID
final String _iosAdUnitId = 'ca-app-pub-3940256099942544/2934735716'; // 테스트 ID
@override
void initState() {
super.initState();
_loadAd();
}
void _loadAd() {
_bannerAd = BannerAd(
adUnitId: Platform.isAndroid ? _androidAdUnitId : _iosAdUnitId,
size: AdSize.banner,
request: const AdRequest(),
listener: BannerAdListener(
onAdLoaded: (Ad ad) {
setState(() {
_isAdLoaded = true;
});
},
onAdFailedToLoad: (Ad ad, LoadAdError error) {
print('Ad failed to load: $error');
ad.dispose();
},
),
)..load();
}
@override
void dispose() {
_bannerAd?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_isAdLoaded && _bannerAd != null) {
// 광고가 로드되면 광고 위젯을 표시
return Container(
width: _bannerAd!.size.width.toDouble(),
height: _bannerAd!.size.height.toDouble(),
alignment: Alignment.center,
child: AdWidget(ad: _bannerAd!),
);
} else {
// 로드되지 않았으면, 광고 높이만큼의 빈 공간만 차지
return Container(
height: AdSize.banner.height.toDouble(),
);
}
}
}
+78
View File
@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
import 'package:sudoku_app/models/sudoku_theme.dart';
class NumberPad extends StatelessWidget {
final int blockSize;
final SudokuTheme theme;
final Map<int, int> numberCounts;
final int? selectedNumber;
final Function(int) onNumberTapped;
final bool isLandscape; // 👈 [추가] 이 파라미터가 있어야 합니다
const NumberPad({
super.key,
required this.blockSize,
required this.theme,
required this.numberCounts,
required this.selectedNumber,
required this.onNumberTapped,
required this.isLandscape, // 👈 [추가] 생성자에 추가
});
@override
Widget build(BuildContext context) {
final int gridSize = blockSize * blockSize;
// 1. 버튼 위젯 리스트 생성
List<Widget> numberButtons = List.generate(gridSize, (index) {
int numberValue = index + 1;
String numberSymbol = theme.getSymbol(numberValue);
bool isSelected = (numberValue == selectedNumber);
bool isCompleted = (numberCounts[numberValue] ?? 0) >= gridSize;
Widget button = ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: isSelected ? Colors.blue.shade300 : null,
foregroundColor: isSelected ? Colors.white : null,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 0),
textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
),
onPressed: isCompleted
? null
: () => onNumberTapped(numberValue),
child: Text(numberSymbol),
);
// 가로 모드(Wrap)에서는 Flexible로 감싸고,
// 세로 모드(Grid)에서는 감싸지 않음
if (isLandscape) {
// Flexible을 사용해 Wrap 내에서 버튼이 공간을 차지하도록 함
return Flexible(child: button);
} else {
return button;
}
});
// 2. 가로/세로 모드에 따라 다른 레이아웃 반환
if (isLandscape) {
// --- 가로 모드: Wrap 사용 (버튼이 가로로 흐름) ---
return Wrap(
runSpacing: 4.0, // 줄(세로) 간격
spacing: 4.0, // 버튼(가로) 간격
children: numberButtons,
);
} else {
// --- 세로 모드: GridView 사용 (블록 모양) ---
return GridView.count(
crossAxisCount: blockSize, // 2x2, 3x3, 4x4, 5x5
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: EdgeInsets.zero,
mainAxisSpacing: 4,
crossAxisSpacing: 4,
children: numberButtons,
);
}
}
}
+96
View File
@@ -0,0 +1,96 @@
import 'package:flutter/material.dart';
import 'package:sudoku_app/models/sudoku_theme.dart'; // 👈 [추가]
class SudokuBoard extends StatelessWidget {
final int blockSize;
final SudokuTheme theme; // 👈 [추가]
final List<int> cells; // 👈 [수정] List<String> -> List<int>
final List<int> originalCells; // 👈 [수정] List<String> -> List<int>
final int? selectedIndex;
final int? selectedNumberPad;
final Set<int> incorrectCells;
final Function(int) onCellTapped;
const SudokuBoard({
super.key,
required this.blockSize,
required this.theme, // 👈 [추가]
required this.cells,
required this.originalCells,
required this.selectedIndex,
required this.selectedNumberPad,
required this.incorrectCells,
required this.onCellTapped,
});
@override
Widget build(BuildContext context) {
final int gridSize = blockSize * blockSize;
final double fontSize = (gridSize > 9) ? (gridSize > 16 ? 12 : 16) : 24;
return AspectRatio(
aspectRatio: 1.0,
child: GridView.builder(
physics: const NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: gridSize,
),
itemCount: gridSize * gridSize,
itemBuilder: (context, index) {
int row = index ~/ gridSize;
int col = index % gridSize;
int cellValue = cells[index]; // 👈 [수정] 0, 1, 10...
bool isEditable = (originalCells[index] == 0); // 👈 [수정] "0" -> 0
bool isSelected = (index == selectedIndex);
bool isHighlighted = (cellValue != 0 && // 👈 [수정]
selectedNumberPad != null &&
cellValue == selectedNumberPad); // 👈 [수정] int == int 비교
bool isIncorrect = incorrectCells.contains(index);
BorderSide thickBorder = const BorderSide(color: Colors.black, width: 2.0);
BorderSide thinBorder = const BorderSide(color: Colors.grey, width: 0.5);
return GestureDetector(
onTap: () => onCellTapped(index),
child: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: isIncorrect
? Colors.red.shade100
: isSelected
? Colors.blue.shade100
: isHighlighted
? Colors.blue.shade200
: isEditable
? Colors.white
: Colors.grey.shade200,
border: Border(
top: (row == 0) ? thickBorder : thinBorder,
left: (col == 0) ? thickBorder : thinBorder,
right: (col == gridSize - 1) ? thickBorder : (col % blockSize == blockSize - 1) ? thickBorder : thinBorder,
bottom: (row == gridSize - 1) ? thickBorder : (row % blockSize == blockSize - 1) ? thickBorder : thinBorder,
),
),
child: Text(
// 🔽 [수정] 0이면 비우고, 아니면 테마 기호("1", "A", "🍎") 표시
cellValue == 0 ? '' : theme.getSymbol(cellValue),
style: TextStyle(
fontSize: fontSize,
fontWeight: FontWeight.bold,
color: isIncorrect
? Colors.red.shade900
: isEditable
? Colors.blue
: Colors.black,
),
),
),
);
},
),
);
}
}