Skip to content

Instantly share code, notes, and snippets.

@ripter
Last active August 4, 2017 18:06
Show Gist options
  • Save ripter/5130874 to your computer and use it in GitHub Desktop.
Save ripter/5130874 to your computer and use it in GitHub Desktop.
Roll D&D style dice.
// hand golfed the most common dice rolls.
function rnd(max, min) {
return 0| (Math.random() * max) + 0|min;
}
var d20 = rnd.bind(0, 20, 1);
var d8 = rnd.bind(0, 8, 1)
var d6 = rnd.bind(0, 6, 1)
var d4 = rnd.bind(0, 4, 1);
// Rolls a d20 dice string.
// Examples: 2d6, 1d20, 4d2+7, 1d10-2
function rollDice(dice) {
const regexDice = /(\d*)d(\d+)([+-]?\d*)/;
const match = regexDice.exec(dice); // parse the dice string
const max = parseInt(match[2], 10); // number of sides on the dice.
const modifier = parseInt(match[3], 10) || 0; // optional modifier post roll.
let count = parseInt(match[1], 10) || 1; // number of dice to roll.
let result = 0;
if (Number.isNaN(max)) {
throw new Error('Number of sides on dice not specified. ' + dice);
}
// Roll each dice, adding the result.
while (count--) {
result += 0 | ((Math.random() * max) + 1)
}
// add the modifier
result += modifier;
return result;
}
// This is a hand golfed version of dice.js
// When compressed it is only 138 bytes.
// dice is a string in D&D style
// example: 2d6, 1d20, 4d2+7, 1d10-2
function rollDice(dice) {
var match = /(\d*)d(\d+)([+-]?\d*)/.exec(dice);
var numberOfDice = 0|match[1] || 1;
var numberOfSides = 0|match[2];
var modifier = 0|match[3];
var result = 0;
while (numberOfDice--) {
result += 0| Math.random() * numberOfSides + 1;
}
result += modifier;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment