Created
March 29, 2012 18:06
-
-
Save quickredfox/2241194 to your computer and use it in GitHub Desktop.
A seriously (if I may say so) kick-ass implementation of a dice notation reader in coffeescript.
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
## | |
A seriously (if I may say so) kick-ass implementation of a dice notation reader in coffeescript. | |
Careful, it evals code, keep your strings clean before feeding them to this baby! (and adds a "d" method to Number) | |
## | |
Number::d = ( v )-> | |
[1..@].reduce ( a )-> | |
a + ( Math.floor( Math.random()*v ) + 1 ) | |
, 0 | |
Dice = ( dice )-> | |
unless @ instanceof Dice then return new Dice(dice) | |
@src = dice.replace( /x/gi, '*' ) | |
.replace( /d(\%|00)(\D|$)/g, "d100$2" ) | |
.replace( /d(\d+)/g, "d($1)" ) | |
.replace( /(\d+|\))d/g, "($1).d" ) | |
.replace( /\d+/g, ( n )-> n.replace /^0+/g, '' ) | |
.replace( /\(\)/g, '' ) | |
# console.log @src | |
@dice = new Function( 'd','n', "return function(){ return #{@src};}") | |
.apply null, [ | |
( v )-> (1).d( v ) | |
] | |
@roll = ( repeats )-> | |
repeats||=1 | |
value = 0 | |
while repeats > 0 | |
value += @dice() | |
repeats-- | |
value | |
return @ | |
module.exports = Dice | |
# example: | |
# console.log Dice('1d6+3').roll() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment