xdice.py 12 KB

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