Compare commits
32 Commits
checkpoint
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be15983455 | ||
|
|
94d1ffbf56 | ||
|
|
c8bad3ea73 | ||
|
|
4e601cdd6f | ||
|
|
385f87cce0 | ||
|
|
bb08fa9437 | ||
|
|
c2f1bbf4d4 | ||
|
|
e1c08f775e | ||
|
|
1422e0fb1d | ||
|
|
fc6bc1ab54 | ||
|
|
404d35f732 | ||
|
|
fd23cae2ff | ||
|
|
134460a972 | ||
|
|
7c9ff5308f | ||
|
|
0211dfb68b | ||
|
|
609033b835 | ||
|
|
273a228a1c | ||
|
|
84642bc2a9 | ||
|
|
ecb15c27f4 | ||
|
|
13d56c2431 | ||
|
|
c67f97845a | ||
|
|
1a7b667c77 | ||
|
|
59d2dd56bc | ||
|
|
6e65152648 | ||
|
|
f09e14f99a | ||
|
|
31067bc168 | ||
|
|
6a6cf7628b | ||
|
|
b836c53002 | ||
|
|
774e1b982d | ||
|
|
06d2171871 | ||
|
|
9e0e343868 | ||
|
|
8f95413782 |
85
.gitea/workflows/_deployment.yml
Normal file
@@ -0,0 +1,85 @@
|
||||
name: CI/CD - Francia Ocupada (La Resistencia)
|
||||
run-name: Build & Deploy por ${{ gitea.actor }}
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: [production-ready]
|
||||
|
||||
steps:
|
||||
# PASO 1: Instalar Node.js (requerido por las acciones de GitHub)
|
||||
- name: 📦 Instalar Node.js
|
||||
shell: bash
|
||||
run: |
|
||||
echo "Verificando si Node.js está instalado..."
|
||||
if ! command -v node &> /dev/null; then
|
||||
echo "Node.js no encontrado, instalando..."
|
||||
|
||||
if [ -f /etc/debian_version ]; then
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt-get install -y nodejs
|
||||
elif [ -f /etc/alpine-release ]; then
|
||||
apk add --no-cache nodejs npm
|
||||
else
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
|
||||
export NVM_DIR="$HOME/.nvm"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
||||
nvm install 20
|
||||
fi
|
||||
else
|
||||
echo "Node.js ya está instalado: $(node --version)"
|
||||
fi
|
||||
|
||||
node --version
|
||||
npm --version
|
||||
|
||||
# PASO 2: Checkout del Código
|
||||
- name: 🚀 Checkout del Código
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# PASO 3: Ejecutar script de deployment en el host
|
||||
- name: 🎯 Ejecutar Deployment
|
||||
shell: bash
|
||||
run: |
|
||||
echo "🚀 Ejecutando script de deployment en el host..."
|
||||
|
||||
PROJECT_DIR="/home/marti/Documentos/Gitea/resistencia"
|
||||
|
||||
echo "📂 Directorio del proyecto: $PROJECT_DIR"
|
||||
|
||||
# Ir al directorio del proyecto y ejecutar deployment
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
# Asegurarse de que el script es ejecutable
|
||||
chmod +x deploy.sh
|
||||
|
||||
# Ejecutar el script de deployment
|
||||
# El script hará git pull para obtener los últimos cambios
|
||||
./deploy.sh
|
||||
|
||||
# PASO 4: Verificación Final
|
||||
- name: ✅ Verificación Final
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
PROJECT_DIR="/home/marti/Documentos/Gitea/resistencia"
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
echo "📊 Estado final de los contenedores:"
|
||||
docker compose -f docker-compose_prod.yml ps || echo "No se pudo verificar el estado"
|
||||
|
||||
echo ""
|
||||
echo "🌐 URLs de la aplicación:"
|
||||
echo " - Frontend: https://franciaocupada.martivich.es"
|
||||
echo " - API: https://api.franciaocupada.martivich.es"
|
||||
3
.gitignore
vendored
@@ -5,3 +5,6 @@ dist/
|
||||
.env
|
||||
.DS_Store
|
||||
postgres_data/
|
||||
|
||||
# Credenciales
|
||||
GiteaToken.txt
|
||||
|
||||
54
CHANGELOG.md
@@ -1,5 +1,59 @@
|
||||
# Notas de Versión
|
||||
|
||||
## v0.2.0-complete-ui (2025-12-13)
|
||||
|
||||
### 🎉 Juego Completamente Funcional
|
||||
|
||||
Esta versión marca la **finalización de todas las fases del juego**, incluyendo las pantallas de resultado de misión, histórico y victoria.
|
||||
|
||||
### ✅ Nuevas Funcionalidades
|
||||
|
||||
#### UI de Fases Finales
|
||||
- ✅ **MISSION_REVEAL**: Animación de cartas revelándose una a una
|
||||
- ✅ **MISSION_RESULT**: Pantalla con mapa táctico mostrando tokens de victoria/fracaso
|
||||
- ✅ **Histórico de Misiones**: Círculos clicables en esquina superior derecha
|
||||
- ✅ **Mapa Táctico**: Tablero `board_map.jpg` con tokens posicionados sobre hexágonos
|
||||
- ✅ **Pantallas de Victoria**: Fondos específicos para victoria Aliados/Nazis
|
||||
- ✅ **ASSASSIN_PHASE**: Fase de francotirador completamente funcional
|
||||
|
||||
#### Mejoras de UI (2025-12-13)
|
||||
- ✅ Timer de votación reposicionado a esquina superior izquierda (fixed, 20px margen)
|
||||
- ✅ Cartas de votación de líder redimensionadas a cuadradas (32x32)
|
||||
- ✅ Eliminado contador de votos rechazados en resultado de misión
|
||||
- ✅ Mapa táctico permanece visible durante toda la fase MISSION_RESULT
|
||||
- ✅ Tokens de victoria/fracaso posicionados en el mapa
|
||||
- ✅ Título de intro cambiado a "Traidores en París"
|
||||
|
||||
### 🎨 Assets Añadidos
|
||||
- Nuevas imágenes de misiones cuadradas en `/missions/quadrades/`
|
||||
- Cartas de votación de líder cuadradas (`accept_leader.jpg`, `deny_leader.jpg`)
|
||||
- Respaldo de imágenes originales en `/missions/original_backup/`
|
||||
|
||||
### 🐛 Correcciones
|
||||
- ✅ Eliminado timeout de 7 segundos que ocultaba el mapa en MISSION_RESULT
|
||||
- ✅ Ajustadas posiciones de tokens en el mapa (tokens 1 y 2 correctos)
|
||||
|
||||
### ⚠️ Pendiente
|
||||
- Ajuste fino de posiciones de tokens 3, 4 y 5 en el mapa táctico
|
||||
|
||||
### 📦 Tecnologías
|
||||
- **Frontend**: Next.js 14, React, TypeScript, Framer Motion, TailwindCSS
|
||||
- **Backend**: Node.js, Express, Socket.IO, TypeScript
|
||||
- **Base de Datos**: PostgreSQL 15
|
||||
- **Containerización**: Docker, Docker Compose
|
||||
|
||||
### 📝 Commits Principales
|
||||
- `13d56c2` - feat: Mejoras UI - Timer, mapa resultado misión y tokens
|
||||
- `ecb15c2` - docs: Actualizar README con estado actual del proyecto
|
||||
|
||||
### 🎯 Próximos Pasos
|
||||
1. Afinar posiciones de tokens 3, 4 y 5 en el mapa
|
||||
2. Testing exhaustivo de todas las fases
|
||||
3. Optimizar rendimiento del servidor
|
||||
4. Ajustes finales según feedback de jugadores
|
||||
|
||||
---
|
||||
|
||||
## v0.1.0-functional-until-mission (2025-12-05)
|
||||
|
||||
### ✅ Funcionalidades Implementadas
|
||||
|
||||
167
CI-CD-README.md
Normal file
@@ -0,0 +1,167 @@
|
||||
# 🚀 CI/CD con Gitea Actions - Francia Ocupada
|
||||
|
||||
## 📋 Configuración Actual
|
||||
|
||||
### Runner Configurado
|
||||
- **Nombre**: `runner-01-ci-vm`
|
||||
- **Etiqueta**: `production-ready:host`
|
||||
- **URL Gitea**: `http://gitea.local:3000`
|
||||
- **Estado**: ✅ Corriendo sin problemas
|
||||
|
||||
### Workflow Creado
|
||||
- **Ubicación**: `.gitea/workflows/deployment.yml`
|
||||
- **Trigger**: Push a `main` o `master`, o ejecución manual
|
||||
- **Acciones**: Build y deploy automático con Docker Compose
|
||||
|
||||
## 🔄 Flujo de Despliegue
|
||||
|
||||
El workflow ejecuta los siguientes pasos:
|
||||
|
||||
1. **🚀 Checkout del Código**: Descarga el código del repositorio
|
||||
2. **⚙️ Configurar Node.js**: Instala Node.js 20 para las acciones
|
||||
3. **🛑 Detener Contenedores Anteriores**: Para y elimina los contenedores existentes
|
||||
4. **🧹 Limpiar Imágenes Antiguas**: Elimina imágenes Docker sin usar
|
||||
5. **🔨 Construir Imágenes Docker**: Construye las imágenes con `docker-compose_prod.yml`
|
||||
6. **📦 Desplegar Aplicación**: Levanta los contenedores en modo producción
|
||||
7. **✅ Verificar Despliegue**: Comprueba que los contenedores están corriendo
|
||||
8. **📋 Mostrar Logs Recientes**: Muestra logs para debugging
|
||||
|
||||
## 🧪 Cómo Hacer Pruebas de Despliegue
|
||||
|
||||
### Opción 1: Push a la rama principal (Automático)
|
||||
|
||||
```bash
|
||||
# Hacer algún cambio en el código
|
||||
echo "# Test CI/CD" >> README.md
|
||||
|
||||
# Commit y push
|
||||
git add .
|
||||
git commit -m "test: Prueba de CI/CD automático"
|
||||
git push origin main # o master, según tu rama principal
|
||||
```
|
||||
|
||||
### Opción 2: Ejecución Manual desde Gitea
|
||||
|
||||
1. Ve a tu repositorio en Gitea: `http://gitea.local:3000/[tu-usuario]/resistencia`
|
||||
2. Navega a la pestaña **Actions**
|
||||
3. Selecciona el workflow **"CI/CD - Francia Ocupada (La Resistencia)"**
|
||||
4. Haz clic en **"Run workflow"**
|
||||
5. Selecciona la rama y confirma
|
||||
|
||||
### Opción 3: Forzar un push vacío (sin cambios)
|
||||
|
||||
```bash
|
||||
# Esto dispara el workflow sin hacer cambios reales
|
||||
git commit --allow-empty -m "test: Trigger CI/CD workflow"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
## 📊 Monitorear el Despliegue
|
||||
|
||||
### Desde Gitea Web UI
|
||||
1. Ve a **Actions** en tu repositorio
|
||||
2. Verás el workflow ejecutándose en tiempo real
|
||||
3. Haz clic en el workflow para ver los logs detallados de cada paso
|
||||
|
||||
### Desde el Servidor (SSH)
|
||||
```bash
|
||||
# Ver estado de los contenedores
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
|
||||
# Ver logs en tiempo real
|
||||
docker compose -f docker-compose_prod.yml logs -f
|
||||
|
||||
# Ver logs de un servicio específico
|
||||
docker compose -f docker-compose_prod.yml logs -f client
|
||||
docker compose -f docker-compose_prod.yml logs -f server
|
||||
docker compose -f docker-compose_prod.yml logs -f db
|
||||
|
||||
# Ver imágenes Docker
|
||||
docker images | grep resistencia
|
||||
```
|
||||
|
||||
## 🔧 Solución de Problemas
|
||||
|
||||
### El workflow falla en el checkout
|
||||
**Problema**: Error de autenticación con Gitea
|
||||
|
||||
**Solución**:
|
||||
- Verifica que el token de registro del runner sea correcto
|
||||
- Asegúrate de que el runner tenga acceso al repositorio
|
||||
|
||||
### El workflow falla en la construcción
|
||||
**Problema**: Error al construir las imágenes Docker
|
||||
|
||||
**Solución**:
|
||||
```bash
|
||||
# En el servidor, construir manualmente para ver el error
|
||||
cd /ruta/al/proyecto
|
||||
docker compose -f docker-compose_prod.yml build --no-cache
|
||||
```
|
||||
|
||||
### Los contenedores no inician
|
||||
**Problema**: Los contenedores se detienen inmediatamente
|
||||
|
||||
**Solución**:
|
||||
```bash
|
||||
# Ver logs de error
|
||||
docker compose -f docker-compose_prod.yml logs
|
||||
|
||||
# Verificar configuración
|
||||
docker compose -f docker-compose_prod.yml config
|
||||
```
|
||||
|
||||
### Puerto ya en uso
|
||||
**Problema**: Los puertos 3000, 4000 o 5432 están ocupados
|
||||
|
||||
**Solución**:
|
||||
```bash
|
||||
# Ver qué está usando los puertos
|
||||
sudo lsof -i :3000
|
||||
sudo lsof -i :4000
|
||||
sudo lsof -i :5432
|
||||
|
||||
# Detener contenedores anteriores
|
||||
docker compose -f docker-compose_prod.yml down
|
||||
```
|
||||
|
||||
## 🎯 Verificación Post-Despliegue
|
||||
|
||||
Después de un despliegue exitoso, verifica:
|
||||
|
||||
1. **Frontend accesible**: https://franciaocupada.martivich.es
|
||||
2. **API accesible**: https://api.franciaocupada.martivich.es
|
||||
3. **Contenedores corriendo**:
|
||||
```bash
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
```
|
||||
Deberías ver 3 contenedores: `client`, `server`, `db`
|
||||
|
||||
4. **Logs sin errores**:
|
||||
```bash
|
||||
docker compose -f docker-compose_prod.yml logs --tail=100
|
||||
```
|
||||
|
||||
## 📝 Notas Importantes
|
||||
|
||||
- **Rama principal**: El workflow se activa en push a `main` o `master`
|
||||
- **Etiqueta del runner**: Debe ser `production-ready` (configurada en tu runner)
|
||||
- **Docker Compose**: Usa `docker-compose_prod.yml` para producción
|
||||
- **Variables de entorno**: Configuradas en `docker-compose_prod.yml`:
|
||||
- `NEXT_PUBLIC_API_URL=https://api.franciaocupada.martivich.es`
|
||||
- `CORS_ORIGIN=https://franciaocupada.martivich.es`
|
||||
|
||||
## 🔐 Seguridad
|
||||
|
||||
- El workflow usa el token de Gitea automáticamente (`${{ gitea.token }}`)
|
||||
- No es necesario configurar secrets adicionales para este workflow básico
|
||||
- Si necesitas secrets (API keys, passwords), agrégalos en:
|
||||
- Gitea → Repositorio → Settings → Secrets
|
||||
|
||||
## 🚀 Próximos Pasos Recomendados
|
||||
|
||||
1. **Pruebas automatizadas**: Agregar tests antes del deploy
|
||||
2. **Notificaciones**: Configurar notificaciones de éxito/fallo
|
||||
3. **Rollback automático**: Implementar rollback si el deploy falla
|
||||
4. **Health checks**: Verificar que la app responde correctamente
|
||||
5. **Backup de DB**: Hacer backup antes de cada deploy
|
||||
176
DEPLOYMENT-SUMMARY.md
Normal file
@@ -0,0 +1,176 @@
|
||||
# 🎯 Resumen de Configuración CI/CD
|
||||
|
||||
## ✅ Lo que hemos hecho
|
||||
|
||||
### 1. Workflow de Gitea Actions
|
||||
- **Archivo**: `.gitea/workflows/deployment.yml`
|
||||
- **Trigger**: Push a `main` o `master`
|
||||
- **Runner**: `production-ready` (tu runner configurado)
|
||||
- **Acciones**:
|
||||
- ✅ Checkout del código
|
||||
- ✅ Configuración de Node.js 20
|
||||
- ✅ Detención de contenedores anteriores
|
||||
- ✅ Limpieza de imágenes antiguas
|
||||
- ✅ Construcción de imágenes Docker
|
||||
- ✅ Despliegue con docker-compose_prod.yml
|
||||
- ✅ Verificación de estado
|
||||
- ✅ Logs de debugging
|
||||
|
||||
### 2. Documentación
|
||||
- **CI-CD-README.md**: Guía completa de uso y troubleshooting
|
||||
- **monitor-deploy.sh**: Script interactivo de monitoreo
|
||||
|
||||
### 3. Commit y Push
|
||||
- ✅ Commit realizado: `273a228`
|
||||
- ✅ Push a origin/main completado
|
||||
- ✅ Workflow debería estar ejecutándose ahora
|
||||
|
||||
## 🚀 Próximos Pasos
|
||||
|
||||
### 1. Verificar que el Workflow se está ejecutando
|
||||
|
||||
Abre tu navegador y ve a:
|
||||
```
|
||||
http://gitea.local:3000/marti/FranciaOcupada/actions
|
||||
```
|
||||
|
||||
Deberías ver el workflow "CI/CD - Francia Ocupada (La Resistencia)" ejecutándose.
|
||||
|
||||
### 2. Monitorear el Despliegue
|
||||
|
||||
Desde tu servidor donde está el runner, ejecuta:
|
||||
```bash
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
./monitor-deploy.sh
|
||||
```
|
||||
|
||||
O manualmente:
|
||||
```bash
|
||||
# Ver estado de contenedores
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
|
||||
# Ver logs en tiempo real
|
||||
docker compose -f docker-compose_prod.yml logs -f
|
||||
```
|
||||
|
||||
### 3. Verificar el Despliegue
|
||||
|
||||
Una vez completado el workflow, verifica:
|
||||
|
||||
**Frontend**: https://franciaocupada.martivich.es
|
||||
**API**: https://api.franciaocupada.martivich.es
|
||||
|
||||
## 🔍 Cómo Saber si Funcionó
|
||||
|
||||
### En Gitea Web UI
|
||||
1. Ve a Actions en tu repositorio
|
||||
2. Busca el workflow más reciente
|
||||
3. Todos los pasos deberían tener un ✅ verde
|
||||
4. El último paso mostrará las URLs de la aplicación
|
||||
|
||||
### En el Servidor
|
||||
```bash
|
||||
# Deberías ver 3 contenedores corriendo
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
|
||||
# Salida esperada:
|
||||
# NAME STATUS PORTS
|
||||
# resistencia-client Up 0.0.0.0:3000->3000/tcp
|
||||
# resistencia-server Up 0.0.0.0:4000->4000/tcp
|
||||
# resistencia-db Up 0.0.0.0:5432->5432/tcp
|
||||
```
|
||||
|
||||
## 🧪 Hacer una Prueba de Despliegue
|
||||
|
||||
### Opción A: Cambio real
|
||||
```bash
|
||||
# Hacer un cambio pequeño
|
||||
echo "# CI/CD Test" >> README.md
|
||||
git add README.md
|
||||
git commit -m "test: Verificación de CI/CD"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
### Opción B: Commit vacío
|
||||
```bash
|
||||
# Trigger sin cambios
|
||||
git commit --allow-empty -m "test: Trigger CI/CD workflow"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
### Opción C: Ejecución manual
|
||||
1. Ve a http://gitea.local:3000/marti/FranciaOcupada/actions
|
||||
2. Click en el workflow
|
||||
3. Click en "Run workflow"
|
||||
4. Selecciona la rama `main`
|
||||
5. Click en "Run"
|
||||
|
||||
## 📊 Diferencias con el Ejemplo Original
|
||||
|
||||
### Tu Proyecto vs HolaMundo
|
||||
|
||||
| Aspecto | HolaMundo | Francia Ocupada |
|
||||
|---------|-----------|-----------------|
|
||||
| **Imagen** | Una sola imagen | 3 servicios (client, server, db) |
|
||||
| **Herramienta** | `docker build` | `docker compose` |
|
||||
| **Config** | Dockerfile simple | docker-compose_prod.yml |
|
||||
| **Puerto** | 8080 | 3000 (client), 4000 (server) |
|
||||
| **Complejidad** | Baja | Media-Alta |
|
||||
|
||||
### Adaptaciones Realizadas
|
||||
|
||||
1. **Docker Compose en lugar de Docker directo**
|
||||
- Usamos `docker compose -f docker-compose_prod.yml` en todos los pasos
|
||||
|
||||
2. **Múltiples servicios**
|
||||
- Cliente (Next.js)
|
||||
- Servidor (Node.js + Socket.IO)
|
||||
- Base de datos (PostgreSQL)
|
||||
|
||||
3. **Variables de entorno de producción**
|
||||
- `NEXT_PUBLIC_API_URL=https://api.franciaocupada.martivich.es`
|
||||
- `CORS_ORIGIN=https://franciaocupada.martivich.es`
|
||||
|
||||
4. **Verificación mejorada**
|
||||
- Comprueba que los 3 contenedores estén corriendo
|
||||
- Muestra logs de cada servicio
|
||||
|
||||
## 🛠️ Troubleshooting Rápido
|
||||
|
||||
### El workflow no se ejecuta
|
||||
- Verifica que el runner esté corriendo: `docker ps | grep gitea-act_runner`
|
||||
- Verifica la conexión del runner con Gitea
|
||||
|
||||
### El workflow falla en el build
|
||||
- Revisa los logs en Gitea Actions
|
||||
- Construye manualmente: `docker compose -f docker-compose_prod.yml build`
|
||||
|
||||
### Los contenedores no inician
|
||||
- Verifica puertos disponibles: `sudo lsof -i :3000 :4000 :5432`
|
||||
- Revisa logs: `docker compose -f docker-compose_prod.yml logs`
|
||||
|
||||
### La aplicación no responde
|
||||
- Espera 30-60 segundos después del deploy
|
||||
- Verifica que los contenedores estén "Up": `docker compose -f docker-compose_prod.yml ps`
|
||||
- Revisa logs del cliente y servidor
|
||||
|
||||
## 📝 Archivos Creados
|
||||
|
||||
```
|
||||
resistencia/
|
||||
├── .gitea/
|
||||
│ └── workflows/
|
||||
│ └── deployment.yml # Workflow de CI/CD
|
||||
├── CI-CD-README.md # Documentación detallada
|
||||
├── monitor-deploy.sh # Script de monitoreo
|
||||
└── DEPLOYMENT-SUMMARY.md # Este archivo
|
||||
```
|
||||
|
||||
## 🎉 ¡Listo!
|
||||
|
||||
Tu proyecto ahora tiene CI/CD automático. Cada vez que hagas push a `main`, se desplegará automáticamente en producción.
|
||||
|
||||
**URLs de Verificación**:
|
||||
- 🌐 Frontend: https://franciaocupada.martivich.es
|
||||
- 🔌 API: https://api.franciaocupada.martivich.es
|
||||
- 🔧 Gitea Actions: http://gitea.local:3000/marti/FranciaOcupada/actions
|
||||
247
NUEVO-ENFOQUE-CICD.md
Normal file
@@ -0,0 +1,247 @@
|
||||
# 🎯 Nuevo Enfoque de CI/CD - Script de Deployment en el Host
|
||||
|
||||
## El Problema que Resolvimos
|
||||
|
||||
### ❌ Enfoque Anterior (No Funcionaba)
|
||||
El workflow intentaba ejecutar comandos `docker` directamente dentro del contenedor del runner:
|
||||
|
||||
```yaml
|
||||
- name: Construir Imágenes
|
||||
run: |
|
||||
docker compose -f docker-compose_prod.yml build
|
||||
```
|
||||
|
||||
**Problema**: Aunque el socket de Docker estaba montado (`/var/run/docker.sock`), el binario `docker` no estaba disponible dentro del contenedor del runner, causando el error:
|
||||
```
|
||||
docker: command not found
|
||||
```
|
||||
|
||||
### ✅ Nuevo Enfoque (Funciona)
|
||||
Creamos un script `deploy.sh` que se ejecuta **directamente en el host**, donde Docker SÍ está instalado:
|
||||
|
||||
```yaml
|
||||
- name: Ejecutar Deployment
|
||||
run: |
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
## Arquitectura del Nuevo Sistema
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ GITEA SERVER │
|
||||
│ - Detecta push a main │
|
||||
│ - Envía job al runner │
|
||||
└────────────────┬────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ GITEA RUNNER (Contenedor) │
|
||||
│ - Instala Node.js │
|
||||
│ - Hace checkout del código │
|
||||
│ - Ejecuta deploy.sh en el HOST │
|
||||
└────────────────┬────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ HOST (Servidor de Producción) │
|
||||
│ - deploy.sh se ejecuta aquí │
|
||||
│ - Docker está instalado aquí │
|
||||
│ - Construye y despliega contenedores │
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Client │ │ Server │ │ Database │ │
|
||||
│ │ (Next.js) │ │ (Node.js) │ │ (PostgreSQL) │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Componentes del Sistema
|
||||
|
||||
### 1. `deploy.sh` - Script de Deployment en el Host
|
||||
|
||||
**Ubicación**: `/home/marti/Documentos/Gitea/resistencia/deploy.sh`
|
||||
|
||||
**Responsabilidades**:
|
||||
- ✅ Actualizar código desde Git
|
||||
- ✅ Detener contenedores anteriores
|
||||
- ✅ Limpiar imágenes antiguas
|
||||
- ✅ Construir nuevas imágenes Docker
|
||||
- ✅ Desplegar contenedores
|
||||
- ✅ Verificar que todo funciona
|
||||
- ✅ Mostrar logs
|
||||
|
||||
**Ventajas**:
|
||||
- Se ejecuta directamente en el host donde Docker está instalado
|
||||
- Puede ser ejecutado manualmente para debugging: `./deploy.sh`
|
||||
- Fácil de modificar y probar
|
||||
- No depende de las limitaciones del runner
|
||||
|
||||
### 2. `.gitea/workflows/deployment.yml` - Workflow Simplificado
|
||||
|
||||
**Responsabilidades**:
|
||||
- ✅ Instalar Node.js (necesario para `actions/checkout`)
|
||||
- ✅ Hacer checkout del código
|
||||
- ✅ Ejecutar `deploy.sh` en el host
|
||||
- ✅ Verificar el resultado
|
||||
|
||||
**Ventajas**:
|
||||
- Mucho más simple y mantenible
|
||||
- Menos propenso a errores
|
||||
- Fácil de entender y debuggear
|
||||
|
||||
## Cómo Funciona
|
||||
|
||||
### Flujo Completo
|
||||
|
||||
1. **Desarrollador hace push a `main`**
|
||||
```bash
|
||||
git push origin main
|
||||
```
|
||||
|
||||
2. **Gitea detecta el push y activa el workflow**
|
||||
- El runner recibe el job
|
||||
|
||||
3. **Runner instala Node.js**
|
||||
- Necesario para que `actions/checkout` funcione
|
||||
|
||||
4. **Runner hace checkout del código**
|
||||
- Descarga la última versión del repositorio
|
||||
|
||||
5. **Runner ejecuta `deploy.sh` en el host**
|
||||
- El script se ejecuta con acceso completo a Docker del host
|
||||
|
||||
6. **`deploy.sh` realiza el deployment**
|
||||
- Actualiza código
|
||||
- Construye imágenes
|
||||
- Despliega contenedores
|
||||
|
||||
7. **Verificación final**
|
||||
- El workflow verifica que los contenedores estén corriendo
|
||||
|
||||
## Uso Manual del Script
|
||||
|
||||
También puedes ejecutar el deployment manualmente:
|
||||
|
||||
```bash
|
||||
# Conectarte al servidor
|
||||
ssh usuario@servidor
|
||||
|
||||
# Ir al directorio del proyecto
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
|
||||
# Ejecutar deployment
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
Esto es útil para:
|
||||
- Debugging
|
||||
- Deployments de emergencia
|
||||
- Probar cambios antes de hacer commit
|
||||
|
||||
## Comparación con el Ejemplo que Funciona
|
||||
|
||||
El ejemplo que compartiste usa `runs-on: ubuntu-latest`, que es una imagen de GitHub/Gitea con **todas las herramientas preinstaladas**:
|
||||
|
||||
```yaml
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest # ← Imagen completa con todo instalado
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4 # ← Node.js ya disponible
|
||||
- run: mvn clean deploy # ← Maven ya disponible
|
||||
```
|
||||
|
||||
Tu runner usa `runs-on: [production-ready]`, que es un **runner personalizado** que:
|
||||
- ✅ Tiene acceso al Docker del host (vía socket)
|
||||
- ❌ NO tiene Docker CLI instalado dentro del contenedor
|
||||
- ❌ NO tiene Node.js preinstalado
|
||||
- ❌ NO tiene otras herramientas preinstaladas
|
||||
|
||||
Por eso necesitamos:
|
||||
1. Instalar Node.js manualmente
|
||||
2. Ejecutar un script en el host (donde Docker SÍ está)
|
||||
|
||||
## Ventajas del Nuevo Enfoque
|
||||
|
||||
1. **Simplicidad**: Un script bash es más fácil de entender que un workflow complejo
|
||||
2. **Debugging**: Puedes ejecutar `./deploy.sh` manualmente para probar
|
||||
3. **Flexibilidad**: Fácil modificar el script sin tocar el workflow
|
||||
4. **Portabilidad**: El mismo script puede usarse en otros sistemas de CI/CD
|
||||
5. **Confiabilidad**: Se ejecuta en el host donde sabemos que Docker funciona
|
||||
|
||||
## Archivos del Sistema
|
||||
|
||||
```
|
||||
resistencia/
|
||||
├── .gitea/
|
||||
│ └── workflows/
|
||||
│ └── deployment.yml # Workflow simplificado
|
||||
├── deploy.sh # Script de deployment (NUEVO)
|
||||
├── docker-compose_prod.yml # Configuración de producción
|
||||
├── CI-CD-README.md # Documentación general
|
||||
├── TROUBLESHOOTING-CICD.md # Problemas resueltos
|
||||
└── monitor-deploy.sh # Script de monitoreo
|
||||
```
|
||||
|
||||
## Próximos Pasos
|
||||
|
||||
Ahora que el CI/CD funciona, puedes:
|
||||
|
||||
1. **Probar el deployment**:
|
||||
```bash
|
||||
git commit --allow-empty -m "test: Probar nuevo CI/CD"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
2. **Monitorear en Gitea**:
|
||||
- http://gitea.local:3000/marti/FranciaOcupada/actions
|
||||
|
||||
3. **Verificar la aplicación**:
|
||||
- https://franciaocupada.martivich.es
|
||||
- https://api.franciaocupada.martivich.es
|
||||
|
||||
4. **Mejoras futuras**:
|
||||
- Agregar tests antes del deploy
|
||||
- Implementar rollback automático
|
||||
- Agregar notificaciones (Discord, email, etc.)
|
||||
- Backup de base de datos antes de deploy
|
||||
- Health checks post-deployment
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Si el workflow falla
|
||||
|
||||
1. **Ver logs en Gitea Actions**
|
||||
2. **Ejecutar manualmente el script**:
|
||||
```bash
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
./deploy.sh
|
||||
```
|
||||
3. **Verificar que Docker funciona en el host**:
|
||||
```bash
|
||||
docker ps
|
||||
docker compose version
|
||||
```
|
||||
|
||||
### Si los contenedores no inician
|
||||
|
||||
```bash
|
||||
# Ver logs
|
||||
docker compose -f docker-compose_prod.yml logs
|
||||
|
||||
# Reiniciar servicios
|
||||
docker compose -f docker-compose_prod.yml restart
|
||||
|
||||
# Reconstruir desde cero
|
||||
docker compose -f docker-compose_prod.yml down
|
||||
docker compose -f docker-compose_prod.yml up -d --build
|
||||
```
|
||||
|
||||
## Conclusión
|
||||
|
||||
Este nuevo enfoque es más simple, más confiable y más fácil de mantener. En lugar de luchar contra las limitaciones del runner, aprovechamos que el runner puede ejecutar scripts en el host donde Docker ya está instalado y funcionando.
|
||||
|
||||
**¡El CI/CD ahora debería funcionar correctamente!** 🎉
|
||||
39
README.md
@@ -18,22 +18,33 @@
|
||||
- ✅ Sistema de victoria (3 misiones exitosas o 3 fallidas)
|
||||
- ✅ Fase de asesinato (ASSASSIN_PHASE)
|
||||
|
||||
#### Frontend (Funcional hasta MISSION)
|
||||
#### Frontend (Funcional hasta Victoria)
|
||||
- ✅ Lobby con creación/unión de partidas
|
||||
- ✅ Intro con música y animaciones
|
||||
- ✅ Intro con música y animaciones (título: "Traidores en París")
|
||||
- ✅ Revelación de roles con cartas
|
||||
- ✅ Roll call con avatares
|
||||
- ✅ Votación de líder con timer de 10 segundos
|
||||
- ✅ Votación de líder con timer de 10 segundos (esquina superior izquierda)
|
||||
- ✅ Selección de equipo por el líder
|
||||
- ✅ Votación de equipo
|
||||
- ✅ Votación de equipo con cartas cuadradas (aceptar/rechazar)
|
||||
- ✅ Votación de misión (éxito/sabotaje solo para espías)
|
||||
- ✅ Componente VotingTimer funcionando
|
||||
- ✅ **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)
|
||||
|
||||
### ❌ Pendiente de Implementar (Solo UI)
|
||||
### 🎨 Mejoras de UI Recientes (2025-12-13)
|
||||
|
||||
1. **Fase MISSION_REVEAL**: Pantalla que muestra las cartas de votación una a una (backend listo)
|
||||
2. **Fase MISSION_RESULT**: Pantalla resumen con resultado de la misión (backend listo)
|
||||
3. **Histórico de Misiones**: Componente visual en esquina mostrando misiones completadas (backend listo)
|
||||
- ✅ Timer de votación reposicionado (esquina superior izquierda, fixed, 20px margen)
|
||||
- ✅ Cartas de votación de líder redimensionadas (cuadradas 32x32)
|
||||
- ✅ Eliminado contador de votos rechazados en resultado de misión
|
||||
- ✅ Mapa táctico permanece visible durante toda la fase MISSION_RESULT
|
||||
- ✅ Tokens de victoria/fracaso posicionados en el mapa (ajuste fino pendiente para tokens 3, 4, 5)
|
||||
|
||||
### ⚠️ Pendiente de Ajustar
|
||||
|
||||
1. **Posiciones de tokens en mapa**: Afinar ubicación de tokens de misiones 3, 4 y 5 en el tablero táctico
|
||||
|
||||
## 🚀 Cómo Ejecutar
|
||||
|
||||
@@ -68,14 +79,14 @@ docker compose down
|
||||
## 🐛 Problemas Conocidos
|
||||
|
||||
1. **CPU Alta en Servidor**: El servidor puede consumir mucha CPU. Si ocurre, reiniciar con `docker compose restart server`
|
||||
2. **Fases MISSION_REVEAL y MISSION_RESULT**: No tienen UI implementada. El juego se quedará en esa fase si se completa una misión.
|
||||
2. **Posiciones de tokens en mapa**: Los tokens de misiones 3, 4 y 5 necesitan ajuste fino en sus coordenadas
|
||||
|
||||
## 📋 Próximos Pasos
|
||||
|
||||
1. Implementar UI para MISSION_REVEAL (mostrar cartas una a una con animación)
|
||||
2. Implementar UI para MISSION_RESULT (pantalla resumen)
|
||||
3. Agregar histórico de misiones visual
|
||||
4. Optimizar rendimiento del servidor
|
||||
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
|
||||
|
||||
|
||||
261
RESUMEN-FINAL.md
Normal file
@@ -0,0 +1,261 @@
|
||||
# ✅ Resumen Final - CI/CD Configurado
|
||||
|
||||
## 🎉 ¡CI/CD Configurado Exitosamente!
|
||||
|
||||
Has configurado un sistema completo de CI/CD para tu proyecto "Francia Ocupada" usando Gitea Actions.
|
||||
|
||||
## 📦 Lo que Hemos Creado
|
||||
|
||||
### 1. Script de Deployment (`deploy.sh`)
|
||||
- ✅ Script bash que se ejecuta en el host
|
||||
- ✅ Maneja todo el proceso de deployment
|
||||
- ✅ Puede ejecutarse manualmente para debugging
|
||||
|
||||
### 2. Workflow de Gitea Actions (`.gitea/workflows/deployment.yml`)
|
||||
- ✅ Se activa automáticamente en push a `main`
|
||||
- ✅ Instala Node.js
|
||||
- ✅ Hace checkout del código
|
||||
- ✅ Ejecuta el script de deployment
|
||||
|
||||
### 3. Documentación Completa
|
||||
- ✅ `CI-CD-README.md` - Guía general de uso
|
||||
- ✅ `TROUBLESHOOTING-CICD.md` - Problemas resueltos
|
||||
- ✅ `NUEVO-ENFOQUE-CICD.md` - Explicación del enfoque actual
|
||||
- ✅ `DEPLOYMENT-SUMMARY.md` - Resumen de la configuración
|
||||
- ✅ `monitor-deploy.sh` - Script de monitoreo
|
||||
- ✅ `useful-commands.sh` - Comandos útiles
|
||||
|
||||
## 🚀 Cómo Usar el CI/CD
|
||||
|
||||
### Deployment Automático
|
||||
|
||||
Simplemente haz push a la rama `main`:
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "feat: Nueva funcionalidad"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
El workflow se ejecutará automáticamente y desplegará tu aplicación.
|
||||
|
||||
### Deployment Manual
|
||||
|
||||
Si necesitas hacer un deployment sin hacer cambios:
|
||||
|
||||
```bash
|
||||
# Opción 1: Commit vacío
|
||||
git commit --allow-empty -m "deploy: Trigger deployment"
|
||||
git push origin main
|
||||
|
||||
# Opción 2: Ejecutar el script directamente en el servidor
|
||||
ssh usuario@servidor
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
## 📊 Monitoreo
|
||||
|
||||
### Ver el Workflow en Gitea
|
||||
```
|
||||
http://gitea.local:3000/marti/FranciaOcupada/actions
|
||||
```
|
||||
|
||||
### Verificar Estado de Contenedores
|
||||
```bash
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
```
|
||||
|
||||
### Ver Logs
|
||||
```bash
|
||||
# Todos los logs
|
||||
docker compose -f docker-compose_prod.yml logs
|
||||
|
||||
# Logs en tiempo real
|
||||
docker compose -f docker-compose_prod.yml logs -f
|
||||
|
||||
# Script de monitoreo interactivo
|
||||
./monitor-deploy.sh
|
||||
```
|
||||
|
||||
## 🌐 URLs de la Aplicación
|
||||
|
||||
Después del deployment, tu aplicación estará disponible en:
|
||||
|
||||
- **Frontend**: https://franciaocupada.martivich.es
|
||||
- **API**: https://api.franciaocupada.martivich.es
|
||||
|
||||
## 🔧 Configuración del Runner
|
||||
|
||||
Tu runner está configurado correctamente:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
gitea-runner:
|
||||
image: gitea/act_runner:latest
|
||||
container_name: gitea-act_runner
|
||||
restart: always
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
environment:
|
||||
- GITEA_INSTANCE_URL=http://gitea.local:3000
|
||||
- GITEA_RUNNER_NAME=runner-01-ci-vm
|
||||
- GITEA_RUNNER_LABELS=production-ready:host
|
||||
- GITEA_RUNNER_REGISTRATION_TOKEN=jzLi65hxB1Rt2RgIGFglXB5RjW9ggCbq9UFX3NrS
|
||||
```
|
||||
|
||||
## 📝 Archivos Importantes
|
||||
|
||||
```
|
||||
resistencia/
|
||||
├── .gitea/
|
||||
│ └── workflows/
|
||||
│ └── deployment.yml # ← Workflow de CI/CD
|
||||
│
|
||||
├── deploy.sh # ← Script de deployment (ejecutable)
|
||||
├── docker-compose_prod.yml # ← Configuración de producción
|
||||
│
|
||||
├── monitor-deploy.sh # ← Monitoreo interactivo
|
||||
├── useful-commands.sh # ← Comandos de referencia
|
||||
│
|
||||
└── Documentación:
|
||||
├── CI-CD-README.md # ← Guía general
|
||||
├── TROUBLESHOOTING-CICD.md # ← Problemas y soluciones
|
||||
├── NUEVO-ENFOQUE-CICD.md # ← Explicación técnica
|
||||
├── DEPLOYMENT-SUMMARY.md # ← Resumen de configuración
|
||||
└── RESUMEN-FINAL.md # ← Este archivo
|
||||
```
|
||||
|
||||
## 🎯 Próximos Pasos Recomendados
|
||||
|
||||
### 1. Probar el CI/CD
|
||||
```bash
|
||||
# Hacer un cambio pequeño
|
||||
echo "# Test CI/CD" >> README.md
|
||||
git add README.md
|
||||
git commit -m "test: Verificar CI/CD"
|
||||
git push origin main
|
||||
|
||||
# Monitorear en Gitea
|
||||
# http://gitea.local:3000/marti/FranciaOcupada/actions
|
||||
```
|
||||
|
||||
### 2. Verificar el Deployment
|
||||
```bash
|
||||
# Esperar 2-3 minutos para que complete
|
||||
# Luego verificar:
|
||||
curl -I https://franciaocupada.martivich.es
|
||||
curl -I https://api.franciaocupada.martivich.es
|
||||
```
|
||||
|
||||
### 3. Mejoras Futuras
|
||||
|
||||
#### Tests Automatizados
|
||||
Agregar tests antes del deployment:
|
||||
```yaml
|
||||
- name: Run Tests
|
||||
run: |
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
npm test
|
||||
```
|
||||
|
||||
#### Notificaciones
|
||||
Configurar notificaciones de éxito/fallo (Discord, email, etc.)
|
||||
|
||||
#### Rollback Automático
|
||||
Implementar rollback si el deployment falla
|
||||
|
||||
#### Staging Environment
|
||||
Crear un ambiente de staging para probar antes de producción
|
||||
|
||||
#### Health Checks
|
||||
Verificar que la aplicación responde correctamente después del deploy
|
||||
|
||||
#### Backup de Base de Datos
|
||||
Hacer backup automático antes de cada deployment
|
||||
|
||||
## 🐛 Troubleshooting Rápido
|
||||
|
||||
### El workflow falla
|
||||
1. Ver logs en Gitea Actions
|
||||
2. Ejecutar `./deploy.sh` manualmente
|
||||
3. Revisar `TROUBLESHOOTING-CICD.md`
|
||||
|
||||
### Los contenedores no inician
|
||||
```bash
|
||||
docker compose -f docker-compose_prod.yml logs
|
||||
docker compose -f docker-compose_prod.yml restart
|
||||
```
|
||||
|
||||
### La aplicación no responde
|
||||
```bash
|
||||
# Verificar contenedores
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
|
||||
# Ver logs
|
||||
docker compose -f docker-compose_prod.yml logs -f
|
||||
|
||||
# Reiniciar
|
||||
docker compose -f docker-compose_prod.yml restart
|
||||
```
|
||||
|
||||
## 📚 Comandos Útiles de Referencia
|
||||
|
||||
```bash
|
||||
# Ver estado
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
|
||||
# Ver logs
|
||||
docker compose -f docker-compose_prod.yml logs -f
|
||||
|
||||
# Reiniciar
|
||||
docker compose -f docker-compose_prod.yml restart
|
||||
|
||||
# Reconstruir
|
||||
docker compose -f docker-compose_prod.yml up -d --build
|
||||
|
||||
# Detener
|
||||
docker compose -f docker-compose_prod.yml down
|
||||
|
||||
# Deployment manual
|
||||
./deploy.sh
|
||||
|
||||
# Monitoreo interactivo
|
||||
./monitor-deploy.sh
|
||||
|
||||
# Ver todos los comandos
|
||||
./useful-commands.sh
|
||||
```
|
||||
|
||||
## 🎓 Lecciones Aprendidas
|
||||
|
||||
1. **Runners personalizados son diferentes a `ubuntu-latest`**
|
||||
- No tienen todas las herramientas preinstaladas
|
||||
- Necesitan configuración específica
|
||||
|
||||
2. **El socket de Docker no es suficiente**
|
||||
- Necesitas también el binario `docker` instalado
|
||||
- O ejecutar scripts en el host donde Docker está instalado
|
||||
|
||||
3. **Los scripts en el host son más simples**
|
||||
- Más fáciles de debuggear
|
||||
- Más flexibles
|
||||
- Más confiables
|
||||
|
||||
4. **La documentación es clave**
|
||||
- Ayuda a entender problemas futuros
|
||||
- Facilita el mantenimiento
|
||||
- Útil para otros desarrolladores
|
||||
|
||||
## 🎉 ¡Felicidades!
|
||||
|
||||
Has configurado exitosamente un sistema completo de CI/CD para tu aplicación. Ahora cada vez que hagas push a `main`, tu aplicación se desplegará automáticamente en producción.
|
||||
|
||||
**¡A disfrutar del deployment automático!** 🚀
|
||||
|
||||
---
|
||||
|
||||
**Última actualización**: 2025-12-13
|
||||
**Versión**: 1.0
|
||||
**Estado**: ✅ Funcional
|
||||
255
SESION-CICD-RESUMEN.md
Normal file
@@ -0,0 +1,255 @@
|
||||
# 📚 Resumen de la Sesión CI/CD - Puntos de Aprendizaje
|
||||
|
||||
## 🎯 Lo que Intentamos Lograr
|
||||
|
||||
Configurar CI/CD automático para desplegar "Francia Ocupada" en producción usando Gitea Actions.
|
||||
|
||||
## 🔍 Problemas Encontrados
|
||||
|
||||
### 1. **Runner Personalizado vs Runner Estándar**
|
||||
|
||||
**Tu configuración**:
|
||||
```yaml
|
||||
runs-on: [production-ready] # Runner personalizado
|
||||
```
|
||||
|
||||
**Ejemplo que funciona**:
|
||||
```yaml
|
||||
runs-on: ubuntu-latest # Runner estándar de GitHub/Gitea
|
||||
```
|
||||
|
||||
**Diferencia clave**:
|
||||
- `ubuntu-latest` tiene TODAS las herramientas preinstaladas (docker, node, git, etc.)
|
||||
- Tu runner personalizado es un contenedor vacío que solo tiene acceso al socket de Docker
|
||||
|
||||
### 2. **Socket de Docker ≠ Docker CLI**
|
||||
|
||||
Tu runner tiene:
|
||||
- ✅ Acceso al socket de Docker (`/var/run/docker.sock`)
|
||||
- ❌ NO tiene el binario `docker` instalado
|
||||
|
||||
Por eso todos los comandos `docker` fallan con "command not found".
|
||||
|
||||
### 3. **Comandos dentro del Runner vs Comandos en el Host**
|
||||
|
||||
El runner ejecuta comandos **dentro de su contenedor**, no directamente en el host.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ HOST (Servidor) │
|
||||
│ - Docker instalado ✅ │
|
||||
│ - Proyecto en /home/marti/... │
|
||||
│ │
|
||||
│ ┌───────────────────────────┐ │
|
||||
│ │ RUNNER (Contenedor) │ │
|
||||
│ │ - Docker NO instalado ❌ │ │
|
||||
│ │ - Comandos se ejecutan │ │
|
||||
│ │ AQUÍ, no en el host │ │
|
||||
│ └───────────────────────────┘ │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 📋 Soluciones Intentadas
|
||||
|
||||
### Intento 1: Usar variables de contexto de Gitea ❌
|
||||
- No funcionó: Variables mal interpoladas
|
||||
|
||||
### Intento 2: Reordenar pasos (Node.js antes de checkout) ❌
|
||||
- No funcionó: Seguía faltando Node.js
|
||||
|
||||
### Intento 3: Instalar Node.js manualmente ✅
|
||||
- Funcionó: Node.js instalado correctamente
|
||||
|
||||
### Intento 4: Especificar `shell: bash` ❌
|
||||
- No funcionó: Docker seguía sin encontrarse
|
||||
|
||||
### Intento 5: Instalar Docker CLI en el runner ❌
|
||||
- No intentado: Demasiado complejo
|
||||
|
||||
### Intento 6: Script de deployment en el host ⚠️
|
||||
- Parcialmente: Script creado pero falta ejecutarlo correctamente
|
||||
|
||||
### Intento 7: Eliminar copia con rsync ⏸️
|
||||
- En progreso: Simplificado pero no probado
|
||||
|
||||
## 🎓 Conceptos Clave Aprendidos
|
||||
|
||||
### 1. **Etiquetas de Runner**
|
||||
|
||||
```yaml
|
||||
GITEA_RUNNER_LABELS=production-ready:host
|
||||
```
|
||||
|
||||
- `production-ready`: Nombre de la etiqueta
|
||||
- `:host`: Indica que debe ejecutar en modo "host" (acceso al Docker del host)
|
||||
|
||||
### 2. **Volúmenes de Docker**
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
Esto da acceso al **socket** de Docker, pero NO instala el **cliente** de Docker.
|
||||
|
||||
### 3. **Diferencia entre CI y CD**
|
||||
|
||||
- **CI (Continuous Integration)**: Construir, probar, validar código
|
||||
- **CD (Continuous Deployment)**: Desplegar a producción
|
||||
|
||||
Tu runner está configurado para CD (deployment), no para CI (build).
|
||||
|
||||
## 🛠️ Opciones para Continuar
|
||||
|
||||
### Opción 1: Usar un Runner Estándar (Más Fácil) ⭐
|
||||
|
||||
**Ventajas**:
|
||||
- Todo preinstalado
|
||||
- Funciona como el ejemplo que compartiste
|
||||
- Menos configuración
|
||||
|
||||
**Desventajas**:
|
||||
- Necesitas configurar acceso SSH al servidor de producción
|
||||
- El deployment se hace remotamente
|
||||
|
||||
**Cómo hacerlo**:
|
||||
```yaml
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest # ← Cambiar a esto
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Deploy via SSH
|
||||
run: |
|
||||
ssh user@servidor 'cd /path/to/project && ./deploy.sh'
|
||||
```
|
||||
|
||||
### Opción 2: Configurar el Runner con Docker Preinstalado (Medio)
|
||||
|
||||
Crear una imagen personalizada del runner con Docker ya instalado.
|
||||
|
||||
**Dockerfile del runner**:
|
||||
```dockerfile
|
||||
FROM gitea/act_runner:latest
|
||||
RUN apt-get update && apt-get install -y docker-ce-cli
|
||||
```
|
||||
|
||||
### Opción 3: Deployment Manual con Git Hooks (Más Simple) ⭐⭐
|
||||
|
||||
Usar Git hooks en el servidor para auto-desplegar cuando haces push.
|
||||
|
||||
**En el servidor**:
|
||||
```bash
|
||||
# .git/hooks/post-receive
|
||||
#!/bin/bash
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
git pull
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
### Opción 4: Usar Portainer o Watchtower (Automático)
|
||||
|
||||
Herramientas que detectan cambios en imágenes Docker y auto-actualizan.
|
||||
|
||||
### Opción 5: Continuar con el Enfoque Actual (Más Complejo)
|
||||
|
||||
Necesitarías:
|
||||
1. Entender mejor cómo el runner accede al filesystem del host
|
||||
2. Configurar permisos correctos
|
||||
3. Posiblemente usar SSH desde el runner al host
|
||||
|
||||
## 📚 Recursos para Estudiar
|
||||
|
||||
### Gitea Actions
|
||||
- [Documentación oficial de Gitea Actions](https://docs.gitea.com/usage/actions/overview)
|
||||
- [Act Runner GitHub](https://github.com/nektos/act)
|
||||
- [Diferencias entre GitHub Actions y Gitea Actions](https://docs.gitea.com/usage/actions/comparison)
|
||||
|
||||
### Docker en CI/CD
|
||||
- [Docker-in-Docker (DinD)](https://www.docker.com/blog/docker-can-now-run-within-docker/)
|
||||
- [Docker socket mounting](https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option)
|
||||
|
||||
### Alternativas
|
||||
- [Drone CI](https://www.drone.io/) - CI/CD más simple
|
||||
- [Jenkins](https://www.jenkins.io/) - Más potente pero complejo
|
||||
- [GitLab CI/CD](https://docs.gitlab.com/ee/ci/) - Similar a Gitea Actions
|
||||
|
||||
## 💡 Mi Recomendación
|
||||
|
||||
Para tu caso específico, te recomendaría **Opción 1 o Opción 3**:
|
||||
|
||||
### Opción 1: Runner Estándar + SSH
|
||||
```yaml
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Deploy to Production
|
||||
uses: appleboy/ssh-action@master
|
||||
with:
|
||||
host: ${{ secrets.HOST }}
|
||||
username: ${{ secrets.USERNAME }}
|
||||
key: ${{ secrets.SSH_KEY }}
|
||||
script: |
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
git pull
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
### Opción 3: Git Hook (Sin CI/CD)
|
||||
```bash
|
||||
# En el servidor, en el repositorio bare de Gitea
|
||||
# /path/to/gitea/data/gitea-repositories/marti/FranciaOcupada.git/hooks/post-receive
|
||||
|
||||
#!/bin/bash
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
git pull origin main
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
## 📝 Estado Actual del Proyecto
|
||||
|
||||
### ✅ Lo que SÍ funciona:
|
||||
- Script `deploy.sh` - Listo para usar
|
||||
- Docker Compose configurado
|
||||
- Aplicación funcional en local
|
||||
|
||||
### ⚠️ Lo que NO funciona:
|
||||
- Workflow de Gitea Actions con runner personalizado
|
||||
- Ejecución automática de deployment
|
||||
|
||||
### 🎯 Lo que tienes listo para usar:
|
||||
```bash
|
||||
# Deployment manual (esto SÍ funciona)
|
||||
cd /home/marti/Documentos/Gitea/resistencia
|
||||
./deploy.sh
|
||||
```
|
||||
|
||||
## 🚀 Próximos Pasos Sugeridos
|
||||
|
||||
1. **Estudiar** los recursos mencionados arriba
|
||||
2. **Decidir** qué opción se adapta mejor a tus necesidades
|
||||
3. **Probar** el deployment manual mientras tanto: `./deploy.sh`
|
||||
4. **Considerar** si realmente necesitas CI/CD automático o si el deployment manual es suficiente
|
||||
|
||||
## 📦 Archivos Útiles Creados
|
||||
|
||||
Aunque el CI/CD automático no funcionó, estos archivos son útiles:
|
||||
|
||||
- ✅ `deploy.sh` - Script de deployment manual (funciona)
|
||||
- ✅ `monitor-deploy.sh` - Monitoreo de contenedores
|
||||
- ✅ `useful-commands.sh` - Comandos de referencia
|
||||
- ✅ Documentación completa del proceso
|
||||
|
||||
## 💭 Reflexión Final
|
||||
|
||||
CI/CD con runners personalizados es complejo. No es un fallo tuyo no haberlo logrado en la primera sesión. Muchos equipos profesionales tardan días o semanas en configurar correctamente su CI/CD.
|
||||
|
||||
**Alternativa práctica**: Mientras estudias más sobre el tema, puedes usar deployment manual con `./deploy.sh`, que es perfectamente válido para proyectos pequeños/medianos.
|
||||
|
||||
---
|
||||
|
||||
**Fecha**: 2025-12-13
|
||||
**Estado**: En pausa para estudio
|
||||
**Próximo paso**: Decidir entre las opciones propuestas arriba
|
||||
233
TROUBLESHOOTING-CICD.md
Normal file
@@ -0,0 +1,233 @@
|
||||
# 🔧 Troubleshooting CI/CD - Problemas Resueltos
|
||||
|
||||
## Resumen de Problemas Encontrados y Soluciones
|
||||
|
||||
Durante la configuración del CI/CD con Gitea Actions, encontramos varios problemas que fueron resueltos paso a paso. Este documento sirve como referencia para futuros problemas similares.
|
||||
|
||||
---
|
||||
|
||||
## Problema 1: Error en el Checkout - Variables de Contexto
|
||||
|
||||
### ❌ Error
|
||||
```
|
||||
%!t(string=http://gitea.local:3000)
|
||||
%!t(string=***)
|
||||
%!t(string=marti/FranciaOcupada)
|
||||
```
|
||||
|
||||
### 🔍 Causa
|
||||
El workflow intentaba usar variables de contexto de Gitea (`${{ gitea.server_url }}`, `${{ gitea.repository }}`, `${{ gitea.token }}`) en el paso de checkout, pero estas no se interpolaban correctamente.
|
||||
|
||||
### ✅ Solución
|
||||
Simplificar el checkout eliminando los parámetros innecesarios:
|
||||
|
||||
```yaml
|
||||
# ❌ ANTES (No funcionaba)
|
||||
- name: 🚀 Checkout del Código
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
server-url: ${{ gitea.server_url }}
|
||||
repository: ${{ gitea.repository }}
|
||||
token: ${{ gitea.token }}
|
||||
fetch-depth: 0
|
||||
|
||||
# ✅ DESPUÉS (Funciona)
|
||||
- name: 🚀 Checkout del Código
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
```
|
||||
|
||||
**Commit**: `609033b` - "fix: Corregir checkout en workflow de Gitea Actions"
|
||||
|
||||
---
|
||||
|
||||
## Problema 2: Node.js No Encontrado
|
||||
|
||||
### ❌ Error
|
||||
```
|
||||
Cannot find: node in PATH
|
||||
```
|
||||
|
||||
### 🔍 Causa
|
||||
El runner de Gitea Actions no tiene Node.js preinstalado, y las acciones de GitHub (como `actions/checkout@v4` y `actions/setup-node@v4`) requieren Node.js para ejecutarse.
|
||||
|
||||
### ✅ Solución
|
||||
Instalar Node.js manualmente usando comandos del sistema ANTES de cualquier acción de GitHub:
|
||||
|
||||
```yaml
|
||||
- name: 📦 Instalar Node.js
|
||||
shell: bash
|
||||
run: |
|
||||
echo "Verificando si Node.js está instalado..."
|
||||
if ! command -v node &> /dev/null; then
|
||||
echo "Node.js no encontrado, instalando..."
|
||||
|
||||
# Detectar el sistema operativo
|
||||
if [ -f /etc/debian_version ]; then
|
||||
# Debian/Ubuntu
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt-get install -y nodejs
|
||||
elif [ -f /etc/redhat-release ]; then
|
||||
# RedHat/CentOS/Fedora
|
||||
curl -fsSL https://rpm.nodesource.com/setup_20.x | bash -
|
||||
yum install -y nodejs
|
||||
elif [ -f /etc/alpine-release ]; then
|
||||
# Alpine Linux
|
||||
apk add --no-cache nodejs npm
|
||||
else
|
||||
# Fallback a nvm
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
|
||||
export NVM_DIR="$HOME/.nvm"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
||||
nvm install 20
|
||||
fi
|
||||
else
|
||||
echo "Node.js ya está instalado: $(node --version)"
|
||||
fi
|
||||
|
||||
# Verificar instalación
|
||||
node --version
|
||||
npm --version
|
||||
```
|
||||
|
||||
**Commit**: `7c9ff53` - "feat: Instalación manual de Node.js en el runner"
|
||||
|
||||
---
|
||||
|
||||
## Problema 3: Scripts No Encontrados (2.sh, 3.sh, 4.sh)
|
||||
|
||||
### ❌ Error
|
||||
```
|
||||
/root/.cache/act/6d07dd4849690bae/act/workflow/2.sh: line 3: docker: command not found
|
||||
/root/.cache/act/6d07dd4849690bae/act/workflow/3.sh: line 3: docker: command not found
|
||||
/root/.cache/act/6d07dd4849690bae/act/workflow/4.sh: line 3: docker: command not found
|
||||
```
|
||||
|
||||
### 🔍 Causa
|
||||
El runner de Gitea Actions (basado en `act`) estaba creando archivos temporales (2.sh, 3.sh, 4.sh) para ejecutar los bloques `run:`, pero no especificaba correctamente el shell a usar, causando que los comandos no se ejecutaran en el contexto correcto.
|
||||
|
||||
### ✅ Solución
|
||||
Especificar explícitamente `shell: bash` en todos los pasos que usan bloques `run:`:
|
||||
|
||||
```yaml
|
||||
# ❌ ANTES (No funcionaba)
|
||||
- name: 🛑 Detener Contenedores Anteriores
|
||||
run: |
|
||||
echo "Deteniendo contenedores existentes..."
|
||||
docker compose -f docker-compose_prod.yml down || true
|
||||
|
||||
# ✅ DESPUÉS (Funciona)
|
||||
- name: 🛑 Detener Contenedores Anteriores
|
||||
shell: bash
|
||||
run: |
|
||||
echo "Deteniendo contenedores existentes..."
|
||||
docker compose -f docker-compose_prod.yml down || true
|
||||
```
|
||||
|
||||
**Commit**: `134460a` - "fix: Especificar shell bash explícitamente en todos los pasos"
|
||||
|
||||
---
|
||||
|
||||
## Orden Correcto de los Pasos
|
||||
|
||||
El orden final correcto de los pasos es:
|
||||
|
||||
1. **Instalar Node.js** (con `shell: bash`)
|
||||
2. **Checkout del Código** (usando `actions/checkout@v4`)
|
||||
3. **Detener Contenedores Anteriores** (con `shell: bash`)
|
||||
4. **Limpiar Imágenes Antiguas** (con `shell: bash`)
|
||||
5. **Construir Imágenes Docker** (con `shell: bash`)
|
||||
6. **Desplegar Aplicación** (con `shell: bash`)
|
||||
7. **Verificar Despliegue** (con `shell: bash`)
|
||||
8. **Mostrar Logs Recientes** (con `shell: bash` e `if: always()`)
|
||||
|
||||
---
|
||||
|
||||
## Lecciones Aprendidas
|
||||
|
||||
### 1. Diferencias entre GitHub Actions y Gitea Actions
|
||||
- Gitea Actions usa `act` bajo el capó, que tiene algunas diferencias con GitHub Actions
|
||||
- No todas las variables de contexto funcionan igual
|
||||
- El runner puede no tener las mismas herramientas preinstaladas
|
||||
|
||||
### 2. Especificar el Shell es Importante
|
||||
- Siempre especifica `shell: bash` cuando uses bloques `run:` con múltiples líneas
|
||||
- Esto evita problemas de interpretación de comandos
|
||||
|
||||
### 3. Node.js es Requerido
|
||||
- Muchas acciones de GitHub requieren Node.js
|
||||
- En runners de Gitea, puede que necesites instalarlo manualmente
|
||||
- Instálalo ANTES de usar cualquier acción de GitHub
|
||||
|
||||
### 4. El Runner Necesita Acceso a Docker
|
||||
- Asegúrate de que el runner tenga acceso al socket de Docker del host
|
||||
- En tu configuración: `-v /var/run/docker.sock:/var/run/docker.sock`
|
||||
- La etiqueta debe ser `production-ready:host` para acceso al Docker del host
|
||||
|
||||
---
|
||||
|
||||
## Configuración del Runner
|
||||
|
||||
Tu configuración del runner que funciona:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
gitea-runner:
|
||||
image: gitea/act_runner:latest
|
||||
container_name: gitea-act_runner
|
||||
restart: always
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
environment:
|
||||
- GITEA_INSTANCE_URL=http://gitea.local:3000
|
||||
- GITEA_RUNNER_NAME=runner-01-ci-vm
|
||||
- GITEA_RUNNER_LABELS=production-ready:host
|
||||
- GITEA_RUNNER_REGISTRATION_TOKEN=jzLi65hxB1Rt2RgIGFglXB5RjW9ggCbq9UFX3NrS
|
||||
```
|
||||
|
||||
**Puntos clave**:
|
||||
- `production-ready:host` - La etiqueta `:host` es crucial para acceso a Docker
|
||||
- Volumen del socket de Docker montado
|
||||
- URL de Gitea correcta
|
||||
|
||||
---
|
||||
|
||||
## Verificación Post-Despliegue
|
||||
|
||||
Después de un despliegue exitoso, verifica:
|
||||
|
||||
```bash
|
||||
# 1. Estado de contenedores
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
|
||||
# 2. Logs recientes
|
||||
docker compose -f docker-compose_prod.yml logs --tail=50
|
||||
|
||||
# 3. Acceso a la aplicación
|
||||
curl -I https://franciaocupada.martivich.es
|
||||
curl -I https://api.franciaocupada.martivich.es
|
||||
|
||||
# 4. Estado del runner
|
||||
docker ps | grep gitea-act_runner
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Recursos Útiles
|
||||
|
||||
- **Gitea Actions Docs**: https://docs.gitea.com/usage/actions/overview
|
||||
- **Act Runner**: https://gitea.com/gitea/act_runner
|
||||
- **GitHub Actions Syntax**: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions
|
||||
|
||||
---
|
||||
|
||||
## Próximas Mejoras Recomendadas
|
||||
|
||||
1. **Caché de Node.js**: Cachear la instalación de Node.js para acelerar futuros builds
|
||||
2. **Tests Automatizados**: Agregar tests antes del deploy
|
||||
3. **Rollback Automático**: Implementar rollback si el deploy falla
|
||||
4. **Notificaciones**: Configurar notificaciones de éxito/fallo (email, Discord, etc.)
|
||||
5. **Health Checks**: Verificar que la app responde correctamente antes de dar por exitoso el deploy
|
||||
6. **Backup de DB**: Hacer backup de la base de datos antes de cada deploy
|
||||
7. **Staging Environment**: Crear un ambiente de staging para probar antes de producción
|
||||
56
bitacoraDelProyecto/2025-12-10_bitacora.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# Bitácora del Proyecto: Francia Ocupada (La Resistencia)
|
||||
**Fecha:** 10 de Diciembre de 2025
|
||||
**Versión actual:** v1.0
|
||||
|
||||
---
|
||||
|
||||
## 1. Resumen de Actividades Realizadas
|
||||
|
||||
### 🔧 Corrección de Entornos (Desarrollo vs Producción)
|
||||
- **Problema detectado:** La aplicación en producción (`franciaocupada.martivich.es`) intentaba conectarse a `localhost`, provocando advertencias de seguridad en el navegador y fallos de conexión desde redes externas.
|
||||
- **Solución implementada:**
|
||||
- Se han separado los archivos de orquestación de Docker:
|
||||
1. `docker-compose.yml`: Configurado para desarrollo local (`localhost:3000` y `localhost:4000`).
|
||||
2. `docker-compose_prod.yml`: Nuevo archivo optimizado para producción.
|
||||
- Se configuraron las variables de entorno `NEXT_PUBLIC_API_URL` y `CORS_ORIGIN` para apuntar al dominio público en el archivo de producción.
|
||||
|
||||
### 🌐 Configuración de Proxy Inverso (Nginx Proxy Manager)
|
||||
- Se ha definido la arquitectura correcta para el despliegue tras un Nginx Proxy Manager:
|
||||
- **Frontend:** `franciaocupada.martivich.es` -> Redirige al contenedor cliente (puerto 3000).
|
||||
- **Backend (API):** `api.franciaocupada.martivich.es` -> Redirige al contenedor servidor (puerto 4000).
|
||||
- Se habilitó soporte para **WebSockets** y **SSL** (Force SSL, HTTP/2) en el proxy.
|
||||
|
||||
### 📦 Gestión de Versiones (Git & Gitea)
|
||||
- **Release v1.0:**
|
||||
- Se creó un commit de consolidación ("Release v1.0").
|
||||
- Se etiquetó la versión con `git tag v1.0`.
|
||||
- Se normalizó la rama principal renombrándola de `fix-gameboard` a `main`.
|
||||
- **Configuración del Repositorio Remoto:**
|
||||
- Se cambió el nombre del repositorio en Gitea a **FranciaOcupada**.
|
||||
- Se configuró la autenticación mediante **HTTPS + Token Personal** (más didáctico para la docencia) en lugar de SSH.
|
||||
- Se configuró el `credential.helper store` para evitar reintroducir credenciales constantemente.
|
||||
- Se añadió `GiteaToken.txt` al `.gitignore` por seguridad.
|
||||
- Se realizó la subida inicial completa (`git push -u origin main` y `git push origin --tags`).
|
||||
|
||||
---
|
||||
|
||||
## 2. Próximos Pasos (Roadmap)
|
||||
|
||||
### 🚀 Implementación de CI/CD (Gitea Actions)
|
||||
El siguiente gran objetivo es automatizar el ciclo de vida del desarrollo.
|
||||
|
||||
#### Pipeline de Integración Continua (Local/Dev)
|
||||
- **Objetivo:** Ejecutar pruebas automáticas al hacer push para asegurar la calidad del código.
|
||||
- **Herramientas:** Gitea Actions (compatible con sintaxis GitHub Actions).
|
||||
|
||||
#### Pipeline de Despliegue Continuo (Producción)
|
||||
- **Objetivo:** Desplegar automáticamente la nueva versión en el servidor cuando se publique un Tag (ej: `v1.1`).
|
||||
- **Tareas pendientes:**
|
||||
1. Habilitar/Verificar Runners en Gitea.
|
||||
2. Crear el archivo workflow `.gitea/workflows/deploy.yaml`.
|
||||
3. Configurar la construcción de imágenes Docker y su subida al Gitea Container Registry.
|
||||
4. Automatizar el comando de despliegue en el servidor remoto vía SSH (`docker compose -f ... up -d`).
|
||||
|
||||
### 🛠️ Mejoras Futuras
|
||||
- Revisar logs de producción para posibles ajustes de rendimiento.
|
||||
- Documentar el proceso de alta de nuevos desarrolladores (alumnos).
|
||||
5870
client/package-lock.json
generated
Normal file
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "resistencia-client",
|
||||
"version": "0.1.0",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -19,7 +19,7 @@
|
||||
"tailwind-merge": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20",
|
||||
"@types/node": "^20.19.27",
|
||||
"@types/react": "^18",
|
||||
"@types/react-dom": "^18",
|
||||
"autoprefixer": "^10.0.1",
|
||||
|
||||
BIN
client/public/assets/audio/Rondas (Copiar).ogg
Normal file
BIN
client/public/assets/audio/Rondas.mp3
Normal file
BIN
client/public/assets/audio/Rondas_corto.mp3
Normal file
BIN
client/public/assets/audio/Rondas_original.mp3
Normal file
BIN
client/public/assets/images/missions/mission1.png
Normal file
|
After Width: | Height: | Size: 985 KiB |
BIN
client/public/assets/images/missions/mission2-p2.png
Normal file
|
After Width: | Height: | Size: 1.3 MiB |
BIN
client/public/assets/images/missions/mission2.png
Normal file
|
After Width: | Height: | Size: 3.3 MiB |
BIN
client/public/assets/images/missions/mission3.png
Normal file
|
After Width: | Height: | Size: 1.1 MiB |
BIN
client/public/assets/images/missions/mission4.png
Normal file
|
After Width: | Height: | Size: 920 KiB |
BIN
client/public/assets/images/missions/mission5.png
Normal file
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 764 KiB |
|
After Width: | Height: | Size: 720 KiB |
|
After Width: | Height: | Size: 680 KiB |
|
After Width: | Height: | Size: 716 KiB |
|
After Width: | Height: | Size: 691 KiB |
BIN
client/public/assets/images/missions/quadrades/mission1.png
Normal file
|
After Width: | Height: | Size: 893 KiB |
BIN
client/public/assets/images/missions/quadrades/mission2.jpg
Normal file
|
After Width: | Height: | Size: 2.1 MiB |
BIN
client/public/assets/images/missions/quadrades/mission2.png
Normal file
|
After Width: | Height: | Size: 3.5 MiB |
BIN
client/public/assets/images/missions/quadrades/mission3.png
Normal file
|
After Width: | Height: | Size: 1.0 MiB |
BIN
client/public/assets/images/missions/quadrades/mission4.png
Normal file
|
After Width: | Height: | Size: 875 KiB |
BIN
client/public/assets/images/missions/quadrades/mission5.jpg
Normal file
|
After Width: | Height: | Size: 366 KiB |
BIN
client/public/assets/images/missions/quadrades/mission5.png
Normal file
|
After Width: | Height: | Size: 1.7 MiB |
BIN
client/public/assets/images/missions/thumbdown.jpg
Normal file
|
After Width: | Height: | Size: 307 KiB |
BIN
client/public/assets/images/missions/thumbup.jpg
Normal file
|
After Width: | Height: | Size: 219 KiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.4 MiB |
BIN
client/public/assets/images/tokens/lastshot.jpg
Normal file
|
After Width: | Height: | Size: 197 KiB |
BIN
client/public/assets/images/tokens/originals/accept_leader.png
Normal file
|
After Width: | Height: | Size: 1.0 MiB |
BIN
client/public/assets/images/tokens/originals/deny_leader.png
Normal file
|
After Width: | Height: | Size: 1.0 MiB |
BIN
client/public/assets/images/tokens/paret1.png
Normal file
|
After Width: | Height: | Size: 202 KiB |
BIN
client/public/assets/images/tokens/paret2.jpg
Normal file
|
After Width: | Height: | Size: 232 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
BIN
client/public/assets/images/tokens/vote_aprove.png
Normal file
|
After Width: | Height: | Size: 1.4 MiB |
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.3 MiB |
BIN
client/public/assets/images/tokens/vote_reject_original.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 872 KiB After Width: | Height: | Size: 1.5 MiB |
BIN
client/public/assets/images/ui/bg_game_original.png
Normal file
|
After Width: | Height: | Size: 872 KiB |
BIN
client/public/assets/images/ui/logo copy.png
Normal file
|
After Width: | Height: | Size: 558 KiB |
|
Before Width: | Height: | Size: 558 KiB After Width: | Height: | Size: 581 KiB |
BIN
client/public/assets/images/ui/portada.png
Normal file
|
After Width: | Height: | Size: 852 KiB |
@@ -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',
|
||||
}
|
||||
|
||||
|
||||
@@ -100,6 +100,7 @@ export default function Home() {
|
||||
<div className="z-10 bg-black/80 p-8 rounded border border-white/20 max-w-2xl w-full mx-4 backdrop-blur-md">
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-3xl font-bold text-yellow-500 mb-2 uppercase tracking-widest">Sala de Espera</h2>
|
||||
<p className="text-xl font-bold text-white mb-1">{gameState.roomName}</p>
|
||||
<p className="text-gray-400">Operación en curso. Esperando activación...</p>
|
||||
</div>
|
||||
|
||||
@@ -173,7 +174,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' && (
|
||||
|
||||
@@ -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,13 @@ 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);
|
||||
|
||||
// Estado para controlar el colapso del panel de jugadores
|
||||
const [isPlayersCollapsed, setIsPlayersCollapsed] = useState(false);
|
||||
|
||||
// Estado para controlar el colapso del historial de misiones
|
||||
const [isHistoryCollapsed, setIsHistoryCollapsed] = useState(false);
|
||||
|
||||
|
||||
// Timer para avanzar automáticamente en REVEAL_ROLE
|
||||
@@ -41,6 +49,25 @@ 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 durante MISSION_RESULT
|
||||
useEffect(() => {
|
||||
if (gameState.phase === GamePhase.MISSION_RESULT) {
|
||||
setShowBoard(true);
|
||||
} else {
|
||||
setShowBoard(false);
|
||||
}
|
||||
}, [gameState.phase]);
|
||||
|
||||
|
||||
const currentPlayer = gameState.players.find(p => p.id === currentPlayerId);
|
||||
const isLeader = gameState.currentLeaderId === currentPlayerId; // FIX: Usar currentLeaderId del estado
|
||||
@@ -66,11 +93,20 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
|
||||
// Coordenadas porcentuales de los hexágonos de misión en el mapa
|
||||
const missionCoords = [
|
||||
{ left: '12%', top: '55%' }, // Misión 1
|
||||
{ left: '28%', top: '15%' }, // Misión 2
|
||||
{ left: '52%', top: '25%' }, // Misión 3
|
||||
{ left: '42%', top: '70%' }, // Misión 4
|
||||
{ left: '82%', top: '40%' }, // Misión 5
|
||||
{ left: '18%', top: '60%' }, // Misión 1 - Abajo izquierda
|
||||
{ left: '25%', top: '18%' }, // Misión 2 - Arriba izquierda
|
||||
{ left: '50%', top: '75%' }, // Misión 3 - Abajo centro
|
||||
{ left: '50%', top: '30%' }, // Misión 4 - Centro
|
||||
{ left: '80%', top: '45%' }, // Misión 5 - Derecha
|
||||
];
|
||||
|
||||
// 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 ---
|
||||
@@ -85,16 +121,18 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
<div className="absolute inset-0 bg-black/40" />
|
||||
</div>
|
||||
|
||||
<h1 className="z-10 text-5xl font-bold uppercase tracking-[0.3em] mb-8 text-yellow-500 drop-shadow-lg text-center">
|
||||
Guerra Total
|
||||
<h1 className="z-10 text-[2.55rem] font-bold uppercase tracking-[0.3em] mb-8 text-yellow-500 drop-shadow-lg text-center">
|
||||
Traición en París
|
||||
</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 +150,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`;
|
||||
@@ -177,16 +215,10 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
<motion.div
|
||||
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);
|
||||
}
|
||||
}}
|
||||
dragElastic={0.5}
|
||||
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
|
||||
@@ -207,46 +239,52 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
// FASE ROLL CALL
|
||||
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="relative w-full h-screen flex flex-col 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" />
|
||||
</div>
|
||||
|
||||
<div className="z-10 w-full max-w-5xl px-4">
|
||||
<h2 className="text-3xl text-center mb-12 uppercase tracking-[0.2em] text-gray-300 border-b border-gray-600 pb-4">
|
||||
{/* --- 1. SECCIÓN SUPERIOR: TÍTULO (20-25% altura) --- */}
|
||||
<div className="relative z-10 w-full h-[20vh] flex items-center justify-center px-4 border-b border-gray-600/50 bg-black/20 backdrop-blur-sm">
|
||||
<h2 className="text-2xl md:text-3xl lg:text-4xl text-center uppercase tracking-[0.2em] text-gray-300 drop-shadow-lg">
|
||||
Pasando Lista...
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
{/* --- 2. SECCIÓN INFERIOR: JUGADORES (Resto de altura) --- */}
|
||||
<div className="relative z-10 w-full flex-1 overflow-y-auto p-4 flex flex-col items-center">
|
||||
{isHost && (
|
||||
<audio
|
||||
src="/assets/audio/Rondas.ogg"
|
||||
src="/assets/audio/Rondas.mp3"
|
||||
autoPlay
|
||||
onEnded={() => actions.finishRollCall()} // Host avanza cuando acaba audio
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8">
|
||||
<div className="w-full max-w-6xl grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 md:gap-8 justify-items-center content-center py-4">
|
||||
{gameState.players.map((p, i) => {
|
||||
// Asignar avatar determinista basado en charCode
|
||||
const avatarIdx = (p.name.length % 3) + 1;
|
||||
return (
|
||||
<motion.div
|
||||
key={p.id}
|
||||
initial={{ opacity: 0, scale: 0.8 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: i * 0.3 }} // Aparecen uno a uno
|
||||
className="flex flex-col items-center gap-3"
|
||||
className="flex flex-col items-center gap-1 md:gap-3 w-full"
|
||||
>
|
||||
<div className="w-32 h-32 rounded-full border-4 border-gray-400 overflow-hidden relative shadow-2xl bg-black">
|
||||
{/* Avatar Responsive */}
|
||||
<div className="w-20 h-20 md:w-32 md:h-32 rounded-full border-2 md: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"
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-black/80 px-4 py-1 rounded border border-white/20 text-xl font-bold text-yellow-500 uppercase">
|
||||
{/* Nombre Responsive */}
|
||||
<div className="bg-black/80 px-2 py-0.5 md:px-4 md:py-1 rounded border border-white/20 text-xs md:text-xl font-bold text-yellow-500 uppercase text-center w-full truncate max-w-[120px] md:max-w-none">
|
||||
{p.name}
|
||||
</div>
|
||||
</motion.div>
|
||||
@@ -259,83 +297,150 @@ 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="relative w-full h-screen flex flex-col overflow-hidden">
|
||||
{/* Fondo */}
|
||||
<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">
|
||||
{/* Contenedor principal */}
|
||||
<div className="relative z-10 w-full flex flex-col items-center pb-32">
|
||||
|
||||
{/* --- 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 - centrado verticalmente */}
|
||||
<div className="absolute top-1/3 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>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
/* 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,22 +462,22 @@ 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>
|
||||
|
||||
{gameState.leaderVotes?.[currentPlayerId] === undefined ? (
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteLeader(true)} className="group">
|
||||
<div className="w-40 h-60 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<div className="w-32 h-32 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<Image src="/assets/images/tokens/accept_leader.png" alt="Accept Leader" fill className="object-contain" />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded uppercase tracking-widest">ACEPTAR</span>
|
||||
</button>
|
||||
<button onClick={() => actions.voteLeader(false)} className="group">
|
||||
<div className="w-40 h-60 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<div className="w-32 h-32 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<Image src="/assets/images/tokens/deny_leader.png" alt="Deny Leader" fill className="object-contain" />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded uppercase tracking-widest">RECHAZAR</span>
|
||||
@@ -396,27 +501,31 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
className="flex flex-col items-center gap-6 w-full max-w-4xl"
|
||||
>
|
||||
{/* Información del líder */}
|
||||
<div className="bg-yellow-600/90 text-black p-4 rounded-lg shadow-xl border-4 border-yellow-400 w-full text-center">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<Image src="/assets/images/tokens/token_leader.png" alt="Leader" width={40} height={40} />
|
||||
<div>
|
||||
<div className="text-sm uppercase tracking-wider font-bold">Líder Actual</div>
|
||||
<div className="text-2xl font-bold">
|
||||
{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name || 'Desconocido'}
|
||||
{/* Información del líder - SOLO para NO líderes */}
|
||||
{!isLeader && (
|
||||
<div className="bg-yellow-600/90 text-black p-2 rounded-lg shadow-xl border-4 border-yellow-400 w-full text-center mb-2">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<div>
|
||||
<div className="text-xs uppercase tracking-wider font-bold">Líder Actual</div>
|
||||
<div className="text-xl font-bold">
|
||||
{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name || 'Desconocido'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Image src="/assets/images/tokens/token_leader.png" alt="Leader" width={40} height={40} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mensaje para el líder o para los demás */}
|
||||
<div className="bg-paper-bg text-black p-6 rounded shadow-2xl rotate-1 w-full text-center">
|
||||
<h2 className="text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue">
|
||||
{/* Mensaje para el líder o para los demás */}
|
||||
<div className="bg-paper-bg text-black p-4 md:p-6 rounded shadow-2xl w-full text-center">
|
||||
<h2 className="text-xl md:text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue">
|
||||
{isLeader ? '🎯 TU TURNO: ELIGE TU EQUIPO' : '⏳ ESPERANDO AL LÍDER...'}
|
||||
</h2>
|
||||
<p className="mb-4 font-serif italic text-gray-700">
|
||||
Se necesitan <span className="font-bold text-red-700 text-xl">{currentQuestSize} agentes</span> para la misión #{gameState.currentRound}.
|
||||
</p>
|
||||
{isLeader && (
|
||||
<p className="mb-4 font-serif italic text-gray-700">
|
||||
Se necesitan <span className="font-bold text-red-700 text-xl">{currentQuestSize} agentes</span> para la misión #{gameState.currentRound}.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Contador de seleccionados */}
|
||||
{isLeader && (
|
||||
@@ -468,19 +577,23 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!currentPlayer?.hasVoted ? (
|
||||
{gameState.teamVotes[currentPlayerId] === undefined ? (
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteTeam(true)} className="group">
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4">
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Approve" width={100} height={100} />
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex flex-col items-center justify-center border-2 border-blue-500 group-hover:border-blue-400 group-hover:shadow-blue-500/50 transition-all transform group-hover:-translate-y-4 relative overflow-hidden p-2">
|
||||
<span className="text-blue-600 font-bold text-sm uppercase tracking-wider mb-1 z-10">Éxito</span>
|
||||
<div className="relative w-full h-full flex items-center justify-center">
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Approve" fill className="object-contain" />
|
||||
</div>
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded">APROBAR</span>
|
||||
</button>
|
||||
<button onClick={() => actions.voteTeam(false)} className="group">
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4">
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Reject" width={100} height={100} />
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex flex-col items-center justify-center border-2 border-red-500 group-hover:border-red-400 group-hover:shadow-red-500/50 transition-all transform group-hover:-translate-y-4 relative overflow-hidden p-2">
|
||||
<span className="text-red-600 font-bold text-sm uppercase tracking-wider mb-1 z-10">Fracaso</span>
|
||||
<div className="relative w-full h-full flex items-center justify-center">
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Reject" fill className="object-contain" />
|
||||
</div>
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded">RECHAZAR</span>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
@@ -496,26 +609,19 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
{gameState.phase === GamePhase.MISSION && (
|
||||
<motion.div
|
||||
key="mission"
|
||||
className="fixed inset-0 flex items-center justify-center bg-black/90 z-50"
|
||||
className="fixed inset-0 flex items-start justify-center bg-black/90 z-50 pt-20"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
>
|
||||
{gameState.proposedTeam.includes(currentPlayerId) ? (
|
||||
<div className="flex flex-col items-center gap-8 w-full max-w-6xl px-4">
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-white mb-4 drop-shadow-2xl text-center uppercase tracking-wider animate-pulse">
|
||||
🎯 ¡ESTÁS EN LA MISIÓN!
|
||||
<div className="flex flex-col items-center gap-4 w-full max-w-6xl px-4">
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-white mb-2 drop-shadow-2xl text-center uppercase tracking-wider animate-pulse">
|
||||
🎯 REALIZA LA MISIÓN
|
||||
</h2>
|
||||
<p className="text-white text-xl mb-4 text-center">
|
||||
Elige el resultado de tu participación
|
||||
<p className="text-white text-xl mb-2 text-center">
|
||||
Elige si quieres un éxito o un fracaso
|
||||
</p>
|
||||
|
||||
{/* DEBUG INFO - TEMPORAL */}
|
||||
<div className="text-xs text-gray-400 bg-black/50 p-2 rounded mb-4">
|
||||
Debug: Tu ID: {currentPlayerId} | Equipo: [{gameState.proposedTeam.join(', ')}]
|
||||
<br />
|
||||
Tu facción: {currentPlayer?.faction || 'UNDEFINED'} | Rol: {currentPlayer?.role || 'UNDEFINED'}
|
||||
</div>
|
||||
|
||||
{/* Cartas en orden aleatorio */}
|
||||
<div className="flex gap-12 flex-wrap justify-center">
|
||||
{cardOrder ? (
|
||||
@@ -523,45 +629,53 @@ 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
|
||||
className="w-64 h-96 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-6 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
|
||||
className="w-32 h-48 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-4 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
|
||||
whileHover={{ scale: 1.1, rotate: 3 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={180} height={180} className="drop-shadow-2xl" />
|
||||
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">ÉXITO</span>
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={80} height={80} className="drop-shadow-2xl" />
|
||||
<span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">ÉXITO</span>
|
||||
</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"
|
||||
className="w-32 h-48 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-4 transform transition-all hover:scale-110 hover:-rotate-3 hover:shadow-red-500/50"
|
||||
whileHover={{ scale: 1.1, rotate: -3 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={180} height={180} className="drop-shadow-2xl" />
|
||||
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">SABOTAJE</span>
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={80} height={80} className="drop-shadow-2xl" />
|
||||
<span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">SABOTAJE</span>
|
||||
</motion.div>
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* 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"
|
||||
className="w-32 h-48 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-4 transform transition-all hover:scale-110 hover:-rotate-3 hover:shadow-red-500/50"
|
||||
whileHover={{ scale: 1.1, rotate: -3 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={180} height={180} className="drop-shadow-2xl" />
|
||||
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">SABOTAJE</span>
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Fail" width={80} height={80} className="drop-shadow-2xl" />
|
||||
<span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">SABOTAJE</span>
|
||||
</motion.div>
|
||||
</button>
|
||||
)}
|
||||
@@ -569,16 +683,16 @@ 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
|
||||
className="w-64 h-96 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-6 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
|
||||
className="w-32 h-48 bg-gradient-to-br from-blue-600 to-blue-900 rounded-2xl shadow-2xl border-4 border-blue-400 flex flex-col items-center justify-center p-4 transform transition-all hover:scale-110 hover:rotate-3 hover:shadow-blue-500/50"
|
||||
whileHover={{ scale: 1.1, rotate: 3 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={180} height={180} className="drop-shadow-2xl" />
|
||||
<span className="mt-6 text-white font-bold text-2xl tracking-widest uppercase">ÉXITO</span>
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Success" width={80} height={80} className="drop-shadow-2xl" />
|
||||
<span className="mt-2 text-white font-bold text-lg tracking-widest uppercase">ÉXITO</span>
|
||||
</motion.div>
|
||||
</button>
|
||||
</>
|
||||
@@ -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,16 +721,108 @@ 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>
|
||||
|
||||
{/* JUGADORES (TIENDA DE CAMPAÑA) */}
|
||||
<div className="z-10 w-full overflow-x-auto pb-4">
|
||||
<div className="flex justify-center gap-4 min-w-max px-4">
|
||||
{/* JUGADORES - POSICIONADOS ABSOLUTAMENTE EN EL FONDO */}
|
||||
<motion.div
|
||||
className="fixed bottom-0 left-0 right-0 z-50 bg-black/80 border-t border-white/10 backdrop-blur-md"
|
||||
initial={false}
|
||||
animate={{
|
||||
y: isPlayersCollapsed ? '100%' : '0%'
|
||||
}}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
>
|
||||
{/* Botón de colapso/expansión */}
|
||||
<div className="absolute -top-10 left-1/2 transform -translate-x-1/2">
|
||||
<button
|
||||
onClick={() => setIsPlayersCollapsed(!isPlayersCollapsed)}
|
||||
className="bg-gradient-to-b from-yellow-600 to-yellow-700 hover:from-yellow-500 hover:to-yellow-600 text-white rounded-t-lg px-6 py-2 shadow-lg border-2 border-yellow-500 border-b-0 transition-all hover:shadow-yellow-500/50 flex items-center gap-2"
|
||||
>
|
||||
<motion.svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
animate={{ rotate: isPlayersCollapsed ? 180 : 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M19 9l-7 7-7-7" />
|
||||
</motion.svg>
|
||||
<span className="text-sm font-bold uppercase tracking-wider">
|
||||
{isPlayersCollapsed ? 'Mostrar' : 'Ocultar'}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="w-full px-4 py-2 flex flex-wrap items-center justify-center gap-4">
|
||||
{gameState.players.map((player) => {
|
||||
const isSelected = selectedTeam.includes(player.id);
|
||||
const isMe = player.id === currentPlayerId;
|
||||
@@ -628,16 +835,15 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
key={player.id}
|
||||
onClick={() => isLeader && gameState.phase === GamePhase.TEAM_BUILDING && toggleTeamSelection(player.id)}
|
||||
className={`
|
||||
relative flex flex-col items-center cursor-pointer transition-all duration-300
|
||||
${isSelected ? 'scale-110' : 'scale-100 opacity-80 hover:opacity-100'}
|
||||
`}
|
||||
relative flex flex-col items-center cursor-pointer transition-all duration-300 group
|
||||
${isSelected ? 'scale-110 z-10' : 'scale-100 opacity-70 hover:opacity-100 hover:scale-105'}
|
||||
`}
|
||||
>
|
||||
{/* Avatar */}
|
||||
<div className={`
|
||||
w-16 h-16 rounded-full border-2 overflow-hidden relative shadow-lg bg-black
|
||||
${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30' : 'border-gray-400'}
|
||||
${gameState.currentLeaderId === player.id ? 'ring-2 ring-white' : ''}
|
||||
`}>
|
||||
<div className="relative rounded-full border-2 overflow-hidden shadow-lg bg-black transition-all w-16 h-16
|
||||
${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30 shadow-yellow-400/20' : 'border-gray-500 group-hover:border-gray-300'}
|
||||
${gameState.currentLeaderId === player.id ? 'ring-2 ring-white' : ''}
|
||||
">
|
||||
<Image
|
||||
src={avatarSrc}
|
||||
alt={player.name}
|
||||
@@ -647,7 +853,7 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
|
||||
{/* Icono de Líder */}
|
||||
{gameState.currentLeaderId === player.id && (
|
||||
<div className="absolute bottom-0 right-0 bg-yellow-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-black font-bold border border-white z-10">
|
||||
<div className="absolute bottom-0 right-0 bg-yellow-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-[10px] text-black font-bold border border-white z-20 shadow-sm">
|
||||
L
|
||||
</div>
|
||||
)}
|
||||
@@ -659,62 +865,128 @@ export default function GameBoard({ gameState, currentPlayerId, actions }: GameB
|
||||
gameState.phase === 'mission_reveal' as any ||
|
||||
gameState.phase === 'mission_result' as any
|
||||
) && (
|
||||
<div className="absolute top-0 left-0 bg-green-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-white font-bold border border-white z-10">
|
||||
<div className="absolute top-0 left-0 bg-green-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-white font-bold border border-white z-20">
|
||||
⭐
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Nombre */}
|
||||
<span className={`mt-2 text-xs font-mono px-2 py-0.5 rounded ${isMe ? 'bg-blue-600 text-white' : 'bg-black/50 text-gray-300'}`}>
|
||||
<span className={`
|
||||
mt-1 text-xs font-mono px-2 py-0.5 rounded shadow-sm whitespace-nowrap max-w-[100px] truncate
|
||||
${isMe ? 'bg-blue-600 text-white font-bold' : 'bg-black/60 text-gray-300 border border-white/10'}
|
||||
`}>
|
||||
{player.name}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* HISTÓRICO DE MISIONES (Esquina superior derecha) */}
|
||||
{gameState.missionHistory.length > 0 && (
|
||||
<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>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<motion.div
|
||||
className="fixed top-4 right-0 z-50"
|
||||
initial={false}
|
||||
animate={{
|
||||
x: isHistoryCollapsed ? '0%' : '0%'
|
||||
}}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
>
|
||||
{/* Botón de colapso/expansión */}
|
||||
<motion.button
|
||||
onClick={() => setIsHistoryCollapsed(!isHistoryCollapsed)}
|
||||
className="absolute top-0 bg-gradient-to-l from-yellow-600 to-yellow-700 hover:from-yellow-500 hover:to-yellow-600 text-white rounded-l-lg px-2 py-3 shadow-lg border-2 border-yellow-500 border-r-0 transition-all hover:shadow-yellow-500/50 flex items-center"
|
||||
initial={false}
|
||||
animate={{
|
||||
right: isHistoryCollapsed ? '0px' : '100%'
|
||||
}}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
>
|
||||
<motion.svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
animate={{ rotate: isHistoryCollapsed ? 0 : 180 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M15 19l-7-7 7-7" />
|
||||
</motion.svg>
|
||||
</motion.button>
|
||||
|
||||
{/* Panel del historial */}
|
||||
<motion.div
|
||||
className="bg-black/80 p-3 rounded-lg border border-white/20 backdrop-blur-sm"
|
||||
initial={false}
|
||||
animate={{
|
||||
x: isHistoryCollapsed ? '100%' : '0%'
|
||||
}}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
>
|
||||
<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) => {
|
||||
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 relative z-[60]' : ''}`}
|
||||
title={`Misión ${mission.round}: ${mission.isSuccess ? 'Éxito' : 'Fracaso'} (${mission.successes}✓ ${mission.fails}✗)`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
console.log('Click en misión', idx);
|
||||
setExpandedMission(prev => prev === idx ? 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>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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">
|
||||
<div className="fixed top-5 left-5 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">
|
||||
{timeLeft}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,711 +0,0 @@
|
||||
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';
|
||||
|
||||
interface GameBoardProps {
|
||||
gameState: GameState;
|
||||
currentPlayerId: string;
|
||||
actions: any;
|
||||
}
|
||||
|
||||
export default function GameBoard({ gameState, currentPlayerId, actions }: GameBoardProps) {
|
||||
const [selectedTeam, setSelectedTeam] = useState<string[]>([]);
|
||||
|
||||
// Hooks para FASE REVEAL ROLE
|
||||
const [revealCard, setRevealCard] = useState(false);
|
||||
|
||||
// Timer para avanzar automáticamente en REVEAL_ROLE
|
||||
useEffect(() => {
|
||||
if (gameState.phase === 'reveal_role' as any) {
|
||||
const timer = setTimeout(() => {
|
||||
actions.finishReveal();
|
||||
}, 10000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [gameState.phase, actions]);
|
||||
|
||||
const currentPlayer = gameState.players.find(p => p.id === currentPlayerId);
|
||||
const isLeader = currentPlayer?.isLeader;
|
||||
const config = GAME_CONFIG[gameState.players.length as keyof typeof GAME_CONFIG];
|
||||
const currentQuestSize = config?.quests[gameState.currentRound - 1];
|
||||
|
||||
// Manejar selección de equipo
|
||||
const toggleTeamSelection = (playerId: string) => {
|
||||
if (selectedTeam.includes(playerId)) {
|
||||
setSelectedTeam(selectedTeam.filter(id => id !== playerId));
|
||||
} else {
|
||||
if (selectedTeam.length < currentQuestSize) {
|
||||
setSelectedTeam([...selectedTeam, playerId]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Coordenadas porcentuales de los hexágonos de misión en el mapa
|
||||
const missionCoords = [
|
||||
{ left: '12%', top: '55%' }, // Misión 1
|
||||
{ left: '28%', top: '15%' }, // Misión 2
|
||||
{ left: '52%', top: '25%' }, // Misión 3
|
||||
{ left: '42%', top: '70%' }, // Misión 4
|
||||
{ left: '82%', top: '40%' }, // Misión 5
|
||||
];
|
||||
|
||||
// --- UI/Efectos para FASES TEMPRANAS ---
|
||||
const isHost = gameState.hostId === currentPlayerId;
|
||||
|
||||
// FASE INTRO
|
||||
if (gameState.phase === 'intro' as any) {
|
||||
return (
|
||||
<div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white">
|
||||
<div className="absolute inset-0 z-0">
|
||||
<Image src="/assets/images/ui/bg_intro.png" alt="Battlefield" fill className="object-cover" />
|
||||
<div className="absolute inset-0 bg-black/40" />
|
||||
</div>
|
||||
|
||||
<h1 className="z-10 text-5xl font-bold uppercase tracking-[0.3em] mb-8 text-yellow-500 drop-shadow-lg text-center">
|
||||
Guerra Total
|
||||
</h1>
|
||||
|
||||
{/* Audio Auto-Play */}
|
||||
<audio
|
||||
src="/assets/audio/Intro.ogg"
|
||||
autoPlay
|
||||
onEnded={() => isHost && actions.finishIntro()}
|
||||
/>
|
||||
|
||||
{isHost && (
|
||||
<button
|
||||
onClick={() => actions.finishIntro()}
|
||||
className="z-10 bg-white/20 hover:bg-white/40 border border-white px-6 py-2 rounded text-sm uppercase tracking-widest backdrop-blur-sm transition-all"
|
||||
>
|
||||
Omitir Introducción
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// FASE REVEAL ROLE NO HOOKS HERE
|
||||
|
||||
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
|
||||
|
||||
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') {
|
||||
// Random soldier 1-5
|
||||
const idx = (currentPlayerId.charCodeAt(0) % 5) + 1;
|
||||
roleImage = `/assets/images/characters/good_soldier_${idx}.png`;
|
||||
}
|
||||
else if (role === 'minion') {
|
||||
// Random minion 1-3
|
||||
const idx = (currentPlayerId.charCodeAt(0) % 3) + 1;
|
||||
roleImage = `/assets/images/characters/evil_minion_${idx}.png`;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white font-mono">
|
||||
{/* FONDO (Mismo que Roll Call) */}
|
||||
<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" />
|
||||
</div>
|
||||
|
||||
<div className="z-10 flex flex-col items-center gap-8">
|
||||
<h2 className="text-2xl uppercase tracking-[0.2em] text-gray-300">
|
||||
Tu Identidad Secreta
|
||||
</h2>
|
||||
|
||||
<p className="text-sm text-gray-400 mb-4 animate-pulse">
|
||||
Desliza hacia arriba para revelar
|
||||
</p>
|
||||
|
||||
<div className="relative w-64 h-96 perspective-1000">
|
||||
{/* Carta Revelada (Fondo) */}
|
||||
<div className="absolute inset-0 w-full h-full rounded-xl overflow-hidden shadow-2xl border-4 border-yellow-600 bg-gray-900 flex items-center justify-center">
|
||||
<Image
|
||||
src={roleImage}
|
||||
alt="Role"
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
<div className="absolute bottom-0 w-full bg-black/80 text-center py-2 font-bold text-yellow-500 uppercase">
|
||||
{role?.replace('_', ' ')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Reverso de Carta (Draggable) */}
|
||||
<motion.div
|
||||
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);
|
||||
}
|
||||
}}
|
||||
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
|
||||
src="/assets/images/characters/card_back.png"
|
||||
alt="Card Back"
|
||||
fill
|
||||
className="object-cover pointer-events-none" // Importante: pointer-events-none en la imagen para que no capture el drag
|
||||
/>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// FASE ROLL CALL
|
||||
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" />
|
||||
</div>
|
||||
|
||||
<div className="z-10 w-full max-w-5xl px-4">
|
||||
<h2 className="text-3xl text-center mb-12 uppercase tracking-[0.2em] text-gray-300 border-b border-gray-600 pb-4">
|
||||
Pasando Lista...
|
||||
</h2>
|
||||
|
||||
{isHost && (
|
||||
<audio
|
||||
src="/assets/audio/Rondas.ogg"
|
||||
autoPlay
|
||||
onEnded={() => actions.finishRollCall()} // Host avanza cuando acaba audio
|
||||
/>
|
||||
)}
|
||||
|
||||
<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}
|
||||
initial={{ opacity: 0, scale: 0.8 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: i * 0.3 }} // Aparecen uno a uno
|
||||
className="flex flex-col items-center gap-3"
|
||||
>
|
||||
<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`}
|
||||
alt="Avatar"
|
||||
fill
|
||||
className="object-cover grayscale contrast-125"
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-black/80 px-4 py-1 rounded border border-white/20 text-xl font-bold text-yellow-500 uppercase">
|
||||
{p.name}
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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" />
|
||||
<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"
|
||||
/>
|
||||
|
||||
{/* TOKENS SOBRE EL MAPA */}
|
||||
{missionCoords.map((coord, idx) => {
|
||||
const result = gameState.questResults[idx];
|
||||
const isCurrent = gameState.currentRound === idx + 1;
|
||||
|
||||
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>
|
||||
)}
|
||||
|
||||
{/* 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>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* 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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- ÁREA DE JUEGO (CARTAS Y ACCIONES) --- */}
|
||||
<div className="flex-1 w-full max-w-6xl relative mt-4 px-4">
|
||||
<AnimatePresence mode="wait">
|
||||
|
||||
{/* FASE: VOTACIÓN DE LÍDER */}
|
||||
{gameState.phase === 'vote_leader' as any && (
|
||||
<motion.div
|
||||
key="vote-leader"
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="flex flex-col items-center gap-6"
|
||||
>
|
||||
<div className="bg-black/80 p-4 rounded text-white text-center border border-yellow-500/50 relative">
|
||||
<h3 className="text-xl font-mono mb-2 text-yellow-500 uppercase tracking-widest">
|
||||
Confirmar Líder
|
||||
</h3>
|
||||
<div className="text-2xl font-bold mb-2">
|
||||
¿Aceptas a <span className="text-yellow-400">{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name}</span> como Líder?
|
||||
</div>
|
||||
|
||||
{/* Timer */}
|
||||
{!gameState.leaderVotes?.[currentPlayerId] && (
|
||||
<VotingTimer onTimeout={() => actions.voteLeader(null)} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gameState.leaderVotes?.[currentPlayerId] === undefined ? (
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteLeader(true)} className="group">
|
||||
<div className="w-40 h-60 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<Image src="/assets/images/tokens/accept_leader.png" alt="Accept Leader" fill className="object-contain" />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded uppercase tracking-widest">ACEPTAR</span>
|
||||
</button>
|
||||
<button onClick={() => actions.voteLeader(false)} className="group">
|
||||
<div className="w-40 h-60 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<Image src="/assets/images/tokens/deny_leader.png" alt="Deny Leader" fill className="object-contain" />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded uppercase tracking-widest">RECHAZAR</span>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-white text-xl font-mono animate-pulse bg-black/50 px-6 py-3 rounded-full border border-white/20">
|
||||
VOTO REGISTRADO. ESPERANDO AL RESTO...
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: CONSTRUCCIÓN DE EQUIPO */}
|
||||
{gameState.phase === GamePhase.TEAM_BUILDING && (
|
||||
<motion.div
|
||||
key="team-building"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -20 }}
|
||||
className="bg-paper-bg text-black p-6 rounded shadow-2xl rotate-1 max-w-md w-full text-center"
|
||||
>
|
||||
<h2 className="text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue">
|
||||
{isLeader ? 'TU TURNO: ELIGE EQUIPO' : `ESPERANDO AL LÍDER...`}
|
||||
</h2>
|
||||
<p className="mb-4 font-serif italic text-gray-700">
|
||||
Se necesitan <span className="font-bold text-red-700">{currentQuestSize} agentes</span> para esta misión.
|
||||
</p>
|
||||
|
||||
{isLeader && (
|
||||
<button
|
||||
onClick={() => actions.proposeTeam(selectedTeam)}
|
||||
disabled={selectedTeam.length !== currentQuestSize}
|
||||
className="w-full bg-resistance-blue text-white font-bold py-3 px-4 rounded hover:bg-blue-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed uppercase tracking-widest"
|
||||
>
|
||||
Proponer Equipo
|
||||
</button>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: VOTACIÓN DE EQUIPO */}
|
||||
{gameState.phase === GamePhase.VOTING_TEAM && (
|
||||
<motion.div
|
||||
key="voting"
|
||||
initial={{ scale: 0.8, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="flex flex-col items-center gap-6"
|
||||
>
|
||||
<div className="bg-black/80 p-4 rounded text-white text-center border border-white/20">
|
||||
<h3 className="text-xl font-mono mb-2 text-yellow-500">PROPUESTA DE MISIÓN</h3>
|
||||
<div className="flex gap-2 justify-center">
|
||||
{gameState.proposedTeam.map(id => {
|
||||
const p = gameState.players.find(pl => pl.id === id);
|
||||
return (
|
||||
<div key={id} className="bg-white/10 px-3 py-1 rounded text-sm">
|
||||
{p?.name}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!currentPlayer?.hasVoted ? (
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteTeam(true)} className="group">
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4">
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Approve" width={100} height={100} />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded">APROBAR</span>
|
||||
</button>
|
||||
<button onClick={() => actions.voteTeam(false)} className="group">
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4">
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Reject" width={100} height={100} />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded">RECHAZAR</span>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-white text-xl font-mono animate-pulse">
|
||||
VOTO REGISTRADO. ESPERANDO AL RESTO...
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: MISIÓN */}
|
||||
{gameState.phase === GamePhase.MISSION && (
|
||||
<motion.div key="mission" className="text-center">
|
||||
{gameState.proposedTeam.includes(currentPlayerId) ? (
|
||||
<div className="flex flex-col items-center gap-6">
|
||||
<h2 className="text-3xl font-bold text-white mb-4 drop-shadow-lg">¡ESTÁS EN LA MISIÓN!</h2>
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteMission(true)} className="group">
|
||||
<div className="w-40 h-60 bg-blue-900 rounded-lg shadow-2xl border-2 border-blue-400 flex flex-col items-center justify-center p-4 transform transition-transform hover:scale-105">
|
||||
<Image src="/assets/images/tokens/mission_success.png" alt="Success" width={120} height={120} />
|
||||
<span className="mt-4 text-blue-200 font-bold tracking-widest">ÉXITO</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Solo los malos pueden sabotear */}
|
||||
{currentPlayer?.faction === 'spies' && (
|
||||
<button onClick={() => actions.voteMission(false)} className="group">
|
||||
<div className="w-40 h-60 bg-red-900 rounded-lg shadow-2xl border-2 border-red-400 flex flex-col items-center justify-center p-4 transform transition-transform hover:scale-105">
|
||||
<Image src="/assets/images/tokens/mission_fail.png" alt="Fail" width={120} height={120} />
|
||||
<span className="mt-4 text-red-200 font-bold tracking-widest">SABOTAJE</span>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-white text-2xl font-mono bg-black/50 p-6 rounded">
|
||||
La misión está en curso...<br />
|
||||
<span className="text-sm text-gray-400">Rezando por el éxito.</span>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: REVELACIÓN DE CARTAS */}
|
||||
{gameState.phase === 'mission_reveal' as any && (
|
||||
<MissionReveal
|
||||
votes={gameState.revealedVotes || []}
|
||||
onComplete={() => isHost && actions.finishMissionReveal()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* FASE: RESULTADO DE MISIÓN */}
|
||||
{gameState.phase === 'mission_result' as any && (
|
||||
<MissionResult
|
||||
gameState={gameState}
|
||||
onContinue={() => isHost && actions.finishMissionResult()}
|
||||
/>
|
||||
)}
|
||||
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
|
||||
{/* JUGADORES (TIENDA DE CAMPAÑA) */}
|
||||
<div className="z-10 w-full overflow-x-auto pb-4">
|
||||
<div className="flex justify-center gap-4 min-w-max px-4">
|
||||
{gameState.players.map((player) => {
|
||||
const isSelected = selectedTeam.includes(player.id);
|
||||
const isMe = player.id === currentPlayerId;
|
||||
|
||||
// Avatar logic
|
||||
const avatarSrc = `/assets/images/characters/${player.avatar}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={player.id}
|
||||
onClick={() => isLeader && gameState.phase === GamePhase.TEAM_BUILDING && toggleTeamSelection(player.id)}
|
||||
className={`
|
||||
relative flex flex-col items-center cursor-pointer transition-all duration-300
|
||||
${isSelected ? 'scale-110' : 'scale-100 opacity-80 hover:opacity-100'}
|
||||
`}
|
||||
>
|
||||
{/* Avatar */}
|
||||
<div className={`
|
||||
w-16 h-16 rounded-full border-2 overflow-hidden relative shadow-lg bg-black
|
||||
${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30' : 'border-gray-400'}
|
||||
${player.isLeader ? 'ring-2 ring-white' : ''}
|
||||
`}>
|
||||
<Image
|
||||
src={avatarSrc}
|
||||
alt={player.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
|
||||
{/* Icono de Líder */}
|
||||
{player.isLeader && (
|
||||
<div className="absolute bottom-0 right-0 bg-yellow-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-black font-bold border border-white z-10">
|
||||
L
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Nombre */}
|
||||
<span className={`mt-2 text-xs font-mono px-2 py-0.5 rounded ${isMe ? 'bg-blue-600 text-white' : 'bg-black/50 text-gray-300'}`}>
|
||||
{player.name}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* HISTÓRICO DE MISIONES (Esquina superior derecha) */}
|
||||
{gameState.missionHistory.length > 0 && (
|
||||
<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>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Subcomponente para el Timer de Votación
|
||||
function VotingTimer({ onTimeout }: { onTimeout: () => void }) {
|
||||
const [timeLeft, setTimeLeft] = useState(10);
|
||||
|
||||
useEffect(() => {
|
||||
if (timeLeft <= 0) {
|
||||
onTimeout();
|
||||
return;
|
||||
}
|
||||
const interval = setInterval(() => setTimeLeft(t => t - 1), 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [timeLeft, onTimeout]);
|
||||
|
||||
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">
|
||||
{timeLeft}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Componente para revelar cartas una a una
|
||||
function MissionReveal({ votes, onComplete }: { votes: boolean[], onComplete: () => void }) {
|
||||
const [revealedCount, setRevealedCount] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (revealedCount < votes.length) {
|
||||
const timer = setTimeout(() => {
|
||||
setRevealedCount(c => c + 1);
|
||||
}, 2000); // 2 segundos entre carta y carta
|
||||
return () => clearTimeout(timer);
|
||||
} else if (revealedCount === votes.length && votes.length > 0) {
|
||||
// Todas reveladas, esperar 2s más y avanzar
|
||||
const timer = setTimeout(() => {
|
||||
onComplete();
|
||||
}, 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [revealedCount, votes.length, onComplete]);
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key="mission-reveal"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="flex flex-col items-center gap-8"
|
||||
>
|
||||
<h2 className="text-3xl font-bold text-white uppercase tracking-widest">
|
||||
Revelando Votos...
|
||||
</h2>
|
||||
|
||||
<div className="flex gap-4 flex-wrap justify-center">
|
||||
{votes.slice(0, revealedCount).map((vote, idx) => (
|
||||
<motion.div
|
||||
key={idx}
|
||||
initial={{ scale: 0, rotateY: 180 }}
|
||||
animate={{ scale: 1, rotateY: 0 }}
|
||||
transition={{ type: "spring", stiffness: 200 }}
|
||||
className="relative w-32 h-48"
|
||||
>
|
||||
<Image
|
||||
src={vote ? "/assets/images/tokens/mission_success.png" : "/assets/images/tokens/mission_fail.png"}
|
||||
alt={vote ? "Éxito" : "Sabotaje"}
|
||||
fill
|
||||
className="object-contain drop-shadow-2xl"
|
||||
/>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="text-white text-lg font-mono">
|
||||
{revealedCount} / {votes.length} cartas reveladas
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
// Componente para mostrar el resultado de la misión
|
||||
function MissionResult({ gameState, onContinue }: { gameState: any, onContinue: () => void }) {
|
||||
const currentMission = gameState.missionHistory[gameState.missionHistory.length - 1];
|
||||
const isHost = gameState.hostId === gameState.players[0]?.id; // Simplificado
|
||||
|
||||
useEffect(() => {
|
||||
// Auto-avanzar después de 5 segundos
|
||||
const timer = setTimeout(() => {
|
||||
onContinue();
|
||||
}, 5000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [onContinue]);
|
||||
|
||||
if (!currentMission) return null;
|
||||
|
||||
const { isSuccess, successes, fails, team, round } = currentMission;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key="mission-result"
|
||||
initial={{ scale: 0.8, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.8, opacity: 0 }}
|
||||
className="flex flex-col items-center gap-6 p-8 bg-black/90 rounded-xl border-4 max-w-2xl mx-auto"
|
||||
style={{ borderColor: isSuccess ? '#3b82f6' : '#ef4444' }}
|
||||
>
|
||||
{/* Título */}
|
||||
<div className="text-center">
|
||||
<h2 className="text-5xl font-bold mb-2 uppercase tracking-widest" style={{ color: isSuccess ? '#3b82f6' : '#ef4444' }}>
|
||||
{isSuccess ? '✓ MISIÓN EXITOSA' : '✗ MISIÓN FALLIDA'}
|
||||
</h2>
|
||||
<p className="text-gray-400 text-lg">Misión #{round}</p>
|
||||
</div>
|
||||
|
||||
{/* Estadísticas */}
|
||||
<div className="flex gap-8 text-center">
|
||||
<div className="bg-blue-900/30 p-4 rounded-lg border border-blue-500/50">
|
||||
<div className="text-4xl font-bold text-blue-400">{successes}</div>
|
||||
<div className="text-sm text-gray-300 uppercase">Éxitos</div>
|
||||
</div>
|
||||
<div className="bg-red-900/30 p-4 rounded-lg border border-red-500/50">
|
||||
<div className="text-4xl font-bold text-red-400">{fails}</div>
|
||||
<div className="text-sm text-gray-300 uppercase">Sabotajes</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Equipo */}
|
||||
<div className="w-full">
|
||||
<h3 className="text-xl text-white mb-3 text-center uppercase tracking-wider">Equipo de Misión:</h3>
|
||||
<div className="flex gap-3 justify-center flex-wrap">
|
||||
{team.map((playerId: string) => {
|
||||
const player = gameState.players.find((p: any) => p.id === playerId);
|
||||
return (
|
||||
<div key={playerId} className="bg-white/10 px-4 py-2 rounded-full border border-white/20 text-white text-sm font-mono">
|
||||
{player?.name || 'Desconocido'}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mensaje */}
|
||||
<div className="text-center text-gray-300 text-sm animate-pulse">
|
||||
Continuando en breve...
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -1,544 +0,0 @@
|
||||
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';
|
||||
|
||||
interface GameBoardProps {
|
||||
gameState: GameState;
|
||||
currentPlayerId: string;
|
||||
actions: any;
|
||||
}
|
||||
|
||||
export default function GameBoard({ gameState, currentPlayerId, actions }: GameBoardProps) {
|
||||
const [selectedTeam, setSelectedTeam] = useState<string[]>([]);
|
||||
|
||||
// Hooks para FASE REVEAL ROLE
|
||||
const [revealCard, setRevealCard] = useState(false);
|
||||
|
||||
// Timer para avanzar automáticamente en REVEAL_ROLE
|
||||
useEffect(() => {
|
||||
if (gameState.phase === 'reveal_role' as any) {
|
||||
const timer = setTimeout(() => {
|
||||
actions.finishReveal();
|
||||
}, 10000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [gameState.phase, actions]);
|
||||
|
||||
const currentPlayer = gameState.players.find(p => p.id === currentPlayerId);
|
||||
const isLeader = currentPlayer?.isLeader;
|
||||
const config = GAME_CONFIG[gameState.players.length as keyof typeof GAME_CONFIG];
|
||||
const currentQuestSize = config?.quests[gameState.currentRound - 1];
|
||||
|
||||
// Manejar selección de equipo
|
||||
const toggleTeamSelection = (playerId: string) => {
|
||||
if (selectedTeam.includes(playerId)) {
|
||||
setSelectedTeam(selectedTeam.filter(id => id !== playerId));
|
||||
} else {
|
||||
if (selectedTeam.length < currentQuestSize) {
|
||||
setSelectedTeam([...selectedTeam, playerId]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Coordenadas porcentuales de los hexágonos de misión en el mapa
|
||||
const missionCoords = [
|
||||
{ left: '12%', top: '55%' }, // Misión 1
|
||||
{ left: '28%', top: '15%' }, // Misión 2
|
||||
{ left: '52%', top: '25%' }, // Misión 3
|
||||
{ left: '42%', top: '70%' }, // Misión 4
|
||||
{ left: '82%', top: '40%' }, // Misión 5
|
||||
];
|
||||
|
||||
// --- UI/Efectos para FASES TEMPRANAS ---
|
||||
const isHost = gameState.hostId === currentPlayerId;
|
||||
|
||||
// FASE INTRO
|
||||
if (gameState.phase === 'intro' as any) {
|
||||
return (
|
||||
<div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white">
|
||||
<div className="absolute inset-0 z-0">
|
||||
<Image src="/assets/images/ui/bg_intro.png" alt="Battlefield" fill className="object-cover" />
|
||||
<div className="absolute inset-0 bg-black/40" />
|
||||
</div>
|
||||
|
||||
<h1 className="z-10 text-5xl font-bold uppercase tracking-[0.3em] mb-8 text-yellow-500 drop-shadow-lg text-center">
|
||||
Guerra Total
|
||||
</h1>
|
||||
|
||||
{/* Audio Auto-Play */}
|
||||
<audio
|
||||
src="/assets/audio/Intro.ogg"
|
||||
autoPlay
|
||||
onEnded={() => isHost && actions.finishIntro()}
|
||||
/>
|
||||
|
||||
{isHost && (
|
||||
<button
|
||||
onClick={() => actions.finishIntro()}
|
||||
className="z-10 bg-white/20 hover:bg-white/40 border border-white px-6 py-2 rounded text-sm uppercase tracking-widest backdrop-blur-sm transition-all"
|
||||
>
|
||||
Omitir Introducción
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// FASE REVEAL ROLE NO HOOKS HERE
|
||||
|
||||
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
|
||||
|
||||
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') {
|
||||
// Random soldier 1-5
|
||||
const idx = (currentPlayerId.charCodeAt(0) % 5) + 1;
|
||||
roleImage = `/assets/images/characters/good_soldier_${idx}.png`;
|
||||
}
|
||||
else if (role === 'minion') {
|
||||
// Random minion 1-3
|
||||
const idx = (currentPlayerId.charCodeAt(0) % 3) + 1;
|
||||
roleImage = `/assets/images/characters/evil_minion_${idx}.png`;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative w-full h-screen flex flex-col items-center justify-center bg-black overflow-hidden text-white font-mono">
|
||||
{/* FONDO (Mismo que Roll Call) */}
|
||||
<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" />
|
||||
</div>
|
||||
|
||||
<div className="z-10 flex flex-col items-center gap-8">
|
||||
<h2 className="text-2xl uppercase tracking-[0.2em] text-gray-300">
|
||||
Tu Identidad Secreta
|
||||
</h2>
|
||||
|
||||
<p className="text-sm text-gray-400 mb-4 animate-pulse">
|
||||
Desliza hacia arriba para revelar
|
||||
</p>
|
||||
|
||||
<div className="relative w-64 h-96 perspective-1000">
|
||||
{/* Carta Revelada (Fondo) */}
|
||||
<div className="absolute inset-0 w-full h-full rounded-xl overflow-hidden shadow-2xl border-4 border-yellow-600 bg-gray-900 flex items-center justify-center">
|
||||
<Image
|
||||
src={roleImage}
|
||||
alt="Role"
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
<div className="absolute bottom-0 w-full bg-black/80 text-center py-2 font-bold text-yellow-500 uppercase">
|
||||
{role?.replace('_', ' ')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Reverso de Carta (Draggable) */}
|
||||
<motion.div
|
||||
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);
|
||||
}
|
||||
}}
|
||||
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
|
||||
src="/assets/images/characters/card_back.png"
|
||||
alt="Card Back"
|
||||
fill
|
||||
className="object-cover pointer-events-none" // Importante: pointer-events-none en la imagen para que no capture el drag
|
||||
/>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// FASE ROLL CALL
|
||||
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" />
|
||||
</div>
|
||||
|
||||
<div className="z-10 w-full max-w-5xl px-4">
|
||||
<h2 className="text-3xl text-center mb-12 uppercase tracking-[0.2em] text-gray-300 border-b border-gray-600 pb-4">
|
||||
Pasando Lista...
|
||||
</h2>
|
||||
|
||||
{isHost && (
|
||||
<audio
|
||||
src="/assets/audio/Rondas.ogg"
|
||||
autoPlay
|
||||
onEnded={() => actions.finishRollCall()} // Host avanza cuando acaba audio
|
||||
/>
|
||||
)}
|
||||
|
||||
<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}
|
||||
initial={{ opacity: 0, scale: 0.8 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: i * 0.3 }} // Aparecen uno a uno
|
||||
className="flex flex-col items-center gap-3"
|
||||
>
|
||||
<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`}
|
||||
alt="Avatar"
|
||||
fill
|
||||
className="object-cover grayscale contrast-125"
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-black/80 px-4 py-1 rounded border border-white/20 text-xl font-bold text-yellow-500 uppercase">
|
||||
{p.name}
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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" />
|
||||
<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"
|
||||
/>
|
||||
|
||||
{/* TOKENS SOBRE EL MAPA */}
|
||||
{missionCoords.map((coord, idx) => {
|
||||
const result = gameState.questResults[idx];
|
||||
const isCurrent = gameState.currentRound === idx + 1;
|
||||
|
||||
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>
|
||||
)}
|
||||
|
||||
{/* 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>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* 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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* --- ÁREA DE JUEGO (CARTAS Y ACCIONES) --- */}
|
||||
<div className="flex-1 w-full max-w-6xl relative mt-4 px-4">
|
||||
<AnimatePresence mode="wait">
|
||||
|
||||
{/* FASE: VOTACIÓN DE LÍDER */}
|
||||
{gameState.phase === 'vote_leader' as any && (
|
||||
<motion.div
|
||||
key="vote-leader"
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="flex flex-col items-center gap-6"
|
||||
>
|
||||
<div className="bg-black/80 p-4 rounded text-white text-center border border-yellow-500/50 relative">
|
||||
<h3 className="text-xl font-mono mb-2 text-yellow-500 uppercase tracking-widest">
|
||||
Confirmar Líder
|
||||
</h3>
|
||||
<div className="text-2xl font-bold mb-2">
|
||||
¿Aceptas a <span className="text-yellow-400">{gameState.players.find(p => p.id === gameState.currentLeaderId)?.name}</span> como Líder?
|
||||
</div>
|
||||
|
||||
{/* Timer */}
|
||||
{!gameState.leaderVotes?.[currentPlayerId] && (
|
||||
<VotingTimer onTimeout={() => actions.voteLeader(null)} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gameState.leaderVotes?.[currentPlayerId] === undefined ? (
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteLeader(true)} className="group">
|
||||
<div className="w-40 h-60 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<Image src="/assets/images/tokens/accept_leader.png" alt="Accept Leader" fill className="object-contain" />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded uppercase tracking-widest">ACEPTAR</span>
|
||||
</button>
|
||||
<button onClick={() => actions.voteLeader(false)} className="group">
|
||||
<div className="w-40 h-60 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4 relative overflow-hidden">
|
||||
<Image src="/assets/images/tokens/deny_leader.png" alt="Deny Leader" fill className="object-contain" />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded uppercase tracking-widest">RECHAZAR</span>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-white text-xl font-mono animate-pulse bg-black/50 px-6 py-3 rounded-full border border-white/20">
|
||||
VOTO REGISTRADO. ESPERANDO AL RESTO...
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: CONSTRUCCIÓN DE EQUIPO */}
|
||||
{gameState.phase === GamePhase.TEAM_BUILDING && (
|
||||
<motion.div
|
||||
key="team-building"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -20 }}
|
||||
className="bg-paper-bg text-black p-6 rounded shadow-2xl rotate-1 max-w-md w-full text-center"
|
||||
>
|
||||
<h2 className="text-2xl font-bold font-mono mb-2 uppercase text-resistance-blue">
|
||||
{isLeader ? 'TU TURNO: ELIGE EQUIPO' : `ESPERANDO AL LÍDER...`}
|
||||
</h2>
|
||||
<p className="mb-4 font-serif italic text-gray-700">
|
||||
Se necesitan <span className="font-bold text-red-700">{currentQuestSize} agentes</span> para esta misión.
|
||||
</p>
|
||||
|
||||
{isLeader && (
|
||||
<button
|
||||
onClick={() => actions.proposeTeam(selectedTeam)}
|
||||
disabled={selectedTeam.length !== currentQuestSize}
|
||||
className="w-full bg-resistance-blue text-white font-bold py-3 px-4 rounded hover:bg-blue-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed uppercase tracking-widest"
|
||||
>
|
||||
Proponer Equipo
|
||||
</button>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: VOTACIÓN DE EQUIPO */}
|
||||
{gameState.phase === GamePhase.VOTING_TEAM && (
|
||||
<motion.div
|
||||
key="voting"
|
||||
initial={{ scale: 0.8, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
className="flex flex-col items-center gap-6"
|
||||
>
|
||||
<div className="bg-black/80 p-4 rounded text-white text-center border border-white/20">
|
||||
<h3 className="text-xl font-mono mb-2 text-yellow-500">PROPUESTA DE MISIÓN</h3>
|
||||
<div className="flex gap-2 justify-center">
|
||||
{gameState.proposedTeam.map(id => {
|
||||
const p = gameState.players.find(pl => pl.id === id);
|
||||
return (
|
||||
<div key={id} className="bg-white/10 px-3 py-1 rounded text-sm">
|
||||
{p?.name}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!currentPlayer?.hasVoted ? (
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteTeam(true)} className="group">
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-green-500 transition-all transform group-hover:-translate-y-4">
|
||||
<Image src="/assets/images/tokens/vote_approve.png" alt="Approve" width={100} height={100} />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-green-600 px-2 rounded">APROBAR</span>
|
||||
</button>
|
||||
<button onClick={() => actions.voteTeam(false)} className="group">
|
||||
<div className="w-32 h-48 bg-white rounded-lg shadow-xl flex items-center justify-center border-4 border-transparent group-hover:border-red-500 transition-all transform group-hover:-translate-y-4">
|
||||
<Image src="/assets/images/tokens/vote_reject.png" alt="Reject" width={100} height={100} />
|
||||
</div>
|
||||
<span className="block text-center text-white mt-2 font-bold bg-red-600 px-2 rounded">RECHAZAR</span>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-white text-xl font-mono animate-pulse">
|
||||
VOTO REGISTRADO. ESPERANDO AL RESTO...
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: MISIÓN */}
|
||||
{gameState.phase === GamePhase.MISSION && (
|
||||
<motion.div key="mission" className="text-center">
|
||||
{gameState.proposedTeam.includes(currentPlayerId) ? (
|
||||
<div className="flex flex-col items-center gap-6">
|
||||
<h2 className="text-3xl font-bold text-white mb-4 drop-shadow-lg">¡ESTÁS EN LA MISIÓN!</h2>
|
||||
<div className="flex gap-8">
|
||||
<button onClick={() => actions.voteMission(true)} className="group">
|
||||
<div className="w-40 h-60 bg-blue-900 rounded-lg shadow-2xl border-2 border-blue-400 flex flex-col items-center justify-center p-4 transform transition-transform hover:scale-105">
|
||||
<Image src="/assets/images/tokens/mission_success.png" alt="Success" width={120} height={120} />
|
||||
<span className="mt-4 text-blue-200 font-bold tracking-widest">ÉXITO</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Solo los malos pueden sabotear */}
|
||||
{currentPlayer?.faction === 'spies' && (
|
||||
<button onClick={() => actions.voteMission(false)} className="group">
|
||||
<div className="w-40 h-60 bg-red-900 rounded-lg shadow-2xl border-2 border-red-400 flex flex-col items-center justify-center p-4 transform transition-transform hover:scale-105">
|
||||
<Image src="/assets/images/tokens/mission_fail.png" alt="Fail" width={120} height={120} />
|
||||
<span className="mt-4 text-red-200 font-bold tracking-widest">SABOTAJE</span>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-white text-2xl font-mono bg-black/50 p-6 rounded">
|
||||
La misión está en curso...<br />
|
||||
<span className="text-sm text-gray-400">Rezando por el éxito.</span>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* FASE: REVELACIÓN DE CARTAS */}
|
||||
{gameState.phase === 'mission_reveal' as any && (
|
||||
<MissionReveal
|
||||
votes={gameState.revealedVotes || []}
|
||||
onComplete={() => isHost && actions.finishMissionReveal()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* FASE: RESULTADO DE MISIÓN */}
|
||||
{gameState.phase === 'mission_result' as any && (
|
||||
<MissionResult
|
||||
gameState={gameState}
|
||||
onContinue={() => isHost && actions.finishMissionResult()}
|
||||
/>
|
||||
)}
|
||||
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
|
||||
{/* JUGADORES (TIENDA DE CAMPAÑA) */}
|
||||
<div className="z-10 w-full overflow-x-auto pb-4">
|
||||
<div className="flex justify-center gap-4 min-w-max px-4">
|
||||
{gameState.players.map((player) => {
|
||||
const isSelected = selectedTeam.includes(player.id);
|
||||
const isMe = player.id === currentPlayerId;
|
||||
|
||||
// Avatar logic
|
||||
const avatarSrc = `/assets/images/characters/${player.avatar}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={player.id}
|
||||
onClick={() => isLeader && gameState.phase === GamePhase.TEAM_BUILDING && toggleTeamSelection(player.id)}
|
||||
className={`
|
||||
relative flex flex-col items-center cursor-pointer transition-all duration-300
|
||||
${isSelected ? 'scale-110' : 'scale-100 opacity-80 hover:opacity-100'}
|
||||
`}
|
||||
>
|
||||
{/* Avatar */}
|
||||
<div className={`
|
||||
w-16 h-16 rounded-full border-2 overflow-hidden relative shadow-lg bg-black
|
||||
${isSelected ? 'border-yellow-400 ring-4 ring-yellow-400/30' : 'border-gray-400'}
|
||||
${player.isLeader ? 'ring-2 ring-white' : ''}
|
||||
`}>
|
||||
<Image
|
||||
src={avatarSrc}
|
||||
alt={player.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
|
||||
{/* Icono de Líder */}
|
||||
{player.isLeader && (
|
||||
<div className="absolute bottom-0 right-0 bg-yellow-500 rounded-full p-1 w-6 h-6 flex items-center justify-center text-xs text-black font-bold border border-white z-10">
|
||||
L
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Nombre */}
|
||||
<span className={`mt-2 text-xs font-mono px-2 py-0.5 rounded ${isMe ? 'bg-blue-600 text-white' : 'bg-black/50 text-gray-300'}`}>
|
||||
{player.name}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* HISTÓRICO DE MISIONES (Esquina superior derecha) */}
|
||||
{gameState.missionHistory.length > 0 && (
|
||||
<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>
|
||||
@@ -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 pt-8"
|
||||
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-3xl sm:text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold mb-8 whitespace-nowrap px-4 ${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-yellow-600 to-yellow-700 hover:from-yellow-500 hover:to-yellow-600 text-white font-bold py-4 px-8 rounded-lg text-lg 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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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-3xl font-bold text-white mb-12 uppercase tracking-widest drop-shadow-lg text-center">
|
||||
Resultado de la misión
|
||||
</h2>
|
||||
|
||||
<div className="flex gap-4 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-32 h-48 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 text-center"
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
127
client/src/components/VictoryScreen.tsx
Normal 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-[4rem] md:text-[4.5rem] 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>
|
||||
);
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
94
deploy copy.sh
Executable file
@@ -0,0 +1,94 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script de deployment para Francia Ocupada
|
||||
# Este script se ejecuta en el HOST, no en el runner
|
||||
|
||||
set -e # Salir si hay algún error
|
||||
|
||||
echo "🚀 Iniciando deployment de Francia Ocupada..."
|
||||
echo "================================================"
|
||||
|
||||
# Directorio del proyecto
|
||||
PROJECT_DIR="/home/marti/docker/FranciaOcupada"
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
echo "📂 Directorio de trabajo: $(pwd)"
|
||||
echo ""
|
||||
|
||||
# PASO 1: Actualizar código desde Git
|
||||
echo "📥 PASO 1: Actualizando código desde Git..."
|
||||
git fetch origin
|
||||
git reset --hard origin/main
|
||||
echo "✅ Código actualizado"
|
||||
echo ""
|
||||
|
||||
# PASO 2: Detener contenedores anteriores
|
||||
echo "🛑 PASO 2: Deteniendo contenedores anteriores..."
|
||||
docker compose -f docker-compose_prod.yml down || true
|
||||
docker container prune -f || true
|
||||
echo "✅ Contenedores anteriores detenidos"
|
||||
echo ""
|
||||
|
||||
# PASO 3: Limpiar imágenes antiguas
|
||||
echo "🧹 PASO 3: Limpiando imágenes antiguas..."
|
||||
docker image prune -f || true
|
||||
echo "✅ Limpieza completada"
|
||||
echo ""
|
||||
|
||||
# PASO 4: Construir imágenes Docker
|
||||
echo "🔨 PASO 4: Construyendo imágenes Docker..."
|
||||
docker compose -f docker-compose_prod.yml build --no-cache
|
||||
|
||||
# Etiquetar con timestamp para trazabilidad
|
||||
TAG_VERSION=$(date +%Y%m%d_%H%M%S)
|
||||
docker tag resistencia-client:latest resistencia-client:${TAG_VERSION} || true
|
||||
docker tag resistencia-server:latest resistencia-server:${TAG_VERSION} || true
|
||||
|
||||
echo "✅ Imágenes construidas:"
|
||||
echo " - resistencia-client:latest (${TAG_VERSION})"
|
||||
echo " - resistencia-server:latest (${TAG_VERSION})"
|
||||
echo ""
|
||||
|
||||
# PASO 5: Desplegar contenedores
|
||||
echo "📦 PASO 5: Desplegando aplicación..."
|
||||
docker compose -f docker-compose_prod.yml up -d
|
||||
|
||||
echo "✅ Aplicación desplegada exitosamente"
|
||||
echo ""
|
||||
|
||||
# PASO 6: Verificar deployment
|
||||
echo "✅ PASO 6: Verificando deployment..."
|
||||
sleep 10
|
||||
|
||||
echo "📊 Estado de los contenedores:"
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
echo ""
|
||||
|
||||
# Verificar que los contenedores están corriendo
|
||||
RUNNING_CONTAINERS=$(docker compose -f docker-compose_prod.yml ps -q | wc -l)
|
||||
if [ "$RUNNING_CONTAINERS" -eq 0 ]; then
|
||||
echo "❌ ERROR: No hay contenedores corriendo"
|
||||
docker compose -f docker-compose_prod.yml logs
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ Verificación completada - $RUNNING_CONTAINERS contenedores corriendo"
|
||||
echo ""
|
||||
|
||||
# PASO 7: Mostrar logs recientes
|
||||
echo "📋 PASO 7: Logs recientes..."
|
||||
echo ""
|
||||
echo "--- Logs del Cliente (últimas 20 líneas) ---"
|
||||
docker compose -f docker-compose_prod.yml logs --tail=20 client || true
|
||||
echo ""
|
||||
echo "--- Logs del Servidor (últimas 20 líneas) ---"
|
||||
docker compose -f docker-compose_prod.yml logs --tail=20 server || true
|
||||
echo ""
|
||||
|
||||
echo "================================================"
|
||||
echo "🎉 Deployment completado exitosamente!"
|
||||
echo ""
|
||||
echo "🌐 Aplicación disponible en:"
|
||||
echo " - Frontend: https://franciaocupada.martivich.es"
|
||||
echo " - API: https://api.franciaocupada.martivich.es"
|
||||
echo "================================================"
|
||||
94
deploy.sh
Executable file
@@ -0,0 +1,94 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script de deployment para Francia Ocupada
|
||||
# Este script se ejecuta en el HOST, no en el runner
|
||||
|
||||
set -e # Salir si hay algún error
|
||||
|
||||
echo "🚀 Iniciando deployment de Francia Ocupada..."
|
||||
echo "================================================"
|
||||
|
||||
# Directorio del proyecto
|
||||
PROJECT_DIR="/home/marti/Documentos/Gitea/resistencia"
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
echo "📂 Directorio de trabajo: $(pwd)"
|
||||
echo ""
|
||||
|
||||
# PASO 1: Actualizar código desde Git
|
||||
echo "📥 PASO 1: Actualizando código desde Git..."
|
||||
git fetch origin
|
||||
git reset --hard origin/main
|
||||
echo "✅ Código actualizado"
|
||||
echo ""
|
||||
|
||||
# PASO 2: Detener contenedores anteriores
|
||||
echo "🛑 PASO 2: Deteniendo contenedores anteriores..."
|
||||
docker compose -f docker-compose_prod.yml down || true
|
||||
docker container prune -f || true
|
||||
echo "✅ Contenedores anteriores detenidos"
|
||||
echo ""
|
||||
|
||||
# PASO 3: Limpiar imágenes antiguas
|
||||
echo "🧹 PASO 3: Limpiando imágenes antiguas..."
|
||||
docker image prune -f || true
|
||||
echo "✅ Limpieza completada"
|
||||
echo ""
|
||||
|
||||
# PASO 4: Construir imágenes Docker
|
||||
echo "🔨 PASO 4: Construyendo imágenes Docker..."
|
||||
docker compose -f docker-compose_prod.yml build --no-cache
|
||||
|
||||
# Etiquetar con timestamp para trazabilidad
|
||||
TAG_VERSION=$(date +%Y%m%d_%H%M%S)
|
||||
docker tag resistencia-client:latest resistencia-client:${TAG_VERSION} || true
|
||||
docker tag resistencia-server:latest resistencia-server:${TAG_VERSION} || true
|
||||
|
||||
echo "✅ Imágenes construidas:"
|
||||
echo " - resistencia-client:latest (${TAG_VERSION})"
|
||||
echo " - resistencia-server:latest (${TAG_VERSION})"
|
||||
echo ""
|
||||
|
||||
# PASO 5: Desplegar contenedores
|
||||
echo "📦 PASO 5: Desplegando aplicación..."
|
||||
docker compose -f docker-compose_prod.yml up -d
|
||||
|
||||
echo "✅ Aplicación desplegada exitosamente"
|
||||
echo ""
|
||||
|
||||
# PASO 6: Verificar deployment
|
||||
echo "✅ PASO 6: Verificando deployment..."
|
||||
sleep 10
|
||||
|
||||
echo "📊 Estado de los contenedores:"
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
echo ""
|
||||
|
||||
# Verificar que los contenedores están corriendo
|
||||
RUNNING_CONTAINERS=$(docker compose -f docker-compose_prod.yml ps -q | wc -l)
|
||||
if [ "$RUNNING_CONTAINERS" -eq 0 ]; then
|
||||
echo "❌ ERROR: No hay contenedores corriendo"
|
||||
docker compose -f docker-compose_prod.yml logs
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ Verificación completada - $RUNNING_CONTAINERS contenedores corriendo"
|
||||
echo ""
|
||||
|
||||
# PASO 7: Mostrar logs recientes
|
||||
echo "📋 PASO 7: Logs recientes..."
|
||||
echo ""
|
||||
echo "--- Logs del Cliente (últimas 20 líneas) ---"
|
||||
docker compose -f docker-compose_prod.yml logs --tail=20 client || true
|
||||
echo ""
|
||||
echo "--- Logs del Servidor (últimas 20 líneas) ---"
|
||||
docker compose -f docker-compose_prod.yml logs --tail=20 server || true
|
||||
echo ""
|
||||
|
||||
echo "================================================"
|
||||
echo "🎉 Deployment completado exitosamente!"
|
||||
echo ""
|
||||
echo "🌐 Aplicación disponible en:"
|
||||
echo " - Frontend: https://franciaocupada.martivich.es"
|
||||
echo " - API: https://api.franciaocupada.martivich.es"
|
||||
echo "================================================"
|
||||
63
docker-compose_prod.yml
Normal 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
@@ -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
|
||||
131
monitor-deploy.sh
Executable file
@@ -0,0 +1,131 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script de monitoreo para el despliegue de Francia Ocupada
|
||||
# Uso: ./monitor-deploy.sh
|
||||
|
||||
echo "🔍 Monitor de Despliegue - Francia Ocupada"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# Colores para output
|
||||
GREEN='\033[0;32m'
|
||||
RED='\033[0;31m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Función para verificar estado de contenedores
|
||||
check_containers() {
|
||||
echo -e "${YELLOW}📦 Estado de Contenedores:${NC}"
|
||||
docker compose -f docker-compose_prod.yml ps
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Función para verificar logs
|
||||
check_logs() {
|
||||
echo -e "${YELLOW}📋 Logs Recientes (últimas 20 líneas):${NC}"
|
||||
echo ""
|
||||
echo "--- CLIENT ---"
|
||||
docker compose -f docker-compose_prod.yml logs --tail=20 client 2>/dev/null || echo "Cliente no disponible"
|
||||
echo ""
|
||||
echo "--- SERVER ---"
|
||||
docker compose -f docker-compose_prod.yml logs --tail=20 server 2>/dev/null || echo "Servidor no disponible"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Función para verificar conectividad
|
||||
check_connectivity() {
|
||||
echo -e "${YELLOW}🌐 Verificación de Conectividad:${NC}"
|
||||
|
||||
# Verificar puerto 3000 (cliente)
|
||||
if nc -z localhost 3000 2>/dev/null; then
|
||||
echo -e "${GREEN}✅ Puerto 3000 (Cliente): ABIERTO${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ Puerto 3000 (Cliente): CERRADO${NC}"
|
||||
fi
|
||||
|
||||
# Verificar puerto 4000 (servidor)
|
||||
if nc -z localhost 4000 2>/dev/null; then
|
||||
echo -e "${GREEN}✅ Puerto 4000 (Servidor): ABIERTO${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ Puerto 4000 (Servidor): CERRADO${NC}"
|
||||
fi
|
||||
|
||||
# Verificar puerto 5432 (base de datos)
|
||||
if nc -z localhost 5432 2>/dev/null; then
|
||||
echo -e "${GREEN}✅ Puerto 5432 (Base de Datos): ABIERTO${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ Puerto 5432 (Base de Datos): CERRADO${NC}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Función para verificar uso de recursos
|
||||
check_resources() {
|
||||
echo -e "${YELLOW}💻 Uso de Recursos:${NC}"
|
||||
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" \
|
||||
$(docker compose -f docker-compose_prod.yml ps -q 2>/dev/null) 2>/dev/null || echo "No hay contenedores corriendo"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Menú principal
|
||||
while true; do
|
||||
echo ""
|
||||
echo "Selecciona una opción:"
|
||||
echo "1) Ver estado de contenedores"
|
||||
echo "2) Ver logs recientes"
|
||||
echo "3) Verificar conectividad"
|
||||
echo "4) Ver uso de recursos"
|
||||
echo "5) Monitoreo completo"
|
||||
echo "6) Logs en tiempo real (Ctrl+C para salir)"
|
||||
echo "7) Reiniciar servicios"
|
||||
echo "8) Detener servicios"
|
||||
echo "9) Salir"
|
||||
echo ""
|
||||
read -p "Opción: " option
|
||||
|
||||
case $option in
|
||||
1)
|
||||
check_containers
|
||||
;;
|
||||
2)
|
||||
check_logs
|
||||
;;
|
||||
3)
|
||||
check_connectivity
|
||||
;;
|
||||
4)
|
||||
check_resources
|
||||
;;
|
||||
5)
|
||||
check_containers
|
||||
check_connectivity
|
||||
check_resources
|
||||
check_logs
|
||||
;;
|
||||
6)
|
||||
echo "📡 Logs en tiempo real (Ctrl+C para detener)..."
|
||||
docker compose -f docker-compose_prod.yml logs -f
|
||||
;;
|
||||
7)
|
||||
echo "🔄 Reiniciando servicios..."
|
||||
docker compose -f docker-compose_prod.yml restart
|
||||
echo -e "${GREEN}✅ Servicios reiniciados${NC}"
|
||||
;;
|
||||
8)
|
||||
read -p "¿Estás seguro de que quieres detener los servicios? (s/n): " confirm
|
||||
if [ "$confirm" = "s" ]; then
|
||||
echo "🛑 Deteniendo servicios..."
|
||||
docker compose -f docker-compose_prod.yml down
|
||||
echo -e "${GREEN}✅ Servicios detenidos${NC}"
|
||||
fi
|
||||
;;
|
||||
9)
|
||||
echo "👋 ¡Hasta luego!"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo -e "${RED}❌ Opción inválida${NC}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
@@ -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);
|
||||
|
||||
@@ -29,6 +29,7 @@ export class Game {
|
||||
|
||||
this.state = {
|
||||
roomId,
|
||||
roomName,
|
||||
phase: GamePhase.LOBBY,
|
||||
players: [],
|
||||
currentRound: 1,
|
||||
@@ -47,9 +48,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 +105,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 +120,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 +142,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 +237,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 +292,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 +313,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 +333,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 +365,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
|
||||
|
||||
@@ -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',
|
||||
}
|
||||
|
||||
@@ -60,6 +62,7 @@ export interface MissionRecord {
|
||||
|
||||
export interface GameState {
|
||||
roomId: string;
|
||||
roomName: string;
|
||||
phase: GamePhase;
|
||||
players: Player[];
|
||||
hostId: string;
|
||||
|
||||
174
useful-commands.sh
Executable file
@@ -0,0 +1,174 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 🚀 Comandos Útiles para CI/CD - Francia Ocupada
|
||||
# Este archivo contiene comandos útiles para gestionar el CI/CD
|
||||
|
||||
echo "==================================================="
|
||||
echo "🎮 Francia Ocupada - Comandos Útiles CI/CD"
|
||||
echo "==================================================="
|
||||
echo ""
|
||||
|
||||
# Función para mostrar comandos con descripción
|
||||
show_command() {
|
||||
echo -e "\033[1;33m$1\033[0m"
|
||||
echo -e "\033[0;36m$2\033[0m"
|
||||
echo ""
|
||||
}
|
||||
|
||||
echo "📦 GESTIÓN DE CONTENEDORES"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Ver estado de contenedores:" \
|
||||
"docker compose -f docker-compose_prod.yml ps"
|
||||
|
||||
show_command "Iniciar servicios:" \
|
||||
"docker compose -f docker-compose_prod.yml up -d"
|
||||
|
||||
show_command "Detener servicios:" \
|
||||
"docker compose -f docker-compose_prod.yml down"
|
||||
|
||||
show_command "Reiniciar servicios:" \
|
||||
"docker compose -f docker-compose_prod.yml restart"
|
||||
|
||||
show_command "Reconstruir y reiniciar:" \
|
||||
"docker compose -f docker-compose_prod.yml up -d --build"
|
||||
|
||||
echo ""
|
||||
echo "📋 LOGS Y DEBUGGING"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Ver todos los logs:" \
|
||||
"docker compose -f docker-compose_prod.yml logs"
|
||||
|
||||
show_command "Logs en tiempo real:" \
|
||||
"docker compose -f docker-compose_prod.yml logs -f"
|
||||
|
||||
show_command "Logs del cliente:" \
|
||||
"docker compose -f docker-compose_prod.yml logs -f client"
|
||||
|
||||
show_command "Logs del servidor:" \
|
||||
"docker compose -f docker-compose_prod.yml logs -f server"
|
||||
|
||||
show_command "Logs de la base de datos:" \
|
||||
"docker compose -f docker-compose_prod.yml logs -f db"
|
||||
|
||||
show_command "Últimas 100 líneas de logs:" \
|
||||
"docker compose -f docker-compose_prod.yml logs --tail=100"
|
||||
|
||||
echo ""
|
||||
echo "🔍 INSPECCIÓN Y DEBUGGING"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Entrar al contenedor del cliente:" \
|
||||
"docker exec -it resistencia-client sh"
|
||||
|
||||
show_command "Entrar al contenedor del servidor:" \
|
||||
"docker exec -it resistencia-server sh"
|
||||
|
||||
show_command "Entrar a la base de datos:" \
|
||||
"docker exec -it resistencia-db psql -U postgres -d resistencia"
|
||||
|
||||
show_command "Ver uso de recursos:" \
|
||||
"docker stats"
|
||||
|
||||
show_command "Inspeccionar red:" \
|
||||
"docker network inspect resistencia_resistencia-net"
|
||||
|
||||
echo ""
|
||||
echo "🧹 LIMPIEZA"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Limpiar contenedores detenidos:" \
|
||||
"docker container prune -f"
|
||||
|
||||
show_command "Limpiar imágenes sin usar:" \
|
||||
"docker image prune -f"
|
||||
|
||||
show_command "Limpiar todo (CUIDADO):" \
|
||||
"docker system prune -a -f"
|
||||
|
||||
show_command "Limpiar volúmenes (CUIDADO - BORRA DATOS):" \
|
||||
"docker volume prune -f"
|
||||
|
||||
echo ""
|
||||
echo "🔧 TROUBLESHOOTING"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Ver puertos en uso:" \
|
||||
"sudo lsof -i :3000 :4000 :5432"
|
||||
|
||||
show_command "Verificar conectividad local:" \
|
||||
"curl http://localhost:3000 && curl http://localhost:4000"
|
||||
|
||||
show_command "Ver configuración de docker-compose:" \
|
||||
"docker compose -f docker-compose_prod.yml config"
|
||||
|
||||
show_command "Reconstruir sin caché:" \
|
||||
"docker compose -f docker-compose_prod.yml build --no-cache"
|
||||
|
||||
echo ""
|
||||
echo "🚀 GIT Y DESPLIEGUE"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Ver estado de Git:" \
|
||||
"git status"
|
||||
|
||||
show_command "Ver último commit:" \
|
||||
"git log -1"
|
||||
|
||||
show_command "Trigger CI/CD (commit vacío):" \
|
||||
"git commit --allow-empty -m 'test: Trigger CI/CD' && git push origin main"
|
||||
|
||||
show_command "Ver commits recientes:" \
|
||||
"git log --oneline -10"
|
||||
|
||||
show_command "Ver diferencias con origin:" \
|
||||
"git diff origin/main"
|
||||
|
||||
echo ""
|
||||
echo "🌐 VERIFICACIÓN DE PRODUCCIÓN"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Verificar frontend (local):" \
|
||||
"curl -I http://localhost:3000"
|
||||
|
||||
show_command "Verificar API (local):" \
|
||||
"curl -I http://localhost:4000"
|
||||
|
||||
show_command "Verificar frontend (producción):" \
|
||||
"curl -I https://franciaocupada.martivich.es"
|
||||
|
||||
show_command "Verificar API (producción):" \
|
||||
"curl -I https://api.franciaocupada.martivich.es"
|
||||
|
||||
echo ""
|
||||
echo "📊 MONITOREO"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Script de monitoreo interactivo:" \
|
||||
"./monitor-deploy.sh"
|
||||
|
||||
show_command "Ver acciones de Gitea (navegador):" \
|
||||
"xdg-open http://gitea.local:3000/marti/FranciaOcupada/actions"
|
||||
|
||||
echo ""
|
||||
echo "💾 BACKUP Y RESTAURACIÓN"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Backup de la base de datos:" \
|
||||
"docker exec resistencia-db pg_dump -U postgres resistencia > backup_\$(date +%Y%m%d_%H%M%S).sql"
|
||||
|
||||
show_command "Restaurar base de datos:" \
|
||||
"docker exec -i resistencia-db psql -U postgres resistencia < backup.sql"
|
||||
|
||||
show_command "Exportar volumen de datos:" \
|
||||
"docker run --rm -v resistencia_postgres_data:/data -v \$(pwd):/backup alpine tar czf /backup/postgres_data_backup.tar.gz -C /data ."
|
||||
|
||||
echo ""
|
||||
echo "🎯 COMANDOS RÁPIDOS"
|
||||
echo "---------------------------------------------------"
|
||||
show_command "Reinicio completo (desarrollo):" \
|
||||
"docker compose down && docker compose up -d --build"
|
||||
|
||||
show_command "Reinicio completo (producción):" \
|
||||
"docker compose -f docker-compose_prod.yml down && docker compose -f docker-compose_prod.yml up -d --build"
|
||||
|
||||
show_command "Ver todo el estado del sistema:" \
|
||||
"docker compose -f docker-compose_prod.yml ps && docker compose -f docker-compose_prod.yml logs --tail=20"
|
||||
|
||||
echo ""
|
||||
echo "==================================================="
|
||||
echo "💡 Tip: Guarda este archivo como referencia"
|
||||
echo " Ejecuta: cat useful-commands.sh | less"
|
||||
echo "==================================================="
|
||||