Skip to content

Instantly share code, notes, and snippets.

@taylorlapeyre
Created December 17, 2018 04:16
Show Gist options
  • Save taylorlapeyre/e460065ae869922701b45961c1ef9740 to your computer and use it in GitHub Desktop.
Save taylorlapeyre/e460065ae869922701b45961c1ef9740 to your computer and use it in GitHub Desktop.
roll initiative!
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function roll20() {
return getRandomInt(1, 20);
}
function getOtherPlayersWithSameRoll(rolls, player) {
return Object.keys(rolls).filter(
otherPlayer => otherPlayer !== player && rolls[otherPlayer] === rolls[player]
)
}
function resolveDuplicateRolls(rolls) {
for (const player in rolls) {
const roll = rolls[player];
const otherPlayersWithTheSameRoll = getOtherPlayersWithSameRoll(rolls, player);
if (otherPlayersWithTheSameRoll.length > 0) {
for (const otherPlayer of [player, ...otherPlayersWithTheSameRoll]) {
rolls[otherPlayer] = roll20();
}
}
}
const rollValues = Object.values(rolls);
const duplicatesStillExist = new Set(rollValues).size !== rollValues.length;
if (duplicatesStillExist) {
return resolveDuplicateRolls(rolls);
} else {
return rolls;
}
}
function rollInitiative() {
const rolls = resolveDuplicateRolls({
spoone: roll20(),
casus: roll20(),
phenelope: roll20(),
ger: roll20(),
emrick: roll20()
});
const rankedPlayers = Object.keys(rolls).sort(
(playerA, playerB) => rolls[playerA] < rolls[playerB] ? 1 : -1
)
rankedPlayers.forEach((player, index) => {
console.log(`${index + 1}: ${player}`)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment