Browse Source

Integrate the 'd', 'Ad', and 'dX' short notations

olinox 8 years ago
parent
commit
1d34b28551
4 changed files with 16 additions and 10 deletions
  1. 1 0
      .gitignore
  2. 1 1
      README.md
  3. 3 3
      test.py
  4. 11 6
      xdice.py

+ 1 - 0
.gitignore

@@ -2,4 +2,5 @@
 .project
 .pydevproject
 .coverage
+.settings/
 htmlcov/*

+ 1 - 1
README.md

@@ -8,7 +8,7 @@ It allows to easily interpret literal expressions as rolls of dice ('1d6', '3d4+
 
 #### Python Versions
 
-DiceRollParser has been tested with python 3.3+
+DiceRollParser has been tested with **python 3.3+**
 
 ### Documentation
 

+ 3 - 3
test.py

@@ -40,13 +40,13 @@ class Test(unittest.TestCase):
         xdice.roll("abs(1d6-1d10)")
         xdice.roll("max(1d6,2d4)")
         xdice.roll("min(1d6,2d4)")
+        xdice.roll("d")
+        xdice.roll("2d")
+        xdice.roll("d6")
 
         # test invalid expressions
-        self.assertRaises(SyntaxError, xdice.roll, "1d-8")
-        self.assertRaises(SyntaxError, xdice.roll, "1d")
         self.assertRaises(ValueError, xdice.roll, "")
         self.assertRaises(ValueError, xdice.roll, "1d0")
-        self.assertRaises(TypeError, xdice.roll, "d6")
         self.assertRaises(TypeError, xdice.roll, "abc")
         self.assertRaises(TypeError, xdice.roll, "1d2,3")
 

+ 11 - 6
xdice.py

@@ -34,6 +34,8 @@ class Dice():
 
     Use roll() to get a Score() object.
     """
+    DEFAULT_SIDES = 20
+
     def __init__(self, sides, amount=1):
         self._sides = 1
         self._amount = 0
@@ -80,12 +82,15 @@ class Dice():
     @classmethod
     def parse(cls, pattern):
         """ parse a pattern of the form 'xdx', where x are positive integers """
-        # normalize
         pattern = str(pattern).replace(" ", "").lower()
-        # parse
-        amount, faces = (int(x) for x in pattern.split("d"))
-        # instanciate
-        return Dice(faces, amount)
+
+        a, x = pattern.split("d")
+        if not a:
+            a = 1
+        if not x:
+            x = cls.DEFAULT_SIDES
+
+        return Dice(*map(int, [x, a]))
 
 class Score(int):
     """ Score is a subclass of integer.
@@ -145,7 +150,7 @@ class Pattern():
             self.dices.append(dice)
             return "{{{}}}".format(index)
 
-        self.format_string = re.sub('\d+d\d+', _submatch, self.instr)
+        self.format_string = re.sub('\d*d\d*', _submatch, self.instr)
 
     def roll(self):
         if not self.format_string: