Reputation:
I'm trying to create the Hi Ho Cherry O game in Python. You take a turn by spinning a random spinner which tells you whether you get to add or remove cherries on the turn. Like the game, the possible spinner results are:
Remove 1 cherry, Remove 2 cherries, Remove 3 cherries, Remove 4 cherries, Bird visits your cherry bucket (Add 2 cherries), Dog visits your cherry bucket (Add 2 cherries), Spilled bucket (Place all 10 cherries back on your tree)
I have figured out how to calculate the result of each spin, the number of the cherries on the tree after each turn (his must always be between 0 and 10), and the final number of turns needed to win the game. However, I want to add lines of code which would, after each game is won, iterate the game 100 times and then exit out. Finally, the average number of turns throughout 100 games would be calculated. Here is what I have so far and any help would be much appreciated:
import random
spinnerChoices = [-1, -2, -3, -4, 2, 2, 10]
turns = 0
cherriesOnTree = 10
while cherriesOnTree > 0:
spinIndex = random.randrange(0, 7)
spinResult = spinnerChoices[spinIndex]
print "You spun " + str(spinResult) + "."
cherriesOnTree += spinResult
if cherriesOnTree > 10:
cherriesOnTree = 10
elif cherriesOnTree < 0:
cherriesOnTree = 0
print "You have " + str(cherriesOnTree) + " cherries on your tree."
turns += 1
print "It took you " + str(turns) + " turns to win the game."
lastline = raw_input(">")
Upvotes: 1
Views: 888
Reputation: 7821
You should put your while-loop inside a for-loop, like this:
for i in range(100):
while cherriesOnTree > 0:
etc..
In order to calculate the mean, create an array before the for-loop, e.g. named turns.
tot_turns = []
Then, when the game is won, you need to append the result to the list you created.
tot_turns.append(turns)
To find the mean, you could do something like this after the for loop:
mean_turns = sum(tot_turns)/len(tot_turns)
Edit: I added a working example. Please note that you have to reset the turns
and cherriesOnTree
variables in the beginning of each iteration.
import random
spinnerChoices = [-1, -2, -3, -4, 2, 2, 10]
tot_turns = []
for i in range(100):
cherriesOnTree = 10
turns = 0
while cherriesOnTree > 0:
spinIndex = random.randrange(0, 7)
spinResult = spinnerChoices[spinIndex]
#print "You spun " + str(spinResult) + "."
cherriesOnTree += spinResult
if cherriesOnTree > 10:
cherriesOnTree = 10
elif cherriesOnTree < 0:
cherriesOnTree = 0
#print "You have " + str(cherriesOnTree) + " cherries on your tree."
turns += 1
print "It took you " + str(turns) + " turns to win the game."
tot_turns.append(turns)
mean_turns = sum(tot_turns)/len(tot_turns)
print 'It took you {} turns on average to win the game.'.format(mean_turns)
lastline = raw_input(">")
Upvotes: 4