保存python游戏的高分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16726354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving the highscore for a python game
提问by Kevin Klute
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.
我使用 pygame 在 python 中制作了一个非常简单的游戏。分数基于玩家达到的任何级别。我有一个名为score. 我想在游戏开始或结束时显示顶级。
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.
我会更乐意显示不止一个分数,但是我看到的所有其他线程都太复杂了,我无法理解,所以请保持简单:我是初学者,只需要一个分数。
采纳答案by elyase
I recommend you use shelve. For example:
我建议你使用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()
Next time you open your program use:
下次打开程序时使用:
import shelve
d = shelve.open('score.txt')
score = d['score'] # the score is read from disk
d.close()
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.
它将从磁盘读取。如果需要,您可以使用此技术以相同的方式保存分数列表。
回答by JAL
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
我来自 Java 背景,我的 Python 不是很好,但我会查看有关读取和写入文件的 Python 文档: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.
看看进入read(),readline()和write()方法。
回答by Blorgbeard is out
You can use the picklemodule to save variables to disk and then reload them.
您可以使用该pickle模块将变量保存到磁盘,然后重新加载它们。
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 scoresto be an array instead of a single value. picklewill save pretty much any type of variable you throw at it.
这会将单个乐谱保存到磁盘。pickle 的好处是您可以轻松扩展它以保存多个分数 - 只需更改scores为数组而不是单个值。pickle几乎可以保存您扔给它的任何类型的变量。
回答by Vishnu Das
First create a highscore.txt with a value zero initially. Then use the following code:
首先创建一个 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()
I could make a permanent highscore storer with this simple method, no need for shelves or pickle.
我可以用这个简单的方法制作一个永久性的高分储物柜,不需要架子或泡菜。
回答by JohnDoe
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()
回答by Patrick Artner
You can use a dict to hold your highscore and simply write it into a file:
您可以使用 dict 来保存您的高分并将其写入文件:
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
回答by skrx
I usually store the player names and high-scores as a list of lists (e.g. [['Joe', 50], ['Sarah', 230], ['Carl', 120]]), because you can sort and slice them (for example if there should be a maximum of 10 entries). You can save and load the list with the jsonmodule (json.dumpand json.load) or with pickle.
我通常将玩家姓名和高分存储为列表(例如[['Joe', 50], ['Sarah', 230], ['Carl', 120]]),因为您可以对它们进行排序和切片(例如,如果最多应有 10 个条目)。您可以使用json模块 (json.dump和json.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()
The highscores.jsonfile would then look like this:
该highscores.json文件将如下所示:
[["Sarah", 230], ["Carl", 120], ["Joe", 50]]

