Skip to content

Instantly share code, notes, and snippets.

@p7g
Last active September 29, 2019 00:09
Show Gist options
  • Save p7g/25bbecaddf921f221b384691fc5a209d to your computer and use it in GitHub Desktop.
Save p7g/25bbecaddf921f221b384691fc5a209d to your computer and use it in GitHub Desktop.
Dice roller script
#!/usr/bin/env python3
from collections import defaultdict
from secrets import token_bytes
def roll(num_sides: int) -> int:
assert num_sides > 0, 'cannot have no sides'
return int.from_bytes(token_bytes(48), 'little') % num_sides + 1
def distribution(f, *, samples=100_000):
distribution = defaultdict(lambda: 0)
for r in (f() for _ in range(samples)):
distribution[r] += 1
return dict(sorted(distribution.items(), key=lambda i: i[0]))
if __name__ == '__main__':
import sys, re
def exit_with(msg, *, code=1):
print(msg, file=sys.stderr)
exit(code)
if len(sys.argv) < 2:
exit_with('Expected dice expression')
regex = re.compile(
r'^(?P<times>\d+)?' # the number of times to roll, default 1
r'd(?P<sides>\d+)' # the number of sides of the dice to roll
r'(?:\s*\+\s*(?P<add>\d+))?$' # an amount to add to the total rolled
)
result = regex.match(' '.join(sys.argv[1:]))
if not result:
exit_with('Invalid dice expression')
sides, times, add = result.group('sides', 'times', 'add')
sides, times, add = int(sides), int(times or 1), int(add or 0)
total = sum((roll(sides) for _ in range(times)), add)
print(total)
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment