我仍然是python的初学者,因此我决定制作一款摇滚纸质游戏。由于某种原因,当用户或计算机获胜时,直到下一轮才给他们分数。
import random
games = int(input("")) #how many games
usersc = 0
compsc = 0
for x in range(games):
score = (str(usersc) + "-" + str(compsc))
user = input("") #ROCK, PAPER, SCISSORS
comp = random.randint(0,2)
if user == 'ROCK':
if comp == 0:
print("tie " + score)
elif comp == 1:
compsc += 1
print("loss " + score)
else:
usersc += 1
print("win " + score)
elif user == 'PAPER':
if comp == 0:
usersc += 1
print("win " + score)
elif comp == 1:
print("tie " + score)
else:
compsc += 1
print("loss " + score)
elif user == 'SCISSORS':
if comp == 0:
compsc += 1
print("loss " + score)
elif comp == 1:
usersc += 1
print("win " + score)
else:
print("tie " + score)
else:
print("try again")
if compsc > usersc:
print("loss")
elif usersc > compsc:
print("win")
else:
print("tie")
例如,当计算机获胜时,它说损失0-0,应该说损失0-1,但是在下一轮它会说0-1。任何帮助,将不胜感激。
问题来源:stackoverflow
问题是在将分数增加之前将分数存储在变量中,因此您总是落后1个游戏。确保分数始终正确的最简单方法是创建一个函数来获取分数,如下所示:
def get_score():
return str(usersc) + "-" + str(compsc)
这样可以确保始终使用最新的用户和comp得分值。使用这个代码变成...
import random
games = int(input("")) #how many games
usersc = 0
compsc = 0
def get_score():
return str(usersc) + "-" + str(compsc)
for x in range(games):
user = input("") #ROCK, PAPER, SCISSORS
comp = random.randint(0,2)
if user == 'ROCK':
if comp == 0:
print("tie " + get_score())
elif comp == 1:
compsc += 1
print("loss " + get_score())
else:
usersc += 1
print("win " + get_score())
elif user == 'PAPER':
if comp == 0:
usersc += 1
print("win " + get_score())
elif comp == 1:
print("tie " + get_score())
else:
compsc += 1
print("loss " + get_score())
elif user == 'SCISSORS':
if comp == 0:
compsc += 1
print("loss " + get_score())
elif comp == 1:
usersc += 1
print("win " + get_score())
else:
print("tie " + get_score())
else:
print("try again")
if compsc > usersc:
print("loss")
elif usersc > compsc:
print("win")
else:
print("tie")
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。