如何制作包含变量的数据结构,以便在重新定义变量时更新?

问题描述 投票:0回答:1

我正在制作一个文字冒险游戏。我正在使用命名元组来定义位置。

Location = namedtuple('Location', ['desc', 'ldesc', 'func', 'dirloc'])

entrance = foyer = None 

entrance = Location('Dungeon Entrance', (
'You are in a small clearing in a forest. '          
'To the north, a large iron-studded door is visible, '          
'embedded in a small hill that rises up in the middle of the clearing. '
'The sun shines down upon you and birds sing.'), None,
{'north':foyer, 'south':None, 'east':None, 'west':None, 'up':None, 'down':None}) 

foyer = Location('Foyer', ('You are in a medium-sized room made of stone. '
'Alcoves are carved along the wall at all angles. '
'One passage leads west. Another leads north. '
'Footsteps on the ground lead towards the west passage.'),
None,
{'north':None, 'south':entrance, 'east':None, 'west':None, 'up':None, 'down':None})

我需要入口位置字典

dictloc
中的门厅变量,以便在定义真正的门厅位置时自动更新。我怎样才能做到这一点?我在互联网上搜索了文章,但没有找到任何相关内容。

我一遍又一遍地尝试使用不同的数据结构,看看我是否能找到一个有效的方法。不幸的是,没有人这样做。

python namedtuple forward-reference
1个回答
0
投票

试试这个布局

dungeon = {
    "entrance": {
        "desc": "Dungeon Entrance",
        "ldesc": (
            "You are in a small clearing in a forest. "
            "To the north, a large iron-studded door is visible, "
            "embedded in a small hill that rises up in the middle of the clearing. "
            "The sun shines down upon you and birds sing."
        ),
        "func": None,
        "dirloc": {
            "north": "foyer",
            "south": None,
            "east": None,
            "west": None,
            "up": None,
            "down": None,
        },
    },
    "foyer": {
        "desc": "Foyer",
        "ldesc": (
            "You are in a medium-sized room made of stone. "
            "Alcoves are carved along the wall at all angles. "
            "One passage leads west. Another leads north. "
            "Footsteps on the ground lead towards the west passage."
        ),
        "func": None,
        "dirloc": {
            "north": None,
            "south": "entrance",
            "east": None,
            "west": None,
            "up": None,
            "down": None,
        },
    },
}


location_key = "entrance"

while location_key:
    location = dungeon[location_key]
    print(location["desc"])
    print("="*len(location["desc"]))
    print(location["ldesc"])

    direction = input("\nWhich direction?")
    if direction in location["dirloc"]:
        if location["dirloc"][direction] is None:
            print("You cannot go "+direction)
        else:
            location_key = location["dirloc"][direction]
            print("\nGoing "+direction)
    else:
        raise ValueError("Unexpected direction: " + direction)
© www.soinside.com 2019 - 2024. All rights reserved.