首页 > 解决方案 > 尝试在游戏中加载-更新-重新保存参数

问题描述

我对编程和尝试通过创建文本冒险游戏和阅读 Python 文档/博客来学习非常陌生。

我的问题是我试图在文本游戏中保存/加载数据以创建一些元素,这些元素在游戏之间传递并作为参数传递。特别是在这个例子中,我的目标是在每次游戏结束时回忆、更新和加载一个递增的迭代。特别是我在这里的意图是导入保存的march_iteration编号,将其作为默认名称建议显示给用户,然后迭代迭代编号并保存更新的保存的march_iteration编号。

从我调试的尝试来看,我似乎正在更新值并将更新后的值 2 正确保存到 game.sav 文件中,所以我相信我的问题是我无法正确加载数据或覆盖保存的值静态的不知何故。我已经阅读了尽可能多的文档,但是从我读过的关于保存和加载到 json 的文章中,我无法确定我的代码哪里出错了。

下面是我写的一个小代码片段,只是为了尝试让保存/加载工作。任何见解将不胜感激。

import json

def _save(dummy):
    f = open("game.sav", 'w+')
    json.dump(world_states, f)
    f.close

def _continue(dummy):
    f = open("game.sav", 'r+')
    world_states = json.load(f)
    f.close

world_states = {
    "march_iteration" : 1
}

def _resume():
    _continue("")
_resume()
print ("world_states['march_iteration']", world_states['march_iteration'])

current_iteration = world_states["march_iteration"]

def name_the_march(curent_iteration=world_states["march_iteration"]):
    march_name = input("\nWhat is the name of your march?  We suggest TrinMar#{}. >".format(current_iteration))
    if len(march_name) == 0:
        print("\nThe undifferentiated units shift nerviously, unnerved and confused, perhaps even angry.")
        print("\nPlease give us a proper name executor.  The march must not be nameless, that would be chaos.")
        name_the_march()
    else:
        print("\nThank you Executor.  The {} march begins its long journey.".format(march_name))
        world_states['march_iteration'] = (world_states['march_iteration'] +1)
        print ("world_states['march_iteration']", world_states['march_iteration'])
#Line above used only for debugging purposed
        _save("")
name_the_march()

标签: pythonpython-3.xsave

解决方案


我似乎找到了一个适合我的目的的解决方案,允许我加载、更新和重新保存。它不是最有效的,但它可以工作,打印只是为了显示在重新保存之前正确加载和更新的数字。

先决条件:此示例假定您已经创建了一个文件以供打开。

import json

#Initial data
iteration = 1

#Restore from previously saved from a file
with open('filelocation/filename.json') as f:
  iteration = json.load(f)
print(iteration)

iteration = iteration + 1
print(iteration)

#save updated data
f = open("filename.json", 'w')
json.dump(iteration, f)
f.close

推荐阅读