我正在尝试编写一个RPG游戏,并坚持如何使用一个唯一ID来调用项目,怪物,任务等来获取所有数据。这主要基于this Code Review question中的最佳答案。
我不想将所有数据传递给Item
类,而是调用一个方法或函数,该方法或函数包含所有项目的字典,然后根据这些项目将数据传递给Item
一个唯一的ID。
我目前拥有的相关代码如下(所有代码都可以找到here):
inventory.add_item(Item(ListItem.list(1))) #The 1 is a placeholder to specifically get the sword.
class Inventory(object):
def __init__(self):
self.items = {}
def add_item(self, item):
self.items[item.name] = item
class Item(object):
def __init__(self, name, attack, armor, cost, quantity, description):
self.name = name
self.attack = attack
self.armor = armor
self.cost = cost
self.quantity = quantity
self.description = description
class ListItem(object):
# This is a database to hold all the games loot/items
def __init__(self):
# What goes here?
def list(self, itemid):
# Probably don't even need this here? Can it go under __init__?
all_items = {
1: {"name": "Sword", "desc": "A rusty looking sword", "dmg": 5, "arm": 1, "val": 10},
}
return list(all_items[itemid].values())
答案 0 :(得分:0)
我得到了它的工作,但也许不是最有效的方式如下:
1)删除了ListItem类
2)将字典添加到主方法
3)将变量iid(项目ID)设置为房间中项目的值
4)将项目的每个值传递给Item类
但这限制了我每个位置的一个项目。
location = {
2: {"name": "Cave - Upper area",
"description": "Placeholder",
"west": 1,
"south": 4,
"item": "sword",
"iid": 1},
all_items = {
1: {"name": "Sword", "dmg": 5, "arm": 1, "val": 10, "desc": "A rusty looking sword"},
100: {"name": "Beer", "desc": "A foaming mug of ale", "dmg": 1, "arm": 1, "val": 1}
}
elif move[0] == "get":
if "iid" in location[currentLocation] and move[1] in location[currentLocation]["item"]:
iid = location[currentLocation]["iid"]
inventory.add_item(Item(all_items[iid]["name"], all_items[iid]["dmg"], all_items[iid]["arm"], all_items[iid]["val"], all_items[iid]["desc"]))
print("%s added to inventory!\n" % all_items[iid]["name"])
del location[currentLocation]["item"]
else:
print("\nThere is no %s here!\n" % move[1])