nodito
Version:
Una librería para aprender juegos por turnos en node.
72 lines • 2.59 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("underscore");
const utils_1 = require("./utils");
class Game {
constructor(users, rooms, factory, secretToken, options = {
checkPlayerOnlineInterval: 1000 * 5,
cleanInterval: 5000 * 5,
roomsInterval: 1000 * 15,
turnMaxTime: 1000 * 30,
usersInterval: 1000 * 15,
}) {
this.users = users;
this.rooms = rooms;
this.factory = factory;
this.secretToken = secretToken;
this.options = options;
this.throttledSendRooms = _.throttle(() => {
const rooms = this.rooms.toClient();
this.users.sendToAll({ type: "rooms", rooms });
}, 1000);
this.throttledSendPlayers = _.throttle(() => {
const players = this.users.toClient();
this.users.sendToAll({ type: "players", players });
}, 1000);
this.roomsMessageInterval = null;
this.playersMessageInterval = null;
this.checkPlayerOnlineInterval = null;
this.factory.install(this);
this.roomsMessageInterval = setInterval(this.throttledSendRooms, this.options.roomsInterval);
this.playersMessageInterval = setInterval(this.throttledSendPlayers, this.options.usersInterval);
this.checkPlayerOnlineInterval =
setInterval(this.checkPlayersTime.bind(this), this.options.checkPlayerOnlineInterval);
}
findOrCreate(id) {
let player = this.users.find(id);
if (!player) {
player = this.users.makeUser(id, this.signToken(id));
this.users.add(player);
}
return player;
}
infoOf(player) {
const room = this.rooms.findByPlayer(player);
const playing = (room && room.isPlaying());
return Object.assign({}, player.toClient(), { isPlaying: playing });
}
signToken(id) {
return utils_1.sign(this.secretToken, id);
}
exec(message) {
return this.factory.exec(message);
}
checkPlayersTime() {
const players = this.users.getUsersForRemove();
players.forEach((p) => {
this.users.remove(p);
const r = this.rooms.findByPlayer(p);
if (r) {
r.remove(p);
if (r.empty()) {
this.rooms.remove(r);
}
}
});
if (players.length) {
console.log("Removed users by expired time: " + players.length);
}
}
}
exports.Game = Game;
//# sourceMappingURL=Game.js.map