feat: Migración completa de SnatchGame a Nuxt 4
Some checks failed
build-and-deploy / filter (push) Successful in 3s
build-and-deploy / build (push) Failing after 6s
build-and-deploy / deploy (push) Has been skipped

- Creado nuevo proyecto Nuxt 4 con estructura app/
- Servidor Colyseus separado para evitar problemas con decoradores
- Migrado GameRoom y toda la lógica del juego
- Implementado cliente con composables useGameClient
- Panel de administración funcional
- Componentes Vue migrados (HomeScreen, GameScreen, PlayerCard, etc)
- Configuración para ejecutar ambos servidores (npm run dev:all)
This commit is contained in:
2025-08-05 16:05:51 -06:00
parent b83d450ac6
commit 62226ab5d4
36 changed files with 17126 additions and 2661 deletions

6
.gitignore vendored
View File

@@ -208,6 +208,12 @@ admin/src/types/GameState.ts
.env.*.local .env.*.local
secrets/ secrets/
# ===== DEPLOYMENT SECRETS =====
# Google Cloud Platform deployment documentation (contains sensitive info)
deploy-gcp/
# Oracle Cloud deployment documentation (contains sensitive info)
deploy-oracle/
# ===== PACKAGE MANAGERS ===== # ===== PACKAGE MANAGERS =====
# Yarn # Yarn
.yarn/cache .yarn/cache

View File

