python - 骰子游戏得分和开始不起作用
问题描述
我最近开始学习 python,并试图在 python 2.7 中制作一个简单的游戏,其中计算机随机生成一个介于 1 和 6 之间的数字,而玩家输入介于 1 和 6 之间的数字。规则是大数字获胜,除非一个人有6个,另一个有1个,在这种情况下,拥有1个的人获胜。游戏还应该问第一个问题,如果玩家回答“是”,那么游戏将继续。否则它将执行其他过程。然而,当我运行代码时,即使计算机生成的数字更高,它也不会为计算机添加任何积分。此外,如果我输入 no 或其他内容,即使我试图让代码打印一些其他行,代码也会继续启动游戏。
我尝试只使用 if else 语句而不使用 try 和 except 以及将开始提示更改为布尔语句。
import random as r
score1 = 0
score2 = 0
start = raw_input("Would you like to start a new game")
if start == "yes" or " yes":
print "Choose a number between 1 and 6"
print "Enter stop to end game"
choice1 = raw_input("Pick a number")
choice2 = r.randint (1,6)
while choice1 != "stop":
try:
if choice1 > choice2:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
elif choice2 > choice1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
except:
if choice1 == 1 and choice2 == 6:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
else:
if choice1 == 6 and choice2 == 1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
print "Final score is: " + str(score1) + " and Computer is: " + str(score2)
elif start == "no" or " no":
print "Maybe another time"
else:
print "Please enter yes or no"
start = raw_input("Would you like to start a new game")
程序输出:
Would you like to start a new game no
Choose a number between 1 and 6
Enter stop to end game
Pick a number1
The computer picked: 2
Pick a number1
The computer picked: 4
Pick a number1
The computer picked: 5
Pick a number1
The computer picked: 3
Pick a numbersotp
The computer picked: 2
Pick a numberstop
Final score is: 5 and Computer is: 0
Process finished with exit code 0
解决方案
首先,这个说法
if start == "yes" or " yes":
评估为 (start == 'yes') 或 ('yes')。由于“是”是一个常数并且始终为真,因此它将始终评估为真。相反,试试这个,它会在评估之前从前面或后面去掉空格。
if start.strip() == 'yes':
如果有多个条件,我也会看看你所在的其他地方。考虑使用括号来确保代码按预期进行评估。例如,
if (choice1 == 1) and (choice2 == 6):
此外,try\expect
用于异常记录。我不确定您希望在此处记录哪些异常。可能更好地检查用户输入并确保它是一个明确的数字而不是依赖于try\expect
推荐阅读
- r - R Shiny - 具有相同 id 的多个单选按钮/向单选按钮组添加标头
- php - 在 foreach 循环中将数字递增 1 到 10
- jenkins-pipeline - Jenkinsfile - 匹配多个标签的代理
- swift - 编辑为真或假时更改目标视图控制器
- php - 从平面数组php创建父子
- oop - 是否总是需要在子类中创建新实例才能使用超类的属性?
- java - Eclipse RCP 获取部件实例
- sql - 如何显示部门编号、部门名称和员工编号?
- ruby - 在 Heroku 上找不到用于 Ruby on Rails 的 Selenium 的 Chrome 二进制文件
- azure - VM 仍然会产生计算费用,即使它已“停止”?