Skip to content

Instantly share code, notes, and snippets.

@e-eight
Created August 12, 2019 00:51
Show Gist options
  • Save e-eight/333454989c11eccc70fe18ab77eb47a5 to your computer and use it in GitHub Desktop.
Save e-eight/333454989c11eccc70fe18ab77eb47a5 to your computer and use it in GitHub Desktop.
RPG dice roller
import random
import re
import sys
def roll(dices=1, sides=20, modifier=0):
troll = sum(random.randint(1, sides) for dice in range(dices)) + modifier
return troll
def main():
dice_pattern = re.compile(r'(\d*)d(\d*)([+-]?\d*)')
dices = sys.argv[1:]
if not dices:
print(f'1d20: {roll()}')
elif len(dices) == 1:
d = dice_pattern.match(dices[0])
droll = roll(int(d.group(1) or 1), int(d.group(2)), int(d.group(3) or 0))
print(f'{d.group(1) or 1}d{d.group(2)}{d.group(3)}: {droll}')
else:
troll = 0
for dice in dices:
d = dice_pattern.match(dice)
droll = roll(int(d.group(1) or 1), int(d.group(2)), int(d.group(3) or 0))
print(f'{d.group(1) or 1}d{d.group(2)}{d.group(3)}: {droll}')
troll += droll
print(f'Total: {troll}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment