Created
January 21, 2017 04:57
-
-
Save madigan/3788793273208d61bf33c36e668eb4b9 to your computer and use it in GitHub Desktop.
JavaScript used to simulate a die roll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Expects input in the standard format- 1d6+2 or 1d12-1 or 4d4 | |
*/ | |
function roll(dieCode) { | |
var total = 0; | |
var results = dieCode.match(/([0-9]+)d([0-9]+)([\-\+][0-9]+)?/); | |
if(results !== null) { | |
for(var i = 0; i < parseInt(results[1]); i++) { | |
total += Math.floor(Math.random() * parseInt(results[2])) + 1; | |
} | |
if(parseInt(results[3])) { | |
total += parseInt(results[3]); | |
} | |
} | |
return total; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment