Compare commits
9 Commits
c4c08c64c3
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c723b373d3 | ||
|
|
a3789e5289 | ||
|
|
b68f4e9ff5 | ||
|
|
800db837bb | ||
|
|
69e1f35886 | ||
|
|
98b5984a6b | ||
|
|
b0eb3bd637 | ||
|
|
1a68ed2a5c | ||
|
|
904bd80bd5 |
20
.env.example
20
.env.example
@@ -1,13 +1,25 @@
|
|||||||
|
# ===========================================
|
||||||
|
# Archivo de ejemplo de configuración
|
||||||
|
# Copia este archivo a .env y modifica los valores
|
||||||
|
# ===========================================
|
||||||
|
|
||||||
# Configuración de red local
|
# Configuración de red local
|
||||||
# Cambia esta IP a la IP de tu PC en la red local
|
# Cambia esta IP a la IP de tu PC en la red local
|
||||||
HOST_IP=192.168.1.131
|
HOST_IP=192.168.1.XXX
|
||||||
|
|
||||||
# URLs para desarrollo local
|
# URLs para desarrollo local
|
||||||
NEXT_PUBLIC_API_URL=http://192.168.1.131:4000
|
NEXT_PUBLIC_API_URL=http://192.168.1.XXX:4000
|
||||||
CORS_ORIGIN=http://192.168.1.131:3000
|
CORS_ORIGIN=http://192.168.1.XXX:3000
|
||||||
|
|
||||||
|
# URLs para producción (descomentar y ajustar)
|
||||||
|
# NEXT_PUBLIC_API_URL=https://api.tudominio.com
|
||||||
|
# CORS_ORIGIN=https://tudominio.com
|
||||||
|
|
||||||
# Configuración de base de datos
|
# Configuración de base de datos
|
||||||
DATABASE_URL=postgresql://postgres:password@db:5432/resistencia
|
DATABASE_URL=postgresql://postgres:password@db:5432/resistencia
|
||||||
POSTGRES_USER=postgres
|
POSTGRES_USER=postgres
|
||||||
POSTGRES_PASSWORD=password
|
POSTGRES_PASSWORD=cambia_esta_contraseña
|
||||||
POSTGRES_DB=resistencia
|
POSTGRES_DB=resistencia
|
||||||
|
|
||||||
|
# Contraseña del dashboard de administración
|
||||||
|
NEXT_PUBLIC_ADMIN_PASSWORD=cambia_esta_contraseña
|
||||||
|
|||||||
141
README.md
141
README.md
@@ -1,104 +1,91 @@
|
|||||||
# La Resistencia - Estado del Proyecto
|
# Francia Ocupada (La Resistencia)
|
||||||
|
|
||||||
## 🎮 Estado Actual: FUNCIONAL (Parcial)
|
## 🎮 Estado Actual: v1.4 - ESTABLE
|
||||||
|
|
||||||
|
Proyecto renombrado a **"Traición en París"** / **"Francia Ocupada"**.
|
||||||
|
|
||||||
### ✅ Funcionalidades Implementadas
|
### ✅ Funcionalidades Implementadas
|
||||||
|
|
||||||
#### Backend (100% Completo)
|
#### Backend (Socket.io + Node.js)
|
||||||
- ✅ Sistema de salas y jugadores
|
- ✅ **Sistema de Reconexión Inteligente:** Los jugadores pueden recargar la página o volver a entrar y mantienen su sesión (ID de socket actualizado en tiempo real).
|
||||||
- ✅ Asignación de roles (Resistencia/Espías)
|
- ✅ **Persistencia de Partidas:** Las partidas no se pierden si un jugador se desconecta brevemente.
|
||||||
- ✅ Fases del juego: LOBBY, INTRO, REVEAL_ROLE, ROLL_CALL, VOTE_LEADER, TEAM_BUILDING, VOTE_TEAM, MISSION
|
- ✅ **Control de Sesiones:** Seguimiento de `matchNumber` y `matchResults` para estadísticas continuas en el dashboard de admin.
|
||||||
- ✅ **Nuevas fases**: MISSION_REVEAL, MISSION_RESULT (lógica completa)
|
- ✅ **Lógica de Juego Completa:**
|
||||||
- ✅ Votación de líder con sistema de aprobación/rechazo
|
- Roles ocultos y asignación aleatoria balanceada.
|
||||||
- ✅ Selección y votación de equipos
|
- Fases: Lobby, Intro, Reveal Role, Roll Call, Vote Leader, Team Building, Vote Team, Mission, Mission Reveal, Mission Result, Assassin Phase.
|
||||||
- ✅ Votación de misiones (éxito/sabotaje)
|
- Reglas especiales: 4ª misión con 7+ jug. requiere 2 fallos, 5 rechazos de líder = Victoria espía.
|
||||||
- ✅ **Barajado aleatorio de votos de misión**
|
- Temporizadores de seguridad para votaciones de líder.
|
||||||
- ✅ **Histórico de misiones** (MissionRecord)
|
|
||||||
- ✅ Reglas correctas de éxito/fracaso (misión 4 con 7+ jugadores requiere 2 fallos)
|
|
||||||
- ✅ Sistema de victoria (3 misiones exitosas o 3 fallidas)
|
|
||||||
- ✅ Fase de asesinato (ASSASSIN_PHASE)
|
|
||||||
|
|
||||||
#### Frontend (Funcional hasta Victoria)
|
#### Frontend (Next.js + Tailwind + Framer Motion)
|
||||||
- ✅ Lobby con creación/unión de partidas
|
- ✅ **Diseño Premium:** Estética "World War II" con tipografías, colores y assets temáticos (fichas de póker, documentos secretos, mapas tácticos).
|
||||||
- ✅ Intro con música y animaciones (título: "Traidores en París")
|
- ✅ **UX Fluida:** Animaciones de transición entre todas las fases.
|
||||||
- ✅ Revelación de roles con cartas
|
- ✅ **Feedback Visual:**
|
||||||
- ✅ Roll call con avatares
|
- Cartas de rol específicas para cada personaje (Marlene, Capitán Philippe, Francotirador, etc.).
|
||||||
- ✅ Votación de líder con timer de 10 segundos (esquina superior izquierda)
|
- Tablero táctico dinámico que muestra el progreso de la partida.
|
||||||
- ✅ Selección de equipo por el líder
|
- Indicadores claros de "Tu Turno" o "Esperando al líder".
|
||||||
- ✅ Votación de equipo con cartas cuadradas (aceptar/rechazar)
|
- ✅ **Audio:** Banda sonora y efectos de sonido integrados.
|
||||||
- ✅ Votación de misión (éxito/sabotaje solo para espías)
|
|
||||||
- ✅ **Fase MISSION_REVEAL**: Animación de cartas de votación revelándose
|
|
||||||
- ✅ **Fase MISSION_RESULT**: Pantalla resumen con mapa táctico y tokens de victoria/fracaso
|
|
||||||
- ✅ **Histórico de Misiones**: Círculos clicables en esquina superior derecha
|
|
||||||
- ✅ **Mapa táctico**: Tablero con tokens de misiones y marcadores de resultado
|
|
||||||
- ✅ Pantallas de victoria (Aliados/Nazis)
|
|
||||||
- ✅ Fase de asesinato (ASSASSIN_PHASE)
|
|
||||||
|
|
||||||
### 🎨 Mejoras de UI Recientes (2025-12-13)
|
### 🎨 Últimas Mejoras (v1.4 - Diciembre 2025)
|
||||||
|
|
||||||
- ✅ Timer de votación reposicionado (esquina superior izquierda, fixed, 20px margen)
|
- 🔄 **Fix Crítico:** Solucionado bug donde el Líder perdía sus botones de acción al recargar la página.
|
||||||
- ✅ Cartas de votación de líder redimensionadas (cuadradas 32x32)
|
- 📊 **Dashboard Admin:** Panel de administración mejorado con historial de partidas y estadísticas de victorias.
|
||||||
- ✅ Eliminado contador de votos rechazados en resultado de misión
|
- 🖼️ **Assets:** Nuevas imágenes para roles y fondos de victoria/derrota.
|
||||||
- ✅ Mapa táctico permanece visible durante toda la fase MISSION_RESULT
|
- 📱 **Responsividad:** Mejoras en la vista móvil para la fase de "Pasando Lista" y Tablero.
|
||||||
- ✅ Tokens de victoria/fracaso posicionados en el mapa (ajuste fino pendiente para tokens 3, 4, 5)
|
|
||||||
|
|
||||||
### ⚠️ Pendiente de Ajustar
|
## 🚀 Despliegue y Ejecución
|
||||||
|
|
||||||
1. **Posiciones de tokens en mapa**: Afinar ubicación de tokens de misiones 3, 4 y 5 en el tablero táctico
|
### Requisitos
|
||||||
|
- Docker y Docker Compose
|
||||||
## 🚀 Cómo Ejecutar
|
- Node.js 18+ (para desarrollo local)
|
||||||
|
|
||||||
|
### Ejecución con Docker (Producción)
|
||||||
```bash
|
```bash
|
||||||
# Iniciar todos los servicios
|
# Desplegar todo el stack
|
||||||
docker compose up -d
|
./deploy.sh
|
||||||
|
```
|
||||||
|
|
||||||
# Ver logs
|
El script `deploy.sh` se encarga de:
|
||||||
docker compose logs -f
|
1. Bajar los últimos cambios de `main`.
|
||||||
|
2. Construir las imágenes con tags de versión.
|
||||||
|
3. Levantar los contenedores (Client, Server, DB).
|
||||||
|
|
||||||
# Detener servicios
|
### Desarrollo Local
|
||||||
docker compose down
|
```bash
|
||||||
|
# Servidor
|
||||||
|
cd server && npm run dev
|
||||||
|
|
||||||
|
# Cliente
|
||||||
|
cd client && npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🌐 URLs
|
## 🌐 URLs
|
||||||
|
|
||||||
- **Cliente**: http://localhost:3000
|
- **Juego**: https://franciaocupada.martivich.es
|
||||||
- **Servidor**: http://localhost:4000
|
- **API**: https://api.franciaocupada.martivich.es
|
||||||
- **Base de Datos**: localhost:5432
|
- **Dashboard Admin**: (Accesible vía socket evento `admin_get_data`)
|
||||||
|
|
||||||
## 📝 Git
|
## 📝 Ramas Git
|
||||||
|
|
||||||
### Ramas
|
- `main`: Rama de producción (Estable v1.4).
|
||||||
- `master`: Estado inicial con errores
|
- `develop`: Rama de desarrollo e integración.
|
||||||
- `fix-gameboard`: Estado actual funcional ✅
|
|
||||||
|
|
||||||
### Commits Importantes
|
## 👥 Roles del Juego
|
||||||
1. `8d423ac` - Estado inicial con errores de sintaxis
|
|
||||||
2. `44d7418` - GameBoard limpio y funcional
|
|
||||||
3. `5bb1b17` - VotingTimer agregado correctamente
|
|
||||||
|
|
||||||
## 🐛 Problemas Conocidos
|
**La Resistencia (Aliados)**
|
||||||
|
- **Marlene (Merlín):** Conoce a los espías. Debe mantenerse oculta.
|
||||||
|
- **Capitán Philippe (Percival):** Conoce a Marlene (y al Agente Doble). Debe protegerla.
|
||||||
|
- **Partisanos:** Miembros leales de la resistencia. No saben nada.
|
||||||
|
|
||||||
1. **CPU Alta en Servidor**: El servidor puede consumir mucha CPU. Si ocurre, reiniciar con `docker compose restart server`
|
**El Eje (Alemanes/Espías)**
|
||||||
2. **Posiciones de tokens en mapa**: Los tokens de misiones 3, 4 y 5 necesitan ajuste fino en sus coordenadas
|
- **Francotirador (Asesino):** Si los aliados ganan las 3 misiones, tiene un disparo final para matar a Marlene y robar la victoria.
|
||||||
|
- **Agente Doble (Morgana):** Se hace pasar por Marlene ante el Capitán Philippe.
|
||||||
|
- **Comandante Schmidt (Mordred):** Espía desconocido para Marlene.
|
||||||
|
- **Infiltrado (Oberon):** Espía que no conoce a los otros espías.
|
||||||
|
- **Colaboricionistas:** Espías estándar.
|
||||||
|
|
||||||
## 📋 Próximos Pasos
|
## 🔧 Stack Tecnológico
|
||||||
|
|
||||||
1. Afinar posiciones de tokens de misiones 3, 4 y 5 en el mapa táctico
|
|
||||||
2. Optimizar rendimiento del servidor
|
|
||||||
3. Testing exhaustivo de todas las fases del juego
|
|
||||||
4. Ajustes finales de UX/UI según feedback de jugadores
|
|
||||||
|
|
||||||
## 🎯 Reglas del Juego Implementadas
|
|
||||||
|
|
||||||
- Votación de líder: mayoría simple aprueba
|
|
||||||
- 5 rechazos consecutivos: victoria de espías
|
|
||||||
- Misiones: 1 fallo = fracaso (excepto misión 4 con 7+ jugadores que requiere 2 fallos)
|
|
||||||
- 3 misiones exitosas: victoria de resistencia (con fase de asesinato)
|
|
||||||
- 3 misiones fallidas: victoria de espías
|
|
||||||
|
|
||||||
## 🔧 Tecnologías
|
|
||||||
|
|
||||||
- **Frontend**: Next.js 14, React, TypeScript, Framer Motion, TailwindCSS
|
- **Frontend**: Next.js 14, React, TypeScript, Framer Motion, TailwindCSS
|
||||||
- **Backend**: Node.js, Express, Socket.IO, TypeScript
|
- **Backend**: Node.js, Express, Socket.IO, TypeScript
|
||||||
- **Base de Datos**: PostgreSQL 15
|
- **Base de Datos**: PostgreSQL 15
|
||||||
- **Containerización**: Docker, Docker Compose
|
- **Infraestructura**: Docker, Nginx (Proxy Inverso)
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
FROM node:20-alpine
|
FROM node:20-alpine
|
||||||
|
|
||||||
# Build argument for API URL
|
# Build arguments
|
||||||
ARG NEXT_PUBLIC_API_URL=http://localhost:4000
|
ARG NEXT_PUBLIC_API_URL=http://localhost:4000
|
||||||
|
ARG NEXT_PUBLIC_ADMIN_PASSWORD=admin123
|
||||||
|
|
||||||
|
# Make args available as env vars during build
|
||||||
|
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||||
|
ENV NEXT_PUBLIC_ADMIN_PASSWORD=$NEXT_PUBLIC_ADMIN_PASSWORD
|
||||||
|
|
||||||
# Create app directory
|
# Create app directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "resistencia-client",
|
"name": "resistencia-client",
|
||||||
"version": "1.1.2",
|
"version": "1.3.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { motion, AnimatePresence } from 'framer-motion';
|
|||||||
import { useSocket } from '../../hooks/useSocket';
|
import { useSocket } from '../../hooks/useSocket';
|
||||||
import { Shield, Users, Gamepad2, LogOut, Clock, History, UserMinus, Key, ChevronDown } from 'lucide-react';
|
import { Shield, Users, Gamepad2, LogOut, Clock, History, UserMinus, Key, ChevronDown } from 'lucide-react';
|
||||||
|
|
||||||
const ADMIN_PASSWORD = "admin123";
|
const ADMIN_PASSWORD = process.env.NEXT_PUBLIC_ADMIN_PASSWORD || "admin123";
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
const { socket, isConnected } = useSocket();
|
const { socket, isConnected } = useSocket();
|
||||||
@@ -252,7 +252,7 @@ export default function Dashboard() {
|
|||||||
</div>
|
</div>
|
||||||
{game.currentRound > 0 && (
|
{game.currentRound > 0 && (
|
||||||
<div className="bg-white/10 px-3 py-1 rounded text-[10px] font-black uppercase tracking-widest border border-white/10">
|
<div className="bg-white/10 px-3 py-1 rounded text-[10px] font-black uppercase tracking-widest border border-white/10">
|
||||||
Ronda {game.currentRound}
|
{game.matchNumber > 1 ? `P${game.matchNumber} - R${game.currentRound}` : `Ronda ${game.currentRound}`}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<ChevronDown
|
<ChevronDown
|
||||||
@@ -388,24 +388,26 @@ export default function Dashboard() {
|
|||||||
<span>AGENTES:</span>
|
<span>AGENTES:</span>
|
||||||
<span className="text-gray-300">{entry.players.split(',').length}</span>
|
<span className="text-gray-300">{entry.players.split(',').length}</span>
|
||||||
</div>
|
</div>
|
||||||
{entry.rounds_played > 0 && (
|
{entry.matches_played > 0 && (
|
||||||
<>
|
<>
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span>RONDAS:</span>
|
<span>PARTIDAS:</span>
|
||||||
<span className="text-gray-300">{entry.rounds_played}</span>
|
<span className="text-gray-300">{entry.matches_played}</span>
|
||||||
</div>
|
</div>
|
||||||
|
{entry.match_results && entry.match_results.length > 0 && (
|
||||||
<div className="flex justify-between items-center pt-2">
|
<div className="flex justify-between items-center pt-2">
|
||||||
<span>RESULTADOS:</span>
|
<span>RESULTADOS:</span>
|
||||||
<div className="flex gap-1">
|
<div className="flex gap-1">
|
||||||
{entry.round_results && entry.round_results.split(',').map((res: string, idx: number) => (
|
{entry.match_results.split(',').map((res: string, idx: number) => (
|
||||||
<div
|
<div
|
||||||
key={idx}
|
key={idx}
|
||||||
className={`w-3 h-3 rounded-full ${res === 'true' ? 'bg-blue-500' : 'bg-red-500'}`}
|
className={`w-3 h-3 rounded-full ${res === 'aliados' ? 'bg-blue-500' : 'bg-red-500'}`}
|
||||||
title={res === 'true' ? 'Victoria Resistencia' : 'Victoria Espías'}
|
title={res === 'aliados' ? 'Victoria Aliados' : 'Victoria Nazis'}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{entry.players && (
|
{entry.players && (
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { motion, AnimatePresence } from 'framer-motion';
|
|||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import GameBoard from '../components/GameBoard';
|
import GameBoard from '../components/GameBoard';
|
||||||
import LogoutButton from '../components/LogoutButton';
|
import LogoutButton from '../components/LogoutButton';
|
||||||
|
import HelpModal from '../components/HelpModal';
|
||||||
import { GameRoom } from '../../../shared/types';
|
import { GameRoom } from '../../../shared/types';
|
||||||
|
|
||||||
// Constantes de apellidos
|
// Constantes de apellidos
|
||||||
@@ -34,6 +35,7 @@ export default function Home() {
|
|||||||
// UI Create/Join
|
// UI Create/Join
|
||||||
const [showCreateModal, setShowCreateModal] = useState(false);
|
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||||
const [createConfig, setCreateConfig] = useState({ maxPlayers: 5, password: '' });
|
const [createConfig, setCreateConfig] = useState({ maxPlayers: 5, password: '' });
|
||||||
|
const [showHelp, setShowHelp] = useState(false);
|
||||||
|
|
||||||
const [passwordPromptRoomId, setPasswordPromptRoomId] = useState<string | null>(null);
|
const [passwordPromptRoomId, setPasswordPromptRoomId] = useState<string | null>(null);
|
||||||
const [joinPassword, setJoinPassword] = useState('');
|
const [joinPassword, setJoinPassword] = useState('');
|
||||||
@@ -244,10 +246,24 @@ export default function Home() {
|
|||||||
</div>
|
</div>
|
||||||
{view === 'lobby' && (
|
{view === 'lobby' && (
|
||||||
<div className="flex items-center gap-3 bg-black/50 px-4 py-2 rounded border border-white/10">
|
<div className="flex items-center gap-3 bg-black/50 px-4 py-2 rounded border border-white/10">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col text-right">
|
||||||
<span className="text-xs text-gray-400">AGENTE:</span>
|
<span className="text-[10px] text-gray-400 uppercase tracking-wider">AGENTE</span>
|
||||||
<span className="font-bold text-yellow-500">{fullPlayerName}</span>
|
<span className="font-bold text-yellow-500 text-sm">{fullPlayerName}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Help Button */}
|
||||||
|
<motion.button
|
||||||
|
onClick={() => setShowHelp(true)}
|
||||||
|
whileHover={{ scale: 1.05 }}
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
className="bg-blue-900/80 hover:bg-blue-800 text-white p-2 rounded-full border border-blue-700/50 backdrop-blur-sm shadow-lg transition-all"
|
||||||
|
title="Ayuda / Reglas"
|
||||||
|
>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2.5} stroke="currentColor" className="w-5 h-5">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M12 17.25h.007v.008H12v-.008z" />
|
||||||
|
</svg>
|
||||||
|
</motion.button>
|
||||||
|
|
||||||
<LogoutButton onClick={handleLogout} />
|
<LogoutButton onClick={handleLogout} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -298,7 +314,7 @@ export default function Home() {
|
|||||||
initial={{ opacity: 0 }}
|
initial={{ opacity: 0 }}
|
||||||
animate={{ opacity: 1 }}
|
animate={{ opacity: 1 }}
|
||||||
exit={{ opacity: 0 }}
|
exit={{ opacity: 0 }}
|
||||||
className="w-full max-w-5xl"
|
className="w-full max-w-5xl h-full flex flex-col max-h-[75vh]"
|
||||||
>
|
>
|
||||||
<div className="flex justify-between items-end mb-6 border-b border-white/20 pb-4">
|
<div className="flex justify-between items-end mb-6 border-b border-white/20 pb-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -313,6 +329,7 @@ export default function Home() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto pr-2 min-h-0">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
{roomsList.length === 0 ? (
|
{roomsList.length === 0 ? (
|
||||||
<div className="col-span-full py-20 text-center text-gray-500 bg-black/30 rounded border border-white/5 border-dashed">
|
<div className="col-span-full py-20 text-center text-gray-500 bg-black/30 rounded border border-white/5 border-dashed">
|
||||||
@@ -371,6 +388,7 @@ export default function Home() {
|
|||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
@@ -451,6 +469,9 @@ export default function Home() {
|
|||||||
<div className="absolute bottom-2 right-4 text-[10px] text-gray-600 font-mono">
|
<div className="absolute bottom-2 right-4 text-[10px] text-gray-600 font-mono">
|
||||||
{isConnected ? <span className="text-green-900">● CONEXIÓN SEGURA</span> : <span className="text-red-900">● BUSCANDO SEÑAL...</span>}
|
{isConnected ? <span className="text-green-900">● CONEXIÓN SEGURA</span> : <span className="text-red-900">● BUSCANDO SEÑAL...</span>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Modal de Ayuda */}
|
||||||
|
<HelpModal isOpen={showHelp} onClose={() => setShowHelp(false)} />
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
174
client/src/components/HelpModal.tsx
Normal file
174
client/src/components/HelpModal.tsx
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
import { motion, AnimatePresence } from 'framer-motion';
|
||||||
|
import Image from 'next/image';
|
||||||
|
|
||||||
|
interface HelpModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function HelpModal({ isOpen, onClose }: HelpModalProps) {
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnimatePresence>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
initial={{ scale: 0.9, y: 20 }}
|
||||||
|
animate={{ scale: 1, y: 0 }}
|
||||||
|
exit={{ scale: 0.9, y: 20 }}
|
||||||
|
className="relative w-full max-w-4xl max-h-[90vh] bg-[#1a1a1a] rounded-lg border-2 border-[#8b7355] shadow-2xl overflow-hidden flex flex-col"
|
||||||
|
onClick={e => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{/* Header estilo Carpeta Confidencial */}
|
||||||
|
<div className="bg-[#2d2d2d] p-4 border-b border-[#8b7355] flex justify-between items-center bg-[url('/assets/images/ui/paper_texture_dark.png')]">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="bg-red-900 text-white text-xs font-bold px-2 py-1 uppercase tracking-widest border border-red-700">
|
||||||
|
Top Secret
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl md:text-2xl font-bold text-[#d4b483] uppercase tracking-wider font-mono">
|
||||||
|
Dossier de Misión
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="text-[#8b7355] hover:text-[#d4b483] transition-colors"
|
||||||
|
>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Contenido Scrollable */}
|
||||||
|
<div className="flex-1 overflow-y-auto p-6 md:p-8 space-y-8 text-gray-300 font-serif leading-relaxed custom-scrollbar">
|
||||||
|
|
||||||
|
{/* 1. INTRODUCCIÓN */}
|
||||||
|
<section>
|
||||||
|
<h3 className="text-xl font-bold text-yellow-500 mb-3 uppercase tracking-widest border-b border-white/10 pb-2 font-mono">
|
||||||
|
1. Objetivo del Juego
|
||||||
|
</h3>
|
||||||
|
<p className="mb-4">
|
||||||
|
<strong className="text-blue-400">La Resistencia</strong> debe completar con éxito <strong>3 misiones</strong>.
|
||||||
|
<br />
|
||||||
|
<strong className="text-red-400">Los Espías</strong> deben sabotear <strong>3 misiones</strong> o asesinar al líder de la Resistencia (Marlene) al final del juego.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* 2. ROLES */}
|
||||||
|
<section>
|
||||||
|
<h3 className="text-xl font-bold text-yellow-500 mb-4 uppercase tracking-widest border-b border-white/10 pb-2 font-mono">
|
||||||
|
2. Identidades Ocultas
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="grid md:grid-cols-2 gap-6">
|
||||||
|
<div className="bg-blue-900/10 p-4 rounded border border-blue-500/20">
|
||||||
|
<h4 className="font-bold text-blue-400 mb-2 flex items-center gap-2">
|
||||||
|
🔵 LA RESISTENCIA (Aliados)
|
||||||
|
</h4>
|
||||||
|
<ul className="space-y-3 text-sm">
|
||||||
|
<li>
|
||||||
|
<strong className="text-white">Marlene:</strong> Conoce la identidad de los Espías, pero debe permanecer oculta. Si los espías la descubren al final, la Resistencia pierde.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong className="text-white">Partisanos:</strong> Miembros leales. No tienen información privilegiada.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-red-900/10 p-4 rounded border border-red-500/20">
|
||||||
|
<h4 className="font-bold text-red-500 mb-2 flex items-center gap-2">
|
||||||
|
🔴 EL EJE (Espías)
|
||||||
|
</h4>
|
||||||
|
<ul className="space-y-3 text-sm">
|
||||||
|
<li>
|
||||||
|
<strong className="text-white">Francotirador (Asesino):</strong> Si la Resistencia gana las 3 misiones, tiene una "bala de plata" para matar a Marlene e invertir la victoria.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong className="text-white">Colaboracionista:</strong> Espía estándar. Conoce a sus compañeros.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* 3. MECÁNICA DE JUEGO */}
|
||||||
|
<section>
|
||||||
|
<h3 className="text-xl font-bold text-yellow-500 mb-4 uppercase tracking-widest border-b border-white/10 pb-2 font-mono">
|
||||||
|
3. Desarrollo de la Partida
|
||||||
|
</h3>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h4 className="font-bold text-white mb-1">A. Asignación de Líder</h4>
|
||||||
|
<p className="text-sm">El liderazgo rota en sentido horario cada ronda. El Líder propone un equipo para la misión.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h4 className="font-bold text-white mb-1">B. Construcción de Equipo</h4>
|
||||||
|
<p className="text-sm">El Líder selecciona a los jugadores que irán a la misión. El número de jugadores requeridos varía según la ronda y el total de jugadores.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h4 className="font-bold text-white mb-1">C. Votación de Equipo</h4>
|
||||||
|
<p className="text-sm pb-2">Todos los jugadores discuten y votan públicamente si aprueban o rechazan al líder propuesto.</p>
|
||||||
|
<ul className="list-disc list-inside text-sm text-gray-400 pl-4">
|
||||||
|
<li>Si la mayoría aprueba, la misión procede.</li>
|
||||||
|
<li>Si se rechaza (o hay empate), el liderazgo pasa al siguiente jugador.</li>
|
||||||
|
<li><strong className="text-red-400">ATENCIÓN:</strong> Si se rechazan 5 equipos consecutivos en una misma ronda, los Espías ganan automáticamente la partida.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h4 className="font-bold text-white mb-1">D. Ejecución de la Misión</h4>
|
||||||
|
<p className="text-sm pb-2">Los miembros del equipo votan en secreto usándo cartas de "ÉXITO" o "SABOTAJE".</p>
|
||||||
|
<ul className="list-disc list-inside text-sm text-gray-400 pl-4">
|
||||||
|
<li><strong className="text-blue-400">La Resistencia</strong> SOLO puede votar ÉXITO.</li>
|
||||||
|
<li><strong className="text-red-400">Los Espías</strong> pueden elegir entre ÉXITO (para disimular) o SABOTAJE.</li>
|
||||||
|
<li>Las cartas se barajan y se revelan. <strong>Un solo voto de SABOTAJE hace fracasar la misión</strong>.</li>
|
||||||
|
<li><em className="text-yellow-500 text-xs">Excepción: En partidas de 7+ jugadores, la 4ª misión requiere 2 sabotajes para fallar.</em></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* 4. FINAL */}
|
||||||
|
<section>
|
||||||
|
<h3 className="text-xl font-bold text-yellow-500 mb-3 uppercase tracking-widest border-b border-white/10 pb-2 font-mono">
|
||||||
|
4. Final de Partida
|
||||||
|
</h3>
|
||||||
|
<p className="mb-2">
|
||||||
|
Si hay <strong>3 misiones fallidas</strong>: <span className="text-red-500 font-bold">VICTORIA DEL EJE</span>.
|
||||||
|
</p>
|
||||||
|
<p className="mb-4">
|
||||||
|
Si hay <strong>3 misiones exitosas</strong>: Comienza la <span className="text-red-500 font-bold">FASE DE ASESINATO</span>.
|
||||||
|
</p>
|
||||||
|
<div className="bg-zinc-800 p-4 rounded border-l-4 border-red-600">
|
||||||
|
<h4 className="font-bold text-white uppercase mb-1">El Disparo Final</h4>
|
||||||
|
<p className="text-sm text-gray-300">
|
||||||
|
El Francotirador revela su identidad y tiene una oportunidad para adivinar quién es <strong>Marlene</strong>.
|
||||||
|
Si acierta, asesina a Marlene y los Espías roban la victoria. Si falla, la Resistencia gana definitivamente.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Footer / Botón Cerrar */}
|
||||||
|
<div className="p-4 bg-[#2d2d2d] border-t border-[#8b7355] flex justify-end">
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="bg-[#8b7355] hover:bg-[#a68b66] text-black font-bold py-2 px-6 rounded shadow-lg uppercase tracking-wider transition-all"
|
||||||
|
>
|
||||||
|
Comprendido
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
</motion.div>
|
||||||
|
</AnimatePresence>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { motion } from 'framer-motion';
|
import { motion } from 'framer-motion';
|
||||||
import { useEffect } from 'react';
|
import { useEffect, useMemo } from 'react';
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
|
|
||||||
interface MissionRevealProps {
|
interface MissionRevealProps {
|
||||||
@@ -8,6 +8,16 @@ interface MissionRevealProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function MissionReveal({ votes, onFinished }: MissionRevealProps) {
|
export default function MissionReveal({ votes, onFinished }: MissionRevealProps) {
|
||||||
|
// Barajar votos de forma aleatoria en cada cliente (orden diferente para cada jugador)
|
||||||
|
const shuffledVotes = useMemo(() => {
|
||||||
|
const shuffled = [...votes];
|
||||||
|
for (let i = shuffled.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||||
|
}
|
||||||
|
return shuffled;
|
||||||
|
}, [votes]);
|
||||||
|
|
||||||
// Timer de seguridad: 5 segundos y avanza
|
// Timer de seguridad: 5 segundos y avanza
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
@@ -28,7 +38,7 @@ export default function MissionReveal({ votes, onFinished }: MissionRevealProps)
|
|||||||
</h2>
|
</h2>
|
||||||
|
|
||||||
<div className="flex gap-4 justify-center mb-12 flex-wrap max-w-[90vw]">
|
<div className="flex gap-4 justify-center mb-12 flex-wrap max-w-[90vw]">
|
||||||
{votes.map((vote, idx) => (
|
{shuffledVotes.map((vote, idx) => (
|
||||||
<motion.div
|
<motion.div
|
||||||
key={idx}
|
key={idx}
|
||||||
className="w-32 h-48 rounded-xl flex items-center justify-center shadow-2xl relative overflow-hidden"
|
className="w-32 h-48 rounded-xl flex items-center justify-center shadow-2xl relative overflow-hidden"
|
||||||
@@ -55,7 +65,7 @@ export default function MissionReveal({ votes, onFinished }: MissionRevealProps)
|
|||||||
className="text-white text-xl font-mono mt-8 text-center"
|
className="text-white text-xl font-mono mt-8 text-center"
|
||||||
initial={{ opacity: 0 }}
|
initial={{ opacity: 0 }}
|
||||||
animate={{ opacity: 1 }}
|
animate={{ opacity: 1 }}
|
||||||
transition={{ delay: votes.length * 0.3 + 0.5 }}
|
transition={{ delay: shuffledVotes.length * 0.3 + 0.5 }}
|
||||||
>
|
>
|
||||||
<span className="animate-pulse">Analizando resultado estratégico...</span>
|
<span className="animate-pulse">Analizando resultado estratégico...</span>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ services:
|
|||||||
dockerfile: client/Dockerfile
|
dockerfile: client/Dockerfile
|
||||||
args:
|
args:
|
||||||
- NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL:-https://api.franciaocupada.martivich.es}
|
- NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL:-https://api.franciaocupada.martivich.es}
|
||||||
|
- NEXT_PUBLIC_ADMIN_PASSWORD=${NEXT_PUBLIC_ADMIN_PASSWORD:-admin123}
|
||||||
ports:
|
ports:
|
||||||
- "3000:3000"
|
- "3000:3000"
|
||||||
volumes:
|
volumes:
|
||||||
@@ -15,6 +16,7 @@ services:
|
|||||||
- /app/client/node_modules
|
- /app/client/node_modules
|
||||||
environment:
|
environment:
|
||||||
- NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL:-https://api.franciaocupada.martivich.es}
|
- NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL:-https://api.franciaocupada.martivich.es}
|
||||||
|
- NEXT_PUBLIC_ADMIN_PASSWORD=${NEXT_PUBLIC_ADMIN_PASSWORD:-admin123}
|
||||||
depends_on:
|
depends_on:
|
||||||
- server
|
- server
|
||||||
networks:
|
networks:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "resistencia-server",
|
"name": "resistencia-server",
|
||||||
"version": "1.1.2",
|
"version": "1.3.0",
|
||||||
"description": "Backend para el juego La Resistencia",
|
"description": "Backend para el juego La Resistencia",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -30,7 +30,9 @@ export const initDb = async () => {
|
|||||||
await client.query(`
|
await client.query(`
|
||||||
ALTER TABLE game_logs
|
ALTER TABLE game_logs
|
||||||
ADD COLUMN IF NOT EXISTS rounds_played INTEGER DEFAULT 0,
|
ADD COLUMN IF NOT EXISTS rounds_played INTEGER DEFAULT 0,
|
||||||
ADD COLUMN IF NOT EXISTS round_results TEXT DEFAULT '';
|
ADD COLUMN IF NOT EXISTS round_results TEXT DEFAULT '',
|
||||||
|
ADD COLUMN IF NOT EXISTS matches_played INTEGER DEFAULT 1,
|
||||||
|
ADD COLUMN IF NOT EXISTS match_results TEXT DEFAULT '';
|
||||||
`);
|
`);
|
||||||
|
|
||||||
console.log('[DB] Base de datos inicializada correctamente');
|
console.log('[DB] Base de datos inicializada correctamente');
|
||||||
@@ -71,15 +73,19 @@ export const logGameEnd = async (
|
|||||||
winner: string | null = null,
|
winner: string | null = null,
|
||||||
aborted: boolean = false,
|
aborted: boolean = false,
|
||||||
roundsPlayed: number = 0,
|
roundsPlayed: number = 0,
|
||||||
roundResults: boolean[] = []
|
roundResults: boolean[] = [],
|
||||||
|
matchesPlayed: number = 1,
|
||||||
|
matchResults: string[] = []
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
// Convert boolean[] to string "true,false,true" or simplified "W,L,W"
|
// Convert boolean[] to string "true,false,true"
|
||||||
const resultsStr = roundResults.join(',');
|
const roundResultsStr = roundResults.map(r => r === true ? 'true' : r === false ? 'false' : '').filter(r => r).join(',');
|
||||||
|
// matchResults is already string[] like ["aliados", "alemanes"]
|
||||||
|
const matchResultsStr = matchResults.join(',');
|
||||||
|
|
||||||
await pool.query(
|
await pool.query(
|
||||||
'UPDATE game_logs SET finished_at = CURRENT_TIMESTAMP, winner = $1, status = $2, rounds_played = $3, round_results = $4 WHERE room_id = $5 AND status = $6',
|
'UPDATE game_logs SET finished_at = CURRENT_TIMESTAMP, winner = $1, status = $2, rounds_played = $3, round_results = $4, matches_played = $5, match_results = $6 WHERE room_id = $7 AND status = $8',
|
||||||
[winner, aborted ? 'aborted' : 'finished', roundsPlayed, resultsStr, roomId, 'active']
|
[winner, aborted ? 'aborted' : 'finished', roundsPlayed, roundResultsStr, matchesPlayed, matchResultsStr, roomId, 'active']
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[DB] Error al registrar fin de partida:', err);
|
console.error('[DB] Error al registrar fin de partida:', err);
|
||||||
|
|||||||
@@ -91,6 +91,7 @@ const getAdminData = async () => {
|
|||||||
currentPlayers: g.state.players.length,
|
currentPlayers: g.state.players.length,
|
||||||
maxPlayers: g.maxPlayers,
|
maxPlayers: g.maxPlayers,
|
||||||
currentRound: g.state.currentRound,
|
currentRound: g.state.currentRound,
|
||||||
|
matchNumber: g.state.matchNumber,
|
||||||
players: g.state.players.map(p => ({ id: p.id, name: p.name }))
|
players: g.state.players.map(p => ({ id: p.id, name: p.name }))
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -348,8 +349,10 @@ io.on('connection', (socket) => {
|
|||||||
// Desconectar a todos los jugadores de la sala
|
// Desconectar a todos los jugadores de la sala
|
||||||
io.in(roomId).socketsLeave(roomId);
|
io.in(roomId).socketsLeave(roomId);
|
||||||
|
|
||||||
// LOG EN DB
|
// LOG EN DB - Incluir resultado de la partida actual en matchResults
|
||||||
logGameEnd(roomId, game.state.winner, false, game.state.currentRound, game.state.questResults);
|
const finalMatchResults = [...game.state.matchResults];
|
||||||
|
if (game.state.winner) finalMatchResults.push(game.state.winner);
|
||||||
|
logGameEnd(roomId, game.state.winner, false, game.state.currentRound, game.state.questResults, game.state.matchNumber, finalMatchResults);
|
||||||
broadcastAdminUpdate();
|
broadcastAdminUpdate();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -382,7 +385,9 @@ io.on('connection', (socket) => {
|
|||||||
io.in(roomId).socketsLeave(roomId);
|
io.in(roomId).socketsLeave(roomId);
|
||||||
|
|
||||||
// LOG EN DB COMO ABORTADA
|
// LOG EN DB COMO ABORTADA
|
||||||
logGameEnd(roomId, null, true, game.state.currentRound, game.state.questResults);
|
const finalMatchResults = [...game.state.matchResults];
|
||||||
|
if (game.state.winner) finalMatchResults.push(game.state.winner);
|
||||||
|
logGameEnd(roomId, null, true, game.state.currentRound, game.state.questResults, game.state.matchNumber, finalMatchResults);
|
||||||
broadcastAdminUpdate();
|
broadcastAdminUpdate();
|
||||||
|
|
||||||
console.log(`[LEAVE_GAME] ${playerName} abandonó la partida ${roomId}. Partida eliminada.`);
|
console.log(`[LEAVE_GAME] ${playerName} abandonó la partida ${roomId}. Partida eliminada.`);
|
||||||
@@ -400,8 +405,8 @@ io.on('connection', (socket) => {
|
|||||||
const existingPlayer = game.state.players.find(p => p.name === playerName);
|
const existingPlayer = game.state.players.find(p => p.name === playerName);
|
||||||
|
|
||||||
if (existingPlayer) {
|
if (existingPlayer) {
|
||||||
// Actualizar el socket ID del jugador
|
// Actualizar el socket ID del jugador y referencias
|
||||||
existingPlayer.id = socket.id;
|
game.updatePlayerSocket(existingPlayer.id, socket.id);
|
||||||
|
|
||||||
// Unir al socket a la sala
|
// Unir al socket a la sala
|
||||||
socket.join(roomId);
|
socket.join(roomId);
|
||||||
@@ -470,7 +475,9 @@ io.on('connection', (socket) => {
|
|||||||
io.in(roomId).socketsLeave(roomId);
|
io.in(roomId).socketsLeave(roomId);
|
||||||
|
|
||||||
// Log como abortada por admin
|
// Log como abortada por admin
|
||||||
await logGameEnd(roomId, null, true, game.state.currentRound, game.state.questResults);
|
const finalMatchResults = [...game.state.matchResults];
|
||||||
|
if (game.state.winner) finalMatchResults.push(game.state.winner);
|
||||||
|
await logGameEnd(roomId, null, true, game.state.currentRound, game.state.questResults, game.state.matchNumber, finalMatchResults);
|
||||||
socket.emit('admin_action_success');
|
socket.emit('admin_action_success');
|
||||||
broadcastAdminUpdate();
|
broadcastAdminUpdate();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,9 @@ export class Game {
|
|||||||
missionHistory: [],
|
missionHistory: [],
|
||||||
revealedVotes: [],
|
revealedVotes: [],
|
||||||
history: [],
|
history: [],
|
||||||
hostId: hostId
|
hostId: hostId,
|
||||||
|
matchNumber: 1,
|
||||||
|
matchResults: []
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,7 +371,13 @@ export class Game {
|
|||||||
restartGame() {
|
restartGame() {
|
||||||
this.log('=== REINICIANDO PARTIDA ===');
|
this.log('=== REINICIANDO PARTIDA ===');
|
||||||
|
|
||||||
// Resetear variables de juego
|
// Guardar resultado de la partida actual antes de resetear
|
||||||
|
if (this.state.winner) {
|
||||||
|
this.state.matchResults.push(this.state.winner);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Incrementar contador de partidas y resetear variables de juego
|
||||||
|
this.state.matchNumber++;
|
||||||
this.state.currentRound = 1;
|
this.state.currentRound = 1;
|
||||||
this.state.failedVotesCount = 0;
|
this.state.failedVotesCount = 0;
|
||||||
this.state.questResults = [null, null, null, null, null];
|
this.state.questResults = [null, null, null, null, null];
|
||||||
@@ -407,4 +415,44 @@ export class Game {
|
|||||||
// Mantener solo los últimos 50 mensajes
|
// Mantener solo los últimos 50 mensajes
|
||||||
if (this.state.history.length > 50) this.state.history.shift();
|
if (this.state.history.length > 50) this.state.history.shift();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
updatePlayerSocket(oldId: string, newId: string) {
|
||||||
|
const player = this.state.players.find(p => p.id === oldId);
|
||||||
|
if (!player) return;
|
||||||
|
|
||||||
|
// Actualizar ID del jugador
|
||||||
|
player.id = newId;
|
||||||
|
|
||||||
|
// Actualizar referencias en el estado
|
||||||
|
|
||||||
|
// 1. Host
|
||||||
|
if (this.hostId === oldId) {
|
||||||
|
this.hostId = newId;
|
||||||
|
this.state.hostId = newId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Líder actual
|
||||||
|
if (this.state.currentLeaderId === oldId) {
|
||||||
|
this.state.currentLeaderId = newId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Votos de Líder (leaderVotes)
|
||||||
|
if (this.state.leaderVotes && this.state.leaderVotes[oldId] !== undefined) {
|
||||||
|
this.state.leaderVotes[newId] = this.state.leaderVotes[oldId];
|
||||||
|
delete this.state.leaderVotes[oldId];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Votos de Equipo (teamVotes)
|
||||||
|
if (this.state.teamVotes && this.state.teamVotes[oldId] !== undefined) {
|
||||||
|
this.state.teamVotes[newId] = this.state.teamVotes[oldId];
|
||||||
|
delete this.state.teamVotes[oldId];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Equipo Propuesto (proposedTeam)
|
||||||
|
if (this.state.proposedTeam && this.state.proposedTeam.includes(oldId)) {
|
||||||
|
this.state.proposedTeam = this.state.proposedTeam.map(id => id === oldId ? newId : id);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.log(`Jugador ${player.name} reconectado. ID actualizado.`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -89,6 +89,8 @@ export interface GameState {
|
|||||||
|
|
||||||
winner?: Faction;
|
winner?: Faction;
|
||||||
history: string[]; // Log de acciones para mostrar en pantalla
|
history: string[]; // Log de acciones para mostrar en pantalla
|
||||||
|
matchNumber: number; // Número de partida en esta operación (se incrementa con cada restart)
|
||||||
|
matchResults: Faction[]; // Resultados de cada partida (quién ganó)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Configuración de jugadores por partida (según tus reglas)
|
// Configuración de jugadores por partida (según tus reglas)
|
||||||
|
|||||||
Reference in New Issue
Block a user