xdice.py 11 KB

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