roll.py 26 KB

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