This commit is contained in:
2025-11-26 18:10:10 +09:00
parent 283f08786e
commit bf40c42c2c
43 changed files with 4454 additions and 971 deletions
+244 -159
View File
@@ -2,10 +2,10 @@ import 'dart:convert';
import 'package:bonsoir/bonsoir.dart';
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:playwith_core/playwith_core.dart'; // Core (AvatarWidget, NetworkManager 등)
import 'package:playwith_game_quiz/quiz_game.dart';
import 'package:playwith_core/playwith_core.dart';
import 'package:qr_flutter/qr_flutter.dart';
class LobbyScreen extends StatefulWidget {
const LobbyScreen({super.key});
@@ -22,40 +22,68 @@ class _LobbyScreenState extends State<LobbyScreen> {
void initState() {
super.initState();
// 로그 리스너
_net.logStream.listen((log) {
if (!mounted) return;
setState(() {
_logs.add(log);
if (_logs.length > 100) _logs.removeAt(0);
});
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
if (SettingsNotifier().isShowDebugLog) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
}
});
// 게임 시작 신호 감지
_net.messageStream.listen((data) {
if (data['type'] == 'GAME_START') {
final String gameId = data['gameId'];
if (gameId == 'quiz_ox') {
if (gameId == 'quiz_ox' || gameId == 'quiz_mix') {
_startGameAndNavigate(QuizGame());
}
else if (gameId == 'sudoku_battle') {
_startGameAndNavigate(SudokuMultiGame());
}
else if (gameId == 'spider_battle') {
_startGameAndNavigate(SpiderMultiGame());
}
// [추가] 오목 & 장기 연결
else if (gameId == 'omok') {
_startGameAndNavigate(OmokGame());
}
else if (gameId == 'janggi') {
_startGameAndNavigate(JanggiGame());
}
else if (gameId == 'yutnori') {
_startGameAndNavigate(YutnoriGame());
}
else if (gameId == 'memory_battle') {
_startGameAndNavigate(MemoryGame());
}
// [추가] 밸런스 & 터치 배틀 연결
else if (gameId == 'balance_game') {
_startGameAndNavigate(BalanceGame());
}
else if (gameId == 'tap_battle') {
_startGameAndNavigate(TapBattleGame());
}
}
});
}
void _startGameAndNavigate(BaseGame game) {
Future<void> _startGameAndNavigate(BaseGame game) async {
if (!mounted) return;
game.onStart();
Navigator.push(
await Navigator.push(
context,
MaterialPageRoute(builder: (context) {
Widget gameView;
@@ -64,16 +92,103 @@ class _LobbyScreenState extends State<LobbyScreen> {
} else {
gameView = game.buildGuestView(context);
}
// 게임 위 채팅 오버레이
return Stack(
children: [
gameView,
const SafeArea(child: GameChatOverlay()),
const SafeArea(
// 배너 광고 높이만큼 띄워서 채팅창 표시
child: GameChatOverlay(bottomOffset: 60.0),
),
],
);
}),
);
// [수정] 게임 종료 후 복귀 시 로직
// 솔로 모드였다면 네트워크를 종료하고 초기 화면으로 돌아감
if (_net.hostIp == "Solo Mode") {
_net.stopNetwork();
}
}
void _navigateToGameSelection({required bool isSolo}) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GameSelectionScreen(
onGameSelected: (gameId) async {
// 스도쿠 선택 시 난이도 팝업
Map<String, dynamic> config = {};
if (gameId == 'sudoku_battle') {
final difficulty = await _showDifficultyDialog();
if (difficulty == null) return; // 취소함
config['difficulty'] = difficulty;
}
if (!mounted) return;
Navigator.pop(context); // 선택 화면 닫기
if (isSolo) {
_net.startSoloMode(gameId, config: config);
} else {
_net.selectGame(gameId, config: config);
_net.startHosting("${_net.me.nickname}의 방");
Future.delayed(const Duration(milliseconds: 500), () {
if (mounted && _net.role == NetworkRole.host) _showHostQRDialog();
});
}
},
),
),
);
}
// [추가] 난이도 선택 다이얼로그
Future<int?> _showDifficultyDialog() {
return showDialog<int>(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: const Text("난이도 선택"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: const Text("쉬움"),
leading: const Icon(Icons.filter_1, color: Colors.green),
onTap: () => Navigator.pop(context, 4),
),
ListTile(
title: const Text("보통"),
leading: const Icon(Icons.filter_2, color: Colors.blue),
onTap: () => Navigator.pop(context, 5), // 4~5 레벨이 보통 9x9
),
ListTile(
title: const Text("약간 어려움"),
leading: const Icon(Icons.filter_3, color: Colors.red),
onTap: () => Navigator.pop(context, 6), // 7 레벨이 어려움
),
ListTile(
title: const Text("약간 어려움"),
leading: const Icon(Icons.filter_4, color: Colors.red),
onTap: () => Navigator.pop(context, 7), // 7 레벨이 어려움
),
ListTile(
title: const Text("개 어려움"),
leading: const Icon(Icons.filter_5, color: Colors.red),
onTap: () => Navigator.pop(context, 8), // 7 레벨이 어려움
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, null),
child: const Text("취소"),
)
],
),
);
}
@override
@@ -81,50 +196,50 @@ class _LobbyScreenState extends State<LobbyScreen> {
return ListenableBuilder(
listenable: _net,
builder: (context, child) {
return Scaffold(
appBar: AppBar(
title: const Text('대기실'),
centerTitle: true,
actions: [
// 연결된 상태라면 나가기 버튼 표시
if (_net.role != NetworkRole.none)
IconButton(
icon: const Icon(Icons.exit_to_app, color: Colors.red),
tooltip: "나가기",
onPressed: () => _net.stopNetwork(),
)
],
),
body: Column(
children: [
// 메인 바디 (연결 상태에 따라 분기)
Expanded(flex: 3, child: _buildMainBody()),
const Divider(thickness: 1, height: 1),
// 하단 디버그 로그 (개발용)
_buildDebugConsole(),
],
),
return ListenableBuilder(
listenable: SettingsNotifier(),
builder: (context, _) {
return Scaffold(
appBar: AppBar(
title: Text('대기실: ${_net.me.nickname}'),
actions: [
if (_net.role == NetworkRole.host)
IconButton(
icon: const Icon(Icons.qr_code),
tooltip: "초대 QR 보기",
onPressed: () => _showHostQRDialog(),
),
if (_net.role != NetworkRole.none)
IconButton(
icon: const Icon(Icons.exit_to_app),
tooltip: "나가기",
onPressed: () => _net.stopNetwork(),
)
],
),
bottomNavigationBar: const SafeArea(child: AdBannerWidget()),
body: Column(
children: [
Expanded(
flex: 3,
child: _net.role == NetworkRole.none
? _buildInitView()
: _buildLobbyView()
),
const Divider(thickness: 1, height: 1),
if (SettingsNotifier().isShowDebugLog)
_buildDebugConsole(),
],
),
);
},
);
},
);
}
// [Main Body] 상태에 따라 초기화면 vs 대기실 화면 분기
Widget _buildMainBody() {
// 1. 아직 연결 안 됨 (초기 화면)
if (_net.role == NetworkRole.none) {
return _buildInitView();
}
// 2. 연결됨 (대기실 - 방장/참가자 통합 UI)
return _buildLobbyView();
}
// ------------------------------------------------------------------------
// 1. 초기 화면 (방 만들기 / 찾기)
// ------------------------------------------------------------------------
Widget _buildInitView() {
return Center(
child: SingleChildScrollView(
@@ -134,6 +249,15 @@ class _LobbyScreenState extends State<LobbyScreen> {
const Text("게임을 시작해볼까요?", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
const SizedBox(height: 40),
_BigButton(
title: "혼자 연습하기\n(Single)",
color: Colors.orange[100]!,
icon: Icons.person,
onTap: () => _navigateToGameSelection(isSolo: true),
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
@@ -141,13 +265,7 @@ class _LobbyScreenState extends State<LobbyScreen> {
title: "방 만들기\n(Host)",
color: Colors.blue[100]!,
icon: Icons.add_home_work,
onTap: () {
_net.startHosting("${_net.me.nickname}의 방");
// 방장은 방 만들자마자 QR 팝업
Future.delayed(const Duration(milliseconds: 500), () {
if (mounted && _net.role == NetworkRole.host) _showHostQRDialog();
});
},
onTap: () => _navigateToGameSelection(isSolo: false),
),
_BigButton(
title: "방 찾기\n(Guest)",
@@ -157,6 +275,7 @@ class _LobbyScreenState extends State<LobbyScreen> {
),
],
),
const SizedBox(height: 30),
ElevatedButton.icon(
@@ -176,20 +295,32 @@ class _LobbyScreenState extends State<LobbyScreen> {
);
}
// ------------------------------------------------------------------------
// 2. 대기실 화면 (통합 UI)
// ------------------------------------------------------------------------
Widget _buildLobbyView() {
final currentGame = AppGames.getById(_net.selectedGameId);
return Column(
children: [
// A. 상단 정보 카드
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
color: Colors.indigo.withOpacity(0.1),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(currentGame.icon, size: 20, color: Colors.indigo),
const SizedBox(width: 8),
Text(
"선택된 게임: ${currentGame.name}",
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.indigo),
),
],
),
),
Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.grey[100],
border: const Border(bottom: BorderSide(color: Colors.black12)),
),
color: Colors.grey[100],
child: Column(
children: [
Row(
@@ -203,70 +334,53 @@ class _LobbyScreenState extends State<LobbyScreen> {
),
],
),
// 방장일 경우 접속 정보 표시
if (_net.role == NetworkRole.host) ...[
const SizedBox(height: 15),
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20), border: Border.all(color: Colors.blue.shade100)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text("IP: ${_net.hostIp} : ${_net.hostPort}", style: const TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(width: 10),
InkWell(
onTap: () => _showHostQRDialog(),
child: const Icon(Icons.qr_code, color: Colors.black87),
)
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SelectableText(
"IP: ${_net.hostIp} / Port: ${_net.hostPort}",
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
const SizedBox(width: 10),
InkWell(
onTap: () => _showHostQRDialog(),
child: const Icon(Icons.qr_code, color: Colors.black87),
)
],
),
const SizedBox(height: 5),
const Text("QR 코드를 눌러 친구를 초대하세요!", style: TextStyle(fontSize: 12, color: Colors.grey)),
] else ...[
// 참가자일 경우 방장 정보 표시
const SizedBox(height: 10),
Text("방장 IP: ${_net.hostIp ?? '...'}", style: const TextStyle(color: Colors.grey)),
]
],
),
),
// B. 참가자 리스트 (나 + 게스트)
const Divider(height: 1),
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
const Text("대기 중인 참가자", style: TextStyle(color: Colors.grey, fontWeight: FontWeight.bold)),
const Text("참가자 목록", style: TextStyle(color: Colors.grey, fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
// 1. 나 (항상 맨 위)
_buildUserTile(_net.me, isMe: true),
// 2. 다른 참가자들
..._net.guestList.map((guest) => _buildUserTile(guest, isMe: false)),
// 대기 문구
if (_net.guestList.isEmpty && _net.role == NetworkRole.host)
Padding(
padding: const EdgeInsets.only(top: 40.0),
child: Center(
child: Column(
children: const [
CircularProgressIndicator(),
SizedBox(height: 20),
Text("친구를 기다리는 중...", style: TextStyle(color: Colors.grey)),
],
),
),
const Padding(
padding: EdgeInsets.all(40.0),
child: Center(child: Text("참가자를 기다리는 중...\nQR 코드를 보여주세요.", textAlign: TextAlign.center, style: TextStyle(color: Colors.grey))),
),
],
),
),
// C. 하단 레디 버튼
_buildReadyButton(),
Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: _buildReadyButton(),
),
],
);
}
@@ -282,7 +396,7 @@ class _LobbyScreenState extends State<LobbyScreen> {
margin: const EdgeInsets.symmetric(vertical: 6),
child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
leading: AvatarWidget(user: user, size: 50), // Core의 AvatarWidget 사용
leading: AvatarWidget(user: user, size: 50),
title: Text(
user.nickname + (isMe ? " (나)" : ""),
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
@@ -297,66 +411,40 @@ class _LobbyScreenState extends State<LobbyScreen> {
Widget _buildReadyButton() {
bool isReady = _net.me.isReady;
// 조건: 방장이라도 게스트가 없으면 레디 불가 (혼자 게임 불가)
// 게스트는 들어오자마자 레디 가능
bool canReady = _net.role == NetworkRole.host ? _net.guestList.isNotEmpty : true;
bool canReady = _net.role == NetworkRole.host ? _net.guestList.isNotEmpty : true;
return Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 10, offset: const Offset(0, -5))],
),
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: ElevatedButton(
onPressed: canReady
? () => _net.toggleReady()
: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("친구를 초대해야 시작할 수 있습니다!")));
},
: () => ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("친구를 초대해야 시작할 수 있습니다!"))),
style: ElevatedButton.styleFrom(
backgroundColor: !canReady
? Colors.grey[300]
: (isReady ? Colors.redAccent : Colors.blueAccent),
backgroundColor: !canReady ? Colors.grey[300] : (isReady ? Colors.redAccent : Colors.blueAccent),
padding: const EdgeInsets.symmetric(vertical: 18),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
elevation: canReady ? 5 : 0,
),
child: Text(
isReady ? "준비 취소 (WAIT)" : "준비 완료 (READY)",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: !canReady ? Colors.grey : Colors.white
),
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: !canReady ? Colors.grey : Colors.white),
),
),
);
}
// ------------------------------------------------------------------------
// [Components] 디버그 콘솔
// ------------------------------------------------------------------------
Widget _buildDebugConsole() {
return Column(
children: [
GestureDetector(
onTap: () => _scrollController.jumpTo(_scrollController.position.maxScrollExtent),
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
color: Colors.black87,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Text("DEBUG LOGS", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 10)),
Icon(Icons.keyboard_arrow_down, color: Colors.white, size: 14)
],
),
),
Container(
width: double.infinity,
padding: const EdgeInsets.all(8.0),
color: Colors.black87,
child: const Text("DEBUG LOGS", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
),
SizedBox(
height: 100,
height: 150,
child: Container(
color: Colors.black,
child: ListView.builder(
@@ -364,10 +452,10 @@ class _LobbyScreenState extends State<LobbyScreen> {
itemCount: _logs.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 1.0),
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
child: Text(
_logs[index],
style: const TextStyle(color: Colors.greenAccent, fontSize: 10, fontFamily: 'Courier'),
style: const TextStyle(color: Colors.greenAccent, fontSize: 12, fontFamily: 'Courier'),
),
);
},
@@ -378,9 +466,6 @@ class _LobbyScreenState extends State<LobbyScreen> {
);
}
// ------------------------------------------------------------------------
// [Dialogs] QR, 검색, 수동입력
// ------------------------------------------------------------------------
void _showHostQRDialog() {
if (_net.hostIp == null || _net.hostPort == null) return;
final qrData = jsonEncode({'ip': _net.hostIp, 'port': _net.hostPort});
@@ -394,7 +479,7 @@ class _LobbyScreenState extends State<LobbyScreen> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text("친구 초대", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
const Text("초대 QR 코드", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(10),
@@ -444,7 +529,7 @@ class _LobbyScreenState extends State<LobbyScreen> {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text("방 찾"),
title: const Text("방 찾는 중..."),
content: SizedBox(
width: double.maxFinite,
height: 300,
+2 -2
View File
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
import 'package:playwith_core/playwith_core.dart';
import 'package:playwith_game_quiz/quiz_game.dart';
import 'login_screen.dart'; // [수정] 인트로 스크린 import (경로가 다르면 수정 필요)
import 'intro/intro_screen.dart'; // 만약 intro 폴더에 넣으셨다면 이 경로 사용
import 'lobby_screen.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
@@ -15,7 +15,7 @@ Future<void> main() async {
SoundKey.win: 'audio/win.mp3',
SoundKey.click: 'audio/correct.mp3',
});
await MobileAds.instance.initialize(); // [추가]
await NotificationManager().initialize();
runApp(const PlayWithApp());
+79 -3
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:playwith_core/playwith_core.dart'; // AvatarWidget 포함됨
import 'package:url_launcher/url_launcher.dart'; // [추가] 링크 이동용
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@@ -24,6 +25,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
super.dispose();
}
// [추가] 홈페이지 열기 함수
Future<void> _launchHomepage() async {
// 이동할 홈페이지 주소를 입력하세요
final Uri url = Uri.parse('https://lunaticbum.kr"');
try {
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
throw Exception('Could not launch $url');
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("페이지를 열 수 없습니다.")),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -41,7 +60,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
// 아바타 변경 영역
GestureDetector(
onTap: () => _settings.pickProfileImage(),
child: Stack(
@@ -70,7 +88,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 20),
// 닉네임 입력
TextField(
controller: _nickController,
decoration: const InputDecoration(
@@ -83,7 +100,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 10),
// 기본 아바타 색상 선택 (이미지 없을 때 사용)
const Align(alignment: Alignment.centerLeft, child: Text("기본 배경색")),
const SizedBox(height: 5),
SingleChildScrollView(
@@ -171,6 +187,66 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
),
),
const SizedBox(height: 20),
// 3. 개발자 옵션 (디버그 로그)
_buildSectionTitle("개발자 옵션"),
Card(
child: SwitchListTile(
title: const Text("디버그 로그 표시"),
subtitle: const Text("로비 화면 하단에 네트워크 로그를 표시합니다."),
value: _settings.isShowDebugLog,
onChanged: (val) => _settings.toggleDebugLog(val),
),
),
const SizedBox(height: 20),
// [추가] 4. 정보 섹션 (라이선스)
_buildSectionTitle("정보"),
Card(
child: ListTile(
leading: const Icon(Icons.description_outlined),
title: const Text("오픈소스 라이선스"),
subtitle: const Text("앱에 사용된 라이브러리 정보"),
trailing: const Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey),
onTap: () {
// 플러터 내장 라이선스 페이지 호출
showLicensePage(
context: context,
applicationName: "PlayWith",
applicationVersion: "1.0.0",
// applicationIcon: Image.asset('assets/icon.png', width: 50), // 아이콘이 있다면 주석 해제
);
},
),
),
const SizedBox(height: 40),
// [추가] 하단 카피라이트 & 링크
GestureDetector(
onTap: _launchHomepage,
child: Column(
children: const [
Text(
"© 2025 lunaticbum. All rights reserved.",
style: TextStyle(color: Colors.grey, fontSize: 12),
),
SizedBox(height: 4),
Text(
"https://lunaticbum.kr", // 보여줄 텍스트
style: TextStyle(
color: Colors.blueAccent,
fontSize: 12,
decoration: TextDecoration.underline
),
),
],
),
),
const SizedBox(height: 30),
],
);
},