87 lines
1.8 KiB
JavaScript
87 lines
1.8 KiB
JavaScript
class Player {
|
|
constructor(id, name) {
|
|
this.name = name;
|
|
this.timeout = null;
|
|
this.id = id;
|
|
this.ready = false;
|
|
this.isPlaying = false;
|
|
|
|
let randomColor = Math.random() * 360;
|
|
this.color = `hsl(${randomColor} 57% 50%)`;
|
|
}
|
|
|
|
resetTimeout() {
|
|
if (this.timeout !== null) {
|
|
window.clearTimeout(this.timeout);
|
|
}
|
|
|
|
this.timeout = window.setTimeout(() => {
|
|
if (players[this.id] !== undefined) {
|
|
delete players[this.id];
|
|
}
|
|
updateDom();
|
|
}, TIMEOUT);
|
|
}
|
|
|
|
/**
|
|
* Get our color as used on the board.
|
|
*/
|
|
getColor() {
|
|
return this.color;
|
|
}
|
|
|
|
/**
|
|
* Claim a region of the map.
|
|
*
|
|
* @param data Data received via socket.
|
|
*/
|
|
claim(data) {
|
|
let region = Region.getRegion(data.region);
|
|
|
|
if (region.owner === null) {
|
|
region.claim(this);
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Reinforce a region of the map.
|
|
*
|
|
* @param data Data received via socket.
|
|
*/
|
|
reinforce(data) {
|
|
let region = Region.getRegion(data.region);
|
|
|
|
if (region.owner === this) {
|
|
region.reinforce(1);
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Start a player's turn.
|
|
*/
|
|
startTurn() {
|
|
this.isPlaying = true;
|
|
}
|
|
|
|
/**
|
|
* End player's turn
|
|
*/
|
|
endTurn() {
|
|
this.isPlaying = false;
|
|
this.nextPlayer().startTurn();
|
|
}
|
|
|
|
nextPlayer() {
|
|
let sorted = Object.values(players).sort((a, b) => (a.id < b.id ? -1 : 1));
|
|
let ourIndex = sorted.findIndex((player) => player.id === this.id);
|
|
|
|
return sorted[(ourIndex + 1) % sorted.length];
|
|
}
|
|
}
|