364 Dice Roller

Dice Roller — 364[Easy]

Simple challenge today, The goal is to create a dice rolling script. I decided to make it command line argument driven, so I had to import sys

I imported random, as I do not know how to create pseudo random numbers properly.

Last, but probably the most important, I have imported re for regular expressions. This is needed to validate input, as I need to make sure it’s any amount of numbers, followed by a “d” and another set of numbers.

Short rundown of what the script does.

  • Check command line arguments, if only 1 (the script name) display help text
  • Loop through all provided arguments. If the argument passes the regex validation continue to the roll
  • Split the string on the “d” character to get your faces and how many dice there are.
  • Start a running total, and randomly get a number for how many faces the die has, and add them to that total
  • Repeat for how many dice you have and print the result.

Here is the code I came up with:


import re
import sys
import random

def Roll(inStr):
	l = inStr.split("d")
	howMany = l[0]
	faces = l[1]

	i=0
	total = 0
	while i < int(howMany):
		total += random.randint(1, int(faces))
		i += 1

	print str(inStr) + " :: " + str(total)


if __name__ == "__main__":	
	if(len(sys.argv) == 1):
		print "Example: 3d6 to roll 3x 6 sided dice"
	else:
		p = re.compile("\d*d\d*")

		for r in sys.argv[1:]:
			if(p.match(str(r.lower()))):
				Roll(r.lower())
			else:
				print "invalid input: " + str(r)