2014-10-11 163 views
0

[解決]這是一個愚蠢的錯字。抱歉。Python骰子游戲錯誤

我目前正在學習python,並且遇到一些錯誤,如果你能指出我如何修復它們,以及爲什麼它們會是很好的錯誤,因爲我通過試驗和錯誤學習這樣的項目。 錯誤;

Would you like one or two die?2 
Traceback (most recent call last): 
    File "diceRoller.py", line 34, in <module> 
    rollDice2(); 
    File "diceRoller.py", line 18, in rollDice2 
    result = random.randrage(2,13) 
AttributeError: 'module' object has no attribute 'randrage' 

我的代碼;

import random 
import time 

numDice = input("Would you like one or two die?") 
if (numDice == 1): 
    rollDice1(); 
else: 
    rollDice2(); 

def rollDice1(): 
    result = random.randrange(1,7) 
    print ("It landed on..") 
    time.sleep(1) 
    print(result) 
    try: 
     answer = input("would you like to play again? [y/n]") 
    except: 
     pass 
    if answer in ('y','Y'): 
     return True 
    return False 

def rollDice2():   
    result = random.randrange(2,13) 
    print ("It landed on..") 
    time.sleep(1) 
    print(result) 
    try: 
     answer= input("would you like to play again? [y/n]") 
    except: 
     pass 
    if answer in ('y', 'Y'): 
     return True 
    return False 

while rollDice1 or rollDice2(): 
    continue 
+2

這是一個錯字。它應該是:'result = random.randrange(2,13)' – bernie 2014-10-11 00:16:37

+0

謝謝,我想它睡覺的時間都是這個問題嗎? – 2014-10-11 00:19:43

+0

另外,我想你應該在調用它們之前先定義你的方法。並使用主要方法來測試它們。 – 2014-10-11 00:20:17

回答

1
def rollDice1(): 
    result = random.randrange(1,7) 
    print ("It landed on..") 
    time.sleep(1) 
    print(result) 

def rollDice2(): 
    result = random.randrange(2,13) 
    print ("It landed on..") 
    time.sleep(1) 
    print(result) 

def main(): 
    while True: 
     numDice = input("Would you like one or two die?") 
     if numDice == "1": 
      rollDice1() 
      break 
     elif numDice == "2": 
      rollDice2() 
      break 
     else: 
      print("Invalid choice") 
    while True: 
     answer = input("would you like to play again? [y/n]").lower() 
     if answer == "y": 
      main() 
     elif answer == "n": 
      print ("Goodbye") 
      break 
     else: 
      print("Invalid choice") 
main() 
+0

感謝您的解決方案,我要求你解釋的唯一事情就是你使用主函數,正如我所說的我仍然學習,我從來沒有遇到過,它是否像任何其他功能一樣工作?另外如果我想我可以加入;如果回答==「Y」或「Y」遇到,如果有人正在使用大寫鎖定。 – 2014-10-11 10:20:25

+0

基本上,主函數只是處理輸入並根據輸入調用必要的函數,while循環會一直循環直到用戶輸入正確的數據,當我們調用rollDice 1或2時,我們需要添加一箇中斷,我們得到結果並詢問用戶他們是否想在第二次再玩一次 – 2014-10-11 10:29:28

+0

沒關係,如果「y」或「Y」我沒有看到.lower( )這是一個非常聰明的主意! – 2014-10-11 10:38:30