修改.json文件的有效方法

时间:2015-12-02 17:31:39

标签: python json

我正在尝试在Python中创建一个textgame,并且它非常依赖于.json文件。最新问题是如何处理游戏中物品的拾取和丢弃。从概念上讲,我认为我可以创建一个包含播放器信息的.json文件(其中包括库存),使用item的关键字更新库存,并从房间的.json文件中删除该关键字。如果玩家丢弃物品,我会反其道而行。

我的game.py:

import cmd
from room import get_room
from item import get_item
import textwrap

class Game(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
    #Start the player out in Room #1 by calling the get_room() function
    #passing the integer '1' with it, and reading 1.json.
        self.loc = get_room(1)
    # Displays the room to the player.
        self.showRoom()

    def move(self, dir):
        #Grabs the direction the layer is moving, runs it through the
        #_neighbor function within the room module. Determines if there
        #is a room in that direction. If so, update to that new room an
        #display it.
        newroom = self.loc._neighbor(dir)
        if newroom is None:
            print("You can't go that way.")
        else:
            self.loc = get_room(newroom)
            self.showRoom()

    def showRoom(self):
        #Displays the current room the player is in, as well as any other
        #Objects within it. (Items, enemies, NPCs, etc)
        print(self.loc.name)
        print("")
        #Wraps the text up to 70 words per line.
        for line in textwrap.wrap(self.loc.description, 70):
            print(line)
        print("")
        #Looks in the room's .json file to see if the room has a key to
        #an item. If it does. Display it on the ground.
        if self.loc.haveItem != "None":
            print(self.loc.onGround)
            print("")
        #Looks to the room's .json file to see if the room has a key to
        #'showNeighbors.' If it does, display the possible exits of that
        #room.
        print("Possible Exits:")
        print(self.loc.showNeighbors)

    def do_look(self, args):
        #An exact copy of the showRoom function. There has to be a way to
        #point do_look to showRoom() to keep from executing duplicate form.
        #This is just bad form.
        """Reprints the rooms description and available exits."""
        print(self.loc.name)
        print("")
        for line in textwrap.wrap(self.loc.description, 70):
            print(line)
        print("")
        if self.loc.haveItem != "None":
            print(self.loc.onGround)
            print("")
        print("Possible Exits:")
        print(self.loc.showNeighbors)

    def do_get(self, args):
        #A function that handles getting an item off the room's ground.
        #Currently not functioning as intended. Is meant to find the item
        #In the room's .json file, use it to open the items .json file,
        #and grab the 'keywords of said item. Then checks to see if
        #get <keyword> was typed. If so, edit room's .json file to remove
        #item from room, and add it to player inventory. Removing the
        #.json file is neccessary to ensure item does not diplay in room
        #once picked up.
        """type 'pick <item>' to pick up item in room."""
        itemToTake = args.lower()
        keywords = self.loc.keywords
        if itemToTake == "":
            print ("Take what? Type 'look' to see the items to take.")
            return
        if (itemToTake == keywords[0]) or (itemToTake == keywords[1]):
            if self.loc.canTake == "True":
                print("You have picked up a " + self.loc.itemName + ".")
                #code should be placed here to wipe current room's .json
                #file to ensure room is devoid of any items.

        else:
            print("That item is not here.")

    def do_drop(self, args):
        #A function that will handle dropping an item from a player's
        #inventory. If an item is dropped in inventory, it will be removed
        #from players .json inventory file, and added as a key:value
        #to the room's .json file, so that should the player return, the
        #item will load up as intended.
        pass

    def do_inv(self):
        """Opens up your inventory"""
        #Hasen't been implimented yet. Would like to have it done through a
        #.json file. The file would hold other players attributes such as:
        #Hit Points, Strength, Dexterity, Armor Class, and the like.

   #Self explainatory functions:
    def do_quit(self, args):
        """Quit the game"""
        print("Thank you for playing.")
        return True

    def do_n(self, args):
        """Goes North"""
        self.move('n')

    def do_s(self, args):
        """Goes South"""
        self.move('s')

    def do_e(self, args):
        """Goes East"""
        self.move('e')

    def do_w(self, args):
        """Goes West"""
        self.move('w')

if __name__ == "__main__":
    play = Game()
    play.cmdloop()

我的room.py:

import json
from item import get_item

"""
This module handles all of the rooms in the game. It searches for a .json file with the approriate id number, then opens it, reads it line by line, and stores it in a dictonary. The Room class then takes the information and sorts it out in to the corrisponding variables. If there is no string listed, it will list the default strings declared in the parameters.
"""

def get_room(id):
    ret = None
    with open(str(id) + ".json", "r") as file:
        jsontext = file.read()
        dictonary = json.loads(jsontext)
        dictonary['id'] = id
        ret = Room(**dictonary)
    return ret

class Room():

    def __init__(self, id = 0, name="A Room", description = "An Empty Room", neighbors = {}, showNeighbors = "None", haveItem = "None"):
        #This is a mess. Has to be a better way to do all this rather than
        #place it all in the initiate function. Function assigns .json file
        # dictonaries to seperate variables. This is fine.
        self.id = id
        self.name = name
        self.description = description
        self.neighbors = neighbors
        self.showNeighbors = showNeighbors
        self.haveItem = haveItem
        #This checks to see if room has an item. If so, grab it's .json file
        #and assign it's values to variables. Fell that this SHOULD NOT be
        #in __init__. Unsure how to do it any other way.
        if haveItem != "None":
            item = get_item(haveItem)
            self.onGround = item.onGround  
            onGround = self.onGround        
            self.keywords = item.keywords
            keywords = self.keywords
            self.canTake = item.canTake
            canTake = self.canTake
            self.itemName = item.itemName
            itemName = self.itemName        
    def modifiyRoom(self, id = 0, haveItem = "None"):
        pass
           #Function used to modify room .json files. uses include:
           #Adding a dropped item.
           #Removing an item dropped within room.
           #Detect if enemy entered or left room.
           #At least it would do all of that. If I can get it to work.

    def _neighbor(self, direction):
        if direction in self.neighbors:
            return self.neighbors[direction]
        else:
            return None

    def north(self):
        return self._neighbor('n')

    def south(self):
        return self._neighbor('n')

    def east(self):
        return self._neighbor('n')

    def west(self):
        return self._neighbor('n')    

和item.py:

import json

"""
This module handles all of the items in the game. It searches for a .json file with the approriate id, then opens it, reads it line by line, and stores it in a dictonary. The Item class then takes the information and sorts it out in to the corrisponding variables. If there is no string listed, it will list the default strings declared in the parameters.
"""

def get_item(itemName):
    ret = None
    with open(itemName + ".json", "r") as file:
        jsontext = file.read()
        item = json.loads(jsontext)
        item['itemName'] = itemName
        ret = Item(**item)
    return ret

class Item():

    def __init__(self, itemName = "", name = "An Item", onGround = "On ground", description = "A sweet Item", canTake = "False", keywords = "None", value = 0):
        #Handles all of the variables found in an item's .json file.
        #Feel this will have to act as a super class for more unique
        #items, such as weapons, which will hold a damage value.
        self.itemName = itemName
        self.name = name
        self.onGround = onGround
        self.description = description
        self.canTake = canTake
        self.keywords = keywords
        self.value = value

示例room.json:

{"name" : "Disposal Room",
 "description" : "A powerful burst of pain in your head wakes you up from your brief slumber, the intense throbbing causing you to see everything in a dull haze. It takes a few moments for the pain to die down, and with it your vision eventually returns to normal. After some examining you discover that you are in some sort of forgotten cell, the prison door to the west of you unlocked and slightly ajar.",
 "neighbors" : {"s" : 2},
 "showNeighbors" : "south",
 "haveItem" : "sword"
}

0 个答案:

没有答案