【问题标题】:How to implement items to each room in a python3 text adventure?如何在 python3 文本冒险中为每个房间实现项目?
【发布时间】:2019-10-15 13:28:33
【问题描述】:

我对 oop 很陌生,但我想了解一些关于它的知识,所以我开始用 Python3 编写一个文本冒险。

在阅读了很多关于如何开始的建议和方法之后,我决定使用 cmd-module 进行解析以及房间和其他东西的类。我不想在代码中写入这么多冒险数据,所以我偶然想到了使用 json 模块将其外包的想法。到目前为止,我设法在房间之间切换,现在我想在其中放置物品。

我尝试向 Room-class 添加另一个属性,它应该是该特定房间中可用项目的列表。现在我被困在如何在房间里制作这些物品的实例,以便按此顺序打印出它们的描述:

1.) Room name 
2.) Room description
3.) Item1 description
4.) Item2 description
5.) ...

1.) 和 2.) 已经用 do_look() 打印出来了

这是主游戏循环:

import cmd
from rooms import get_room

class Play(cmd.Cmd):
    """Base class for the game"""
    def __init__(self):
        cmd.Cmd.__init__(self)
        cmd.Cmd.prompt = '> '
        self.location = get_room(1)    
        self.do_look()

    def move(self, direction):
        new_id = self.location.exit_to(direction)
        if new_id is None:
            print('You can not go there')
        else:
            self.location = get_room(new_id)
            self.do_look()

    def do_look(self, *args):
        """Print the Room description."""
        print(self.location.name)
        print("")
        print(self.location.desc)
        print("")

    def do_north(self, *args): #Example direction command
        """Move north"""
        self.move('north')

if __name__ == '__main__':
    play = Play()
    play.cmdloop()

这里是房间模块(已经添加了“items”属性):

import json

def get_room(_id):
    # ret = None
    with open(str(_id) + '.json', 'r') as f:
        jsontext = f.read()
        d = json.loads(jsontext)
        # d["_id"] = _id 
        ret = Room(**d)
    return ret

class Room:
    def __init__(self, _id = 0, name = '', desc = '' exits = {}, items = []):
        self._id = _id
        self.name = name
        self.desc = desc
        self.exits =  exits
        self.items = items

    def exit_to(self, _dir):
        if _dir in self.exits:
            return self.exits[_dir]
        else:
            return None

一个典型的.json看起来像这样(文件名:1.json):

{   
    "_id" : "1", 
    "name" : "The First Room",
    "desc" : "You wake up in the First Room ...",
    "exits" : {"north" : 4},
    "items" : ["puppet", "gun"]
    }

我还创建了一个项目模块,但我不知道如何将它连接到房间:

class Item:
    def __init__(self, name, desc, desc_in_room):
        self.name = name
        self.desc = desc
        self.desc_in_room = desc_in_room


""" This is the first and unfinished attempt to deal with it,
    but I think this is not gonna work:"""

def make_item(self, _id):
     with open(str(_id) + '.json', 'r') as f:
        jsontext = f.read()
        d = json.jsonloads(jsontext)
            for i in d["items"]:
                with open(str(i) + '.json', 'r') as fil:
                    itemtext = f.read()
                    item_dict = json.jsonloads(itemtext)
                    """Dont know..."""
    return ret

因此,对于如何从 dict 中的列表中提取“puppet”并将其转换为 Item 实例并打印其描述的任何建议,我们将不胜感激!

【问题讨论】:

    标签: python python-3.x class oop adventure


    【解决方案1】:

    Python 的美妙之处在于它有一个库可用于大多数常见操作 - 以及许多不常见的操作。在您的情况下,JsonPickle 看起来是一个不错的选择。您可以从房间创建模板 json,然后在其他地方对其进行修改并根据需要重新补充水分。我在下面为你写了一个例子;

    第一

    pip-install jsonpickle

    然后运行下面的代码

    import jsonpickle
    import pprint
    
    
    class Item:
        def __init__(self, name, desc, desc_in_room):
            self.name = name
            self.desc = desc
            self.desc_in_room = desc_in_room
    
        def __str__(self):
            return f"{self.name}, {self.desc}, {self.desc_in_room}"
    
    
    class Room:
        def __init__(self, _id=0, name='', desc='', exits=None, items=None):
            self._id = _id
            self.name = name
            self.desc = desc
            self.exits = exits if exits is not None else {}
            self.items = items if items is not None else []
    
        def exit_to(self, _dir):
            if _dir in self.exits:
                return self.exits[_dir]
            else:
                return None
    
    
    if __name__ == '__main__':
        myroom = Room(1, "First", "An eerie door leads to your destiny",
                      items=[Item("Item1", "Hammer", "Large and heavy"), Item("Item2", "Sword", "Old and rusty")])
    
        frozen = jsonpickle.encode(myroom)
        print(frozen)
    
        # YIELDS
        """{"_id": 1, "desc": "An eerie door leads to your destiny", "exits": {}, "items": 
        [{"desc": "Hammer", "desc_in_room": "Large and heavy", "name": "Item1", "py/object": "__main__.Item"}, 
        {"desc": "Sword", "desc_in_room": "Old and rusty", "name": "Item2", "py/object": "__main__.Item"}], 
        "name": "First", "py/object": "__main__.Room"}"""
    
        # CHANGE AT WILL
        modified = """{"_id": 1, "desc": "An eerie door leads to your destiny", "exits": {}, "items": 
        [{"desc": "Feather", "desc_in_room": "Harmless", "name": "Item1", "py/object": "__main__.Item"}, 
        {"desc": "Sword", "desc_in_room": "Old and rusty", "name": "Item2", "py/object": "__main__.Item"}], 
        "name": "Second", "py/object": "__main__.Room"}"""
    
        new_room = jsonpickle.decode(modified)  # type: Room
        print(new_room.name)
        for i in new_room.items:
            print(i)
    
        # YIELDS the Following. Note the new name for the room and for the Hammer
        """
        Second
        Item1, Feather, Harmless
        Item2, Sword, Old and rusty
        """
    

    【讨论】:

    • 您好,感谢您的快速回复!我以前不知道那个模块。但我认为这更多是关于创建新房间,然后将项目实例粘贴到它们上,不是吗?也许我的开场白并不清楚这一点:我可以使用字符串列表创建房间实例(即项目:“puppet”、“gun”)。但我想知道如何从列表中制作实际的 Item 实例。
    • 原则是一样的——我只是懒惰。我编辑了上面的内容,向您展示如果您有非空项目,它可以工作。请注意,我只是更改了字符串的相关部分,解码字符串和 vala - 一个填充了项目的新房间:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多