【发布时间】: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