我最近开始学习python,并尝试在python 2.7中制作一个简单的游戏,其中计算机随机生成一个1到6之间的数字,而玩家输入一个1到6之间的数字。规则是更大的数字获胜,但除外如果一个人有6个,而另一个人有1个,在这种情况下,拥有1个的人获胜。游戏还应该问第一个问题,如果玩家回答“是”,则游戏将继续。否则它将执行其他过程。但是,当我运行代码时,即使计算机生成的数量更高,也不会向计算机添加任何点。另外,如果我输入no或其他内容,即使我试图获取打印其他代码的代码,代码也会继续启动游戏。
我尝试只使用if else语句而不使用try,除了将开始提示符更改为布尔型语句外。
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
答案 0 :(得分:1)
首先,这句话
if start == "yes" or " yes":
被评估为(start =='yes')或('yes')。由于“是”是一个常数,并且始终为true,因此它将始终为true。相反,请尝试这样做,这样会在评估之前在正面或背面留出空间。
if start.strip() == 'yes':
如果有多个条件,我还会考虑您在其他地方的情况。考虑使用parens以确保代码正在按您期望的方式进行评估。例如,
if (choice1 == 1) and (choice2 == 6):
此外,try\expect
用于记录异常。我不确定您希望在此处记录哪些异常。最好检查用户输入并确保它是数字,而不是依靠try\expect