Created
November 5, 2011 02:19
-
-
Save ryands/1340998 to your computer and use it in GitHub Desktop.
Dice parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]+)?$'