feat: Complete Admin Dashboard with game control and player management (v0.0.8-alpha)
## Major Features Added - **🎛️ Complete Admin Dashboard**: Real-time player monitoring with detailed stats - **👥 Player Management**: Individual and mass player kicking with proper notifications - **🎯 Global Round Control**: Advance/retreat rounds across all rooms simultaneously - **⏸️ Game Control**: Pause/resume games from admin interface - **🔔 Client Notifications**: Players receive alerts for kicks and round changes ## Technical Improvements - **🏗️ Official Colyseus API**: Replaced global variable hacks with `matchMaker.query()` and `matchMaker.remoteRoomCall()` - **📡 Proper Client Communication**: Implemented broadcast messages for `adminKicked`, `gamePaused`, `gameResumed`, `roundChanged` - **🎮 Enhanced GameRoom Methods**: Added `pauseGame()`, `resumeGame()`, `advanceRound()`, `previousRound()`, `_forceClientDisconnect()`, `_forceDisconnectAllClients()`, `getInspectData()` ## UI/UX Enhancements - **📊 Detailed Player Info**: Name, room, role, producer type, and current tokens (🦃☕🌽) - **🚫 Proper Kick Notifications**: Clients auto-redirect to home with clear messaging - **🎨 Improved Admin Interface**: Better organized controls for non-technical commentators - **📱 Responsive Design**: Works well on different screen sizes ## Bug Fixes - **🔧 Fixed Admin Service URLs**: Now correctly calls Colyseus server (port 2567) instead of admin server (port 3001) - **✅ Mass Kick Notifications**: All players receive proper notifications when expelled en masse - **🔄 Auto-redirect**: Kicked clients properly return to home screen ## Architecture - **🏗️ Clean API Design**: All admin endpoints use official Colyseus patterns - **🔒 Type Safety**: Maintained TypeScript sync between server and clients - **📦 Microservices Ready**: Separated concerns between game server and admin interface **Breaking Changes:** None - fully backward compatible **Migration:** No migration needed
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import config from "@colyseus/tools";
|
||||
import { monitor } from "@colyseus/monitor";
|
||||
import { matchMaker } from "@colyseus/core";
|
||||
import { GameRoom } from "./rooms/GameRoom";
|
||||
|
||||
export default config({
|
||||
@@ -19,12 +21,380 @@ export default config({
|
||||
res.json({
|
||||
name: "SnatchGame Server",
|
||||
status: "running",
|
||||
version: "1.0.0"
|
||||
version: "0.0.8-alpha",
|
||||
description: "Multiplayer game server for SnatchGame",
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/health", (req, res) => {
|
||||
res.json({ status: "healthy" });
|
||||
});
|
||||
|
||||
// Colyseus official monitoring panel
|
||||
app.use("/monitor", monitor({
|
||||
columns: [
|
||||
'roomId',
|
||||
'name',
|
||||
'clients',
|
||||
'maxClients',
|
||||
'locked',
|
||||
'elapsedTime'
|
||||
]
|
||||
}));
|
||||
|
||||
// CORS for admin interface
|
||||
app.use("/api/admin", (req, res, next) => {
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
||||
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
res.sendStatus(200);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
// Admin endpoints
|
||||
app.use(require('express').json());
|
||||
|
||||
// Get game statistics using official matchMaker API
|
||||
app.get("/api/admin/stats", async (req, res) => {
|
||||
try {
|
||||
const rooms = await matchMaker.query({});
|
||||
let totalPlayers = 0;
|
||||
let activeGames = 0;
|
||||
const gameRooms = [];
|
||||
const allPlayers = [];
|
||||
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
activeGames++;
|
||||
totalPlayers += room.clients;
|
||||
|
||||
// Get detailed room information including players
|
||||
try {
|
||||
const roomData = await matchMaker.remoteRoomCall(room.roomId, "getInspectData");
|
||||
|
||||
gameRooms.push({
|
||||
roomId: room.roomId,
|
||||
players: room.clients,
|
||||
maxPlayers: room.maxClients,
|
||||
locked: room.locked,
|
||||
createdAt: room.createdAt,
|
||||
elapsedTime: Date.now() - new Date(room.createdAt).getTime()
|
||||
});
|
||||
|
||||
// Extract player information with their tokens
|
||||
if (roomData.state && roomData.state.players) {
|
||||
// Use forEach to iterate over MapSchema properly
|
||||
roomData.state.players.forEach((player, playerId) => {
|
||||
// Skip internal MapSchema properties
|
||||
if (playerId.startsWith('$') || playerId === 'deletedItems') {
|
||||
return;
|
||||
}
|
||||
|
||||
allPlayers.push({
|
||||
id: playerId,
|
||||
name: player.name || 'Unknown',
|
||||
roomId: room.roomId,
|
||||
role: player.role || 'player',
|
||||
producerRole: player.producerRole || 'turkey',
|
||||
tokens: {
|
||||
turkeys: player.tokens?.turkey || 0,
|
||||
coffee: player.tokens?.coffee || 0,
|
||||
corn: player.tokens?.corn || 0
|
||||
},
|
||||
isReady: player.isReady || false,
|
||||
isConnected: player.isConnected !== false
|
||||
});
|
||||
});
|
||||
}
|
||||
} catch (roomError) {
|
||||
console.error(`Failed to get room data for ${room.roomId}:`, roomError);
|
||||
// Still add basic room info even if detailed data fails
|
||||
gameRooms.push({
|
||||
roomId: room.roomId,
|
||||
players: room.clients,
|
||||
maxPlayers: room.maxClients,
|
||||
locked: room.locked,
|
||||
createdAt: room.createdAt,
|
||||
elapsedTime: Date.now() - new Date(room.createdAt).getTime()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
connectedPlayers: totalPlayers,
|
||||
activeGames,
|
||||
currentRound: activeGames > 0 ? 'Ronda 1' : 'waiting',
|
||||
gameState: activeGames > 0 ? 'in_progress' : 'waiting_for_players',
|
||||
players: allPlayers,
|
||||
rooms: gameRooms
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Admin stats error:', error);
|
||||
res.status(500).json({
|
||||
error: 'Failed to get stats',
|
||||
connectedPlayers: 0,
|
||||
activeGames: 0,
|
||||
currentRound: 'error',
|
||||
gameState: 'error',
|
||||
players: [],
|
||||
rooms: []
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Kick player using official matchMaker API
|
||||
app.post("/api/admin/kick-player", async (req, res) => {
|
||||
try {
|
||||
const { playerId } = req.body;
|
||||
|
||||
if (!playerId) {
|
||||
return res.status(400).json({ success: false, message: 'Player ID is required' });
|
||||
}
|
||||
|
||||
// Get all rooms to find the player
|
||||
const rooms = await matchMaker.query({});
|
||||
let playerFound = false;
|
||||
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
try {
|
||||
// Try to kick the player from this room
|
||||
await matchMaker.remoteRoomCall(room.roomId, "_forceClientDisconnect", [playerId]);
|
||||
console.log(`🚫 Admin kicked player ${playerId} from room ${room.roomId}`);
|
||||
playerFound = true;
|
||||
break;
|
||||
} catch (error) {
|
||||
// Player not in this room, continue searching
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (playerFound) {
|
||||
res.json({ success: true, message: `Player ${playerId} kicked` });
|
||||
} else {
|
||||
res.status(404).json({ success: false, message: 'Player not found' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Kick player error:', error);
|
||||
res.status(500).json({ success: false, message: 'Failed to kick player' });
|
||||
}
|
||||
});
|
||||
|
||||
// Pause game using official matchMaker API
|
||||
app.post("/api/admin/pause-game", async (req, res) => {
|
||||
try {
|
||||
const rooms = await matchMaker.query({});
|
||||
let pausedGames = 0;
|
||||
|
||||
// Pause all active games
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
try {
|
||||
await matchMaker.remoteRoomCall(room.roomId, "pauseGame");
|
||||
pausedGames++;
|
||||
console.log(`⏸️ Admin paused game in room ${room.roomId}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to pause game in room ${room.roomId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `${pausedGames} games paused`,
|
||||
pausedGames
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Pause game error:', error);
|
||||
res.status(500).json({ success: false, message: 'Failed to pause games' });
|
||||
}
|
||||
});
|
||||
|
||||
// Resume game using official matchMaker API
|
||||
app.post("/api/admin/resume-game", async (req, res) => {
|
||||
try {
|
||||
const rooms = await matchMaker.query({});
|
||||
let resumedGames = 0;
|
||||
|
||||
// Resume all paused games
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
try {
|
||||
await matchMaker.remoteRoomCall(room.roomId, "resumeGame");
|
||||
resumedGames++;
|
||||
console.log(`▶️ Admin resumed game in room ${room.roomId}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to resume game in room ${room.roomId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `${resumedGames} games resumed`,
|
||||
resumedGames
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Resume game error:', error);
|
||||
res.status(500).json({ success: false, message: 'Failed to resume games' });
|
||||
}
|
||||
});
|
||||
|
||||
// Cancel game using official matchMaker API
|
||||
app.post("/api/admin/cancel-game", async (req, res) => {
|
||||
try {
|
||||
const { gameId } = req.body;
|
||||
|
||||
if (gameId) {
|
||||
// Cancel specific game
|
||||
try {
|
||||
await matchMaker.remoteRoomCall(gameId, "disconnect");
|
||||
console.log(`❌ Admin cancelled game ${gameId}`);
|
||||
res.json({ success: true, message: `Game ${gameId} cancelled` });
|
||||
} catch (error) {
|
||||
console.error(`Failed to cancel game ${gameId}:`, error);
|
||||
res.status(404).json({ success: false, message: 'Game not found' });
|
||||
}
|
||||
} else {
|
||||
// Cancel all games
|
||||
const rooms = await matchMaker.query({});
|
||||
let cancelledGames = 0;
|
||||
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
try {
|
||||
await matchMaker.remoteRoomCall(room.roomId, "disconnect");
|
||||
cancelledGames++;
|
||||
console.log(`❌ Admin cancelled game ${room.roomId}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to cancel game ${room.roomId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `${cancelledGames} games cancelled`,
|
||||
cancelledGames
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Cancel game error:', error);
|
||||
res.status(500).json({ success: false, message: 'Failed to cancel games' });
|
||||
}
|
||||
});
|
||||
|
||||
// Kick all players - empty all rooms
|
||||
app.post("/api/admin/kick-all-players", async (req, res) => {
|
||||
try {
|
||||
const rooms = await matchMaker.query({});
|
||||
let kickedPlayers = 0;
|
||||
let roomsCleared = 0;
|
||||
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
try {
|
||||
// Get room data to get player information
|
||||
const roomData = await matchMaker.remoteRoomCall(room.roomId, "getInspectData");
|
||||
const playerCount = roomData.clients?.length || 0;
|
||||
|
||||
if (playerCount > 0) {
|
||||
// Kick each player individually to send proper notifications
|
||||
await matchMaker.remoteRoomCall(room.roomId, "_forceDisconnectAllClients");
|
||||
kickedPlayers += playerCount;
|
||||
roomsCleared++;
|
||||
console.log(`🚫🚫 Admin cleared room ${room.roomId} - ${playerCount} players kicked`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to clear room ${room.roomId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `${kickedPlayers} jugadores expulsados de ${roomsCleared} salas`,
|
||||
kickedPlayers,
|
||||
roomsCleared
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Kick all players error:', error);
|
||||
res.status(500).json({ success: false, message: 'Failed to kick all players' });
|
||||
}
|
||||
});
|
||||
|
||||
// Advance round globally - all active games
|
||||
app.post("/api/admin/advance-round", async (req, res) => {
|
||||
try {
|
||||
const rooms = await matchMaker.query({});
|
||||
let roundsAdvanced = 0;
|
||||
let newRound = 1;
|
||||
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
try {
|
||||
const result = await matchMaker.remoteRoomCall(room.roomId, "advanceRound");
|
||||
if (result && result.success) {
|
||||
roundsAdvanced++;
|
||||
newRound = result.newRound;
|
||||
console.log(`⏭️ Admin advanced round in ${room.roomId} to round ${newRound}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to advance round in room ${room.roomId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `Ronda avanzada a ${newRound} en ${roundsAdvanced} salas`,
|
||||
roundsAdvanced,
|
||||
newRound
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Advance round error:', error);
|
||||
res.status(500).json({ success: false, message: 'Failed to advance round' });
|
||||
}
|
||||
});
|
||||
|
||||
// Go back round globally - all active games
|
||||
app.post("/api/admin/previous-round", async (req, res) => {
|
||||
try {
|
||||
const rooms = await matchMaker.query({});
|
||||
let roundsChanged = 0;
|
||||
let newRound = 1;
|
||||
|
||||
for (const room of rooms) {
|
||||
if (room.name === 'game') {
|
||||
try {
|
||||
const result = await matchMaker.remoteRoomCall(room.roomId, "previousRound");
|
||||
if (result && result.success) {
|
||||
roundsChanged++;
|
||||
newRound = result.newRound;
|
||||
console.log(`⏮️ Admin went back round in ${room.roomId} to round ${newRound}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to go back round in room ${room.roomId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `Ronda retrocedida a ${newRound} en ${roundsChanged} salas`,
|
||||
roundsChanged,
|
||||
newRound
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Previous round error:', error);
|
||||
res.status(500).json({ success: false, message: 'Failed to go back round' });
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -268,4 +268,148 @@ export class GameRoom extends Room<GameState> {
|
||||
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',
|
||||
clients: 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 };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user