Exercises for Lesson 17
Exercise: MultiSidedDie
Here is the MultiSidedDie class:
# multiSidedDie.py
#
# Creating our own classes!
import random
class MultiSidedDie:
def __init__(self, n):
self.numSides = n
self.value = 1
def getValue(self):
return self.value
def setValue(self, val):
self.value = val
def roll(self):
self.value = random.randint(1, self.numSides)
def main():
# Die #1 is a 6-sided die
die1 = MultiSidedDie(6)
print("Initial value of die1 (should be 1):", die1.getValue())
die1.roll()
print("New value after rolling die1 (should be random, 1-6):",
die1.getValue())
# Die #2 is a 20-sided die
die2 = MultiSidedDie(20)
print("\nInitial value of die2 (should be 2):", die2.getValue())
die2.setValue(18) # "cheat" and set the die to 18
print("New value after setting die2 to be 18:", die2.getValue())
print("\nNow going to roll die2 a whole bunch. Values should be random, 1-20.")
for i in range(10):
die2.roll()
print("Value of die2:", die2.getValue())
if __name__ == "__main__":
main()