保存游戏高分记录?

9

我用pygame在Python中制作了一个非常简单的游戏。得分是基于玩家达到的级别。我把级别作为名为score的变量。我想在游戏开始或结束时显示最高级别。

我甚至更愿意显示多个分数,但我看到的所有其他帖子对我来说都太复杂了,所以请保持简单:我是个初学者,只需要一个分数。


Python 2 还是 Python 3? - Blorgbeard
你有什么问题?是什么阻止了你打印 print(score) - elyase
2.7.4,我的问题是希望在程序关闭后能够再次显示分数。 - Kevin Klute
换句话说,您想能够从过去的会话中加载分数? - Ben Schwabe
6个回答

11

我建议您使用shelve。例如:

import shelve
d = shelve.open('score.txt')  # here you will save the score variable   
d['score'] = score            # thats all, now it is saved on disk.
d.close()

下次打开程序时,请使用:

import shelve
d = shelve.open('score.txt')
score = d['score']  # the score is read from disk
d.close()

它将从磁盘中读取。如果您希望以同样的方式保存得分列表,可以使用此技术。


我想我明白了,我的唯一问题是如何用“键”来定义某个东西。你能否发布一两行示例代码,展示该.txt文件应该是什么样子的? - Kevin Klute
@KevinKlute,没有什么需要定义的,它只是起作用了,试一下吧!键名“score”是由您选择的。我本可以使用d['saved_score']。当然,要想稍后检索它,您需要使用与保存时相同的名称。该文件是自动创建的,但它不是文本格式,而是一种特殊的Python格式来保存变量。 - elyase
我运行了你的代码,只是替换了我的文件名,但是出现了“无法确定数据库类型”的错误。很抱歉让你烦恼了,但我真的无法解决这个问题。 - Kevin Klute
好的,感谢您的帮助!我明白了,我需要使用d.close方法。 - Kevin Klute

8
你可以使用 pickle 模块将变量保存到磁盘并重新加载它们。
示例:
import pickle

# load the previous score if it exists
try:
    with open('score.dat', 'rb') as file:
        score = pickle.load(file)
except:
    score = 0

print "High score: %d" % score

# your game code goes here
# let's say the user scores a new high-score of 10
score = 10;

# save the score
with open('score.dat', 'wb') as file:
    pickle.dump(score, file)

这将一个分数保存到磁盘中。pickle的好处是,您可以轻松地扩展它以保存多个分数 - 只需将scores更改为数组而不是单个值即可。pickle几乎可以保存您提供的任何类型的变量。


除了 pygame 的 Surfaces 外。由于某种原因,我在将 surfaces 进行 pickling 时遇到了很多麻烦。不确定为什么... - Ben Schwabe

2
您可以使用字典来保存您的最高分,并将其简单地写入文件中:
def store_highscore_in_file(dictionary, fn = "./high.txt", top_n=0):
    """Store the dict into a file, only store top_n highest values."""
    with open(fn,"w") as f:
        for idx,(name,pts) in enumerate(sorted(dictionary.items(), key= lambda x:-x[1])):
            f.write(f"{name}:{pts}\n")
            if top_n and idx == top_n-1:
                break

def load_highscore_from_file(fn = "./high.txt"):
    """Retrieve dict from file"""
    hs = {}
    try:
        with open(fn,"r") as f:
            for line in f:
                name,_,points = line.partition(":")
                if name and points:
                    hs[name]=int(points)
    except FileNotFoundError:
        return {}
    return hs

用法:

# file does not exist
k = load_highscore_from_file()
print(k)

# add some highscores to dict
k["p"]=10
k["a"]=110
k["k"]=1110
k["l"]=1022 
print(k)

# store file, only top 3
store_highscore_in_file(k, top_n=3)

# load back into new dict
kk = load_highscore_from_file()
print(kk)

输出:

{} # no file
{'p': 10, 'a': 110, 'k': 1110, 'l': 1022} # before storing top 3 
{'k': 1110, 'l': 1022, 'a': 110} # after loading the top 3 file again

0

首先创建一个名为 highscore.txt 的文件,初始值为零。 然后使用以下代码:

hisc=open("highscore.txt","w+")
highscore=hisc.read()
highscore_in_no=int(highscore)
if current_score>highscore_in_no:
                hisc.write(str(current_score))
                highscore_in_no=current_score
                     .
                     .
#use the highscore_in_no to print the highscore.
                     .

                     .
hisc.close()

我可以用这种简单的方法制作一个永久的高分记录器,不需要使用架子或腌制。


0
通常我会将玩家的名字和高分存储为一个列表的列表(例如[['Joe', 50], ['Sarah', 230], ['Carl', 120]]),因为你可以对它们进行排序和切片(例如如果应该有最多10个条目)。你可以使用json模块(json.dumpjson.load)或pickle保存和加载列表。
import json
from operator import itemgetter

import pygame as pg
from pygame import freetype


pg.init()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
FONT = freetype.Font(None, 24)


def save(highscores):
    with open('highscores.json', 'w') as file:
        json.dump(highscores, file)  # Write the list to the json file.


def load():
    try:
        with open('highscores.json', 'r') as file:
            highscores = json.load(file)  # Read the json file.
    except FileNotFoundError:
        return []  # Return an empty list if the file doesn't exist.
    # Sorted by the score.
    return sorted(highscores, key=itemgetter(1), reverse=True)


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    highscores = load()  # Load the json file.

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_s:
                    # Save the sorted the list when 's' is pressed.
                    # Append a new high-score (omitted in this example).
                    # highscores.append([name, score])
                    save(sorted(highscores, key=itemgetter(1), reverse=True))

        screen.fill((30, 30, 50))
        # Display the high-scores.
        for y, (hi_name, hi_score) in enumerate(highscores):
            FONT.render_to(screen, (100, y*30+40), f'{hi_name} {hi_score}', BLUE)

        pg.display.flip()
        clock.tick(60)


if __name__ == '__main__':
    main()
    pg.quit()

highscores.json文件将会如下所示:

[["Sarah", 230], ["Carl", 120], ["Joe", 50]]

-3
我建议:
def add():
input_file=open("name.txt","a")#this opens up the file 
name=input("enter your username: ")#this input asks the user to enter their username
score=input("enter your score: ")#this is another input that asks user for their score
print(name,file=input_file)
print(number,file=input_file)#it prints out the users name and is the commas and speech marks is what is also going to print before the score number is going to print
input_file.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接