@@ -1,263 +0,0 @@
# Changelog
Todos los cambios notables de este proyecto serán documentados en este archivo.
El formato está basado en [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
y este proyecto adhiere a [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Planeado
- Ronda 2-5: Implementar reglas evolutivas
- Sistema de Judge rotativo
- Shame tokens y penalizaciones
- Efectos de sonido
- PWA support
- Multi-idioma
## [0.0.9-alpha] - 2025-07-05
### Added
- **🐳 Docker Production Environment**: Sistema completo de containerización
- Dockerfiles individuales para server, client y admin
- Docker Compose con orquestación completa
- Health checks automáticos para todos los servicios
- Restart policies para alta disponibilidad
- **⚙️ Gitea Actions CI/CD Pipeline**: Automatización completa de deployment
- Build automático de imágenes Docker
- Push a registry interno gitea.interno.com/nucleo000
- Conditional building basado en archivos modificados
- Deploy automático en main branch
- **🌐 Production Network Architecture**: Arquitectura de redes optimizada
- Red "principal" para Nginx Proxy Manager
- Red interna "snatchgame-network" para comunicación entre servicios
- Separación de URLs internas (HTTP) y externas (HTTPS)
- **🔧 Environment-based URL Configuration**: URLs dinámicas según ambiente
- SERVER_URL para comunicación interna entre contenedores
- PUBLIC_SERVER_URL para comunicación frontend-backend
- Configuración automática via /api/config endpoints
### Changed
- **⚡ SSE Performance Optimizations**: Comunicación admin optimizada
- Polling reducido de 500ms a 250ms para updates más rápidos
- Headers anti-buffering (X-Accel-Buffering, Content-Encoding)
- Heartbeat mechanism cada 30 segundos
- Auto-reconexión cliente cada 5 segundos en caso de error
- **🏗️ Production URLs**: Configuración de producción completa
- snatchGame.interno.com (Cliente UI)
- snatchGameServer.interno.com (Servidor Colyseus)
- snatchgGameAdmin.interno.com (Admin UI)
- **📦 Build Process**: Optimización del proceso de build
- build:prod script para omitir generación de tipos en Docker
- npm ci para instalaciones más rápidas y reproducibles
- Multi-stage builds para imágenes más pequeñas
### Fixed
- **🔌 SSL Certificate Issues**: Separación URLs interna/externa
- URLs HTTPS para comunicación navegador-servidor (frontend)
- URLs HTTP para comunicación contenedor-contenedor (backend)
- Resuelve errores de certificado SSL en comunicación interna
- **🎯 Admin Service URL Configuration**: URLs dinámicas basadas en ambiente
- AdminService obtiene URL desde /api/config en lugar de hardcoded localhost
- Soporte completo para desarrollo y producción
- Inicialización async de URLs antes de llamadas API
- **📊 SSE Connection Stability**: Mejoras en estabilidad de conexión
- Manejo mejorado de heartbeat messages
- Logging detallado para debugging
- Cleanup apropiado de intervalos en disconnection
### Technical
- **🐳 Docker Configuration**:
- Puertos de producción: 3067 (server), 3010 (client), 3011 (admin)
- Alpine Linux base images para menor tamaño
- wget para health checks (más ligero que curl)
- **📡 Network Communication**:
- Separación limpia entre comunicación interna y externa
- Optimización de headers SSE para mejor performance
- Express middleware optimizado para SSE endpoints
- **🔧 Environment Management**:
- Variables de entorno separadas por servicio
- Runtime configuration via API endpoints
- Support para development y production environments
### Infrastructure
- **🏗️ Complete Production Setup**: Sistema listo para producción
- Docker registry interno configurado
- CI/CD pipeline completamente automático
- High availability con health checks y restart policies
- Network isolation y security best practices
- **📊 Monitoring & Debugging**: Herramientas de monitoreo mejoradas
- Logging estructurado con timestamps
- Connection tracking para SSE
- Performance metrics para fetch requests
- Detailed error handling y reporting
## [0.0.8-alpha] - 2025-07-04
### Added
- **Admin Dashboard Completo**: UI de administración con información detallada de jugadores
- **Control de Jugadores**: Expulsar jugadores individuales y todos los jugadores
- **Control de Rondas Global**: Avanzar y retroceder rondas en todas las salas simultáneamente
- **Control de Juego**: Pausar y reanudar juegos desde el admin
- **Notificaciones a Clientes**: Los jugadores reciben notificaciones cuando son expulsados o cuando cambian las rondas
- **Información Detallada de Jugadores**: Nombre, sala, rol, tipo de productor y tokens actuales
- **Redirección Automática**: Los clientes expulsados vuelven automáticamente al home
### Changed
- **API Oficial de Colyseus**: Refactorizado todos los endpoints admin para usar `matchMaker.query()` y `matchMaker.remoteRoomCall()`
- **Arquitectura sin Variables Globales**: Eliminado el hack de variables globales por implementación oficial
- **UI Admin Mejorada**: Información más clara y organizada para comentaristas no-técnicos
### Fixed
- **Notificación de Expulsión**: Los clientes ahora reciben notificación correcta cuando son expulsados
- **URLs del Admin Service**: Corregido para llamar al servidor Colyseus (puerto 2567) en lugar del admin (puerto 3001)
- **Expulsión Masiva**: Todos los jugadores reciben notificación apropiada cuando se expulsan todos
### Technical
- **GameRoom Methods**: Implementado `pauseGame()`, `resumeGame()`, `advanceRound()`, `previousRound()`, `_forceClientDisconnect()`, `_forceDisconnectAllClients()`, `getInspectData()`
- **Client Notifications**: Manejo de mensajes `adminKicked`, `gamePaused`, `gameResumed`, `roundChanged`
- **Type Safety**: Mantenida sincronización de tipos TypeScript entre servidor y clientes
## [0.0.5-alpha] - 2025-01-04
### Añadido
- **🎮 Juego Snatch or Share completo**
- Implementación del "Snatch Game" de Elinor Ostrom
- Sistema de roles únicos: Productor de Pavos, Café, Maíz
- Exactamente 3 jugadores por sala
- Tokens múltiples (turkey, coffee, corn)
- Sistema de puntuación: tokens propios = 1pt, ajenos = 2pts
- **🔄 Sistema de ofertas comerciales**
- Ofertas simultáneas entre jugadores
- Límite de 2 ofertas por target por jugador
- Respuestas: Accept, Reject, Snatch
- Cumplimiento parcial automático
- Todas las ofertas son públicas
- **🎨 UI/UX completamente rediseñada**
- Layout responsivo optimizado (desktop/móvil)
- Componentes modulares: PlayerCard, TradeOfferCard, MakeOfferForm
- Modal flotante para crear ofertas
- Scroll customizado para lista de ofertas
- Botones +/- prominentes para cantidades
- Input compacto optimizado para números de 3 dígitos
- **📱 Mejoras móviles**
- Layout vertical adaptativo
- Cards de ofertas horizontales y compactas
- Botones táctiles optimizados
- Altura diferencial desktop vs móvil
### Changed
- **🏗️ Arquitectura del servidor**
- GameState con múltiples tipos de tokens
- Player con rol de productor y tokens individuales
- TradeOffer con inventarios de offering/requesting
- Asignación automática de roles únicos
- **⚙️ Sistema de tipos**
- Regeneración automática desde servidor
- TokenInventory schema separado
- Interfaces para ofertas comerciales
- GameRoomOptions actualizado
- **🎯 Lógica del juego**
- Ronda 1: Estado de naturaleza implementado
- Ofertas más recientes aparecen arriba
- Validación de límites por jugador
- Cálculo automático de puntos en tiempo real
### Fixed
- **🐛 Problemas de layout**
- Overflow vertical en desktop eliminado
- Altura móvil permite scroll natural
- Posicionamiento de elementos mejorado
- **⚡ Rendimiento**
- Componentización reduce bundle size
- CSS encapsulado por componente
- Reactivity optimizada con computed properties
- **📚 Documentación completa**
- README.md principal actualizado con enfoque educativo
- README.md específico del servidor con API y schemas
- README.md específico del cliente con componentes
- gameRules.md con lógica detallada del juego
- Roadmap actualizado con progreso real
### Technical
- **📊 Schemas Colyseus**: GameState, Player, TradeOffer, TokenInventory
- **🧩 Componentes Vue**: 6 componentes modulares especializados
- **📋 Validación**: Límites de tokens, ofertas y jugadores
- **🔄 Estado**: Sincronización en tiempo real mejorada
- **🛠️ Build**: Generación automática de tipos client/server
## [0.0.1-alpha] - 2025-01-03
### Añadido
- **Funcionalidad core del juego**
- Juego multijugador de click battle en tiempo real
- Soporte para hasta 8 jugadores simultáneos
- Scoreboard en tiempo real
- Auto-inicio cuando hay 2+ jugadores
- Auto-pausa cuando <2 jugadores
- **Arquitectura técnica**
- Servidor Colyseus.io con TypeScript
- Cliente Vue 3 con Composition API
- Sincronización automática de tipos con schema-codegen
- Sistema de logging configurable
- Variables de entorno por ambiente
- **UI/UX**
- Pantalla de home con branding
- Pantalla de espera con contador de jugadores
- Pantalla de juego con botón animado
- Modal de configuración
- Diseño responsive
- **Desarrollo**
- VSCode tasks para desarrollo
- Hot reload en desarrollo
- TypeScript estricto en todo el proyecto
- Sistema de tipos compartidos
- Docker setup para producción
- **Documentación**
- README.md completo
- CLAUDE.md para desarrollo interno
- .gitignore comprehensivo
- Estructura de proyecto documentada
### Características técnicas
- **Backend**: Colyseus.io 0.16+, Node.js 18+, TypeScript, Express
- **Frontend**: Vue 3, TypeScript, Vite, CSS vanilla
- **Desarrollo**: Schema-codegen, ESLint, Hot reload
- **Deploy**: Docker, docker-compose, Nginx proxy
### Estado actual
- Funcionalidad básica del juego completamente funcional
- Multijugador en tiempo real working
- UI responsive y animada
- Sistema de logging configurable
- Documentación completa
- En desarrollo activo - versión Alpha
---
## Formato de versiones
- **Major.Minor.Patch-PreRelease**
- **Alpha**: Desarrollo inicial, funcionalidad básica
- **Beta**: Características completas, testing intensivo
- **RC**: Release Candidate, listo para producción
- **Stable**: Versión estable para uso general
### Tipos de cambios
- `Added` para nuevas características
- `Changed` para cambios en funcionalidad existente
- `Deprecated` para características que serán removidas
- `Removed` para características removidas
- `Fixed` para bug fixes
- `Security` para fixes de vulnerabilidades

358
CLAUDE.md
View File

@@ -1,358 +0,0 @@
# Guía de Trabajo - SnatchGame
## Instrucciones del Proyecto
Crear un juego multijugador para red local con:
- Servidor central usando Colyseus.io para estado compartido
- Cliente con Vue 3 + CSS + HTML vanilla
- Cliente usa Colyseus.js SDK
- Servidor y clientes en la misma red local
## Estructura del Proyecto
```
/server/ # Servidor Colyseus.io
/client/ # Cliente Vue 3 vanilla
```
## Stack Tecnológico
**Servidor:**
- Colyseus.io (framework de servidor)
- Node.js
- TypeScript
**Cliente:**
- Vue 3 (vanilla, sin build tools)
- HTML vanilla
- CSS vanilla
- Colyseus.js (SDK cliente)
- TypeScript
**UI Administración:**
- Vue 3 (vanilla, sin build tools)
- HTML vanilla
- CSS vanilla
- Colyseus.js (SDK cliente)
- TypeScript
## Convenciones de Código
**Lenguaje:**
- Código: Inglés
- UI/Diálogos: Español
- Comentarios: Inglés
**Naming Conventions:**
- Variables/Funciones: `thisIsAFunction`
- Clases: `ThisIsAClass`
- Constantes globales/env: `THIS_IS_A_GLOBAL_CONSTANT`
**TypeScript:**
- Tipado estricto en todos los componentes
- Tipos auto-generados desde servidor usando schema-codegen
- Homogeneidad de tipos entre los 3 componentes
## Arquitectura - Microservicios
### Desarrollo
```
/server/ # Servidor Colyseus.io + TypeScript (Puerto 2567)
/client/ # Cliente Vue 3 + Express server (Puerto 3000)
/admin/ # UI Admin Vue 3 + Express server (Puerto 3001)
```
### Producción (Docker + Nginx Proxy Manager)
```
snatchgame-server # Contenedor servidor Colyseus
snatchgame-client # Contenedor cliente Express
snatchgame-admin # Contenedor admin Express
nginx-proxy-manager # Proxy reverso y balanceador
```
**Enrutamiento Producción:**
- `https://snatchGame.interno.com` → Cliente UI
- `https://snatchgGameAdmin.interno.com` → Admin UI
- `https://snatchGameServer.interno.com` → API Servidor Colyseus
**Puertos de Producción:**
- Cliente: Puerto 3010 (externo) → 3000 (interno)
- Admin: Puerto 3011 (externo) → 3001 (interno)
- Servidor: Puerto 3067 (externo) → 2567 (interno)
## UI de Administración
**Arquitectura:**
- Servidor Express independiente (Puerto 3001)
- Comunicación SSE con servidor Colyseus
- Actualización de estado cada 250ms (polling optimizado)
- Una interfaz principal (múltiples conexiones opcionales)
- Separación URLs: HTTP interna, HTTPS externa
- Auto-reconexión y heartbeat para estabilidad
**Funcionalidades principales:**
- Dashboard con estadísticas en tiempo real:
- Cantidad de jugadores conectados
- Cantidad de partidas activas
- Ronda actual del juego global
- Estados: esperando jugadores, pausa, juego terminado
- Nombres de las rondas
- Panel de control:
- Expulsar jugadores individuales y todos (con notificaciones)
- Control de rondas global (avanzar/retroceder en todas las salas)
- Pausar/reanudar juego
- Cancelar partidas de grupos específicos
- Lista de jugadores detallada:
- Nombre, sala, rol del juego y tipo de productor
- Tokens actuales (🦃 pavos, ☕ café, 🌽 maíz)
- Estado de conexión en tiempo real
- Sistema de notificaciones a clientes:
- Expulsión con redirección automática
- Cambios de ronda globales
- Pausas y reanudaciones
- Panel de debugging para IT profesional
- Transparencia total del estado del servidor
**Usuarios objetivo:**
- Admin no-técnico: Vista simple de estadísticas
- IT profesional: Vista detallada de debugging
- Comentaristas deportivos: Información clara para narración en vivo
## Comandos Importantes
### Desarrollo
- **Servidor**: `cd server && npm run dev` (Puerto 2567)
- **Cliente**: `cd client && npm run dev` (Puerto 3000)
- **Admin**: `cd admin && npm run dev` (Puerto 3001)
### Generación de Tipos TypeScript
- **Manual**: `cd server && npx schema-codegen src/rooms/GameRoom.ts --ts --output ../client/src/types/`
- **Automático (cliente)**: `cd client && npm run generate-types`
- **Automático (admin)**: `cd admin && npm run generate-types`
### Testing y Debugging
- **Verificar puertos libres**: `lsof -i :2567,3000,3001`
- **Cerrar procesos**: `pkill -f "ts-node-dev" && pkill -f "vite" && pkill -f "node.*server"`
- **Cerrar procesos específicos**: `kill <PID>` (usar PID del proceso)
**IMPORTANTE:**
- ⚠️ **Siempre cerrar servicios** después de testing/debugging
- ⚠️ **Si servicios no arrancan** probablemente el usuario los levantó manualmente
- ⚠️ **Verificar puertos** antes de iniciar servicios para evitar conflictos
### Producción Local
- **Build Server**: `cd server && npm run build`
- **Start Server**: `cd server && npm run start`
- **Start Client**: `cd client && npm run start`
- **Start Admin**: `cd admin && npm run start`
### Docker (Producción)
- **Build todas las imágenes**: `docker-compose build`
- **Start en producción**: `docker-compose up -d`
- **Stop servicios**: `docker-compose down`
- **Logs en tiempo real**: `docker-compose logs -f`
- **Logs de servicio específico**: `docker-compose logs -f [snatchgame-server|snatchgame-client|snatchgame-admin]`
- **Rebuild tras cambios**: `docker-compose down && docker-compose up -d --build`
- **Ver estado de contenedores**: `docker-compose ps`
### CI/CD (Gitea Actions)
- **Push automático**: `git push gitea main` (triggerea build y deploy automático)
- **Ver logs de CI/CD**: Revisar en Gitea Actions tab
- **Conditional builds**: Solo builds los servicios con cambios detectados
### Variables de Entorno
- Desarrollo: `.env.development`
- Producción: `.env.production`
### VSCode Tasks
- **Ctrl+Shift+P** → `Tasks: Run Task`
- **Start Server** - Ejecutar solo servidor Colyseus
- **Start Client** - Ejecutar solo cliente UI
- **Start Admin** - Ejecutar solo admin UI
- **Start All Services** - Ejecutar todos los servicios paralelo
- **Install All Dependencies** - Instalar deps de todos
- **Build Server** - Compilar servidor TypeScript
## Gestión de Tipos TypeScript
### Schema-Codegen (Colyseus)
**Funcionalidad:**
- Genera automáticamente tipos TypeScript desde Schema classes del servidor
- Solo funciona para clases que extienden `Schema` con decoradores `@type`
- Mantiene sincronización perfecta entre servidor y cliente
- Es la práctica oficial recomendada por Colyseus
**Comandos:**
```bash
# Desde directorio server
npx schema-codegen src/rooms/GameRoom.ts --ts --output ../client/src/types/
# Desde directorio client (npm script configurado)
npm run generate-types
```
**Archivos generados:**
```
client/src/types/
├── Player.ts # Auto-generado desde server/src/rooms/GameRoom.ts
├── GameState.ts # Auto-generado desde server/src/rooms/GameRoom.ts
└── index.ts # Re-exports + tipos auxiliares manuales
```
### Tipos No-Schema (Manuales)
**Importante:** Los tipos que NO son Schema classes deben copiarse manualmente:
**Ejemplos de tipos manuales:**
- `GameRoomOptions` (interfaces para opciones)
- `export interface` (interfaces auxiliares)
- `export type` (type aliases)
- Enums, constantes, utilidades
**Ubicación:**
- **Server**: `server/src/rooms/GameRoom.ts` (junto a Schema classes)
- **Cliente**: `client/src/types/index.ts` (copiados manualmente)
- **Admin**: `admin/src/types/index.ts` (copiados manualmente)
**Flujo de trabajo:**
1. **Schema classes**: Se auto-generan con schema-codegen
2. **Tipos auxiliares**: Se copian manualmente cuando se añaden/modifican
3. **Consistencia**: Usar nombres idénticos entre server y client
## API Admin - Arquitectura Técnica
### Endpoints Implementados
**Servidor Colyseus (Puerto 2567):**
- `GET /api/admin/stats` - Estadísticas en tiempo real usando `matchMaker.query()`
- `POST /api/admin/kick-player` - Expulsar jugador específico con notificación
- `POST /api/admin/kick-all-players` - Expulsar todos los jugadores con notificaciones
- `POST /api/admin/pause-game` - Pausar todas las partidas activas
- `POST /api/admin/resume-game` - Reanudar partidas pausadas
- `POST /api/admin/advance-round` - Avanzar ronda globalmente
- `POST /api/admin/previous-round` - Retroceder ronda globalmente
- `POST /api/admin/cancel-game` - Cancelar partidas específicas o todas
### Métodos GameRoom Implementados
- `getInspectData()` - Datos completos para el admin (compatible con monitor oficial)
- `pauseGame()` - Pausar juego con broadcast a clientes
- `resumeGame()` - Reanudar juego con broadcast a clientes
- `advanceRound()` - Avanzar ronda con límite máximo 10
- `previousRound()` - Retroceder ronda con límite mínimo 1
- `_forceClientDisconnect(sessionId)` - Expulsar jugador con notificación
- `_forceDisconnectAllClients()` - Expulsar todos con notificaciones
### Comunicación Cliente-Servidor
**Mensajes del servidor a clientes:**
- `adminKicked` - Notificación de expulsión individual
- `gamePaused` - Notificación de pausa del juego
- `gameResumed` - Notificación de reanudación del juego
- `roundChanged` - Notificación de cambio de ronda global
**Manejo en el cliente:**
- Auto-redirección a home al recibir `adminKicked`
- Alerts informativos para cambios de estado
- Logging detallado de eventos administrativos
### Principios de Diseño
- **API Oficial Colyseus**: Sin hacks de variables globales
- **matchMaker.query()**: Acceso seguro a información de salas
- **matchMaker.remoteRoomCall()**: Ejecución remota de métodos
- **Type Safety**: Sincronización completa TypeScript
- **Error Handling**: Try/catch en todos los endpoints
- **Graceful Notifications**: Delay de 1 segundo para procesar mensajes
## Notas Específicas
- **Offline**: Sin dependencias externas de internet
- **Microservicios**: Arquitectura separada por responsabilidades
- **Red Local**: Funciona completamente en LAN
- **Monorepo**: Un repositorio para todos los servicios
- **Docker**: Orquestación con docker-compose en producción
- **Nginx Proxy Manager**: Enrutamiento y balanceo de carga
- **Variables de Entorno**: Configuración por ambiente (.env)
- **Logging**: Detallado para debugging profesional
- **Tipos TypeScript**: Auto-generación con schema-codegen + copiar tipos auxiliares manualmente
- **Admin Dashboard**: Completamente funcional con control total del juego
- **Separación URLs**: HTTP para comunicación interna, HTTPS para navegadores
- **CI/CD Automático**: Gitea Actions con conditional building y deploy automático
- **SSE Optimizado**: Anti-buffering, polling 250ms, heartbeat y auto-reconexión
## Arquitectura de Producción
### Flujo de Comunicación
```
Browser Nginx Proxy Docker Containers
Manager
┌─────────────┐ ┌─────────────┐ ┌─────────────────┐
│ HTTPS │ ────────► │ Routes │ ────────► │ HTTP (interno) │
│ Requests │ │ Traffic │ │ Entre servicios │
└─────────────┘ └─────────────┘ └─────────────────┘
Frontend (Vue) ──HTTPS──► Nginx ──HTTP──► Express Server ──HTTP──► Colyseus
SSE Stream ──HTTP──► Admin Service
```
### Separación de Responsabilidades
**Nginx Proxy Manager:**
- Terminación SSL/TLS
- Enrutamiento por dominio
- Balance de carga
- Certificados automáticos
**Docker Network "principal":**
- Comunicación con Nginx
- Acceso externo controlado
- Isolation de otros servicios
**Docker Network "snatchgame-network":**
- Comunicación interna entre servicios
- Sin acceso externo directo
- Optimizada para velocidad
### URLs y Configuración
**Externa (HTTPS - Navegador):**
```javascript
// Frontend usa PUBLIC_SERVER_URL
const serverUrl = config.serverUrl // https://snatchGameServer.interno.com
this.client = new Client(serverUrl.replace('https://', 'wss://'))
```
**Interna (HTTP - Contenedores):**
```javascript
// Backend usa SERVER_URL
const gameServerUrl = process.env.SERVER_URL // http://snatchgame-server:2567
const response = await fetch(`${gameServerUrl}/api/admin/stats`)
```
### Health Checks y Monitoring
**Health Endpoints:**
- `/health` en todos los servicios
- Respuesta JSON con status y metadata
- Usado por Docker y monitoring
**Logging Estructurado:**
```javascript
console.log(`[SSE] Connection #${connectionId} established. Total: ${sseConnections}`)
console.log(`[SSE] Stats fetched successfully in ${fetchTime}ms`)
```
**Métricas de Performance:**
- SSE polling: 250ms (4 updates/segundo)
- Heartbeat: 30 segundos
- Auto-reconnect: 5 segundos
- Health check: 30 segundos
### Security Best Practices
**Network Isolation:**
- Servicios en red interna Docker
- Solo puertos necesarios expuestos
- Nginx como único punto de entrada
**SSL/TLS:**
- HTTPS/WSS para comunicación externa
- HTTP interno (rápido y seguro en Docker)
- Certificados manejados por Nginx
**Environment Variables:**
- Configuración sensitive via env vars
- Separación desarrollo/producción
- Runtime configuration endpoints

View File

@@ -1,426 +0,0 @@
# 🚀 Guía de Deployment - SnatchGame
## 📋 Resumen
Este documento detalla el proceso completo de deployment de SnatchGame en producción usando Docker, Gitea Actions y Nginx Proxy Manager.
## 🏗️ Arquitectura de Producción
### Componentes del Sistema
```
┌────────────────────────────────────────────────────────────────┐
│ Nginx Proxy Manager │
│ (Red "principal") │
├────────────────────────────────────────────────────────────────┤
│ │
│ 🌐 snatchGame.interno.com ──► snatchgame-client:3000 │
│ 🎯 snatchGameServer.interno.com ──► snatchgame-server:2567 │
│ 📊 snatchgGameAdmin.interno.com ──► snatchgame-admin:3001 │
│ │
└────────────────────────────────────────────────────────────────┘
```
### Servicios Docker
| Servicio | Imagen | Puerto Interno | Puerto Externo | Descripción |
|----------|--------|----------------|----------------|-------------|
| `snatchgame-server` | `gitea.interno.com/nucleo000/snatchgame-server:latest` | 2567 | 3067 | Servidor Colyseus |
| `snatchgame-client` | `gitea.interno.com/nucleo000/snatchgame-client:latest` | 3000 | 3010 | Cliente Vue + Express |
| `snatchgame-admin` | `gitea.interno.com/nucleo000/snatchgame-admin:latest` | 3001 | 3011 | Admin Vue + Express |
## 🔧 Configuración de URLs
### Separación Interna/Externa
El sistema utiliza una arquitectura de **doble URL** para optimizar la comunicación:
#### URLs Externas (HTTPS)
- **Propósito**: Comunicación navegador ↔ servicios
- **Protocolo**: HTTPS/WSS (seguro)
- **Destino**: Nginx Proxy Manager
```
Cliente Frontend → https://snatchGameServer.interno.com (WebSocket)
Admin Frontend → https://snatchGameServer.interno.com (Fetch API)
```
#### URLs Internas (HTTP)
- **Propósito**: Comunicación contenedor ↔ contenedor
- **Protocolo**: HTTP (rápido, sin SSL)
- **Destino**: Directo entre contenedores
```
Admin Server → http://snatchgame-server:2567 (SSE, Control API)
Client Server → http://snatchgame-server:2567 (Health checks)
```
### Variables de Entorno
```yaml
# En docker-compose.yml
environment:
- NODE_ENV=production
- SERVER_URL=http://snatchgame-server:2567 # URL interna
- PUBLIC_SERVER_URL=https://snatchGameServer.interno.com # URL externa
```
## 🐳 Docker Configuration
### Dockerfiles
#### Servidor (server/Dockerfile)
```dockerfile
FROM node:20-alpine
RUN apk add --no-cache git wget
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build && npm prune --production
EXPOSE 2567
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=40s \
CMD wget --no-verbose --tries=1 --spider http://localhost:2567/health || exit 1
CMD ["npm", "start"]
```
#### Cliente y Admin (client/Dockerfile, admin/Dockerfile)
```dockerfile
FROM node:20-alpine
RUN apk add --no-cache git wget
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build:prod # Skips type generation in Docker
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=40s \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["npm", "start"]
```
### Docker Compose
```yaml
version: '3.8'
services:
snatchgame-server:
image: gitea.interno.com/nucleo000/snatchgame-server:latest
container_name: snatchgame-server
ports:
- "3067:2567"
environment:
- NODE_ENV=production
- PORT=2567
networks:
- principal
- snatchgame-network
restart: unless-stopped
snatchgame-client:
image: gitea.interno.com/nucleo000/snatchgame-client:latest
container_name: snatchgame-client
ports:
- "3010:3000"
environment:
- NODE_ENV=production
- PORT=3000
- SERVER_URL=http://snatchgame-server:2567
- PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
depends_on:
- snatchgame-server
networks:
- principal
- snatchgame-network
restart: unless-stopped
snatchgame-admin:
image: gitea.interno.com/nucleo000/snatchgame-admin:latest
container_name: snatchgame-admin
ports:
- "3011:3001"
environment:
- NODE_ENV=production
- PORT=3001
- SERVER_URL=http://snatchgame-server:2567
- PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
depends_on:
- snatchgame-server
networks:
- principal
- snatchgame-network
restart: unless-stopped
networks:
principal:
external: true
snatchgame-network:
driver: bridge
```
## ⚙️ CI/CD Pipeline
### Gitea Actions (.gitea/workflows/build-and-deploy.yml)
```yaml
name: Build and Deploy SnatchGame
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build-server:
runs-on: ubuntu-latest
if: contains(github.event.head_commit.modified, 'server/') || github.event_name == 'pull_request'
steps:
- uses: actions/checkout@v4
- name: Build and push server image
run: |
docker build -t gitea.interno.com/nucleo000/snatchgame-server:latest ./server
docker push gitea.interno.com/nucleo000/snatchgame-server:latest
build-client:
runs-on: ubuntu-latest
if: contains(github.event.head_commit.modified, 'client/') || github.event_name == 'pull_request'
steps:
- uses: actions/checkout@v4
- name: Build and push client image
run: |
docker build -t gitea.interno.com/nucleo000/snatchgame-client:latest ./client
docker push gitea.interno.com/nucleo000/snatchgame-client:latest
build-admin:
runs-on: ubuntu-latest
if: contains(github.event.head_commit.modified, 'admin/') || github.event_name == 'pull_request'
steps:
- uses: actions/checkout@v4
- name: Build and push admin image
run: |
docker build -t gitea.interno.com/nucleo000/snatchgame-admin:latest ./admin
docker push gitea.interno.com/nucleo000/snatchgame-admin:latest
deploy:
runs-on: ubuntu-latest
needs: [build-server, build-client, build-admin]
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- name: Deploy to production
run: |
docker-compose down
docker-compose pull
docker-compose up -d
```
### Conditional Building
El pipeline utiliza **conditional building** basado en archivos modificados:
- **server/** → Builds `snatchgame-server`
- **client/** → Builds `snatchgame-client`
- **admin/** → Builds `snatchgame-admin`
- **Pull requests** → Builds todo pero no deploya
## 🔄 Optimizaciones SSE
### Problema Identificado
La comunicación SSE entre el navegador y los contenedores Docker presentaba latencia alta (~10 segundos entre actualizaciones).
### Solución Implementada
#### Headers Anti-Buffering
```javascript
// admin/server.js
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no', // Disable nginx buffering
'Content-Encoding': 'identity' // Disable compression
});
```
#### Polling Optimizado
```javascript
// Reducido de 500ms a 250ms para updates más rápidos
const pollInterval = setInterval(async () => {
// Fetch game stats...
}, 250);
```
#### Heartbeat Mechanism
```javascript
// Keepalive cada 30 segundos
const heartbeatInterval = setInterval(() => {
res.write(': heartbeat\n\n');
}, 30000);
```
#### Auto-reconexión Cliente
```javascript
// admin/src/services/adminService.ts
this.eventSource.onerror = (error) => {
// Auto-reconnect after 5 seconds
setTimeout(() => {
if (!this.isConnected) {
this.connect(this.callback!);
}
}, 5000);
};
```
## 🚀 Proceso de Deployment
### 1. Push a Main Branch
```bash
git add .
git commit -m "feature: new functionality"
git push gitea main
```
### 2. Automatic CI/CD
- Gitea Actions detecta cambios
- Builds las imágenes necesarias
- Push al registry interno
- Deploy automático en producción
### 3. Verificación
```bash
# Verificar estado de contenedores
docker-compose ps
# Ver logs en tiempo real
docker-compose logs -f
# Health check manual
curl -f http://localhost:3067/health
curl -f http://localhost:3010/health
curl -f http://localhost:3011/health
```
### 4. Rollback si es Necesario
```bash
# Rollback a versión anterior
docker-compose down
git checkout <previous-commit>
docker-compose up -d --build
```
## 🔧 Comandos de Mantenimiento
### Development to Production
```bash
# Build local para testing
docker-compose build
# Deploy en producción
docker-compose up -d
# Rebuild completo tras cambios
docker-compose down && docker-compose up -d --build
```
### Monitoring
```bash
# Logs de servicio específico
docker-compose logs -f snatchgame-server
docker-compose logs -f snatchgame-client
docker-compose logs -f snatchgame-admin
# Estadísticas de recursos
docker stats
# Estado de redes
docker network ls
docker network inspect snatchgame_principal
```
### Troubleshooting
```bash
# Verificar conectividad entre contenedores
docker exec snatchgame-admin curl http://snatchgame-server:2567/health
# Reiniciar servicio específico
docker-compose restart snatchgame-admin
# Limpiar imágenes antiguas
docker image prune -f
```
## 📊 Monitoring y Salud del Sistema
### Health Checks
Todos los servicios incluyen health checks automáticos:
```yaml
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:2567/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
```
### Logs Estructurados
```javascript
// Logs con timestamps y prefijos para debugging
console.log(`[SSE] Connection #${connectionId} established. Total: ${sseConnections}`);
console.log(`[SSE] Stats fetched successfully in ${fetchTime}ms`);
```
### Métricas de Rendimiento
- **SSE Update Frequency**: 250ms
- **Heartbeat Interval**: 30s
- **Auto-reconnect Delay**: 5s
- **Health Check Interval**: 30s
## 🔒 Seguridad
### HTTPS/WSS
- Todas las comunicaciones externas usan HTTPS/WSS
- Certificados SSL manejados por Nginx Proxy Manager
- Comunicación interna HTTP (rápida y segura dentro de Docker)
### Network Isolation
- Red `principal`: Comunicación con Nginx
- Red `snatchgame-network`: Comunicación interna entre servicios
- Puertos expuestos mínimos
### Environment Variables
- Configuración sensitive via variables de entorno
- Separación clara desarrollo/producción
- No secrets hardcoded en código
## 📈 Escalabilidad
### Horizontal Scaling
```yaml
# Múltiples instancias del mismo servicio
snatchgame-server-1:
image: gitea.interno.com/nucleo000/snatchgame-server:latest
# ...
snatchgame-server-2:
image: gitea.interno.com/nucleo000/snatchgame-server:latest
# ...
```
### Load Balancing
- Nginx Proxy Manager puede distribuir carga
- Health checks aseguran disponibilidad
- Auto-restart en caso de fallas
## 🎯 Próximos Pasos
1. **Monitoring Avanzado**: Prometheus + Grafana
2. **Backup Automático**: Estrategia de backups de datos
3. **Blue-Green Deployment**: Deploy sin downtime
4. **Resource Limits**: CPU/Memory limits por contenedor
5. **Log Aggregation**: ELK Stack o similar
---
> 📝 **Nota**: Esta documentación refleja el estado actual del sistema al 2025-07-05. Actualizar tras modificaciones significativas.

490
README.md
View File

@@ -1,490 +0,0 @@
# 🎮 SnatchGame
[![Version](https://img.shields.io/badge/version-0.0.8--alpha-orange.svg)](https://github.com/username/snatchgame)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Node.js](https://img.shields.io/badge/node-%3E%3D18.0.0-green.svg)](https://nodejs.org/)
[![Vue.js](https://img.shields.io/badge/vue-3.0+-brightgreen.svg)](https://vuejs.org/)
[![Colyseus](https://img.shields.io/badge/colyseus-0.16+-purple.svg)](https://colyseus.io/)
Un juego multijugador educativo que simula la evolución de instituciones y cooperación, basado en el **"Snatch Game"** de **Elinor Ostrom**. Construido con **Colyseus.io** y **Vue 3** para redes locales.
> ✨ **Admin Dashboard Completo** - Versión Alpha (v0.0.8-alpha) con interfaz de administración profesional
## 🎓 Sobre el Juego
**Snatch or Share** es una simulación interactiva que permite a los participantes experimentar cómo las reglas, la confianza y los arreglos institucionales afectan la cooperación en intercambios descentralizados. Basado en el trabajo de la Nobel de Economía **Elinor Ostrom** sobre gobernanza de recursos comunes.
### 🎯 Objetivos Educativos
- Demostrar la evolución de instituciones en el intercambio
- Experimentar con diferentes sistemas de gobernanza
- Entender el rol de la confianza en la cooperación
- Aplicar conceptos de teoría de juegos en tiempo real
## 🚀 Características del Juego
- **👥 Multijugador exacto** - Salas de exactamente 3 jugadores
- **🎭 Roles únicos** - Productor de Pavos, Café o Maíz
- **⚡ Tiempo real** - Sincronización instantánea con Colyseus.io
- **🔄 Sistema de intercambio** - Ofertas, negociaciones y "snatch"
- **📊 Cálculo automático** - Puntuación basada en tokens
- **📱 Responsive** - Interfaz optimizada para desktop y móvil
- **🎯 Red local** - Funciona completamente offline
- **📈 Progresión por rondas** - 5 rondas con reglas evolutivas
- **🎛️ Admin Dashboard** - Interfaz completa de administración y monitoreo
- **🔔 Notificaciones** - Sistema completo de alertas para jugadores
## 🎮 Cómo Jugar
### Preparación
1. **Únete a una sala** - Exactamente 3 jugadores requeridos
2. **Rol asignado** - Recibes un rol de productor único al azar
3. **Tokens iniciales** - Comienzas con 5 tokens de tu tipo
### Mecánicas de Juego
1. **Haz ofertas** - Click en otros jugadores para ofertar
2. **Responde ofertas** - Acepta, rechaza o haz "snatch"
3. **Acumula puntos** - Tokens propios = 1pt, ajenos = 2pts
4. **Estrategia** - Coopera o compite según las reglas de la ronda
### Progresión (5 Rondas)
- **Ronda 1-2**: Estado de naturaleza (sin reglas)
- **Ronda 3**: Reglas contraproductivas
- **Ronda 4**: Normas sociales (shame tokens)
- **Ronda 5**: Gobernanza institucional (juez rotativo)
## 🛠️ Stack Tecnológico
### Backend
- **[Colyseus.io](https://colyseus.io/)** - Framework multijugador en tiempo real
- **Node.js** + **TypeScript**
- **Express.js**
### Frontend
- **[Vue 3](https://vuejs.org/)** - Composition API
- **TypeScript** - Tipado estricto
- **Vite** - Build tool ultra-rápido
- **CSS vanilla** - Estilos custom
### Desarrollo
- **Schema-codegen** - Sincronización automática de tipos
- **Hot reload** - Desarrollo en vivo
- **ESLint + Prettier** - Calidad de código
## 📦 Instalación
### Prerrequisitos
- **Node.js** >= 18.0.0
- **npm** >= 8.0.0
### 1. Clonar el repositorio
```bash
git clone https://github.com/username/snatchgame.git
cd snatchgame
```
### 2. Instalar dependencias
```bash
# Instalar todas las dependencias automáticamente
npm run install:all
# O manualmente:
# Servidor
cd server && npm install
# Cliente
cd ../client && npm install
# Admin
cd ../admin && npm install
```
## 🚀 Ejecución
### Desarrollo
#### Opción 1: VSCode Tasks (Recomendado)
```bash
# Presiona Ctrl+Shift+P → "Tasks: Run Task"
# Selecciona "Start All Services"
```
#### Opción 2: Manual
```bash
# Terminal 1 - Servidor
cd server
npm run dev
# Terminal 2 - Cliente
cd client
npm run dev
# Terminal 3 - Admin Dashboard
cd admin
npm run dev
```
### URLs de desarrollo
- **Cliente**: http://localhost:3000
- **Servidor**: http://localhost:2567
- **Admin Dashboard**: http://localhost:3001
- **Monitor Colyseus**: http://localhost:2567/monitor
### Producción con Docker
**URLs de Producción:**
- **Cliente**: https://snatchGame.interno.com
- **Servidor**: https://snatchGameServer.interno.com
- **Admin Dashboard**: https://snatchgGameAdmin.interno.com
```bash
# Build todas las imágenes
docker-compose build
# Deploy en producción
docker-compose up -d
# Ver logs en tiempo real
docker-compose logs -f
# Rebuild y redeploy tras cambios
docker-compose down && docker-compose up -d --build
```
## 🎮 Interfaz del Juego
### Vista Desktop
- **Layout de 2 columnas**: Jugadores a la izquierda, ofertas a la derecha
- **Jugador actual prominente**: Tarjeta grande en la parte inferior
- **Otros jugadores compactos**: Tarjetas pequeñas y clickeables
- **Panel de ofertas**: Scroll customizado con ofertas en tiempo real
### Vista Móvil
- **Layout vertical**: Jugadores arriba, ofertas abajo
- **Formulario modal**: Ofertas en modal flotante
- **Botones optimizados**: +/- táctiles para cantidades
- **Scroll adaptativo**: Altura limitada con navegación suave
### Componentes Principales
- **PlayerCard**: Información de jugador con tokens y puntos
- **TradeOfferCard**: Ofertas con acciones (Accept/Reject/Snatch)
- **MakeOfferForm**: Formulario con botones +/- intuitivos
- **OfferModal**: Modal flotante para crear ofertas dirigidas
## 🎛️ Admin Dashboard
El **Admin Dashboard** proporciona control completo y monitoreo en tiempo real del juego, diseñado tanto para administradores técnicos como para comentaristas no-técnicos.
### 📊 Características Principales
#### **Información en Tiempo Real**
- **👥 Lista de Jugadores Detallada**: Nombre, sala, rol, tipo de productor y tokens actuales
- **📈 Estadísticas Globales**: Jugadores conectados, partidas activas, ronda actual
- **🎯 Estado del Juego**: En progreso, pausado, esperando jugadores
- **🔄 Actualización Automática**: SSE con polling cada 500ms
#### **Control de Jugadores**
- **🚫 Expulsar Jugador Individual**: Con notificación al cliente y redirección automática
- **🚫🚫 Expulsar Todos los Jugadores**: Vaciar todas las salas con notificaciones apropiadas
- **👤 Información Detallada**: Ver tokens específicos (🦃 pavos, ☕ café, 🌽 maíz)
#### **Control del Juego**
- **⏸️ Pausar Juego**: Pausar todas las partidas activas
- **▶️ Reanudar Juego**: Reanudar partidas pausadas
- **⏮️ Retroceder Ronda**: Cambio global a ronda anterior (mínimo 1)
- **⏭️ Avanzar Ronda**: Cambio global a ronda siguiente (máximo 10)
#### **Notificaciones a Clientes**
- **🔔 Expulsión**: Mensaje personalizado y redirección automática
- **🎯 Cambio de Ronda**: Notificación inmediata de nuevas rondas
- **⏸️ Estado del Juego**: Alertas de pausa/reanudación
### 🎯 Usuarios Objetivo
- **👨‍💼 Administrador No-Técnico**: Vista limpia con estadísticas esenciales
- **👨‍💻 IT Profesional**: Información de debugging y estado técnico detallado
- **🎙️ Comentaristas Deportivos**: Información clara para narración en vivo
### 🏗️ Arquitectura Técnica
- **API Oficial Colyseus**: Uso de `matchMaker.query()` y `matchMaker.remoteRoomCall()`
- **Comunicación Bidireccional**: SSE para updates, HTTP para control
- **Sin Variables Globales**: Implementación limpia y mantenible
- **Type Safety**: Sincronización completa de tipos TypeScript
- **Separación URLs**: URLs internas HTTP para contenedores, HTTPS para clientes
- **Optimización SSE**: Anti-buffering headers, polling optimizado (250ms), heartbeat
## ⚙️ Configuración
### Variables de Entorno
**Desarrollo** (`.env.development`):
```env
VITE_SERVER_URL=ws://localhost:2567
NODE_ENV=development
PORT=2567
```
**Producción** (`.env.production`):
```env
NODE_ENV=production
# Servidor
PORT=2567
# Cliente
SERVER_URL=http://snatchgame-server:2567
PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
# Admin
SERVER_URL=http://snatchgame-server:2567
PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
```
### Configuración de Logs
- **Desarrollo**: Logs habilitados por defecto
- **Producción**: Logs deshabilitados por defecto
- **Usuario**: Configurable en "Configuración" → "Logs de depuración"
## 🏗️ Arquitectura
### Desarrollo
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Client UI │ │ Colyseus │ │ Admin UI │
│ (Vue 3) │◄──►│ Server │◄──►│ (Vue 3 + SSE) │
│ Port 3000 │ │ Port 2567 │ │ Port 3001 │
└─────────────────┘ └─────────────────┘ └─────────────────┘
```
### Producción con Docker
```
┌────────────────────────────────────────────────────────────────┐
│ Nginx Proxy Manager │
│ Red "principal" │
├────────────────────────────────────────────────────────────────┤
│ https://snatchGame.interno.com │
│ ↓ (Puerto 3010) │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ snatchgame- │ │ snatchgame- │ │
│ │ client │◄────┤ server │ │
│ │ (Vue + Express) │ │ (Colyseus) │ │
│ │ Puerto 3000 │ │ Puerto 2567 │ │
│ └─────────────────┘ └─────────────────┘ │
│ ▲ ▲ │
│ │ │ │
│ │ ┌─────────────────┐ │
│ └───────────────┤ snatchgame- │ │
│ │ admin │ │
│ │ (Vue + Express) │ │
│ https://snatchgGameAdmin.interno.com │ │
│ │ Puerto 3001 │ │
│ └─────────────────┘ │
│ ↑ (Puerto 3011) │
└────────────────────────────────────────────────────────────────┘
```
### Separación de URLs en Producción
**URLs Externas (HTTPS - Navegador → Nginx):**
- Cliente: `https://snatchGame.interno.com`
- Servidor: `https://snatchGameServer.interno.com`
- Admin: `https://snatchgGameAdmin.interno.com`
**URLs Internas (HTTP - Contenedor → Contenedor):**
- Servidor: `http://snatchgame-server:2567`
- Cliente API: `http://snatchgame-client:3000`
- Admin API: `http://snatchgame-admin:3001`
### Comunicación Admin
- **SSE (Server-Sent Events)**: Servidor → Admin UI
- **Polling**: Actualización cada 250ms (optimizado)
- **Control**: Admin → Servidor (HTTP endpoints)
- **Heartbeat**: Keepalive cada 30 segundos
### Sincronización de Tipos
```bash
# Los tipos se generan automáticamente del servidor al cliente
npm run generate-types
```
## 🧪 Testing
```bash
# Servidor
cd server
npm test
# Cliente
cd client
npm test
# E2E
npm run test:e2e
```
## 📁 Estructura del Proyecto
```
snatchgame/
├── 📁 server/ # Colyseus.io backend
│ ├── src/
│ │ ├── rooms/
│ │ │ └── GameRoom.ts # Lógica principal del juego
│ │ ├── app.config.ts # Configuración Colyseus
│ │ └── index.ts # Entry point
│ └── README.md # Documentación del servidor
├── 📁 client/ # Vue 3 frontend
│ ├── src/
│ │ ├── components/ # Componentes Vue
│ │ │ ├── Game.vue # Componente principal
│ │ │ ├── PlayerCard.vue
│ │ │ ├── TradeOfferCard.vue
│ │ │ ├── MakeOfferForm.vue
│ │ │ ├── ScrollableOffers.vue
│ │ │ └── OfferModal.vue
│ │ ├── services/ # Game client & logger
│ │ │ ├── gameClient.ts
│ │ │ └── logger.ts
│ │ ├── types/ # Auto-generated types
│ │ │ ├── GameState.ts
│ │ │ ├── Player.ts
│ │ │ ├── TradeOffer.ts
│ │ │ └── TokenInventory.ts
│ │ └── main.ts
│ ├── server.js # Express server (producción)
│ └── README.md # Documentación del cliente
├── 📁 admin/ # Admin dashboard
│ ├── src/
│ │ ├── components/ # Componentes Vue admin
│ │ ├── services/ # Admin service
│ │ │ └── adminService.ts
│ │ └── main.ts
│ ├── server.js # Express server (producción)
│ └── README.md # Documentación del admin
├── 🎮 gameRules.md # Reglas del juego detalladas
├── 🐳 docker-compose.yml # Orquestación Docker
├── 📋 CLAUDE.md # Guía de desarrollo
└── 📖 README.md # Este archivo
```
## 🤝 Contribuir
1. **Fork** el proyecto
2. **Crea** una feature branch (`git checkout -b feature/AmazingFeature`)
3. **Commit** tus cambios (`git commit -m 'Add AmazingFeature'`)
4. **Push** a la branch (`git push origin feature/AmazingFeature`)
5. **Abre** un Pull Request
### Guías de contribución
- Sigue las convenciones de código existentes
- Añade tests para nuevas características
- Actualiza la documentación si es necesario
- Los commits deben ser descriptivos
## 🐛 Debugging
### Logs de desarrollo
1. Ve a **Configuración** en la UI
2. Habilita **"Logs de depuración"**
3. Abre **DevTools** (F12) para ver logs detallados
### Comandos útiles
```bash
# Verificar puertos libres
lsof -i :2567,3000,3001
# Cerrar procesos
pkill -f "ts-node-dev" && pkill -f "vite"
# Regenerar tipos
cd client && npm run generate-types
```
## 🚀 Deploy
### Docker (Recomendado)
```bash
# Build y start
docker-compose up -d
# Logs
docker-compose logs -f
# Stop
docker-compose down
```
### Manual
```bash
# Build servidor
cd server && npm run build
# Build cliente
cd client && npm run build
# Start producción
npm run start
```
## 📋 Roadmap
### Funcionalidades del Juego
- [x] 🎮 Ronda 1: Estado de naturaleza (completado)
- [ ] 🎭 Ronda 2-5: Implementar reglas evolutivas
- [ ] 👨‍⚖️ Sistema de Judge rotativo
- [ ] 😔 Shame tokens y penalizaciones
- [ ] 📊 Estadísticas por ronda
- [ ] 🏆 Sistema de puntuación final
### Mejoras de UI/UX
- [x] 📱 Layout responsivo optimizado
- [x] 🎯 Formulario con botones +/-
- [x] 🔄 Scroll customizado para ofertas
- [ ] 🎨 Themes y customización visual
- [ ] 🔊 Efectos de sonido y feedback
- [ ] ⚡ Animaciones de transición
- [ ] 📊 Gráficos y visualizaciones
### Infraestructura
- [x] 📈 UI de administración completa
- [x] Dashboard con estadísticas en tiempo real
- [x] Panel de control para administrar partidas
- [x] Sistema de expulsión de jugadores
- [x] Pausa/reanudación de partidas
- [x] Control de rondas globales
- [x] Información detallada de jugadores con tokens
- [x] Notificaciones automáticas a clientes
- [x] Optimización SSE (250ms polling, heartbeat, anti-buffering)
- [ ] Historial de partidas anteriores
- [x] 🐳 Docker en producción
- [x] Dockerfiles para todos los servicios
- [x] Docker Compose con orquestación completa
- [x] Gitea Actions CI/CD pipeline
- [x] Separación URLs internas/externas para SSL
- [x] Red principal para Nginx Proxy Manager
- [x] Health checks y restart policies
- [ ] 📱 PWA support
- [ ] 🌍 Multi-idioma (EN/ES)
- [ ] 🔒 Sistema de salas privadas
- [ ] 📄 Exportar resultados (PDF/CSV)
## 📄 Licencia
Este proyecto está bajo la licencia **MIT**. Ver el archivo [LICENSE](LICENSE) para más detalles.
## 👥 Autores
- **NucleoServices** - *Desarrollo inicial* - [@draganel](https://github.com/draganel)
## 📞 Soporte
¿Encontraste un bug? ¿Tienes una sugerencia?
- 🐛 **Issues**: [GitHub Issues](https://github.com/username/snatchgame/issues)
- 💬 **Discusiones**: [GitHub Discussions](https://github.com/username/snatchgame/discussions)
- 📧 **Email**: support@nucleoservices.com
---
<div align="center">
**⭐ ¡Dale una estrella si te gusta el proyecto! ⭐**
Hecho con ❤️ por **NucleoServices**
</div>

26
TODO.md
View File

@@ -1,26 +0,0 @@
# TODO - SnatchGame
## Problemas Técnicos Pendientes
### TypeScript - Tipos en Game.vue
**Problema:** Se tuvo que usar `any` en Game.vue para el prop `gameClient` debido a incompatibilidades de tipos entre Vue y la clase GameClient.
**Archivo afectado:** `client/src/components/Game.vue`
```typescript
const props = defineProps<{
gameClient: any // TEMPORAL - debería ser GameClient
}>()
```
**Causa:** Vue está infiriendo mal el tipo de GameClient cuando se pasa como prop/emit, causando errores como:
```
Type 'GameClient' is missing the following properties from type 'GameClient': client, room
```
**Solución pendiente:**
- Investigar la causa raíz del problema de inferencia de tipos
- Posiblemente usar una interface en lugar de clase
- O definir tipos de props más explícitos
**Prioridad:** Media (funciona pero no es tipo-seguro)

View File

@@ -1,358 +0,0 @@
# 🎛️ SnatchGame Admin Dashboard
[![Version](https://img.shields.io/badge/version-0.0.8--alpha-orange.svg)](https://github.com/username/snatchgame)
[![Vue.js](https://img.shields.io/badge/vue-3.0+-brightgreen.svg)](https://vuejs.org/)
[![TypeScript](https://img.shields.io/badge/typescript-5.0+-blue.svg)](https://www.typescriptlang.org/)
**Interfaz de administración completa** para el control y monitoreo en tiempo real del juego **SnatchGame**. Diseñada para administradores técnicos, personal no-técnico y comentaristas deportivos.
## 📊 Características Principales
### **🔄 Monitoreo en Tiempo Real**
- **👥 Lista de Jugadores Detallada**: Nombre, sala, rol, tipo de productor
- **🎯 Estado de Tokens**: Cantidad actual de 🦃 pavos, ☕ café, 🌽 maíz por jugador
- **📈 Estadísticas Globales**: Jugadores conectados, partidas activas, ronda actual
- **🔗 Estado de Conexión**: Indicador visual de jugadores conectados/desconectados
- **⚡ Actualización Automática**: SSE con polling cada 500ms
### **🎮 Control del Juego**
- **⏮️ Retroceder Ronda**: Cambio global a ronda anterior (mínimo 1)
- **⏭️ Avanzar Ronda**: Cambio global a ronda siguiente (máximo 10)
- **⏸️ Pausar Juego**: Pausar todas las partidas activas
- **▶️ Reanudar Juego**: Reanudar partidas pausadas
### **👥 Gestión de Jugadores**
- **🚫 Expulsar Jugador Individual**: Con notificación automática al cliente
- **🚫🚫 Expulsar Todos los Jugadores**: Vaciar todas las salas con notificaciones
- **🏠 Redirección Automática**: Los jugadores expulsados vuelven al home
- **📱 Notificaciones Inmediatas**: Alerts personalizados para cada acción
### **🎯 Usuarios Objetivo**
- **👨‍💼 Administrador No-Técnico**: Vista limpia con estadísticas esenciales
- **👨‍💻 IT Profesional**: Información de debugging y estado técnico
- **🎙️ Comentaristas Deportivos**: Información clara para narración en vivo
## 🏗️ Arquitectura Técnica
### **Stack Tecnológico**
- **Frontend**: Vue 3 + Composition API + TypeScript
- **Build Tool**: Vite (desarrollo) + Express (producción)
- **Comunicación**: HTTP (control) + fetch API
- **Styling**: CSS vanilla con diseño responsivo
- **Types**: Auto-generados desde servidor con schema-codegen
### **Comunicación con Servidor**
```typescript
// Admin Service comunica con servidor Colyseus
adminService.kickPlayer(playerId) // → POST /api/admin/kick-player
adminService.advanceRound() // → POST /api/admin/advance-round
adminService.pauseGame() // → POST /api/admin/pause-game
```
### **Arquitectura del Sistema**
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Admin UI │ │ Colyseus │ │ Game Client │
│ Port 3001 │───▶│ Server │◄──▶│ Port 3000 │
│ (Vue 3) │ │ Port 2567 │ │ (Vue 3) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└───── HTTP/Fetch ──────┘ │
│ │
┌───────────▼───────────┐ │
│ Notifications │ │
│ (adminKicked, │◄─────────┘
│ roundChanged) │
└───────────────────────┘
```
## 🚀 Instalación y Ejecución
### **Prerrequisitos**
- Node.js >= 18.0.0
- npm >= 8.0.0
- Servidor Colyseus ejecutándose en puerto 2567
### **Desarrollo**
```bash
# Desde el directorio admin
cd admin
# Instalar dependencias
npm install
# Generar tipos desde servidor
npm run generate-types
# Iniciar desarrollo
npm run dev
```
### **Producción**
```bash
# Build para producción
npm run build
# Iniciar servidor Express
npm start
```
### **URLs**
- **Desarrollo**: http://localhost:3001
- **Producción**: Configurado según variables de entorno
## 📁 Estructura del Proyecto
```
admin/
├── src/
│ ├── components/ # Componentes Vue
│ ├── services/ # Servicios de comunicación
│ │ └── adminService.ts # API client para servidor Colyseus
│ ├── types/ # Tipos auto-generados
│ │ ├── GameState.ts # Estado del juego
│ │ ├── Player.ts # Información de jugador
│ │ ├── TokenInventory.ts # Inventario de tokens
│ │ └── index.ts # Re-exports y tipos auxiliares
│ ├── App.vue # Componente principal
│ └── main.ts # Entry point
├── server.js # Express server (producción)
├── package.json # Dependencias y scripts
├── vite.config.ts # Configuración Vite
└── README.md # Este archivo
```
## 🎨 Interfaz de Usuario
### **Dashboard Principal**
```
📊 SnatchGame Dashboard 🟢 Conectado
┌─────────────────────────────────────────────────────────────┐
│ 👥 Jugadores: 6 🎮 Partidas: 2 🎯 Ronda: 3 │
│ 📊 Estado: En progreso │
└─────────────────────────────────────────────────────────────┘
🎛️ Control del Juego
┌─────────────────────────────────────────────────────────────┐
│ ⏮️ Retroceder ⏭️ Avanzar ⏸️ Pausar ▶️ Reanudar │
│ Ronda Ronda Juego Juego │
│ │
│ 🚫 Expulsar 🚫🚫 Expulsar │
│ Jugador Jugadores │
└─────────────────────────────────────────────────────────────┘
👥 Lista de Jugadores (6)
┌─────────────────────────────────────────────────────────────┐
│ Juan Carlos 🟢 Sala: a3f2b1 │
│ Comerciante 🦃 Productor de Pavos │
│ 🦃 3 ☕ 2 🌽 1 🚫 Expulsar │
├─────────────────────────────────────────────────────────────┤
│ María López 🟢 Sala: a3f2b1 │
│ Comerciante ☕ Productor de Café │
│ 🦃 1 ☕ 4 🌽 2 🚫 Expulsar │
└─────────────────────────────────────────────────────────────┘
```
### **Responsive Design**
- **Desktop**: Layout de 2 columnas con información completa
- **Tablet**: Layout adaptativo con botones optimizados
- **Mobile**: Layout vertical con información esencial
## ⚙️ Configuración
### **Variables de Entorno**
```env
# .env.development
VITE_ADMIN_PORT=3001
NODE_ENV=development
# .env.production
VITE_ADMIN_PORT=3001
NODE_ENV=production
```
### **AdminService Configuration**
```typescript
// src/services/adminService.ts
class AdminService {
private serverUrl = 'http://localhost:2567' // Colyseus server
// Todos los métodos apuntan al servidor Colyseus
async kickPlayer(playerId: string) { /* ... */ }
async advanceRound() { /* ... */ }
// ...
}
```
## 🔧 API Reference
### **AdminService Methods**
#### **Control de Jugadores**
```typescript
// Expulsar jugador específico
await adminService.kickPlayer('player-session-id')
// Expulsar todos los jugadores
await adminService.kickAllPlayers()
```
#### **Control del Juego**
```typescript
// Pausar todas las partidas
await adminService.pauseGame()
// Reanudar partidas pausadas
await adminService.resumeGame()
```
#### **Control de Rondas**
```typescript
// Avanzar ronda globalmente
await adminService.advanceRound()
// Retroceder ronda globalmente
await adminService.previousRound()
```
#### **Gestión de Partidas**
```typescript
// Cancelar partida específica
await adminService.cancelGame('room-id')
// Cancelar todas las partidas
await adminService.cancelGame()
```
### **Endpoints del Servidor**
Todos los endpoints están en el **servidor Colyseus** (puerto 2567):
- `GET /api/admin/stats` - Estadísticas en tiempo real
- `POST /api/admin/kick-player` - Expulsar jugador específico
- `POST /api/admin/kick-all-players` - Expulsar todos los jugadores
- `POST /api/admin/pause-game` - Pausar juego
- `POST /api/admin/resume-game` - Reanudar juego
- `POST /api/admin/advance-round` - Avanzar ronda
- `POST /api/admin/previous-round` - Retroceder ronda
- `POST /api/admin/cancel-game` - Cancelar partida
## 🔔 Sistema de Notificaciones
### **Notificaciones a Clientes**
El admin puede enviar notificaciones automáticas que los clientes reciben:
```typescript
// El cliente recibe estos mensajes automáticamente
client.onMessage("adminKicked", (data) => {
alert("🚫 Has sido expulsado por el administrador")
// Auto-redirección a home screen
})
client.onMessage("roundChanged", (data) => {
alert(`🎯 ${data.message}`) // "Ronda 3 - Cambio realizado por el administrador"
})
```
### **Experiencia del Usuario**
1. **Admin ejecuta acción** (expulsar, cambiar ronda, etc.)
2. **Servidor procesa** usando API oficial de Colyseus
3. **Clientes reciben notificación** inmediata y automática
4. **Redirección automática** cuando corresponde (expulsión)
## 🛠️ Desarrollo
### **Scripts Disponibles**
```bash
# Desarrollo con hot reload
npm run dev
# Generar tipos desde servidor
npm run generate-types
# Build para producción
npm run build
# Preview del build
npm run preview
# Servidor Express (producción)
npm start
```
### **Debugging**
```bash
# Verificar que el servidor Colyseus esté ejecutándose
curl http://localhost:2567/
# Verificar endpoint de stats
curl http://localhost:2567/api/admin/stats
# Ver logs del admin en desarrollo
npm run dev
# Abrir DevTools (F12) para logs detallados
```
### **Type Generation**
```bash
# Los tipos se generan automáticamente desde el servidor
cd admin
npm run generate-types
# Esto ejecuta:
# cd ../server && npx schema-codegen src/rooms/GameRoom.ts --ts --output ../admin/src/types/
```
## 🚀 Deploy
### **Docker (Recomendado)**
```bash
# Desde el directorio raíz del proyecto
docker-compose up -d
# El admin estará disponible en el puerto configurado
```
### **Manual**
```bash
# Build admin
cd admin
npm run build
# Start en producción
npm start
```
## 🤝 Contribuir
### **Estructura de Contribución**
1. **Servidor primero**: Implementar nuevos endpoints en `/server/src/app.config.ts`
2. **GameRoom methods**: Agregar métodos necesarios en `/server/src/rooms/GameRoom.ts`
3. **AdminService**: Actualizar `/admin/src/services/adminService.ts`
4. **UI Components**: Modificar `/admin/src/App.vue` según necesidad
5. **Types**: Regenerar con `npm run generate-types`
### **Convenciones**
- **Endpoints**: Prefijo `/api/admin/` para todas las rutas admin
- **Métodos GameRoom**: Prefijo `_` para métodos admin (ej: `_forceClientDisconnect`)
- **Notificaciones**: Mensajes descriptivos en español para usuarios
- **Error Handling**: Try/catch en todos los métodos async
## 📄 Licencia
Este microservicio es parte del proyecto **SnatchGame** bajo licencia **MIT**.
## 🙋‍♂️ Soporte
- **Documentación Principal**: `/README.md` (directorio raíz)
- **Guía Técnica**: `/CLAUDE.md`
- **Issues**: [GitHub Issues](https://github.com/username/snatchgame/issues)
---
<div align="center">
**🎛️ Admin Dashboard Completo para SnatchGame**
*Control total • Monitoreo en tiempo real • Notificaciones automáticas*
</div>

View File

@@ -1,242 +0,0 @@
# 🎮 Snatch or Share - Cliente
Cliente web para el juego multijugador Snatch or Share, basado en el trabajo de Elinor Ostrom sobre instituciones y cooperación.
## 🛠️ Stack Tecnológico
- **Vue 3** (Composition API, vanilla sin build tools)
- **TypeScript** (tipado estricto)
- **Vite** (development server)
- **Colyseus.js** (cliente WebSocket)
- **Express** (servidor estático en producción)
## 🚀 Inicio Rápido
### Prerrequisitos
- Node.js 18+
- npm 9+
- Servidor Snatch or Share ejecutándose (puerto 2567)
### Instalación y Desarrollo
```bash
# Instalar dependencias
npm install
# Generar tipos TypeScript desde el servidor
npm run generate-types
# Iniciar servidor de desarrollo (puerto 3000)
npm run dev
```
### Comandos Disponibles
```bash
# Desarrollo
npm run dev # Servidor de desarrollo con hot reload
npm run generate-types # Generar tipos desde servidor Colyseus
# Producción
npm run build # Compilar proyecto para producción
npm run preview # Vista previa del build
npm run start # Servidor Express en producción
# Utilidades
npm run serve # Servidor Express con nodemon
```
## 🏗️ Arquitectura del Cliente
### Estructura de Directorios
```
client/
├── src/
│ ├── components/ # Componentes Vue
│ │ ├── Game.vue # Componente principal del juego
│ │ ├── PlayerCard.vue # Tarjeta de jugador
│ │ ├── TradeOfferCard.vue # Tarjeta de oferta comercial
│ │ ├── MakeOfferForm.vue # Formulario para ofertas
│ │ ├── ScrollableOffers.vue # Contenedor de ofertas con scroll
│ │ └── OfferModal.vue # Modal para hacer ofertas
│ ├── services/ # Servicios y lógica de negocio
│ │ ├── gameClient.ts # Cliente Colyseus
│ │ └── logger.ts # Sistema de logging
│ ├── types/ # Tipos TypeScript
│ │ ├── GameState.ts # (Auto-generado)
│ │ ├── Player.ts # (Auto-generado)
│ │ ├── TradeOffer.ts # (Auto-generado)
│ │ ├── TokenInventory.ts # (Auto-generado)
│ │ └── index.ts # Tipos auxiliares
│ ├── App.vue # Componente raíz
│ └── main.ts # Punto de entrada
├── index.html # Template HTML
├── server.js # Servidor Express (producción)
└── vite.config.ts # Configuración Vite
```
### Componentes Principales
#### Game.vue
Componente principal que maneja:
- Layout responsivo (desktop/móvil)
- Estado del juego en tiempo real
- Coordinación entre componentes hijos
#### PlayerCard.vue
Tarjeta de jugador con:
- Modo compacto para otros jugadores
- Modo expandido para jugador actual
- Click para hacer ofertas
#### TradeOfferCard.vue
Muestra ofertas comerciales:
- Información de tokens ofrecidos/solicitados
- Botones de acción (Aceptar/Rechazar/Snatch)
- Estados visuales según tipo de oferta
#### MakeOfferForm.vue
Formulario optimizado con:
- Botones +/- prominentes
- Input compacto para números
- Validación en tiempo real
## 🔄 Generación de Tipos
El cliente utiliza tipos auto-generados desde el servidor Colyseus:
```bash
# Generar tipos automáticamente
npm run generate-types
# Comando manual equivalente
cd ../server && npx schema-codegen src/rooms/GameRoom.ts --ts --output ../client/src/types/
```
**Tipos Auto-generados:**
- `GameState.ts` - Estado principal del juego
- `Player.ts` - Información del jugador
- `TradeOffer.ts` - Ofertas comerciales
- `TokenInventory.ts` - Inventario de tokens
**Tipos Manuales:**
- `GameRoomOptions` - Opciones de sala
- Interfaces auxiliares en `index.ts`
## 🎯 Funcionalidades del Cliente
### Layout Responsivo
**Desktop:**
- Layout de 2 columnas (jugadores | ofertas)
- Jugador actual prominente abajo
- Panel de ofertas con scroll customizado
**Móvil:**
- Layout vertical adaptativo
- Cards de jugadores compactas
- Ofertas optimizadas horizontalmente
### Interacciones
- **Click en PlayerCard** → Abre modal de oferta
- **Botones +/-** → Incrementar/decrementar tokens
- **Formulario modal** → Crear ofertas dirigidas
- **Scroll customizado** → Navegación suave de ofertas
### Estado en Tiempo Real
- Conexión WebSocket con Colyseus
- Sincronización automática de estado
- Reactivity de Vue 3 con estado del servidor
## 🔧 Configuración
### Variables de Entorno
```env
# Desarrollo (.env.development)
VITE_SERVER_URL=ws://localhost:2567
# Producción (.env.production)
VITE_SERVER_URL=ws://tu-servidor-produccion:2567
```
### Configuración del Servidor
El cliente incluye un servidor Express para producción:
```javascript
// server.js
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Servir archivos estáticos
app.use(express.static(path.join(__dirname, 'dist')));
// SPA fallback
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
```
## 🔍 Debugging
### Logger del Cliente
```typescript
import { logger } from '@/services/logger'
// Logs automáticos del estado del juego
logger.gameStateChange(state)
logger.gameComponentUpdate(updates)
logger.clickSent()
```
### DevTools
- Vue DevTools para componentes
- Network tab para conexiones WebSocket
- Console para logs del gameClient
## 📱 Compatibilidad
- **Navegadores**: Chrome 90+, Firefox 88+, Safari 14+
- **Dispositivos**: Desktop, tablet, móvil
- **Resoluciones**: 320px - 1920px+
## 🎮 Uso del Cliente
1. **Espera**: Pantalla de espera hasta 3 jugadores
2. **Asignación**: Roles de productor asignados aleatoriamente
3. **Trading**: Interfaz de intercambio con ofertas
4. **Ofertas**: Click en jugadores para hacer ofertas
5. **Respuestas**: Aceptar, rechazar o hacer "snatch"
## 🚀 Despliegue
### Desarrollo
```bash
npm run dev
# Cliente disponible en http://localhost:3000
```
### Producción
```bash
npm run build
npm run start
# Servidor Express sirviendo build estático
```
### Docker (desde raíz del proyecto)
```bash
docker-compose up client
```
## 🤝 Contribución
Ver [CLAUDE.md](../CLAUDE.md) para guías de desarrollo y convenciones del proyecto.

View File

@@ -1,138 +0,0 @@
# Snatch or Share - Game Logic
## Game Overview
Snatch or Share is a multiplayer game that simulates governance evolution in decentralized exchanges, based on Elinor Ostrom's "Snatch Game".
## Game State Structure
### Main Game State
```typescript
GameState {
round: number (1-5)
groups: Group[] // Groups of 3 players
currentPhase: 'waiting' | 'trading' | 'judging' | 'results'
}
Group {
id: string
players: Player[3]
currentJudge?: Player // Only in Round 5
activeTradeOffers: TradeOffer[] // Multiple simultaneous offers
}
Player {
id: string
name: string
producerRole: 'turkey' | 'coffee' | 'corn'
tokens: {
turkey: number
coffee: number
corn: number
}
points: number // Calculated: own_tokens * 1 + other_tokens * 2
shameTokens: number // For Round 4
isSuspended: boolean // For Round 5
role: 'trader' | 'judge' // Only relevant in Round 5
}
TradeOffer {
id: string
offererId: string
targetId: string
offering: { turkey: number, coffee: number, corn: number }
requesting: { turkey: number, coffee: number, corn: number }
status: 'pending' | 'accepted' | 'rejected' | 'snatched' | 'cancelled'
}
```
## Game Initialization
### Room Configuration
- **Exactly 3 players required** to start the game
- **Maximum 3 players** per room
### Producer Role Assignment
- Each player is randomly assigned **one unique producer role**:
- **Turkey Producer**: Starts with 5 turkey tokens
- **Coffee Producer**: Starts with 5 coffee tokens
- **Corn Producer**: Starts with 5 corn tokens
- **Roles cannot be repeated** - exactly one producer of each type per game
### Judge Role (Round 5)
- In Round 5, one player becomes **Judge** (rotates each round)
- **Judge role is decorative** - player keeps their original producer role
- Judge has additional responsibilities but maintains their trading capabilities
## Round Flow (Focus: Round 1)
### Round 1: State of Nature
- **No time limits** on turns
- **Simultaneous trading**: All players can make offers at the same time
- **Offer limit**: Each player can make maximum 2 offers to each opponent
- **Offer format**: "I give X tokens in exchange for Y tokens"
- **Offer responses**: Target player can Accept, Reject, or Snatch
### Trading Mechanics
#### Making Offers
- Players can offer and request **any amount** of tokens (even more than they have)
- Offers are made simultaneously to multiple players
- Format: `offering: {turkey: X, coffee: Y, corn: Z}` for `requesting: {turkey: A, coffee: B, corn: C}`
- **All trade offers are public** - visible to all players in the room, not just offerer and target
#### Resolving Offers
- **Accept**: Trade executed to the extent possible with available tokens
- **Reject**: Offer cancelled, no exchange
- **Snatch**: Receiver gets offered tokens (up to what offerer has) without giving anything in return
- **Cancel**: Offerer can cancel pending offers
#### Partial Fulfillment
- All trades execute with available tokens only
- Example: Offer "6 corn for 6 coffee" but only have 5 corn → Execute "5 corn for 5 coffee"
- Example: Accept offer for 8 tokens but only have 3 → Give 3 tokens, receive offered amount
- **No negative consequences** for partial fulfillment - it's part of the game
## Rules by Round
### Round 1-2: State of Nature / Anarchy
- No special rules
- All players are Traders
- No enforcement mechanisms
### Round 3: Counterproductive Rule
- **Mandatory Rule**: "All trade offers must be accepted"
- Players still have freedom to snatch
- Reduces agency, invites exploitation
### Round 4: Soft Norms (Shame Tokens)
- Each player can assign 1 shame token per round
- If player starts round with 2+ shame tokens:
- Loses 2 tokens before round begins
- Barred from offering trades (can only respond)
### Round 5: Governance Rules (Ostrom Adapted)
- **Group Roles**: Two Traders and One Judge
- **Judge Role**: Rotates each round
- **Applied Rules**:
- **Position Rule**: Judge oversees fairness and conflict resolution
- **Boundary Rule**: Only group members can trade; Judge may suspend rule-breaker for 1 round
- **Choice Rule**: Trades are voluntary; Players can report snatching to Judge
- **Enforcement Rule**: If Judge confirms snatch → goods returned + snatcher forfeits 3 tokens to victim
- **Aggregation Rule**: Trade only completes with explicit mutual consent
## Key Mechanics
### Trading
- **Exchange Amount**: Always 5 tokens of player's own type
- **Value System**: own_tokens × 1 + other_tokens × 2
- **Snatch**: Take opponent's tokens without giving anything in return
### Point Calculation Examples
- Holding 10 of own = 10 points
- Holding 5 of own + 5 of other = 15 points
- Holding 10 of own + 5 snatched = 20 points
### Governance Evolution
- **Round 1-2**: No trust → no cooperation → suboptimal outcomes
- **Round 4**: Social deterrents emerge
- **Round 5**: Governance stabilizes expectations → trust emerges → optimal outcomes through fair trades

334
migration-plan-nuxt.md Normal file
View File

@@ -0,0 +1,334 @@
# Plan de Migración a Nuxt - SnatchGame
## Resumen Ejecutivo
Migración de arquitectura multi-aplicación (Colyseus server + Vue client + Vue admin) a una aplicación unificada Nuxt 3 que maneje servidor, cliente y administración en un solo proyecto.
## Análisis de la Arquitectura Actual
### Componentes Existentes
1. **Servidor Colyseus** (Puerto 2567)
- Framework: Colyseus.io v0.16
- GameRoom con lógica de juego
- API REST para admin
- WebSocket para sincronización en tiempo real
2. **Cliente Vue** (Puerto 3000)
- Vue 3 con Composition API
- Colyseus.js SDK para conexión
- Componentes: Home, Game, Settings, PlayerCard, TradeOfferCard
- Sin build tools (vanilla)
3. **Admin Vue** (Puerto 3001)
- Vue 3 con dashboard de estadísticas
- SSE (Server-Sent Events) para actualizaciones
- Control total del juego
- Sin build tools (vanilla)
## Arquitectura Propuesta Nuxt 3
### Estructura del Proyecto
```
nuxt-snatchgame/
├── server/
│ ├── api/ # API REST endpoints
│ │ ├── admin/ # Admin endpoints
│ │ └── config.ts # Configuración
│ ├── plugins/
│ │ └── colyseus.ts # Integración Colyseus
│ └── rooms/
│ └── GameRoom.ts # Lógica del juego
├── pages/
│ ├── index.vue # Cliente del juego (/)
│ └── admin.vue # Dashboard admin (/admin)
├── components/
│ ├── game/ # Componentes del juego
│ │ ├── PlayerCard.vue
│ │ ├── TradeOfferCard.vue
│ │ ├── MakeOfferForm.vue
│ │ └── OfferModal.vue
│ └── admin/ # Componentes admin
│ ├── StatsCard.vue
│ ├── PlayerList.vue
│ └── ControlPanel.vue
├── composables/
│ ├── useGameClient.ts # Cliente Colyseus
│ └── useAdminService.ts # Servicio admin
├── types/
│ └── game.ts # TypeScript types
├── public/
│ └── assets/ # Imágenes y recursos
├── nuxt.config.ts
└── package.json
```
## Fases de Migración
### Fase 1: Setup Inicial (2 horas)
1. **Crear proyecto Nuxt 3**
```bash
npx nuxi@latest init nuxt-snatchgame
cd nuxt-snatchgame
```
2. **Instalar dependencias necesarias**
```json
{
"dependencies": {
"nuxt": "^3.x",
"@colyseus/core": "^0.16.19",
"@colyseus/schema": "^3.0.42",
"colyseus": "^0.16.0",
"colyseus.js": "^0.16.19"
}
}
```
3. **Configuración base en nuxt.config.ts**
- Nitro server configuration
- WebSocket support
- Vue 3 setup
### Fase 2: Migración del Servidor Colyseus (3 horas)
1. **Integrar Colyseus en Nitro**
```typescript
// server/plugins/colyseus.ts
import { Server } from 'colyseus'
import { WebSocketTransport } from '@colyseus/ws-transport'
import { GameRoom } from '../rooms/GameRoom'
export default defineNitroPlugin((nitroApp) => {
const gameServer = new Server({
transport: new WebSocketTransport({
server: nitroApp.node.server
})
})
gameServer.define('game', GameRoom)
.filterBy(['gameMode'])
.sortBy({ clients: 1 })
})
```
2. **Migrar GameRoom y tipos**
- Copiar GameRoom.ts sin cambios
- Mantener Schema classes
- Adaptar métodos admin
3. **API Endpoints**
```typescript
// server/api/admin/stats.get.ts
export default defineEventHandler(async (event) => {
// Migrar lógica de stats
})
```
### Fase 3: Migración del Cliente (3 horas)
1. **Página principal del juego**
```vue
<!-- pages/index.vue -->
<template>
<div>
<HomeScreen v-if="!inGame" @join="joinGame" />
<GameScreen v-else :client="gameClient" />
</div>
</template>
```
2. **Composable para cliente Colyseus**
```typescript
// composables/useGameClient.ts
export const useGameClient = () => {
const client = ref<Client | null>(null)
const room = ref<Room | null>(null)
const connect = async (playerName: string) => {
client.value = new Client('ws://localhost:3000')
room.value = await client.value.joinOrCreate('game', {
playerName
})
}
return { client, room, connect }
}
```
3. **Migrar componentes Vue**
- Convertir a script setup
- Usar auto-imports de Nuxt
- Mantener lógica existente
### Fase 4: Migración del Admin (2 horas)
1. **Página admin**
```vue
<!-- pages/admin.vue -->
<template>
<AdminDashboard />
</template>
```
2. **Servicio SSE con Nitro**
```typescript
// server/api/admin/stream.get.ts
export default defineEventHandler(async (event) => {
const stream = createEventStream(event)
// Enviar stats cada 250ms
const interval = setInterval(async () => {
const stats = await getGameStats()
await stream.push(stats)
}, 250)
stream.onClosed(() => {
clearInterval(interval)
})
return stream.send()
})
```
3. **Composable admin**
```typescript
// composables/useAdminService.ts
export const useAdminService = () => {
const stats = ref({})
const connect = () => {
const eventSource = new EventSource('/api/admin/stream')
eventSource.onmessage = (e) => {
stats.value = JSON.parse(e.data)
}
}
return { stats, connect }
}
```
### Fase 5: Integración y Testing (2 horas)
1. **Configuración de desarrollo**
```json
{
"scripts": {
"dev": "nuxt dev",
"build": "nuxt build",
"preview": "nuxt preview"
}
}
```
2. **Variables de entorno**
```env
NUXT_PUBLIC_GAME_NAME=SnatchGame
NUXT_SERVER_PORT=3000
```
3. **Testing funcional**
- Verificar conexión WebSocket
- Probar sincronización de estado
- Validar panel admin
- Test de múltiples jugadores
## Consideraciones Técnicas
### WebSocket en Nuxt/Nitro
- Nitro soporta WebSocket nativamente
- Colyseus se integra mediante plugin
- Un solo puerto para todo (3000)
### Estado Compartido
- Usar Pinia para estado local
- Colyseus para estado sincronizado
- SSE para actualizaciones admin
### TypeScript
- Schema-codegen sigue funcionando
- Types compartidos en /types
- Auto-imports de Nuxt
### Rutas
- `/` - Cliente del juego
- `/admin` - Panel de administración
- `/api/*` - API endpoints
- WebSocket en el mismo puerto
## Simplificaciones MVP
1. **Sin autenticación** - Solo nombres de usuario
2. **Sin base de datos** - Todo en memoria
3. **Sin Docker** - Deploy directo con Node
4. **Sin HTTPS** - Solo HTTP/WS local
5. **Sin optimizaciones** - Código simple y directo
## Ventajas de la Migración
1. **Un solo proyecto** - Más fácil de mantener
2. **Un solo puerto** - Simplifica deployment
3. **Hot reload completo** - Mejor DX
4. **Auto-imports** - Menos boilerplate
5. **TypeScript integrado** - Mejor tooling
6. **SSR opcional** - Mejor SEO si necesario
## Riesgos y Mitigaciones
| Riesgo | Mitigación |
|--------|------------|
| WebSocket en Nitro no probado | Usar h3-ws o plugin dedicado |
| Colyseus incompatible | Mantener servidor separado si falla |
| Performance SSE | Usar WebSocket para admin también |
| Complejidad aumenta | Mantener arquitectura simple |
## Cronograma Estimado
- **Día 1**: Setup + Servidor (5 horas)
- **Día 2**: Cliente + Admin (5 horas)
- **Día 3**: Testing + Ajustes (2 horas)
**Total: ~12 horas de desarrollo**
## Comando para Iniciar
```bash
# Desarrollo
npm run dev
# Producción
npm run build
npm run preview
```
## Estructura de Datos del Juego
### Juegos (5 rondas totales)
1. **Sin reglas** - Ofrecer/Aceptar/Rechazar/Robar sin castigo
2. **Reglas contraproducentes** - Jugador 2 puede forzar oferta
3. **Fichas de vergüenza** - Visible para siguiente contrincante
4. **Derechos mínimos** - Sistema castiga robos denunciados
5. **Comunicación abierta** - Jugadores pueden hablar
### Mecánicas Core
- 3 rondas por juego (solo la 3ra cuenta)
- Roles: Jugador 1 / Jugador 2
- Contrincantes aleatorios
- Sin comunicación (excepto juego 5)
- Auto-increment para nombres duplicados
## Decisiones de Diseño
1. **Nuxt sobre Next.js** - Mejor integración Vue
2. **Nitro server** - WebSocket nativo
3. **Sin build tools en components** - Usar SFC de Nuxt
4. **Colyseus integrado** - No servidor separado
5. **SSE para admin** - Mantener patrón actual
## Próximos Pasos
1. ✅ Aprobar plan de migración
2. ⏳ Crear proyecto Nuxt base
3. ⏳ Migrar servidor Colyseus
4. ⏳ Migrar cliente Vue
5. ⏳ Migrar admin Vue
6. ⏳ Testing integral
7. ⏳ Deploy local

View File

@@ -118,6 +118,8 @@ EOF
# Reiniciar Docker con configuración final # Reiniciar Docker con configuración final
cd .. && docker compose down && cd ngrok cd .. && docker compose down && cd ngrok
# Limpiar contenedores existentes por si acaso
docker rm -f snatchgame-server snatchgame-client snatchgame-admin 2>/dev/null || true
cd .. && docker compose -f /tmp/docker-compose-final.yml up -d && cd ngrok cd .. && docker compose -f /tmp/docker-compose-final.yml up -d && cd ngrok
echo "⏳ Esperando servicios reconfigurados..." echo "⏳ Esperando servicios reconfigurados..."

View File

@@ -0,0 +1,3 @@
NUXT_PUBLIC_GAME_NAME=SnatchGame
NUXT_PUBLIC_WS_URL=ws://localhost:2567
NODE_ENV=development

24
nuxt-snatchgame/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Nuxt dev/build outputs
.output
.data
.nuxt
.nitro
.cache
dist
# Node dependencies
node_modules
# Logs
logs
*.log
# Misc
.DS_Store
.fleet
.idea
# Local env files
.env
.env.*
!.env.example

74
nuxt-snatchgame/README.md Normal file
View File

@@ -0,0 +1,74 @@
# Snatch Game - Nuxt 3 Migration
Migración completa del juego SnatchGame a una aplicación unificada Nuxt 3.
## Arquitectura
- **Frontend**: Nuxt 3 (SSR deshabilitado)
- **Backend de juego**: Servidor Colyseus independiente (puerto 2567)
- **Comunicación**: WebSocket para tiempo real
## Instalación
```bash
npm install
```
## Desarrollo
Ejecutar ambos servidores (Nuxt + Colyseus):
```bash
npm run dev:all
```
O ejecutar por separado:
```bash
# Terminal 1 - Servidor Nuxt (puerto 3000)
npm run dev
# Terminal 2 - Servidor Colyseus (puerto 2567)
npm run dev:colyseus
```
## URLs
- Cliente del juego: http://localhost:3000
- Panel admin: http://localhost:3000/admin
- WebSocket Colyseus: ws://localhost:2567
- Monitor Colyseus: http://localhost:2567/monitor
## Estructura del proyecto
```
nuxt-snatchgame/
├── pages/ # Páginas de Nuxt
│ ├── index.vue # Cliente del juego
│ └── admin.vue # Panel de administración
├── components/ # Componentes Vue
│ ├── game/ # Componentes del juego
│ └── admin/ # Componentes admin
├── composables/ # Composables Vue
│ ├── useGameClient.ts # Cliente Colyseus
│ └── useAdminService.ts # Servicio admin
├── server/ # Backend
│ ├── colyseus-server.ts # Servidor Colyseus
│ └── rooms/ # Salas de juego
│ └── GameRoom.ts # Lógica del juego
└── public/ # Assets estáticos
```
## Características implementadas
✅ Cliente del juego con conexión WebSocket
✅ Panel de administración
✅ Sistema de intercambio de tokens
✅ Gestión de jugadores y salas
✅ Control administrativo del juego
## Notas de la migración
- El servidor Colyseus se ejecuta de forma independiente para evitar problemas con decoradores TypeScript
- SSR deshabilitado ya que es una aplicación de juego en tiempo real
- Los endpoints admin se conectan directamente al servidor Colyseus

View File

@@ -0,0 +1,3 @@
<template>
<NuxtPage />
</template>

View File

@@ -0,0 +1,328 @@
<template>
<div class="game-container">
<div v-if="!gameState" class="loading">
<h2>Esperando estado del juego...</h2>
</div>
<div v-else class="game-content">
<!-- Game Header -->
<div class="game-header">
<div class="game-info">
<h2>Snatch Game</h2>
<div class="game-status">
<span>Ronda: {{ gameState.round }}</span>
<span>Fase: {{ gamePhaseDisplay }}</span>
<span>Jugadores: {{ playerCount }}/{{ gameState.maxPlayers }}</span>
</div>
</div>
</div>
<!-- Waiting Screen -->
<div v-if="gameState.gamePhase === 'waiting'" class="waiting-room">
<h3>Esperando jugadores...</h3>
<p>Se necesitan {{ gameState.minPlayers }} jugadores para comenzar</p>
<div class="players-waiting">
<div v-for="[id, player] in gameState.players" :key="id" class="player-waiting">
{{ player.name }}
</div>
</div>
</div>
<!-- Trading Phase -->
<div v-else-if="gameState.gamePhase === 'trading'" class="trading-phase">
<div class="my-info">
<h3>Tu información</h3>
<div class="role">Productor de: {{ currentPlayer?.producerRole }}</div>
<div class="tokens">
<div>🦃 Pavos: {{ currentPlayer?.tokens.turkey || 0 }}</div>
<div> Café: {{ currentPlayer?.tokens.coffee || 0 }}</div>
<div>🌽 Maíz: {{ currentPlayer?.tokens.corn || 0 }}</div>
</div>
<div class="points">Puntos: {{ currentPlayer?.points || 0 }}</div>
</div>
<!-- Other Players -->
<div class="other-players">
<h3>Otros jugadores</h3>
<div class="players-grid">
<div v-for="[id, player] in otherPlayers" :key="id" class="player-card">
<PlayerCard :player="player" :is-current="false" @make-offer="onMakeOffer(id)" />
</div>
</div>
</div>
<!-- Active Trade Offers -->
<div v-if="activeOffers.length > 0" class="trade-offers">
<h3>Ofertas de intercambio</h3>
<div v-for="offer in activeOffers" :key="offer.id" class="offer-card">
<TradeOfferCard
:offer="offer"
:current-player-id="currentPlayerId"
@respond="onRespondToOffer"
@cancel="onCancelOffer"
/>
</div>
</div>
</div>
<!-- Paused Phase -->
<div v-else-if="gameState.gamePhase === 'paused'" class="paused-phase">
<h2> Juego pausado</h2>
<p>El administrador ha pausado el juego</p>
</div>
<!-- Results Phase -->
<div v-else-if="gameState.gamePhase === 'results'" class="results-phase">
<h2>Resultados de la ronda {{ gameState.round }}</h2>
<div class="results-grid">
<div v-for="[id, player] in gameState.players" :key="id" class="result-card">
<h4>{{ player.name }}</h4>
<p>Puntos: {{ player.points }}</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, watch } from 'vue'
const props = defineProps<{
gameClient: any
}>()
const gameState = computed(() => props.gameClient?.gameState.value)
const currentPlayerId = computed(() => props.gameClient?.currentPlayerId.value)
const currentPlayer = computed(() => {
if (!gameState.value || !currentPlayerId.value) return null
return gameState.value.players.get(currentPlayerId.value)
})
const otherPlayers = computed(() => {
if (!gameState.value) return new Map()
const others = new Map()
gameState.value.players.forEach((player, id) => {
if (id !== currentPlayerId.value) {
others.set(id, player)
}
})
return others
})
const playerCount = computed(() => gameState.value?.players.size || 0)
const gamePhaseDisplay = computed(() => {
const phase = gameState.value?.gamePhase
switch (phase) {
case 'waiting': return 'Esperando jugadores'
case 'trading': return 'Intercambio'
case 'paused': return 'Pausado'
case 'results': return 'Resultados'
default: return phase
}
})
const activeOffers = computed(() => {
if (!gameState.value) return []
return gameState.value.activeTradeOffers.filter(offer =>
offer.status === 'pending' &&
(offer.offererId === currentPlayerId.value || offer.targetId === currentPlayerId.value)
)
})
const onMakeOffer = (targetId: string) => {
// This would open a modal or form to create an offer
console.log('Make offer to:', targetId)
// For now, create a simple offer
props.gameClient.makeOffer(targetId,
{ turkey: 1, coffee: 0, corn: 0 },
{ turkey: 0, coffee: 1, corn: 0 }
)
}
const onRespondToOffer = (offerId: string, response: string) => {
props.gameClient.respondToOffer(offerId, response)
}
const onCancelOffer = (offerId: string) => {
props.gameClient.cancelOffer(offerId)
}
</script>
<style scoped>
.game-container {
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 2rem;
}
.loading {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.game-content {
max-width: 1200px;
margin: 0 auto;
}
.game-header {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.5rem;
margin-bottom: 2rem;
backdrop-filter: blur(10px);
}
.game-info h2 {
margin: 0 0 1rem 0;
font-size: 2rem;
}
.game-status {
display: flex;
gap: 2rem;
font-size: 1.1rem;
}
.waiting-room {
text-align: center;
padding: 3rem;
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
backdrop-filter: blur(10px);
}
.players-waiting {
display: flex;
gap: 1rem;
justify-content: center;
margin-top: 2rem;
}
.player-waiting {
padding: 0.75rem 1.5rem;
background: rgba(255, 255, 255, 0.2);
border-radius: 8px;
}
.trading-phase {
display: grid;
gap: 2rem;
}
.my-info {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.5rem;
backdrop-filter: blur(10px);
}
.my-info h3 {
margin: 0 0 1rem 0;
}
.role {
font-size: 1.2rem;
font-weight: 600;
margin-bottom: 1rem;
text-transform: capitalize;
}
.tokens {
display: flex;
gap: 2rem;
margin-bottom: 1rem;
font-size: 1.1rem;
}
.points {
font-size: 1.3rem;
font-weight: 700;
color: #ffd700;
}
.other-players {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.5rem;
backdrop-filter: blur(10px);
}
.other-players h3 {
margin: 0 0 1rem 0;
}
.players-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}
.player-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 1rem;
}
.trade-offers {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.5rem;
backdrop-filter: blur(10px);
}
.trade-offers h3 {
margin: 0 0 1rem 0;
}
.offer-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 1rem;
margin-bottom: 1rem;
}
.paused-phase {
text-align: center;
padding: 3rem;
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
backdrop-filter: blur(10px);
}
.results-phase {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 2rem;
backdrop-filter: blur(10px);
}
.results-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
margin-top: 2rem;
}
.result-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 1rem;
text-align: center;
}
.result-card h4 {
margin: 0 0 0.5rem 0;
}
.result-card p {
font-size: 1.2rem;
font-weight: 700;
color: #ffd700;
}
</style>

View File

@@ -0,0 +1,160 @@
<template>
<div class="container">
<div class="branding">
<img src="/assets/logo.svg" alt="Snatch Game Logo" class="logo" />
<h1>Snatch Game</h1>
</div>
<div class="buttons">
<button @click="onJoin" :disabled="isConnecting">
{{ isConnecting ? 'Conectando...' : 'Unirse a partida' }}
</button>
<button @click="onSettings">Configuración</button>
<button @click="onLogin">Iniciar sesión</button>
</div>
<div v-if="connectionStatus" class="connection-status">
{{ connectionStatus }}
</div>
<div class="footer">NucleoServices</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useGameClient } from '~/composables/useGameClient'
const emit = defineEmits<{
'join-game': [client: any]
'show-settings': []
}>()
const gameClient = useGameClient()
const isConnecting = ref(false)
const connectionStatus = computed(() => gameClient.connectionStatus.value)
const onJoin = async () => {
if (isConnecting.value) return
isConnecting.value = true
try {
await gameClient.connect('Jugador Test', 'classic')
console.log('Connected successfully')
// Emit the join-game event with the game client
emit('join-game', gameClient)
} catch (error) {
console.error('Error connecting:', error)
} finally {
isConnecting.value = false
}
}
const onSettings = () => {
emit('show-settings')
}
const onLogin = () => {
console.log('Login clicked')
// TODO: implement login logic
}
</script>
<style scoped>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 2rem;
}
.branding {
text-align: center;
margin-bottom: 3rem;
}
.logo {
width: 120px;
height: 120px;
margin-bottom: 1rem;
}
h1 {
font-size: 3rem;
font-weight: 700;
margin: 0;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
.buttons {
display: flex;
flex-direction: column;
gap: 1rem;
width: 100%;
max-width: 300px;
}
button {
padding: 1rem 2rem;
font-size: 1.1rem;
font-weight: 600;
background: rgba(255, 255, 255, 0.2);
color: white;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
backdrop-filter: blur(10px);
}
button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.3);
border-color: rgba(255, 255, 255, 0.5);
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.connection-status {
margin-top: 2rem;
padding: 0.75rem 1.5rem;
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
backdrop-filter: blur(10px);
font-size: 0.9rem;
text-align: center;
}
.footer {
position: absolute;
bottom: 2rem;
font-size: 0.9rem;
opacity: 0.7;
}
@media (max-width: 768px) {
h1 {
font-size: 2rem;
}
.logo {
width: 80px;
height: 80px;
}
button {
font-size: 1rem;
padding: 0.75rem 1.5rem;
}
}
</style>

View File

@@ -0,0 +1,289 @@
<template>
<div class="modal-overlay" @click="$emit('close')">
<div class="modal-content" @click.stop>
<div class="modal-header">
<h2>Configuración</h2>
<button class="close-button" @click="$emit('close')"></button>
</div>
<div class="modal-body">
<div class="settings-section">
<h3>Audio</h3>
<div class="setting-item">
<label>
<input type="checkbox" v-model="settings.soundEnabled" />
Efectos de sonido
</label>
</div>
<div class="setting-item">
<label>
<input type="checkbox" v-model="settings.musicEnabled" />
Música de fondo
</label>
</div>
<div class="setting-item">
<label>
Volumen
<input
type="range"
min="0"
max="100"
v-model="settings.volume"
class="volume-slider"
/>
<span>{{ settings.volume }}%</span>
</label>
</div>
</div>
<div class="settings-section">
<h3>Notificaciones</h3>
<div class="setting-item">
<label>
<input type="checkbox" v-model="settings.notifications" />
Notificaciones del juego
</label>
</div>
<div class="setting-item">
<label>
<input type="checkbox" v-model="settings.tradeAlerts" />
Alertas de intercambio
</label>
</div>
</div>
<div class="settings-section">
<h3>Apariencia</h3>
<div class="setting-item">
<label>
<input type="checkbox" v-model="settings.animations" />
Animaciones
</label>
</div>
<div class="setting-item">
<label>
Tema
<select v-model="settings.theme">
<option value="light">Claro</option>
<option value="dark">Oscuro</option>
<option value="auto">Automático</option>
</select>
</label>
</div>
</div>
</div>
<div class="modal-footer">
<button @click="saveSettings" class="btn-save">Guardar</button>
<button @click="$emit('close')" class="btn-cancel">Cancelar</button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
const emit = defineEmits<{
'close': []
}>()
const settings = reactive({
soundEnabled: true,
musicEnabled: true,
volume: 50,
notifications: true,
tradeAlerts: true,
animations: true,
theme: 'dark'
})
onMounted(() => {
// Load settings from localStorage
const savedSettings = localStorage.getItem('gameSettings')
if (savedSettings) {
Object.assign(settings, JSON.parse(savedSettings))
}
})
const saveSettings = () => {
// Save settings to localStorage
localStorage.setItem('gameSettings', JSON.stringify(settings))
console.log('Settings saved:', settings)
emit('close')
}
</script>
<style scoped>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
backdrop-filter: blur(5px);
}
.modal-content {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 16px;
width: 90%;
max-width: 500px;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.5rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}
.modal-header h2 {
margin: 0;
color: white;
font-size: 1.5rem;
}
.close-button {
background: none;
border: none;
color: white;
font-size: 1.5rem;
cursor: pointer;
padding: 0;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
transition: background 0.3s ease;
}
.close-button:hover {
background: rgba(255, 255, 255, 0.2);
}
.modal-body {
padding: 1.5rem;
color: white;
}
.settings-section {
margin-bottom: 2rem;
}
.settings-section:last-child {
margin-bottom: 0;
}
.settings-section h3 {
margin: 0 0 1rem 0;
font-size: 1.2rem;
color: rgba(255, 255, 255, 0.9);
}
.setting-item {
margin-bottom: 1rem;
}
.setting-item label {
display: flex;
align-items: center;
gap: 0.75rem;
cursor: pointer;
font-size: 1rem;
}
.setting-item input[type="checkbox"] {
width: 20px;
height: 20px;
cursor: pointer;
}
.volume-slider {
flex: 1;
margin: 0 1rem;
}
select {
padding: 0.5rem;
border-radius: 6px;
background: rgba(255, 255, 255, 0.2);
color: white;
border: 1px solid rgba(255, 255, 255, 0.3);
cursor: pointer;
}
select option {
background: #667eea;
color: white;
}
.modal-footer {
display: flex;
gap: 1rem;
padding: 1.5rem;
border-top: 1px solid rgba(255, 255, 255, 0.2);
}
.modal-footer button {
flex: 1;
padding: 0.75rem 1.5rem;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
color: white;
}
.btn-save {
background: rgba(76, 175, 80, 0.8);
}
.btn-save:hover {
background: rgba(76, 175, 80, 1);
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
.btn-cancel {
background: rgba(158, 158, 158, 0.8);
}
.btn-cancel:hover {
background: rgba(158, 158, 158, 1);
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
/* Custom scrollbar */
.modal-content::-webkit-scrollbar {
width: 8px;
}
.modal-content::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
}
.modal-content::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
.modal-content::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
</style>

View File

@@ -0,0 +1,146 @@
<template>
<div class="player-card" :class="{ 'is-current': isCurrent }">
<div class="player-header">
<h4>{{ player.name }}</h4>
<span class="role">{{ player.producerRole }}</span>
</div>
<div class="player-tokens">
<div class="token">🦃 {{ player.tokens.turkey }}</div>
<div class="token"> {{ player.tokens.coffee }}</div>
<div class="token">🌽 {{ player.tokens.corn }}</div>
</div>
<div class="player-stats">
<div class="stat">
<span>Puntos:</span>
<span class="value">{{ player.points }}</span>
</div>
<div v-if="player.shameTokens > 0" class="stat shame">
<span>Vergüenza:</span>
<span class="value">{{ player.shameTokens }}</span>
</div>
</div>
<button v-if="!isCurrent" @click="$emit('make-offer')" class="offer-button">
Hacer oferta
</button>
</div>
</template>
<script setup lang="ts">
defineProps<{
player: {
name: string
producerRole: string
tokens: {
turkey: number
coffee: number
corn: number
}
points: number
shameTokens: number
role: string
}
isCurrent: boolean
}>()
defineEmits<{
'make-offer': []
}>()
</script>
<style scoped>
.player-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.25rem;
backdrop-filter: blur(10px);
border: 2px solid rgba(255, 255, 255, 0.2);
transition: all 0.3s ease;
}
.player-card:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
border-color: rgba(255, 255, 255, 0.4);
}
.player-card.is-current {
border-color: #ffd700;
background: rgba(255, 215, 0, 0.1);
}
.player-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.player-header h4 {
margin: 0;
font-size: 1.2rem;
font-weight: 600;
}
.role {
background: rgba(255, 255, 255, 0.2);
padding: 0.25rem 0.75rem;
border-radius: 6px;
font-size: 0.9rem;
text-transform: capitalize;
}
.player-tokens {
display: flex;
justify-content: space-around;
margin-bottom: 1rem;
padding: 0.75rem;
background: rgba(0, 0, 0, 0.2);
border-radius: 8px;
}
.token {
font-size: 1.1rem;
font-weight: 500;
}
.player-stats {
margin-bottom: 1rem;
}
.stat {
display: flex;
justify-content: space-between;
margin-bottom: 0.5rem;
font-size: 1rem;
}
.stat.shame {
color: #ff6b6b;
}
.value {
font-weight: 700;
}
.offer-button {
width: 100%;
padding: 0.75rem;
background: rgba(103, 126, 234, 0.8);
color: white;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
}
.offer-button:hover {
background: rgba(103, 126, 234, 1);
transform: translateY(-1px);
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
}
</style>

View File

@@ -0,0 +1,290 @@
<template>
<div class="offer-card" :class="offerClass">
<div class="offer-header">
<span class="offer-type">{{ offerTypeText }}</span>
<span class="offer-status" :class="'status-' + offer.status">
{{ statusText }}
</span>
</div>
<div class="offer-content">
<div class="offer-section">
<h5>Ofrece:</h5>
<div class="tokens">
<span v-if="offer.offering.turkey > 0">🦃 {{ offer.offering.turkey }}</span>
<span v-if="offer.offering.coffee > 0"> {{ offer.offering.coffee }}</span>
<span v-if="offer.offering.corn > 0">🌽 {{ offer.offering.corn }}</span>
<span v-if="totalOffering === 0">Nada</span>
</div>
</div>
<div class="exchange-icon"></div>
<div class="offer-section">
<h5>Solicita:</h5>
<div class="tokens">
<span v-if="offer.requesting.turkey > 0">🦃 {{ offer.requesting.turkey }}</span>
<span v-if="offer.requesting.coffee > 0"> {{ offer.requesting.coffee }}</span>
<span v-if="offer.requesting.corn > 0">🌽 {{ offer.requesting.corn }}</span>
<span v-if="totalRequesting === 0">Nada</span>
</div>
</div>
</div>
<div v-if="offer.status === 'pending'" class="offer-actions">
<template v-if="isMyOffer">
<button @click="$emit('cancel', offer.id)" class="btn-cancel">
Cancelar
</button>
</template>
<template v-else>
<button @click="$emit('respond', offer.id, 'accept')" class="btn-accept">
Aceptar
</button>
<button @click="$emit('respond', offer.id, 'reject')" class="btn-reject">
Rechazar
</button>
<button @click="$emit('respond', offer.id, 'snatch')" class="btn-snatch">
Robar
</button>
</template>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
offer: {
id: string
offererId: string
targetId: string
offering: {
turkey: number
coffee: number
corn: number
}
requesting: {
turkey: number
coffee: number
corn: number
}
status: string
}
currentPlayerId: string
}>()
const emit = defineEmits<{
'respond': [offerId: string, response: string]
'cancel': [offerId: string]
}>()
const isMyOffer = computed(() => props.offer.offererId === props.currentPlayerId)
const isTargetedAtMe = computed(() => props.offer.targetId === props.currentPlayerId)
const offerClass = computed(() => ({
'my-offer': isMyOffer.value,
'targeted-at-me': isTargetedAtMe.value,
'status-pending': props.offer.status === 'pending',
'status-accepted': props.offer.status === 'accepted',
'status-rejected': props.offer.status === 'rejected',
'status-snatched': props.offer.status === 'snatched',
'status-cancelled': props.offer.status === 'cancelled'
}))
const offerTypeText = computed(() => {
if (isMyOffer.value) return 'Tu oferta'
if (isTargetedAtMe.value) return 'Oferta para ti'
return 'Oferta'
})
const statusText = computed(() => {
switch (props.offer.status) {
case 'pending': return 'Pendiente'
case 'accepted': return 'Aceptada'
case 'rejected': return 'Rechazada'
case 'snatched': return '¡Robada!'
case 'cancelled': return 'Cancelada'
default: return props.offer.status
}
})
const totalOffering = computed(() =>
props.offer.offering.turkey + props.offer.offering.coffee + props.offer.offering.corn
)
const totalRequesting = computed(() =>
props.offer.requesting.turkey + props.offer.requesting.coffee + props.offer.requesting.corn
)
</script>
<style scoped>
.offer-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.25rem;
margin-bottom: 1rem;
backdrop-filter: blur(10px);
border: 2px solid rgba(255, 255, 255, 0.2);
transition: all 0.3s ease;
}
.offer-card.my-offer {
border-color: rgba(103, 126, 234, 0.5);
background: rgba(103, 126, 234, 0.1);
}
.offer-card.targeted-at-me {
border-color: rgba(255, 215, 0, 0.5);
background: rgba(255, 215, 0, 0.1);
}
.offer-card.status-accepted {
border-color: rgba(76, 175, 80, 0.5);
background: rgba(76, 175, 80, 0.1);
}
.offer-card.status-rejected {
border-color: rgba(244, 67, 54, 0.5);
background: rgba(244, 67, 54, 0.1);
}
.offer-card.status-snatched {
border-color: rgba(255, 107, 107, 0.7);
background: rgba(255, 107, 107, 0.2);
}
.offer-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.offer-type {
font-weight: 600;
font-size: 1.1rem;
}
.offer-status {
padding: 0.25rem 0.75rem;
border-radius: 6px;
font-size: 0.9rem;
font-weight: 500;
}
.status-pending {
background: rgba(255, 193, 7, 0.2);
color: #ffc107;
}
.status-accepted {
background: rgba(76, 175, 80, 0.2);
color: #4caf50;
}
.status-rejected {
background: rgba(244, 67, 54, 0.2);
color: #f44336;
}
.status-snatched {
background: rgba(255, 107, 107, 0.3);
color: #ff6b6b;
}
.status-cancelled {
background: rgba(158, 158, 158, 0.2);
color: #9e9e9e;
}
.offer-content {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1rem;
padding: 1rem;
background: rgba(0, 0, 0, 0.2);
border-radius: 8px;
}
.offer-section {
flex: 1;
}
.offer-section h5 {
margin: 0 0 0.5rem 0;
font-size: 0.9rem;
opacity: 0.8;
}
.tokens {
display: flex;
gap: 0.75rem;
font-size: 1.1rem;
font-weight: 500;
}
.exchange-icon {
font-size: 1.5rem;
opacity: 0.5;
}
.offer-actions {
display: flex;
gap: 0.5rem;
}
button {
flex: 1;
padding: 0.5rem 1rem;
border: none;
border-radius: 6px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
color: white;
}
.btn-accept {
background: rgba(76, 175, 80, 0.8);
}
.btn-accept:hover {
background: rgba(76, 175, 80, 1);
transform: translateY(-1px);
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
}
.btn-reject {
background: rgba(244, 67, 54, 0.8);
}
.btn-reject:hover {
background: rgba(244, 67, 54, 1);
transform: translateY(-1px);
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
}
.btn-snatch {
background: rgba(255, 107, 107, 0.8);
}
.btn-snatch:hover {
background: rgba(255, 107, 107, 1);
transform: translateY(-1px);
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
}
.btn-cancel {
background: rgba(158, 158, 158, 0.8);
}
.btn-cancel:hover {
background: rgba(158, 158, 158, 1);
transform: translateY(-1px);
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
}
</style>

View File

@@ -0,0 +1,176 @@
import { ref, onUnmounted } from 'vue'
export interface AdminStats {
connectedPlayers: number
activeGames: number
currentRound: string
gameState: string
players: any[]
rooms: any[]
timestamp?: number
}
export const useAdminService = () => {
const stats = ref<AdminStats>({
connectedPlayers: 0,
activeGames: 0,
currentRound: 'waiting',
gameState: 'waiting_for_players',
players: [],
rooms: []
})
const isConnected = ref(false)
const error = ref<string | null>(null)
let eventSource: EventSource | null = null
const connect = () => {
if (eventSource) {
console.warn('Already connected to admin stream')
return
}
try {
eventSource = new EventSource('/api/admin/stream')
eventSource.onopen = () => {
console.log('Connected to admin stream')
isConnected.value = true
error.value = null
}
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
stats.value = data
} catch (err) {
console.error('Failed to parse admin stats:', err)
error.value = 'Failed to parse stats data'
}
}
eventSource.onerror = (err) => {
console.error('Admin stream error:', err)
isConnected.value = false
error.value = 'Connection lost'
// Attempt to reconnect after 5 seconds
setTimeout(() => {
if (!eventSource) return
console.log('Attempting to reconnect to admin stream...')
disconnect()
connect()
}, 5000)
}
} catch (err) {
console.error('Failed to connect to admin stream:', err)
error.value = 'Failed to connect'
isConnected.value = false
}
}
const disconnect = () => {
if (eventSource) {
eventSource.close()
eventSource = null
isConnected.value = false
console.log('Disconnected from admin stream')
}
}
const kickPlayer = async (playerId: string) => {
try {
const response = await $fetch('/api/admin/kick-player', {
method: 'POST',
body: { playerId }
})
return response
} catch (err) {
console.error('Failed to kick player:', err)
throw err
}
}
const pauseGame = async () => {
try {
const response = await $fetch('/api/admin/pause-game', {
method: 'POST'
})
return response
} catch (err) {
console.error('Failed to pause game:', err)
throw err
}
}
const resumeGame = async () => {
try {
const response = await $fetch('/api/admin/resume-game', {
method: 'POST'
})
return response
} catch (err) {
console.error('Failed to resume game:', err)
throw err
}
}
const kickAllPlayers = async () => {
try {
const response = await $fetch('/api/admin/kick-all-players', {
method: 'POST'
})
return response
} catch (err) {
console.error('Failed to kick all players:', err)
throw err
}
}
const advanceRound = async () => {
try {
const response = await $fetch('/api/admin/advance-round', {
method: 'POST'
})
return response
} catch (err) {
console.error('Failed to advance round:', err)
throw err
}
}
const previousRound = async () => {
try {
const response = await $fetch('/api/admin/previous-round', {
method: 'POST'
})
return response
} catch (err) {
console.error('Failed to go to previous round:', err)
throw err
}
}
// Clean up on unmount
onUnmounted(() => {
disconnect()
})
return {
// State
stats: readonly(stats),
isConnected: readonly(isConnected),
error: readonly(error),
// Methods
connect,
disconnect,
kickPlayer,
pauseGame,
resumeGame,
kickAllPlayers,
advanceRound,
previousRound
}
}

View File

@@ -0,0 +1,214 @@
import { Client, Room } from 'colyseus.js'
import { ref, reactive } from 'vue'
export interface TokenInventory {
turkey: number
coffee: number
corn: number
}
export interface TradeOffer {
id: string
offererId: string
targetId: string
offering: TokenInventory
requesting: TokenInventory
status: string
}
export interface Player {
id: string
name: string
producerRole: string
tokens: TokenInventory
points: number
shameTokens: number
isSuspended: boolean
role: string
}
export interface GameState {
players: Map<string, Player>
activeTradeOffers: TradeOffer[]
round: number
gamePhase: string
gameStarted: boolean
minPlayers: number
maxPlayers: number
}
export const useGameClient = () => {
const client = ref<Client | null>(null)
const room = ref<Room | null>(null)
const gameState = ref<GameState | null>(null)
const currentPlayerId = ref('')
const isConnected = ref(false)
const connectionStatus = ref('')
// Event callbacks
const onStateChangeCallbacks = ref<((state: GameState) => void)[]>([])
const onGamePhaseChangeCallbacks = ref<((phase: string) => void)[]>([])
const onAdminKickedCallbacks = ref<((data: any) => void)[]>([])
const onRoundChangedCallbacks = ref<((data: any) => void)[]>([])
const connect = async (playerName: string, gameMode: string = 'classic') => {
try {
connectionStatus.value = 'Conectando...'
// Use runtime config for WebSocket URL
const config = useRuntimeConfig()
const wsUrl = config.public.wsUrl || 'ws://localhost:2567'
client.value = new Client(wsUrl)
console.log('Connecting to:', wsUrl)
room.value = await client.value.joinOrCreate('game', {
playerName,
gameMode
})
currentPlayerId.value = room.value.sessionId
isConnected.value = true
connectionStatus.value = 'Conectado exitosamente!'
console.log('Successfully joined room:', room.value.id)
console.log('Player ID:', currentPlayerId.value)
// Setup event listeners
room.value.onStateChange((state) => {
console.log('State changed:', state)
const previousPhase = gameState.value?.gamePhase
gameState.value = state
// Notify all state change callbacks
onStateChangeCallbacks.value.forEach(callback => callback(state))
// Notify phase change if it changed
if (previousPhase !== state.gamePhase) {
console.log('Game phase changed:', previousPhase, '->', state.gamePhase)
onGamePhaseChangeCallbacks.value.forEach(callback => callback(state.gamePhase))
}
})
room.value.onMessage('adminKicked', (data) => {
console.log('Admin kicked:', data)
onAdminKickedCallbacks.value.forEach(callback => callback(data))
})
room.value.onMessage('roundChanged', (data) => {
console.log('Round changed:', data)
onRoundChangedCallbacks.value.forEach(callback => callback(data))
})
room.value.onMessage('gamePaused', (data) => {
console.log('Game paused:', data)
alert(`⏸️ ${data.message}`)
})
room.value.onMessage('gameResumed', (data) => {
console.log('Game resumed:', data)
alert(`▶️ ${data.message}`)
})
room.value.onLeave((code) => {
console.log('Left room with code:', code)
isConnected.value = false
connectionStatus.value = 'Desconectado'
// Handle forced disconnect by admin
if (code === 4000) {
console.log('Disconnected by admin (code 4000)')
}
})
room.value.onError((code, message) => {
console.error('Room error:', code, message)
connectionStatus.value = `Error: ${message}`
})
return room.value
} catch (error) {
console.error('Failed to connect:', error)
connectionStatus.value = 'Error de conexión: ' + (error as Error).message
throw error
}
}
const disconnect = () => {
if (room.value) {
room.value.leave()
room.value = null
}
client.value = null
isConnected.value = false
gameState.value = null
currentPlayerId.value = ''
connectionStatus.value = 'Desconectado'
}
const makeOffer = (targetId: string, offering: TokenInventory, requesting: TokenInventory) => {
if (!room.value) return
room.value.send('makeOffer', {
targetId,
offering,
requesting
})
}
const respondToOffer = (offerId: string, response: 'accept' | 'reject' | 'snatch') => {
if (!room.value) return
room.value.send('respondToOffer', {
offerId,
response
})
}
const cancelOffer = (offerId: string) => {
if (!room.value) return
room.value.send('cancelOffer', {
offerId
})
}
const onStateChange = (callback: (state: GameState) => void) => {
onStateChangeCallbacks.value.push(callback)
}
const onGamePhaseChange = (callback: (phase: string) => void) => {
onGamePhaseChangeCallbacks.value.push(callback)
}
const onAdminKicked = (callback: (data: any) => void) => {
onAdminKickedCallbacks.value.push(callback)
}
const onRoundChanged = (callback: (data: any) => void) => {
onRoundChangedCallbacks.value.push(callback)
}
return {
// State
client: readonly(client),
room: readonly(room),
gameState: readonly(gameState),
currentPlayerId: readonly(currentPlayerId),
isConnected: readonly(isConnected),
connectionStatus: readonly(connectionStatus),
// Methods
connect,
disconnect,
makeOffer,
respondToOffer,
cancelOffer,
// Event handlers
onStateChange,
onGamePhaseChange,
onAdminKicked,
onRoundChanged
}
}

View File

@@ -0,0 +1,395 @@
<template>
<div class="admin-dashboard">
<div class="dashboard-header">
<h1>Panel de Administración - Snatch Game</h1>
<div class="connection-status" :class="{ connected: isConnected }">
{{ isConnected ? '🟢 Conectado' : '🔴 Desconectado' }}
</div>
</div>
<div class="dashboard-content">
<!-- Statistics Cards -->
<div class="stats-grid">
<div class="stat-card">
<h3>Jugadores Conectados</h3>
<div class="stat-value">{{ stats.connectedPlayers }}</div>
</div>
<div class="stat-card">
<h3>Juegos Activos</h3>
<div class="stat-value">{{ stats.activeGames }}</div>
</div>
<div class="stat-card">
<h3>Ronda Actual</h3>
<div class="stat-value">{{ stats.currentRound }}</div>
</div>
<div class="stat-card">
<h3>Estado del Juego</h3>
<div class="stat-value">{{ gameStateDisplay }}</div>
</div>
</div>
<!-- Control Panel -->
<div class="control-panel">
<h2>Controles del Juego</h2>
<div class="controls-grid">
<button @click="pauseGame" class="control-btn pause">
Pausar Juego
</button>
<button @click="resumeGame" class="control-btn resume">
Reanudar Juego
</button>
<button @click="advanceRound" class="control-btn advance">
Avanzar Ronda
</button>
<button @click="previousRound" class="control-btn previous">
Retroceder Ronda
</button>
<button @click="kickAllPlayers" class="control-btn danger">
🚫 Expulsar a Todos
</button>
</div>
</div>
<!-- Players List -->
<div class="players-section">
<h2>Jugadores Activos ({{ stats.players.length }})</h2>
<div v-if="stats.players.length === 0" class="no-players">
No hay jugadores conectados
</div>
<div v-else class="players-grid">
<div v-for="player in stats.players" :key="player.id" class="player-admin-card">
<div class="player-info">
<h4>{{ player.name }}</h4>
<div class="player-details">
<span>Sala: {{ player.roomId?.substring(0, 8) || 'N/A' }}</span>
<span>Rol: {{ player.producerRole }}</span>
<span>Puntos: {{ player.points }}</span>
</div>
<div class="player-tokens">
<span>🦃 {{ player.tokens.turkeys }}</span>
<span> {{ player.tokens.coffee }}</span>
<span>🌽 {{ player.tokens.corn }}</span>
</div>
</div>
<button @click="kickPlayer(player.id)" class="kick-btn">
Expulsar
</button>
</div>
</div>
</div>
<!-- Rooms List -->
<div class="rooms-section">
<h2>Salas Activas ({{ stats.rooms.length }})</h2>
<div v-if="stats.rooms.length === 0" class="no-rooms">
No hay salas activas
</div>
<div v-else class="rooms-grid">
<div v-for="room in stats.rooms" :key="room.roomId" class="room-card">
<h4>Sala: {{ room.roomId.substring(0, 8) }}</h4>
<div class="room-details">
<span>Jugadores: {{ room.players }}/{{ room.maxPlayers }}</span>
<span>Estado: {{ room.locked ? 'Cerrada' : 'Abierta' }}</span>
<span>Fase: {{ room.metadata?.gamePhase || 'N/A' }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, computed } from 'vue'
import { useAdminService } from '~/composables/useAdminService'
const adminService = useAdminService()
const stats = computed(() => adminService.stats.value)
const isConnected = computed(() => adminService.isConnected.value)
const gameStateDisplay = computed(() => {
const state = stats.value.gameState
switch (state) {
case 'waiting_for_players': return 'Esperando jugadores'
case 'in_progress': return 'En progreso'
case 'paused': return 'Pausado'
default: return state
}
})
onMounted(() => {
adminService.connect()
})
const pauseGame = async () => {
try {
const result = await adminService.pauseGame()
console.log('Game paused:', result)
} catch (error) {
console.error('Failed to pause game:', error)
alert('Error al pausar el juego')
}
}
const resumeGame = async () => {
try {
const result = await adminService.resumeGame()
console.log('Game resumed:', result)
} catch (error) {
console.error('Failed to resume game:', error)
alert('Error al reanudar el juego')
}
}
const advanceRound = async () => {
try {
const result = await adminService.advanceRound()
console.log('Round advanced:', result)
} catch (error) {
console.error('Failed to advance round:', error)
alert('Error al avanzar la ronda')
}
}
const previousRound = async () => {
try {
const result = await adminService.previousRound()
console.log('Round went back:', result)
} catch (error) {
console.error('Failed to go to previous round:', error)
alert('Error al retroceder la ronda')
}
}
const kickPlayer = async (playerId: string) => {
if (!confirm(`¿Estás seguro de expulsar al jugador ${playerId}?`)) return
try {
const result = await adminService.kickPlayer(playerId)
console.log('Player kicked:', result)
} catch (error) {
console.error('Failed to kick player:', error)
alert('Error al expulsar al jugador')
}
}
const kickAllPlayers = async () => {
if (!confirm('¿Estás seguro de expulsar a TODOS los jugadores?')) return
try {
const result = await adminService.kickAllPlayers()
console.log('All players kicked:', result)
} catch (error) {
console.error('Failed to kick all players:', error)
alert('Error al expulsar a todos los jugadores')
}
}
</script>
<style scoped>
.admin-dashboard {
min-height: 100vh;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
color: white;
padding: 2rem;
}
.dashboard-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
padding-bottom: 1rem;
border-bottom: 2px solid rgba(255, 255, 255, 0.2);
}
.dashboard-header h1 {
margin: 0;
font-size: 2rem;
}
.connection-status {
padding: 0.5rem 1rem;
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
font-weight: 600;
}
.connection-status.connected {
background: rgba(76, 175, 80, 0.2);
}
.dashboard-content {
max-width: 1400px;
margin: 0 auto;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
}
.stat-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 1.5rem;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2);
}
.stat-card h3 {
margin: 0 0 1rem 0;
font-size: 1rem;
opacity: 0.9;
}
.stat-value {
font-size: 2rem;
font-weight: 700;
color: #ffd700;
}
.control-panel {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 2rem;
margin-bottom: 2rem;
backdrop-filter: blur(10px);
}
.control-panel h2 {
margin: 0 0 1.5rem 0;
}
.controls-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.control-btn {
padding: 1rem;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
color: white;
}
.control-btn.pause {
background: rgba(255, 193, 7, 0.8);
}
.control-btn.resume {
background: rgba(76, 175, 80, 0.8);
}
.control-btn.advance, .control-btn.previous {
background: rgba(33, 150, 243, 0.8);
}
.control-btn.danger {
background: rgba(244, 67, 54, 0.8);
}
.control-btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
filter: brightness(1.1);
}
.players-section, .rooms-section {
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 2rem;
margin-bottom: 2rem;
backdrop-filter: blur(10px);
}
.players-section h2, .rooms-section h2 {
margin: 0 0 1.5rem 0;
}
.no-players, .no-rooms {
text-align: center;
padding: 2rem;
opacity: 0.7;
}
.players-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1rem;
}
.player-admin-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 1rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.player-info h4 {
margin: 0 0 0.5rem 0;
font-size: 1.1rem;
}
.player-details {
display: flex;
gap: 1rem;
font-size: 0.9rem;
opacity: 0.9;
margin-bottom: 0.5rem;
}
.player-tokens {
display: flex;
gap: 0.75rem;
font-size: 1rem;
}
.kick-btn {
padding: 0.5rem 1rem;
background: rgba(244, 67, 54, 0.8);
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.3s ease;
}
.kick-btn:hover {
background: rgba(244, 67, 54, 1);
transform: translateY(-1px);
}
.rooms-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}
.room-card {
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 1rem;
}
.room-card h4 {
margin: 0 0 0.5rem 0;
}
.room-details {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.9rem;
opacity: 0.9;
}
</style>

