Recall that we created a class to model a multi-sided die. The code for the class is below.
from random import randrange class MSDie: def __init__(self, sides): self.sides = sides self.value = 1 def roll(self): self.value = randrange(self.sides) + 1 def getValue(self): return self.value
a. Before we experiment with the code, let’s play with the
randrange function. Open up the shell in Thonny and run the following.
>>> from random import randrange >>> randrange(0, 5)
b. Try repeatedly typing
randrange(0, 5) to see what it generates. Does it ever generate the number 0? What about 5?
c. Try changing the parameters to other numbers to make sure you understand what it is doing.
d. Copy and paste the above class into a file named
yahtzee.py and create a
main() function that creates two six-sided dice, rolls them, and prints off their individual values and their sum. (Remember that to create an
MSDie object, you must use do something like
d4 = MSDie(4) which creates a single die with four sides. Initially the die has a value of 1, and to randomize its value you must call the
roll() method. To do this, you would do something like
e. Modify your
yahtzee.py program so that the main function creates five six-sided
MSDie objects, rolls them all, and then prints out the values of the five dice individually.
f. Modify your program so that it asks the user if they’d like to re-roll any of the dice, and if so, which ones. (They should be allowed to select up to five of them.) Then it should re-roll only the selected dice and reprint their values.
g. Modify your program so that it does this three times (preferably in a loop).