Skip to content

Instantly share code, notes, and snippets.

@denchistyakov
Created August 1, 2018 17:25
Show Gist options
  • Save denchistyakov/f16933249896a15a87c34ce2fad2ffdf to your computer and use it in GitHub Desktop.
Save denchistyakov/f16933249896a15a87c34ce2fad2ffdf to your computer and use it in GitHub Desktop.
class SnakesLadders {
constructor() {
this.board = [
0,
0, 36, 0, 0, 0, 0, 7, 23, 0, 0,
0, 0, 0, 0, 11, -10, 0, 0, 0, 0,
21, 0, 0, 0, 0, 0, 0, 56, 0, 0,
0, 0, 0, 0, 0, 8, 0, 0, 0, 0,
0, 0, 0, 0, 0, -21, 0, 0, -38, 0,
16, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -43, 0, -4, 0, 0, 0, 0, 0, 0,
20, 0, 0, -21, 0, 0, 0, 20, 0, 0,
0, 0, 0, 0, 0, 0, 7, 0, -21, 0,
0, -4, 0, 0, -20, 0, 0, 0, -19, 0
];
this.cellByPlayer = {
1: 0,
2: 0
};
this.player = 1;
this.winner = 0;
}
get cell() {
return this.cellByPlayer[this.player];
}
set cell(val) {
this.cellByPlayer[this.player] = val;
}
switchPlayer() {
this.player = (this.player === 1) ? 2 : 1;
}
play(die1, die2) {
let result;
// Возвращаем окончание игры, если победитель уже есть
if (this.winner !== 0 && this.winner !== this.player) {
return 'Game over!';
}
this.cell += (die1 + die2);
if (this.cell === 100) {
this.winner = this.player;
result = `Player ${this.player} Wins!`;
this.switchPlayer();
return result;
} else if (this.cell > 100) {
this.cell -= (this.cell - 100) * 2;
}
// Поднимаемся по лестнице или скатываемся вниз по змее
if (this.board[this.cell] !== 0) {
this.cell += this.board[this.cell];
}
result = `Player ${this.player} is on square ${this.cell}`;
// Сменяем текущего игрока
// Если выпал повтор, то даем дополнительный ход
if (die1 !== die2) {
this.switchPlayer();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment