Created a simple Dice class and test script for it

This commit is contained in:
2019-01-25 20:28:41 -05:00
parent 305518db00
commit e95de04209
2 changed files with 81 additions and 0 deletions

28
Dice.py Normal file
View File

@@ -0,0 +1,28 @@
#This is a simple dice class. It can be initiated with any positive number of sides
import random
class Dice:
#Setup all the variables needed and the random number generator
def __init__(self, sides = 6):
#Setup the highest number that can be rolled
if(sides < 1):
self.__sides = 6
else:
self.__sides = sides
#Setup the other variables needed
self.__face = 1 #The 'face' of the die that is used for scoring, etc
#Get the number on the face of the die
def getFace(self):
return self.__face
#Get the number of sides on the dice
def getSides(self):
return self.__sides
#Get a new number in face
def roll(self):
self.__face = random.randint(1, self.__sides)
return self.__face

53
testDice.py Normal file
View File

@@ -0,0 +1,53 @@
#A simple script to test the Dice class
from Dice import Dice
#Try giving a negative number of sides
print("Testing for negative number of sides")
die = Dice(-3)
if(die.getSides() != 6):
print("The die should have 6 sides, instead it has " + str(die.getSides()) + " sides.\nTest failed")
else:
print("Test passed")
#Try the default constructor
die = Dice()
if(die.getSides() != 6):
print("\nThe die should have 6 sides, instead it has " + str(die.getSides()) + " sides.\nTest failed")
else:
print("Test passed")
#Try rolling it a few times and making sure the rolls are within expected boundaries
print("Testing the rolls of a default die")
die = Dice()
#Setup an array to keep track of how many times a number has been rolled
rolls = []
for x in range(die.getSides()):
rolls.append(0)
#Roll 100 times the number of sides
for x in range(100 * die.getSides()):
num = die.roll()
rolls[num - 1] += 1 #You add one to the number directly behind the current number. This accounts for starting at subscript 0
#Print the results
cnt = 0
for num in rolls:
print(str(cnt + 1) + ". " + str(num))
cnt += 1
#Try using a many sided die and using the same tests as above
print("Testing the rolls of a die with a large number of sides")
die = Dice(50)
#Setup an array to keep track of how many times a number has been rolled
rolls = []
for x in range(die.getSides()):
rolls.append(0)
#Roll 100 times the number of sides
for x in range(100 * die.getSides()):
num = die.roll()
rolls[num - 1] += 1 #You add one to the number directly behind the current number. This accounts for starting at subscript 0
#Print the results
cnt = 0
for num in rolls:
print(str(cnt + 1) + ". " + str(num))
cnt += 1