1

我正在尝试用 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(">")
4

1 回答 1

4

您应该将 while 循环放在 for 循环中,如下所示:

for i in range(100):
    while cherriesOnTree > 0:
        etc..

为了计算平均值,在for循环之前创建一个数组,例如命名为turns。

tot_turns = []

然后,当游戏获胜时,您需要将结果附加到您创建的列表中。

tot_turns.append(turns)

要找到平均值,您可以在 for 循环之后执行以下操作:

mean_turns = sum(tot_turns)/len(tot_turns)

编辑:我添加了一个工作示例。请注意,您必须在每次迭代开始时重置turnscherriesOnTree变量。

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(">")
于 2013-10-27T23:30:09.703 回答