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
+142 -44
View File
@@ -9,6 +9,7 @@ import '../modelos/inicio_partida_multijugador.dart';
import '../modelos/jugador.dart';
import '../modelos/palabra.dart';
import '../modelos/partida.dart';
import '../modelos/sala_multijugador.dart';
import '../modelos/snapshot_partida_online.dart';
import '../servicios/servicio_historial_partidas.dart';
import '../servicios/servicio_nearby.dart';
@@ -40,6 +41,8 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
String? _primerTurnoNombre;
final Map<String, bool> _clientesListos = {};
final Map<String, String> _votosRecibidos = {};
OnMensajeCallback? _listenerMensajes;
ServicioNearby? _nearby;
@override
void initState() {
@@ -65,28 +68,118 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
void _registrarListeners() {
final nearby = context.read<ServicioNearby>();
nearby.onMensaje((endpointId, mensaje) {
_nearby = nearby;
_listenerMensajes = (endpointId, mensaje) {
if (!mounted) return;
if (mensaje.tipo == TipoMensaje.listo) {
setState(() => _clientesListos[endpointId] = true);
// Se indexa por clientId, no por endpointId: el endpoint cambia en
// cada reconexión y si no perderíamos el "ya la he visto".
final clientId = _clientIdDe(endpointId) ?? endpointId;
setState(() => _clientesListos[clientId] = true);
} else if (mensaje.tipo == TipoMensaje.unirse) {
// Con la partida ya en marcha, un `unirse` solo puede ser un móvil
// que vuelve tras caerse.
final nombre = mensaje.datos['nombre'] as String?;
if (nombre != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.playerRejoined(nombre)),
),
);
}
} else if (mensaje.tipo == TipoMensaje.solicitarResync) {
_responderResync(endpointId);
} else if (mensaje.tipo == TipoMensaje.voto) {
final votanteId = mensaje.datos['votanteId'] as String?;
final votoId =
mensaje.datos['votadoId'] as String? ??
mensaje.datos['votoporId'] as String?;
if (votanteId != null && votoId != null) {
context.read<EstadoJuego>().registrarVoto(votanteId, votoId);
setState(() => _votosRecibidos[votanteId] = votoId);
}
if (votanteId == null || votoId == null) return;
// Un jugador eliminado ya no vota, venga de donde venga el mensaje.
final partida = context.read<EstadoJuego>().partida;
final sigueVivo =
partida?.jugadoresActivos.any((j) => j.id == votanteId) ?? false;
if (!sigueVivo) return;
context.read<EstadoJuego>().registrarVoto(votanteId, votoId);
setState(() => _votosRecibidos[votanteId] = votoId);
}
});
};
nearby.onMensaje(_listenerMensajes!);
}
@override
void dispose() {
_timer?.cancel();
final listener = _listenerMensajes;
if (listener != null) _nearby?.removeMensajeListener(listener);
super.dispose();
}
String? _clientIdDe(String endpointId) {
return context
.read<ServicioNearby>()
.estadoSala
?.clientePorEndpoint(endpointId)
?.clientId;
}
/// Jugadores de la partida que controla un cliente concreto, con su palabra,
/// su rol y sus compañeros. Es lo que necesita un móvil para volver a jugar.
List<JugadorInicioPartida> _jugadoresDeCliente(
Partida partida,
EstadoSalaMultijugador sala,
String clientId,
) {
final estado = context.read<EstadoJuego>();
return sala
.usuariosPorCliente(clientId)
.where((usuario) => partida.jugadores.any((j) => j.id == usuario.id))
.map((usuario) {
final jugador = partida.jugadores.firstWhere(
(j) => j.id == usuario.id,
);
return JugadorInicioPartida(
jugadorId: jugador.id,
nombre: jugador.nombre,
esImpostor: jugador.esImpostor,
palabra: jugador.esImpostor ? null : partida.palabraSecreta,
companerosImpostores: estado.companerosImpostoresDe(jugador.id),
);
})
.toList();
}
/// Responde a un móvil que vuelve tras una caída con el estado completo:
/// en qué fase va la partida y qué jugadores le tocan.
Future<void> _responderResync(String endpointId) async {
final nearby = context.read<ServicioNearby>();
final estado = context.read<EstadoJuego>();
final partida = estado.partida;
final sala = nearby.estadoSala;
if (partida == null || sala == null) return;
final clientId = _clientIdDe(endpointId);
if (clientId == null) return;
final datos = _snapshot(fase: partida.fase.name).toJson();
datos['fase'] = partida.fase.name;
datos['jugadores'] = _jugadoresDeCliente(partida, sala, clientId)
.map((jugador) => jugador.toJson())
.toList();
if (partida.config.pistaImpostor) {
datos['pistaImpostor'] = partida.pistaImpostor;
}
if (partida.config.tiempoDebateSegundos != null) {
datos['tiempoDebateSegundos'] = partida.config.tiempoDebateSegundos;
}
if (_primerTurnoNombre != null) {
datos['primerTurnoNombre'] = _primerTurnoNombre;
}
await nearby.enviarResync(endpointId, datos);
if (mounted) setState(() {});
}
String _formatearTiempo(int segundos) {
final min = segundos ~/ 60;
final seg = segundos % 60;
@@ -152,8 +245,16 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
);
}
// Solo bloquean los clientes que siguen conectados: un móvil caído no
// puede impedir que avance la partida.
final clientesPendientes =
nearby.estadoSala?.clientes.values
.where((cliente) => !cliente.esHost && cliente.conectado)
.map((cliente) => cliente.clientId) ??
const <String>[];
final todosListos =
_hostListo && _clientesListos.length >= nearby.jugadores.length;
_hostListo &&
clientesPendientes.every((id) => _clientesListos[id] == true);
final todosVotaron = estado.todosHanVotado();
return Scaffold(
@@ -172,8 +273,8 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
partida,
nearby,
),
pistaCategoria: partida.config.pistaImpostor
? partida.categoriaReal
pistaImpostor: partida.config.pistaImpostor
? partida.pistaImpostor
: null,
),
),
@@ -287,7 +388,16 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
texto: AppLocalizations.of(context)!.assumeOnThisPhone,
icono: Icons.person_add_alt_1,
assetIconPath: 'assets/ui/generated/actions/action_add_player.webp',
onPressed: () => nearby.asumirUsuariosDesconectados(),
onPressed: () async {
// Son jugadores nuevos para este móvil: sus palabras están
// sin ver y sus votos sin emitir.
final fase = context.read<EstadoJuego>().partida?.fase;
await nearby.asumirUsuariosDesconectados();
if (!mounted) return;
setState(() {
if (fase == FaseJuego.verPalabra) _hostListo = false;
});
},
),
),
),
@@ -422,7 +532,9 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
(jugador) => _buildJugadorTile(
jugador.nombre,
false,
_clientesListos[jugador.endpointId] ?? false,
_clientesListos[_clientIdDe(jugador.endpointId) ??
jugador.endpointId] ??
false,
),
),
const SizedBox(height: 12),
@@ -451,22 +563,7 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
) {
final sala = nearby.estadoSala;
if (sala == null) return const [];
return sala
.usuariosPorCliente(sala.hostClientId)
.where((usuario) => partida.jugadores.any((j) => j.id == usuario.id))
.map((usuario) {
final jugador = partida.jugadores.firstWhere(
(j) => j.id == usuario.id,
);
return JugadorInicioPartida(
jugadorId: jugador.id,
nombre: jugador.nombre,
esImpostor: jugador.esImpostor,
palabra: jugador.palabra ?? partida.palabraSecreta,
);
})
.toList();
return _jugadoresDeCliente(partida, sala, sala.hostClientId);
}
void _mostrarPalabraHost(BuildContext context) {
@@ -483,8 +580,8 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
MaterialPageRoute(
builder: (_) => PantallaPalabrasCliente(
jugadores: jugadoresHost,
pistaCategoria: partida.config.pistaImpostor
? partida.categoriaReal
pistaImpostor: partida.config.pistaImpostor
? partida.pistaImpostor
: null,
onTodosVistos: () {
setState(() => _hostListo = true);
@@ -508,7 +605,8 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
esImpostor: hostLocal.esImpostor,
palabra: partida.palabraSecreta,
pistaActiva: partida.config.pistaImpostor,
categoria: partida.categoriaReal,
pista: partida.pistaImpostor,
companerosImpostores: estado.companerosImpostoresDe(hostLocal.id),
onVisto: () => setState(() => _hostListo = true),
),
),
@@ -767,8 +865,8 @@ class _PantallaGestorHostState extends State<PantallaGestorHost> {
jugadores: partida.jugadoresActivos,
jugadoresControlados: jugadoresHost,
partidaId: context.read<ServicioNearby>().roomId,
pistaCategoria: partida.config.pistaImpostor
? partida.categoriaReal
pistaImpostor: partida.config.pistaImpostor
? partida.pistaImpostor
: null,
onVotos: (votos) {
for (final entry in votos.entries) {
@@ -1029,7 +1127,8 @@ class _PantallaRevelarPalabraHost extends StatefulWidget {
final bool esImpostor;
final String palabra;
final bool pistaActiva;
final String categoria;
final String pista;
final List<String>? companerosImpostores;
final VoidCallback onVisto;
const _PantallaRevelarPalabraHost({
@@ -1037,7 +1136,8 @@ class _PantallaRevelarPalabraHost extends StatefulWidget {
required this.esImpostor,
required this.palabra,
required this.pistaActiva,
required this.categoria,
required this.pista,
required this.companerosImpostores,
required this.onVisto,
});
@@ -1120,15 +1220,13 @@ class _PantallaRevelarPalabraHostState
],
if (widget.esImpostor && widget.pistaActiva) ...[
const SizedBox(height: 12),
Text(
l10n.clueCategory(
BancoPalabras.nombreBonitoCategoria(
widget.categoria,
l10n,
),
),
style: Theme.of(context).textTheme.bodyLarge
?.copyWith(color: TemaApp.colorNaranja),
PistaImpostorFarolero(pista: widget.pista),
],
if (widget.esImpostor &&
widget.companerosImpostores != null) ...[
const SizedBox(height: 12),
CompanerosImpostorFarolero(
nombres: widget.companerosImpostores!,
),
],
],