MultiplayerMinesweeper/scripts/roomManager.mjs

81 lines
1.9 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 * as util from "./util.mjs"
2022-06-22 01:51:09 +00:00
import {IllegalAction} from "./server/illegalAction.mjs"
class RoomManager {
constructor(){
this.games = [];
}
getGameByID(id) {
const game = this.games.filter(obj => obj.id == id)[0]
if (game === undefined) {
return false
2022-06-22 01:51:09 +00:00
}
return game
}
addGame(id, options) {
const game = new Game(id, options);
2022-06-22 01:51:09 +00:00
this.games.push(game);
return game
}
removeGameByID(id) {
this.games = this.games.filter(obj => obj.id != id);
log.log("removed game - " + id)
2022-06-22 01:51:09 +00:00
}
getAllPlayerIDs() {
2022-06-22 01:51:09 +00:00
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
}
getAllGameIDs() {
let ids = []
for (let i = 0; i < this.games.length; i++) {
ids.push(this.games[i].id)
}
return ids
}
playerJoinGame(roomCode, playerName, playerID) {
// See if the client is already in a game
console.log(roomCode, playerName)
if (this.getAllPlayerIDs().includes(playerID)) {
2022-06-22 01:51:09 +00:00
return new IllegalAction(id, 22)
}
if (!this.getAllGameIDs().includes(roomCode)) {
return new IllegalAction(id, 30)
2022-06-22 01:51:09 +00:00
}
const game = this.getGameByID(roomCode);
const player = game.addPlayer(playerID, playerName);
// See if player name is taken already
2022-06-22 01:51:09 +00:00
if (player === false) {
this.removeGame(game)
return new IllegalAction(id, 20)
}
return [game, player]
2022-06-22 01:51:09 +00:00
}
playerCreateGame(options, playerName, playerID) {
if (this.getAllPlayerIDs().includes(playerID)) {
return new IllegalAction(id, 22)
}
console.log(options)
const id = util.createCode()
const game = this.addGame(id, options)
const player = game.addPlayer(playerID, playerName);
return [game, player]
}
2022-06-22 01:51:09 +00:00
}
export var roomManager = new RoomManager();