import random
allx = ["rock", "Rock", "paper", "Paper", "Scissors", "scissors"]
rock = ["rock", "Rock"]
paper = ["paper", "Paper"]
scissors = ["Scissors", "scissors"]
robot = ["ROCK!", "PAPER!", "SCISSORS!"]
while True:
print("Let's play rock paper scissors!")
hand = input("Choose one: ")
if hand not in allx:
print("Something went wrong!")
continue
if hand in rock:
print("You choose rock... Let's see what the computer chooses!")
break
elif hand in paper:
print("You choose paper... Let's see what the computer chooses!")
break
elif hand in scissors:
print("You choose scissors... Let's see what the computer chooses!")
break
choice = random.choice(robot)
print("The robot chose " + choice)
现在有了这个,我想看看机器人从列表中选择了什么,将它与用户的选择进行比较,看看他们是否赢了。我问了一个类似的问题,但它没有我需要的。
答案 0 :(得分:1)
我有一些技巧可以让您的代码更短、更易于阅读
第一个提示:您可以使用 string_name.upper() 或 string_example.lower() 来避免创建每个项目都在 lower 和 upper 的列表,只需规范化用户的输入即可。
第二个提示:机器人不需要另一个列表,您不能个性化第一个列表的相同字符串添加感叹号并再次使用 string.upper()。
第三:不需要为每一个选择都写打印句,可以使用字符串的.format()方法
import random
options = ["rock", "paper", "scissors"]
while True:
print("Let's play rock paper scissors!")
human_chose = input("Choose one: ").lower()
if human_chose in options:
print("You choose {}... Let's see what the computer chooses!".format(human_chose))
break
else:
print("Something went wrong!")
robot_chose = random.choice(options)
print("The robot chose: {}".format(robot_chose.upper() + '!'))
现在,为了比较human_chose和robot_chose,你可以这样使用if条件:
if human_chose == robot_chose:
# the == symbols compare bot variables searching for equality
print('You win!')
else:
print('You lose')
对不起,如果我解释太多,我拖延了,也对不起我的英语不好
更正:
if human_choice == 'paper':
if robot_choice == 'rock':
print('you win')
elif robot_chice == 'scissors':
print('you loss')
else:
print('tie')
elif human_choice == 'rock':
if robot_choice == 'scissors':
print('you win')
elif robot_chice == 'paper':
print('you loss')
else:
print('tie')
elif human_choice == 'scissors':
if robot_choice == 'paper':
print('you win')
elif robot_chice == 'rock':
print('you loss')
else:
print('tie')
# or you can do something like:
who_wins = {
'paper': 'rock',
'scissors': 'paper',
'rock': 'scissors'
}
if who_wins[human_choice] == robot_chice:
print('you win')
elif human_choice == robot_chice:
print('tie')
else:
print('you loss')
如果逻辑不好你可以改正,可能长长的ifs句子对你来说更容易理解。