2014-02-12 51 views
2

嗨,我正在做剪刀石頭布的遊戲,我做了下面的腳本至今:,石頭,剪刀(蟒蛇3.3)

def main(): 
    from random import randint 
    UserChoices = input("'rock', 'paper' or 'scissors'? \n Input: ") 
    if UserChoices == "rock": 
     UserChoice = 1 
    elif UserChoices == "paper": 
     UserChoice = 2 
    elif UserChoices == "scissors": 
     UserChoice = 3 
    CpuChoice = randint(1,3) 
    if UserChoice == CpuChoice: 
     print("DRAW!") 
    elif UserChoice == "1" and CpuChoice== "3": 
     print("Rock beats scissors PLAYER WINS!") 
     main() 
    elif UserChoice == "3" and CpuChoice== "1": 
     print("Rock beats scissors CPU WINS") 
     main() 
    elif UserChoice == "1" and CpuChoice== "2": 
     print("Paper beats rock CPU WINS!") 
     main() 
    elif UserChoice == "2" and CpuChoice== "1": 
     print("paper beats rock PLAYER WINS!") 
     main() 
    elif UserChoice == "2" and CpuChoice== "3": 
     print("Scissors beats paper CPU WINS!") 
     main() 
    elif UserChoice == "3" and CpuChoice== "2": 
     print("Scissors beats paper PLAYER WINS!") 
     main() 
    elif UserChoice == "1" and CpuChoice== "2": 
     print("cpu wins") 
     main() 
    else: 
     print("Error: outcome not implemented") 
main() 

但是當我運行它,我得到我所做的錯誤「錯誤:結果未執行」有人可以告訴我爲什麼這是?謝謝。

+5

'UserChoice'和'CpuChoice'設置爲整數,然後將它們與字符串進行比較。 –

+1

在其他地方,做一個打印的值,你會爲什麼 –

+1

不相關的問題,但我建議你映射ramdom數字字符串,而不是其他方式。 –

回答

2

這和所有其他的比較類似於它:

elif UserChoice == "1" and CpuChoice == "3": 

...應該是:

elif UserChoice == 1 and CpuChoice == 3: 

換句話說,你應該int s爲單位進行比較,而不是int S, int現在正在發生的字符串。

+1

謝謝你不能相信它是那麼簡單! –

2

用戶選擇設置爲整數,但是您將其與字符串進行比較。它應該如下

if userChoice == 1: #Note no quotation marks 

此外,您允許CPU從3個整數中選擇,它可以工作。然而,它可以節省線路和更有效的是從陣列

CPU_Moves = ['Rock','Paper','Scissors'] 
cpuchoice = random.choice(CPUMoves) 

選擇隨機這將設置cpuchoice從數組隨機的一個,然後可以用它在用戶輸入到比較cpuchoice。這意味着你根本不需要設置userChoice,你可以使用用戶直接輸入的內容。

0

從if if語句中刪除引號。條件是尋找一個字符串進行比較,而石頭紙和剪刀被分配爲整數。這些處理方式不同。你需要改變你的if elif,不要在數字周圍加引號。它會打印出DRAW,因爲它比較類似的項目,它給出錯誤,因爲它不是相同的變量類型。

1

正如前面的答案所說,你最終將一個字符串與一個整數進行比較。 避免使用這麼多的條件是個好主意。下面是一個「精簡版」我已經寫了,如果你有興趣:

from random import randrange 

def RPS(user_choice = ''): 
    choices = ('rock', 'paper', 'scissors') 
    results = ('Draw!', 'You Win!', 'Cpu Wins!') 
    while user_choice not in choices: 
     user_choice = input("Choose: rock, paper or scissors? ") 
    user_num = choices.index(user_choice) 
    cpu_num = randrange(3) 
    diff = (user_num - cpu_num) % 3 
    print("You chose:", user_choice, "-", "Cpu chose:", choices[cpu_num]) 
    print(results[diff]) 

RPS('rock') # User choice can be passed as an argument. 

注意如何計算用減法和模操作的贏家。在Rock,paper,scissors,lizzard,Spock遊戲中,這更有用,其中有5個選項,而不是3個。