我的“摇滚,纸,剪刀”代码有问题

时间:2017-03-05 01:42:24

标签: python python-3.x

嘿伙计们我已经编写了下面的代码,一切似乎工作得很好,除非它应该是一个平局我一直得到“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")

3 个答案:

答案 0 :(得分:1)

检查多个条件的整个方法不正确 -

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

取得choice1 == "r", choice2 == "p"形成的元组的真实性,这将是真实的,因为它不会是空的,所以你永远不会达到elif陈述,而玩家2将永远胜利。

检查这两个条件的正确方法是使用and运算符,并且不需要括号。

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

修复所有这些条件应该会有所帮助。

答案 1 :(得分:0)

更改'和'的所有if条件中的',',如下所示:

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

注意:括号不是必需品。

为什么你总是得到“name2 wins”?

由于逗号,您在创建tuple的位置,如果不为空,则评估为true。

答案 2 :(得分: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!")