View File

@@ -0,0 +1,70 @@
<template>
<div id="app">
<HomeScreen
v-if="currentScreen === 'home'"
@join-game="onJoinGame"
@show-settings="showSettings = true"
/>
<GameScreen
v-else-if="currentScreen === 'game'"
:game-client="gameClient"
/>
<!-- Settings Modal -->
<SettingsModal
v-if="showSettings"
@close="showSettings = false"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const currentScreen = ref<'home' | 'game'>('home')
const gameClient = ref<any>(null)
const showSettings = ref(false)
const onJoinGame = (client: any) => {
gameClient.value = client
currentScreen.value = 'game'
console.log('Transitioning to game screen')
// Handle admin kick notification
client.onAdminKicked((data: any) => {
// Show alert message
alert(`🚫 ${data.message}`)
// Return to home screen
currentScreen.value = 'home'
gameClient.value = null
console.log('Player kicked by admin, returned to home screen')
})
// Handle round change notification
client.onRoundChanged((data: any) => {
// Show alert message
alert(`🎯 ${data.message}`)
console.log('Round changed by admin:', data)
})
}
</script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background-color: #f5f5f5;
}
#app {
min-height: 100vh;
}
</style>

View File

@@ -0,0 +1,59 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
future: {
compatibilityVersion: 4,
},
compatibilityDate: '2025-07-15',
devtools: { enabled: true },
// Configure server
nitro: {
experimental: {
websocket: true
},
// Enable WebSocket support
devProxy: {
'/ws': {
target: 'ws://localhost:3000',
ws: true,
changeOrigin: true
}
}
},
// Environment variables
runtimeConfig: {
public: {
gameName: 'SnatchGame',
wsUrl: process.env.NUXT_PUBLIC_WS_URL || 'ws://localhost:2567'
}
},
// TypeScript configuration
typescript: {
strict: true,
shim: false,
tsConfig: {
compilerOptions: {
experimentalDecorators: true,
emitDecoratorMetadata: true
}
}
},
// Disable SSR for game application
ssr: false,
// Vite configuration for WebSocket support
vite: {
server: {
proxy: {
'/ws': {
target: 'ws://localhost:3000',
ws: true,
changeOrigin: true
}
}
}
}
})

