Skip to content

Instantly share code, notes, and snippets.

@soggychips
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soggychips/5d76ad672cca2774627d to your computer and use it in GitHub Desktop.
Save soggychips/5d76ad672cca2774627d to your computer and use it in GitHub Desktop.
#! /usr/bin/python2.7
from random import seed, randint
from re import findall, match
def parse_input(_input):
_input = _input.lower()
# quit if requested
if findall('exit|quit', _input.lower()):
import sys
sys.exit()
# Check for validity:
# 1. If one integer X is given, assume 1dX (e.g. 100).
# 2. Only integers and "d"
# 3. Can not roll a die with zero sides
# 4, Only one "d" allowed
check = match('[0-9]+[d][1-9]+[0-9]*', _input)
# Validity checks 2-4
if check and check.group() == _input:
nums = [int(num) for num in _input.split('d')]
# Validity Check 1
elif not findall('[^0-9]', _input):
nums = [1, int(_input)]
else:
return
return int(nums[0]), int(nums[1])
def roll_die(number_of_sides):
seed()
return randint(1, number_of_sides)
def roll_dice(num_of_dice, num_of_sides):
return [ str(roll_die(num_of_sides)) for dice in range(num_of_dice) ]
def prompt_user(prompt_string=None):
if prompt_string:
print prompt_string
return raw_input(">> ")
def print_roll(_input, roll):
print "---"*3
print "Rolling %s" % _input
print ", ".join(roll)
def welcome_message(name):
print "-"*40
print "-"*40
print "> Time to roll some dice, %s." % name
print "> Enter a roll."
print "> e.g. 2d6, 1d20, 3d12, etc."
print "> Tip: Entering a single number (e.g. 100) will roll 1 die that size"
print "> Type 'exit' or 'quit' to quit."
print "-"*40
print "-"*40
def main():
name = raw_input("What is your name?\n> ")
welcome_message(name if name else 'nerd')
prompt_string = None
while True:
try:
_in = prompt_user(prompt_string)
roll_input = parse_input(_in)
if roll_input:
roll = roll_dice(*roll_input)
print_roll(_in, roll)
prompt_string = None
else:
prompt_string = "Invalid roll. Try again."
except KeyboardInterrupt:
print "\n> Type 'exit' or 'quit' to quit."
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment