xdice.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. '''
  2. xdice is a lightweight python 3.3+ library for managing rolls of dice.
  3. License: GNU
  4. @author: Olivier Massot <croki.contact@gmail.com>, 2017
  5. '''
  6. import random
  7. import re
  8. __VERSION__ = 1.0
  9. # TODO: 'L', 'LX', 'H' and 'HX' notations: drop the x lowest or highest results => eg: 'AdXl3'
  10. # TODO: (?) 'Rx(...)' notation: roll x times the pattern in the parenthesis => eg: R3(1d4+3)
  11. # TODO: 'd%' notation: d% <=> d100
  12. # TODO: (?) Dice pools, 6-sided variations, 10-sided variations,
  13. # Open-ended variations (https://en.wikipedia.org/wiki/Dice_notation)
  14. def compile(pattern_string): # @ReservedAssignment
  15. """
  16. > Similar to xdice.Pattern(pattern_string).compile()
  17. Returns a compiled Pattern object.
  18. Pattern object can then be rolled to obtain a PatternScore object.
  19. """
  20. pattern = Pattern(pattern_string)
  21. pattern.compile()
  22. return pattern
  23. def roll(pattern_string):
  24. """
  25. > Similar to xdice.Pattern(pattern_string).roll()
  26. """
  27. return Pattern(pattern_string).roll()
  28. def rolldice(faces, amount=1):
  29. """
  30. > Similar to xdice.Dice(faces, amount).roll()
  31. """
  32. return Dice(faces, amount).roll()
  33. _ALLOWED = {'abs': abs, 'max': max, 'min': min}
  34. def _secured_eval(raw):
  35. """ securely evaluate the incoming raw string
  36. by avoiding the use of any non-allowed function """
  37. return eval(raw, {"__builtins__":None}, _ALLOWED)
  38. class Dice():
  39. """
  40. Dice(sides, amount=1):
  41. Set of dice.
  42. Use roll() to get a Score() object.
  43. """
  44. DEFAULT_SIDES = 20
  45. def __init__(self, sides, amount=1):
  46. """ Instanciate a Die object """
  47. self._sides = 1
  48. self._amount = 0
  49. self.sides = sides
  50. self.amount = amount
  51. @property
  52. def sides(self):
  53. """ Number of faces of the dice """
  54. return self._sides
  55. @sides.setter
  56. def sides(self, sides):
  57. """ Set the number of faces of the dice """
  58. try:
  59. if int(sides) < 1:
  60. raise ValueError()
  61. except (TypeError, ValueError):
  62. raise ValueError("Invalid value for sides (given: '{}')".format(sides))
  63. self._sides = sides
  64. @property
  65. def amount(self):
  66. """ Amount of dice """
  67. return self._amount
  68. @amount.setter
  69. def amount(self, amount):
  70. """ Set the amount of dice """
  71. try:
  72. if int(amount) < 0:
  73. raise ValueError()
  74. except (TypeError, ValueError):
  75. raise ValueError("Invalid value for amount (given: '{}')".format(amount))
  76. self._amount = amount
  77. def __repr__(self):
  78. """ Return a string representation of the Dice """
  79. return "<Dice; sides={}; amount={}>".format(self.sides, self.amount)
  80. def __eq__(self, d):
  81. """
  82. Eval equality of two Dice objects
  83. used for testing matters
  84. """
  85. return self.sides == d.sides and self.amount == d.amount
  86. def roll(self):
  87. """ Role the dice and return a Score object """
  88. return Score([random.randint(1, self._sides) for _ in range(self._amount)])
  89. @classmethod
  90. def parse(cls, pattern):
  91. """ parse a pattern of the form 'xdx', where x are positive integers """
  92. pattern = str(pattern).replace(" ", "").lower()
  93. amount, sides = pattern.split("d")
  94. if not amount:
  95. amount = 1
  96. if not sides:
  97. sides = cls.DEFAULT_SIDES
  98. return Dice(*map(int, [sides, amount]))
  99. class Score(int):
  100. """ Score is a subclass of integer.
  101. Then you can manipulate it as you would do with an integer.
  102. It also provides an access to the detailed score with the property 'detail'.
  103. 'detail' is the list of the scores obtained by each dice.
  104. Score class can also be used as an iterable, to walk trough the individual scores.
  105. eg:
  106. >>> s = Score([1,2,3])
  107. >>> print(s)
  108. 6
  109. >>> s + 1
  110. 7
  111. >>> list(s)
  112. [1,2,3]
  113. """
  114. def __new__(cls, detail):
  115. """
  116. detail should only contain integers
  117. Score value will be the sum of the list's values.
  118. """
  119. score = super(Score, cls).__new__(cls, sum(detail))
  120. score._detail = detail
  121. return score
  122. @property
  123. def detail(self):
  124. """ Return the detailed score
  125. as a list of integers,
  126. which are the results of each die rolled """
  127. return self._detail
  128. def __repr__(self):
  129. """ Return a string representation of the Score """
  130. return "<Score; score={}; detail={}>".format(int(self), self.detail)
  131. def __contains__(self, value):
  132. """ Does score contains the given result """
  133. return self.detail.__contains__(value)
  134. def __iter__(self):
  135. """ Iterate over results """
  136. return self.detail.__iter__()
  137. class Pattern():
  138. """ A dice-notation pattern """
  139. def __init__(self, instr):
  140. """ Instantiate a Pattern object. """
  141. if not instr:
  142. raise ValueError("Invalid value for 'instr' ('{}')".format(instr))
  143. self.instr = Pattern._normalize(instr)
  144. self.dices = []
  145. self.format_string = ""
  146. @staticmethod
  147. def _normalize(instr):
  148. """ normalize the incoming string to a lower string without spaces"""
  149. return str(instr).replace(" ", "").lower()
  150. def compile(self):
  151. """
  152. Parse the pattern. Two properties are updated at this time:
  153. * pattern.format_string:
  154. The ready-to-be-formatted string built from the instr argument.
  155. > Eg: '1d6+4+1d4' => '{0}+4-{1}'
  156. * pattern.dices
  157. The list of parsed dice.
  158. > Eg: '1d6+4+1d4' => [(Dice; sides=6;amount=1), (Dice; sides=4;amount=1)]
  159. """
  160. def _submatch(match):
  161. dice = Dice.parse(match.group(0))
  162. index = len(self.dices)
  163. self.dices.append(dice)
  164. return "{{{}}}".format(index)
  165. self.format_string = re.sub(r'\d*d\d*', _submatch, self.instr)
  166. def roll(self):
  167. """
  168. Compile the pattern if it has not been yet, then roll the dice.
  169. Return a PatternScore object.
  170. """
  171. if not self.format_string:
  172. self.compile()
  173. scores = [dice.roll() for dice in self.dices]
  174. return PatternScore(self.format_string, scores)
  175. class PatternScore(int):
  176. """
  177. PatternScore is a subclass of integer, you can then manipulate it as you would do with an integer.
  178. Moreover, you can get the list of the scores with the score(i) or scores() methods, and retrieve a formatted result with the format() method.
  179. """
  180. def __new__(cls, eval_string, scores):
  181. ps = super(PatternScore, cls).__new__(cls, _secured_eval(eval_string.format(*scores)))
  182. ps._eval_string = eval_string
  183. ps._scores = scores
  184. return ps
  185. def format(self):
  186. """
  187. Return a formatted string detailing the result of the roll.
  188. > Eg: '3d6+4' => '[1,5,6]+4'
  189. """
  190. return self._eval_string.format(*[str(list(score)) for score in self._scores])
  191. def score(self, i):
  192. """ Returns the Score object at index i. """
  193. return self._scores[i]
  194. def scores(self):
  195. """ Returns the list of Score objects extracted from the pattern and rolled. """
  196. return self._scores