xdice.py 11 KB

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