feat(multidispositivo): reconnection, impostor awareness and protocol fixes

Fixes
- SnapshotPartidaOnline no longer serializes esImpostor unless the game is
  over. Every phase change was broadcasting the impostor roles in clear to
  all clients.
- The impostor clue travels in its own field and only when the game enables
  it. It used to be sent as the category key ("todas" when no category was
  picked) and was overwritten by each phase snapshot.
- Eliminated players can no longer vote nor be voted for, on both the client
  screen and the host listener.
- Nearby listeners are removed on dispose; votes are no longer dispatched
  twice; votacionResultado no longer triggers two navigations.
- _jugadoresHostControlados handed the secret word to the host's own
  impostors in the payload.
- Impostor cap unified as maxImpostoresPara(n) for both modes, and the
  silent clamp in multi-device now reports the effective number.
- palabraAleatoria uses Random.secure.

Impostors know each other
- ConfigPartida.impostoresSeConocen, on by default. companerosImpostores is
  nullable: null means nothing to show, an empty list means "you are the
  only impostor".

Reconnection
- IdentidadDispositivo persists a stable device id; the host uses it as the
  clientId so a phone that drops and returns is the same client. Falls back
  to the endpointId for clients that do not send one.
- Usuario.absorbidoDe records the original owner when the host takes over a
  disconnected player, and they are handed back automatically on return.
- New solicitarResync/resync messages: the host replies with the current
  phase plus that client's own players, and the client jumps straight to the
  running phase.
- Readiness is keyed by clientId instead of endpointId, and a disconnected
  client no longer blocks the round.
- The retry gives up after three minutes, only reconnects to the host it
  belonged to, and is cancelled correctly while shutting down.

Per-word clue support
- The word bank loader accepts both the old list-of-strings format and the
  new one carrying a clue per word, falling back to the category clue.

