roll.py 26 KB

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