25 Commits

Author SHA1 Message Date
Resistencia Dev
59d2dd56bc Release v1.0 - Primera versión estable de Francia Ocupada
- Implementación completa del juego La Resistencia
- Sistema de roles: Aliados y Nazis (incluyendo Francotirador)
- Fases del juego: Selección de equipo, votación, misión, asesinato
- Interfaz de usuario con imágenes temáticas
- Sistema de WebSockets para multijugador en tiempo real
- Configuración Docker para desarrollo y producción
- Dockerfiles optimizados para cliente y servidor
- docker-compose.yml para desarrollo local
- docker-compose_prod.yml para despliegue en producción con Nginx Proxy Manager
- Base de datos PostgreSQL integrada
- Documentación de cambios y fases del juego
2025-12-10 12:58:00 +01:00
Resistencia Dev
6e65152648 feat: Fix victory screens background images
- Changed GameBoard background to show mission_success.png for ALLIED_WIN and mission_fail.png for NAZIS_WIN
- Hidden board area completely during victory phases
- Removed redundant background image from VictoryScreen component
- Fixed image extensions from .jpg to .png for victory backgrounds
2025-12-08 22:39:05 +01:00
Resistencia Dev
f09e14f99a 🚪 Finalizar partida expulsa a todos al lobby - El host puede terminar la partida, eliminándola del listado y enviando a todos los jugadores al lobby 2025-12-08 20:51:46 +01:00
Resistencia Dev
31067bc168 🎴 Arreglada animación de las cartas - La carta de rol ahora vuelve a su posición al soltarla 2025-12-08 20:49:05 +01:00
Resistencia Dev
6a6cf7628b Checkpoint: Aplicación completamente funcional - Logo actualizado a 'FRANCIA OCUPADA' y botones de victoria redimensionados 2025-12-08 20:40:49 +01:00
Resistencia Dev
b836c53002 feat: Sistema completo de fin de juego y pantallas de victoria
Nuevas funcionalidades:
- Pantallas de victoria diferenciadas (NAZIS_WIN / ALLIED_WIN)
  * Diseño visual diferenciado (rojo para Nazis, azul para Aliados)
  * Timer de 30 segundos con auto-finalización
  * Estadísticas de misiones (exitosas vs fracasadas)
  * Opciones para el host: NUEVA PARTIDA o TERMINAR
  * Mensaje de espera para jugadores no-host

- Sistema de reinicio de partida
  * Método restartGame() que resetea todas las variables
  * Reasigna roles y líder aleatorios
  * Vuelve a fase REVEAL_ROLE manteniendo jugadores

- Sistema de finalización y expulsión
  * Método finalizeGame() que expulsa a todos después de 5s
  * Auto-expulsión si el host no decide en 30s
  * Limpieza de partida del servidor

Mejoras en MISSION_RESULT:
- Eliminado oscurecimiento de fondo (bg-transparent)
- Tiempo de visualización aumentado de 5 a 7 segundos
- Ahora se puede ver claramente el tablero con las fichas

Lógica de transiciones:
- 3 misiones fracasadas → NAZIS_WIN
- 3 misiones exitosas → ASSASSIN_PHASE
  * Asesino acierta (mata a Marlene) → NAZIS_WIN
  * Asesino falla → ALLIED_WIN

Archivos modificados:
- shared/types.ts: Nuevas fases NAZIS_WIN y ALLIED_WIN
- server/src/models/Game.ts: Métodos restartGame() y finalizeGame()
- server/src/index.ts: Eventos restart_game y finalize_game
- client/src/hooks/useSocket.ts: Acciones restartGame() y finalizeGame()
- client/src/components/GameBoard.tsx: Renderizado de VictoryScreen
- client/src/components/MissionResult.tsx: Sin oscurecimiento, 7s
- client/src/components/VictoryScreen.tsx: NUEVO componente
2025-12-08 13:41:44 +01:00
Resistencia Dev
774e1b982d feat: Títulos de misiones y fix timer votación post-misión
Nuevas funcionalidades:
- Títulos y subtítulos en cartas de misión
  * Título: 'MISIÓN X' (blanco, mayúsculas)
  * Subtítulo: Nombre de la misión (amarillo dorado)
  * Objeto missionNames con 5 nombres editables:
    1. Sabotaje en el Tren
    2. Rescate del Prisionero
    3. Destrucción del Puente
    4. Robo de Documentos
    5. Asalto al Cuartel General

Correcciones:
- Timer de votación de líder ahora se inicia correctamente después de terminar una misión
- Importado GamePhase en server/src/index.ts para comparaciones de fase
- Agregada lógica en finish_mission_result para iniciar timer cuando vuelve a VOTE_LEADER
- Votación se resuelve automáticamente si no todos votan (mayoría sobre votos emitidos)

Archivos modificados:
- client/src/components/GameBoard.tsx: Títulos de misiones
- server/src/index.ts: Fix timer post-misión
2025-12-08 13:13:33 +01:00
Resistencia Dev
06d2171871 fix: Sistema de votación de líder completamente refactorizado
- Timer de 10 segundos que se reinicia correctamente al cambiar de líder
- Votación por mayoría calculada sobre votos emitidos, no total de jugadores
- Si nadie vota, líder rechazado automáticamente
- Alemanes pueden ver carta de sabotaje en misiones
- Reset correcto de selectedTeam al cambiar de fase
- Contador de votos fallidos incrementa correctamente
- Logs mejorados para debugging

Fixes:
- Timer visual se reinicia con key basada en currentLeaderId
- Facción verificada correctamente (Faction.ALEMANES vs 'spies')
- forceResolveLeaderVote llama a resolución con votos actuales
- selectedTeam se limpia al salir de TEAM_BUILDING
2025-12-08 00:05:08 +01:00
Resistencia Dev
9e0e343868 feat: Actualizar roles y facciones a Francia Ocupada
- Cambiar nombre del juego de 'La Resistencia' a 'Francia Ocupada'
- Actualizar roles: Marlene, Capitán Philippe, Partisano, Comandante Schmidt, Francotirador, Agente Doble, Infiltrado, Colaboracionista
- Actualizar facciones: Aliados vs Alemanes
- Implementar timer de votación de líder con auto-avance
- Eliminar componentes de debug
2025-12-07 00:20:33 +01:00
Resistencia Dev
8f95413782 Checkpoint: Fix role shuffling bug and improve mission reveal flow 2025-12-06 00:32:09 +01:00
Resistencia Dev
ead54e0102 Fix: Auto-avanzar de MISSION_REVEAL a MISSION_RESULT
- Servidor avanza automáticamente después de 5 segundos
- Resuelve problema de quedarse bloqueado en pantalla de votos
- Cliente muestra 'Procesando resultado...'
2025-12-05 23:57:46 +01:00
Resistencia Dev
4b4936449a Feature: Implementar MissionResult completo
- Muestra resultado de la misión con animaciones
- Obtiene datos de missionHistory
- Muestra éxitos vs sabotajes
- Muestra progreso de misiones (Resistencia vs Espías)
- Botón CONTINUAR para avanzar
- Animaciones escalonadas para mejor UX
2025-12-05 23:51:32 +01:00
Resistencia Dev
1c8f1b08f5 Debug: Agregar info de facción y rol en fase MISSION
- Muestra facción y rol del jugador
- Ayuda a identificar por qué algunos espías no ven carta de sabotaje
2025-12-05 23:46:43 +01:00
Resistencia Dev
00434daf97 Feature: Feedback visual simple con opacidad en cartas
- Carta seleccionada: opacity-100 (brillante)
- Carta NO seleccionada: opacity-50 (apagada)
- Aplicado a las 4 cartas (2 éxito + 2 sabotaje)
- Botones deshabilitados después de votar
- Solución mucho más simple y elegante
2025-12-05 23:44:26 +01:00
Resistencia Dev
94cb0d671d WIP: Agregar feedback visual a carta de éxito (primera)
- Borde amarillo brillante cuando está seleccionada
- Ring amarillo con glow
- Deshabilitar botón después de votar
- Falta aplicar a las otras 3 cartas
2025-12-05 23:39:35 +01:00
Resistencia Dev
951098540c Fix: MissionReveal con tics blancos y mejor layout
- Cambiar text-4xl a text-5xl para tics más grandes
- Agregar text-white para que los tics sean blancos
- Agregar font-bold para mejor visibilidad
- Mejorar layout con flex-col
- Agregar mensaje informativo
2025-12-05 23:34:21 +01:00
Resistencia Dev
40565a936b Feature: Completar sistema de votación de misiones
- Cambiar onClick para usar handleMissionVote
- Crear componentes MissionReveal y MissionResult
- Importar componentes en GameBoard
- Tracking de votos con feedback visual
- Usar imágenes vote_approve y vote_reject

Resuelve error: MissionReveal is not defined
2025-12-05 23:27:32 +01:00
Resistencia Dev
2f2bc4e4d0 WIP: Cambiar imágenes de misión y agregar tracking de votos
- Cambiar mission_success/fail a vote_approve/reject
- Agregar estado missionVote para trackear voto del jugador
- Agregar función handleMissionVote
- Reset de voto cuando cambia la fase
- Falta: actualizar onClick y agregar feedback visual
2025-12-05 23:26:20 +01:00
Resistencia Dev
7fbf964c12 Fix: Resolver error de React hooks en fase MISSION
- Mover useState de cardOrder al nivel del componente
- Eliminar IIFE que causaba violación de reglas de hooks
- Usar cardOrder directamente en lugar de successFirst
- Ahora la fase MISSION debería funcionar correctamente
2025-12-05 23:18:20 +01:00
Resistencia Dev
79ec36dd1a Feature: Eliminar fase VOTING_TEAM - ir directo a MISSION
- Cambio de flujo: Líder elige equipo → Directamente a MISSION
- Ya no se vota si se aprueba o rechaza el equipo
- Simplifica el juego según las reglas solicitadas
- El líder selecciona y el equipo ejecuta inmediatamente
2025-12-05 23:11:19 +01:00
Resistencia Dev
19f4d1d6fb Debug: Agregar información de depuración para fase MISSION
- Muestra el ID del jugador actual y los IDs del equipo propuesto
- Ayuda a identificar por qué todos ven las cartas en lugar de solo el equipo
2025-12-05 23:01:29 +01:00
Resistencia Dev
9cd22365ec Fix: Corregir iconos de líder y equipo
- Fix: Usar currentLeaderId en lugar de player.isLeader (evita múltiples L)
- Fix: Mostrar estrella verde también en VOTING_TEAM
- Ahora solo aparece un icono L (líder actual)
- Estrellas verdes visibles para equipo propuesto
2025-12-05 22:55:12 +01:00
Resistencia Dev
ffdbc78193 Feature: Agregar estrella verde para miembros del equipo de misión
- Add: Icono de estrella  verde para identificar miembros del equipo
- Fix: Diferencia clara entre líder (L amarillo) y miembros del equipo ( verde)
- Visible durante fases MISSION, MISSION_REVEAL y MISSION_RESULT
2025-12-05 22:45:00 +01:00
Resistencia Dev
677c2c0eab Fix: Corregir selección de líder y mejorar UI de misiones
- Fix: isLeader ahora usa currentLeaderId del estado (evita múltiples líderes)
- Mejora: TEAM_BUILDING muestra claramente quién es el líder actual
- Mejora: Contador de jugadores seleccionados en TEAM_BUILDING
- Mejora: MISSION con cartas grandes en pantalla completa
- Feature: Posición aleatoria de cartas (izq/der) para evitar detectar votos
- Mejora: Animaciones mejoradas con Framer Motion
- Mejora: Mensajes más claros para jugadores que esperan
2025-12-05 22:30:10 +01:00
Resistencia Dev
dad148ebb6 Add CHANGELOG for v0.1.0 2025-12-05 22:23:20 +01:00
26 changed files with 1390 additions and 215 deletions

View File

