roll.py 30 KB

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