13939
nuxt-snatchgame/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
{
"name": "nuxt-app",
"private": true,
"type": "module",
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"dev:colyseus": "tsx watch server/colyseus-server.ts",
"dev:all": "concurrently \"npm run dev\" \"npm run dev:colyseus\"",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"dependencies": {
"@colyseus/core": "^0.16.19",
"@colyseus/schema": "^3.0.49",
"@colyseus/ws-transport": "^0.16.5",
"colyseus": "^0.16.4",
"colyseus.js": "^0.16.19",
"nuxt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"vue": "^3.5.18",
"vue-router": "^4.5.1"
},
"devDependencies": {
"@colyseus/monitor": "^0.16.7",
"@colyseus/tools": "^0.16.13",
"@types/cors": "^2.8.19",
"@types/express": "^5.0.3",
"concurrently": "^9.2.0",
"cors": "^2.8.5",
"express": "^5.1.0",
"tsx": "^4.20.3"
}
}

View File

@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
<stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
</linearGradient>
</defs>
<circle cx="100" cy="100" r="90" fill="url(#grad1)" />
<text x="100" y="110" font-family="Arial, sans-serif" font-size="48" font-weight="bold" fill="white" text-anchor="middle">SG</text>
</svg>

After

Width:  |  Height:  |  Size: 509 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -0,0 +1,2 @@
User-Agent: *
Disallow:

