2023-03-04 00:25:54 +00:00
|
|
|
import { Player } from "./player.js";
|
2023-03-03 17:34:15 +00:00
|
|
|
|
|
|
|
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);
|
2023-03-03 17:34:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
currentPlayer() {
|
|
|
|
return Object.values(this.players).filter((p) => p.isPlaying)[0];
|
|
|
|
}
|
|
|
|
|
2023-03-04 00:25:54 +00:00
|
|
|
addPlayer(id, is_us) {
|
2023-03-03 17:34:15 +00:00
|
|
|
let is_new = this.players[id] === undefined;
|
|
|
|
|
|
|
|
if (this.isWaiting()) {
|
2023-03-04 00:25:54 +00:00
|
|
|
this.players[id] = new Player(id, is_us);
|
|
|
|
if (is_us) {
|
2023-03-03 17:34:15 +00:00
|
|
|
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);
|
2023-03-03 17:34:15 +00:00
|
|
|
|
|
|
|
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) {
|
2023-03-03 17:34:15 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|