【问题标题】:High score code not saving scores properly高分代码未正确保存分数
【发布时间】:2018-11-05 22:39:18
【问题描述】:

我将此代码作为更大的骰子游戏程序的一部分,以将高分保存在单独的文件中(以及正常的获胜分数文件),但它总是保存高分,无论它是更高还是更低,也不会' t 将其保存在 Winning_scores 文件中 它还以 ('Name: ', 'John', 'Score: ', '10', '\n') 的形式保存它,而不是单独保存变量,因为 str 因为否则我得到 'write() argument must be str, not tuple' 我也不太确定如何解决

tot1 = 5
tot2 = 1
name1 = ('John')
while True: #Code to find & print the winner
    if tot1 > tot2:
        print("Player 1 is the winner!")
        #Opens file & appends the winning score at the end of it
        tot1 = str(tot1)#Turns the score into a str
        win_score = open("Winning_scores.txt", "a")
        winner = ("Name: "+name1+" Score: "+tot1)
        win_score.write(winner)
        win_score.write("\n")
        win_score.close()
        print("Score saved.")
        hisc = open("Winning_scores.txt", "w+")
        highscore = hisc.read()
        highscore_in_no = (highscore)
        highscore_in_no = highscore_in_no
        if tot1 > highscore_in_no:
            print("Exceeded high score.")
            highscore_in_no = tot1
            hiscore = open("High_scores.txt", "a")
            winner = ("Name: ",name1,"Score: ",tot1,"\n")
            hiscore.write(winner)
            hiscore.close()
            print("High score saved.")
            break

【问题讨论】:

    标签: python file-handling


    【解决方案1】:

    你的获胜者变量是一个元组,而不是一个字符串。

    为了使用hiscore.write(winner),获胜者应该是一个字符串,如下所示:

    winner = "Name: " + name1 + "Score: " + tot1 + "\n"
    

    或更好的可读性:

    winner = "Name: {name1} Score: {tot1}\n".format(**locals())
    

    您还可以将现有的获胜者元组加入字符串:

    hiscore.write(' '.join(winner))
    

    【讨论】:

      【解决方案2】:

      这是你的问题:

      winner = ("Name: "+name1+" Score: "+tot1)
      win_score.write(winner)
      

      当你在 Python 中用括号包裹一个值时,你说它是一个 元组,有点类似于列表。这是一个希望更清楚的例子

      one = "foo"
      two = "bar"
      this_is_a_tuple = (one, two)
      this_is_also_a_tuple = (one)
      this_is_not_a_tuple = one + two
      this_is_a_tuple = (one + two)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多