查看了很多现有的问题,并没有看到完全相同的情况。我正在学习 Python 的基础知识,并尝试创建无处不在的石头剪刀布游戏。但是,我有一个等于用户猜测的变量,我无法将其与代表计算机猜测的随机选择的项目进行成功比较。所有的计算结果都是“你赢了!:)”,即使它不应该,这表明两个变量永远不会彼此相等。我尝试使用 str(computer_choice) 但没有任何运气。
这是完整的代码:
import time
import random
rps = ['Rock', 'Paper', 'Scissors']
computer_choice = random.sample(rps, 1)
print("Let's play some Rock, Paper, Scissors")
print("Hit enter when ready:")
input("")
print("Rock...")
time.sleep(1)
print("Paper...")
time.sleep(1)
print("Scissors...")
time.sleep(.75)
print("SHOOT!")
print("Which is it?")
user_choice = input(">>>")
while True:
valid_check = user_choice in rps
if valid_check == True:
break
else:
print('Bad input, try again:')
user_choice = input(">>>")
print("The computer picked: %s" % computer_choice)
if user_choice == computer_choice:
print("It's a draw!")
elif user_choice == 'Rock':
if computer_choice == 'Paper':
print("You lose :(")
else:
print("You win! :)")
elif user_choice == 'Paper':
if computer_choice == 'Scissors':
print("You lose :(")
else:
print("You win! :)")
elif user_choice == 'Scissors':
if computer_choice == 'Rock':
print("You lose :(")
else:
print("You win! :)")
最佳答案
您需要使用返回原始列表元素的random.choice(rps)
,而不是返回列表的random.sample(rps,1)
原始列表中的尺寸 1。
关于Python-将字符串与列表中的随机项目进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37770052/