Skip to content

Instantly share code, notes, and snippets.

@archangel-irk
Created January 24, 2019 11:00
Show Gist options
  • Save archangel-irk/410263a03a4373cc8a9a8e006861fa95 to your computer and use it in GitHub Desktop.
Save archangel-irk/410263a03a4373cc8a9a8e006861fa95 to your computer and use it in GitHub Desktop.
/*
-----------------------
Example:
-----------------------
Round 1
Player1 hits Player2 with 5 dmg
Player2 hits Player3 with 10 dmg
Player3 has died
Player4 hits Player1 with 4 dmg
Round 2
Player1 hits Player2 with 7 dmg
Player2 has died
Player4 hits Player1 with 7 dmg
Player1 has died
Player4 is a winner
-----------------------
console.log(`Round ${round}`);
console.log(`${player1} hits ${player2} with ${dmg} dmg`);
console.log(`${player} has died`);
console.log(`${player} is a winner`);
*/
const PLAYERS_NUM = 4;
const PLAYER_LIVES = 10;
const MIN_DMG = 1;
const MAX_DMG = 10;
function getDamage() {
return Math.floor(Math.random() * (MAX_DMG - MIN_DMG + 1)) + MIN_DMG;
}
function play() {
const players = Array(PLAYERS_NUM).fill(true).map((player, i) => {
return {
index: i + 1,
lives: PLAYER_LIVES,
}
});
let round = 1;
let currentPlayerIndex = 0;
let nextPlayerIndex = 1;
while (players.length > 1) {
if (currentPlayerIndex === 0) {
console.log(`\nRound ${round}`);
round++;
}
const player = players[currentPlayerIndex];
const nextPlayer = players[nextPlayerIndex];
const dmg = getDamage();
console.log(`${player.index} hits ${nextPlayer.index} with ${dmg} dmg`);
nextPlayer.lives -= dmg;
if (nextPlayer.lives <= 0) {
console.log(`${nextPlayer.index} has died`);
players.splice(nextPlayerIndex, 1);
}
currentPlayerIndex = nextPlayerIndex;
// If nextPlayer was the last player and he died.
if (currentPlayerIndex > players.length - 1) {
currentPlayerIndex = 0;
}
nextPlayerIndex = (currentPlayerIndex + 1) % players.length;
}
console.log(`\n${players[0].index} is a winner`);
}
play();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment