flutter_sudoku/lib/screens/ranking_screen.dart
2025-11-10 18:02:01 +09:00

146 lines
5.1 KiB
Dart

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 {
// 🔽 [추가] 홈 화면에서 전달받을 초기 난이도 이름
final String? initialDifficultyName;
const RankingScreen({
super.key,
this.initialDifficultyName, // 👈 생성자에 추가
});
@override
State<RankingScreen> createState() => _RankingScreenState();
}
class _RankingScreenState extends State<RankingScreen> {
final PuzzleService _puzzleService = PuzzleService();
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();
// 🔽 [수정]
// 1. HomeScreen에서 전달받은 값이 있는지 확인
String defaultDifficulty = widget.initialDifficultyName ?? "중급 (9x9)";
// 2. (안전장치) 전달받은 값이 맵에 없으면(예: 향후 변경) 기본값 사용
if (!difficultyContexts.containsKey(defaultDifficulty)) {
defaultDifficulty = "중급 (9x9)";
}
// 3. 랭킹 조회
_fetchRanksForDifficulty(defaultDifficulty);
}
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: 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: 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),
),
],
),
);
},
);
},
),
),
],
),
);
}
}