如何通过原始输入从 类 中提取信息

How to pull information from classes through raw input

我很喜欢基于文本的角色扮演游戏的开发。现在,我的商店系统很长很复杂,因为有很多重复的代码。我目前的想法是我有一个可供出售的物品清单,并且根据用户的原始输入,它会将这些物品与 if / else 语句相关联,假设我有合适的物品和播放器 classes 制作,即:

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'.

相反,我希望玩家能够输入物品名称,然后将原始输入翻译成 class 名称。换句话说,如果我输入 'sword',我希望 Python 从 'sword' 对象 class 中提取信息,并将这些值应用到播放器。例如,武器的伤害会转移到玩家的技能上。如果一把剑造成 5 点力量伤害,玩家的力量将提高 5 点。我怎样才能 python 将一个 class 的值加到另一个而不用一大堆 if / else 语句?

如果您将所有游戏项目 classes 名称放在一个地方(例如,一个模块),您可以使用 Python 的 getattr 检索 class本身有它的字符串。

所以,例如,假设您有一个 items.py 文件执行类似以下操作:

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

(或者直接在 items 模块中定义那些 classes) 你可以在那里继续做:

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 classes - 具有所有属性等。

感谢 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

即使在原始输入中输入 'iron' 也会拉出正确的项目。打印 user.inventory 时,它 returns 正确的项目名称,例如['iron longsword'],并且在打印用户强度变量时,它会打印相应的数量。