我正在开发基于文本的角色扮演游戏。现在,我的商店系统非常长且复杂,有很多重复的代码。我目前的想法是,我有一个可出售的元素列表,并根据用户的原始输入,它将这些元素与 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.
如您所见,我使用“item”变量的结果来确定每个项目的 if/elif/else 语句行,以及如果该项目名称等于变量“item”会发生什么.
相反,我希望玩家能够输入项目名称,然后将该原始输入转换为类名称。换句话说,如果我输入“sword”,我希望 Python 从“sword”对象类中提取信息,并将这些值应用于玩家。例如,武器的伤害会转移到玩家的技能上。如果一把剑造成 5 点力量伤害,玩家的力量将提高 5 点。我怎样才能让 python 将一个类别的值添加到另一个类别,而无需大量的 if/else 语句?
最佳答案
如果您将所有游戏项目类名称放在一个位置(例如,一个模块),则可以使用 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]
...
请注意,文本被引用 - 它是文本数据,未引用的值是实际的 Python 类 - 具有所有属性等。
关于python - 如何通过原始输入从类中提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34958692/