A buddy of mine asked me a couple days ago if it’d be possible to write a program that rolled dice and dealt with the results in a certain way. Seeing this as an opportunity to dabble in some programming I naturally replied that 1) Yes, it’s possible, and 2) I’ll do it for you.
The obvious choice for the job was Python.
Anyway, the task took an embarassingly long time (over 3 hours), but I didn’t feel bad about it considering my limited programming experience. Plus, the old saying about only getting good at programming by doing it is quite true.
At any rate, here’s what I came up with for the basic task, which was to roll 2-9 d6 and add the two highest rolls. From here I’m going to add the ability to provide a second argument that determines how many times the roll with x number of dice will be made. That version will also keep a running average of the totals from each roll.
#!/usr/bin/python
roll -- A dice-rolling application that rolls 2-9 d6
and adds the highest two values.
import sys
import random
Make sure an argument is given when the program is run,
and make sure it's only one (nop).
try:
nop = len(sys.argv)
except:
sys.exit("roll -- A dice rolling application that rolls 2-9 d6 and adds the highest two values.\nUsage: roll .")
if nop != 2:
sys.exit("roll -- A dice rolling application that rolls 2-9 d6 and adds the highest two values.\n\nUsage: roll .")
Take in the number of d6 to be rolled, ensuring something is entered
try:
nod = sys.argv[1]
except:
sys.exit("Usage: roll . \nPlease retry.")
Make sure nod is a number between 2 and 9.
r = range(2,10)
if (int(nod) not in r):
sys.exit("Please enter a number of dice between 2 and 9.")
print "You have rolled " + nod + " dice..."
Roll the dice "nod" number of times
dr = [random.randint(1, 6) for i in xrange(int(nod))]
Print the unsorted list of rolls and then sort the list
print "Your rolls were: " + str(dr)
dr.sort()
Pop off the top two values from the list and store them seperately
highest = dr.pop()
print "Your highest roll was: " + str(highest) + "."
next_highest = dr.pop()
print "Your next highest roll was: " + str(next_highest) + "."
total = highest + next_highest
print "Your total was: " + str(total) + "."