2013-10-27 133 views
1

我想用Python創建Hi Ho Cherry O遊戲。你通過旋轉一個隨機微調器來轉彎,告訴你是否在轉彎時添加或移除櫻桃。像遊戲一樣,可能的微調結果如下:在Python中,我如何運行n次迭代的while循環?

刪除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(">") 
+2

爲什麼不把整個東西放在'for'循環中? – Frank

回答

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) 

編輯:我添加了一個工作示例。請注意,您必須在每次迭代開始時重置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(">") 
+0

我想建議您計算平均值,您可以導入numpy,然後使用平均值函數。通過在函數'numpy.mean(lst)'中傳遞列表'lst',這將節省大量時間。 – tilaprimera