2014-12-25 80 views
0

此代碼,更具體地在第28行,要求用戶有多種選擇。代碼確實起作用,但是這是一個問題,我無法找到適合我的案例的答案(這不會因爲某種原因阻止你們中的一些人拒絕這個問題),無論如何,問題在於它始終要求輸入甚至是我已經告訴它跳到第二個函數(scenario_exit),我沒有在這裏複製,以保持簡單。所以這就是問題,它一直要求我提供輸入,即使是我告訴我停止的時候。雖然不斷要求輸入。不跳到第二功能

因此,太久沒讀過了?代碼循環在「您需要選擇一個選項」,行40

scenario2options =['Approach exit door', 'Check for vital signs'] 
scenario2options_2 =['Shoot him', 'Let him live'] 

def scenario2(response): 
    print response 
    print "Conversation" 
    print "Conversation2" 
    print "Conversation3" 
    print scenario2options 

    decision_sc2 = 1 

    while decision_sc2 == 1: 
     decision_scenario2 = raw_input("> ") 

     if 'Approach exit door' in decision_scenario2: 
      print "Conversation" 
      decision_sc2 = 0 
      dead("Conversation") 
     elif 'Check for vital signs' in decision_scenario2: 
      print "One of them is still alive finish him off, says Lars" 


      print scenario2options_2 

      decision_sc2_2 = 1 

      while decision_sc2_2 == 1: 

       decision2_scenario2 = raw_input("> ") 

       if 'Shoot him' in decision2_scenario2:      
        decision_sc2_2 = 0 
        scenario2_exit("You deliver him a quick dead.") 
       elif 'Let him live' in decision2_scenario2:     
        decision_sc2_2 = 0 
        scenario2_exit("Conversation") 

       else: 
        print "You need to select one option" 
        decision_sc2_2 = 1 

     else: 
      print "You need to select one option" 
+0

使循環提示變成一個帶有可接受響應數組的函數。測試會更容易。 – Ryan

回答

2

'Check for vital signs'if塊中,您不會將decision_sc2設置爲任何不同的值,因此您的外部循環仍會重複。

考慮這樣的功能,使這些東西更容易:

def get_choice(options): 
    while True: 
     print options 
     choice = raw_input('> ').lower() 
     for i, opt in enumerate(options): 
      if opt.lower() in choice: 
       return i 
     print "You need to select one of the given options." 

然後你可以檢查:

if get_choice(scenario2options)==0: # first choice, i.e. Approach exit door 
    ... 
else: # other choice, i.e. Check for vital signs 
    ... 

,而無需嵌套while循環的繼承。

1

你的外部while循環將永遠只能評估其他分支。因此,即使在輸入decision_sc2_2(您需要處理您的變量命名....)之後爲0(無需在輸入的最後一個else子句中始終將其重置爲1),它將循環遍歷再次將外觀重置爲decision_sc2_2,並且「遊戲」繼續。