View File

@@ -0,0 +1,42 @@
import 'reflect-metadata'
import { listen } from '@colyseus/tools'
import { monitor } from '@colyseus/monitor'
import { Server } from 'colyseus'
import { WebSocketTransport } from '@colyseus/ws-transport'
import { createServer } from 'http'
import express from 'express'
import cors from 'cors'
import { GameRoom } from './rooms/GameRoom'
const port = parseInt(process.env.PORT || '2567', 10)
const app = express()
// Enable CORS
app.use(cors())
app.use(express.json())
// Create HTTP & WebSocket servers
const server = createServer(app)
const gameServer = new Server({
transport: new WebSocketTransport({
server
})
})
// Register GameRoom
gameServer.define('game', GameRoom)
.filterBy(['gameMode'])
.sortBy({ clients: 1 })
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'healthy' })
})
// Colyseus monitor
app.use('/monitor', monitor())
gameServer.listen(port)
console.log(`🎮 Colyseus server is listening on ws://localhost:${port}`)

View File

View File

@@ -0,0 +1,416 @@
import { Room, Client } from "colyseus";
import { Schema, MapSchema, ArraySchema, type } from "@colyseus/schema";
export interface GameRoomOptions {
gameMode?: string;
playerName?: string;
}
export class TokenInventory extends Schema {
@type("number") turkey: number = 0;
@type("number") coffee: number = 0;
@type("number") corn: number = 0;
}
export class TradeOffer extends Schema {
@type("string") id: string = "";
@type("string") offererId: string = "";
@type("string") targetId: string = "";
@type(TokenInventory) offering = new TokenInventory();
@type(TokenInventory) requesting = new TokenInventory();
@type("string") status: string = "pending"; // "pending" | "accepted" | "rejected" | "snatched" | "cancelled"
}
export class Player extends Schema {
@type("string") id: string = "";
@type("string") name: string = "";
@type("string") producerRole: string = "turkey"; // "turkey" | "coffee" | "corn"
@type(TokenInventory) tokens = new TokenInventory();
@type("number") points: number = 0;
@type("number") shameTokens: number = 0;
@type("boolean") isSuspended: boolean = false;
@type("string") role: string = "trader"; // "trader" | "judge"
}
export class GameState extends Schema {
@type({ map: Player }) players = new MapSchema<Player>();
@type({ array: TradeOffer }) activeTradeOffers = new ArraySchema<TradeOffer>();
@type("number") round: number = 1;
@type("string") gamePhase: string = "waiting"; // "waiting" | "trading" | "judging" | "results"
@type("boolean") gameStarted: boolean = false;
@type("number") minPlayers: number = 3;
@type("number") maxPlayers: number = 3;
}
export class GameRoom extends Room<GameState> {
maxClients = 3;
private producerRoles = ["turkey", "coffee", "corn"];
onCreate(options: GameRoomOptions) {
console.log(`GameRoom created with options:`, options);
this.setState(new GameState());
this.state.gamePhase = "waiting";
this.onMessage("makeOffer", (client, message) => {
this.handleMakeOffer(client, message);
});
this.onMessage("respondToOffer", (client, message) => {
this.handleRespondToOffer(client, message);
});
this.onMessage("cancelOffer", (client, message) => {
this.handleCancelOffer(client, message);
});
this.onMessage("*", (client, type, message) => {
console.log(`Message from ${client.sessionId}:`, type, message);
});
}
private assignProducerRoles() {
const playerIds = Array.from(this.state.players.keys());
const shuffledRoles = [...this.producerRoles].sort(() => Math.random() - 0.5);
playerIds.forEach((playerId, index) => {
const player = this.state.players.get(playerId);
if (player) {
player.producerRole = shuffledRoles[index];
// Initialize tokens based on producer role
player.tokens.turkey = 0;
player.tokens.coffee = 0;
player.tokens.corn = 0;
switch (player.producerRole) {
case "turkey":
player.tokens.turkey = 5;
break;
case "coffee":
player.tokens.coffee = 5;
break;
case "corn":
player.tokens.corn = 5;
break;
}
console.log(`🎭 Player ${player.name} assigned role: ${player.producerRole}`);
}
});
}
private calculatePoints(player: Player): number {
const ownTokens = Number(player.tokens[player.producerRole as keyof TokenInventory]) || 0;
const totalTokens = Number(player.tokens.turkey || 0) + Number(player.tokens.coffee || 0) + Number(player.tokens.corn || 0);
const otherTokens = totalTokens - ownTokens;
return ownTokens * 1 + otherTokens * 2;
}
private updateAllPlayerPoints() {
this.state.players.forEach(player => {
player.points = this.calculatePoints(player);
});
}
private handleMakeOffer(client: Client, message: any) {
const player = this.state.players.get(client.sessionId);
if (!player || this.state.gamePhase !== "trading") {
console.log(`Offer rejected - invalid state`);
return;
}
// Cannot offer to self
if (message.targetId === client.sessionId) {
console.log(`Offer rejected - cannot offer to self`);
return;
}
// Count existing offers from THIS player to THIS target
const existingOffers = this.state.activeTradeOffers.filter(offer =>
offer.offererId === client.sessionId &&
offer.targetId === message.targetId &&
offer.status === "pending"
);
if (existingOffers.length >= 2) {
console.log(`Offer rejected - maximum 2 offers per target reached`);
return;
}
const offer = new TradeOffer();
offer.id = `${client.sessionId}-${Date.now()}`;
offer.offererId = client.sessionId;
offer.targetId = message.targetId;
offer.offering.turkey = message.offering.turkey || 0;
offer.offering.coffee = message.offering.coffee || 0;
offer.offering.corn = message.offering.corn || 0;
offer.requesting.turkey = message.requesting.turkey || 0;
offer.requesting.coffee = message.requesting.coffee || 0;
offer.requesting.corn = message.requesting.corn || 0;
offer.status = "pending";
this.state.activeTradeOffers.push(offer);
console.log(`📝 Trade offer created: ${offer.id}`);
}
private handleRespondToOffer(client: Client, message: any) {
const offer = this.state.activeTradeOffers.find(o => o.id === message.offerId);
if (!offer || offer.targetId !== client.sessionId || offer.status !== "pending") {
console.log(`Response rejected - invalid offer`);
return;
}
const response = message.response; // "accept" | "reject" | "snatch"
offer.status = response === "accept" ? "accepted" : response === "reject" ? "rejected" : "snatched";
if (response === "accept" || response === "snatch") {
this.executeTradeOffer(offer, response === "snatch");
}
console.log(`✅ Trade offer ${offer.id} ${response}ed`);
this.updateAllPlayerPoints();
}
private handleCancelOffer(client: Client, message: any) {
const offer = this.state.activeTradeOffers.find(o => o.id === message.offerId);
if (!offer || offer.offererId !== client.sessionId || offer.status !== "pending") {
console.log(`Cancel rejected - invalid offer`);
return;
}
offer.status = "cancelled";
console.log(`❌ Trade offer ${offer.id} cancelled`);
}
private executeTradeOffer(offer: TradeOffer, isSnatch: boolean) {
const offerer = this.state.players.get(offer.offererId);
const target = this.state.players.get(offer.targetId);
if (!offerer || !target) return;
// Calculate what can actually be transferred
const actualOffering = {
turkey: Math.min(offer.offering.turkey, offerer.tokens.turkey),
coffee: Math.min(offer.offering.coffee, offerer.tokens.coffee),
corn: Math.min(offer.offering.corn, offerer.tokens.corn)
};
const actualRequesting = isSnatch ? { turkey: 0, coffee: 0, corn: 0 } : {
turkey: Math.min(offer.requesting.turkey, target.tokens.turkey),
coffee: Math.min(offer.requesting.coffee, target.tokens.coffee),
corn: Math.min(offer.requesting.corn, target.tokens.corn)
};
// Transfer tokens
offerer.tokens.turkey -= actualOffering.turkey;
offerer.tokens.coffee -= actualOffering.coffee;
offerer.tokens.corn -= actualOffering.corn;
offerer.tokens.turkey += actualRequesting.turkey;
offerer.tokens.coffee += actualRequesting.coffee;
offerer.tokens.corn += actualRequesting.corn;
target.tokens.turkey += actualOffering.turkey;
target.tokens.coffee += actualOffering.coffee;
target.tokens.corn += actualOffering.corn;
target.tokens.turkey -= actualRequesting.turkey;
target.tokens.coffee -= actualRequesting.coffee;
target.tokens.corn -= actualRequesting.corn;
console.log(`🔄 Trade executed: ${isSnatch ? 'SNATCH' : 'FAIR'}`);
}
private checkGameStart() {
const playerCount = this.state.players.size;
if (playerCount === this.state.minPlayers && this.state.gamePhase === "waiting") {
this.assignProducerRoles();
this.state.gamePhase = "trading";
this.state.gameStarted = true;
this.state.round = 1;
console.log(`🚀 Game started! Round ${this.state.round} - Trading phase`);
} else if (playerCount < this.state.minPlayers && this.state.gameStarted) {
this.state.gamePhase = "waiting";
this.state.gameStarted = false;
console.log(`⏸️ Game paused - not enough players (${playerCount}/${this.state.minPlayers})`);
}
}
onJoin(client: Client, options: any) {
console.log(`Client ${client.sessionId} joined the room`);
const player = new Player();
player.id = client.sessionId;
player.name = options.playerName || `Player ${this.state.players.size + 1}`;
player.producerRole = "turkey"; // Will be reassigned when game starts
player.tokens = new TokenInventory();
player.points = 0;
player.shameTokens = 0;
player.isSuspended = false;
player.role = "trader";
this.state.players.set(client.sessionId, player);
// Check if we can start the game
this.checkGameStart();
}
onLeave(client: Client, consented: boolean) {
console.log(`Client ${client.sessionId} left the room`);
this.state.players.delete(client.sessionId);
// Check if we need to pause the game
this.checkGameStart();
}
onDispose() {
console.log(`GameRoom ${this.roomId} disposed`);
}
// Method for admin monitoring - used by Colyseus monitor and admin API
getInspectData() {
const stateSize = JSON.stringify(this.state).length;
const roomElapsedTime = this.clock.elapsedTime;
// Gather client information
const clients = this.clients.map((client) => ({
sessionId: client.sessionId,
elapsedTime: roomElapsedTime - (client as any)._joinedAt || 0
}));
// Return comprehensive room data
return {
roomId: this.roomId,
name: 'game',
clientCount: clients.length,
maxClients: this.maxClients,
locked: this.locked,
state: this.state,
stateSize,
clients: clients,
elapsedTime: roomElapsedTime,
metadata: {
gamePhase: this.state.gamePhase,
gameStarted: this.state.gameStarted,
round: this.state.round,
playerCount: this.state.players.size,
activeOffers: this.state.activeTradeOffers.length
}
};
}
// Admin methods for game control
pauseGame() {
if (this.state.gameStarted && this.state.gamePhase !== 'paused') {
this.state.gamePhase = 'paused';
console.log(`⏸️ Game paused in room ${this.roomId} by admin`);
// Broadcast pause message to all clients
this.broadcast("gamePaused", {
message: "El juego ha sido pausado por el administrador",
timestamp: Date.now()
});
}
}
resumeGame() {
if (this.state.gameStarted && this.state.gamePhase === 'paused') {
this.state.gamePhase = 'trading'; // Resume to trading phase
console.log(`▶️ Game resumed in room ${this.roomId} by admin`);
// Broadcast resume message to all clients
this.broadcast("gameResumed", {
message: "El juego ha sido reanudado por el administrador",
timestamp: Date.now()
});
}
}
_forceClientDisconnect(sessionId: string) {
const client = this.clients.find(c => c.sessionId === sessionId);
if (client) {
console.log(`🚫 Admin force disconnect player ${sessionId} from room ${this.roomId}`);
// Send notification to the specific client before disconnecting
client.send("adminKicked", {
message: "Has sido expulsado del juego por el administrador",
reason: "admin_kick",
timestamp: Date.now()
});
// Give client time to process the message, then disconnect
setTimeout(() => {
client.leave(4000); // Force disconnect with code 4000
}, 1000);
} else {
throw new Error(`Player ${sessionId} not found in room ${this.roomId}`);
}
}
_forceDisconnectAllClients() {
console.log(`🚫🚫 Admin force disconnect ALL players from room ${this.roomId}`);
if (this.clients.length === 0) {
return { success: true, kickedPlayers: 0 };
}
// Send notification to all clients first
this.broadcast("adminKicked", {
message: "Todos los jugadores han sido expulsados por el administrador",
reason: "admin_kick_all",
timestamp: Date.now()
});
const kickedCount = this.clients.length;
// Give clients time to process the message, then disconnect all
setTimeout(() => {
// Create a copy of clients array since it will be modified during iteration
const clientsToDisconnect = [...this.clients];
clientsToDisconnect.forEach(client => {
client.leave(4000); // Force disconnect with code 4000
});
}, 1000);
return { success: true, kickedPlayers: kickedCount };
}
advanceRound() {
const oldRound = this.state.round;
this.state.round = Math.min(oldRound + 1, 10); // Max 10 rounds
const newRound = this.state.round;
console.log(`⏭️ Round advanced from ${oldRound} to ${newRound} in room ${this.roomId}`);
// Broadcast round change to all clients
this.broadcast("roundChanged", {
oldRound,
newRound,
message: `Ronda ${newRound} - Cambio realizado por el administrador`,
timestamp: Date.now()
});
return { success: true, newRound, oldRound };
}
previousRound() {
const oldRound = this.state.round;
this.state.round = Math.max(oldRound - 1, 1); // Min round 1
const newRound = this.state.round;
console.log(`⏮️ Round went back from ${oldRound} to ${newRound} in room ${this.roomId}`);
// Broadcast round change to all clients
this.broadcast("roundChanged", {
oldRound,
newRound,
message: `Ronda ${newRound} - Cambio realizado por el administrador`,
timestamp: Date.now()
});
return { success: true, newRound, oldRound };
}
}

