为我的Python游戏制作JSON保存系统[已关闭]

ijxebb2r  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(225)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

昨天关门了。
Improve this question
我做了一个简单的计数器,这样我就可以看看我是否可以从一个程序中存储数据,并为下一次运行它保留它,但我不确定我如何才能做到这一点。这是我目前所知道的如果你想知道我会用这个作为后记的话,它是一个pygame。

import json, time
start = 0
with open("data.json", "r") as read_file:
  data = json.load(read_file)
while True:
  save = data
  with open("data.json", "w") as write_file:
    json.dump(save, write_file)
  with open("data.json", "r") as read_file:
    data = json.load(read_file)
    if data=={'part': 0}:
      print("Works")
  start = start + 1
  time.sleep(1)
  print(data)
  save = data

正如你所看到的,当你运行这段代码时,它不会继续计数,它只会重置并重新开始。

km0tfn4u

km0tfn4u1#

这里有几个问题:

import json, time
start = 0

with open("data.json", "r") as read_file:
  data = json.load(read_file)

while True:
  save = data
# unnecessary variable assignment! you can just keep it as 'data'
  with open("data.json", "w") as write_file:
    json.dump(save, write_file)
# you're repeatedly reading and writing the data here: why not set it to just write the data if you're keeping it in memory anyway?
  with open("data.json", "r") as read_file:
    data = json.load(read_file)
    if data=={'part': 0}:
# compare values and not the whole dict object
      print("Works")
  start = start + 1
# start is now 1
  time.sleep(1)
  print(data)
  save = data

这可能更好地写成:

game_data = { 'yourdata' : 1 }

def save_game_data(data):
    with open("data.json", "w") as write_file:
        json.dump(data, write_file)

def load_game_data():
    # check to see if data exists
    try:
        with open("data.json", "r") as read_file:
            return json.load(read_file)
    except FileNotFoundError:
        # if you can't find the file, create new game data
        return game_data

然后,你可以使用一个循环来偶尔将数据转储到json文件中,如下所示:

import json, time

current_save = load_game_data()

while True:
    save_game_data(current_save)
    if current_save['yourdata']==1:
        print("Works")
    current_save['yourdata'] += 1
    time.sleep(1)
    print(current_save)

此循环加载当前保存或启动一个新的保存,然后使用函数保存每个循环的数据。你可能要考虑--你要反复保存吗?您希望保存间隔多长时间?您希望用户能够触发保存功能吗?这个循环会有成本吗?您可以考虑仅在修改数据或满足特定条件时保存数据,而不是在循环的每次迭代时保存数据。

相关问题