开发者社区> 问答> 正文

为什么分数显示不正确?

我仍然是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

展开
收起
is大龙 2020-03-24 22:42:44 674 0
1 条回答
写回答
取消 提交回答
  • 问题是在将分数增加之前将分数存储在变量中,因此您总是落后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

    2020-03-24 22:42:52
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载