Last active
August 29, 2015 13:58
-
-
Save eugenioclrc/9993305 to your computer and use it in GitHub Desktop.
A simple dice generator for dungeons and dragons
This file contains hidden or 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
/** | |
* @returns { | |
* diceRoll:[int number that dices roll], | |
* number: int(sum of dices), | |
* bonus: int, | |
* total: number+bonus | |
* } | |
*/ | |
function diceRoll(data){ | |
// data val sample '1d8+12' | |
// data val sample '4d8-10' | |
// data val sample 'd8+2' | |
data=' '+data; | |
var dataSplit=data.split(/-|\+|d/g); | |
var dices=parseInt(dataSplit[0],10); | |
if(!dices){ | |
dices=1; | |
} | |
var sides=parseInt(dataSplit[1],10); | |
var ret={ diceRoll:[], number:0, bonus:0 }; | |
ret.number=0; | |
var n; | |
for(var i=0;i<dices;i++){ | |
n=1+Math.floor(Math.random() * sides); | |
ret.diceRoll.push(n); | |
ret.number+=n; | |
} | |
if(dataSplit[2]){ | |
ret.bonus=parseInt(dataSplit[2],10); | |
if(data.indexOf('-')>-1){ | |
ret.bonus=ret.bonus*-1; | |
} | |
} | |
ret.total=ret.number+ret.bonus; | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment