Files
farolero/lib/pantallas/pantalla_lobby_host.dart
ShanaiaBot d3fc3386f9 feat(multi-device): host puede participar como jugador
- Añadido modelo Usuario con pool de usuarios sincronizado
- El host ahora recibe palabra y rol como cualquier jugador
- UI de selección de perfil en pantallas de lobby
- Los clientes pueden ver usuarios del servidor o crear nuevos
- El juego no inicia hasta que el host selecciona perfil
2026-04-24 18:47:56 +02:00

324 lines
11 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:farolero/l10n/generated/app_localizations.dart';
import '../modelos/usuario.dart';
import '../servicios/servicio_nearby.dart';
import '../tema/tema_app.dart';
/// Pantalla de lobby del host: muestra QR y lista de jugadores conectados
class PantallaLobbyHost extends StatefulWidget {
final String nombreSala;
final VoidCallback onIniciar;
const PantallaLobbyHost({
super.key,
required this.nombreSala,
required this.onIniciar,
});
@override
State<PantallaLobbyHost> createState() => _PantallaLobbyHostState();
}
class _PantallaLobbyHostState extends State<PantallaLobbyHost> {
bool _iniciando = false;
String? _perfilSeleccionado;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final nearby = context.watch<ServicioNearby>();
final jugadores = nearby.jugadores;
final totalJugadores = jugadores.length + 1; // +1 host
return Scaffold(
appBar: AppBar(
title: Text(widget.nombreSala),
leading: IconButton(
icon: const Icon(Icons.close),
onPressed: () async {
await nearby.desconectar();
if (context.mounted) Navigator.pop(context);
},
),
),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
// QR Code
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
),
child: QrImageView(
data: nearby.generarDatosQR(widget.nombreSala),
version: QrVersions.auto,
size: 180,
backgroundColor: Colors.white,
),
),
const SizedBox(height: 12),
Text(
l10n.scanToJoin,
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 24),
// Selección de perfil
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.selectYourProfile,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
value: _perfilSeleccionado,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.person),
hintText: l10n.selectProfile,
border: const OutlineInputBorder(),
),
items: [
// Opción para crear nuevo usuario
DropdownMenuItem<String>(
value: '_new_',
child: Row(
children: [
const Icon(Icons.add, size: 18),
const SizedBox(width: 8),
Text(l10n.createNewUser),
],
),
),
// Usuarios existentes
...nearby.usuarios.map((usuario) {
return DropdownMenuItem<String>(
value: usuario.nombre,
child: Row(
children: [
Text(usuario.avatar ?? '👤'),
const SizedBox(width: 8),
Text(usuario.nombre),
],
),
);
}),
],
onChanged: (valor) {
if (valor == '_new_') {
_crearNuevoUsuario(context);
} else {
setState(() => _perfilSeleccionado = valor);
}
},
),
],
),
),
),
const SizedBox(height: 16),
// Lista de jugadores
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
l10n.connectedPlayers,
style: Theme.of(context).textTheme.titleLarge,
),
const Spacer(),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 4,
),
decoration: BoxDecoration(
color: totalJugadores >= 3
? TemaApp.colorVerde.withValues(alpha: 0.2)
: TemaApp.colorNaranja.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'$totalJugadores',
style: TextStyle(
color: totalJugadores >= 3
? TemaApp.colorVerde
: TemaApp.colorNaranja,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 12),
// Host (yo)
_buildJugadorTile(
nombre: nearby.miNombre ?? 'Host',
esHost: true,
),
// Jugadores conectados
Expanded(
child: jugadores.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'📱',
style: TextStyle(fontSize: 48),
),
const SizedBox(height: 12),
Text(
l10n.waitingForPlayers,
style: Theme.of(context).textTheme.bodyLarge,
),
],
),
)
: ListView.builder(
itemCount: jugadores.length,
itemBuilder: (context, index) {
final j = jugadores[index];
return _buildJugadorTile(nombre: j.nombre);
},
),
),
],
),
),
// Botón iniciar
if (totalJugadores < 3)
Text(
l10n.needMorePlayers(3 - totalJugadores),
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: TemaApp.colorNaranja),
),
const SizedBox(height: 12),
if (_perfilSeleccionado == null)
Text(
l10n.selectProfile,
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: TemaApp.colorNaranja),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed:
totalJugadores >= 3 &&
_perfilSeleccionado != null &&
!_iniciando
? () {
setState(() => _iniciando = true);
widget.onIniciar();
}
: null,
icon: const Icon(Icons.play_arrow),
label: Text(_iniciando ? l10n.starting : l10n.startGame),
),
),
],
),
),
);
}
Widget _buildJugadorTile({required String nombre, bool esHost = false}) {
return Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: TemaApp.colorTarjeta,
borderRadius: BorderRadius.circular(12),
border: esHost
? Border.all(color: TemaApp.colorAcento.withValues(alpha: 0.5))
: null,
),
child: Row(
children: [
Text(esHost ? '👑' : '🎭', style: const TextStyle(fontSize: 20)),
const SizedBox(width: 12),
Expanded(
child: Text(nombre, style: Theme.of(context).textTheme.titleMedium),
),
if (esHost)
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: TemaApp.colorAcento.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'HOST',
style: TextStyle(
color: TemaApp.colorAcento,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}
Future<void> _crearNuevoUsuario(BuildContext context) async {
final l10n = AppLocalizations.of(context)!;
final controller = TextEditingController();
final nearby = context.read<ServicioNearby>();
final nombre = await showDialog<String>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.createNewUser),
content: TextField(
controller: controller,
autofocus: true,
textCapitalization: TextCapitalization.words,
decoration: InputDecoration(
hintText: l10n.yourName,
prefixIcon: const Icon(Icons.person),
),
onSubmitted: (v) => Navigator.pop(ctx, v),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: Text(l10n.cancel),
),
TextButton(
onPressed: () => Navigator.pop(ctx, controller.text),
child: Text(l10n.accept),
),
],
),
);
if (nombre != null && nombre.trim().isNotEmpty) {
final nuevoUsuario = Usuario(
id: DateTime.now().millisecondsSinceEpoch.toString(),
nombre: nombre.trim(),
);
nearby.agregarUsuario(nuevoUsuario);
setState(() => _perfilSeleccionado = nombre.trim());
}
}
}