在Python中为战舰游戏创建和保存文本文件

时间:2012-04-26 18:03:27

标签: python

我现在已经在相同的战舰游戏上工作了很长一段时间,并且正在进入最后阶段。现在我需要让游戏使用def saveScore函数在文本文件中保存前五个分数。然后我需要它来读取我刚刚创建的文件,并使用try打开分数到python代码,除了文件打开和关闭。我不知道如何让python识别我的变量得分因为我相信它唯一的本地。这就是我所拥有的。我不知道如何使用泡菜。

def main():
    board=createBoard()
    printBoard(board)
    s = [[21,22,23,24,25],
    [45,55,65,75],
    [1,2,3],
    [85,86,87],
    [5,15],
    [46,56]]
    playBattleship(s,board)
main()

3 个答案:

答案 0 :(得分:1)

最简单的方法可能是使用Pickle。使用“加载”和“转储”功能,您可以轻松保存/加载分数对象。

http://docs.python.org/library/pickle.html

import pickle

def saveScore(score):
    pickle.dump(score, 'topfive2.txt')

def loadScore():
    return pickle.load('topfive2.txt')

答案 1 :(得分:1)

使用pickle是一种将python对象序列化为文件的低级方法,然后再将该格式读回到对象中。如果您想要一些可能更容易自然使用的更高级别界面,请尝试查看shelve模块:http://docs.python.org/library/shelve.html#example

您可以将其视为字典,只需附加并保存您的分数即可。它会在引擎盖下腌制保存到文件中。

import shelve

# open a shelve file. writeback=True makes it save
# on the fly
d = shelve.open('temp.file', writeback=True)
if not d.has_key('scores'):
    d['scores'] = []

print d['scores']
# []

# add some score values
d['scores'].append(10)
d['scores'].append(20)
d.close()

# next time, open the file again. It will have
# the 'scores' key. Though you should probably check
# for it each time in case its a first run.
d = shelve.open('temp.file', writeback=True)
print d['scores']
#[10, 20]

# sort the list backwards and take the first 5 top scores
topScores = sorted(d['scores'], reverse=True)[:5]

答案 2 :(得分:1)

在Python中读取和写入文件是pretty straightforward

# Opening a file for writing will return the file handle f
f = open('/tmp/workfile', 'w')

# You can then write to the file using the 'write' method
f.write('Hello world!\n')

# To read your data back you can use the 'read' or 'readlines' methods

# Read the entire file
str = f.read()

# Read the file one line at a time
line = f.readline()

# Read the file into a list
list = f.readlines()

如果要存储的数据不仅仅是最后一个得分,您可以考虑创建一个SQLite3数据库。 Python对SQLite3有很好的built-in support。这是一个跨平台的文件系统数据库。数据库只是磁盘上的常规文本文件,但它支持您希望从数据库中获得的许多SQL操作。