nodito
Version:
Una librería para aprender juegos por turnos en node.
105 lines • 2.84 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Player {
constructor() {
this._user = null;
this.room = null;
this.inTurn = false;
this.takenTurnTime = null;
this.asked = [];
this._removeTimer = null;
}
get user() {
return this._user;
}
set user(value) {
this._user = value;
}
playGame(msg) {
throw new Error("Implement play game.");
}
cleanAsked() {
this.asked = [];
this.inTurn = false;
this.cleanTurnTimer();
}
takeTurn(questions) {
this.inTurn = true;
this.takenTurnTime = new Date();
this.setupRemove();
this.asked = questions;
this.room.sendStatusToAll();
}
reconnection() {
this.room.sendStatusToAll();
}
getTurn() {
return {
seconds: this.calcSeconds(),
turn: this.isInTurn(),
};
}
setRoom(room) {
this.room = room;
}
setInTurn(b) {
this.inTurn = b;
}
isValidPlayGame(message) {
return this.asked.find((x) => JSON.stringify(x) === JSON.stringify(message.answer));
}
restOfPlayers() {
if (!this.room) {
return [];
}
return this.room.getGamePlayers()
.filter((x) => x !== this);
}
opponent() {
return this.restOfPlayers()[0];
}
sendStatus() {
throw new Error("Implement sendStatus");
}
isInTurn() {
return this.inTurn;
}
isPlaying() {
return this.room && this.room.isPlaying();
}
send(msg) {
if (this.user) {
this.user.send(msg);
}
}
calcSeconds() {
const now = new Date();
const takenTurn = this.takenTurnTime ? this.takenTurnTime : new Date();
const turnMaxTime = this.room.game.options.turnMaxTime;
const ret = Math.max(0, turnMaxTime - (now.getTime() - takenTurn.getTime()));
return Math.floor(ret / 1000);
}
setupRemove() {
this.cleanTurnTimer();
this._removeTimer = setTimeout(() => {
if (this.isInTurn() && this.calcSeconds() === 0) {
this.send({ type: "abandonGame", you: true });
let who = {};
if (this.user) {
who = this.user.toClient();
}
this.restOfPlayers().forEach((x) => x.send({ type: "abandonGame", who, you: false }));
if (this.room) {
this.room.finish();
}
}
}, this.calcSeconds() * 1000);
}
cleanTurnTimer() {
if (this._removeTimer) {
clearTimeout(this._removeTimer);
}
}
}
exports.Player = Player;
//# sourceMappingURL=Player.js.map