View File

@@ -0,0 +1,25 @@
{
// https://nuxt.com/docs/guide/concepts/typescript
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"files": [],
"references": [
{
"path": "./.nuxt/tsconfig.app.json"
},
{
"path": "./.nuxt/tsconfig.server.json"
},
{
"path": "./.nuxt/tsconfig.shared.json"
},
{
"path": "./.nuxt/tsconfig.node.json"
}
]
}

View File

@@ -35,7 +35,7 @@
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/username/snatchgame.git" "url": "git+https://github.com/username/snatchgame.git"
}, },
"bugs": { "bugs": {
"url": "https://github.com/username/snatchgame/issues" "url": "https://github.com/username/snatchgame/issues"
@@ -51,5 +51,86 @@
], ],
"devDependencies": { "devDependencies": {
"concurrently": "^8.2.2" "concurrently": "^8.2.2"
} },
} "main": "index.js",
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.0",
"bytes": "^3.1.2",
"call-bind-apply-helpers": "^1.0.2",
"call-bound": "^1.0.4",
"content-disposition": "^1.0.0",
"content-type": "^1.0.5",
"cookie": "^0.7.2",
"cookie-signature": "^1.2.2",
"debug": "^4.4.1",
"depd": "^2.0.0",
"detect-libc": "^2.0.4",
"dunder-proto": "^1.0.1",
"ee-first": "^1.1.1",
"encodeurl": "^2.0.0",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"escape-html": "^1.0.3",
"etag": "^1.8.1",
"express": "^5.1.0",
"finalhandler": "^2.1.0",
"forwarded": "^0.2.0",
"fresh": "^2.0.0",
"function-bind": "^1.1.2",
"get-intrinsic": "^1.3.0",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"http-errors": "^2.0.0",
"iconv-lite": "^0.6.3",
"inherits": "^2.0.4",
"ipaddr.js": "^1.9.1",
"is-promise": "^4.0.0",
"lodash": "^4.17.21",
"math-intrinsics": "^1.1.0",
"media-typer": "^1.1.0",
"merge-descriptors": "^2.0.0",
"mime-db": "^1.54.0",
"mime-types": "^3.0.1",
"ms": "^2.1.3",
"msgpackr-extract": "^3.0.3",
"nanoid": "^2.1.11",
"negotiator": "^1.0.0",
"node-gyp-build-optional-packages": "^5.2.2",
"node-os-utils": "^1.3.7",
"object-inspect": "^1.13.4",
"on-finished": "^2.4.1",
"once": "^1.4.0",
"parseurl": "^1.3.3",
"path-to-regexp": "^8.2.0",
"proxy-addr": "^2.0.7",
"qs": "^6.14.0",
"range-parser": "^1.2.1",
"raw-body": "^3.0.0",
"router": "^2.2.0",
"safe-buffer": "^5.2.1",
"safer-buffer": "^2.1.2",
"send": "^1.2.0",
"serve-static": "^2.2.0",
"setprototypeof": "^1.2.0",
"side-channel": "^1.1.0",
"side-channel-list": "^1.0.0",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2",
"snatchgame-client": "^0.0.8-alpha",
"snatchgame-server": "^0.0.8-alpha",
"statuses": "^2.0.2",
"toidentifier": "^1.0.1",
"tree-kill": "^1.2.2",
"tslib": "^2.8.1",
"type-is": "^2.0.1",
"typescript": "^5.8.3",
"unpipe": "^1.0.0",
"vary": "^1.1.2",
"wrappy": "^1.0.2"
},
"type": "commonjs"
}

