xdice.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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.1
  9. # TODO: (?) 'Rx(...)' notation: roll x times the pattern in the parenthesis => eg: R3(1d4+3)
  10. # TODO: (?) Dice pools, 6-sided variations, 10-sided variations,
  11. # Open-ended variations (https://en.wikipedia.org/wiki/Dice_notation)
  12. def compile(pattern_string): # @ReservedAssignment
  13. """
  14. > Similar to xdice.Pattern(pattern_string).compile()
  15. Returns a compiled Pattern object.
  16. Pattern object can then be rolled to obtain a PatternScore object.
  17. """
  18. pattern = Pattern(pattern_string)
  19. pattern.compile()
  20. return pattern
  21. def roll(pattern_string):
  22. """
  23. > Similar to xdice.Pattern(pattern_string).roll()
  24. """
  25. return Pattern(pattern_string).roll()
  26. def rolldice(faces, amount=1):
  27. """
  28. > Similar to xdice.Dice(faces, amount).roll()
  29. """
  30. return Dice(faces, amount).roll()
  31. _ALLOWED = {'abs': abs, 'max': max, 'min': min}
  32. def _secured_eval(raw):
  33. """ securely evaluate the incoming raw string
  34. by avoiding the use of any non-allowed function """
  35. return eval(raw, {"__builtins__":None}, _ALLOWED)
  36. def _assert_int_ge_to(value, threshold=0, msg=""):
  37. """ assert value is an integer greater or equal to threshold """
  38. try:
  39. if int(value) < threshold:
  40. raise ValueError()
  41. except (TypeError, ValueError):
  42. raise ValueError(msg)
  43. def _split_list(lst, left, right):
  44. """ divides a list in 3 sections: [:left], [left:right], [right:]
  45. return a tuple of lists"""
  46. return lst[:left], lst[left:right], lst[right:]
  47. def _normalize(pattern):
  48. return str(pattern).replace(" ", "").lower().replace("d%", "d100")
  49. class Dice():
  50. """
  51. Dice(sides, amount=1):
  52. Set of dice.
  53. Use roll() to get a Score() object.
  54. """
  55. DEFAULT_SIDES = 20
  56. DICE_RE_STR = r"(?P<amount>\d*)d(?P<sides>\d*)(?:l(?P<lowest>\d*))?(?:h(?P<highest>\d*))?"
  57. DICE_RE = re.compile(DICE_RE_STR)
  58. def __init__(self, sides, amount=1, drop_lowest=0, drop_highest=0):
  59. """ Instantiate a Die object """
  60. self._sides = 1
  61. self._amount = 0
  62. self._drop_lowest = 0
  63. self._drop_highest = 0
  64. self.sides = sides
  65. self.amount = amount
  66. self.drop_lowest = drop_lowest
  67. self.drop_highest = drop_highest
  68. @property
  69. def sides(self):
  70. """ Number of faces of the dice """
  71. return self._sides
  72. @sides.setter
  73. def sides(self, sides):
  74. """ Set the number of faces of the dice """
  75. _assert_int_ge_to(sides, 1, "Invalid value for sides ('{}')".format(sides))
  76. self._sides = sides
  77. @property
  78. def amount(self):
  79. """ Amount of dice """
  80. return self._amount
  81. @amount.setter
  82. def amount(self, amount):
  83. """ Set the amount of dice """
  84. _assert_int_ge_to(amount, 0, "Invalid value for amount ('{}')".format(amount))
  85. self._amount = amount
  86. @property
  87. def drop_lowest(self):
  88. """ The N lowest dices to ignore """
  89. return self._drop_lowest
  90. @drop_lowest.setter
  91. def drop_lowest(self, drop_lowest):
  92. """ Set the number of lowest dices to ignore """
  93. _assert_int_ge_to(drop_lowest, 0, "Invalid value for drop_lowest ('{}')".format(drop_lowest))
  94. if self.drop_highest + drop_lowest > self.amount:
  95. raise ValueError("You can not drop more dice than amount")
  96. self._drop_lowest = drop_lowest
  97. @property
  98. def drop_highest(self):
  99. """ The N highest dices to ignore """
  100. return self._drop_highest
  101. @drop_highest.setter
  102. def drop_highest(self, drop_highest):
  103. """ Set the number of highest dices to ignore """
  104. _assert_int_ge_to(drop_highest, 0, "Invalid value for drop_highest ('{}')".format(drop_highest))
  105. if self.drop_lowest + drop_highest > self.amount:
  106. raise ValueError("You can not drop more dice than amount")
  107. self._drop_highest = drop_highest
  108. @property
  109. def name(self):
  110. """ build the name of the Dice """
  111. return "{}d{}{}{}".format(self._amount,
  112. self._sides,
  113. "l{}".format(self._drop_lowest) if self._drop_lowest else "",
  114. "h{}".format(self._drop_highest) if self._drop_highest else "")
  115. def __repr__(self):
  116. """ Return a string representation of the Dice """
  117. return "<Dice; sides={}; amount={}>".format(self.sides, self.amount)
  118. def __eq__(self, d):
  119. """
  120. Eval equality of two Dice objects
  121. used for testing matters
  122. """
  123. return self.sides == d.sides and self.amount == d.amount
  124. def roll(self):
  125. """ Role the dice and return a Score object """
  126. # Sort results
  127. results = sorted([random.randint(1, self._sides) for _ in range(self._amount)])
  128. # Drop the lowest / highest results
  129. lowest, results, highest = _split_list(results, self._drop_lowest, len(results) - self._drop_highest)
  130. return Score(results, lowest + highest, self.name)
  131. @classmethod
  132. def parse(cls, pattern):
  133. """ parse a pattern of the form 'xdx', where x are positive integers """
  134. pattern = _normalize(pattern)
  135. match = cls.DICE_RE.match(pattern)
  136. if match is None:
  137. raise ValueError("Invalid Dice pattern ('{}')".format(pattern))
  138. amount, sides, lowest, highest = match.groups()
  139. amount = amount or 1
  140. sides = sides or cls.DEFAULT_SIDES
  141. lowest = (lowest or 1) if lowest is not None else 0
  142. highest = (highest or 1) if highest is not None else 0
  143. return Dice(*map(int, [sides, amount, lowest, highest]))
  144. class Score(int):
  145. """ Score is a subclass of integer.
  146. Then you can manipulate it as you would do with an integer.
  147. It also provides an access to the detailed score with the property 'detail'.
  148. 'detail' is the list of the scores obtained by each dice.
  149. Score class can also be used as an iterable, to walk trough the individual scores.
  150. eg:
  151. >>> s = Score([1,2,3])
  152. >>> print(s)
  153. 6
  154. >>> s + 1
  155. 7
  156. >>> list(s)
  157. [1,2,3]
  158. """
  159. def __new__(cls, detail, dropped=[], name=""):
  160. """
  161. detail should only contain integers
  162. Score value will be the sum of the list's values.
  163. """
  164. score = super(Score, cls).__new__(cls, sum(detail))
  165. score._detail = detail
  166. score._dropped = dropped
  167. score._name = name
  168. return score
  169. @property
  170. def detail(self):
  171. """ Return the detailed score
  172. as a list of integers,
  173. which are the results of each die rolled """
  174. return self._detail
  175. def __repr__(self):
  176. """ Return a string representation of the Score """
  177. return "<Score; score={}; detail={}; dropped={}; name={}>".format(int(self),
  178. self.detail,
  179. self.dropped,
  180. self.name)
  181. def format(self, verbose=False):
  182. """
  183. Return a formatted string detailing the score of the Dice roll.
  184. > Eg: '3d6' => '[1,5,6]'
  185. """
  186. basestr = str(list(self.detail))
  187. if not verbose:
  188. return basestr
  189. else:
  190. droppedstr = ", dropped:{}".format(self.dropped) if verbose and self.dropped else ""
  191. return " {}(scores:{}{}) ".format(self._name, basestr, droppedstr)
  192. def __contains__(self, value):
  193. """ Does score contains the given result """
  194. return self.detail.__contains__(value)
  195. def __iter__(self):
  196. """ Iterate over results """
  197. return self.detail.__iter__()
  198. @property
  199. def dropped(self):
  200. """ list of dropped results """
  201. return self._dropped
  202. @property
  203. def name(self):
  204. """ descriptive name of the score """
  205. return self._name
  206. class Pattern():
  207. """ A dice-notation pattern """
  208. def __init__(self, instr):
  209. """ Instantiate a Pattern object. """
  210. if not instr:
  211. raise ValueError("Invalid value for 'instr' ('{}')".format(instr))
  212. self.instr = _normalize(instr)
  213. self.dices = []
  214. self.format_string = ""
  215. def compile(self):
  216. """
  217. Parse the pattern. Two properties are updated at this time:
  218. * pattern.format_string:
  219. The ready-to-be-formatted string built from the instr argument.
  220. > Eg: '1d6+4+1d4' => '{0}+4-{1}'
  221. * pattern.dices
  222. The list of parsed dice.
  223. > Eg: '1d6+4+1d4' => [(Dice; sides=6;amount=1), (Dice; sides=4;amount=1)]
  224. """
  225. def _submatch(match):
  226. dice = Dice.parse(match.group(0))
  227. index = len(self.dices)
  228. self.dices.append(dice)
  229. return "{{{}}}".format(index)
  230. self.format_string = Dice.DICE_RE.sub(_submatch, self.instr)
  231. def roll(self):
  232. """
  233. Compile the pattern if it has not been yet, then roll the dice.
  234. Return a PatternScore object.
  235. """
  236. if not self.format_string:
  237. self.compile()
  238. scores = [dice.roll() for dice in self.dices]
  239. return PatternScore(self.format_string, scores)
  240. class PatternScore(int):
  241. """
  242. PatternScore is a subclass of integer, you can then manipulate it as you would do with an integer.
  243. Moreover, you can get the list of the scores with the score(i)
  244. or scores() methods, and retrieve a formatted result with the format() method.
  245. """
  246. def __new__(cls, eval_string, scores):
  247. ps = super(PatternScore, cls).__new__(cls, _secured_eval(eval_string.format(*scores)))
  248. ps._eval_string = eval_string
  249. ps._scores = scores
  250. return ps
  251. def format(self, verbose=False):
  252. """
  253. Return a formatted string detailing the result of the roll.
  254. > Eg: '3d6+4' => '[1,5,6]+4'
  255. """
  256. return self._eval_string.format(*[score.format(verbose) for score in self._scores])
  257. def score(self, i):
  258. """ Returns the Score object at index i. """
  259. return self._scores[i]
  260. def scores(self):
  261. """ Returns the list of Score objects extracted from the pattern and rolled. """
  262. return self._scores