Not verified on real devices: Nearby reconnection timing still needs two
Android phones.
This commit is contained in:
2026-07-25 20:36:32 +02:00
parent bad641653c
commit 863690168c
23 changed files with 1284 additions and 235 deletions
+118 -10
View File
@@ -3,6 +3,7 @@ import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:provider/provider.dart';
import 'package:farolero/l10n/generated/app_localizations.dart';
import '../modelos/jugador.dart';
import '../modelos/partida.dart';
import '../modelos/inicio_partida_multijugador.dart';
import '../modelos/snapshot_partida_online.dart';
import '../modelos/usuario.dart';
@@ -41,10 +42,12 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
// Estado del juego recibido del host
String? _palabraRecibida;
bool _esImpostor = false;
String? _pistaCategoria;
String? _pistaImpostor;
String? _partidaId;
final List<Jugador> _jugadores = [];
final List<JugadorInicioPartida> _jugadoresControlados = [];
OnMensajeCallback? _listenerMensajes;
ServicioNearby? _nearby;
@override
void initState() {
@@ -61,7 +64,8 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
void _registrarListenerPartida() {
final nearby = context.read<ServicioNearby>();
nearby.onMensaje((endpointId, mensaje) {
_nearby = nearby;
_listenerMensajes = (endpointId, mensaje) {
if (!mounted) return;
if (mensaje.tipo == TipoMensaje.partidaInicio) {
// El host ha iniciado la partida — nos ha enviado nuestra palabra
@@ -105,7 +109,9 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
);
}
}
_pistaCategoria = mensaje.datos['categoria'] as String?;
// La pista solo llega si la partida la tiene activada; la categoría
// no vale como pista porque puede ser 'todas'.
_pistaImpostor = mensaje.datos['pistaImpostor'] as String?;
_partidaId = (mensaje.datos['roomId'] as String?) ??
nearby.roomId ??
(mensaje.datos['clientId'] as String?) ??
@@ -115,6 +121,8 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
if (mounted && (_jugadoresControlados.isNotEmpty || _palabraRecibida != null)) {
_navegarAPalabra();
}
} else if (mensaje.tipo == TipoMensaje.resync) {
_aplicarResync(mensaje.datos);
} else if (mensaje.tipo == TipoMensaje.fase) {
final fase = mensaje.datos['fase'] as String?;
_actualizarSnapshotSiExiste(mensaje.datos);
@@ -128,7 +136,43 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
_actualizarSnapshotSiExiste(mensaje.datos);
if (mounted) _navegarFinPartida(mensaje.datos);
}
};
nearby.onMensaje(_listenerMensajes!);
}
/// Reincorpora este móvil a una partida ya empezada tras una caída.
///
/// El host manda el estado completo, así que se reconstruye todo —jugadores
/// controlados, pista, censo— antes de saltar a la pantalla de la fase en
/// curso. Se descartan las rutas viejas: la pila de antes ya no vale.
void _aplicarResync(Map<String, dynamic> datos) {
final controlados = (datos['jugadores'] as List<dynamic>? ?? const [])
.map((json) => JugadorInicioPartida.fromJson(
json as Map<String, dynamic>,
))
.toList();
setState(() {
_jugadoresControlados
..clear()
..addAll(controlados);
_pistaImpostor = datos['pistaImpostor'] as String? ?? _pistaImpostor;
_partidaId = (datos['roomId'] as String?) ??
_partidaId ??
context.read<ServicioNearby>().roomId;
});
_actualizarSnapshotSiExiste(datos);
if (!mounted) return;
Navigator.of(context).popUntil((route) => route.isFirst);
final fase = datos['fase'] as String?;
if (fase == null || fase == FaseJuego.verPalabra.name) {
// Aún no ha empezado el debate: que vuelva a ver su palabra.
if (_jugadoresControlados.isNotEmpty) _navegarAPalabra();
return;
}
_navegarSegunFase(fase, datos);
}
void _navegarAPalabra() {
@@ -137,7 +181,7 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
MaterialPageRoute(
builder: (_) => PantallaPalabrasCliente(
jugadores: List.unmodifiable(_jugadoresControlados),
pistaCategoria: _pistaCategoria,
pistaImpostor: _pistaImpostor,
onTodosVistos: () {
final nearby = context.read<ServicioNearby>();
if (nearby.hostEndpointId != null) {
@@ -159,7 +203,7 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
builder: (_) => PantallaPalabraCliente(
palabra: _palabraRecibida ?? '',
esImpostor: _esImpostor,
pistaCategoria: _pistaCategoria,
pistaImpostor: _pistaImpostor,
onVisto: () {
// Enviar "listo" al host y volver a la espera
final nearby = context.read<ServicioNearby>();
@@ -190,7 +234,7 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
_partidaId = (datos['roomId'] as String?) ??
_partidaId ??
context.read<ServicioNearby>().roomId;
_pistaCategoria = (datos['categoria'] as String?) ?? _pistaCategoria;
});
}
@@ -206,7 +250,7 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
primerTurnoNombre:
datosFase?['primerTurnoNombre'] as String?,
partidaId: _partidaId ?? context.read<ServicioNearby>().roomId,
pistaCategoria: _pistaCategoria,
pistaImpostor: _pistaImpostor,
jugadores: List.unmodifiable(_jugadores),
jugadoresControlados: List.unmodifiable(_jugadoresControlados),
onSolicitarVotacion: () {
@@ -232,7 +276,7 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
jugadores: _jugadores,
jugadoresControlados: List.unmodifiable(_jugadoresControlados),
partidaId: _partidaId ?? context.read<ServicioNearby>().roomId,
pistaCategoria: _pistaCategoria,
pistaImpostor: _pistaImpostor,
onVotos: (votos) {
final nearby = context.read<ServicioNearby>();
if (nearby.hostEndpointId != null) {
@@ -273,7 +317,7 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
builder: (_) => PantallaResultadoOnline(
snapshot: snapshot,
jugadoresControlados: List.unmodifiable(_jugadoresControlados),
pistaCategoria: _pistaCategoria,
pistaImpostor: _pistaImpostor,
),
),
);
@@ -287,13 +331,15 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
builder: (_) => PantallaFinPartidaOnline(
snapshot: snapshot,
jugadoresControlados: List.unmodifiable(_jugadoresControlados),
pistaCategoria: _pistaCategoria,
pistaImpostor: _pistaImpostor,
),
),
);
}
@override
void dispose() {
final listener = _listenerMensajes;
if (listener != null) _nearby?.removeMensajeListener(listener);
_nombreController.dispose();
super.dispose();
}
@@ -419,6 +465,10 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
final l10n = AppLocalizations.of(context)!;
final nearby = context.watch<ServicioNearby>();
if (nearby.reconectando && !nearby.conectado) {
return _buildReconectando(context, l10n, nearby);
}
// Si estamos conectados → pantalla de espera
if (nearby.conectado && !nearby.esHost) {
return _buildPantallaEspera(context, l10n);
@@ -704,6 +754,64 @@ class _PantallaUnirseState extends State<PantallaUnirse> {
);
}
// ==================== RECONEXIÓN ====================
Widget _buildReconectando(
BuildContext context,
AppLocalizations l10n,
ServicioNearby nearby,
) {
return Scaffold(
appBar: AppBar(
title: Text(_salaSeleccionada ?? l10n.joinGameTitle),
automaticallyImplyLeading: false,
actions: [
IconButton(
tooltip: l10n.leaveGame,
icon: IconoFarolero(Icons.close),
onPressed: () async {
await nearby.desconectar();
if (!context.mounted) return;
setState(() {
_buscando = false;
_conectando = false;
});
},
),
],
),
body: FondoFarolero(
intenso: true,
child: Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const _JoinLobbySignalArt(height: 180),
const SizedBox(height: 16),
EncabezadoFarolero(
icono: Icons.wifi_tethering_off,
titulo: l10n.reconnecting,
subtitulo: l10n.reconnectingHint,
color: TemaApp.colorNaranja,
trailing: const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 2.4,
color: TemaApp.colorNaranja,
),
),
),
],
),
),
),
),
);
}
// ==================== ESPERA ====================
Widget _buildPantallaEspera(BuildContext context, AppLocalizations l10n) {