<p>我能想象的最好的方法是创建对象,然后分两个不同的步骤创建链接。你知道吗</p>
<pre><code>class Room(object):
def __init__(self, monster, loot):
self.exits = {direction:None for direction in
["North", "South", "East", "West"]}
# rooms have no exits until you add links to them manually
self.room_guard = monster
self.guard_is_alive = True
self.loot = loot
def add_link(self, other, ordinal):
"""Creates a link between this room and another in the specified direction
room_A.add_link(room_B, 'East')
sets room_A.exits['East'] = room_B and room_B.exits['West'] = room_A"""
if not hasattr(other, 'exits')
raise ValueError("Can only link with other objects with exits")
ordinal_map = {"North":"South", "South":"North",
"East":"West", "West":"East"}
try:
other_ordinal = ordinal_map[ordinal]
except KeyError:
raise ValueError("ordinal must be one of {}".format(
', '.join(ordinal_map.keys())))
self.exits[ordinal] = other
other.exits[other_ordinal] = self
</code></pre>
<p>先整理房间</p>
<pre><code>map = """ A - B C
| |
D - E - F """
# bonus points if you can build a function that takes this as input and
# outputs the correct structure of rooms!!!
rooms = {key:Room(*args) for key,args in zip("ABCDEF",monster_loot_tuples)}
# monster_loot_tuples would be a list like [("Gargoyle","+1 Sword of Smiting"), ...]
</code></pre>
<p>然后添加链接</p>
<pre><code>rooms['A'].add_link(rooms['B'], 'East')
rooms['A'].add_link(rooms['D'], 'South')
rooms['D'].add_link(rooms['E'], 'East')
rooms['E'].add_link(rooms['F'], 'East')
rooms['F'].add_link(rooms['C'], 'North')
</code></pre>