2014-03-03 32 views
0

這是一個螃蟹模擬器。我的while循環有問題。它在哪裏說程序停留在while循環但不運行程序?

while val == True: 

是問題發生的地方。它停留在while循環中,但沒有任何反應。如果您發現任何問題,我將非常感激。 這裏是完整的代碼。 (我曾嘗試來驗證一切)通過程序xval都是False

import time 
import random 
control1 = False 
control2 = True 
x = True 
val = True 
z = True 
def throw(n): 
    for i in range(1,n+1): 
     dice_1 = random.randint(1,6);dice_2 = random.randint(1,6) 
     print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2 
     time.sleep(2) 
    return n 

while z == True: 
    if x == True: 
     while control1 == False: 
      try: 
       amount_1 = int(raw_input("Welcome to crabs.\nHow many times would you like to roll:")) 
       control1 = True 
      except ValueError: 
       print ("Enter a valid number.") 
      throw(amount_1) 
      x = False 
    else: 
     while val == True: 
      roll_again = raw_input("Would you like to roll again: ") 
      if roll_again == "1": 
       val = False 
       while control2 == True: 
        try: 
         amount_2 = int(raw_input("How many times would you like to roll:")) 
         control2 = False 
        except ValueError: 
         print ("Enter a valid number.") 
        throw(amount_2) 
        z = True 
      elif roll_again == "2": 
       val = False 
       exit() 
      else: 
       val = True 
+1

'while z == True' may be''while z' because it's same。不需要'重複檢查'布爾值;)你也應該給你的變量顯式名稱...... – Depado

+0

爲了幫助調試,爲什麼不在每個'if'分支中做一個簡單的'print'? –

+0

Your final else:val = True並不是必需的,因爲val在while val內已經是true:當你說它什麼都不做時,你的意思是說你沒有看到raw_input命令的提示嗎? – sabbahillel

回答

2

你第一次運行之後,但z仍然True。結果,外環繼續滾動。

0

,就把這行:

print z, x, val 

在其下方while語句。

您會看到,在您回答「您是否想再次滾動:」問題與「2」之後,xval都是錯誤的。這意味着它將通過if..else語句的每個部分,並保持循環無限。

0

由於您將該值設置爲False,所以在執行else分支(的if x)之後,它停留在無限循環中。在接下來的迭代中,你會說while val == True,因爲這個語句不是False,並且有沒有其他語句要考慮,所以你運行在一個無限循環中。

要明白我的意思,只要加入一打印statment這裏:

else: 
    print val 
    while val == True: 
     roll_again = raw_input("Would you like to roll again: ") 
     if roll_again == "1": 

現在,我不知道你是否需要所有這些布爾爲您的實際計劃,但如果我要使它工作,我會開始消除我不需要的布爾值。我認爲你的結構太複雜了。

編輯: 這裏有一個建議,使程序更簡單。

import time 
import random 
x = True 
z = True 
def throw(n): 
    for i in range(1,n+1): 
     dice_1 = random.randint(1,6);dice_2 = random.randint(1,6) 
     print "roll",i,", die 1 rolled",dice_1,"and die 2  rolled",dice_2,",total",dice_1+dice_2 
     time.sleep(2) 
    return n 


def ask(x): 
    if x: 
     print "Welcome to crabs." 
    try: 
     amount = int(raw_input("How many times would you like to roll:")) 
    except ValueError: 
     print ("Enter a valid number.") 
    throw(amount) 

while z: 
    ask(x) 
    x = False 
    roll_again = raw_input("Would you like to roll again: ") 
    if roll_again == "1": 
     continue 
    else: 
     break 
+0

非常感謝您的幫助:)) – MrJagsterS

+0

不客氣。如果您的問題得到解答,請確保接受答案。 – runDOSrun