Skip to content

Instantly share code, notes, and snippets.

@cmgdragon
Last active July 29, 2022 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmgdragon/44ed01c9934e2cff4539e893ac1dae35 to your computer and use it in GitHub Desktop.
Save cmgdragon/44ed01c9934e2cff4539e893ac1dae35 to your computer and use it in GitHub Desktop.
A function for starting a game based in turns and rounds. You can select the initial player and the starting round. Made for practicing remainders
startTurnBasedGame(5, 3, 4);
function startTurnBasedGame(num_players, num_rounds, turn_time, init_player=1, init_round=1) {
let [elapsed_time, player_turn, round, actual_player] = [0, 0, init_round, init_player-1];
const getPlayer = () => actual_player === num_players ? num_players : actual_player % num_players;
const printTimeInfo = remaining_time => console.log(
`Next turn in: ${remaining_time}s`, `Player: ${getPlayer()}`, `Round: ${round}/${num_rounds}`
);
const interval = setInterval(roundsInterval, 1000);
function roundsInterval() {
const remainder = turn_time - (elapsed_time % turn_time);
if (remainder === turn_time) {
if (player_turn++ === num_players) {
player_turn = 1;
if (round++ === num_rounds) {
console.log("------- Game finished! -------");
return clearInterval(interval);
}
}
actual_player = getPlayer() === num_players ? 1 : actual_player + 1;
elapsed_time = 1;
console.log(`------- Round ${round} - Player ${actual_player} -------`)
printTimeInfo(turn_time);
} else {
elapsed_time++;
printTimeInfo(remainder);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment