Skip to content

Instantly share code, notes, and snippets.

@ryands
Created November 5, 2011 02:19
Show Gist options
  • Save ryands/1340998 to your computer and use it in GitHub Desktop.
Save ryands/1340998 to your computer and use it in GitHub Desktop.
Dice parser
#!/usr/bin/env python
# Python dice rolling and parsing
# Embed into a bot, service, whatever...
# Was bored...
import random
import re
import sys
from exceptions import ValueError
def roll(sides):
""" Roll a (sides) sided die and return the value. 1 <= N <= sides """
return random.randint(1,sides)
def parse_dice(cmd):
""" Parse strings like "2d6" or "1d20" and roll accordingly """
pattern = re.compile(r'^(?P<count>[0-9]*d)?(?P<sides>[0-9]+)$')
match = re.match(pattern, cmd)
if not match:
raise ValueError() # invalid input string
sides = int(match.group('sides'))
try:
count = int(match.group('count')[:-1])
except:
count = 1
if count > 1:
return [ roll(sides) for i in range(count) ]
else:
return roll(sides)
if __name__=="__main__":
print parse_dice(sys.argv[1])
@treytomes
Copy link

Thanks, this is almost what I was needing. I changed your regex a bit to allow for modifies and remove the need for slicing the count parameter: r'^(?P[0-9]*)?dD(?P[+-][0-9]+)?$'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment