10 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
25 changed files with 1057 additions and 220 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

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'] })
export const metadata: Metadata = {
title: 'La Resistencia: WWII',
title: 'Francia Ocupada: WWII',
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">
<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">
La Resistencia
Francia Ocupada
</h1>
</div>
{view === 'lobby' && (

View File

@@ -1,9 +1,10 @@
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
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 {
gameState: GameState;
@@ -22,6 +23,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
// 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
@@ -41,6 +43,29 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
}
}, [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 isLeader = gameState.currentLeaderId === currentPlayerId; // FIX: Usar currentLeaderId del estado
@@ -73,6 +98,15 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{ 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 ---
const isHost = gameState.hostId === currentPlayerId;
@@ -89,12 +123,14 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
Guerra Total
</h1>
{/* Audio Auto-Play */}
<audio
src="/assets/audio/Intro.ogg"
autoPlay
onEnded={() => isHost && actions.finishIntro()}
/>
{/* Audio Auto-Play - Solo para el host */}
{isHost && (
<audio
src="/assets/audio/Intro.ogg"
autoPlay
onEnded={() => actions.finishIntro()}
/>
)}
{isHost && (
<button
@@ -112,31 +148,31 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
if (gameState.phase === 'reveal_role' as any) {
// Determinar imagen basada en el rol
// Mapeo básico:
// Merlin -> good_merlin.png
// Percival -> good_percival.png
// Servant -> good_soldier_X.png (random)
// Assassin -> evil_assassin.png
// Morgana -> evil_morgana.png
// Mordred -> evil_mordred.png
// Oberon -> evil_oberon.png
// Minion -> evil_minion_X.png
// Mapeo actualizado:
// Marlene -> good_merlin.png
// Capitán Philippe -> good_percival.png
// Partisano -> good_soldier_X.png (random)
// Francotirador -> evil_assassin.png
// Agente Doble -> evil_morgana.png
// Comandante Schmidt -> evil_mordred.png
// Infiltrado -> evil_oberon.png
// Colaboracionista -> evil_minion_X.png
let roleImage = '/assets/images/characters/good_soldier_1.png'; // Default
const role = currentPlayer?.role;
if (role === 'merlin') roleImage = '/assets/images/characters/good_merlin.png';
else if (role === 'assassin') roleImage = '/assets/images/characters/evil_assassin.png';
else if (role === 'percival') roleImage = '/assets/images/characters/good_percival.png';
else if (role === 'morgana') roleImage = '/assets/images/characters/evil_morgana.png';
else if (role === 'mordred') roleImage = '/assets/images/characters/evil_mordred.png';
else if (role === 'oberon') roleImage = '/assets/images/characters/evil_oberon.png';
else if (role === 'loyal_servant') {
if (role === 'marlene') roleImage = '/assets/images/characters/good_merlin.png';
else if (role === 'francotirador') roleImage = '/assets/images/characters/evil_assassin.png';
else if (role === 'capitan_philippe') roleImage = '/assets/images/characters/good_percival.png';
else if (role === 'agente_doble') roleImage = '/assets/images/characters/evil_morgana.png';
else if (role === 'comandante_schmidt') roleImage = '/assets/images/characters/evil_mordred.png';
else if (role === 'infiltrado') roleImage = '/assets/images/characters/evil_oberon.png';
else if (role === 'partisano') {
// Random soldier 1-5
const idx = (currentPlayerId.charCodeAt(0) % 5) + 1;
roleImage = `/assets/images/characters/good_soldier_${idx}.png`;
}
else if (role === 'minion') {
else if (role === 'colaboracionista') {
// Random minion 1-3
const idx = (currentPlayerId.charCodeAt(0) % 3) + 1;
roleImage = `/assets/images/characters/evil_minion_${idx}.png`;
@@ -178,15 +214,9 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
drag="y"
dragConstraints={{ top: -300, bottom: 0 }}
dragElastic={0.2}
onDragEnd={(e, info) => {
// Reducir umbral a -50 para facilitar
if (info.offset.y < -50) {
setRevealCard(true);
}
}}
dragSnapToOrigin={true}
whileHover={{ scale: 1.02 }}
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"
>
<Image
@@ -208,6 +238,8 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
if (gameState.phase === 'roll_call' as any) {
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="absolute inset-0 z-0">
<Image src="/assets/images/ui/bg_roll_call.png" alt="Resistance HQ" fill className="object-cover" />
<div className="absolute inset-0 bg-black/70" />
@@ -228,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">
{gameState.players.map((p, i) => {
// Asignar avatar determinista basado en charCode
const avatarIdx = (p.name.length % 3) + 1;
return (
<motion.div
key={p.id}
@@ -240,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">
<Image
src={`/assets/images/characters/avatar_${avatarIdx}.png`}
src={`/assets/images/characters/${p.avatar}`}
alt="Avatar"
fill
className="object-cover grayscale contrast-125"
@@ -260,82 +290,158 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
return (
<div className="relative w-full h-screen flex flex-col items-center overflow-hidden">
<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>
<div className="relative z-10 w-full flex flex-col items-center">
{/* --- MAPA TÁCTICO (TABLERO) --- */}
<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]">
<Image
src="/assets/images/ui/board_map.jpg"
alt="Tactical Map"
fill
className="object-contain"
/>
{/* --- MAPA TÁCTICO (TABLERO) O CARTA DE MISIÓN O ASSASSIN_PHASE --- */}
{/* No mostrar el tablero en fases de victoria */}
{gameState.phase !== GamePhase.ALLIED_WIN && gameState.phase !== GamePhase.NAZIS_WIN && (
<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]">
{gameState.phase === GamePhase.ASSASSIN_PHASE ? (
/* IMAGEN LASTSHOT PARA ASSASSIN_PHASE */
<>
<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 */}
{missionCoords.map((coord, idx) => {
const result = gameState.questResults[idx];
const isCurrent = gameState.currentRound === idx + 1;
{/* Título sobre la imagen */}
<div className="absolute top-4 left-0 right-0 flex flex-col items-center z-10">
<h1 className="text-5xl font-bold text-red-600 mb-2 drop-shadow-[0_4px_8px_rgba(0,0,0,0.9)]">
¡Ú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 (
<div
key={idx}
className="absolute w-[12%] aspect-square flex items-center justify-center transform -translate-x-1/2 -translate-y-1/2"
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>
)}
{/* TOKENS SOBRE EL MAPA */}
{missionCoords.map((coord, idx) => {
const result = gameState.questResults[idx];
const isCurrent = gameState.currentRound === idx + 1;
{/* Resultado de Misión (Éxito/Fracaso) */}
{result === true && (
<motion.div
initial={{ scale: 0 }} animate={{ scale: 1 }}
className="absolute inset-0 z-20"
>
<Image src="/assets/images/tokens/marker_score_blue.png" alt="Success" fill className="object-contain drop-shadow-lg" />
</motion.div>
)}
{result === false && (
<motion.div
initial={{ scale: 0 }} animate={{ scale: 1 }}
className="absolute inset-0 z-20"
>
<Image src="/assets/images/tokens/marker_score_red.png" alt="Fail" fill className="object-contain drop-shadow-lg" />
</motion.div>
)}
</div>
);
})}
return (
<div
key={idx}
className="absolute w-[10%] aspect-square flex items-center justify-center"
style={{
left: coord.left,
top: coord.top,
transform: 'translate(-50%, -50%)'
}}
>
{/* 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>
)}
{/* TRACK DE VOTOS FALLIDOS (Pequeño indicador en la esquina inferior izquierda del mapa) */}
<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>
{/* Resultado de Misión (Éxito/Fracaso) */}
{result === true && (
<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_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>
)}
{/* --- ÁREA DE JUEGO (CARTAS Y ACCIONES) --- */}
<div className="flex-1 w-full max-w-6xl relative mt-4 px-4">
@@ -357,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?
</div>
{/* Timer */}
{/* Timer visual (solo muestra el tiempo, el servidor controla el timeout) */}
{!gameState.leaderVotes?.[currentPlayerId] && (
<VotingTimer onTimeout={() => actions.voteLeader(null)} />
<VotingTimer key={gameState.currentLeaderId} />
)}
</div>
@@ -523,7 +629,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{/* Carta de Éxito primero */}
<button
onClick={() => handleMissionVote(true)}
className={`group transition-opacity ${missionVote !== null && missionVote !== true ? 'opacity-50' : 'opacity-100'}`}
className={`group transition-opacity ${missionVote === true ? 'opacity-100' : 'opacity-50'}`}
disabled={missionVote !== null}
>
<motion.div
@@ -536,9 +642,13 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
</motion.div>
</button>
{/* Carta de Sabotaje segundo (solo para espías) */}
{currentPlayer?.faction === 'spies' && (
<button onClick={() => handleMissionVote(false)} className="group transition-opacity" style={{ opacity: missionVote !== null && missionVote !== false ? 0.5 : 1 }} disabled={missionVote !== null}>
{/* 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 }}
@@ -552,9 +662,13 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
</>
) : (
<>
{/* Carta de Sabotaje primero (solo para espías) */}
{currentPlayer?.faction === 'spies' && (
<button onClick={() => handleMissionVote(false)} className="group transition-opacity" style={{ opacity: missionVote !== null && missionVote !== false ? 0.5 : 1 }} disabled={missionVote !== null}>
{/* 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 }}
@@ -569,7 +683,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{/* Carta de Éxito segundo */}
<button
onClick={() => handleMissionVote(true)}
className={`group transition-opacity ${missionVote !== null && missionVote !== true ? 'opacity-50' : 'opacity-100'}`}
className={`group transition-opacity ${missionVote === true ? 'opacity-100' : 'opacity-50'}`}
disabled={missionVote !== null}
>
<motion.div
@@ -599,6 +713,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{gameState.phase === 'mission_reveal' as any && (
<MissionReveal
votes={gameState.revealedVotes || []}
onFinished={() => actions.finishMissionReveal()}
/>
)}
@@ -606,10 +721,72 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
{gameState.phase === 'mission_result' as any && (
<MissionResult
gameState={gameState}
isHost={isHost}
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>
</div>
@@ -680,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="text-[10px] text-gray-400 uppercase mb-2 text-center font-bold tracking-wider">Historial</div>
<div className="flex gap-2">
{gameState.missionHistory.map((mission, idx) => (
<div
key={idx}
className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold border-2 ${mission.isSuccess
? 'bg-blue-600 border-blue-400 text-white'
: 'bg-red-600 border-red-400 text-white'
}`}
title={`Misión ${mission.round}: ${mission.isSuccess ? 'Éxito' : 'Fracaso'} (${mission.successes} ${mission.fails})`}
>
{mission.round}
</div>
))}
{gameState.missionHistory.map((mission, idx) => {
const isExpanded = expandedMission === idx;
return (
<div key={idx} className="relative">
<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
? 'bg-blue-600 border-blue-400 text-white'
: 'bg-red-600 border-red-400 text-white'
} ${isExpanded ? 'ring-2 ring-yellow-400' : ''}`}
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>
)}
@@ -700,18 +901,17 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
);
}
// Subcomponente para el Timer de Votación
function VotingTimer({ onTimeout }: { onTimeout: () => void }) {
// Subcomponente para el Timer de Votación (solo visual, el servidor controla el timeout real)
function VotingTimer() {
const [timeLeft, setTimeLeft] = useState(10);
useEffect(() => {
if (timeLeft <= 0) {
onTimeout();
return;
return; // El servidor se encargará de forzar la resolución
}
const interval = setInterval(() => setTimeLeft(t => t - 1), 1000);
return () => clearInterval(interval);
}, [timeLeft, onTimeout]);
}, [timeLeft]);
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">

View File

@@ -4,12 +4,13 @@ import { GameState } from '../../../shared/types';
interface MissionResultProps {
gameState: GameState;
onContinue: () => void;
isHost: boolean;
}
export default function MissionResult({ gameState, onContinue }: MissionResultProps) {
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">
@@ -22,20 +23,20 @@ export default function MissionResult({ gameState, onContinue }: MissionResultPr
return (
<motion.div
className="fixed inset-0 flex flex-col items-center justify-center bg-black/90 z-50"
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' } `}
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
<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 }}
@@ -53,22 +54,33 @@ export default function MissionResult({ gameState, onContinue }: MissionResultPr
>
<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} |
Resistencia: {gameState.missionHistory.filter(m => m.isSuccess).length} |
Espías: {gameState.missionHistory.filter(m => !m.isSuccess).length}
</p>
</motion.div>
<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>
{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

@@ -1,44 +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 }: MissionRevealProps) {
// Auto-avanzar después de mostrar todas las cartas
export default function MissionReveal({ votes, onFinished }: MissionRevealProps) {
// Timer de seguridad: 5 segundos y avanza
useEffect(() => {
const timer = setTimeout(() => {
// El servidor avanzará automáticamente
// Este timer es solo para dar tiempo a ver las cartas
}, 3000 + votes.length * 300); // 3s base + 300ms por carta
if (onFinished) onFinished();
}, 5000);
return () => clearTimeout(timer);
}, [votes.length]);
}, [onFinished]);
return (
<motion.div
className="fixed inset-0 flex flex-col items-center justify-center bg-black/90 z-50"
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-4xl font-bold text-white mb-8">Resultados de la Misión</h2>
<div className="flex gap-4 justify-center mb-8">
<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 - 24 h - 32 rounded - lg flex items - center justify - center text - 5xl font - bold text - white ${
vote ? 'bg-blue-600' : 'bg-red-600'
} `}
initial={{ scale: 0, rotate: -180 }}
animate={{ scale: 1, rotate: 0 }}
transition={{ delay: idx * 0.3 }}
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
}}
>
{vote ? '✓' : '✗'}
<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>
<p className="text-white text-xl">Procesando resultado...</p>
<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
});
// 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);
return () => {
@@ -97,13 +103,15 @@ export const useSocket = () => {
proposeTeam,
voteTeam,
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,
finishIntro: () => socket?.emit('finish_intro', { roomId: gameState?.roomId }),
finishReveal: () => socket?.emit('finish_reveal', { roomId: gameState?.roomId }),
finishRollCall: () => socket?.emit('finish_roll_call', { 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 crypto from 'crypto';
import { Game } from './models/Game';
import { GamePhase } from '../../shared/types';
dotenv.config();
@@ -28,6 +29,9 @@ const io = new Server(server, {
// En el futuro esto podría estar en Redis o Postgres
const games: Record<string, Game> = {};
// Almacén de timers para auto-resolución de votaciones
const voteTimers: Record<string, NodeJS.Timeout> = {};
// --- LOBBY MANAGEMENT ---
const MISSION_NAMES = [
@@ -38,6 +42,24 @@ const MISSION_NAMES = [
"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 idx = Math.floor(Math.random() * MISSION_NAMES.length);
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 }) => {
const game = games[roomId];
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)
// Solo debemos asegurarnos que el GameState se sincronice.
if (game.startGame()) {
io.to(roomId).emit('game_state', game.state);
}
// ERROR CORREGIDO: No llamar a startGame() de nuevo porque re-baraja los roles.
// Simplemente avanzamos a la fase de votación de líder que ya estaba configurada.
game.state.phase = 'vote_leader' as any;
// 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
socket.on('vote_leader', ({ roomId, approve }) => {
const game = games[roomId];
if (game) {
const previousPhase = game.state.phase;
game.voteLeader(socket.id, approve);
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
socket.on('finish_reveal', ({ 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();
io.to(roomId).emit('game_state', game.state);
}
});
// 5.2 FINALIZAR PANTALLA DE RESULTADO
socket.on('finish_mission_result', ({ 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();
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', () => {
// Buscar en qué partida estaba y sacarlo (opcional, por ahora solo notificamos)
console.log('Desconectado:', socket.id);

View File

@@ -47,9 +47,21 @@ export class Game {
}
addPlayer(id: string, name: string): Player {
// Asignar avatar aleatorio persistente (rebel001.jpg - rebel010.jpg)
const avatarIdx = Math.floor(Math.random() * 10) + 1;
const avatarStr = `rebel${avatarIdx.toString().padStart(3, '0')}.jpg`;
// Asignar avatar aleatorio sin repetir (rebel001.jpg - rebel010.jpg)
// Obtener avatares ya usados
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 = {
id,
@@ -92,13 +104,13 @@ export class Game {
// ... assignRoles se mantiene igual ...
private assignRoles(goodCount: number, evilCount: number) {
// Roles obligatorios
const roles: Role[] = [Role.MERLIN, Role.ASSASSIN];
const roles: Role[] = [Role.MARLENE, Role.FRANCOTIRADOR]; // Updated roles
// 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
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
const shuffledRoles = roles.sort(() => Math.random() - 0.5);
@@ -107,16 +119,20 @@ export class Game {
this.state.players.forEach((player, index) => {
player.role = shuffledRoles[index];
// Asignar facción basada en el rol
if ([Role.MERLIN, Role.PERCIVAL, Role.LOYAL_SERVANT].includes(player.role)) {
player.faction = Faction.RESISTANCE;
if ([Role.MARLENE, Role.PARTISANO].includes(player.role)) { // Updated roles
player.faction = Faction.ALIADOS;
} else {
player.faction = Faction.SPIES;
player.faction = Faction.ALEMANES;
}
});
}
// --- 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;
// 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() {
const votes = Object.values(this.state.leaderVotes);
const approves = votes.filter(v => v === true).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.
const totalPlayers = this.state.players.length;
const votesCount = Object.keys(this.state.leaderVotes).length;
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
this.state.phase = GamePhase.TEAM_BUILDING;
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 {
// Líder Rechazado -> Siguiente líder
this.log('Líder rechazado. Pasando turno al siguiente jugador.');
this.nextLeader(); // Esto pondrá phase en VOTE_LEADER de nuevo
// Líder Rechazado -> Incrementar contador y pasar al siguiente líder
this.state.failedVotesCount++;
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
}
}
}
@@ -189,7 +236,7 @@ export class Game {
this.state.proposedTeam = [];
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 {
this.nextLeader(); // Pasa a VOTE_LEADER
this.log('El equipo fue rechazado. El liderazgo pasa al siguiente jugador.');
@@ -244,10 +291,7 @@ export class Game {
this.log(`Misión ${round} completada. Revelando votos...`);
// Auto-avanzar a MISSION_RESULT después de 5 segundos
setTimeout(() => {
this.finishReveal();
}, 5000);
// El cliente controlará el avance a MISSION_RESULT con su timer
}
@@ -268,10 +312,14 @@ export class Game {
const failures = this.state.questResults.filter(r => r === false).length;
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) {
// Los Aliados han completado 3 misiones, pero el Asesino tiene una oportunidad
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 {
// Siguiente ronda
this.state.currentRound++;
@@ -284,14 +332,20 @@ export class Game {
assassinKill(targetId: string) {
const target = this.state.players.find(p => p.id === targetId);
if (target && target.role === Role.MERLIN) {
this.endGame(Faction.SPIES, '¡El Asesino ha eliminado a Marlenne (Merlín)!');
if (target && target.role === Role.MARLENE) {
// 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 {
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 nextIdx = (currentIdx + 1) % this.state.players.length;
@@ -310,6 +364,43 @@ export class Game {
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) {
this.state.history.push(message);
// Mantener solo los últimos 50 mensajes

View File

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