python - 石头剪刀布总是让我赢
问题描述
我是一名新程序员,正在尝试通过创建一个石头剪刀布游戏来熟悉 if else 语句。我的问题是代码总是让我赢。此外,我的 while 循环实际上不会循环,因此非常感谢您对这些东西的任何帮助。谢谢!:)
编码:
from random import randint
t = ["Rock", "Paper", "Scissors"]
computer = t[randint(0, 2)]
player = False
while player == False:
player = input("Rock, Paper, or Scissors: ").lower()
if player == computer:
print("Computer:" + player.capitalize())
print("Tie!")
elif player == "rock":
if computer == "Paper":
print("Computer: Paper")
print("You lose")
else:
print("Computer: Scissors")
print("You Win!")
elif player == "paper":
if computer == "Scissors":
print("Computer: Scissors")
print("You Lose!")
else:
print("Computer: Rock")
print("You win")
elif player == "scissors":
if computer == "Rock":
print("Computer: Rock")
print("You lose!")
else:
print("Computer: Paper")
print("You Win!")
else:
print("Invalid input. Try again!")
player = False
computer = t[randint(0, 2)]
解决方案
游戏不会重复,因为player == False
在玩家做出选择后,您的条件永远不会成立。它总是包含玩家的最后选择,而不是False
.
不要使用该while
条件,而是允许用户输入类似quit
. 然后在运行其余代码之前检查它,然后跳出循环。
您可以使用random.choice()
来从列表中选择一个项目,而不是randint()
.
计算机的选择需要在循环中。否则,玩家总是可以获胜,因为计算机的选择永远不会改变。
from random import choice
t = ["Rock", "Paper", "Scissors"]
while True:
player = input("Rock, Paper, Scissors, or quit: ").lower()
if player == 'quit':
break
computer = choice(t)
if player == computer:
print("Computer:" + player.capitalize())
print("Tie!")
elif player == "rock":
if computer == "Paper":
print("Computer: Paper")
print("You lose")
else:
print("Computer: Scissors")
print("You Win!")
elif player == "paper":
if computer == "Scissors":
print("Computer: Scissors")
print("You Lose!")
else:
print("Computer: Rock")
print("You win")
elif player == "scissors":
if computer == "Rock":
print("Computer: Rock")
print("You lose!")
else:
print("Computer: Paper")
print("You Win!")
else:
print("Invalid input. Try again!")
推荐阅读
- laravel - 如何仅忽略标题形式的第一页
- python - jay 文件格式是否特定于 Python 数据表?
- collections - Binding 现已弃用的 Collection 一致性的干净替代方案?
- python-3.x - 尝试编写文本换行函数,但代码在所需输出后显示几个空行
- apache-spark-sql - 当 arrays_zip 数据源自嵌套时,Spark DataFrame 的输出将列名替换为“0”、“1”
- c++ - 无法增加 QToolButton 的大小(按钮样式设置为 Qt::ToolButtonTextBesideIcon)
- r - 如何使用 for 循环将所有股票价格乘以各自的单位数后求和?
- mysql - 为 Mysql 8.0 构建 docker 容器失败
- sql - 将部分结果放入列而不是行
- canvas - 同一页面的按钮点击不断触发CustomPaint的油漆颤动