MultiplayerMinesweeper/scripts/roomManager.mjs

65 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-06-22 01:51:09 +00:00
import {Game} from "./game.mjs"
import * as log from "./log.mjs"
import {IllegalAction} from "./server/illegalAction.mjs"
class RoomManager {
constructor(){
this.games = [];
}
getGameByName(name, create) {
const game = this.games.filter(obj => obj.name == name)[0]
if (game === undefined && create) {
this.addGame(name);
// Oh no.... This cant be good code.
// Coming back to it two months later. Horrible, but I don't know how to fix it. Maybe I'll leave it as an ancient artifact.
return this.getGameByName(name);
}
return game
}
addGame(name, settings) {
const game = new Game(name, settings);
this.games.push(game);
return game
}
removeGame(name) {
this.games = this.games.filter(obj => obj.name != name);
log.log("removed game - " + name)
// Broken?
}
getAllIDs() {
let ids = []
for (let i = 0; i < this.games.length; i++) {
for (let j = 0; j < this.games[i].players.length; j++) {
ids.push(this.games[i].players[j].id)
}
}
return ids
}
joinClientToGame(room, nick, id, client) {
if (this.getAllIDs().includes(id)) {
return new IllegalAction(id, 22)
}
if (nick.length > 9) {
return new IllegalAction(id, 21)
}
const game = this.getGameByName(room, true);
const player = game.addPlayer(id, nick);
if (player === false) {
this.removeGame(game)
return new IllegalAction(id, 20)
}
client.join(game.name)
client.game = game;
client.player = player
return true
}
}
export var roomManager = new RoomManager();