首页 > 解决方案 > 将高分保存在游戏的文本文件中

问题描述

我创建了一个小游戏。我想将 3 个最高分保存在一个文本文件中,并在游戏结束后显示它们。我创建了一个包含以下内容的文本文件:(0 0 0应该代表你第一次玩游戏之前的状态)。我创建了 2 个函数update_highscores()display_highscores(),但完成游戏后没有任何反应。获得的分数不存储在文本文件中,游戏结束后不显示高分。如何保存和显示高分?

def update_highscores():
    global score, scores
    file = "C:\Programmieren\Eigene Spiele\Catch The Bananas\highscores.txt"
    scores=[]
    with open(filename, "r") as file:
        line = file.readline()
        high_scores = line.split()

    for high_score in high_scores:
        if (score > int(high_score)):
            scores.append(str(score) + " ")
            score = int(high_score)
        else:
            scores.append(str(high_score) + " ")

    with open (filename, "w") as file:
        for high_score in scores:
            file.write(high_score)


def display_highscores():
    screen.draw.text("HIGHSCORES", (350,150), fontsize=40, color = "black")
    y = 200
    position = 1
    for high_score in scores:
        screen.draw.text(str(position) + ". " + high_score, (350, y), color = "black")
        y = y + 25
        position = position + 1

标签: python

解决方案


update_highscores如果您更改,代码应该可以正常工作

file = "C:\Programmieren\Eigene Spiele\Catch The Bananas\highscores.txt"

filename = r"C:\Programmieren\Eigene Spiele\Catch The Bananas\highscores.txt"

更改的两件事是:更改filefilename,否则此代码将引发异常,因为filename未定义。我想它应该是这样的。我更改的第二件事是r在字符串之前添加一个,以便按字面解释反斜杠。另外两个也可以使用的选项是:

"C:\\Programmieren\\Eigene Spiele\\Catch The Bananas\\highscores.txt"

或者

"C:/Programmieren/Eigene Spiele/Catch The Bananas/highscores.txt"

请记住,非原始字符串中的单个反斜杠通常会尝试转义下一个字符。

除此之外,只需确保该文件存在,并且它包含0 0 0,或由空格分隔的任何字符序列。如果文件未正确初始化,则不会有任何分数要替换。

这段代码对我有用,所以如果还有问题,只是显示分数。他们在文件中更新就好了。但我不知道你使用的是什么库screen,所以我无法测试。

哦,还有:确保你真的在调用这个函数。我假设它在您的代码中的其他地方,而您只是省略了它。显然,如果您不调用该函数,您的代码将无法工作。

这是我的有效代码。只需替换路径highscores.txt并自行运行此代码。如果可行,则问题出在您的代码中的其他地方,除非您向我们提供更多代码,否则我们将无法为您提供帮助。

score = int(input("Enter new score: "))
scores = []

def update_highscores():
    global score, scores
    filename = r"path\to\highscores.txt"
    scores=[]
    with open(filename, "r") as file:
        line = file.readline()
        high_scores = line.split()

    for high_score in high_scores:
        if (score > int(high_score)):
            scores.append(str(score) + " ")
            score = int(high_score)
        else:
            scores.append(str(high_score) + " ")

    with open (filename, "w") as file:
        for high_score in scores:
            print(high_score)
            file.write(high_score)


update_highscores()
input()

推荐阅读