2016-01-23 70 views
1

我很好地開發基於文本的RPG。現在,我的商店系統非常冗長而且令人費解,因爲有很多重複的代碼。我目前正在進行的想法是,我有一個可供銷售的物品清單,並且基於用戶的原始輸入,它會將這些物品與if/else語句相關聯,假設我有適當的物品和玩家類,即:如何通過原始輸入從課堂獲取信息

store = ['sword', 'bow', 'health potion'] 
while True: 
    inp = raw_input("Type the name of the item you want to buy: ") 
    lst = [x for x in store if x.startswith(inp) 
    if len(lst) == 0: 
     print "No such item." 
     continue 
    elif len(lst) == 1: 
     item = lst[0] 
     break 
    else: 
     print "Which of the following items did you mean?: {0}".format(lst) 
     continue 
if item == 'sword': 
    user.inventory['Weapons'].append(sword.name) 
    user.strength += sword.strength 
    user.inventory['Gold'] -= sword.cost 
elif item == 'bow' 
    #Buy item 
#Rest of items follow this if statement based off the result of item. 

正如你所看到的,我使用的是「項目」變量的結果來確定行,如果/ elif的/爲每個項目else語句,會發生什麼,如果該項目名稱等於到變量'item'。相反,我希望玩家能夠輸入項目名稱,然後將原始輸入轉換爲類名稱。換句話說,如果我輸入'劍',我希望Python從'劍'對象類中提取信息,並將這些值應用到玩家。例如,武器的傷害轉移到玩家的技能上。如果一把劍造成5點力量傷害,那麼玩家的力量會提高5.如何讓python將一個類別的值添加到另一個類別而不需要大量的if/else語句?

回答

1

如果你在一個地方(例如,一個模塊)中擁有所有的遊戲項目類名稱,那麼可以使用Python的getattr來檢索具有其字符串的類本身。

因此,舉例來說,假設你有一個items.py文件,該文件確實是這樣的:

from weapons import Sword, Bow, Axe, MachinneGun 
from medicine import HealthPotion, MaxHealthPotion, Poison, Antidote 

(或只是定義這些類items模塊在那裏) 您可以繼續存在做:

import items 
... 
inp = raw_input("Type the name of the item you want to buy: ") 
... 
item_class = getattr(items, inp) 

user.inventory.append(item_class.__name__) 
if hasattr(item_class, strength): 
    user.strength += item_class.strength 

等等。

你也可以簡單地創建一個字典:

from items import Sword, Bow, HealthPotion 
store = {"sword: Sword, "bow": Bow, "health potion": HealthPotion} 
... 
item_class = store[inp] 
... 

注意,文本quoted-它是文本數據,以及帶引號的值是實際的Python類 - 裏面有所有的屬性和這樣。

+0

感謝您花時間幫忙!當我使用getattr方法時,Python返回一條錯誤消息,說我的Item類中的'Item'對象沒有屬性'__name__'。這是什麼意思? – PyDive

+0

這應該是一個單獨的問題。除了給出的相當好的答案之外,您還需要驗證輸入的數據/異常情況以完成「存儲」功能。 – Wakaru44

+0

上面的代碼假定它從項目類中選擇屬性 - 如果它們已經實例化,則實例不具有「__name__」屬性。但是你可以使用'item .__ class __.__ name__'。 – jsbueno

0

感謝jsbueno,我的代碼現在可以工作。這是我用他的字典法官方的解決辦法:

from objects import ironsword 
class player(object): 
    def __init__(self, strength): 
     self.strength = strength 
     self.inventory = [] 

user = player(10) 
store = {'iron longsword': ironsword} 
while True: 
    inp = raw_input("Type the name of the item you want to buy: ") 
    lst = [x for x in store if x.startswith(inp)] 
    if len(lst) == 0: 
     print "No such item." 
     continue 
    elif len(lst) == 1: 
     item = lst[0] 
     break 
    else: 
     print "Which of the following items did you mean?: {0}".format(lst) 
     continue 
item_class = store[item] 
user.inventory.append(item_class.name) 
user.strength += item_class.strength 
print user.inventory 
print user.strength 

打字甚至是「鐵」到原始輸入將拉動正確的項目。當打印user.inventory時,它返回正確的項目名稱,例如['iron longsword'],並且當打印用戶強度變量時,它會打印重複量。