...
This commit is contained in:
@@ -12,32 +12,33 @@ class QuizGame extends BaseGame {
|
||||
String get name => "OX 퀴즈 서바이벌";
|
||||
|
||||
@override
|
||||
String get description => "방장도 플레이어! 3초 안에 선택하세요.";
|
||||
String get description => "끝까지 살아남으세요!";
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// 상태 변수
|
||||
// ------------------------------------------------------------------------
|
||||
final _gameStateController = StreamController<Map<String, dynamic>>.broadcast();
|
||||
Stream<Map<String, dynamic>> get gameStateStream => _gameStateController.stream;
|
||||
StreamSubscription? _networkSubscription;
|
||||
|
||||
|
||||
// UI 초기화 지연 방지용 데이터
|
||||
Map<String, dynamic>? _lastState;
|
||||
|
||||
// 게임 데이터
|
||||
final Set<String> _aliveUsers = {}; // 생존자 ID
|
||||
final Set<String> _answeredUsers = {}; // 답변 제출자 ID
|
||||
final Set<String> _aliveUsers = {};
|
||||
final Set<String> _answeredUsers = {};
|
||||
|
||||
// 나의 상태
|
||||
PlayerStatus _myStatus = PlayerStatus.alive;
|
||||
String? _mySelectedAnswer;
|
||||
bool _isLockedIn = false;
|
||||
Timer? _lockInTimer;
|
||||
|
||||
// 카운트다운 상태
|
||||
// [상태] 카운트다운 중인가?
|
||||
bool _isCountingDown = false;
|
||||
int _countdownValue = 3;
|
||||
|
||||
// [상태] 정답 공개 중인가? (중간 대기 화면)
|
||||
bool _isShowingResult = false;
|
||||
String _currentCorrectAnswer = "";
|
||||
|
||||
final List<Map<String, dynamic>> _questions = [
|
||||
{"q": "사과는 영어로 Apple이다.", "a": "O"},
|
||||
{"q": "바나나는 길어지면 기차다.", "a": "X"},
|
||||
@@ -54,25 +55,23 @@ class QuizGame extends BaseGame {
|
||||
// ------------------------------------------------------------------------
|
||||
@override
|
||||
void onStart() {
|
||||
super.onStart();
|
||||
print("Quiz Game Started!");
|
||||
|
||||
_resetLocalState();
|
||||
_lastState = null;
|
||||
_aliveUsers.clear();
|
||||
|
||||
// 참가자 명단 초기화 (나 + 게스트)
|
||||
_aliveUsers.add(NetworkManager().me.id);
|
||||
for (var guest in NetworkManager().guestList) {
|
||||
_aliveUsers.add(guest.id);
|
||||
}
|
||||
|
||||
_networkSubscription = NetworkManager().messageStream.listen((payload) {
|
||||
onMessageReceived("", payload);
|
||||
});
|
||||
|
||||
// [Host] 잠시 후 카운트다운 시작
|
||||
// [Host] 게임 시작 시퀀스 진입
|
||||
if (NetworkManager().role == NetworkRole.host) {
|
||||
Future.delayed(const Duration(milliseconds: 1000), () {
|
||||
_startCountdown();
|
||||
// 잠시 대기 후 첫 번째 문제 카운트다운 시작
|
||||
Future.delayed(const Duration(seconds: 1), () {
|
||||
_startNextQuestionSequence();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -80,24 +79,8 @@ class QuizGame extends BaseGame {
|
||||
@override
|
||||
void onDispose() {
|
||||
_lockInTimer?.cancel();
|
||||
_networkSubscription?.cancel();
|
||||
_gameStateController.close();
|
||||
}
|
||||
|
||||
// [Host] 카운트다운
|
||||
void _startCountdown() {
|
||||
if (_currentQuestionIndex != -1) return;
|
||||
|
||||
Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
int nextCount = 3 - timer.tick;
|
||||
if (nextCount > 0) {
|
||||
_broadcastState({'type': 'GAME_COUNTDOWN', 'count': nextCount});
|
||||
} else {
|
||||
timer.cancel();
|
||||
_nextQuestion(); // 첫 문제 출제
|
||||
}
|
||||
});
|
||||
_broadcastState({'type': 'GAME_COUNTDOWN', 'count': 3});
|
||||
super.onDispose();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
@@ -110,11 +93,15 @@ class QuizGame extends BaseGame {
|
||||
_lastState = payload;
|
||||
}
|
||||
|
||||
// 1. [Common] 카운트다운
|
||||
// 1. [Common] 카운트다운 수신
|
||||
if (payload['type'] == 'GAME_COUNTDOWN') {
|
||||
_isShowingResult = false; // 결과 화면 끄기
|
||||
_isCountingDown = true;
|
||||
_countdownValue = payload['count'];
|
||||
|
||||
// 3, 2, 1 소리
|
||||
SoundManager().playSfx(SoundKey.click);
|
||||
|
||||
_gameStateController.add(payload);
|
||||
}
|
||||
|
||||
@@ -130,12 +117,11 @@ class QuizGame extends BaseGame {
|
||||
|
||||
_answeredUsers.add(userId);
|
||||
|
||||
// 정답 체크 (결과는 바로 반영하되, 탈락 통보는 결과 화면 때 보냄)
|
||||
final currentAnswer = _questions[_currentQuestionIndex]['a'];
|
||||
bool isCorrect = (answer == currentAnswer);
|
||||
|
||||
if (!isCorrect) {
|
||||
_aliveUsers.remove(userId); // 명단에서는 제거하되, 통보는 나중에
|
||||
_aliveUsers.remove(userId);
|
||||
}
|
||||
|
||||
// 제출 현황 전파
|
||||
@@ -143,37 +129,33 @@ class QuizGame extends BaseGame {
|
||||
'type': 'PLAYER_STATUS_UPDATE',
|
||||
'userId': userId,
|
||||
'isSubmitted': true,
|
||||
'isAlive': true // 아직은 살아있는 척 (결과 화면에서 공개)
|
||||
'isAlive': isCorrect
|
||||
});
|
||||
|
||||
// [핵심 변경] 전원 제출 완료 시 -> 결과 발표 화면으로 이동
|
||||
// (방금 죽은 사람 포함해서 이번 라운드 시작 인원만큼 답변이 왔는지 체크)
|
||||
int currentRoundPlayers = _aliveUsers.length + (isCorrect ? 0 : 1); // 방금 뺀 사람 포함
|
||||
// 더 정확히는: answeredUsers가 이번 라운드 참가자 수에 도달하면 진행
|
||||
// (여기선 간단히 answeredUsers가 더이상 늘어날 수 없을 때로 판단)
|
||||
|
||||
// 타임아웃 로직이 없으므로, 현재 살아있는 사람들이 다 냈으면 진행
|
||||
// (로직이 복잡해질 수 있으므로, 간단히 '살아있는 사람 수 == 답변 수'가 아니라
|
||||
// '이번 라운드 시작 시점의 생존자 수'를 별도 변수로 관리하는 게 정석이지만,
|
||||
// 여기서는 생존자 수 + 이번에 틀린 사람 수로 계산)
|
||||
|
||||
// 간단 로직: 1초 뒤 체크해서 더 낼 사람이 없으면 진행 (혹은 모두 냈으면 바로)
|
||||
Future.delayed(const Duration(milliseconds: 500), () {
|
||||
// 대충 모두 냈다고 판단되면 (추가 보정 필요할 수 있음)
|
||||
if (_answeredUsers.length >= (_aliveUsers.length + (isCorrect?0:1))) {
|
||||
_showRoundResult();
|
||||
}
|
||||
});
|
||||
// [자동 진행] 전원 제출 시 -> 결과 발표 -> 카운트다운 -> 다음 문제
|
||||
int currentAliveCount = _aliveUsers.length + (isCorrect ? 0 : 1);
|
||||
if (_answeredUsers.length >= currentAliveCount) {
|
||||
Future.delayed(const Duration(milliseconds: 500), () {
|
||||
_showRoundResultAndNext(); // 결과 발표 및 다음 단계
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. [Common] 중간 결과 발표 (NEW)
|
||||
// 3. [Common] 중간 결과 발표 (정답 공개)
|
||||
if (payload['type'] == 'ROUND_RESULT') {
|
||||
_isCountingDown = false;
|
||||
final bool isSurvived = payload['survivors'].contains(NetworkManager().me.id);
|
||||
_isShowingResult = true; // 결과 화면 모드 진입
|
||||
_currentCorrectAnswer = payload['correctAnswer'];
|
||||
|
||||
// 내 생존 여부 업데이트
|
||||
final List<dynamic> survivors = payload['survivors'] ?? [];
|
||||
final bool isSurvived = survivors.contains(NetworkManager().me.id);
|
||||
|
||||
// 내 생존 여부 업데이트 및 효과음
|
||||
if (!isSurvived && _myStatus == PlayerStatus.alive) {
|
||||
_handleElimination();
|
||||
} else if (isSurvived && _myStatus == PlayerStatus.alive) {
|
||||
// 정답 소리 (선택 사항)
|
||||
// SoundManager().playSfx(SoundKey.correct);
|
||||
}
|
||||
|
||||
_gameStateController.add(payload);
|
||||
@@ -183,17 +165,31 @@ class QuizGame extends BaseGame {
|
||||
if (payload['type'] == 'PLAYER_STATUS_UPDATE') {
|
||||
final userId = payload['userId'];
|
||||
_answeredUsers.add(userId);
|
||||
if (payload['isAlive'] == false) {
|
||||
_aliveUsers.remove(userId);
|
||||
}
|
||||
_gameStateController.add(payload);
|
||||
}
|
||||
|
||||
// 5. [Common] 새 문제 시작
|
||||
// 5. [Common] 탈락 통보 (본인)
|
||||
if (payload['type'] == 'PLAYER_ELIMINATED') {
|
||||
final targetId = payload['targetUserId'];
|
||||
_aliveUsers.remove(targetId);
|
||||
if (targetId == NetworkManager().me.id) {
|
||||
_handleElimination();
|
||||
}
|
||||
_gameStateController.add({'type': 'UI_REFRESH'});
|
||||
}
|
||||
|
||||
// 6. [Common] 새 문제 시작
|
||||
if (payload['type'] == 'GAME_STATE_UPDATE' && payload['status'] == 'QUESTION') {
|
||||
_isCountingDown = false;
|
||||
_isShowingResult = false;
|
||||
_resetLocalState();
|
||||
_gameStateController.add(payload);
|
||||
}
|
||||
|
||||
// 6. [Common] 종료
|
||||
// 7. [Common] 종료
|
||||
if (payload['type'] == 'GAME_OVER' || payload['type'] == 'GAME_EXIT') {
|
||||
if (payload['type'] == 'GAME_OVER') {
|
||||
final winnerId = payload['winnerId'];
|
||||
@@ -210,30 +206,32 @@ class QuizGame extends BaseGame {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// [Host Logic]
|
||||
// [Host Logic] 진행 관리자
|
||||
// ------------------------------------------------------------------------
|
||||
// [NEW] 결과 발표 단계
|
||||
void _showRoundResult() {
|
||||
|
||||
// 1. 라운드 결과 발표 (정답 O/X 보여주기)
|
||||
void _showRoundResultAndNext() {
|
||||
final currentQ = _questions[_currentQuestionIndex];
|
||||
|
||||
final resultData = {
|
||||
'type': 'ROUND_RESULT',
|
||||
'status': 'RESULT',
|
||||
'correctAnswer': currentQ['a'],
|
||||
'survivors': _aliveUsers.toList(), // 생존자 명단 전송
|
||||
'survivors': _aliveUsers.toList(),
|
||||
};
|
||||
|
||||
_broadcastState(resultData);
|
||||
|
||||
// 3초 뒤 다음 문제로 자동 이동
|
||||
// 3초간 결과 보여주고 -> 카운트다운 시작
|
||||
Future.delayed(const Duration(seconds: 3), () {
|
||||
_nextQuestion();
|
||||
_checkWinnerAndNext();
|
||||
});
|
||||
}
|
||||
|
||||
void _nextQuestion() {
|
||||
// 승패 판정
|
||||
// 2. 승패 체크 후 -> 카운트다운 -> 문제 출제
|
||||
void _checkWinnerAndNext() {
|
||||
int totalStartPlayers = NetworkManager().guestList.length + 1;
|
||||
|
||||
// 종료 조건
|
||||
if ((totalStartPlayers > 1 && _aliveUsers.length <= 1) || _currentQuestionIndex >= _questions.length - 1) {
|
||||
String? winnerId;
|
||||
if (_aliveUsers.isNotEmpty) winnerId = _aliveUsers.first;
|
||||
@@ -241,6 +239,27 @@ class QuizGame extends BaseGame {
|
||||
return;
|
||||
}
|
||||
|
||||
// 다음 문제 준비 시퀀스 시작
|
||||
_startNextQuestionSequence();
|
||||
}
|
||||
|
||||
// 3. 카운트다운 (3->2->1) 후 문제 전송
|
||||
void _startNextQuestionSequence() {
|
||||
int count = 3;
|
||||
// 1초 간격 타이머
|
||||
Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
_broadcastState({'type': 'GAME_COUNTDOWN', 'count': count});
|
||||
|
||||
if (count == 0) {
|
||||
timer.cancel();
|
||||
_sendNewQuestion(); // 문제 전송
|
||||
}
|
||||
count--;
|
||||
});
|
||||
}
|
||||
|
||||
// 4. 실제 문제 데이터 전송
|
||||
void _sendNewQuestion() {
|
||||
_currentQuestionIndex++;
|
||||
final questionData = _questions[_currentQuestionIndex];
|
||||
|
||||
@@ -285,21 +304,22 @@ class QuizGame extends BaseGame {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// [UI] Unified View
|
||||
// [UI] Unified View (통일된 UI)
|
||||
// ------------------------------------------------------------------------
|
||||
@override
|
||||
Widget buildHostView(BuildContext context) => _buildGameScreen(context, isHost: true);
|
||||
Widget buildHostView(BuildContext context) => _buildSharedScreen(context, isHost: true);
|
||||
|
||||
@override
|
||||
Widget buildGuestView(BuildContext context) => _buildGameScreen(context, isHost: false);
|
||||
Widget buildGuestView(BuildContext context) => _buildSharedScreen(context, isHost: false);
|
||||
|
||||
Widget _buildGameScreen(BuildContext context, {required bool isHost}) {
|
||||
Widget _buildSharedScreen(BuildContext context, {required bool isHost}) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text("OX 서바이벌"),
|
||||
title: const Text("OX 서바이벌", style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
centerTitle: true, // 타이틀 중앙 정렬 통일
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
if (isHost) IconButton(icon: const Icon(Icons.power_settings_new), onPressed: () => _confirmExit(context))
|
||||
if (isHost) IconButton(icon: const Icon(Icons.close), onPressed: () => _confirmExit(context))
|
||||
],
|
||||
),
|
||||
body: StreamBuilder<Map<String, dynamic>>(
|
||||
@@ -310,79 +330,56 @@ class QuizGame extends BaseGame {
|
||||
|
||||
final data = snapshot.data!;
|
||||
|
||||
if (data['type'] == 'GAME_COUNTDOWN') {
|
||||
int count = data['count'] ?? 3;
|
||||
return Center(child: Text("$count", style: const TextStyle(fontSize: 120, fontWeight: FontWeight.bold, color: Colors.blueAccent)));
|
||||
}
|
||||
|
||||
// 1. 종료 화면
|
||||
if (data['type'] == 'GAME_OVER') return _buildResultScreen(context, data['winnerName']);
|
||||
if (data['type'] == 'GAME_EXIT') {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) { if(context.mounted) Navigator.pop(context); });
|
||||
return const Center(child: Text("종료 중..."));
|
||||
}
|
||||
if (data['type'] == 'GAME_OVER') {
|
||||
return _buildResultScreen(context, data['winnerName']);
|
||||
return const Center(child: Text("종료되었습니다."));
|
||||
}
|
||||
|
||||
// [NEW] 중간 결과 화면
|
||||
if (data['status'] == 'RESULT') {
|
||||
// 2. 카운트다운 화면 (문제 직전)
|
||||
// count가 0일 때는 문제 화면으로 넘어가기 직전이므로 잠깐 보여도 됨
|
||||
if (_isCountingDown) {
|
||||
int count = data['count'] ?? 3;
|
||||
// 0초는 'Start!' 등으로 표현하거나 생략 가능
|
||||
String text = count > 0 ? "$count" : "GO!";
|
||||
return Center(
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(fontSize: 120, fontWeight: FontWeight.bold, color: Theme.of(context).primaryColor)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 3. 중간 결과 화면 (정답 공개)
|
||||
if (_isShowingResult || data['status'] == 'RESULT') {
|
||||
return _buildRoundResultScreen(data);
|
||||
}
|
||||
|
||||
// 문제 풀이 화면
|
||||
// 4. 문제 풀이 화면
|
||||
if (data['status'] == 'QUESTION' || _currentQuestionIndex >= 0) {
|
||||
Map<String, dynamic> qData = data['data'] ?? _questions[_currentQuestionIndex];
|
||||
// 인원 수 계산
|
||||
int answered = data['answeredCount'] ?? _answeredUsers.length;
|
||||
// 총인원 계산 (생존자 기준이 아님, 이번 라운드 참여자 기준이어야 함. 여기선 간단히 전체 인원 사용)
|
||||
int total = NetworkManager().guestList.length + 1;
|
||||
int total = isHost ? _aliveUsers.length : (data['totalAlive'] ?? _aliveUsers.length);
|
||||
if (total == 0) total = 1; // div by zero 방지
|
||||
|
||||
return _buildPlayArea(context, qData, answered, total);
|
||||
}
|
||||
|
||||
return _buildWaitingScreen("대기 중...");
|
||||
return _buildWaitingScreen("잠시만 기다려주세요...");
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// [NEW] 중간 결과 화면 위젯
|
||||
Widget _buildRoundResultScreen(Map<String, dynamic> data) {
|
||||
final String correctAnswer = data['correctAnswer'];
|
||||
final List<dynamic> survivors = data['survivors'] ?? [];
|
||||
final bool amISurvived = survivors.contains(NetworkManager().me.id);
|
||||
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text("정답은?", style: TextStyle(fontSize: 24, color: Colors.grey)),
|
||||
const SizedBox(height: 20),
|
||||
// 정답 표시
|
||||
Container(
|
||||
width: 150, height: 150,
|
||||
decoration: BoxDecoration(
|
||||
color: correctAnswer == "O" ? Colors.blue : Colors.red,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Center(child: Text(correctAnswer, style: const TextStyle(fontSize: 80, color: Colors.white, fontWeight: FontWeight.bold))),
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 생존 여부 메시지
|
||||
if (_myStatus == PlayerStatus.dead)
|
||||
const Text("이미 탈락하셨습니다. 👻", style: TextStyle(fontSize: 20, color: Colors.grey))
|
||||
else if (amISurvived)
|
||||
const Text("생존! 다음 라운드 진출! 🎉", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Colors.green))
|
||||
else
|
||||
const Text("탈락했습니다... 😭", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Colors.red)),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
Text("잠시 후 다음 문제가 시작됩니다.", style: TextStyle(color: Colors.grey[600])),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// UI Components
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
// [문제 풀이 화면]
|
||||
Widget _buildPlayArea(BuildContext context, Map<String, dynamic> qData, int answered, int total) {
|
||||
// 탈락자 뷰
|
||||
if (_myStatus == PlayerStatus.dead) {
|
||||
return Center(
|
||||
child: Column(
|
||||
@@ -392,20 +389,33 @@ class QuizGame extends BaseGame {
|
||||
const SizedBox(height: 20),
|
||||
const Text("탈락했습니다 👻", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 20),
|
||||
Text("관전 중... ($answered명 제출)", style: const TextStyle(fontSize: 18, color: Colors.grey)),
|
||||
Text("관전 중... ($answered / $total 제출)", style: const TextStyle(fontSize: 18, color: Colors.grey)),
|
||||
const SizedBox(height: 40),
|
||||
Text("문제: ${qData['q']}", style: const TextStyle(color: Colors.grey)),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 30),
|
||||
child: Text("문제: ${qData['q']}", textAlign: TextAlign.center, style: const TextStyle(color: Colors.grey)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 생존자 뷰
|
||||
return Column(
|
||||
children: [
|
||||
// 상단 현황판
|
||||
_PlayerStatusGrid(aliveUsers: _aliveUsers, answeredUsers: _answeredUsers),
|
||||
const Divider(),
|
||||
const Divider(height: 1),
|
||||
|
||||
// 진행바
|
||||
LinearProgressIndicator(
|
||||
value: total > 0 ? answered / total : 0,
|
||||
minHeight: 6,
|
||||
backgroundColor: Colors.grey[200],
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(Colors.orange),
|
||||
),
|
||||
|
||||
// 문제 텍스트
|
||||
Expanded(
|
||||
flex: 4,
|
||||
child: Center(
|
||||
@@ -419,6 +429,8 @@ class QuizGame extends BaseGame {
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 컨트롤 (버튼)
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: _isLockedIn
|
||||
@@ -431,11 +443,13 @@ class QuizGame extends BaseGame {
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// 하단 안내
|
||||
SizedBox(
|
||||
height: 60,
|
||||
child: Center(
|
||||
child: _mySelectedAnswer != null && !_isLockedIn
|
||||
? const Text("3초 후 확정됩니다! (변경 가능)", style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold))
|
||||
? const Text("3초 후 확정됩니다!", style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold))
|
||||
: const SizedBox(),
|
||||
),
|
||||
),
|
||||
@@ -443,8 +457,53 @@ class QuizGame extends BaseGame {
|
||||
);
|
||||
}
|
||||
|
||||
// ... (이하 _buildLockedUI, _selectAnswer 등 기존 함수들 유지) ...
|
||||
|
||||
// [결과 발표 화면]
|
||||
Widget _buildRoundResultScreen(Map<String, dynamic> data) {
|
||||
final String correctAnswer = data['correctAnswer'] ?? "?";
|
||||
final List<dynamic> survivors = data['survivors'] ?? [];
|
||||
final bool amISurvived = survivors.contains(NetworkManager().me.id);
|
||||
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text("정답은?", style: TextStyle(fontSize: 24, color: Colors.grey)),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 정답 O/X 표시
|
||||
Container(
|
||||
width: 160, height: 160,
|
||||
decoration: BoxDecoration(
|
||||
color: correctAnswer == "O" ? Colors.blue : Colors.red,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 10, offset: const Offset(0, 5))]
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
correctAnswer,
|
||||
style: const TextStyle(fontSize: 100, color: Colors.white, fontWeight: FontWeight.bold)
|
||||
)
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 상태 메시지
|
||||
if (_myStatus == PlayerStatus.dead)
|
||||
const Text("이미 탈락하셨습니다. 👻", style: TextStyle(fontSize: 20, color: Colors.grey))
|
||||
else if (amISurvived)
|
||||
const Text("생존! 🎉", style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.green))
|
||||
else
|
||||
const Text("탈락했습니다... 😭", style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.red)),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
// 방장에게만 보이는 비상 버튼 (혹시 멈출까봐)
|
||||
if (NetworkManager().role == NetworkRole.host)
|
||||
TextButton(onPressed: () => _checkWinnerAndNext(), child: const Text("강제 진행 (비상용)", style: TextStyle(color: Colors.grey)))
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLockedUI() {
|
||||
return Center(
|
||||
child: Column(
|
||||
@@ -456,163 +515,59 @@ class QuizGame extends BaseGame {
|
||||
color: _mySelectedAnswer == "O" ? Colors.blue : Colors.red,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const Text("제출 완료! 결과를 기다리는 중...", style: TextStyle(fontSize: 20, color: Colors.grey)),
|
||||
const Text("제출 완료!\n결과를 기다리는 중...", textAlign: TextAlign.center, style: TextStyle(fontSize: 18, color: Colors.grey)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ... (이하 _selectAnswer, _submitFinalAnswer, _buildResultScreen, _buildWaitingScreen, _confirmExit 동일) ...
|
||||
void _selectAnswer(String answer) {
|
||||
_lockInTimer?.cancel();
|
||||
_mySelectedAnswer = answer;
|
||||
SoundManager().playSfx(SoundKey.click);
|
||||
_updateLocalState({'type': 'UI_REFRESH'});
|
||||
|
||||
_lockInTimer = Timer(const Duration(seconds: 3), () {
|
||||
_submitFinalAnswer();
|
||||
});
|
||||
_gameStateController.add({'type': 'UI_REFRESH'});
|
||||
_lockInTimer = Timer(const Duration(seconds: 3), () { _submitFinalAnswer(); });
|
||||
}
|
||||
|
||||
|
||||
void _submitFinalAnswer() {
|
||||
if (_mySelectedAnswer == null) return;
|
||||
_isLockedIn = true;
|
||||
_updateLocalState({'type': 'UI_REFRESH'});
|
||||
|
||||
final payload = {
|
||||
'type': 'ANSWER_SUBMIT',
|
||||
'answer': _mySelectedAnswer,
|
||||
'userId': NetworkManager().me.id,
|
||||
};
|
||||
|
||||
if (NetworkManager().role == NetworkRole.host) {
|
||||
onMessageReceived("", payload);
|
||||
} else {
|
||||
NetworkManager().sendMessage(payload);
|
||||
}
|
||||
_gameStateController.add({'type': 'UI_REFRESH'});
|
||||
final payload = {'type': 'ANSWER_SUBMIT', 'answer': _mySelectedAnswer, 'userId': NetworkManager().me.id};
|
||||
if (NetworkManager().role == NetworkRole.host) { onMessageReceived("", payload); } else { NetworkManager().sendMessage(payload); }
|
||||
}
|
||||
|
||||
void _updateLocalState(Map<String, dynamic> data) {
|
||||
_gameStateController.add(data);
|
||||
}
|
||||
|
||||
Widget _buildResultScreen(BuildContext context, String winnerName) {
|
||||
bool amIWinner = _myStatus == PlayerStatus.winner;
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(amIWinner ? Icons.emoji_events : Icons.thumb_down, size: 100, color: amIWinner ? Colors.amber : Colors.grey),
|
||||
const SizedBox(height: 20),
|
||||
Text(amIWinner ? "우승!" : "게임 종료", style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 10),
|
||||
Text("최종 우승자: $winnerName", style: const TextStyle(fontSize: 20)),
|
||||
const SizedBox(height: 50),
|
||||
ElevatedButton(onPressed: () { onDispose(); Navigator.pop(context); }, child: const Text("나가기")),
|
||||
],
|
||||
),
|
||||
);
|
||||
return Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [Icon(amIWinner ? Icons.emoji_events : Icons.thumb_down, size: 100, color: amIWinner ? Colors.amber : Colors.grey), const SizedBox(height: 20), Text(amIWinner ? "우승!" : "게임 종료", style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold)), const SizedBox(height: 10), Text("최종 우승자: $winnerName", style: const TextStyle(fontSize: 20)), const SizedBox(height: 50), ElevatedButton(onPressed: () { onDispose(); Navigator.pop(context); }, child: const Text("로비로 돌아가기"))]));
|
||||
}
|
||||
|
||||
|
||||
Widget _buildWaitingScreen(String msg) => Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [const CircularProgressIndicator(), SizedBox(height: 20), Text(msg)]));
|
||||
|
||||
|
||||
void _confirmExit(BuildContext context) {
|
||||
showDialog(context: context, builder: (ctx) => AlertDialog(
|
||||
title: const Text("게임 종료"), content: const Text("방을 폭파하시겠습니까?"),
|
||||
actions: [
|
||||
TextButton(onPressed: ()=>Navigator.pop(ctx), child: const Text("취소")),
|
||||
TextButton(onPressed: () {
|
||||
Navigator.pop(ctx);
|
||||
NetworkManager().sendMessage({'type': 'GAME_EXIT'});
|
||||
onDispose();
|
||||
Navigator.pop(context);
|
||||
}, child: const Text("종료", style: TextStyle(color: Colors.red))),
|
||||
]
|
||||
));
|
||||
showDialog(context: context, builder: (ctx) => AlertDialog(title: const Text("게임 종료"), content: const Text("방을 폭파하시겠습니까?"), actions: [TextButton(onPressed: ()=>Navigator.pop(ctx), child: const Text("취소")), TextButton(onPressed: () { Navigator.pop(ctx); NetworkManager().sendMessage({'type': 'GAME_EXIT'}); onDispose(); Navigator.pop(context); }, child: const Text("종료", style: TextStyle(color: Colors.red)))]));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// [Widget] 현황판 (기존 코드와 동일하지만 함께 제공)
|
||||
// ------------------------------------------------------------------------
|
||||
// [현황판]
|
||||
class _PlayerStatusGrid extends StatelessWidget {
|
||||
final Set<String> aliveUsers;
|
||||
final Set<String> answeredUsers;
|
||||
|
||||
const _PlayerStatusGrid({required this.aliveUsers, required this.answeredUsers});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final allUsers = [NetworkManager().me, ...NetworkManager().guestList];
|
||||
|
||||
return Container(
|
||||
height: 90,
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(10),
|
||||
color: Colors.grey[100],
|
||||
child: ListView.builder(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: allUsers.length,
|
||||
itemBuilder: (context, index) {
|
||||
final user = allUsers[index];
|
||||
final isAlive = aliveUsers.contains(user.id);
|
||||
final isSubmitted = answeredUsers.contains(user.id);
|
||||
final isMe = user.id == NetworkManager().me.id;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Column(
|
||||
children: [
|
||||
Stack(
|
||||
children: [
|
||||
Container(
|
||||
width: 50, height: 50,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isAlive ? Color(user.colorValue) : Colors.grey,
|
||||
border: isSubmitted ? Border.all(color: Colors.green, width: 3) : null,
|
||||
),
|
||||
child: Center(
|
||||
child: isAlive
|
||||
? Text(user.nickname[0], style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold))
|
||||
: const Icon(Icons.close, color: Colors.white),
|
||||
),
|
||||
),
|
||||
if (isMe) Positioned(top:0, right:0, child: Container(width: 10, height: 10, decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle))),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(user.nickname, style: TextStyle(fontSize: 10, color: isAlive ? Colors.black : Colors.grey)),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
return Container(height: 80, width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10), color: Colors.grey[50], child: ListView.builder(scrollDirection: Axis.horizontal, itemCount: allUsers.length, itemBuilder: (context, index) { final user = allUsers[index]; final isAlive = aliveUsers.contains(user.id); final isSubmitted = answeredUsers.contains(user.id); return Padding(padding: const EdgeInsets.symmetric(horizontal: 6.0), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [Stack(children: [Container(width: 40, height: 40, decoration: BoxDecoration(shape: BoxShape.circle, color: isAlive ? Color(user.colorValue) : Colors.grey, border: isSubmitted ? Border.all(color: Colors.green, width: 3) : null), child: AvatarWidget(user: user, size: 40)), if (!isAlive) Positioned.fill(child: Container(decoration: BoxDecoration(color: Colors.black54, shape: BoxShape.circle), child: const Icon(Icons.close, size: 20, color: Colors.white)))]), const SizedBox(height: 4), Text(user.nickname, style: TextStyle(fontSize: 10, color: isAlive ? Colors.black : Colors.grey))])); }));
|
||||
}
|
||||
}
|
||||
|
||||
// [버튼]
|
||||
class _AnswerBtn extends StatelessWidget {
|
||||
final String text;
|
||||
final Color color;
|
||||
final bool isSelected;
|
||||
final VoidCallback onTap;
|
||||
final String text; final Color color; final bool isSelected; final VoidCallback onTap;
|
||||
const _AnswerBtn({required this.text, required this.color, required this.isSelected, required this.onTap});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
width: isSelected ? 140 : 120,
|
||||
height: isSelected ? 140 : 120,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(isSelected ? 1.0 : 0.6),
|
||||
shape: BoxShape.circle,
|
||||
border: isSelected ? Border.all(color: Colors.white, width: 5) : null,
|
||||
boxShadow: [BoxShadow(color: color.withOpacity(0.4), blurRadius: 10, offset: const Offset(0, 6))]
|
||||
),
|
||||
child: Center(child: Text(text, style: const TextStyle(fontSize: 60, color: Colors.white, fontWeight: FontWeight.bold))),
|
||||
),
|
||||
);
|
||||
return GestureDetector(onTap: onTap, child: AnimatedContainer(duration: const Duration(milliseconds: 200), width: isSelected ? 140 : 120, height: isSelected ? 140 : 120, decoration: BoxDecoration(color: color.withOpacity(isSelected ? 1.0 : 0.6), shape: BoxShape.circle, border: isSelected ? Border.all(color: Colors.white, width: 5) : null, boxShadow: [BoxShadow(color: color.withOpacity(0.4), blurRadius: 10, offset: const Offset(0, 6))]), child: Center(child: Text(text, style: const TextStyle(fontSize: 60, color: Colors.white, fontWeight: FontWeight.bold)))));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user