创建一个用于我的Python游戏的JSON保存系统。

huangapple go评论73阅读模式
英文:

Making a json saving system for my python game

问题

我制作了一个简单的计数器这样我可以查看是否可以从一个程序中存储数据并在下次运行时保留它但我不确定该如何做到这一点到目前为止我有这个如果你想知道以后我会用这个做什么那就是为了一个pygame

```python
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

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


<details>
<summary>英文:</summary>

I made a simple counter so I can see if I can store data from one program and keep it for the next time I run it however I&#39;m not sure how I can do that. This is what I&#39;ve got so far. If your wondering what I&#39;ll use this for afterword&#39;s its for a 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

As you may see when you run this code it doesn&#39;t continue counting it only resets and starts again.

</details>


# 答案1
**得分**: 0

这里有一些问题:

```python
import json, time
start = 0

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

while True:
  save = data
  # 不必要的变量赋值!你可以保持它为 '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
  # start 现在是 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():
    # 检查数据是否存在
    try:
        with open("data.json", "r") as read_file:
            return json.load(read_file)
    except FileNotFoundError:
        # 如果找不到文件,创建新的游戏数据
        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)

这个循环加载当前的存档或开始一个新的存档,然后使用函数在每个循环中保存数据。你可能需要考虑一些问题:你是否想要重复保存?你希望保存之间有多长时间?是否允许用户触发保存功能?这个循环会产生什么成本?你可以考虑仅在修改数据或满足特定条件时才保存数据,而不是在每次循环迭代中都保存数据。

英文:

So there are a couple of issues here:

import json, time
start = 0

with open(&quot;data.json&quot;, &quot;r&quot;) as read_file:
  data = json.load(read_file)

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

This would probably be better written out as:

game_data = { &#39;yourdata&#39; : 1 }

def save_game_data(data):
    with open(&quot;data.json&quot;, &quot;w&quot;) as write_file:
        json.dump(data, write_file)

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

You could then use a loop to occasionally dump your data into the json file like:

import json, time

current_save = load_game_data()

while True:
    save_game_data(current_save)
    if current_save[&#39;yourdata&#39;]==1:
        print(&quot;Works&quot;)
    current_save[&#39;yourdata&#39;] += 1
    time.sleep(1)
    print(current_save)

This loop loads either the current save or starts a new one, then uses the function to save the data for each loop. You might want to consider-- do you want to save repeatedly? How long do you want between saves? Do you want people to be able to trigger a save function? Is there going to be a cost to this loop? You could consider saving the data only when it is modified or when specific conditions are met, rather than saving it on every iteration of the loop.

huangapple
  • 本文由 发表于 2023年6月5日 21:15:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定