write code to simulate the game for one player and calculate the number of dice throws required to finish a game. The user should be allowed to specify the number of games simul
It wasn't what you explicitly asked about, but your code is a bit repetitious with all of those if
statements. One thing you can do is to conceptualize a move as consisting of moving by the amount given by the die roll, followed by a "bump" which is 0 for most squares, a positive number for squares where a ladder starts, and a negative number for squares at the top of a snake. A dictionary is the natural data structure for the bumps, with only the negative and positive bumps stored explicitly. The dictionary method get()
can be used to either return the bump if the final square is a key in the dictionary or return the default 0
if it isn't. Then a single game simulation could simply be:
bump = {1:37, 4:10, 9:22, 21:21, 28:56, 51:16, 72:19, 80:19, 17:-10, 54: -20, 63: -4, 64: -4, 87: -51, 92: -19, 95:-20, 98: -19}
def simulateGame():
pos = 0
count = 0
while pos < 100:
roll = random.randint(1,6)
pos += roll + bump.get(pos,0)
count += 1
return count
And the expected number of rolls can be estimated by:
def expectedRolls(trials = 10000):
return sum(simulateGame() for i in range(trials))/trials
Some of the above might involve things that you haven't seen yet, but when you find yourself writing long sections of almost identical code you should if at all possible streamline it. Repetitious code is not pythonic.
If you haven't studied dictionaries yet but have studied lists, you could make bump
an array with 101 items initialized like: bump = [0]*101
(101 zeros) and then have a series of assignment like bump[1] = 37
, bump[4] = 10
, etc. And then replace the line:
pos += roll + bump.get(pos,0)
by the even simpler line:
pos += roll + bump[0]
which in effect says "add to the current position the roll plus any resulting bump"
The code
def expectedRolls(trials = 10000):
return sum(simulateGame() for i in range(trials))/trials
uses a generator expression inside of the sum function. If you aren't familiar with those yet, you can add them in an explicit loop as in the excellent answer of A. Sokol
The code that you have written only rolls the dice one time. You need to keep rolling until you have won the game. It might be best to create a function that plays the game one time and returns the number of dice rolls needed.
def playGame():
counterPosition = 0
numberOfRolls = 0
while (counterPosition < 100):
numberOfRolls += 1
currentDiceroll = diceroll()
print("The currentDiceroll is", currentDiceroll)
counterPosition += currentDiceroll
# your if statements go here
return numberOfRolls
Then you can call this function however many times you want.
totalDiceRolls = 0
for i in range(userInput):
totalDiceRolls += playGame()
avgRolls = totalDiceRolls / userInput