UNPKG

nodito

Version:

Una librería para aprender juegos por turnos en node.

113 lines 2.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("./utils"); class Room { constructor(game, maxPlayers, playerMaker, id = utils_1.randomId()) { this.game = game; this.maxPlayers = maxPlayers; this.playerMaker = playerMaker; this.id = id; this.users = []; this.startDate = null; this.endDate = null; this.type = "room"; } getId() { return this.id; } add(u) { if (this.find(u)) { return false; } if (this.count() + 1 > this.maxPlayers) { return false; } this.users.push(u); } count() { return this.users.length; } find(u) { return this.users.find((x) => x === u); } findById(id) { return this.users.find((x) => x.getId() === id); } remove(u) { this.users = this.users.filter((x) => x !== u); } empty() { return this.users.length === 0; } isReady() { return this.users.length === this.maxPlayers; } isPlaying() { return !!this.startDate && this.endDate === null; } start() { if (!this.isReady()) { throw new Error("Bad call to start"); } this.each((x) => { x.player = new this.playerMaker(); x.setRoom(this); x.player.user = x; }); this.startDate = new Date(); this.sendAll({ type: "startGame" }); this.game.throttledSendRooms(); } finish() { this.each((x) => { if (x.player) { x.player.cleanAsked(); } x.setRoom(null); }); this.endDate = new Date(); this.game.rooms.remove(this); this.game.throttledSendRooms(); } isFinished() { return this.endDate !== null; } toClient() { return { count: this.count(), id: this.getId(), isPlaying: this.isPlaying(), owner: this.owner() ? this.owner().toClient() : null, total: this.maxPlayers, type: this.getType(), }; } each(fn) { this.users.forEach(fn); } getPlayers() { return this.users; } getGamePlayers() { return this.getPlayers() .map((x) => x.player) .filter(utils_1.notEmpty); } sendStatusToAll() { this.each((x) => x.sendStatus()); } filterPlayer(fn) { return this.users.filter(fn); } owner() { return this.users[0]; } sendAll(msg) { this.users.forEach((x) => x.send(msg)); } getType() { return this.type; } } exports.Room = Room; //# sourceMappingURL=Room.js.map