Projektmanagement-Game/Webservice/Game.js

106 lines
2.9 KiB
JavaScript
Raw Normal View History

const Player = require('./Player');
2021-06-17 06:45:45 +00:00
const Hunter = require("./Hunter");
class Game {
static MAX_PLAYERS = 4;
2021-06-18 11:06:41 +00:00
static WIN_POSITION = 16;
static STATUS = {
SETTING_UP: 0,
ONGOING: 1,
IS_DRAW: 2,
IS_WON: 3
}
2021-06-17 06:45:45 +00:00
constructor() {
this.currentStatus = Game.STATUS.SETTING_UP;
2021-06-17 06:45:45 +00:00
this.players = [];
this.currentPlayerIndex = 0;
this.winnerIndex = 0;
2021-06-17 06:45:45 +00:00
this.round = 0;
this.hunter = new Hunter();
2021-07-01 16:39:23 +00:00
this.playerNames = [];
2021-06-17 06:45:45 +00:00
}
finish_turn() {
this.update_game_status();
2021-06-18 06:55:55 +00:00
if (this.currentStatus !== Game.STATUS.ONGOING) return;
if (!this.players.some(player => player.isAlive === true)) return;
let roundIsOver = false;
do {
this.currentPlayerIndex++;
if (this.currentPlayerIndex >= this.players.length) {
this.currentPlayerIndex = 0;
roundIsOver = true;
2021-06-17 06:45:45 +00:00
}
} while (!this.players[this.currentPlayerIndex].isAlive); // skip dead players
if (roundIsOver) this.#finish_round();
}
#finish_round() {
this.round++;
2021-06-17 06:45:45 +00:00
if (this.round >= 5) {
this.hunter.move_by(1);
2021-06-17 06:45:45 +00:00
this.hunter.hunt(this.players);
}
this.update_game_status();
2021-06-17 06:45:45 +00:00
}
add_player(name) {
let canAddPlayer = this.players.length < Game.MAX_PLAYERS;
if (canAddPlayer) this.players.push(new Player(name));
return canAddPlayer;
}
remove_player(name) {
let index = this.get_player_index(name);
if (index !== -1) {
this.players.splice(index, 1);
if (this.currentPlayerIndex >= index) this.currentPlayerIndex--;
}
if (this.currentPlayerIndex === index) this.finish_turn(); // if current player leaves: move on to next
}
current_player_is(name) {
if (this.players[this.currentPlayerIndex] === undefined) return false;
return this.players[this.currentPlayerIndex].name === name;
}
get_player_index(name) {
return this.players.findIndex(player => player.name === name);
}
move_player(name, amount) {
let index = this.get_player_index(name);
if (index === -1) return;
this.players[index].move_by(amount);
this.update_game_status();
}
update_game_status() {
if (!this.players.some(player => player.isAlive === true)) this.currentStatus = Game.STATUS.IS_DRAW;
2021-06-18 11:06:41 +00:00
let index = this.players.findIndex(player => player.position >= Game.WIN_POSITION);
if (index !== -1) {
this.currentStatus = Game.STATUS.IS_WON;
this.winnerIndex = index;
}
}
2021-07-01 16:39:23 +00:00
getPlayerNames(){
return this.playerNames;
}
addPlayerName(playerName){
this.playerNames.push(playerName);
}
removePlayerName(playerName){
this.playerNames.splice(this.playerNames.indexOf(playerName), 1)
}
2021-06-17 06:45:45 +00:00
}
module.exports = Game;