Skip to content

Instantly share code, notes, and snippets.

@blacktaxi
Last active July 10, 2017 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blacktaxi/2f23f0b784950a6ee1d6b97f927060d0 to your computer and use it in GitHub Desktop.
Save blacktaxi/2f23f0b784950a6ee1d6b97f927060d0 to your computer and use it in GitHub Desktop.
DnD die roll script
#!/usr/bin/env python
if __name__ == '__main__':
import sys, random, re
roll_re = r'(?P<rolls>\d+)d(?P<die>\d+)((?P<mod>(\+|-)\d+))?'
parsed = re.match(roll_re, sys.argv[1].strip()) if len(sys.argv) == 2 else None
if parsed is not None:
d = parsed.groupdict()
rolls, die, mod = int(d['rolls']), int(d['die']), (int(d['mod']) if d['mod'] is not None else 0)
rng = random.SystemRandom()
roll = sum(rng.randint(1, die) for _ in range(rolls)) + mod
print roll
else:
print '''roll -- a D'n'D-like dice roller. Handy when you need a random number.
USAGE:
> roll 1d6
3
> roll 1d4+5
6
How do the D'n'D rolls work?
1d4+5
/-------------^ ^ ^-----------\\
| | |
number of number of die modifier
rolls faces
In the example above, we throw a 4-faced die one time,
then add 5.
Hint: you can use any number of die faces (unlike in real life).
Enjoy.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment