This commit is contained in:
2025-11-10 18:02:01 +09:00
parent 9225ee6026
commit 1883fef583
22 changed files with 991 additions and 286 deletions
+35
View File
@@ -0,0 +1,35 @@
// lib/services/identity_service.dart
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
// 앱-고유 ID와 사용자 이름을 관리하는 서비스
class IdentityService {
static const String _userIdKey = 'app_user_id';
static const String _userNameKey = 'app_user_name';
// 1. 앱-고유 ID 가져오기 (없으면 생성)
Future<String> getOrCreateUserId() async {
final prefs = await SharedPreferences.getInstance();
String? userId = prefs.getString(_userIdKey);
if (userId == null) {
// ID가 없으면 V4 UUID 생성
userId = const Uuid().v4();
await prefs.setString(_userIdKey, userId);
}
return userId;
}
// 2. 랭킹에 등록한 사용자 이름 가져오기
Future<String?> getSavedUserName() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_userNameKey);
}
// 3. 랭킹 등록 성공 시, 사용자 이름 저장하기
Future<void> saveUserName(String name) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_userNameKey, name);
}
}
+22 -17
View File
@@ -1,19 +1,18 @@
import 'dart:convert';
import 'dart:developer';
import 'dart:developer'; // 👈 [추가] log 함수를 위한 임포트
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 확인
final String _baseUrl = "https://lunaticbum.kr";
// 🔽 [수정] 'blockSize' 파라미터 추가
Future<SudokuGameDto> startGame(String level, String blockSize) async {
// ... (startGame 함수는 동일) ...
Future<SudokuGameDto> startGame(String difficulty) async {
final response = await http.get(
Uri.parse('$_baseUrl/puzzle/sudoku/start?level=$level&blockSizeStr=$blockSize'),
Uri.parse('$_baseUrl/puzzle/sudoku/start?difficulty=$difficulty'),
);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
return SudokuGameDto.fromJson(data);
@@ -22,18 +21,16 @@ class PuzzleService {
}
}
// 🔽 [수정] puzzleId 대신 question, answer, blockSize를 전송
Future<bool> validateSolution(String question, String answer, int blockSize) async {
// ... (validateSolution 함수는 동일) ...
Future<bool> validateSolution(int puzzleId, String answer) async {
final response = await http.post(
Uri.parse('$_baseUrl/puzzle/sudoku/validate'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'question': question, // 👈 [수정]
'puzzleId': puzzleId,
'answer': answer,
'blockSize': blockSize, // 👈 [수정]
}),
);
if (response.statusCode == 200) {
return jsonDecode(response.body)['correct'] ?? false;
} else {
@@ -43,43 +40,51 @@ class PuzzleService {
}
}
// POST /api/ranks/submit
Future<void> submitRank(UnifiedRankDto rankDto) async {
final requestBody = jsonEncode(rankDto.toJson());
// 🔽 [로그 추가] 1. 서버로 전송하는 JSON 데이터 출력
log(">>> 랭킹 등록 요청: $requestBody");
final response = await http.post(
Uri.parse('$_baseUrl/api/ranks/submit'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(rankDto.toJson()),
body: requestBody,
);
if (response.statusCode != 200) {
// 🔽 [로그 추가] 2. 서버가 200(OK)이 아닌 응답을 줬을 때
log("<<< 랭킹 등록 실패: ${response.statusCode}");
try {
final errorBody = utf8.decode(response.bodyBytes);
log("<<< 서버 에러 메시지: $errorBody"); // 👈 (예: "이미 사용 중인 이름입니다.")
throw Exception(errorBody);
} catch (e) {
throw Exception('랭킹 등록 실패: ${response.reasonPhrase}');
}
}
// 🔽 [로그 추가] 3. 성공 시
log("<<< 랭킹 등록 성공: 200 OK");
}
// ... (fetchRanks 함수는 동일) ...
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('랭킹 로딩 실패');
}
}
}