Riskless/static/js/modules/interface/game.js

91 lines
1.9 KiB
JavaScript
Raw Normal View History

2023-03-04 00:25:54 +00:00
import { Player } from "./player.js";
const WAITING = 0;
const PRE_GAME = 1;
const PLAYING = 2;
export class Game {
constructor() {
this.us = null;
this.players = {};
this.state = WAITING;
}
isWaiting() {
return this.state === WAITING;
}
isPregame() {
return this.state === PRE_GAME;
}
isPlaying() {
return this.state === PLAYING;
}
incrementState() {
this.state += 1;
2023-03-04 00:25:54 +00:00
const event = new CustomEvent("gameStateUpdate", {
detail: { newState: this.state },
});
document.dispatchEvent(event);
}
currentPlayer() {
return Object.values(this.players).filter((p) => p.isPlaying)[0];
}
2023-03-04 14:19:26 +00:00
addPlayer(id, is_us, pubkey) {
let is_new = this.players[id] === undefined;
if (this.isWaiting()) {
2023-03-04 14:19:26 +00:00
this.players[id] = new Player(id, is_us, pubkey);
2023-03-04 00:25:54 +00:00
if (is_us) {
this.us = this.players[id];
}
}
if (is_new) {
const event = new CustomEvent("addPlayer");
document.dispatchEvent(event);
}
return is_new;
}
removePlayer(id) {
if (this.players[id] !== undefined) {
const event = new CustomEvent("removePlayer");
document.dispatchEvent(event);
delete this.players[id];
}
}
keepAlive(id) {
if (id !== this.us.id) {
this.players[id].resetTimeout(this);
}
}
setReady(id, ready) {
2023-03-04 00:25:54 +00:00
this.players[id].ready = ready;
const event = new CustomEvent("updatePlayer");
document.dispatchEvent(event);
if (this._allPlayersReady()) {
this.incrementState();
}
}
_allPlayersReady() {
for (let player of Object.values(this.players)) {
2023-03-04 00:25:54 +00:00
if (!player.ready) {
return false;
}
}
return true;
}
}