保存游戏高分记录到文本文件中

2024-04-25 09:17:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个小游戏。我想保存在一个文本文件中的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

Tags: infordefdisplaypositionupdate分数file
1条回答
网友
1楼 · 发布于 2024-04-25 09:17:09

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

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

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

更改的两件事是:将file更改为filename,否则此代码会引发异常,因为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()

相关问题 更多 >