roll.py 27 KB

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