2015-05-13 23 views
0

我正在嘗試編寫RPG遊戲,並堅持如何使用單一唯一ID調用物品,怪物,任務等來獲取所有數據。這基本上是基於this Code Review question的最佳答案。使用唯一ID(python)將商品添加到廣告資源中

與其將所有數據傳遞給Item類,我想調用一個方法或函數,它包含所有項目的字典,然後根據單個唯一ID將數據傳遞到Item

相關的代碼我現在有如下(所有代碼都可以找到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()) 
+1

您似乎將ListItem.list作爲一個**類方法**,因此您不一定需要* ListItem .__ init__'中的* anything *。然而,我不清楚你想要達到什麼目的。 – jonrsharpe

+0

爲什麼ListItem()首先是一個類?除非我讀錯了,它的意思是嚴格地說是一個**行爲**,在這種情況下,一個類可能不適合它。在我看來,'list'會更適合作爲'Inventory',FWIW的一種方法。 –

+0

感謝迄今爲止的答案。我是編程新手,所以試圖理解這些概念。澄清我想達到的目標: 而不是當玩家拿起物品並打電話給inventory.add_item(物品('劍',10,1,10,1,一把生鏽的長劍)) 我想'inventory.add_item(Item(這裏唯一的ID引用所有將數據傳遞給Item類的數據)。) –

回答

0

我得到它的工作,但也許不是最有效的方法如下:

1)刪除該列表項類

2)增加了詞典的主要方法

3)設置一個變量IID(項目ID)是無論在v ALUE是該項目在項目的每個值傳遞到項目類

房間

4)這不限制但我每個位置一個項目。

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])