shoehive
Version:
WebSocket-based multiplayer game framework for real-time, event-driven gameplay
108 lines (107 loc) • 3.31 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GameManager = void 0;
const EventTypes_1 = require("../events/EventTypes");
class GameManager {
constructor(eventBus, tableFactory) {
this.games = new Map();
this.tables = new Map();
this.tablesByGame = new Map();
this.eventBus = eventBus;
this.tableFactory = tableFactory;
this.setupEventListeners();
}
/**
* Sets up event listeners for the game manager.
* This listens for table creation and table emptying.
*/
setupEventListeners() {
this.eventBus.on(EventTypes_1.TABLE_EVENTS.CREATED, (table) => {
this.tables.set(table.id, table);
const gameId = table.getAttribute("gameId");
if (gameId) {
if (!this.tablesByGame.has(gameId)) {
this.tablesByGame.set(gameId, new Set());
}
this.tablesByGame.get(gameId)?.add(table.id);
}
});
this.eventBus.on(EventTypes_1.TABLE_EVENTS.EMPTY, (table) => {
this.removeTable(table.id);
});
}
/**
* Registers a game definition.
*
* @param gameDefinition The game definition to register.
*/
registerGame(gameDefinition) {
this.games.set(gameDefinition.id, gameDefinition);
this.tablesByGame.set(gameDefinition.id, new Set());
}
/**
* Unregisters a game definition.
*
* @param gameId The ID of the game to unregister.
*/
unregisterGame(gameId) {
this.games.delete(gameId);
// Remove all tables for this game
const tablesToRemove = this.tablesByGame.get(gameId) || new Set();
tablesToRemove.forEach(tableId => this.removeTable(tableId));
this.tablesByGame.delete(gameId);
}
/**
* Removes a table from the game manager.
*
* @param tableId The ID of the table to remove.
*/
removeTable(tableId) {
const table = this.tables.get(tableId);
if (!table)
return;
const gameId = table.getAttribute("gameId");
if (gameId) {
this.tablesByGame.get(gameId)?.delete(tableId);
}
this.tables.delete(tableId);
}
/**
* Gets all available games.
*
* @returns An array of all game definitions.
*/
getAvailableGames() {
return Array.from(this.games.values());
}
/**
* Gets a game definition by its ID.
*
* @param gameId The ID of the game
* @returns The game definition, or undefined if not found
*/
getGameDefinition(gameId) {
return this.games.get(gameId);
}
/**
* Gets all tables for a game.
*
* @param gameId The ID of the game.
* @returns An array of tables for the game.
*/
getTablesForGame(gameId) {
const tableIds = this.tablesByGame.get(gameId) || new Set();
return Array.from(tableIds)
.map(id => this.tables.get(id))
.filter(table => table !== undefined);
}
/**
* Gets all tables in the game manager.
*
* @returns An array of all tables.
*/
getAllTables() {
return Array.from(this.tables.values());
}
}
exports.GameManager = GameManager;