@@ -0,0 +1,171 @@
RESUMEN DE CAMBIOS - SESIÓN 2025-12-08
========================================
## 1. CORRECCIÓN DE PANTALLAS DE VICTORIA (ALLIED_WIN y NAZIS_WIN)
### Problema inicial:
- Las pantallas de victoria mostraban el tablero de juego encima de la imagen de fondo
- Había imágenes duplicadas y rutas incorrectas (.jpg vs .png)
### Solución implementada:
#### GameBoard.tsx:
- **Fondo dinámico según fase**: El fondo del componente GameBoard ahora cambia según la fase:
* ALLIED_WIN → muestra `/assets/images/tokens/mission_success.png`
* NAZIS_WIN → muestra `/assets/images/tokens/mission_fail.png`
* Otras fases → muestra `/assets/images/ui/bg_game.png`
- **Área del tablero oculta en victorias**: El div del tablero (con las cartas de misión, tablero táctico, etc.)
se oculta completamente cuando `gameState.phase === ALLIED_WIN || gameState.phase === NAZIS_WIN`
#### VictoryScreen.tsx:
- **Eliminada imagen de fondo redundante**: Se eliminó el div con la imagen de fondo que intentaba cargar
`mission_fail.jpg` y `mission_success.jpg`, ya que el GameBoard ahora maneja estos fondos.
### Archivos modificados:
- `client/src/components/GameBoard.tsx` (líneas 293-307, 309-442)
- `client/src/components/VictoryScreen.tsx` (líneas 39-50 eliminadas)
### Commit:
- Hash: 6e65152
- Mensaje: "feat: Fix victory screens background images"
---
## 2. MEJORA DE CARTAS DE MISIÓN (Fase MISSION)
### Problema inicial:
- Las cartas solo se opacaban cuando se seleccionaba la otra
- Si solo había una carta (jugadores aliados), no había feedback visual de que se había seleccionado
### Solución implementada:
#### Cambio de lógica de opacidad:
**ANTES:**
- Sin voto: todas las cartas al 100% de opacidad
- Con voto: la carta NO seleccionada se opaca al 50%
**DESPUÉS:**
- Sin voto: todas las cartas al 50% de opacidad (opacadas por defecto)
- Con voto: solo la carta seleccionada se pone al 100%, las demás permanecen al 50%
#### Implementación:
```tsx
// Carta de Éxito
className={`group transition-opacity ${missionVote === true ? 'opacity-100' : 'opacity-50'}`}
// Carta de Sabotaje (solo alemanes)
className={`group transition-opacity ${missionVote === false ? 'opacity-100' : 'opacity-50'}`}
```
### Archivos modificados:
- `client/src/components/GameBoard.tsx` (líneas 628-678)
### Beneficio:
- Ahora es fácil ver qué carta has seleccionado, incluso cuando solo tienes una opción disponible
---
## 3. INTENTO DE MEJORA DEL HISTORIAL DE MISIONES (NO FUNCIONAL)
### Objetivo:
- Mostrar los participantes de cada misión al hacer clic en el número del historial
### Implementación intentada:
#### Estado añadido:
```tsx
const [expandedMission, setExpandedMission] = useState<number | null>(null);
```
#### Lógica implementada:
- Click en número de misión → expande mostrando nombres de participantes
- Click de nuevo → colapsa la lista
- Solo una misión puede estar expandida a la vez
- Indicador visual: anillo amarillo alrededor del número cuando está expandido
#### Código añadido en GameBoard.tsx (líneas 856-899):
```tsx
{gameState.missionHistory.map((mission, idx) => {
const isExpanded = expandedMission === idx;
return (
<div key={idx} className="relative">
<div
className={`... ${isExpanded ? 'ring-2 ring-yellow-400' : ''}`}
onClick={(e) => {
e.stopPropagation();
console.log('Click en misión', idx, 'Estado actual:', expandedMission);
setExpandedMission(isExpanded ? null : idx);
}}
>
{mission.round}
</div>
{isExpanded && (
<div className="absolute top-10 right-0 bg-black/95 p-2 rounded border border-white/30 min-w-max z-[100]">
{mission.team.map((playerId) => {
const player = gameState.players.find(p => p.id === playerId);
return (
<div key={playerId} className="text-xs text-white whitespace-nowrap">
{player?.name || playerId}
</div>
);
})}
</div>
)}
</div>
);
})}
```
### Archivos modificados:
- `client/src/components/GameBoard.tsx` (líneas 26, 856-899)
### Estado:
⚠️ **NO FUNCIONAL** - El click no dispara la expansión de la lista de participantes.
Posibles causas a investigar:
- Conflicto con otros event handlers
- Problema con el z-index o posicionamiento
- Estado no actualizándose correctamente
- Necesidad de reiniciar servicios Docker
---
## RESUMEN DE COMMITS
1. **6e65152** - "feat: Fix victory screens background images"
- Corregidas pantallas de victoria
- Eliminadas imágenes redundantes
- Fondo dinámico según fase
---
## ARCHIVOS PRINCIPALES MODIFICADOS
1. `client/src/components/GameBoard.tsx`
- Fondo dinámico para fases de victoria
- Área del tablero oculta en victorias
- Opacidad de cartas de misión mejorada
- Intento de historial expandible (no funcional)
2. `client/src/components/VictoryScreen.tsx`
- Eliminada imagen de fondo redundante
---
## PENDIENTES / PROBLEMAS CONOCIDOS
1. ❌ **Historial de misiones expandible no funciona**
- El código está implementado pero el click no dispara la acción
- Requiere investigación adicional
2. ⚠️ **Errores de lint**
- Múltiples errores de tipo "JSX element implicitly has type 'any'"
- Son falsos positivos del IDE en entorno Dockerizado
- No afectan la funcionalidad de la aplicación
---
Fecha: 2025-12-08
Hora: 22:59

77
CHANGELOG.md Normal file
View File

@@ -0,0 +1,77 @@
# Notas de Versión
## v0.1.0-functional-until-mission (2025-12-05)
### ✅ Funcionalidades Implementadas
#### Backend (100% Completo)
- ✅ Sistema completo de salas y jugadores
- ✅ Asignación automática de roles (Resistencia/Espías)
- ✅ Todas las fases del juego implementadas:
- LOBBY, INTRO, REVEAL_ROLE, ROLL_CALL
- VOTE_LEADER (con sistema de aprobación/rechazo)
- TEAM_BUILDING, VOTE_TEAM
- MISSION (votación éxito/sabotaje)
- **MISSION_REVEAL** (barajado de votos - solo lógica)
- **MISSION_RESULT** (resumen de misión - solo lógica)
- ASSASSIN_PHASE
- ✅ Histórico de misiones (MissionRecord)
- ✅ Reglas correctas implementadas:
- Misión 4 con 7+ jugadores requiere 2 fallos
- 5 rechazos consecutivos = victoria espías
- 3 misiones exitosas/fallidas = victoria
- ✅ WebSocket con Socket.IO para comunicación en tiempo real
#### Frontend (Funcional hasta MISSION)
- ✅ Lobby completo con creación/unión de partidas
- ✅ Intro con música (Intro.ogg)
- ✅ Revelación de roles con animaciones
- ✅ Roll call con música (Rondas.ogg) y avatares
- ✅ Votación de líder con timer de 10 segundos
- ✅ Selección de equipo por el líder
- ✅ Votación de equipo con cartas
- ✅ Votación de misión (éxito/sabotaje)
- ✅ Componente VotingTimer funcionando
- ✅ Animaciones con Framer Motion
- ✅ Diseño responsive con TailwindCSS
### ❌ Pendiente (Solo UI)
- ❌ Pantalla MISSION_REVEAL (mostrar cartas una a una)
- ❌ Pantalla MISSION_RESULT (resumen visual)
- ❌ Histórico de misiones en esquina
### 🐛 Problemas Conocidos
- El servidor puede consumir mucha CPU (reiniciar si ocurre)
- El juego se queda en MISSION_REVEAL al completar una misión (falta UI)
### 📦 Tecnologías
- **Frontend**: Next.js 14, React, TypeScript, Framer Motion, TailwindCSS
- **Backend**: Node.js, Express, Socket.IO, TypeScript
- **Base de Datos**: PostgreSQL 15
- **Containerización**: Docker, Docker Compose
### 🚀 Cómo Usar Este Tag
```bash
# Volver a esta versión
git checkout v0.1.0-functional-until-mission
# Ver diferencias con la versión actual
git diff v0.1.0-functional-until-mission HEAD
# Listar todos los tags
git tag -l
```
### 📝 Commits en Esta Versión
- `8d423ac` - Estado inicial con errores de sintaxis
- `44d7418` - GameBoard limpio y funcional
- `5bb1b17` - VotingTimer agregado correctamente
- `98768fb` - README con documentación completa
- `63b9766` - Fix: Eliminados backticks de markdown
### 🎯 Próximos Pasos
1. Implementar UI para MISSION_REVEAL
2. Implementar UI para MISSION_RESULT
3. Agregar histórico visual de misiones
4. Optimizar rendimiento del servidor
5. Agregar tests unitarios

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 764 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 720 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 680 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 716 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 691 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 558 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 558 KiB

After

Width:  |  Height:  |  Size: 581 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 852 KiB

View File

@@ -5,7 +5,7 @@ import './globals.css'
const inter = Inter({ subsets: ['latin'] }) const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'La Resistencia: WWII', title: 'Francia Ocupada: WWII',
description: 'Juego de deducción social ambientado en la Segunda Guerra Mundial', description: 'Juego de deducción social ambientado en la Segunda Guerra Mundial',
} }

View File

