Skip to content

Instantly share code, notes, and snippets.

@kupiakos
Created January 13, 2018 21:26
Show Gist options
  • Save kupiakos/9906715ebf5cc4aac0b5eda3817c4bd5 to your computer and use it in GitHub Desktop.
Save kupiakos/9906715ebf5cc4aac0b5eda3817c4bd5 to your computer and use it in GitHub Desktop.
Dice roll in the d20 format
import re
from operator import pos, neg
from random import randint
def rolld20(fmt):
"""Perform a dice roll in the d20 format (e.g. 5d8-3)"""
x = 0
op = pos
for part in re.findall(r'(\d*d\d+|\d+|\+|-)', fmt):
if 'd' in part:
mult, die_n = part.split('d')
mult = int(mult or 1)
die_n = int(die_n)
x += op(sum(randint(1, die_n) for _ in range(mult)))
elif part[0].isdigit():
x += op(int(part))
op = pos
if part == '-':
op = neg
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment