2017-03-05 55 views
1

嘿,我寫了下面的代碼,一切似乎工作正常,除非它應該是一個平局我不斷得到「name2勝」以及何時答案應該是無效的。我不知道什麼是錯的,因爲我的邏輯看起來是正確的。我的「搖滾,紙,剪刀」代碼有問題

print("Welcome to Rock, Paper, Scissors!") 
print("Let's Begin ...") 
name1 = input("Player 1: What's your name?") 
name2 = input("Player 2: What's your name?") 

print("Hello " + name1 + " and " + name2) 
print(name2 + ": Close your eyes!") 

choice1 = input(name1 + ": enter 'r' for rock, 'p' for paper, and 's' for Scissors: ") 

print("Great choice! Now - cover your answer and ask " + name2 + " to choose. \n\n\n") 
choice2 = input(name2 + ": enter 'r' for rock, 'p' for paper, and 's' for scissors: ") 

if(choice1 == "r" , choice2 == "p"): 
    print(name2 + " wins!") 
elif(choice1 == "r" , choice2 == "s"): 
    print(name1 + " wins!") 
elif(choice1 == "r" , choice2 == "r"): 
    print("It is a draw") 
elif(choice2 == "r" , choice1 == "p"): 
    print(name1 + " wins!") 
elif(choice2 == "r" , choice1 == "s"): 
    print(name2 + " wins!") 
elif(choice1 == "p" , choice2 == "s"): 
    print(name2 + " wins!") 
elif(choice1 == "p" , choice2 == "p"): 
    print("It is a draw!") 
elif(choice2 == "p" , choice1 == "s"): 
    print(name1 + " wins!") 
elif(choice1 == "s" , choice2 == "s"): 
    print("It is a draw!") 
else: 
    print("Invalid asnwer") 


print("Thanks for playing Rock, Paper, scissors") 
+2

哪裏你的想法到把一個逗號你的if語句從何而來? – Soviut

+0

邏輯是正確的,語法也是如此......至少正確的修改不會導致解釋器發生錯誤。您可能想要在if語句中重新查看逗號,這些逗號會導致編譯錯誤。 –

回答

1

你檢查多個條件的整個方法是不正確 -

if(choice1 == "r" , choice2 == "p"): 

需要通過choice1 == "r", choice2 == "p"形成的元組,這將是永遠truthy因爲它不應是空的感實性,所以你永遠不會達到甚至陳述和玩家2將永遠贏。

檢查兩個條件的正確方法是使用and運算符,而括號不是必需的。

if choice == "r" and choice2 == "p": 

修復所有這些條件應該有所幫助。

0

更改 '' 在所有的條件語句是否爲 '和',像這樣:

if choice1 == "r" and choice2 == "p": 
    print(name2 + " wins!") 

注:括號不是必需品。

爲什麼總是得到「name2 wins」?

由於使用逗號,你在創建tuple時,如果不爲空,那麼它將被評估爲true。

0

你可以做到這一點

 

    choice = [choice1, choice2] 
    if(choice == ['r', 'p']): 
     print(name2 + " wins! ") 
    elif(choice == ['r', 'p']): 
     print(name1 + " wins!") 
    elif(choice == ['r', 'r']): 
     print("It is a draw") 
    elif(choice == ['p', 'r']): 
     print(name1 + " wins!") 


相關問題