请有人告诉我如何做一个基本的评分系统进入这个代码。在
import random
print 'Welcome to Rock, paper, scissors!'
firstto=raw_input('How many points do you want to play before it ends? ')
playerscore=+0
compscore=+0
while True:
choice = raw_input ('Press R for rock, press P for paper or press S for scissors, CAPITALS!!! ')
opponent = random.choice(['rock', 'paper' ,'scissors' ])
print 'Computer has chosen', opponent
if choice == 'R' and opponent == "rock":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'P' and opponent == "paper":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'S' and opponent == "scissors":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'R' and opponent == "paper":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'P' and opponent == "scissors":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'S' and opponent == "rock":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'P' and opponent == "rock":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
elif choice == 'S' and opponent == "paper":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
elif choice == 'R' and opponent == "scissors":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
print 'Player score is',playerscore
print 'Computer score is',compscore
if playerscore == firstto:
'You won the game :)'
exit()
elif compscore == firstto:
'You lost the game :('
exit()
问题出在第3行的
raw_input
。raw_input
总是返回一个字符串,而您需要的是一个int。如果您将第3行改为:你的代码会起作用的。在
要清理用户输入(这样当用户输入
"hello"
而不是5
时,代码不会崩溃),可以将raw_input
调用包装到try
,except
语句中。在例如:
^{pr2}$另外,您的代码被困在一个无限循环中,因为您在与整数比较时使用了
^{3}$raw_input
提供的字符串。这将始终返回False:修改第一个原始输入值。你得到了一根绳子。在
为了获得更好的结果,还需要验证输入:-)
这将只接受带数字的字符串。即使有人给出的输入是“5.0”,也会被忽略。在
要更好地阅读原始输入,请单击here。要了解有关内置字符串方法的更多信息,请阅读here。在
附言:这与问题无关。但有一点建议。你的代码可以简化得多。如果您正在学习,请将此代码保留为v0.1并在您的进度时更新它。在
有很多方法可以优化这段代码,但是您当前的问题是
raw_input
和点的入口。这将返回一个字符串,而您需要一个int
。用int()
包起来,你就没事了。也就是说,直到有人输入了一个无法解析的东西。在如果你不想去优化你的代码:
^{pr2}$相关问题 更多 >
编程相关推荐