roll.py 26 KB

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