View File

@@ -1,357 +0,0 @@
# 🎯 Snatch or Share - Servidor
Servidor de juego multijugador basado en Colyseus.io que implementa el "Snatch Game" de Elinor Ostrom para estudiar la evolución de instituciones y cooperación.
## 🛠️ Stack Tecnológico
- **Colyseus.io** (framework de servidor multijugador)
- **Node.js** (runtime)
- **TypeScript** (tipado estricto)
- **Express** (servidor HTTP)
- **@colyseus/schema** (sincronización de estado)
## 🚀 Inicio Rápido
### Prerrequisitos
- Node.js 18+
- npm 9+
### Instalación y Desarrollo
```bash
# Instalar dependencias
npm install
# Iniciar servidor de desarrollo (puerto 2567)
npm run dev
# Verificar que el servidor esté ejecutándose
curl http://localhost:2567
```
### Comandos Disponibles
```bash
# Desarrollo
npm run dev # Servidor con hot reload (ts-node-dev)
# Producción
npm run build # Compilar TypeScript a JavaScript
npm run start # Ejecutar servidor compilado
# Utilidades
npm test # Ejecutar tests (placeholder)
```
## 🏗️ Arquitectura del Servidor
### Estructura de Directorios
```
server/
├── src/
│ ├── rooms/ # Salas de juego Colyseus
│ │ └── GameRoom.ts # Sala principal del juego
│ ├── app.config.ts # Configuración de Colyseus
│ └── index.ts # Punto de entrada del servidor
├── lib/ # JavaScript compilado (build)
└── tsconfig.json # Configuración TypeScript
```
### GameRoom.ts - Sala Principal
```typescript
export class GameRoom extends Room<GameState> {
maxClients = 3;
private producerRoles = ["turkey", "coffee", "corn"];
onCreate(options: GameRoomOptions) {
// Inicialización de la sala
}
onJoin(client: Client, options: any) {
// Manejo de jugadores que se unen
}
onMessage(type: string, callback: Function) {
// Handlers de mensajes del cliente
}
}
```
## 📊 Esquemas de Estado (Colyseus Schema)
### GameState
Estado principal del juego sincronizado con todos los clientes:
```typescript
export class GameState extends Schema {
@type({ map: Player }) players = new MapSchema<Player>();
@type({ array: TradeOffer }) activeTradeOffers = new ArraySchema<TradeOffer>();
@type("number") round: number = 1;
@type("string") gamePhase: string = "waiting";
@type("boolean") gameStarted: boolean = false;
@type("number") minPlayers: number = 3;
@type("number") maxPlayers: number = 3;
}
```
### Player
Información de cada jugador:
```typescript
export class Player extends Schema {
@type("string") id: string;
@type("string") name: string;
@type("string") producerRole: string; // "turkey" | "coffee" | "corn"
@type(TokenInventory) tokens = new TokenInventory();
@type("number") points: number = 0;
@type("number") shameTokens: number = 0;
@type("boolean") isSuspended: boolean = false;
@type("string") role: string = "trader"; // "trader" | "judge"
}
```
### TradeOffer
Ofertas comerciales entre jugadores:
```typescript
export class TradeOffer extends Schema {
@type("string") id: string;
@type("string") offererId: string;
@type("string") targetId: string;
@type(TokenInventory) offering = new TokenInventory();
@type(TokenInventory) requesting = new TokenInventory();
@type("string") status: string = "pending";
}
```
### TokenInventory
Inventario de tokens por jugador:
```typescript
export class TokenInventory extends Schema {
@type("number") turkey: number = 0;
@type("number") coffee: number = 0;
@type("number") corn: number = 0;
}
```
## 🎮 Lógica del Juego
### Inicialización
1. **Sala creada**: Espera exactamente 3 jugadores
2. **Asignación de roles**: Roles únicos asignados aleatoriamente
3. **Distribución inicial**: 5 tokens del tipo correspondiente
4. **Fase trading**: Comienza la Ronda 1
### Sistema de Tokens
- **Valor propio**: 1 punto por token del mismo tipo
- **Valor ajeno**: 2 puntos por token de otro tipo
- **Ejemplo**: 5 propios + 3 ajenos = 5×1 + 3×2 = 11 puntos
### Ofertas Comerciales
- **Límite**: Máximo 2 ofertas por jugador por objetivo
- **Simultaneidad**: Múltiples ofertas activas
- **Visibilidad**: Todas las ofertas son públicas
- **Respuestas**: Accept, Reject, Snatch
### Cumplimiento Parcial
```typescript
// Ejemplo: Ofrecer 6 tokens pero solo tener 5
const actualOffering = {
turkey: Math.min(offer.offering.turkey, offerer.tokens.turkey),
coffee: Math.min(offer.offering.coffee, offerer.tokens.coffee),
corn: Math.min(offer.offering.corn, offerer.tokens.corn)
};
```
## 📡 API de Mensajes
### Mensajes del Cliente → Servidor
#### makeOffer
```typescript
{
targetId: string,
offering: { turkey: number, coffee: number, corn: number },
requesting: { turkey: number, coffee: number, corn: number }
}
```
#### respondToOffer
```typescript
{
offerId: string,
response: "accept" | "reject" | "snatch"
}
```
#### cancelOffer
```typescript
{
offerId: string
}
```
### Eventos del Servidor → Cliente
#### onStateChange
- Sincronización automática del `GameState`
- Reactividad en tiempo real
- Cambios en jugadores, ofertas, puntuaciones
## 🔧 Configuración
### Configuración de Colyseus
```typescript
// app.config.ts
import config from "@colyseus/tools";
import { GameRoom } from "./rooms/GameRoom";
export default config({
initializeGameServer: (gameServer) => {
gameServer.define('game', GameRoom);
},
initializeExpress: (app) => {
app.get("/", (req, res) => {
res.send("Snatch or Share Server");
});
},
beforeListen: () => {
console.log("🎮 Snatch or Share Server starting...");
}
});
```
### Variables de Entorno
```env
# Puerto del servidor
PORT=2567
# Modo de desarrollo
NODE_ENV=development
# URL de producción (si aplica)
PRODUCTION_URL=wss://tu-servidor.com
```
## 🎯 Funcionalidades Implementadas
### Ronda 1: Estado de Naturaleza
- ✅ Sin reglas especiales
- ✅ Todos los jugadores son "Traders"
- ✅ Libre mercado sin enforcement
### Sistema de Ofertas
- ✅ Ofertas simultáneas múltiples
- ✅ Límite de 2 ofertas por target
- ✅ Cumplimiento parcial automático
- ✅ Respuestas: Accept/Reject/Snatch
### Gestión de Estado
- ✅ Sincronización en tiempo real
- ✅ Asignación automática de roles
- ✅ Cálculo automático de puntos
- ✅ Rotación de ofertas (más recientes arriba)
## 🔍 Debugging y Monitoreo
### Logs del Servidor
```typescript
// Logs automáticos incluidos
console.log(`🎭 Player ${player.name} assigned role: ${player.producerRole}`);
console.log(`📝 Trade offer created: ${offer.id}`);
console.log(`✅ Trade offer ${offer.id} ${response}ed`);
console.log(`🔄 Trade executed: ${isSnatch ? 'SNATCH' : 'FAIR'}`);
```
### Monitor de Colyseus
```bash
# Acceder al monitor (desarrollo)
http://localhost:2567/colyseus
```
### Verificación de Estado
```bash
# Verificar salas activas
curl http://localhost:2567/matchmake/game
# Estado del servidor
curl http://localhost:2567
```
## 🚀 Despliegue
### Desarrollo
```bash
npm run dev
# Servidor disponible en ws://localhost:2567
```
### Producción
```bash
npm run build
npm run start
# Puerto configurado via PORT env var
```
### Docker (desde raíz del proyecto)
```bash
docker-compose up server
```
## 🧪 Testing
### Probar Conexión
```bash
# Verificar que el servidor responde
curl -i http://localhost:2567
# Verificar WebSocket (usando wscat)
wscat -c ws://localhost:2567
```
### Generar Tipos para Cliente
```bash
# Desde directorio server
npx schema-codegen src/rooms/GameRoom.ts --ts --output ../client/src/types/
```
## ⚡ Rendimiento
### Optimizaciones Implementadas
- **Schema eficiente**: Solo sincroniza cambios
- **Límites por sala**: Máximo 3 clientes
- **Cleanup automático**: Gestión de memoria
- **Validación**: Prevención de estados inválidos
### Métricas Clave
- **Latencia**: <50ms para red local
- **Throughput**: 100+ mensajes/segundo por sala
- **Memoria**: ~10MB por sala activa
## 🔐 Seguridad
### Validaciones Implementadas
- Límite de ofertas por jugador
- Validación de tokens disponibles
- Verificación de permisos por acción
- Prevención de auto-ofertas
### Consideraciones
- Sin autenticación (red local)
- Validación en servidor (nunca confiar en cliente)
- Límites estrictos en recursos
## 🤝 Contribución
Ver [CLAUDE.md](../CLAUDE.md) para:
- Convenciones de código
- Guías de desarrollo
- Arquitectura del proyecto
- Comandos útiles