我正在通过重新发明轮子来自学Python,也就是说,编写一个带有互联房间的简单控制台冒险游戏。我的兴趣与其说是完成一个真正的游戏,不如说是学习抽象和数据结构。你知道吗
我定义了一些基本类,比如World
,其中包含对Rooms
的引用。这些房间有动作和项目。程序将检查每个房间的可用操作,并将其显示在列表中。所有这些都很有效,所以我试着把事情复杂化一点。你知道吗
I have two problems I can't get my head around. I'll try to explain them with as little detail as possible.
我就是这样为Room
定义一个可能的操作的,在本例中,它是一个Room
,由名为main
的变量引用(目前数据在模块中声明,稍后从CSV
或XML
文件中读取):
main.actions = [Action(type = 'move',
result = 'west',
desc = 'Go to the West Room.')]
我需要定义一个动作类型,因为有些动作不是运动(例如,捡起、拉动操纵杆)。稍后我将修改它以使用Action的子类,这不是这里的问题。你知道吗
这里的“west”字符串指的是将作为操作结果的房间,即在执行操作时它将成为当前房间。你知道吗
However, I'd like the result to be the Room object itself, not a string ID. But I can't do that until all the
Rooms
have been initialized.
所以我用世界对象的以下方法解决了这个问题,这是可行的:
def connect_rooms(self):
'''
Once all the rooms have been created,
replace all the string reference to other rooms by the Room objects themselves.
'''
for room in self.rooms:
for action in room.actions:
if action.type == 'move':
room_object = fetch_room(self, action.result)
action.result = room_object
fetch_room()
函数(全局作用域)只执行以下操作:
def fetch_room(world, shortname):
# Find a room item by its shortname
for room in world.rooms:
if room.shortname == shortname:
return room
return None
我确信有更好的方法来处理这个问题,因为在节点之间创建连接似乎是一个基本的抽象概念。你知道吗
另一个(相关的)问题是,我正在尝试创建内置于动作本身的条件,以便程序仅在满足动作中定义的条件时才向玩家提出这些条件。对于数据的初始构建,我不能引用任何其他内容,因为它尚未创建。我想过以字符串形式添加一个条件,然后用exec()运行它,但这看起来非常愚蠢和丑陋:
main.actions = [Action(type = 'move',
result = 'west',
desc = 'Go to the West Room.',
conditions = ["player.has('smallkey')"])]
如果有一篇关于构建这样的数据结构而不发疯的文章,我很乐意阅读。你知道吗
谢谢你。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