0
我正在尝试构建一个人工智能程序,该程序将跟踪信息和其他内容,但在试图将信息导出到文件时遇到问题。我是Python的新手,希望能够帮助确定可能存在的问题。如何将Python 3.4输入信息导出到JSON?
这里是源代码。
#Importations
import jsonpickle
import math
import os
import sys
import time
from random import randrange, uniform
#Setups
SAVEGAME_FILENAME = 'aisetup.json'
game_state = dict()
#Program AI
class Computer(object):
def __init__(self, name, creator):
self.name = name
self.creator = creator
#User Information
class Human(object):
def __init__(self, name, birth):
self.name = name
self.birth = birth
#Load Program Save
def load_game():
"""Load game state from a predefined savegame location and return the
game state contained in that savegame.
"""
with open(SAVEGAME_FILENAME, 'r') as savegame:
state = jsonpickle.decode(savegame.read())
return state
#Save Program to JSON
def save_game():
"""Save the current game state to a savegame in a predefined location.
"""
global game_state
with open(SAVEGAME_FILENAME, 'w') as savegame:
savegame.write(jsonpickle.encode(game_state))
#Initialize Program
def initialize_game():
"""Runs if no AISave is found"""
UserProg = Human('User', '0/0/0')
AISystem = Computer('TempAI', 'Austin Hargis')
state = dict()
state['UserProg'] = [UserProg]
state['AISystem'] = [AISystem]
return state
#TextPad
#Main Code - Runs Multiple Times per Being Openned
def prog_loop():
global game_state
name = input (str("What is your name?: "))
save_game()
#Main Program
def main():
"""Main function. Check if a savegame exists, and if so, load it. Otherwise
initialize the game state with defaults. Finally, start the game.
"""
global game_state
if not os.path.isfile(SAVEGAME_FILENAME):
game_state = initialize_game()
else:
game_state = load_game()
prog_loop()
#Launch Code
if __name__ == '__main__':
main()
我每次运行它,它导出的信息保存到文件是这样的:
{"UserProg": [{"birth": "0/0/0", "py/object": "__main__.Human", "name": "User"}], "AISystem": [{"py/object": "__main__.Computer", "name": "TempAI", "creator": "Austin Hargis"}]}
我希望它你的名字导出到文件夹,但它不工作的权利。
啊,我明白了。我以为我是在这条正确的轨道上。我以前有过这样的东西,但它没有奏效,所以我摆脱了它。 – orias 2014-12-07 02:54:13
我如何再次使用这些信息?就像名字一样,当程序启动时,我想让它说“Welcome back(name)”。我将如何再次使用该名称? – orias 2014-12-07 14:08:06
@AustinHargis:加载后你可以再次访问'game_state ['UserProg'] [0] .name'。 – 2014-12-07 20:48:00