Saving the highscore for a python game

2019-01-15 15:04发布

I have made a very simple game in python using pygame. The score is based on whatever level the player reached. I have the level as a variable called score. I want to display the top level at the start or end of the game.

I would be even more happy to display more than one score, but all of the other threads I have seen were too complicated for me to understand, so please keep it simple: I'm a beginner, only one score is necessary.

7条回答
Lonely孤独者°
2楼-- · 2019-01-15 15:41

I recommend you use shelve. For example:

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()

Next time you open your program use:

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

and it will be read from disk. You can use this technique to save a list of scores if you want in the same way.

查看更多
够拽才男人
3楼-- · 2019-01-15 15:41

I come from a Java background, and my Python isn't great, but I would look into the Python documentation on reading and writing to files: http://docs.python.org/2/tutorial/inputoutput.html

You could write a score variable to a plaintext file before you end the game, and then load the same file the next time you start the game.

Look into the read(), readline(), and write() methods.

查看更多
干净又极端
4楼-- · 2019-01-15 15:45

First create a highscore.txt with a value zero initially. Then use the following code:

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()

I could make a permanent highscore storer with this simple method, no need for shelves or pickle.

查看更多
孤傲高冷的网名
5楼-- · 2019-01-15 15:57

I would suggest:

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()
查看更多
虎瘦雄心在
6楼-- · 2019-01-15 16:02

You can use the pickle module to save variables to disk and then reload them.

Example:

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)

This saves a single score to disk. The nice thing about pickle is that you can easily extend it to save multiple scores - just change scores to be an array instead of a single value. pickle will save pretty much any type of variable you throw at it.

查看更多
不美不萌又怎样
7楼-- · 2019-01-15 16:03

You can use a dict to hold your highscore and simply write it into a file:

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

Usage:

# 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)

Output:

{} # 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
查看更多
登录 后发表回答