gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:02:01 25 4
gpt4 key购买 nike

我已经为同一款 Battleship 游戏工作了很长一段时间,现在已经到了最后阶段。现在我需要使用函数 def saveScore 将游戏的前五名得分保存在文本文件中。然后我需要它来读取我刚刚创建的文件,并使用 tryexcept 将乐谱加载到 Python 代码中以打开和关闭文件。我不知道如何让 Python 识别我的变量 score 因为我相信它只是本地的。这就是我所拥有的。我不知道如何使用 pickle。

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

最佳答案

使用 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]

关于python - 在 Python 中为战舰游戏创建和保存文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10338914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com