我正在尝试用Python创建Hi Ho Cherry O游戏。你通过旋转一个随机的旋转器来转弯,它告诉你是否可以在转弯处添加或移除樱桃。像游戏一样,可能的微调结果是:
取出1个樱桃,去掉2个樱桃,去掉3个樱桃,去掉4个樱桃,鸟去樱桃桶(加2个樱桃),狗去看你的樱桃桶(加2个樱桃),洒桶(放回所有10个樱桃)你的树)
我已经想出了如何计算每次旋转的结果,每次转弯后树上樱桃的数量(他必须始终在0到10之间),以及赢得比赛所需的最终转弯次数。但是,我想添加一行代码,在每次游戏获胜后,将迭代游戏100次,然后退出。最后,将计算100场比赛的平均转弯次数。以下是我到目前为止所提供的任何帮助都将不胜感激:
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(">")
答案 0 :(得分:4)
你应该把你的while循环放在for循环中,如下所示:
for i in range(100):
while cherriesOnTree > 0:
etc..
为了计算平均值,在for循环之前创建一个数组,例如:命名转弯。
tot_turns = []
然后,当赢得游戏时,您需要将结果附加到您创建的列表中。
tot_turns.append(turns)
要找到平均值,你可以在for循环后执行类似的操作:
mean_turns = sum(tot_turns)/len(tot_turns)
编辑:我添加了一个有效的示例。请注意,您必须在每次迭代开始时重置turns
和cherriesOnTree
变量。
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(">")