]> gitweb.factorcode.org Git - factor.git/commitdiff
dice: little bit faster this way.
authorJohn Benediktsson <mrjbq7@gmail.com>
Wed, 15 Jul 2015 03:35:10 +0000 (20:35 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Wed, 15 Jul 2015 03:35:10 +0000 (20:35 -0700)
extra/dice/dice-tests.factor
extra/dice/dice.factor

index d86df95d203c95e311460f1a1970baf576c55187..58a1a957feabb2c58ef5a66d133cd8e3eca65266 100644 (file)
@@ -1,5 +1,6 @@
-USING: math random tools.test ;
+USING: kernel math tools.test ;
 IN: dice
 
-{ [ 0 1 [ 4 random + 1 + ] times ] } [ "1d4" parse-roll ] unit-test
-{ [ 0 15 [ 45 random + 1 + ] times ] } [ "15d45" parse-roll ] unit-test
+{ [ 1 4 random-roll ] } [ "1d4" roll-quot ] unit-test
+{ [ 1 4 random-roll 3 + ] } [ "1d4+3" roll-quot ] unit-test
+{ [ 15 45 random-roll ] } [ "15d45" roll-quot ] unit-test
index fc1793690a73a1f8a57d663eda056f8809e7b172..31b3e4165ed5da2ec034c46aad80c499a78c0e4f 100644 (file)
@@ -1,21 +1,29 @@
 ! Copyright (C) 2010 John Benediktsson
 ! See http://factorcode.org/license.txt for BSD license
-USING: fry kernel lexer macros math math.parser peg.ebnf random
-sequences ;
+USING: fry kernel lexer macros math math.parser namespaces
+random random.private sequences splitting ;
 IN: dice
 
-EBNF: parse-roll
+: (random-roll) ( #dice #sides obj -- n )
+    [ 0 ] 3dip '[ _ _ (random-integer) + 1 + ] times ;
 
-number = ([0-9])+    => [[ string>number ]]
-dice   = "d" number  => [[ second '[ _ random ] ]]
-roll   = number dice => [[ first2 '[ 0 _ [ @ + 1 + ] times ] ]]
-added  = "+" number  => [[ second '[ _ + ] ]]
-total  = roll added? => [[ first2 [ append ] when* ]]
-error  = .*          => [[ "unknown dice" throw ]]
-rolls  = total | error
+: random-roll ( #dice #sides -- n )
+    random-generator get (random-roll) ;
 
-;EBNF
+: random-rolls ( length #dice #sides -- seq )
+    random-generator get '[ _ _ _ (random-roll) ] replicate ;
 
-MACRO: roll ( string -- ) parse-roll ;
+: parse-roll ( string -- #dice #sides #added )
+    "d" split1 "+" split1 [ string>number ] tri@ ;
 
-SYNTAX: ROLL: scan-token parse-roll append! ;
+: roll ( string -- n )
+    parse-roll [ random-roll ] dip [ + ] when* ;
+
+: roll-quot ( string -- quot: ( -- n ) )
+    parse-roll [
+        '[ _ _ random-roll _ + ]
+    ] [
+        '[ _ _ random-roll ]
+    ] if* ;
+
+SYNTAX: ROLL: scan-token roll-quot append! ;