Fearthepenguin.net

Diary of a Lazy SysAdmin

Skip to: Content | Sidebar | Footer

dice.py

10 August, 2009 (11:04) | Blog | By: ender

Here ladies and gentlemen is the worlds worst dice-rolling program in Python… Ok, maybe it isn’t the worst. But it’s one of my first complete Python programs [or programs of any language] so I’m sure there are lots of ways to improve it. This is a CLI program that will ask you how many dice to roll, and how many sides, then it will print out the results. There are currently no limits set on the number of rolls or sides.

#!/usr/bin/python
# Simple program to roll some dice
# It asks the user how many dice to roll
# as well as how many sides the dice should have
# The results are printed out as text.

import random
from random import randrange
import sys

def diceRoll( NUMBER, SIDES ):
    # To keep indexing simple,
    # DiceList[0] holds which number the roll is
    # For this particular program, this is ignored
    DiceList[0] = DiceList[0] + 1
    for i in range(NUMBER):
          DiceList.append(random.randrange(0,SIDES)+1)
          i+1

def diceChooseNumber():
     # Gotta ask for some input silly...

      RAWNUMBER = raw_input("\nHow many dice would you like to roll? ")

      # Now convert those strings to int
      # while checking to make sure they are valid numbers
      try:
           NUMBER = int(RAWNUMBER)
      except ValueError:
           print "You entered:",RAWNUMBER
           print "Please enter a positive integer next time."
           ## Instead of exiting, ask again
           ## I'm not sure of the safety of doing this with the variable
           #sys.exit()
           NUMBER=diceChooseNumber()

      return NUMBER

def diceChooseSides():
     # Gotta ask for some input silly...

     RAWSIDES = raw_input("\nHow many sides would you like on your dice? ")

     # Now convert those strings to int
     # Eventually need to add a test to make sure
     # user didn't input something stupid

     # while checking to make sure they are valid numbers
     try:
          SIDES = int(RAWSIDES)
     except ValueError:
          print "You entered:",RAWSIDES
          print "Please enter a positive integer next time."
           ## Instead of exiting, ask again
           ## I'm not sure of the safety of doing this with the variable
           #sys.exit()
           SIDES=diceChooseSides()

     return SIDES

def dicePrint():
     COUNT = 1
     while COUNT < len(DiceList):
     print "Die ",COUNT," = ",DiceList[COUNT]
     COUNT = COUNT + 1

def main():
     NUMBER=diceChooseNumber()
     SIDES=diceChooseSides()
     diceRoll(NUMBER,SIDES)
     dicePrint()

if __name__ == '__main__':
     # Assign "DiceList" as a global array
     # With index 0 already assigned
     # this index is ignored in this program
     # but left as a dummy value for ease of indexing
     DiceList = [0]
     main()

Write a comment