roll.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. #!/usr/bin/env python
  2. import attr
  3. import logging
  4. import re
  5. import sys
  6. import readline
  7. import operator
  8. from numbers import Number
  9. from random import SystemRandom
  10. from pyparsing import ParserElement, Token, Regex, oneOf, Optional, Group, Combine, Literal, CaselessLiteral, ZeroOrMore, StringStart, StringEnd, opAssoc, infixNotation, ParseException, Empty, pyparsing_common, ParseResults, White, Suppress
  11. from typing import Union, List, Any, Tuple, Sequence, Dict, Callable, Set, TextIO
  12. from typing import Optional as OptionalType
  13. try:
  14. import colorama
  15. colorama.init()
  16. from colors import color
  17. except ImportError:
  18. # Fall back to no color
  19. def color(s: str, *args, **kwargs):
  20. '''Fake color function that does nothing.
  21. Used when the colors module cannot be imported.'''
  22. return s
  23. EXPR_COLOR = "green"
  24. RESULT_COLOR = "red"
  25. DETAIL_COLOR = "yellow"
  26. logFormatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S')
  27. logger = logging.getLogger(__name__)
  28. logger.setLevel(logging.INFO)
  29. logger.handlers = []
  30. logger.addHandler(logging.StreamHandler())
  31. for handler in logger.handlers:
  32. handler.setFormatter(logFormatter)
  33. sysrand = SystemRandom()
  34. randint = sysrand.randint
  35. def int_limit_converter(x: Any) -> OptionalType[int]:
  36. if x is None:
  37. return None
  38. else:
  39. return int(x)
  40. @attr.s
  41. class IntegerValidator(object):
  42. min_val: OptionalType[int] = attr.ib(default = None, converter = int_limit_converter)
  43. max_val: OptionalType[int] = attr.ib(default = None, converter = int_limit_converter)
  44. handle_float: str = attr.ib(default = 'exception')
  45. @handle_float.validator
  46. def validate_handle_float(self, attribute, value):
  47. assert value in ('exception', 'truncate', 'round')
  48. value_name: str = attr.ib(default = "value")
  49. def __call__(self, value: Any) -> int:
  50. xf: float
  51. x: int
  52. try:
  53. xf = float(value)
  54. except ValueError:
  55. raise ValueError('{} {} does not look like a number'.format(self.value_name, value))
  56. if not xf.is_integer():
  57. if self.handle_float == 'exception':
  58. raise ValueError('{} {} is not an integer'.format(self.value_name, value))
  59. elif self.handle_float == 'truncate':
  60. x = int(xf)
  61. else:
  62. x = round(xf)
  63. else:
  64. x = int(xf)
  65. if self.min_val is not None and x < self.min_val:
  66. raise ValueError('{} {} is too small; must be at least {}'.format(self.value_name, value, self.min_val))
  67. if self.max_val is not None and x > self.max_val:
  68. raise ValueError('{} {} is too large; must be at most {}'.format(self.value_name, value, self.max_val))
  69. return x
  70. die_face_num_validator = IntegerValidator(
  71. min_val = 2, handle_float = 'exception',
  72. value_name = 'die type',
  73. )
  74. DieFaceType = Union[int, str]
  75. def is_fate_face(x: DieFaceType) -> bool:
  76. if isinstance(x, int):
  77. return False
  78. else:
  79. x = str(x).upper()
  80. return x in ('F', 'F.1', 'F.2')
  81. def normalize_die_type(x: DieFaceType) -> DieFaceType:
  82. if is_fate_face(x):
  83. return str(x).upper()
  84. elif x == '%':
  85. return 100
  86. else:
  87. return die_face_num_validator(x)
  88. dice_count_validator = IntegerValidator(
  89. min_val = 1, handle_float = 'exception',
  90. value_name = 'dice count'
  91. )
  92. # Just a named function wrapper for dice_count_validator
  93. def normalize_dice_count(x: Any) -> int:
  94. return dice_count_validator(x)
  95. def ImplicitToken(x) -> ParserElement:
  96. '''Like pyparsing.Empty, but yields one or more tokens instead of nothing.'''
  97. return Empty().setParseAction(lambda toks: x)
  98. # TODO: Look at http://infohost.nmt.edu/tcc/help/pubs/pyparsing/web/classes.html#class-ParserElement
  99. # Implementing the syntax described here: https://www.critdice.com/roll-advanced-dice
  100. # https://stackoverflow.com/a/23956778/125921
  101. # https://stackoverflow.com/a/46583691/125921
  102. var_name: ParserElement = pyparsing_common.identifier.copy().setResultsName('varname')
  103. real_num: ParserElement = pyparsing_common.fnumber.copy()
  104. positive_int: ParserElement = pyparsing_common.integer.copy().setParseAction(lambda toks: [ IntegerValidator(min_val=1)(toks[0]) ])
  105. drop_type: ParserElement = oneOf('K k X x -H -L')
  106. drop_spec: ParserElement = Group(
  107. drop_type.setResultsName('type') +
  108. (positive_int | ImplicitToken(1)).setResultsName('count')
  109. ).setResultsName('drop')
  110. pos_int_implicit_one: ParserElement = (positive_int | ImplicitToken(1))
  111. comparator_type: ParserElement = oneOf('<= < >= > ≤ ≥ =')
  112. reroll_type: ParserElement = Combine(oneOf('R r') ^ ( oneOf('! !!') + Optional('p')))
  113. reroll_spec: ParserElement = Group(
  114. reroll_type.setResultsName('type') +
  115. Optional(
  116. (comparator_type | ImplicitToken('=')).setResultsName('operator') + \
  117. positive_int.setResultsName('value')
  118. )
  119. ).setResultsName('reroll')
  120. count_spec: ParserElement = Group(
  121. Group(
  122. comparator_type.setResultsName('operator') + \
  123. positive_int.setResultsName('value')
  124. ).setResultsName('success_condition') +
  125. Optional(
  126. Literal('f') +
  127. Group(
  128. comparator_type.setResultsName('operator') + \
  129. positive_int.setResultsName('value')
  130. ).setResultsName('failure_condition')
  131. )
  132. ).setResultsName('count_successes')
  133. roll_spec: ParserElement = Group(
  134. (positive_int | ImplicitToken(1)).setResultsName('dice_count') +
  135. CaselessLiteral('d') +
  136. (positive_int | oneOf('% F F.1 F.2')).setResultsName('die_type') +
  137. Optional(reroll_spec ^ drop_spec) +
  138. Optional(count_spec)
  139. ).setResultsName('roll')
  140. expr_parser: ParserElement = infixNotation(
  141. baseExpr=(roll_spec ^ positive_int ^ real_num ^ var_name),
  142. opList=[
  143. (oneOf('** ^').setResultsName('operator', True), 2, opAssoc.RIGHT),
  144. (oneOf('* / × ÷').setResultsName('operator', True), 2, opAssoc.LEFT),
  145. (oneOf('+ -').setResultsName('operator', True), 2, opAssoc.LEFT),
  146. ]
  147. ).setResultsName('expr')
  148. assignment_parser: ParserElement = var_name + Literal('=').setResultsName('assignment') + expr_parser
  149. def roll_die(sides: DieFaceType = 6) -> int:
  150. '''Roll a single die.
  151. Supports any valid integer number of sides as well as 'F' for a fate
  152. die, which can return -1, 0, or 1 with equal probability.
  153. '''
  154. if sides in ('F', 'F.2'):
  155. # Fate die = 1d3-2
  156. return roll_die(3) - 2
  157. elif sides == 'F.1':
  158. d6 = roll_die(6)
  159. if d6 == 1:
  160. return -1
  161. elif d6 == 6:
  162. return 1
  163. else:
  164. return 0
  165. else:
  166. return randint(1, int(sides))
  167. class DieRolled(int):
  168. '''Subclass of int that allows a string suffix.
  169. This is meant for recording the result of rolling a die. The
  170. suffix is purely cosmetic, for the purposes of string conversion.
  171. It can be used to indicate a die roll that has been re-rolled or
  172. exploded, or to indicate a critical hit/miss.
  173. '''
  174. formatter: str
  175. def __new__(cls: type, value: int, formatter: str = '{}') -> 'DieRolled':
  176. newval = super(DieRolled, cls).__new__(cls, value) # type: ignore
  177. newval.formatter = formatter
  178. return newval
  179. def __str__(self) -> str:
  180. return self.formatter.format(super().__str__())
  181. def __repr__(self) -> str:
  182. if self.formatter != '{}':
  183. return 'DieRolled(value={value!r}, formatter={formatter!r})'.format(
  184. value=int(self),
  185. formatter=self.formatter,
  186. )
  187. else:
  188. return 'DieRolled({value!r})'.format(value=int(self))
  189. def normalize_dice_roll_list(value: List[Any]) -> List[int]:
  190. result = []
  191. for x in value:
  192. if isinstance(x, int):
  193. result.append(x)
  194. else:
  195. result.append(int(x))
  196. return result
  197. def format_dice_roll_list(rolls: List[int], always_list: bool = False) -> str:
  198. if len(rolls) == 0:
  199. raise ValueError('Need at least one die rolled')
  200. elif len(rolls) == 1 and not always_list:
  201. return color(str(rolls[0]), DETAIL_COLOR)
  202. else:
  203. return '[' + color(" ".join(map(str, rolls)), DETAIL_COLOR) + ']'
  204. def int_or_none(x: OptionalType[Any]) -> OptionalType[int]:
  205. if x is None:
  206. return None
  207. else:
  208. return int(x)
  209. @attr.s
  210. class DiceRolled(object):
  211. '''Class representing the result of rolling one or more similar dice.'''
  212. dice_results: List[int] = attr.ib(converter = normalize_dice_roll_list)
  213. @dice_results.validator
  214. def validate_dice_results(self, attribute, value):
  215. if len(value) == 0:
  216. raise ValueError('Need at least one non-dropped roll')
  217. dropped_results: List[int] = attr.ib(
  218. default = attr.Factory(list),
  219. converter = normalize_dice_roll_list)
  220. roll_desc: str = attr.ib(default = '', converter = str)
  221. success_count: OptionalType[int] = attr.ib(default = None, converter = int_or_none)
  222. def total(self) -> int:
  223. if self.success_count is not None:
  224. return int(self.success_count)
  225. else:
  226. return sum(self.dice_results)
  227. def __str__(self) -> str:
  228. if self.roll_desc:
  229. prefix = '{roll} rolled'.format(roll=color(self.roll_desc, EXPR_COLOR))
  230. else:
  231. prefix = 'Rolled'
  232. if self.dropped_results:
  233. drop = ' (dropped {dropped})'.format(dropped = format_dice_roll_list(self.dropped_results))
  234. else:
  235. drop = ''
  236. if self.success_count is not None:
  237. tot = ', Total successes: ' + color(str(self.total()), DETAIL_COLOR)
  238. elif len(self.dice_results) > 1:
  239. tot = ', Total: ' + color(str(self.total()), DETAIL_COLOR)
  240. else:
  241. tot = ''
  242. return '{prefix}: {results}{drop}{tot}'.format(
  243. prefix=prefix,
  244. results=format_dice_roll_list(self.dice_results),
  245. drop=drop,
  246. tot=tot,
  247. )
  248. def __int__(self) -> int:
  249. return self.total()
  250. def __float__(self) -> float:
  251. return float(self.total())
  252. def validate_by_parser(parser):
  253. '''Return a validator that validates anything parser can parse.'''
  254. def private_validator(instance, attribute, value):
  255. parser.parseString(str(value), True)
  256. return private_validator
  257. @attr.s
  258. class Comparator(object):
  259. cmp_dict = {
  260. '<=': operator.le,
  261. '<': operator.lt,
  262. '>=': operator.ge,
  263. '>': operator.gt,
  264. '≤': operator.le,
  265. '≥': operator.ge,
  266. '=': operator.eq,
  267. }
  268. operator: str = attr.ib(converter = str,
  269. validator = validate_by_parser(comparator_type))
  270. value: int = attr.ib(converter = int,
  271. validator = validate_by_parser(positive_int))
  272. def __str__(self) -> str:
  273. return '{op}{val}'.format(op=self.operator, val=self.value)
  274. def compare(self, x) -> bool:
  275. '''Return True if x satisfies the comparator.
  276. In other words, x is placed on the left-hand side of the
  277. comparison, the Comparator's value is placed on the right hand
  278. side, and the truth value of the resulting test is returned.
  279. '''
  280. return self.cmp_dict[self.operator](x, self.value)
  281. @attr.s
  282. class RerollSpec(object):
  283. # Yes, it has to be called type
  284. type: str = attr.ib(converter = str, validator=validate_by_parser(reroll_type))
  285. operator: OptionalType[str] = attr.ib(default = None)
  286. value: OptionalType[int] = attr.ib(default = None)
  287. def __attrs_post_init__(self):
  288. if (self.operator is None) != (self.value is None):
  289. raise ValueError('Operator and value must be provided together')
  290. def __str__(self) -> str:
  291. result = self.type
  292. if self.operator is not None:
  293. result += self.operator + str(self.value)
  294. return result
  295. def roll_die(self, sides: DieFaceType) -> List[int]:
  296. '''Roll a single die, following specified re-rolling rules.
  297. Returns a list of rolls, since some types of re-rolling
  298. collect the result of multiple die rolls.
  299. '''
  300. if is_fate_face(sides):
  301. raise ValueError("Re-rolling/exploding is incompatible with Fate dice")
  302. sides = int(sides)
  303. cmpr: Comparator
  304. if self.value is None:
  305. if self.type in ('R', 'r'):
  306. cmpr = Comparator('=', 1)
  307. else:
  308. cmpr = Comparator('=', sides)
  309. else:
  310. cmpr = Comparator(self.operator, self.value)
  311. if self.type == 'r':
  312. # Single reroll
  313. roll = roll_die(sides)
  314. if cmpr.compare(roll):
  315. roll = DieRolled(roll_die(sides), '{}' + self.type)
  316. return [ roll ]
  317. elif self.type == 'R':
  318. # Indefinite reroll
  319. roll = roll_die(sides)
  320. while cmpr.compare(roll):
  321. roll = DieRolled(roll_die(sides), '{}' + self.type)
  322. return [ roll ]
  323. elif self.type in ['!', '!!', '!p', '!!p']:
  324. # Explode/penetrate/compound
  325. all_rolls: List[int] = [ roll_die(sides) ]
  326. while cmpr.compare(all_rolls[-1]):
  327. all_rolls.append(roll_die(sides))
  328. # If we never re-rolled, no need to do anything special
  329. if len(all_rolls) == 1:
  330. return all_rolls
  331. # For penetration, subtract 1 from all rolls except the first
  332. if self.type.endswith('p'):
  333. for i in range(1, len(all_rolls)):
  334. all_rolls[i] -= 1
  335. # For compounding, return the sum
  336. if self.type.startswith('!!'):
  337. total = sum(all_rolls)
  338. return [ DieRolled(total, '{}' + self.type) ]
  339. else:
  340. for i in range(0, len(all_rolls)-1):
  341. all_rolls[i] = DieRolled(all_rolls[i], '{}' + self.type)
  342. return all_rolls
  343. else:
  344. raise Exception('Unknown reroll type: {}'.format(self.type))
  345. @attr.s
  346. class DropSpec(object):
  347. # Yes, it has to be called type
  348. type: str = attr.ib(converter = str, validator=validate_by_parser(drop_type))
  349. count: int = attr.ib(default = 1, converter = int, validator=validate_by_parser(positive_int))
  350. def __str__(self) -> str:
  351. if self.count > 1:
  352. return self.type + str(self.count)
  353. else:
  354. return self.type
  355. def drop_rolls(self, rolls: List[int]) -> Tuple[List[int], List[int]]:
  356. '''Drop the appripriate rolls from a list of rolls.
  357. Returns a 2-tuple of roll lists. The first list is the kept
  358. rolls, and the second list is the dropped rolls.
  359. The order of the rolls is not preserved. (TODO FIX THIS)
  360. '''
  361. if not isinstance(rolls, list):
  362. rolls = list(rolls)
  363. keeping = self.type in ('K', 'k')
  364. if keeping:
  365. num_to_keep = self.count
  366. else:
  367. num_to_keep = len(rolls) - self.count
  368. if num_to_keep == 0:
  369. raise ValueError('Not enough rolls: would drop all rolls')
  370. elif num_to_keep == len(rolls):
  371. raise ValueError('Keeping too many rolls: would not drop any rolls')
  372. rolls.sort()
  373. if self.type in ('K', 'X', '-H'):
  374. rolls.reverse()
  375. (head, tail) = rolls[:self.count], rolls[self.count:]
  376. if keeping:
  377. (kept, dropped) = (head, tail)
  378. else:
  379. (kept, dropped) = (tail, head)
  380. return (kept, dropped)
  381. @attr.s
  382. class DiceRoller(object):
  383. die_type: DieFaceType = attr.ib(converter = normalize_die_type)
  384. dice_count: int = attr.ib(default = 1, converter = normalize_dice_count)
  385. reroll_spec: OptionalType[RerollSpec] = attr.ib(default = None)
  386. @reroll_spec.validator
  387. def validate_reroll_spec(self, attribute, value):
  388. if value is not None:
  389. assert isinstance(value, RerollSpec)
  390. drop_spec: OptionalType[DropSpec] = attr.ib(default = None)
  391. @drop_spec.validator
  392. def validate_drop_spec(self, attribute, value):
  393. if value is not None:
  394. assert isinstance(value, DropSpec)
  395. success_comparator: OptionalType[Comparator] = attr.ib(default = None)
  396. failure_comparator: OptionalType[Comparator] = attr.ib(default = None)
  397. @success_comparator.validator
  398. @failure_comparator.validator
  399. def validate_comparator(self, attribute, value):
  400. if value is not None:
  401. assert isinstance(value, Comparator)
  402. def __attrs_post_init__(self):
  403. if self.reroll_spec is not None and self.drop_spec is not None:
  404. raise ValueError('Reroll and drop specs are mutually exclusive')
  405. if self.success_comparator is None and self.failure_comparator is not None:
  406. raise ValueError('Cannot use a failure condition without a success condition')
  407. def __str__(self) -> str:
  408. return '{count}d{type}{reroll}{drop}{success}{fail}'.format(
  409. count = self.dice_count if self.dice_count > 1 else '',
  410. type = self.die_type,
  411. reroll = self.reroll_spec or '',
  412. drop = self.drop_spec or '',
  413. success = self.success_comparator or '',
  414. fail = ('f' + str(self.failure_comparator)) if self.failure_comparator else '',
  415. )
  416. def roll(self) -> DiceRolled:
  417. '''Roll dice according to specifications. Returns a DiceRolled object.'''
  418. all_rolls = []
  419. if self.reroll_spec:
  420. for i in range(self.dice_count):
  421. all_rolls.extend(self.reroll_spec.roll_die(self.die_type))
  422. else:
  423. for i in range(self.dice_count):
  424. all_rolls.append(roll_die(self.die_type))
  425. if self.drop_spec:
  426. (dice_results, dropped_results) = self.drop_spec.drop_rolls(all_rolls)
  427. else:
  428. (dice_results, dropped_results) = (all_rolls, [])
  429. success_count: OptionalType[int]
  430. if self.success_comparator is not None:
  431. success_count = 0
  432. for roll in dice_results:
  433. if self.success_comparator.compare(roll):
  434. success_count += 1
  435. if self.failure_comparator is not None:
  436. for roll in dice_results:
  437. if self.failure_comparator.compare(roll):
  438. success_count -= 1
  439. else:
  440. success_count = None
  441. return DiceRolled(
  442. dice_results=dice_results,
  443. dropped_results=dropped_results,
  444. roll_desc=str(self),
  445. success_count=success_count,
  446. )
  447. def make_dice_roller(expr: Union[str,ParseResults]) -> DiceRoller:
  448. if isinstance(expr, str):
  449. expr = roll_spec.parseString(expr, True)['roll']
  450. assert expr.getName() == 'roll'
  451. expr = expr.asDict()
  452. dtype = normalize_die_type(expr['die_type'])
  453. dcount = normalize_dice_count(expr['dice_count'])
  454. constructor_args: Dict[str, Any] = {
  455. 'die_type': dtype,
  456. 'dice_count': dcount,
  457. 'reroll_spec': None,
  458. 'drop_spec': None,
  459. 'success_comparator': None,
  460. 'failure_comparator': None,
  461. }
  462. rrdict = None
  463. if 'reroll' in expr:
  464. rrdict = expr['reroll']
  465. constructor_args['reroll_spec'] = RerollSpec(**rrdict)
  466. if 'drop' in expr:
  467. ddict = expr['drop']
  468. constructor_args['drop_spec'] = DropSpec(**ddict)
  469. if 'count_successes' in expr:
  470. csdict = expr['count_successes']
  471. constructor_args['success_comparator'] = Comparator(**csdict['success_condition'])
  472. if 'failure_condition' in csdict:
  473. constructor_args['failure_comparator'] = Comparator(**csdict['failure_condition'])
  474. return DiceRoller(**constructor_args)
  475. # examples = [
  476. # '1+1',
  477. # '1 + 1 + x',
  478. # '3d8',
  479. # '2e3 * 4d6 + 2',
  480. # '2d20k',
  481. # '3d20x2',
  482. # '4d4rK3',
  483. # '4d4R4',
  484. # '4d4R>=3',
  485. # '4d4r>=3',
  486. # '4d4!1',
  487. # '4d4!<3',
  488. # '4d4!p',
  489. # '2D20K+10',
  490. # '2D20k+10',
  491. # '10d6X4',
  492. # '4d8r + 6',
  493. # '20d6R≤2',
  494. # '6d10!≥8+6',
  495. # '10d4!p',
  496. # '20d6≥6',
  497. # '8d12≥10f≤2',
  498. # # '4d20R<=2!>=19Xx21>=20f<=5*2+3', # Pretty much every possible feature
  499. # ]
  500. # example_results = {}
  501. # for x in examples:
  502. # try:
  503. # example_results[x] = parse_roll(x)
  504. # except ParseException as ex:
  505. # example_results[x] = ex
  506. # example_results
  507. # rs = RerollSpec('!!p', '=', 6)
  508. # rs.roll_die(6)
  509. # ds = DropSpec('K', 2)
  510. # ds.drop_rolls([1,2,3,4,5])
  511. # ds = DropSpec('x', 2)
  512. # ds.drop_rolls([1,2,3,4,5])
  513. # parse_roll = lambda x: expr_parser.parseString(x)[0]
  514. # exprstring = 'x + 1 + (2 + (3 + 4))'
  515. # expr = parse_roll(exprstring)
  516. # r = parse_roll('x + 1 - 2 * y * 4d4 + 2d20K1>=20f<=5')[0]
  517. op_dict: Dict[str, Callable] = {
  518. '+': operator.add,
  519. '-': operator.sub,
  520. '*': operator.mul,
  521. '×': operator.mul,
  522. '/': operator.truediv,
  523. '÷': operator.truediv,
  524. '**': operator.pow,
  525. '^': operator.pow,
  526. }
  527. NumericType = Union[float,int]
  528. ExprType = Union[NumericType, str, ParseResults]
  529. def normalize_expr(expr: ExprType) -> ParseResults:
  530. if isinstance(expr, str):
  531. return expr_parser.parseString(expr)['expr']
  532. elif isinstance(expr, Number):
  533. return expr
  534. else:
  535. assert isinstance(expr, ParseResults)
  536. return expr['expr']
  537. def _eval_expr_internal(
  538. expr: ExprType,
  539. env: Dict[str, str] = {},
  540. print_rolls: bool = True,
  541. recursed_vars: Set[str] = set()) -> NumericType:
  542. if isinstance(expr, float) or isinstance(expr, int):
  543. # Numeric literal
  544. return expr
  545. elif isinstance(expr, str):
  546. # variable name
  547. if expr in recursed_vars:
  548. raise ValueError('Recursive variable definition detected for {!r}'.format(expr))
  549. elif expr in env:
  550. var_value = env[expr]
  551. parsed = normalize_expr(var_value)
  552. return _eval_expr_internal(parsed, env, print_rolls,
  553. recursed_vars = recursed_vars.union([expr]))
  554. else:
  555. raise ValueError('Expression referenced undefined variable {!r}'.format(expr))
  556. else:
  557. assert isinstance(expr, ParseResults)
  558. if 'operator' in expr:
  559. # Compound expression
  560. operands = expr[::2]
  561. operators = expr[1::2]
  562. assert len(operands) == len(operators) + 1
  563. values = [ _eval_expr_internal(x, env, print_rolls, recursed_vars)
  564. for x in operands ]
  565. result = values[0]
  566. for (op, nextval) in zip(operators, values[1:]):
  567. opfun = op_dict[op]
  568. result = opfun(result, nextval)
  569. return result
  570. else:
  571. # roll specification
  572. roller = make_dice_roller(expr)
  573. rolled = roller.roll()
  574. if print_rolls:
  575. print(rolled)
  576. return int(rolled)
  577. def eval_expr(expr: ExprType,
  578. env: Dict[str,str] = {},
  579. print_rolls: bool = True) -> NumericType:
  580. expr = normalize_expr(expr)
  581. return _eval_expr_internal(expr, env, print_rolls)
  582. def _expr_as_str_internal(expr: ExprType,
  583. env: Dict[str,str] = {},
  584. recursed_vars: Set[str] = set()) -> str:
  585. if isinstance(expr, float) or isinstance(expr, int):
  586. return '{:g}'.format(expr)
  587. elif isinstance(expr, str):
  588. # variable name
  589. if expr in recursed_vars:
  590. raise ValueError('Recursive variable definition detected for {!r}'.format(expr))
  591. elif expr in env:
  592. var_value = env[expr]
  593. parsed = normalize_expr(var_value)
  594. return _expr_as_str_internal(parsed, env, recursed_vars = recursed_vars.union([expr]))
  595. # Not a variable name, just a string
  596. else:
  597. return expr
  598. else:
  599. assert isinstance(expr, ParseResults)
  600. if 'operator' in expr:
  601. # Compound expression
  602. operands = expr[::2]
  603. operators = expr[1::2]
  604. assert len(operands) == len(operators) + 1
  605. values = [ _expr_as_str_internal(x, env, recursed_vars)
  606. for x in operands ]
  607. result = str(values[0])
  608. for (op, nextval) in zip(operators, values[1:]):
  609. result += ' {} {}'.format(op, nextval)
  610. return '(' + result + ')'
  611. else:
  612. # roll specification
  613. return str(make_dice_roller(expr))
  614. def expr_as_str(expr: ExprType, env: Dict[str,str] = {}) -> str:
  615. expr = normalize_expr(expr)
  616. expr = _expr_as_str_internal(expr, env)
  617. if expr.startswith('(') and expr.endswith(')'):
  618. expr = expr[1:-1]
  619. return expr
  620. def read_roll(handle: TextIO = sys.stdin) -> str:
  621. if handle == sys.stdin:
  622. return input("Enter roll> ")
  623. else:
  624. return handle.readline()[:-1]
  625. special_command_parser: ParserElement = (
  626. oneOf('h help ?').setResultsName('help') |
  627. oneOf('q quit exit').setResultsName('quit') |
  628. oneOf('v vars').setResultsName('vars') |
  629. (oneOf('d del delete').setResultsName('delete').leaveWhitespace() + Suppress(White()) + var_name)
  630. )
  631. def var_name_allowed(vname: str) -> bool:
  632. '''Disallow variable names like 'help' and 'quit'.'''
  633. parsers = [ special_command_parser, roll_spec ]
  634. for parser in [ special_command_parser, roll_spec ]:
  635. try:
  636. parser.parseString(vname, True)
  637. return False
  638. except ParseException:
  639. pass
  640. # If the variable name didn't parse as anything else, it's valid
  641. return True
  642. line_parser: ParserElement = (
  643. special_command_parser ^
  644. (assignment_parser | expr_parser)
  645. )
  646. def print_interactive_help() -> None:
  647. print('\n' + '''
  648. To make a roll, type in the roll in dice notation, e.g. '4d4 + 4'.
  649. Nearly all dice notation forms listed in the following references should be supported:
  650. - http://rpg.greenimp.co.uk/dice-roller/
  651. - https://www.critdice.com/roll-advanced-dice
  652. Expressions can include numeric constants, addition, subtraction,
  653. multiplication, division, and exponentiation.
  654. To assign a variable, use 'VAR = VALUE'. For example 'health_potion =
  655. 2d4+2'. Subsequent roll expressions (and other variables) can refer to
  656. this variable, whose value will be substituted in to the expression.
  657. If a variable's value includes any dice rolls, those dice will be
  658. rolled (and produce a different value) every time the variable is
  659. used.
  660. Special commands:
  661. - To show the values of all currently assigned variables, type 'vars'.
  662. - To delete a previously defined variable, type 'del VAR'.
  663. - To show this help text, type 'help'.
  664. - To quit, type 'quit'.
  665. '''.strip() + '\n', file=sys.stdout)
  666. def print_vars(env: Dict[str,str]) -> None:
  667. if len(env):
  668. print('Currently defined variables:')
  669. for k in sorted(env.keys()):
  670. print('{} = {!r}'.format(k, env[k]))
  671. else:
  672. print('No variables are currently defined.')
  673. if __name__ == '__main__':
  674. expr_string = " ".join(sys.argv[1:])
  675. if re.search("\\S", expr_string):
  676. try:
  677. # Note: using expr_parser instead of line_parser, because
  678. # on the command line only roll expressions are valid.
  679. expr = expr_parser.parseString(expr_string, True)
  680. result = eval_expr(expr)
  681. print('Result: {result} (rolled {expr})'.format(
  682. expr=color(expr_as_str(expr), EXPR_COLOR),
  683. result=color("{:g}".format(result), RESULT_COLOR),
  684. ))
  685. except Exception as exc:
  686. logger.error("Error while rolling: %s", repr(exc))
  687. raise exc
  688. sys.exit(1)
  689. else:
  690. env: Dict[str, str] = {}
  691. while True:
  692. try:
  693. expr_string = read_roll()
  694. if not re.search("\\S", expr_string):
  695. continue
  696. parsed = line_parser.parseString(expr_string, True)
  697. if 'help' in parsed:
  698. print_interactive_help()
  699. elif 'quit' in parsed:
  700. logger.info('Quitting.')
  701. break
  702. elif 'vars' in parsed:
  703. print_vars(env)
  704. elif 'delete' in parsed:
  705. vname = parsed['varname']
  706. if vname in env:
  707. print('Deleting saved value for "{var}".'.format(var=color(vname, RESULT_COLOR)))
  708. del env[vname]
  709. else:
  710. logger.error('Variable "{var}" is not defined.'.format(var=color(vname, RESULT_COLOR)))
  711. elif re.search("\\S", expr_string):
  712. if 'assignment' in parsed:
  713. # We have an assignment operation
  714. vname = parsed['varname']
  715. if var_name_allowed(vname):
  716. env[vname] = expr_as_str(parsed['expr'])
  717. print('Saving "{var}" as "{expr}"'.format(
  718. var=color(vname, RESULT_COLOR),
  719. expr=color(env[vname], EXPR_COLOR),
  720. ))
  721. else:
  722. logger.error('You cannot use {!r} as a variable name.'.format(vname))
  723. else:
  724. # Just an expression to evaluate
  725. result = eval_expr(parsed['expr'], env)
  726. print('Result: {result} (rolled {expr})'.format(
  727. expr=color(expr_as_str(parsed, env), EXPR_COLOR),
  728. result=color("{:g}".format(result), RESULT_COLOR),
  729. ))
  730. print('')
  731. except KeyboardInterrupt:
  732. print('')
  733. except EOFError:
  734. print('')
  735. logger.info('Quitting.')
  736. break
  737. except Exception as exc:
  738. logger.error('Error while evaluating {expr!r}: {ex!r}'.format(
  739. expr=expr_string, ex=exc,
  740. ))