..
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import 'dart:io'; // Platform 확인용
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:playwith_core/playwith_core.dart'; // Core 패키지 import
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:playwith_core/playwith_core.dart';
|
||||
import 'lobby_screen.dart';
|
||||
|
||||
class IntroScreen extends StatefulWidget {
|
||||
@@ -12,13 +14,47 @@ class IntroScreen extends StatefulWidget {
|
||||
class _IntroScreenState extends State<IntroScreen> {
|
||||
final _nicknameController = TextEditingController();
|
||||
|
||||
void _enterLobby() {
|
||||
if (_nicknameController.text.trim().isEmpty) return;
|
||||
Future<void> _enterLobby() async {
|
||||
if (_nicknameController.text.trim().isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text("닉네임을 입력해주세요.")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Core 패키지의 NetworkManager 초기화
|
||||
// [수정됨] 플랫폼별 권한 분기 처리
|
||||
if (Platform.isAndroid) {
|
||||
// 🤖 안드로이드: 명시적 권한 요청 필요
|
||||
Map<Permission, PermissionStatus> statuses = await [
|
||||
Permission.location, // 안드로이드 12 이하
|
||||
Permission.nearbyWifiDevices, // 안드로이드 13 이상
|
||||
].request();
|
||||
|
||||
// 로그 확인용
|
||||
bool isNearby = statuses[Permission.nearbyWifiDevices]?.isGranted ?? false;
|
||||
bool isLocation = statuses[Permission.location]?.isGranted ?? false;
|
||||
print("Android 권한 Check: Nearby=$isNearby, Location=$isLocation");
|
||||
|
||||
// 둘 다 거부되면 진행 불가 (단, 버전에 따라 하나만 있어도 됨)
|
||||
// 여기서는 "둘 다 false일 때만" 막는 것으로 완화
|
||||
if (!isNearby && !isLocation) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text("❌ 안드로이드는 권한이 필요합니다.")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
} else if (Platform.isIOS) {
|
||||
// 🍎 iOS: 별도 요청 불필요
|
||||
// Info.plist에 설정만 잘 되어 있다면,
|
||||
// NetworkManager가 start() 될 때 시스템이 알아서 물어봅니다.
|
||||
print("iOS는 권한 체크를 건너뜁니다. (실행 시 자동 팝업됨)");
|
||||
}
|
||||
|
||||
// 초기화 및 입장
|
||||
NetworkManager().initialize(nickname: _nicknameController.text.trim());
|
||||
|
||||
// 2. 로비 화면으로 이동
|
||||
if (!mounted) return;
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const LobbyScreen()),
|
||||
|
||||
+430
-130
@@ -1,6 +1,10 @@
|
||||
import 'dart:convert';
|
||||
import 'package:bonsoir/bonsoir.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:playwith_core/playwith_core.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
import 'package:playwith_core/playwith_core.dart'; // GameChatOverlay 포함됨
|
||||
import 'package:playwith_game_quiz/quiz_game.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
|
||||
class LobbyScreen extends StatefulWidget {
|
||||
const LobbyScreen({super.key});
|
||||
@@ -10,174 +14,470 @@ class LobbyScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _LobbyScreenState extends State<LobbyScreen> {
|
||||
final _net = NetworkManager(); // Singleton 인스턴스
|
||||
final _net = NetworkManager();
|
||||
final List<String> _logs = [];
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
|
||||
@override
|
||||
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,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
_net.messageStream.listen((data) {
|
||||
if (data['type'] == 'GAME_START') {
|
||||
final String gameId = data['gameId'];
|
||||
if (gameId == 'quiz_ox') {
|
||||
_startGameAndNavigate(QuizGame());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// [핵심] 채팅 오버레이 적용
|
||||
void _startGameAndNavigate(BaseGame game) {
|
||||
if (!mounted) return;
|
||||
|
||||
game.onStart();
|
||||
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) {
|
||||
Widget gameView;
|
||||
if (_net.role == NetworkRole.host) {
|
||||
gameView = game.buildHostView(context);
|
||||
} else {
|
||||
gameView = game.buildGuestView(context);
|
||||
}
|
||||
|
||||
// 플랫폼 구조: 게임 화면 위에 채팅창 오버레이
|
||||
return Stack(
|
||||
children: [
|
||||
gameView, // 1. 게임 화면
|
||||
const SafeArea(
|
||||
child: GameChatOverlay(), // 2. 채팅창 (Core 제공)
|
||||
),
|
||||
],
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// NetworkManager의 상태(notifyListeners)가 변경될 때마다 화면 다시 그림
|
||||
return ListenableBuilder(
|
||||
listenable: _net,
|
||||
builder: (context, child) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('안녕하세요, ${_net.me.nickname}님'),
|
||||
title: Text('대기실: ${_net.me.nickname}'),
|
||||
actions: [
|
||||
if (_net.role == NetworkRole.host)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.qr_code, size: 30),
|
||||
onPressed: () => _showHostQRDialog(),
|
||||
),
|
||||
|
||||
if (_net.role != NetworkRole.none)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => _net.stopNetwork(), // 연결 끊기
|
||||
icon: const Icon(Icons.exit_to_app),
|
||||
onPressed: () => _net.stopNetwork(),
|
||||
)
|
||||
],
|
||||
),
|
||||
body: _buildBody(),
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(flex: 3, child: _buildBody()),
|
||||
const Divider(thickness: 2, color: Colors.grey),
|
||||
_buildDebugConsole(),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody() {
|
||||
// 1. 아무 역할도 없을 때 -> 선택 화면
|
||||
if (_net.role == NetworkRole.none) {
|
||||
return Center(
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
_BigButton(
|
||||
title: "방 만들기\n(Host)",
|
||||
color: Colors.blue[100]!,
|
||||
onTap: () => _net.startHosting("${_net.me.nickname}의 방"),
|
||||
),
|
||||
_BigButton(
|
||||
title: "방 찾기\n(Guest)",
|
||||
color: Colors.green[100]!,
|
||||
onTap: () => _showRoomListDialog(),
|
||||
),
|
||||
],
|
||||
Widget _buildDebugConsole() {
|
||||
return Column(
|
||||
children: [
|
||||
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)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Host 상태일 때 -> 대기실 화면
|
||||
if (_net.role == NetworkRole.host) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text("👑 방장입니다", style: TextStyle(fontSize: 24)),
|
||||
const SizedBox(height: 20),
|
||||
const CircularProgressIndicator(),
|
||||
const SizedBox(height: 20),
|
||||
const Text("참가자를 기다리는 중..."),
|
||||
// TODO: 여기에 접속한 게스트 목록 표시 예정
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Guest 상태일 때 -> 대기실 화면
|
||||
if (_net.role == NetworkRole.guest) {
|
||||
return const Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text("✅ 접속 완료!", style: TextStyle(fontSize: 24)),
|
||||
SizedBox(height: 20),
|
||||
Text("방장이 게임을 시작하기를 기다리세요."),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return const SizedBox();
|
||||
}
|
||||
|
||||
// [Guest용] 방 목록 팝업
|
||||
void _showRoomListDialog() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return AlertDialog(
|
||||
title: const Text("방 찾는 중..."),
|
||||
content: SizedBox(
|
||||
width: double.maxFinite,
|
||||
height: 300,
|
||||
child: StreamBuilder<List<BonsoirService>>(
|
||||
stream: _net.discoverRooms(), // Core의 방 찾기 스트림
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData || snapshot.data!.isEmpty) {
|
||||
return const Center(child: Text("발견된 방이 없습니다.\n(같은 와이파이인지 확인하세요)"));
|
||||
}
|
||||
|
||||
final services = snapshot.data!;
|
||||
return ListView.builder(
|
||||
itemCount: services.length,
|
||||
itemBuilder: (context, index) {
|
||||
final service = services[index];
|
||||
// 이름 포맷: "방이름#ID" -> "방이름"만 파싱
|
||||
final displayName = service.name.split('#').first;
|
||||
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.meeting_room),
|
||||
title: Text(displayName),
|
||||
subtitle: Text(service.host ?? "IP 정보 없음"),
|
||||
onTap: () async {
|
||||
Navigator.pop(context); // 다이얼로그 닫기
|
||||
// 해당 방으로 접속 시도 (IP는 service.attributes나 resolve 과정 필요)
|
||||
// Bonsoir는 service.host에 호스트네임이 들어오므로 resolve 필요
|
||||
// MVP 단계에서는 간단히:
|
||||
await _resolveAndJoin(service);
|
||||
},
|
||||
);
|
||||
},
|
||||
SizedBox(
|
||||
height: 150,
|
||||
child: Container(
|
||||
color: Colors.black,
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
itemCount: _logs.length,
|
||||
itemBuilder: (context, index) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
|
||||
child: Text(
|
||||
_logs[index],
|
||||
style: const TextStyle(color: Colors.greenAccent, fontSize: 12, fontFamily: 'Courier'),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Bonsoir Service Resolve (IP 주소 알아내기)
|
||||
Future<void> _resolveAndJoin(BonsoirService service) async {
|
||||
// 실제로는 service.resolve() 호출 후 IP 획득 과정을 거쳐야 함.
|
||||
// Bonsoir 패키지 특성상 resolve가 비동기로 돔.
|
||||
// MVP 간소화를 위해 service에 host 정보가 있다고 가정하거나
|
||||
// Broadcast 시점에 attributes에 IP를 넣는 방식을 추천하지만,
|
||||
// 일단 resolve 시도:
|
||||
if (service is BonsoirBroadcast) {
|
||||
// 이미 broadcast 객체라면 바로 정보가 있음 (내가 만든 방)
|
||||
} else {
|
||||
await service.resolve(service.resolveRealService);
|
||||
}
|
||||
|
||||
// IP가 ipv4 형태인지 확인 필요. 보통 service.ip 나 attributes 사용
|
||||
// 여기선 port만 확실하므로, 실제 IP 획득은 Bonsoir 예제 참고 필요
|
||||
// (테스트 환경에서는 보통 service.attributes에 {'ip': '192.168...'} 넣어서 보냄)
|
||||
|
||||
// *중요*: 실제 구현 시 NetworkManager.startHosting에서 attributes에 IP를 넣어주는게 가장 확실함.
|
||||
// 일단 현재 코드는 로직 흐름만 잡음.
|
||||
|
||||
// _net.joinRoom('192.168.0.xxx', service.port);
|
||||
Widget _buildBody() {
|
||||
if (_net.role == NetworkRole.none) {
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
_BigButton(
|
||||
title: "방 만들기\n(Host)",
|
||||
color: Colors.blue[100]!,
|
||||
icon: Icons.add_home_work,
|
||||
onTap: () {
|
||||
_net.startHosting("${_net.me.nickname}의 방");
|
||||
Future.delayed(const Duration(milliseconds: 500), () {
|
||||
if (mounted && _net.role == NetworkRole.host) _showHostQRDialog();
|
||||
});
|
||||
},
|
||||
),
|
||||
_BigButton(
|
||||
title: "방 찾기\n(Guest)",
|
||||
color: Colors.green[100]!,
|
||||
icon: Icons.search,
|
||||
onTap: () => _showRoomListDialog(),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
ElevatedButton.icon(
|
||||
icon: const Icon(Icons.qr_code_scanner, size: 28),
|
||||
label: const Text("QR 코드로 접속하기"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
|
||||
),
|
||||
onPressed: () => _openQRScanner(),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
TextButton(
|
||||
onPressed: () => _showManualJoinDialog(),
|
||||
child: const Text("IP 주소 직접 입력 (비상용)", style: TextStyle(color: Colors.grey)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
color: Colors.grey[100],
|
||||
width: double.infinity,
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(_net.role == NetworkRole.host ? Icons.wifi_tethering : Icons.wifi, color: Colors.blue),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
_net.role == NetworkRole.host ? "👑 방장 (나)" : "참가자 (나)",
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
if (_net.role == NetworkRole.host) ...[
|
||||
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)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const Divider(height: 1),
|
||||
|
||||
Expanded(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
const Text("참가자 목록", style: TextStyle(color: Colors.grey)),
|
||||
const SizedBox(height: 10),
|
||||
_buildUserTile(_net.me),
|
||||
..._net.guestList.map((guest) => _buildUserTile(guest)),
|
||||
|
||||
if (_net.guestList.isEmpty && _net.role == NetworkRole.host)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(40.0),
|
||||
child: Center(child: Text("참가자를 기다리는 중...\nQR 코드를 보여주세요.", textAlign: TextAlign.center, style: TextStyle(color: Colors.grey))),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
_buildReadyButton(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUserTile(UserInfo user) {
|
||||
bool isMe = user.id == _net.me.id;
|
||||
return Card(
|
||||
elevation: 2,
|
||||
color: user.isReady ? Colors.green[50] : Colors.white,
|
||||
margin: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: Color(user.colorValue),
|
||||
child: Text(user.nickname[0], style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
|
||||
),
|
||||
title: Text(
|
||||
user.nickname + (isMe ? " (나)" : ""),
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
trailing: user.isReady
|
||||
? const Icon(Icons.check_circle, color: Colors.green, size: 32)
|
||||
: const Icon(Icons.hourglass_empty, color: Colors.grey, size: 32),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildReadyButton() {
|
||||
bool isReady = _net.me.isReady;
|
||||
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))],
|
||||
),
|
||||
child: ElevatedButton(
|
||||
onPressed: canReady
|
||||
? () => _net.toggleReady()
|
||||
: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("참가자가 들어와야 게임을 시작할 수 있습니다.")));
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: !canReady
|
||||
? Colors.grey
|
||||
: (isReady ? Colors.redAccent : Colors.blueAccent),
|
||||
padding: const EdgeInsets.symmetric(vertical: 18),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
elevation: canReady ? 5 : 0,
|
||||
),
|
||||
child: Text(
|
||||
isReady ? "준비 취소 (WAIT)" : "준비 완료 (READY)",
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showHostQRDialog() {
|
||||
if (_net.hostIp == null || _net.hostPort == null) return;
|
||||
final qrData = jsonEncode({'ip': _net.hostIp, 'port': _net.hostPort});
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text("초대 QR 코드", style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(border: Border.all(color: Colors.black12), borderRadius: BorderRadius.circular(10)),
|
||||
child: QrImageView(data: qrData, version: QrVersions.auto, size: 220.0),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text("IP: ${_net.hostIp} / Port: ${_net.hostPort}", style: const TextStyle(color: Colors.grey)),
|
||||
const SizedBox(height: 20),
|
||||
ElevatedButton(onPressed: () => Navigator.pop(context), child: const Text("닫기"))
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _openQRScanner() {
|
||||
bool isScanCompleted = false;
|
||||
Navigator.of(context).push(MaterialPageRoute(
|
||||
builder: (context) => Scaffold(
|
||||
appBar: AppBar(title: const Text("QR 코드 스캔")),
|
||||
body: MobileScanner(
|
||||
onDetect: (capture) {
|
||||
if (isScanCompleted) return;
|
||||
final List<Barcode> barcodes = capture.barcodes;
|
||||
for (final barcode in barcodes) {
|
||||
final String? code = barcode.rawValue;
|
||||
if (code != null) {
|
||||
try {
|
||||
final data = jsonDecode(code);
|
||||
if (data['ip'] != null && data['port'] != null) {
|
||||
isScanCompleted = true;
|
||||
Navigator.pop(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("QR 인식 성공! 접속 중...")));
|
||||
_net.joinRoom(data['ip'], data['port']);
|
||||
return;
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
void _showRoomListDialog() {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text("방 찾는 중..."),
|
||||
content: SizedBox(
|
||||
width: double.maxFinite,
|
||||
height: 300,
|
||||
child: StreamBuilder<List<BonsoirService>>(
|
||||
stream: _net.discoverRooms(),
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData || snapshot.data!.isEmpty) {
|
||||
return const Center(child: Text("검색 중... (로그를 확인하세요)"));
|
||||
}
|
||||
final services = snapshot.data!;
|
||||
return ListView.builder(
|
||||
itemCount: services.length,
|
||||
itemBuilder: (context, index) {
|
||||
final service = services[index];
|
||||
final displayName = service.name.split('#').first;
|
||||
final ip = service.attributes?['ip'] ?? '알 수 없음';
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.meeting_room),
|
||||
title: Text(displayName),
|
||||
subtitle: Text("IP: $ip"),
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
if (service.attributes != null && service.attributes!['ip'] != null) {
|
||||
_net.joinRoom(service.attributes!['ip']!, service.port);
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text("닫기"))],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showManualJoinDialog() {
|
||||
final ipController = TextEditingController(text: "192.168.");
|
||||
final portController = TextEditingController();
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text("수동 접속"),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text("방장 화면의 IP/Port를 입력하세요."),
|
||||
TextField(controller: ipController, decoration: const InputDecoration(labelText: "IP")),
|
||||
TextField(controller: portController, decoration: const InputDecoration(labelText: "Port")),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text("취소")),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
final ip = ipController.text.trim();
|
||||
final port = int.tryParse(portController.text.trim());
|
||||
if (ip.isNotEmpty && port != null) {
|
||||
Navigator.pop(context);
|
||||
_net.joinRoom(ip, port);
|
||||
}
|
||||
},
|
||||
child: const Text("접속"),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BigButton extends StatelessWidget {
|
||||
final String title;
|
||||
final Color color;
|
||||
final IconData icon;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _BigButton({required this.title, required this.color, required this.onTap});
|
||||
|
||||
const _BigButton({required this.title, required this.color, required this.icon, required this.onTap});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: 150,
|
||||
height: 150,
|
||||
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(20)),
|
||||
child: Center(child: Text(title, textAlign: TextAlign.center, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold))),
|
||||
width: 140, height: 140,
|
||||
decoration: BoxDecoration(
|
||||
color: color, borderRadius: BorderRadius.circular(20),
|
||||
boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 10, offset: const Offset(0, 5))],
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(icon, size: 40, color: Colors.black54),
|
||||
const SizedBox(height: 10),
|
||||
Text(title, textAlign: TextAlign.center, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
+49
-1
@@ -1,13 +1,61 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:playwith_core/playwith_core.dart';
|
||||
import 'package:playwith_game_quiz/quiz_game.dart'; // 퀴즈 모듈 import
|
||||
import 'intro_screen.dart';
|
||||
|
||||
void main() {
|
||||
// 1. 플러터 바인딩 초기화
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
// 2. 사운드 리소스 주입 (여기가 핵심!)
|
||||
// AssetSource는 'assets/' 접두어를 자동으로 붙이므로 그 하위 경로만 적습니다.
|
||||
SoundManager().initialize(soundPaths: {
|
||||
SoundKey.bgm: 'audio/bgm.mp3',
|
||||
SoundKey.correct: 'audio/correct.mp3',
|
||||
SoundKey.wrong: 'audio/wrong.mp3',
|
||||
SoundKey.win: 'audio/win.mp3',
|
||||
});
|
||||
|
||||
runApp(const PlayWithApp());
|
||||
}
|
||||
|
||||
class PlayWithApp extends StatelessWidget {
|
||||
class PlayWithApp extends StatefulWidget {
|
||||
const PlayWithApp({super.key});
|
||||
|
||||
@override
|
||||
State<PlayWithApp> createState() => _PlayWithAppState();
|
||||
}
|
||||
|
||||
class _PlayWithAppState extends State<PlayWithApp> {
|
||||
final _net = NetworkManager();
|
||||
|
||||
// 등록된 게임 목록
|
||||
final List<BaseGame> _games = [
|
||||
QuizGame(), // 여기서 등록!
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
// [전역 라우팅] 네트워크 메시지를 감시하다가 'GAME_START'가 오면 해당 게임 실행
|
||||
_net.messageStream.listen((data) {
|
||||
if (data['type'] == 'GAME_START') {
|
||||
final String gameId = data['gameId'];
|
||||
|
||||
// ID에 맞는 게임 찾기
|
||||
final game = _games.firstWhere(
|
||||
(g) => g.id == gameId,
|
||||
orElse: () => throw Exception("Game not found: $gameId")
|
||||
);
|
||||
|
||||
// 게임 화면으로 이동 (네비게이터 키를 안 쓰고 있어서 간단히 처리 불가, 아래 설명 참조)
|
||||
// 실제로는 GlobalKey<NavigatorState>를 쓰거나, 현재 context를 찾아야 함.
|
||||
// MVP에서는 LobbyScreen 내부에서 처리하는 것이 안전함.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
|
||||
Reference in New Issue
Block a user