保存python游戏的高分

Kev*_*ute 5 python pygame leaderboard save

我用pygame在python中做了一个非常简单的游戏.得分基于玩家达到的任何级别.我将级别作为变量调用score.我希望在游戏开始或结束时显示顶级.

我会更乐意展示多个分数,但我看到的所有其他主题对我来说都太复杂了,所以请保持简单:我是初学者,只需要一个分数.

Blo*_*ard 7

您可以使用该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)
Run Code Online (Sandbox Code Playgroud)

这样可以将单个分数保存到磁盘.pickle的好处是你可以轻松扩展它以保存多个分数 - 只需将其更改scores为数组而不是单个值.pickle几乎可以保存任何类型的变量.


ely*_*ase 6

我建议你使用搁架.例如:

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()
Run Code Online (Sandbox Code Playgroud)

下次打开程序时使用:

import shelve
d = shelve.open('score.txt')
score = d['score']           # the score is read from disk
Run Code Online (Sandbox Code Playgroud)

它将从磁盘读取.如果您想以相同的方式使用此技术,则可以使用此技术保存分数列表.