@@ -173,7 +173,7 @@ export default function Home() {
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Image src="/assets/images/ui/logo.png" alt="Logo" width={150} height={50} className="object-contain filter drop-shadow hidden md:block" /> <Image src="/assets/images/ui/logo.png" alt="Logo" width={150} height={50} className="object-contain filter drop-shadow hidden md:block" />
<h1 className="text-2xl font-bold tracking-widest uppercase text-yellow-600"> <h1 className="text-2xl font-bold tracking-widest uppercase text-yellow-600">
La Resistencia Francia Ocupada
</h1> </h1>
</div> </div>
{view === 'lobby' && ( {view === 'lobby' && (

View File

@@ -1,7 +1,10 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion'; import { motion, AnimatePresence } from 'framer-motion';
import Image from 'next/image'; import Image from 'next/image';
import { GameState, GamePhase, Player, GAME_CONFIG } from '../../../shared/types'; import { GameState, GamePhase, Player, GAME_CONFIG, Faction } from '../../../shared/types';
import MissionReveal from './MissionReveal';
import MissionResult from './MissionResult';
import VictoryScreen from './VictoryScreen';
interface GameBoardProps { interface GameBoardProps {
gameState: GameState; gameState: GameState;
@@ -15,6 +18,14 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
// Hooks para FASE REVEAL ROLE // Hooks para FASE REVEAL ROLE
const [revealCard, setRevealCard] = useState(false); const [revealCard, setRevealCard] = useState(false);
// Orden aleatorio de cartas de misión (se genera una vez)
const [cardOrder] = useState(() => Math.random() > 0.5);
// Track del voto de misión del jugador
const [missionVote, setMissionVote] = useState<boolean | null>(null);
const [expandedMission, setExpandedMission] = useState<number | null>(null);
// Timer para avanzar automáticamente en REVEAL_ROLE // Timer para avanzar automáticamente en REVEAL_ROLE
useEffect(() => { useEffect(() => {
if (gameState.phase === 'reveal_role' as any) { if (gameState.phase === 'reveal_role' as any) {
@@ -25,8 +36,39 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
} }
}, [gameState.phase, actions]); }, [gameState.phase, actions]);
// Reset missionVote cuando cambia la fase
useEffect(() => {
if (gameState.phase !== GamePhase.MISSION) {
setMissionVote(null);
}
}, [gameState.phase]);
// Reset selectedTeam cuando no estamos en TEAM_BUILDING o cambia el líder
useEffect(() => {
if (gameState.phase !== GamePhase.TEAM_BUILDING) {
setSelectedTeam([]);
}
}, [gameState.phase, gameState.currentLeaderId]);
// Estado para controlar cuándo mostrar el tablero
const [showBoard, setShowBoard] = useState(false);
// Mostrar tablero 7 segundos después de MISSION_RESULT
useEffect(() => {
if (gameState.phase === GamePhase.MISSION_RESULT) {
setShowBoard(true);
const timer = setTimeout(() => {
setShowBoard(false);
}, 7000); // 7 segundos
return () => clearTimeout(timer);
} else {
setShowBoard(false);
}
}, [gameState.phase]);
const currentPlayer = gameState.players.find(p => p.id === currentPlayerId); const currentPlayer = gameState.players.find(p => p.id === currentPlayerId);
const isLeader = currentPlayer?.isLeader; const isLeader = gameState.currentLeaderId === currentPlayerId; // FIX: Usar currentLeaderId del estado
const config = GAME_CONFIG[gameState.players.length as keyof typeof GAME_CONFIG]; const config = GAME_CONFIG[gameState.players.length as keyof typeof GAME_CONFIG];
const currentQuestSize = config?.quests[gameState.currentRound - 1]; const currentQuestSize = config?.quests[gameState.currentRound - 1];
@@ -41,6 +83,12 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
} }
}; };
const handleMissionVote = (vote: boolean) => {
setMissionVote(vote);
actions.voteMission(vote);
};
// Coordenadas porcentuales de los hexágonos de misión en el mapa // Coordenadas porcentuales de los hexágonos de misión en el mapa
const missionCoords = [ const missionCoords = [
{ left: '12%', top: '55%' }, // Misión 1 { left: '12%', top: '55%' }, // Misión 1
@@ -50,6 +98,15 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{ left: '82%', top: '40%' }, // Misión 5 { left: '82%', top: '40%' }, // Misión 5
]; ];
// Nombres de las misiones
const missionNames = [
'Sabotaje en el Tren',
'Rescate del Prisionero',
'Destrucción del Puente',
'Robo de Documentos',
'Asalto al Cuartel General'
];
// --- UI/Efectos para FASES TEMPRANAS --- // --- UI/Efectos para FASES TEMPRANAS ---
const isHost = gameState.hostId === currentPlayerId; const isHost = gameState.hostId === currentPlayerId;
@@ -66,12 +123,14 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
Guerra Total Guerra Total
</h1> </h1>
{/* Audio Auto-Play */} {/* Audio Auto-Play - Solo para el host */}
<audio {isHost && (
src="/assets/audio/Intro.ogg" <audio
autoPlay src="/assets/audio/Intro.ogg"
onEnded={() => isHost && actions.finishIntro()} autoPlay
/> onEnded={() => actions.finishIntro()}
/>
)}
{isHost && ( {isHost && (
<button <button
@@ -89,31 +148,31 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
if (gameState.phase === 'reveal_role' as any) { if (gameState.phase === 'reveal_role' as any) {
// Determinar imagen basada en el rol // Determinar imagen basada en el rol
// Mapeo básico: // Mapeo actualizado:
// Merlin -> good_merlin.png // Marlene -> good_merlin.png
// Percival -> good_percival.png // Capitán Philippe -> good_percival.png
// Servant -> good_soldier_X.png (random) // Partisano -> good_soldier_X.png (random)
// Assassin -> evil_assassin.png // Francotirador -> evil_assassin.png
// Morgana -> evil_morgana.png // Agente Doble -> evil_morgana.png
// Mordred -> evil_mordred.png // Comandante Schmidt -> evil_mordred.png
// Oberon -> evil_oberon.png // Infiltrado -> evil_oberon.png
// Minion -> evil_minion_X.png // Colaboracionista -> evil_minion_X.png
let roleImage = '/assets/images/characters/good_soldier_1.png'; // Default let roleImage = '/assets/images/characters/good_soldier_1.png'; // Default
const role = currentPlayer?.role; const role = currentPlayer?.role;
if (role === 'merlin') roleImage = '/assets/images/characters/good_merlin.png'; if (role === 'marlene') roleImage = '/assets/images/characters/good_merlin.png';
else if (role === 'assassin') roleImage = '/assets/images/characters/evil_assassin.png'; else if (role === 'francotirador') roleImage = '/assets/images/characters/evil_assassin.png';
else if (role === 'percival') roleImage = '/assets/images/characters/good_percival.png'; else if (role === 'capitan_philippe') roleImage = '/assets/images/characters/good_percival.png';
else if (role === 'morgana') roleImage = '/assets/images/characters/evil_morgana.png'; else if (role === 'agente_doble') roleImage = '/assets/images/characters/evil_morgana.png';
else if (role === 'mordred') roleImage = '/assets/images/characters/evil_mordred.png'; else if (role === 'comandante_schmidt') roleImage = '/assets/images/characters/evil_mordred.png';
else if (role === 'oberon') roleImage = '/assets/images/characters/evil_oberon.png'; else if (role === 'infiltrado') roleImage = '/assets/images/characters/evil_oberon.png';
else if (role === 'loyal_servant') { else if (role === 'partisano') {
// Random soldier 1-5 // Random soldier 1-5
const idx = (currentPlayerId.charCodeAt(0) % 5) + 1; const idx = (currentPlayerId.charCodeAt(0) % 5) + 1;
roleImage = `/assets/images/characters/good_soldier_${idx}.png`; roleImage = `/assets/images/characters/good_soldier_${idx}.png`;
} }
else if (role === 'minion') { else if (role === 'colaboracionista') {
// Random minion 1-3 // Random minion 1-3
const idx = (currentPlayerId.charCodeAt(0) % 3) + 1; const idx = (currentPlayerId.charCodeAt(0) % 3) + 1;
roleImage = `/assets/images/characters/evil_minion_${idx}.png`; roleImage = `/assets/images/characters/evil_minion_${idx}.png`;
@@ -155,15 +214,9 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
drag="y" drag="y"
dragConstraints={{ top: -300, bottom: 0 }} dragConstraints={{ top: -300, bottom: 0 }}
dragElastic={0.2} dragElastic={0.2}
onDragEnd={(e, info) => { dragSnapToOrigin={true}
// Reducir umbral a -50 para facilitar
if (info.offset.y < -50) {
setRevealCard(true);
}
}}
whileHover={{ scale: 1.02 }} whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98, cursor: 'grabbing' }} whileTap={{ scale: 0.98, cursor: 'grabbing' }}
animate={revealCard ? { y: -1000, opacity: 0 } : { y: 0, opacity: 1 }}
className="absolute inset-0 w-full h-full rounded-xl overflow-hidden shadow-2xl z-20 cursor-grab active:cursor-grabbing hover:ring-2 hover:ring-white/50 transition-all" className="absolute inset-0 w-full h-full rounded-xl overflow-hidden shadow-2xl z-20 cursor-grab active:cursor-grabbing hover:ring-2 hover:ring-white/50 transition-all"
> >
<Image <Image
@@ -185,6 +238,8 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
if (gameState.phase === 'roll_call' as any) { if (gameState.phase === 'roll_call' as any) {
return ( return (
<div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white font-mono"> <div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white font-mono">
<div className="absolute inset-0 z-0"> <div className="absolute inset-0 z-0">
<Image src="/assets/images/ui/bg_roll_call.png" alt="Resistance HQ" fill className="object-cover" /> <Image src="/assets/images/ui/bg_roll_call.png" alt="Resistance HQ" fill className="object-cover" />
<div className="absolute inset-0 bg-black/70" /> <div className="absolute inset-0 bg-black/70" />
@@ -205,8 +260,6 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8"> <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8">
{gameState.players.map((p, i) => { {gameState.players.map((p, i) => {
// Asignar avatar determinista basado en charCode
const avatarIdx = (p.name.length % 3) + 1;
return ( return (
<motion.div <motion.div
key={p.id} key={p.id}
@@ -217,7 +270,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
> >
<div className="w-32 h-32 rounded-full border-4 border-gray-400 overflow-hidden relative shadow-2xl bg-black"> <div className="w-32 h-32 rounded-full border-4 border-gray-400 overflow-hidden relative shadow-2xl bg-black">
<Image <Image
src={`/assets/images/characters/avatar_${avatarIdx}.png`} src={`/assets/images/characters/${p.avatar}`}
alt="Avatar" alt="Avatar"
fill fill
className="object-cover grayscale contrast-125" className="object-cover grayscale contrast-125"
@@ -237,82 +290,158 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
return ( return (
<div className="relative w-full h-screen flex flex-col items-center overflow-hidden"> <div className="relative w-full h-screen flex flex-col items-center overflow-hidden">
<div className="absolute inset-0 z-0 opacity-40"> <div className="absolute inset-0 z-0 opacity-40">
<Image src="/assets/images/ui/bg_game.png" alt="Game Background" fill className="object-cover" /> <Image
src={
gameState.phase === GamePhase.ALLIED_WIN
? "/assets/images/tokens/mission_success.png"
: gameState.phase === GamePhase.NAZIS_WIN
? "/assets/images/tokens/mission_fail.png"
: "/assets/images/ui/bg_game.png"
}
alt="Game Background"
fill
className="object-cover"
/>
<div className="absolute inset-0 bg-black/60" /> <div className="absolute inset-0 bg-black/60" />
</div> </div>
<div className="relative z-10 w-full flex flex-col items-center"> <div className="relative z-10 w-full flex flex-col items-center">
{/* --- MAPA TÁCTICO (TABLERO) --- */} {/* --- MAPA TÁCTICO (TABLERO) O CARTA DE MISIÓN O ASSASSIN_PHASE --- */}
<div className="relative w-full max-w-5xl aspect-video mt-4 shadow-2xl border-4 border-gray-800 rounded-lg overflow-hidden bg-[#2a2a2a]"> {/* No mostrar el tablero en fases de victoria */}
<Image {gameState.phase !== GamePhase.ALLIED_WIN && gameState.phase !== GamePhase.NAZIS_WIN && (
src="/assets/images/ui/board_map.jpg" <div className="relative w-full max-w-5xl aspect-video mt-4 shadow-2xl border-4 border-gray-800 rounded-lg overflow-hidden bg-[#2a2a2a]">
alt="Tactical Map" {gameState.phase === GamePhase.ASSASSIN_PHASE ? (
fill /* IMAGEN LASTSHOT PARA ASSASSIN_PHASE */
className="object-contain" <>
/> <Image
src="/assets/images/tokens/lastshot.jpg"
alt="Last Shot"
fill
className="object-cover"
priority
/>
{/* Overlay oscuro para mejorar legibilidad */}
<div className="absolute inset-0 bg-black/40" />
{/* TOKENS SOBRE EL MAPA */} {/* Título sobre la imagen */}
{missionCoords.map((coord, idx) => { <div className="absolute top-4 left-0 right-0 flex flex-col items-center z-10">
const result = gameState.questResults[idx]; <h1 className="text-5xl font-bold text-red-600 mb-2 drop-shadow-[0_4px_8px_rgba(0,0,0,0.9)]">
const isCurrent = gameState.currentRound === idx + 1; ¡ÚLTIMA OPORTUNIDAD!
</h1>
{currentPlayer?.role === 'francotirador' ? (
<p className="text-xl text-white drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] font-bold">
Francotirador, elige a quién crees que es <span className="text-yellow-400">MARLENE</span>
</p>
) : (
<p className="text-xl text-gray-300 drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] font-bold">
El Francotirador está decidiendo...
</p>
)}
</div>
</>
) : showBoard ? (
<>
{/* TABLERO CON TOKENS */}
<Image
src="/assets/images/ui/board_map.jpg"
alt="Tactical Map"
fill
className="object-contain"
/>
return ( {/* TOKENS SOBRE EL MAPA */}
<div {missionCoords.map((coord, idx) => {
key={idx} const result = gameState.questResults[idx];
className="absolute w-[12%] aspect-square flex items-center justify-center transform -translate-x-1/2 -translate-y-1/2" const isCurrent = gameState.currentRound === idx + 1;
style={{ left: coord.left, top: coord.top }}
>
{/* Marcador de Ronda Actual */}
{isCurrent && (
<motion.div
layoutId="round-marker"
className="absolute inset-0 z-10"
initial={{ scale: 1.5, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: "spring", stiffness: 300, damping: 20 }}
>
<Image
src="/assets/images/tokens/marker_round.png"
alt="Current Round"
fill
className="object-contain drop-shadow-lg"
/>
</motion.div>
)}
{/* Resultado de Misión (Éxito/Fracaso) */} return (
{result === true && ( <div
<motion.div key={idx}
initial={{ scale: 0 }} animate={{ scale: 1 }} className="absolute w-[10%] aspect-square flex items-center justify-center"
className="absolute inset-0 z-20" style={{
> left: coord.left,
<Image src="/assets/images/tokens/marker_score_blue.png" alt="Success" fill className="object-contain drop-shadow-lg" /> top: coord.top,
</motion.div> transform: 'translate(-50%, -50%)'
)} }}
{result === false && ( >
<motion.div {/* Marcador de Ronda Actual */}
initial={{ scale: 0 }} animate={{ scale: 1 }} {isCurrent && (
className="absolute inset-0 z-20" <motion.div
> layoutId="round-marker"
<Image src="/assets/images/tokens/marker_score_red.png" alt="Fail" fill className="object-contain drop-shadow-lg" /> className="absolute inset-0 z-10"
</motion.div> initial={{ scale: 1.5, opacity: 0 }}
)} animate={{ scale: 1, opacity: 1 }}
</div> transition={{ type: "spring", stiffness: 300, damping: 20 }}
); >
})} <Image
src="/assets/images/tokens/marker_round.png"
alt="Current Round"
fill
className="object-contain drop-shadow-lg"
/>
</motion.div>
)}
{/* TRACK DE VOTOS FALLIDOS (Pequeño indicador en la esquina inferior izquierda del mapa) */} {/* Resultado de Misión (Éxito/Fracaso) */}
<div className="absolute bottom-[5%] left-[2%] bg-black/60 p-2 rounded border border-white/20"> {result === true && (
<div className="text-[10px] text-gray-300 uppercase mb-1 text-center">Votos Rechazados</div> <motion.div
<div className="flex gap-1"> initial={{ scale: 0 }} animate={{ scale: 1 }}
{[...Array(5)].map((_, i) => ( className="absolute inset-0 z-20 flex items-center justify-center"
<div key={i} className={`w-3 h-3 rounded-full border border-gray-500 ${i < gameState.failedVotesCount ? 'bg-red-500' : 'bg-transparent'}`} /> >
))} <div className="w-[80%] h-[80%] relative">
</div> <Image src="/assets/images/tokens/marker_score_blue.png" alt="Success" fill className="object-contain drop-shadow-lg" />
</div>
</motion.div>
)}
{result === false && (
<motion.div
initial={{ scale: 0 }} animate={{ scale: 1 }}
className="absolute inset-0 z-20 flex items-center justify-center"
>
<div className="w-[80%] h-[80%] relative">
<Image src="/assets/images/tokens/marker_score_red.png" alt="Fail" fill className="object-contain drop-shadow-lg" />
</div>
</motion.div>
)}
</div>
);
})}
{/* TRACK DE VOTOS FALLIDOS */}
<div className="absolute bottom-[5%] left-[2%] bg-black/60 p-2 rounded border border-white/20">
<div className="text-[10px] text-gray-300 uppercase mb-1 text-center">Votos Rechazados</div>
<div className="flex gap-1">
{[...Array(5)].map((_, i) => (
<div key={i} className={`w-3 h-3 rounded-full border border-gray-500 ${i < gameState.failedVotesCount ? 'bg-red-500' : 'bg-transparent'}`} />
))}
</div>
</div>
</>
) : (
/* CARTA DE MISIÓN CON TÍTULO */
<>
<Image
src={`/assets/images/missions/mission${gameState.currentRound}.png`}
alt={`Mission ${gameState.currentRound}`}
fill
className="object-contain"
/>
{/* Título y subtítulo sobre la carta */}
<div className="absolute top-4 left-0 right-0 flex flex-col items-center z-10">
<h2 className="text-4xl font-bold text-white drop-shadow-[0_4px_8px_rgba(0,0,0,0.8)] mb-2 uppercase tracking-wider">
Misión {gameState.currentRound}
</h2>
<h3 className="text-2xl font-semibold text-yellow-400 drop-shadow-[0_4px_8px_rgba(0,0,0,0.8)] uppercase tracking-wide">
{missionNames[gameState.currentRound - 1]}
</h3>
</div>
</>
)}
</div> </div>
</div> )}
{/* --- ÁREA DE JUEGO (CARTAS Y ACCIONES) --- */} {/* --- ÁREA DE JUEGO (CARTAS Y ACCIONES) --- */}
<div className="flex-1 w-full max-w-6xl relative mt-4 px-4"> <div className="flex-1 w-full max-w-6xl relative mt-4 px-4">
@@ -334,9 +463,9 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
¿Aceptas a <span className="text-yellow-400">{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name}</span> como Líder? ¿Aceptas a <span className="text-yellow-400">{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name}</span> como Líder?
</div> </div>
{/* Timer */} {/* Timer visual (solo muestra el tiempo, el servidor controla el timeout) */}
{!gameState.leaderVotes?.[currentPlayerId] && ( {!gameState.leaderVotes?.[currentPlayerId] && (
<VotingTimer onTimeout={() => actions.voteLeader(null)} /> <VotingTimer key={gameState.currentLeaderId} />
)} )}
</div> </div>
@@ -370,24 +499,56 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
initial={{ opacity: 0, y: 20 }} initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }} exit={{ opacity: 0, y: -20 }}
className="bg-paper-bg text-black p-6 rounded shadow-2xl rotate-1 max-w-md w-full text-center" className="flex flex-col items-center gap-6 w-full max-w-4xl"
> >
<h2 className="text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue"> {/* Información del líder */}
{isLeader ? 'TU TURNO: ELIGE EQUIPO' : `ESPERANDO AL LÍDER...`} <div className="bg-yellow-600/90 text-black p-4 rounded-lg shadow-xl border-4 border-yellow-400 w-full text-center">
</h2> <div className="flex items-center justify-center gap-3">
<p className="mb-4 font-serif italic text-gray-700"> <Image src="/assets/images/tokens/token_leader.png" alt="Leader" width={40} height={40} />
Se necesitan <span className="font-bold text-red-700">{currentQuestSize} agentes</span> para esta misión. <div>
</p> <div className="text-sm uppercase tracking-wider font-bold">Líder Actual</div>
<div className="text-2xl font-bold">
{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name || 'Desconocido'}
</div>
</div>
<Image src="/assets/images/tokens/token_leader.png" alt="Leader" width={40} height={40} />
</div>
</div>
{isLeader && ( {/* Mensaje para el líder o para los demás */}
<button <div className="bg-paper-bg text-black p-6 rounded shadow-2xl rotate-1 w-full text-center">
onClick={() => actions.proposeTeam(selectedTeam)} <h2 className="text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue">
disabled={selectedTeam.length !== currentQuestSize} {isLeader ? '🎯 TU TURNO: ELIGE TU EQUIPO' : '⏳ ESPERANDO AL LÍDER...'}
className="w-full bg-resistance-blue text-white font-bold py-3 px-4 rounded hover:bg-blue-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed uppercase tracking-widest" </h2>
> <p className="mb-4 font-serif italic text-gray-700">
Proponer Equipo Se necesitan <span className="font-bold text-red-700 text-xl">{currentQuestSize} agentes</span> para la misión #{gameState.currentRound}.
</button> </p>
)}
{/* Contador de seleccionados */}
{isLeader && (
<div className="mb-4 text-lg font-bold">
Seleccionados: <span className={selectedTeam.length === currentQuestSize ? 'text-green-600' : 'text-orange-600'}>
{selectedTeam.length} / {currentQuestSize}
</span>
</div>
)}
{isLeader && (
<button
onClick={() => actions.proposeTeam(selectedTeam)}
disabled={selectedTeam.length !== currentQuestSize}
className="w-full bg-resistance-blue text-white font-bold py-3 px-4 rounded hover:bg-blue-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed uppercase tracking-widest shadow-lg"
>
{selectedTeam.length === currentQuestSize ? '✓ CONFIRMAR EQUIPO' : `Selecciona ${currentQuestSize - selectedTeam.length} más`}
</button>
)}
{!isLeader && (
<div className="text-gray-600 animate-pulse">
El líder está seleccionando el equipo de misión...
</div>
)}
</div>
</motion.div> </motion.div>
)} )}
@@ -431,6 +592,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
) : ( ) : (
<div className="text-white text-xl font-mono animate-pulse"> <div className="text-white text-xl font-mono animate-pulse">
VOTO REGISTRADO. ESPERANDO AL RESTO... VOTO REGISTRADO. ESPERANDO AL RESTO...
```
</div> </div>
)} )}
</motion.div> </motion.div>
@@ -438,33 +600,110 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{/* FASE: MISIÓN */} {/* FASE: MISIÓN */}
{gameState.phase === GamePhase.MISSION && ( {gameState.phase === GamePhase.MISSION && (
<motion.div key="mission" className="text-center"> <motion.div
key="mission"
className="fixed inset-0 flex items-center justify-center bg-black/90 z-50"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
{gameState.proposedTeam.includes(currentPlayerId) ? ( {gameState.proposedTeam.includes(currentPlayerId) ? (
<div className="flex flex-col items-center gap-6"> <div className="flex flex-col items-center gap-8 w-full max-w-6xl px-4">
<h2 className="text-3xl font-bold text-white mb-4 drop-shadow-lg">¡ESTÁS EN LA MISIÓN!</h2> <h2 className="text-4xl md:text-5xl font-bold text-white mb-4 drop-shadow-2xl text-center uppercase tracking-wider animate-pulse">
<div className="flex gap-8"> 🎯 ¡ESTÁS EN LA MISIÓN!
<button onClick={() => actions.voteMission(true)} className="group"> </h2>
<div className="w-40 h-60 bg-blue-900 rounded-lg shadow-2xl border-2 border-blue-400 flex flex-col items-center justify-center p-4 transform transition-transform hover:scale-105"> <p className="text-white text-xl mb-4 text-center">
<Image src="/assets/images/tokens/mission_success.png" alt="Success" width={120} height={120} /> Elige el resultado de tu participación
<span className="mt-4 text-blue-200 font-bold tracking-widest">ÉXITO</span> </p>
</div>
</button>
{/* Solo los malos pueden sabotear */} {/* DEBUG INFO - TEMPORAL */}
{currentPlayer?.faction === 'spies' && ( <div className="text-xs text-gray-400 bg-black/50 p-2 rounded mb-4">
<button onClick={() => actions.voteMission(false)} className="group"> Debug: Tu ID: {currentPlayerId} | Equipo: [{gameState.proposedTeam.join(', ')}]
<div className="w-40 h-60 bg-red-900 rounded-lg shadow-2xl border-2 border-red-400 flex flex-col items-center justify-center p-4 transform transition-transform hover:scale-105"> <br />
<Image src="/assets/images/tokens/mission_fail.png" alt="Fail" width={120} height={120} /> Tu facción: {currentPlayer?.faction || 'UNDEFINED'} | Rol: {currentPlayer?.role || 'UNDEFINED'}
<span className="mt-4 text-red-200 font-bold tracking-widest">SABOTAJE</span> </div>
</div>
</button> {/* Cartas en orden aleatorio */}
<div className="flex gap-12 flex-wrap justify-center">
{cardOrder ? (
<>
{/* Carta de Éxito primero */}
<button
onClick={() => handleMissionVote(true)}
className={`group transition-opacity ${missionVote === true ? 'opacity-100' : 'opacity-50'}`}
disabled={missionVote !== null}
>
<motion.div
className="w-64 h-96 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-6 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
whileHover={{ scale: 1.1, rotate: 3 }}
whileTap={{ scale: 0.95 }}
>
<Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={180} height={180} className="drop-shadow-2xl" />
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">ÉXITO</span>
</motion.div>
</button>
{/* Carta de Sabotaje segundo (solo para alemanes) */}
{currentPlayer?.faction === Faction.ALEMANES && (
<button
onClick={() => handleMissionVote(false)}
className={`group transition-opacity ${missionVote === false ? 'opacity-100' : 'opacity-50'}`}
disabled={missionVote !== null}
>
<motion.div
className="w-64 h-96 bg-gradient-to-br from-red-600 to-red-900 rounded-2xl shadow-2xl border-4 border-red-400 flex flex-col items-center justify-center p-6 transform transition-all hover:scale-110 hover:-rotate-3 hover:shadow-red-500/50"
whileHover={{ scale: 1.1, rotate: -3 }}
whileTap={{ scale: 0.95 }}
>
<Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={180} height={180} className="drop-shadow-2xl" />
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">SABOTAJE</span>
</motion.div>
</button>
)}
</>
) : (
<>
{/* Carta de Sabotaje primero (solo para alemanes) */}
{currentPlayer?.faction === Faction.ALEMANES && (
<button
onClick={() => handleMissionVote(false)}
className={`group transition-opacity ${missionVote === false ? 'opacity-100' : 'opacity-50'}`}
disabled={missionVote !== null}
>
<motion.div
className="w-64 h-96 bg-gradient-to-br from-red-600 to-red-900 rounded-2xl shadow-2xl border-4 border-red-400 flex flex-col items-center justify-center p-6 transform transition-all hover:scale-110 hover:-rotate-3 hover:shadow-red-500/50"
whileHover={{ scale: 1.1, rotate: -3 }}
whileTap={{ scale: 0.95 }}
>
<Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={180} height={180} className="drop-shadow-2xl" />
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">SABOTAJE</span>
</motion.div>
</button>
)}
{/* Carta de Éxito segundo */}
<button
onClick={() => handleMissionVote(true)}
className={`group transition-opacity ${missionVote === true ? 'opacity-100' : 'opacity-50'}`}
disabled={missionVote !== null}
>
<motion.div
className="w-64 h-96 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-6 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
whileHover={{ scale: 1.1, rotate: 3 }}
whileTap={{ scale: 0.95 }}
>
<Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={180} height={180} className="drop-shadow-2xl" />
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">ÉXITO</span>
</motion.div>
</button>
</>
)} )}
</div> </div>
</div> </div>
) : ( ) : (
<div className="text-white text-2xl font-mono bg-black/50 p-6 rounded"> <div className="text-white text-3xl font-mono bg-black/70 p-8 rounded-xl border-2 border-white/20 text-center">
<div className="animate-pulse mb-4 text-5xl">⏳</div>
La misión está en curso...<br /> La misión está en curso...<br />
<span className="text-sm text-gray-400">Rezando por el éxito.</span> <span className="text-lg text-gray-400 mt-2 block">Esperando a que el equipo complete su votación.</span>
</div> </div>
)} )}
</motion.div> </motion.div>
@@ -474,7 +713,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{gameState.phase === 'mission_reveal' as any && ( {gameState.phase === 'mission_reveal' as any && (
<MissionReveal <MissionReveal
votes={gameState.revealedVotes || []} votes={gameState.revealedVotes || []}
onComplete={() => isHost && actions.finishMissionReveal()} onFinished={() => actions.finishMissionReveal()}
/> />
)} )}
@@ -482,10 +721,72 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{gameState.phase === 'mission_result' as any && ( {gameState.phase === 'mission_result' as any && (
<MissionResult <MissionResult
gameState={gameState} gameState={gameState}
isHost={isHost}
onContinue={() => isHost && actions.finishMissionResult()} onContinue={() => isHost && actions.finishMissionResult()}
/> />
)} )}
{/* FASE: ASESINO (FRANCOTIRADOR) */}
{gameState.phase === GamePhase.ASSASSIN_PHASE && (
<motion.div
className="w-full flex flex-col items-center gap-6"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
{currentPlayer?.role === 'francotirador' && (
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 max-w-4xl">
{gameState.players
.filter(p => p.faction === Faction.ALIADOS) // Solo jugadores Aliados
.map(player => (
<motion.button
key={player.id}
onClick={() => actions.assassinKill(player.id)}
className="bg-black/60 hover:bg-red-600/70 border-2 border-white/30 hover:border-red-500 p-3 rounded-lg transition-all backdrop-blur-sm flex flex-col items-center gap-2"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<div className="w-20 h-20 rounded-full border-2 border-white/50 overflow-hidden bg-black relative shadow-xl">
<Image
src={`/assets/images/characters/${player.avatar}`}
alt={player.name}
fill
className="object-cover"
/>
</div>
<p className="text-white font-bold text-sm drop-shadow-[0_2px_4px_rgba(0,0,0,0.8)]">{player.name}</p>
</motion.button>
))}
</div>
)}
{currentPlayer?.role !== 'francotirador' && (
<div className="text-white text-xl font-mono bg-black/50 px-6 py-3 rounded-full border border-white/20 animate-pulse">
El Francotirador está decidiendo...
</div>
)}
</motion.div>
)}
{/* FASE: VICTORIA NAZIS */}
{gameState.phase === GamePhase.NAZIS_WIN && (
<VictoryScreen
gameState={gameState}
isHost={isHost}
onRestart={() => actions.restartGame()}
onFinalize={() => actions.finalizeGame()}
/>
)}
{/* FASE: VICTORIA ALIADOS */}
{gameState.phase === GamePhase.ALLIED_WIN && (
<VictoryScreen
gameState={gameState}
isHost={isHost}
onRestart={() => actions.restartGame()}
onFinalize={() => actions.finalizeGame()}
/>
)}
</AnimatePresence> </AnimatePresence>
</div> </div>
@@ -512,7 +813,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
<div className={` <div className={`
w-16 h-16 rounded-full border-2 overflow-hidden relative shadow-lg bg-black w-16 h-16 rounded-full border-2 overflow-hidden relative shadow-lg bg-black
${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30' : 'border-gray-400'} ${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30' : 'border-gray-400'}
${player.isLeader ? 'ring-2 ring-white' : ''} ${gameState.currentLeaderId === player.id ? 'ring-2 ring-white' : ''}
`}> `}>
<Image <Image
src={avatarSrc} src={avatarSrc}
@@ -522,11 +823,23 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
/> />
{/* Icono de Líder */} {/* Icono de Líder */}
{player.isLeader && ( {gameState.currentLeaderId === player.id && (
<div className="absolute bottom-0 right-0 bg-yellow-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-black font-bold border border-white z-10"> <div className="absolute bottom-0 right-0 bg-yellow-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-black font-bold border border-white z-10">
L L
</div> </div>
)} )}
{/* Icono de Miembro del Equipo de Misión */}
{gameState.proposedTeam.includes(player.id) && (
gameState.phase === GamePhase.VOTING_TEAM ||
gameState.phase === GamePhase.MISSION ||
gameState.phase === 'mission_reveal' as any ||
gameState.phase === 'mission_result' as any
) && (
<div className="absolute top-0 left-0 bg-green-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-white font-bold border border-white z-10">
</div>
)}
</div> </div>
{/* Nombre */} {/* Nombre */}
@@ -544,18 +857,42 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
<div className="absolute top-4 right-4 bg-black/80 p-3 rounded-lg border border-white/20 backdrop-blur-sm"> <div className="absolute top-4 right-4 bg-black/80 p-3 rounded-lg border border-white/20 backdrop-blur-sm">
<div className="text-[10px] text-gray-400 uppercase mb-2 text-center font-bold tracking-wider">Historial</div> <div className="text-[10px] text-gray-400 uppercase mb-2 text-center font-bold tracking-wider">Historial</div>
<div className="flex gap-2"> <div className="flex gap-2">
{gameState.missionHistory.map((mission, idx) => ( {gameState.missionHistory.map((mission, idx) => {
<div const isExpanded = expandedMission === idx;
key={idx}
className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold border-2 ${mission.isSuccess return (
? 'bg-blue-600 border-blue-400 text-white' <div key={idx} className="relative">
: 'bg-red-600 border-red-400 text-white' <div
}`} className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold border-2 cursor-pointer transition-all hover:scale-110 ${mission.isSuccess
title={`Misión ${mission.round}: ${mission.isSuccess ? 'Éxito' : 'Fracaso'} (${mission.successes}${mission.fails}✗)`} ? 'bg-blue-600 border-blue-400 text-white'
> : 'bg-red-600 border-red-400 text-white'
{mission.round} } ${isExpanded ? 'ring-2 ring-yellow-400' : ''}`}
</div> title={`Misión ${mission.round}: ${mission.isSuccess ? 'Éxito' : 'Fracaso'} (${mission.successes} ${mission.fails})`}
))} onClick={(e) => {
e.stopPropagation();
console.log('Click en misión', idx, 'Estado actual:', expandedMission);
setExpandedMission(isExpanded ? null : idx);
}}
>
{mission.round}
</div>
{/* Lista de participantes */}
{isExpanded && (
<div className="absolute top-10 right-0 bg-black/95 p-2 rounded border border-white/30 min-w-max z-[100]">
{mission.team.map((playerId) => {
const player = gameState.players.find(p => p.id === playerId);
return (
<div key={playerId} className="text-xs text-white whitespace-nowrap">
{player?.name || playerId}
</div>
);
})}
</div>
)}
</div>
);
})}
</div> </div>
</div> </div>
)} )}
@@ -564,18 +901,17 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
); );
} }
// Subcomponente para el Timer de Votación // Subcomponente para el Timer de Votación (solo visual, el servidor controla el timeout real)
function VotingTimer({ onTimeout }: { onTimeout: () => void }) { function VotingTimer() {
const [timeLeft, setTimeLeft] = useState(10); const [timeLeft, setTimeLeft] = useState(10);
useEffect(() => { useEffect(() => {
if (timeLeft <= 0) { if (timeLeft <= 0) {
onTimeout(); return; // El servidor se encargará de forzar la resolución
return;
} }
const interval = setInterval(() => setTimeLeft(t => t - 1), 1000); const interval = setInterval(() => setTimeLeft(t => t - 1), 1000);
return () => clearInterval(interval); return () => clearInterval(interval);
}, [timeLeft, onTimeout]); }, [timeLeft]);
return ( return (
<div className="absolute top-4 right-4 bg-red-600/80 text-white w-16 h-16 rounded-full flex items-center justify-center border-4 border-red-400 animate-pulse text-2xl font-bold font-mono"> <div className="absolute top-4 right-4 bg-red-600/80 text-white w-16 h-16 rounded-full flex items-center justify-center border-4 border-red-400 animate-pulse text-2xl font-bold font-mono">

View File

@@ -0,0 +1,86 @@
import { motion } from 'framer-motion';
import { GameState } from '../../../shared/types';
interface MissionResultProps {
gameState: GameState;
onContinue: () => void;
isHost: boolean;
}
export default function MissionResult({ gameState, onContinue, isHost }: MissionResultProps) {
// Obtener la última misión del historial
const lastMission = gameState.missionHistory[gameState.missionHistory.length - 1];
if (!lastMission) {
return (
<div className="fixed inset-0 flex items-center justify-center bg-black/90 z-50">
<p className="text-white text-2xl">Cargando resultado...</p>
</div>
);
}
const { successes, fails, isSuccess } = lastMission;
return (
<motion.div
className="fixed inset-0 flex flex-col items-center justify-center bg-transparent z-50"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
<motion.h2
className={`text-6xl md:text-7xl font-bold mb-8 ${isSuccess ? 'text-blue-500' : 'text-red-500'}`}
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ type: 'spring', stiffness: 200, delay: 0.2 }}
>
{isSuccess ? '¡MISIÓN EXITOSA!' : 'MISIÓN FALLIDA'}
</motion.h2>
<motion.div
className="text-white text-3xl mb-8 bg-black/50 p-6 rounded-xl"
initial={{ y: 50, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 0.5 }}
>
<p className="mb-2"> Éxitos: <span className="text-blue-400 font-bold">{successes}</span></p>
<p> Sabotajes: <span className="text-red-400 font-bold">{fails}</span></p>
</motion.div>
<motion.div
className="text-white text-xl mb-8"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 1 }}
>
<p>Misión {gameState.currentRound} de 5</p>
<p className="text-gray-400 text-sm mt-2">
Resistencia: {gameState.missionHistory.filter(m => m.isSuccess).length} |
Espías: {gameState.missionHistory.filter(m => !m.isSuccess).length}
</p>
</motion.div>
{isHost ? (
<motion.button
onClick={onContinue}
className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-bold py-4 px-8 rounded-lg text-xl shadow-lg transform transition-all hover:scale-105"
initial={{ y: 50, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 1.5 }}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
CONTINUAR
</motion.button>
) : (
<motion.div
className="text-white text-lg font-mono bg-black/50 px-6 py-3 rounded-full border border-white/20 animate-pulse"
initial={{ y: 50, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 1.5 }}
>
Esperando al comandante...
</motion.div>
)}
</motion.div>
);
}

View File

@@ -0,0 +1,64 @@
import { motion } from 'framer-motion';
import { useEffect } from 'react';
import Image from 'next/image';
interface MissionRevealProps {
votes: boolean[];
onFinished?: () => void;
}
export default function MissionReveal({ votes, onFinished }: MissionRevealProps) {
// Timer de seguridad: 5 segundos y avanza
useEffect(() => {
const timer = setTimeout(() => {
if (onFinished) onFinished();
}, 5000);
return () => clearTimeout(timer);
}, [onFinished]);
return (
<motion.div
className="fixed inset-0 flex flex-col items-center justify-center bg-black/95 z-50 pointer-events-auto"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
<h2 className="text-5xl font-bold text-white mb-12 uppercase tracking-widest drop-shadow-lg">
Resultado de Misión
</h2>
<div className="flex gap-8 justify-center mb-12 flex-wrap max-w-[90vw]">
{votes.map((vote, idx) => (
<motion.div
key={idx}
className="w-48 h-72 rounded-xl flex items-center justify-center shadow-2xl relative overflow-hidden"
initial={{ scale: 0, rotateY: 180 }}
animate={{ scale: 1, rotateY: 0 }}
transition={{
delay: idx * 0.3,
type: "spring",
stiffness: 200,
damping: 20
}}
>
<Image
src={vote ? '/assets/images/tokens/vote_approve.png' : '/assets/images/tokens/vote_reject.png'}
alt={vote ? 'Éxito' : 'Sabotaje'}
fill
className="object-contain"
/>
</motion.div>
))}
</div>
<motion.div
className="text-white text-xl font-mono mt-8"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: votes.length * 0.3 + 0.5 }}
>
<span className="animate-pulse">Analizando resultado estratégico...</span>
</motion.div>
</motion.div>
);
}

View File

@@ -0,0 +1,127 @@
import { motion } from 'framer-motion';
import { useState, useEffect } from 'react';
import Image from 'next/image';
import { GameState, Faction } from '../../../shared/types';
interface VictoryScreenProps {
gameState: GameState;
isHost: boolean;
onRestart: () => void;
onFinalize: () => void;
}
export default function VictoryScreen({ gameState, isHost, onRestart, onFinalize }: VictoryScreenProps) {
const [timeLeft, setTimeLeft] = useState(30);
const isNazisWin = gameState.winner === Faction.ALEMANES;
// Timer de 30 segundos
useEffect(() => {
const timer = setInterval(() => {
setTimeLeft(prev => {
if (prev <= 1) {
// Se acabó el tiempo, finalizar automáticamente
onFinalize();
return 0;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, [onFinalize]);
return (
<motion.div
className="fixed inset-0 flex flex-col items-center justify-center z-50 relative"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
{/* Título de victoria */}
<motion.div
className="text-center mb-12 relative z-10"
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ type: 'spring', stiffness: 200, delay: 0.2 }}
>
<h1 className={`text-7xl md:text-8xl font-bold mb-4 drop-shadow-[0_4px_8px_rgba(0,0,0,0.9)] ${isNazisWin ? 'text-red-600' : 'text-blue-500'}`}>
{isNazisWin ? '¡VICTORIA NAZI!' : '¡VICTORIA ALIADA!'}
</h1>
<p className="text-3xl text-white drop-shadow-[0_4px_8px_rgba(0,0,0,0.9)] font-bold">
{isNazisWin ? 'Los Nazis han conquistado Francia' : 'La Resistencia ha triunfado'}
</p>
</motion.div>
{/* Información del juego */}
<motion.div
className="bg-black/70 p-8 rounded-xl border-2 border-white/30 mb-8 max-w-2xl relative z-10 backdrop-blur-sm"
initial={{ y: 50, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 0.5 }}
>
<div className="grid grid-cols-2 gap-6 text-center">
<div>
<p className="text-gray-300 text-sm uppercase mb-2 font-bold">Misiones Exitosas</p>
<p className="text-4xl font-bold text-blue-400">
{gameState.questResults.filter(r => r === true).length}
</p>
</div>
<div>
<p className="text-gray-300 text-sm uppercase mb-2 font-bold">Misiones Fracasadas</p>
<p className="text-4xl font-bold text-red-400">
{gameState.questResults.filter(r => r === false).length}
</p>
</div>
</div>
</motion.div>
{/* Botones para el host */}
{isHost ? (
<motion.div
className="flex flex-col items-center gap-4 relative z-10"
initial={{ y: 50, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 1 }}
>
<p className="text-yellow-400 font-bold text-2xl mb-2 drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)] bg-black/50 px-6 py-2 rounded-full">
Tiempo restante: {timeLeft}s
</p>
<div className="flex gap-6">
<motion.button
onClick={onRestart}
className="bg-green-600 hover:bg-green-500 text-white font-bold py-3 px-6 rounded-xl text-lg shadow-2xl border-2 border-green-400"
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.95 }}
>
🔄 NUEVA PARTIDA
</motion.button>
<motion.button
onClick={onFinalize}
className="bg-red-600 hover:bg-red-500 text-white font-bold py-3 px-6 rounded-xl text-lg shadow-2xl border-2 border-red-400"
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.95 }}
>
TERMINAR
</motion.button>
</div>
<p className="text-white text-base mt-2 bg-black/60 px-6 py-2 rounded-full drop-shadow-[0_2px_4px_rgba(0,0,0,0.9)]">
Si no decides, la partida terminará automáticamente
</p>
</motion.div>
) : (
<motion.div
className="text-center relative z-10"
initial={{ y: 50, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ delay: 1 }}
>
<p className="text-white text-2xl font-mono bg-black/50 px-8 py-4 rounded-full border border-white/20 animate-pulse">
Esperando decisión del comandante...
</p>
<p className="text-gray-500 text-sm mt-4">
Tiempo restante: {timeLeft}s
</p>
</motion.div>
)}
</motion.div>
);
}

View File

@@ -44,6 +44,12 @@ export const useSocket = () => {
alert(msg); // Simple error handling for now alert(msg); // Simple error handling for now
}); });
// Manejar finalización de partida por el host
socketInstance.on('game_finalized', () => {
console.log('La partida ha sido finalizada por el host');
setGameState(null); // Resetear estado para volver al lobby
});
setSocket(socketInstance); setSocket(socketInstance);
return () => { return () => {
@@ -97,13 +103,15 @@ export const useSocket = () => {
proposeTeam, proposeTeam,
voteTeam, voteTeam,
voteMission, voteMission,
voteLeader: (approve: boolean | null) => socket?.emit('vote_leader', { roomId: gameState?.roomId, approve }), voteLeader: (approve: boolean) => socket?.emit('vote_leader', { roomId: gameState?.roomId, approve }),
assassinKill, assassinKill,
finishIntro: () => socket?.emit('finish_intro', { roomId: gameState?.roomId }), finishIntro: () => socket?.emit('finish_intro', { roomId: gameState?.roomId }),
finishReveal: () => socket?.emit('finish_reveal', { roomId: gameState?.roomId }), finishReveal: () => socket?.emit('finish_reveal', { roomId: gameState?.roomId }),
finishRollCall: () => socket?.emit('finish_roll_call', { roomId: gameState?.roomId }), finishRollCall: () => socket?.emit('finish_roll_call', { roomId: gameState?.roomId }),
finishMissionReveal: () => socket?.emit('finish_reveal', { roomId: gameState?.roomId }), finishMissionReveal: () => socket?.emit('finish_reveal', { roomId: gameState?.roomId }),
finishMissionResult: () => socket?.emit('finish_mission_result', { roomId: gameState?.roomId }) finishMissionResult: () => socket?.emit('finish_mission_result', { roomId: gameState?.roomId }),
restartGame: () => socket?.emit('restart_game', { roomId: gameState?.roomId }),
finalizeGame: () => socket?.emit('finalize_game', { roomId: gameState?.roomId })
} }
}; };
}; };

63
docker-compose_prod.yml Normal file
View File

@@ -0,0 +1,63 @@
services:
# --- FRONTEND (Next.js) ---
client:
container_name: resistencia-client
build:
context: .
dockerfile: client/Dockerfile
ports:
- "3000:3000"
volumes:
- ./client:/app/client
- ./shared:/app/shared
- /app/client/node_modules
environment:
- NEXT_PUBLIC_API_URL=https://api.franciaocupada.martivich.es
depends_on:
- server
networks:
- resistencia-net
# --- BACKEND (Node/Express + Socket.io) ---
server:
container_name: resistencia-server
build:
context: .
dockerfile: server/Dockerfile
ports:
- "4000:4000"
volumes:
- ./server:/app/server
- ./shared:/app/shared
- /app/server/node_modules
environment:
- PORT=4000
- DATABASE_URL=postgresql://postgres:password@db:5432/resistencia
- CORS_ORIGIN=https://franciaocupada.martivich.es
depends_on:
- db
networks:
- resistencia-net
# --- BASE DE DATOS (PostgreSQL) ---
db:
container_name: resistencia-db
image: postgres:15-alpine
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: resistencia
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- resistencia-net
networks:
resistencia-net:
driver: bridge
volumes:
postgres_data:

67
fases.txt Normal file
View File

@@ -0,0 +1,67 @@
FASES DEL JUEGO - FRANCIA OCUPADA
===================================
Orden de las fases desde el inicio hasta el final:
1. LOBBY
- Sala de espera antes de iniciar la partida
- Los jugadores se unen y el host configura la partida
2. INTRO
- Introducción/presentación del juego
- Ambientación inicial
3. REVEAL_ROLE
- Cada jugador descubre su carta/rol de forma privada
- Se asignan roles: Marlene, Capitán Philippe, Partisano, etc.
4. ROLL_CALL
- Fase donde se muestran los roles según las reglas del juego
- Algunos jugadores ven información de otros según su rol
- Ej: Marlene ve quiénes son nazis, Capitán Philippe ve a Marlene y Agente Doble
5. VOTE_LEADER
- Votación para aceptar o rechazar al líder propuesto
- Todos los jugadores votan
6. TEAM_BUILDING
- El líder selecciona el equipo para la misión
- Debe elegir el número correcto de jugadores según la ronda
7. VOTING_TEAM
- Todos votan si aprueban o rechazan el equipo propuesto
- Si se rechaza 5 veces seguidas, ganan los Nazis
8. MISSION
- Los miembros del equipo seleccionado votan éxito/fracaso en la misión
- Aliados solo pueden votar éxito, Nazis pueden votar fracaso
9. MISSION_REVEAL
- Se revelan las cartas de votación de la misión una a una
- Animación de descubrimiento de votos
10. MISSION_RESULT
- Pantalla de resumen del resultado de la misión
- Muestra si la misión fue exitosa o fracasó
11. ASSASSIN_PHASE
- Solo si ganan los Aliados (3 misiones exitosas)
- El Francotirador intenta identificar y eliminar a Marlene
- Si acierta, ganan los Nazis; si falla, ganan los Aliados
12. NAZIS_WIN
- Pantalla de victoria de los Nazis/Alemanes
- Se muestra cuando los Nazis ganan por misiones o por el Francotirador
13. ALLIED_WIN
- Pantalla de victoria de los Aliados
- Se muestra cuando los Aliados ganan y el Francotirador falla
14. GAME_OVER
- Fin del juego
- Opción de nueva partida o salir
NOTAS:
- Las fases 6-10 se repiten hasta que un bando gane 3 misiones
- La fase ASSASSIN_PHASE solo ocurre si los Aliados ganan 3 misiones primero
- Los Nazis pueden ganar por: 3 misiones fracasadas, 5 rechazos consecutivos de equipo, o Francotirador acertando

View File

@@ -5,6 +5,7 @@ import cors from 'cors';
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import crypto from 'crypto'; import crypto from 'crypto';
import { Game } from './models/Game'; import { Game } from './models/Game';
import { GamePhase } from '../../shared/types';
dotenv.config(); dotenv.config();
@@ -28,6 +29,9 @@ const io = new Server(server, {
// En el futuro esto podría estar en Redis o Postgres // En el futuro esto podría estar en Redis o Postgres
const games: Record<string, Game> = {}; const games: Record<string, Game> = {};
// Almacén de timers para auto-resolución de votaciones
const voteTimers: Record<string, NodeJS.Timeout> = {};
// --- LOBBY MANAGEMENT --- // --- LOBBY MANAGEMENT ---
const MISSION_NAMES = [ const MISSION_NAMES = [
@@ -38,6 +42,24 @@ const MISSION_NAMES = [
"Operación Eiche", "Operación León Marino", "Operación Urano" "Operación Eiche", "Operación León Marino", "Operación Urano"
]; ];
// Helper para iniciar timer de votación de líder (10 segundos)
function startLeaderVoteTimer(roomId: string) {
if (voteTimers[roomId]) clearTimeout(voteTimers[roomId]);
voteTimers[roomId] = setTimeout(() => {
const g = games[roomId];
if (g && g.state.phase === 'vote_leader') {
// Forzar resolución de votos cuando se acaba el tiempo
g.forceResolveLeaderVote();
io.to(roomId).emit('game_state', g.state);
// Si sigue en vote_leader (líder rechazado, nuevo líder), reiniciar timer
if (g.state.phase === 'vote_leader') {
startLeaderVoteTimer(roomId);
}
}
}, 10000); // 10 segundos
}
const generateRoomName = () => { const generateRoomName = () => {
const idx = Math.floor(Math.random() * MISSION_NAMES.length); const idx = Math.floor(Math.random() * MISSION_NAMES.length);
const suffix = Math.floor(100 + Math.random() * 900); // 3 digit code const suffix = Math.floor(100 + Math.random() * 900); // 3 digit code
@@ -149,24 +171,43 @@ io.on('connection', (socket) => {
} }
}); });
// 2.3 FINALIZAR ROLL CALL -> PRIMER TURNO DE JUEGO (TEAM_BUILDING) // 2.3 FINALIZAR ROLL CALL -> PRIMER TURNO DE JUEGO
socket.on('finish_roll_call', ({ roomId }) => { socket.on('finish_roll_call', ({ roomId }) => {
const game = games[roomId]; const game = games[roomId];
if (game && game.hostId === socket.id && game.state.phase === 'roll_call') { if (game && game.hostId === socket.id && game.state.phase === 'roll_call') {
// Ir a VOTE_LEADER (ya que startGame lo inicializa a VOTE_LEADER en el modelo, y nextLeader tambien) // ERROR CORREGIDO: No llamar a startGame() de nuevo porque re-baraja los roles.
// Solo debemos asegurarnos que el GameState se sincronice. // Simplemente avanzamos a la fase de votación de líder que ya estaba configurada.
if (game.startGame()) { game.state.phase = 'vote_leader' as any;
io.to(roomId).emit('game_state', game.state);
} // Iniciar timer de 11 segundos para forzar cambio de líder
startLeaderVoteTimer(roomId);
io.to(roomId).emit('game_state', game.state);
} }
}); });
// 2.4 VOTAR LÍDER // 2.4 VOTAR LÍDER
socket.on('vote_leader', ({ roomId, approve }) => { socket.on('vote_leader', ({ roomId, approve }) => {
const game = games[roomId]; const game = games[roomId];
if (game) { if (game) {
const previousPhase = game.state.phase;
game.voteLeader(socket.id, approve); game.voteLeader(socket.id, approve);
io.to(roomId).emit('game_state', game.state); io.to(roomId).emit('game_state', game.state);
// Si cambió de fase (líder aprobado o rechazado)
if (game.state.phase !== previousPhase) {
// Limpiar timer actual
if (voteTimers[roomId]) {
clearTimeout(voteTimers[roomId]);
delete voteTimers[roomId];
}
// Si pasó a vote_leader de nuevo (líder rechazado), iniciar nuevo timer
if (game.state.phase === 'vote_leader') {
startLeaderVoteTimer(roomId);
}
}
} }
}); });
@@ -200,18 +241,26 @@ io.on('connection', (socket) => {
// 5.1 FINALIZAR REVELACIÓN DE CARTAS // 5.1 FINALIZAR REVELACIÓN DE CARTAS
socket.on('finish_reveal', ({ roomId }) => { socket.on('finish_reveal', ({ roomId }) => {
const game = games[roomId]; const game = games[roomId];
if (game && game.hostId === socket.id && game.state.phase === 'mission_reveal') { // Permitir a cualquiera avanzar para evitar bloqueos
if (game && game.state.phase === 'mission_reveal') {
game.finishReveal(); game.finishReveal();
io.to(roomId).emit('game_state', game.state); io.to(roomId).emit('game_state', game.state);
} }
}); });
// 5.2 FINALIZAR PANTALLA DE RESULTADO // 5.2 FINALIZAR PANTALLA DE RESULTADO
socket.on('finish_mission_result', ({ roomId }) => { socket.on('finish_mission_result', ({ roomId }) => {
const game = games[roomId]; const game = games[roomId];
if (game && game.hostId === socket.id && game.state.phase === 'mission_result') { if (game && game.hostId === socket.id && game.state.phase === GamePhase.MISSION_RESULT) {
game.finishMissionResult(); game.finishMissionResult();
io.to(roomId).emit('game_state', game.state); io.to(roomId).emit('game_state', game.state);
// Si volvió a vote_leader (nueva ronda), iniciar timer
// TypeScript no detecta que finishMissionResult() cambia la fase, usamos type assertion
if ((game.state.phase as GamePhase) === GamePhase.VOTE_LEADER) {
startLeaderVoteTimer(roomId);
}
} }
}); });
@@ -225,7 +274,34 @@ io.on('connection', (socket) => {
} }
}); });
// 7. DESCONEXIÓN // 7. REINICIAR PARTIDA
socket.on('restart_game', ({ roomId }) => {
const game = games[roomId];
if (game && game.hostId === socket.id) {
game.restartGame();
io.to(roomId).emit('game_state', game.state);
}
});
// 8. FINALIZAR Y EXPULSAR JUGADORES
socket.on('finalize_game', ({ roomId }) => {
const game = games[roomId];
if (game && game.hostId === socket.id) {
// Notificar a todos los jugadores que la partida ha sido finalizada
io.to(roomId).emit('game_finalized');
// Eliminar la partida inmediatamente del registro
delete games[roomId];
// Actualizar lista de salas para todos los clientes
io.emit('rooms_list', getRoomsList());
// Desconectar a todos los jugadores de la sala
io.in(roomId).socketsLeave(roomId);
}
});
// 9. DESCONEXIÓN
socket.on('disconnect', () => { socket.on('disconnect', () => {
// Buscar en qué partida estaba y sacarlo (opcional, por ahora solo notificamos) // Buscar en qué partida estaba y sacarlo (opcional, por ahora solo notificamos)
console.log('Desconectado:', socket.id); console.log('Desconectado:', socket.id);

View File

@@ -47,9 +47,21 @@ export class Game {
} }
addPlayer(id: string, name: string): Player { addPlayer(id: string, name: string): Player {
// Asignar avatar aleatorio persistente (rebel001.jpg - rebel010.jpg) // Asignar avatar aleatorio sin repetir (rebel001.jpg - rebel010.jpg)
const avatarIdx = Math.floor(Math.random() * 10) + 1; // Obtener avatares ya usados
const avatarStr = `rebel${avatarIdx.toString().padStart(3, '0')}.jpg`; const usedAvatars = this.state.players.map(p => p.avatar);
// Crear lista de avatares disponibles
const allAvatars = Array.from({ length: 10 }, (_, i) =>
`rebel${(i + 1).toString().padStart(3, '0')}.jpg`
);
const availableAvatars = allAvatars.filter(av => !usedAvatars.includes(av));
// Si no hay avatares disponibles (más de 10 jugadores), usar cualquiera
const avatarStr = availableAvatars.length > 0
? availableAvatars[Math.floor(Math.random() * availableAvatars.length)]
: allAvatars[Math.floor(Math.random() * allAvatars.length)];
const player: Player = { const player: Player = {
id, id,
@@ -92,13 +104,13 @@ export class Game {
// ... assignRoles se mantiene igual ... // ... assignRoles se mantiene igual ...
private assignRoles(goodCount: number, evilCount: number) { private assignRoles(goodCount: number, evilCount: number) {
// Roles obligatorios // Roles obligatorios
const roles: Role[] = [Role.MERLIN, Role.ASSASSIN]; const roles: Role[] = [Role.MARLENE, Role.FRANCOTIRADOR]; // Updated roles
// Rellenar resto de malos // Rellenar resto de malos
for (let i = 0; i < evilCount - 1; i++) roles.push(Role.MINION); for (let i = 0; i < evilCount - 1; i++) roles.push(Role.COLABORACIONISTA); // Updated role
// Rellenar resto de buenos // Rellenar resto de buenos
for (let i = 0; i < goodCount - 1; i++) roles.push(Role.LOYAL_SERVANT); for (let i = 0; i < goodCount - 1; i++) roles.push(Role.PARTISANO); // Updated role
// Barajar roles // Barajar roles
const shuffledRoles = roles.sort(() => Math.random() - 0.5); const shuffledRoles = roles.sort(() => Math.random() - 0.5);
@@ -107,16 +119,20 @@ export class Game {
this.state.players.forEach((player, index) => { this.state.players.forEach((player, index) => {
player.role = shuffledRoles[index]; player.role = shuffledRoles[index];
// Asignar facción basada en el rol // Asignar facción basada en el rol
if ([Role.MERLIN, Role.PERCIVAL, Role.LOYAL_SERVANT].includes(player.role)) { if ([Role.MARLENE, Role.PARTISANO].includes(player.role)) { // Updated roles
player.faction = Faction.RESISTANCE; player.faction = Faction.ALIADOS;
} else { } else {
player.faction = Faction.SPIES; player.faction = Faction.ALEMANES;
} }
}); });
} }
// --- LOGICA DE VOTACIÓN DE LÍDER --- // --- LOGICA DE VOTACIÓN DE LÍDER ---
voteLeader(playerId: string, approve: boolean | null) { voteLeader(playerId: string, approve: boolean) {
// Solo registrar el voto si el jugador existe y aún no ha votado
const player = this.state.players.find(p => p.id === playerId);
if (!player) return;
this.state.leaderVotes[playerId] = approve; this.state.leaderVotes[playerId] = approve;
// Comprobar si todos han votado // Comprobar si todos han votado
@@ -125,24 +141,55 @@ export class Game {
} }
} }
// Método para forzar la resolución de votos cuando se acaba el tiempo
forceResolveLeaderVote() {
// Si nadie votó o no todos votaron, se considera fracaso
this.resolveLeaderVote();
}
private resolveLeaderVote() { private resolveLeaderVote() {
const votes = Object.values(this.state.leaderVotes); const totalPlayers = this.state.players.length;
const approves = votes.filter(v => v === true).length; const votesCount = Object.keys(this.state.leaderVotes).length;
const rejects = votes.filter(v => v === false).length;
// Los nulos (timeout) no suman a ninguno, o cuentan como reject implícito?
// "Si llega a 0... su voto no cuenta". Simplemente no suma.
this.log(`Votación de Líder: ${approves} A favor - ${rejects} En contra.`); // Si nadie votó, rechazar automáticamente
if (votesCount === 0) {
this.log(`Votación de Líder: nadie votó. Líder rechazado.`);
this.state.failedVotesCount++;
if (approves > rejects) { if (this.state.failedVotesCount >= 5) {
this.endGame(Faction.ALEMANES, 'Se han rechazado 5 líderes consecutivos.');
} else {
this.nextLeader();
}
return;
}
// Contar votos de aprobación y rechazo
const approves = Object.values(this.state.leaderVotes).filter(v => v === true).length;
const rejects = Object.values(this.state.leaderVotes).filter(v => v === false).length;
// La mayoría se calcula sobre los que votaron, no sobre el total
const isSuccess = approves > rejects;
this.log(`Votación de Líder: ${approves} a favor, ${rejects} en contra (${votesCount}/${totalPlayers} votaron)`);
if (isSuccess) {
// Líder Aprobado -> Fase de Construcción de Equipo // Líder Aprobado -> Fase de Construcción de Equipo
this.state.phase = GamePhase.TEAM_BUILDING; this.state.phase = GamePhase.TEAM_BUILDING;
this.state.proposedTeam = []; // Reset team selection this.state.proposedTeam = []; // Reset team selection
this.log('Líder confirmado. Ahora debe proponer un equipo.'); this.state.failedVotesCount = 0; // Reset contador al aprobar líder
this.log(`Líder ${this.state.players.find(p => p.id === this.state.currentLeaderId)?.name} confirmado con ${approves} votos a favor.`);
} else { } else {
// Líder Rechazado -> Siguiente líder // Líder Rechazado -> Incrementar contador y pasar al siguiente líder
this.log('Líder rechazado. Pasando turno al siguiente jugador.'); this.state.failedVotesCount++;
this.nextLeader(); // Esto pondrá phase en VOTE_LEADER de nuevo this.log(`Líder rechazado: ${rejects} votos en contra superan a ${approves} a favor. Pasando turno al siguiente jugador.`);
// Verificar si se alcanzó el límite de rechazos (5 votos fallidos = alemanes ganan)
if (this.state.failedVotesCount >= 5) {
this.endGame(Faction.ALEMANES, 'Se han rechazado 5 líderes consecutivos.');
} else {
this.nextLeader(); // Esto pondrá phase en VOTE_LEADER de nuevo
}
} }
} }
@@ -154,9 +201,10 @@ export class Game {
if (playerIds.length !== requiredSize) return false; if (playerIds.length !== requiredSize) return false;
this.state.proposedTeam = playerIds; this.state.proposedTeam = playerIds;
this.state.phase = GamePhase.VOTING_TEAM; this.state.phase = GamePhase.MISSION; // Ir directamente a la misión
this.state.teamVotes = {}; // Resetear votos this.state.missionVotes = []; // Resetear votos de misión
this.log(`El líder ha propuesto un equipo de ${playerIds.length} personas.`); this.state.failedVotesCount = 0; // Reset contador de rechazos
this.log(`El líder ha seleccionado un equipo de ${playerIds.length} personas. ¡Comienza la misión!`);
return true; return true;
} }
@@ -188,7 +236,7 @@ export class Game {
this.state.proposedTeam = []; this.state.proposedTeam = [];
if (this.state.failedVotesCount >= 5) { if (this.state.failedVotesCount >= 5) {
this.endGame(Faction.SPIES, 'Se han rechazado 5 equipos consecutivos.'); this.endGame(Faction.ALEMANES, 'Se han rechazado 5 equipos consecutivos.'); // Updated Faction
} else { } else {
this.nextLeader(); // Pasa a VOTE_LEADER this.nextLeader(); // Pasa a VOTE_LEADER
this.log('El equipo fue rechazado. El liderazgo pasa al siguiente jugador.'); this.log('El equipo fue rechazado. El liderazgo pasa al siguiente jugador.');
@@ -242,8 +290,11 @@ export class Game {
this.state.revealedVotes = shuffledVotes; // Las cartas a revelar this.state.revealedVotes = shuffledVotes; // Las cartas a revelar
this.log(`Misión ${round} completada. Revelando votos...`); this.log(`Misión ${round} completada. Revelando votos...`);
// El cliente controlará el avance a MISSION_RESULT con su timer
} }
// Método para avanzar desde MISSION_REVEAL a MISSION_RESULT // Método para avanzar desde MISSION_REVEAL a MISSION_RESULT
finishReveal() { finishReveal() {
this.state.phase = GamePhase.MISSION_RESULT; this.state.phase = GamePhase.MISSION_RESULT;
@@ -261,10 +312,14 @@ export class Game {
const failures = this.state.questResults.filter(r => r === false).length; const failures = this.state.questResults.filter(r => r === false).length;
if (failures >= 3) { if (failures >= 3) {
this.endGame(Faction.SPIES, 'Tres misiones han fracasado.'); // Los Nazis ganan directamente
this.state.winner = Faction.ALEMANES;
this.state.phase = GamePhase.NAZIS_WIN;
this.log('¡Los Nazis han ganado! Tres misiones han fracasado.');
} else if (successes >= 3) { } else if (successes >= 3) {
// Los Aliados han completado 3 misiones, pero el Asesino tiene una oportunidad
this.state.phase = GamePhase.ASSASSIN_PHASE; this.state.phase = GamePhase.ASSASSIN_PHASE;
this.log('¡La Resistencia ha triunfado! Pero el Asesino tiene una última oportunidad...'); this.log('¡La Resistencia ha triunfado! Pero el Francotirador tiene una última oportunidad...');
} else { } else {
// Siguiente ronda // Siguiente ronda
this.state.currentRound++; this.state.currentRound++;
@@ -277,14 +332,20 @@ export class Game {
assassinKill(targetId: string) { assassinKill(targetId: string) {
const target = this.state.players.find(p => p.id === targetId); const target = this.state.players.find(p => p.id === targetId);
if (target && target.role === Role.MERLIN) { if (target && target.role === Role.MARLENE) {
this.endGame(Faction.SPIES, '¡El Asesino ha eliminado a Marlenne (Merlín)!'); // El Francotirador acierta: Nazis ganan
this.state.winner = Faction.ALEMANES;
this.state.phase = GamePhase.NAZIS_WIN;
this.log('¡El Francotirador ha eliminado a Marlene! Los Nazis ganan.');
} else { } else {
this.endGame(Faction.RESISTANCE, 'El Asesino ha fallado. ¡La Resistencia gana!'); // El Francotirador falla: Aliados ganan
this.state.winner = Faction.ALIADOS;
this.state.phase = GamePhase.ALLIED_WIN;
this.log('El Francotirador ha fallado. ¡La Resistencia gana!');
} }
} }
private nextLeader() { nextLeader() {
const currentIdx = this.state.players.findIndex(p => p.id === this.state.currentLeaderId); const currentIdx = this.state.players.findIndex(p => p.id === this.state.currentLeaderId);
const nextIdx = (currentIdx + 1) % this.state.players.length; const nextIdx = (currentIdx + 1) % this.state.players.length;
@@ -303,6 +364,43 @@ export class Game {
this.log(`FIN DEL JUEGO. Victoria para ${winner}. Razón: ${reason}`); this.log(`FIN DEL JUEGO. Victoria para ${winner}. Razón: ${reason}`);
} }
// Método para reiniciar la partida (volver a REVEAL_ROLE)
restartGame() {
this.log('=== REINICIANDO PARTIDA ===');
// Resetear variables de juego
this.state.currentRound = 1;
this.state.failedVotesCount = 0;
this.state.questResults = [null, null, null, null, null];
this.state.leaderVotes = {};
this.state.proposedTeam = [];
this.state.teamVotes = {};
this.state.missionVotes = [];
this.state.revealedVotes = [];
this.state.missionHistory = [];
this.state.winner = undefined;
// Reasignar roles
const count = this.state.players.length;
const config = GAME_CONFIG[count as keyof typeof GAME_CONFIG];
this.assignRoles(config.good, config.evil);
// Asignar nuevo líder aleatorio
const leaderIndex = Math.floor(Math.random() * count);
this.state.players.forEach((p, i) => p.isLeader = i === leaderIndex);
this.state.currentLeaderId = this.state.players[leaderIndex].id;
// Volver a REVEAL_ROLE
this.state.phase = GamePhase.REVEAL_ROLE;
this.log('Nueva partida iniciada. Revelando roles...');
}
// Método para finalizar definitivamente y preparar expulsión
finalizeGame() {
this.state.phase = GamePhase.GAME_OVER;
this.log('Partida finalizada. Los jugadores serán expulsados.');
}
private log(message: string) { private log(message: string) {
this.state.history.push(message); this.state.history.push(message);
// Mantener solo los últimos 50 mensajes // Mantener solo los últimos 50 mensajes

View File

@@ -1,20 +1,20 @@
export enum Role { export enum Role {
// Bando del Bien (Resistencia Francesa) // Bando Aliado (Resistencia Francesa)
MERLIN = 'merlin', // Marlenne MARLENE = 'marlene', // Agente de inteligencia (antes Merlin)
PERCIVAL = 'percival', CAPITAN_PHILIPPE = 'capitan_philippe', // Oficial que conoce a Marlene (antes Percival)
LOYAL_SERVANT = 'loyal_servant', // Soldado Resistencia PARTISANO = 'partisano', // Miembro leal de la resistencia (antes Loyal Servant)
// Bando del Mal (Ocupación Alemana) // Bando Alemán (Ocupación Nazi)
MORDRED = 'mordred', COMANDANTE_SCHMIDT = 'comandante_schmidt', // Oficial nazi oculto (antes Mordred)
ASSASSIN = 'assassin', FRANCOTIRADOR = 'francotirador', // Puede eliminar a Marlene (antes Assassin)
MORGANA = 'morgana', AGENTE_DOBLE = 'agente_doble', // Se hace pasar por Marlene (antes Morgana)
OBERON = 'oberon', INFILTRADO = 'infiltrado', // Espía solitario (antes Oberon)
MINION = 'minion', // Soldado Alemán COLABORACIONISTA = 'colaboracionista', // Espía genérico (antes Minion/Spy)
} }
export enum Faction { export enum Faction {
RESISTANCE = 'resistance', ALIADOS = 'aliados', // Antes RESISTANCE
SPIES = 'spies', ALEMANES = 'alemanes', // Antes SPIES
} }
export enum GamePhase { export enum GamePhase {
@@ -28,7 +28,9 @@ export enum GamePhase {
MISSION = 'mission', // Los elegidos votan éxito/fracaso MISSION = 'mission', // Los elegidos votan éxito/fracaso
MISSION_REVEAL = 'mission_reveal', // Mostrar cartas una a una MISSION_REVEAL = 'mission_reveal', // Mostrar cartas una a una
MISSION_RESULT = 'mission_result', // Pantalla de resumen MISSION_RESULT = 'mission_result', // Pantalla de resumen
ASSASSIN_PHASE = 'assassin_phase', // Si gana el bien, el asesino intenta matar a Merlín ASSASSIN_PHASE = 'assassin_phase', // Si gana el bien, el asesino intenta matar a Marlene
NAZIS_WIN = 'nazis_win', // Pantalla de victoria de los Nazis
ALLIED_WIN = 'allied_win', // Pantalla de victoria de los Aliados
GAME_OVER = 'game_over', GAME_OVER = 'game_over',
} }