Skip to content

Instantly share code, notes, and snippets.

@triplrrr
Last active May 4, 2020 18:21
Show Gist options
  • Save triplrrr/8e0afcab9acda67b27c5b8d54958cf2c to your computer and use it in GitHub Desktop.
Save triplrrr/8e0afcab9acda67b27c5b8d54958cf2c to your computer and use it in GitHub Desktop.
i rewrote the code from https://gist.github.com/ryands/1340998 and added roll dropping functionality
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_roll(cmd):
pattern = re.compile(r"(?P<count>[0-9]*)?d(?P<sides>[0-9]+)(?P<drops>d[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'))
except:
count = 1
rolls = [ roll(sides) for i in range(count) ]
dropped = []
try:
drops = int(match.group('drops')[1:])
except:
drops = 0
for i in range(drops):
dropped.append(min(rolls))
rolls.remove(min(rolls))
return {
"count": count,
"sides": sides,
"drops": drops,
"total": sum(rolls),
"rolls": rolls,
"dropped": dropped
}
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