feat: Implement multiplayer game session management
Some checks failed
Build & Deploy Farolero / Análisis de código (push) Has been cancelled
Build & Deploy Farolero / Build APK + AAB release (push) Has been cancelled

- Add models for managing player assignments and game session initialization in `inicio_partida_multijugador.dart`.
- Create a multiplayer room state management system in `sala_multijugador.dart`, including user registration, selection, and session validation.
- Develop a UI screen for displaying player words sequentially in `pantalla_palabras_cliente.dart`.
- Implement unit tests for the multiplayer session management and player assignment logic in `inicio_partida_multijugador_test.dart` and `sala_multijugador_test.dart`.
This commit is contained in:
Javier Bautista Fernández
2026-04-27 14:02:33 +02:00
parent 4a1abd0be0
commit a8d5b0f002
14 changed files with 1779 additions and 421 deletions

View File

@@ -1,4 +1,4 @@
import 'package:flutter/material.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';
@@ -6,7 +6,7 @@ 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
/// Lobby del host. El host es autoridad de sala y también cliente local.
class PantallaLobbyHost extends StatefulWidget {
final String nombreSala;
final VoidCallback onIniciar;
@@ -23,14 +23,16 @@ class PantallaLobbyHost extends StatefulWidget {
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
final sala = nearby.estadoSala;
final usuarios = nearby.usuarios;
final seleccionados = usuarios.where((u) => u.estaSeleccionado).length;
final validacionInicio = sala?.validarInicio();
final puedeIniciar = validacionInicio?.exitoso ?? false;
return Scaffold(
appBar: AppBar(
@@ -47,7 +49,6 @@ class _PantallaLobbyHostState extends State<PantallaLobbyHost> {
padding: const EdgeInsets.all(24),
child: Column(
children: [
// QR Code
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
@@ -57,174 +58,66 @@ class _PantallaLobbyHostState extends State<PantallaLobbyHost> {
child: QrImageView(
data: nearby.generarDatosQR(widget.nombreSala),
version: QrVersions.auto,
size: 180,
size: 160,
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>(
initialValue: _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);
}
},
),
],
),
),
),
Text(l10n.scanToJoin),
const SizedBox(height: 16),
// Lista de jugadores
_buildResumenSala(context, seleccionados, nearby.jugadores.length),
const SizedBox(height: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
child: Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
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,
Row(
children: [
Expanded(
child: Text(
'Usuarios de la partida',
style: Theme.of(context).textTheme.titleLarge,
),
),
),
IconButton.filledTonal(
onPressed: () => _crearNuevoUsuario(context),
icon: const Icon(Icons.person_add),
),
],
),
const SizedBox(height: 8),
Expanded(
child: usuarios.isEmpty
? Center(child: Text(l10n.waitingForPlayers))
: ListView.builder(
itemCount: usuarios.length,
itemBuilder: (context, index) =>
_buildUsuarioTile(context, usuarios[index]),
),
),
],
),
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)
if (!puedeIniciar)
Text(
l10n.selectProfile,
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: TemaApp.colorNaranja),
_mensajeValidacion(validacionInicio?.codigo),
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(color: TemaApp.colorNaranja),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed:
totalJugadores >= 3 &&
_perfilSeleccionado != null &&
!_iniciando
onPressed: puedeIniciar && !_iniciando
? () {
setState(() => _iniciando = true);
widget.onIniciar();
@@ -240,45 +133,129 @@ class _PantallaLobbyHostState extends State<PantallaLobbyHost> {
);
}
Widget _buildJugadorTile({required String nombre, bool esHost = false}) {
Widget _buildResumenSala(
BuildContext context,
int seleccionados,
int clientesRemotos,
) {
return Row(
children: [
Expanded(
child: _buildStat(
context,
icon: Icons.groups,
label: 'Jugadores seleccionados',
value: '$seleccionados',
ok: seleccionados >= 3,
),
),
const SizedBox(width: 8),
Expanded(
child: _buildStat(
context,
icon: Icons.devices,
label: 'Móviles conectados',
value: '${clientesRemotos + 1}',
ok: true,
),
),
],
);
}
Widget _buildStat(
BuildContext context, {
required IconData icon,
required String label,
required String value,
required bool ok,
}) {
final color = ok ? TemaApp.colorVerde : TemaApp.colorNaranja;
return Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: TemaApp.colorTarjeta,
color: color.withValues(alpha: 0.18),
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),
Icon(icon, color: color),
const SizedBox(width: 8),
Expanded(
child: Text(nombre, style: Theme.of(context).textTheme.titleMedium),
child: Text(label, style: Theme.of(context).textTheme.bodySmall),
),
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,
),
),
Text(
value,
style: TextStyle(color: color, fontWeight: FontWeight.bold),
),
],
),
);
}
Widget _buildUsuarioTile(BuildContext context, Usuario usuario) {
final nearby = context.read<ServicioNearby>();
final miClientId = nearby.miClientId;
final seleccionadoPorMi = usuario.clienteIdSeleccionado == miClientId;
final seleccionadoPorOtro =
usuario.estaSeleccionado && usuario.clienteIdSeleccionado != miClientId;
return ListTile(
leading: CircleAvatar(
backgroundColor: seleccionadoPorMi
? TemaApp.colorVerde
: seleccionadoPorOtro
? TemaApp.colorNaranja
: TemaApp.colorTarjeta,
child: Text(usuario.avatar ?? '👤'),
),
title: Text(usuario.nombre),
subtitle: Text(
seleccionadoPorMi
? 'Seleccionado por este móvil'
: seleccionadoPorOtro
? 'Seleccionado por otro cliente'
: 'Disponible',
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (seleccionadoPorMi)
IconButton(
tooltip: 'Liberar',
icon: const Icon(Icons.close),
onPressed: () => nearby.liberarUsuarioSala(usuario.id),
)
else if (!seleccionadoPorOtro)
IconButton(
tooltip: 'Seleccionar',
icon: const Icon(Icons.check_circle_outline),
onPressed: () => nearby.seleccionarUsuarioSala(usuario.id),
),
if (!usuario.estaSeleccionado)
IconButton(
tooltip: 'Eliminar',
icon: const Icon(Icons.delete_outline, color: TemaApp.colorAcento),
onPressed: () => nearby.eliminarUsuarioSala(usuario.id),
),
],
),
);
}
String _mensajeValidacion(String? codigo) {
switch (codigo) {
case 'faltan_jugadores':
return 'Seleccioná al menos 3 usuarios para iniciar.';
case 'host_sin_usuario':
return 'El móvil servidor debe seleccionar al menos un usuario.';
case 'sala_cerrada':
return 'La sala ya no está en lobby.';
default:
return 'Completá la selección de usuarios para iniciar.';
}
}
Future<void> _crearNuevoUsuario(BuildContext context) async {
final l10n = AppLocalizations.of(context)!;
final controller = TextEditingController();
@@ -312,12 +289,7 @@ class _PantallaLobbyHostState extends State<PantallaLobbyHost> {
);
if (nombre != null && nombre.trim().isNotEmpty) {
final nuevoUsuario = Usuario(
id: DateTime.now().millisecondsSinceEpoch.toString(),
nombre: nombre.trim(),
);
nearby.agregarUsuario(nuevoUsuario);
setState(() => _perfilSeleccionado = nombre.trim());
await nearby.crearUsuarioSala(nombre.trim(), seleccionar: true);
}
}
}