【问题标题】:How to pull information from classes through raw input如何通过原始输入从类中提取信息
【发布时间】:2016-01-23 01:49:08
【问题描述】:

我正在开发基于文本的 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.

如您所见,我使用 'item' 变量的结果来确定每个项目的 if / elif / else 语句行,如果该项目名称等于变量 'item' 会发生什么.

相反,我希望玩家能够输入项目名称,然后将原始输入转换为类名称。换句话说,如果我输入“sword”,我希望 Python 从“sword”对象类中提取信息,并将这些值应用于播放器。例如,武器的伤害会转移到玩家的技能上。如果一把剑造成 5 点力量伤害,玩家的力量将提高 5 点。我如何让 python 将一个类的值添加到另一个类而不需要大量的 if / else 语句?

【问题讨论】:

    标签: python python-2.7 game-development


    【解决方案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]
    ...
    

    请注意,文本被引用——它是文本数据,而未引用的值是实际的 Python 类——它们具有所有属性等。

    【讨论】:

    • 感谢您抽出宝贵时间提供帮助!当我使用 getattr 方法时,Python 返回一条错误消息,指出来自我的 Item 类的“Item”对象没有属性“name”。这是什么意思?
    • 这应该是一个单独的问题。此外,除了给出的非常好的答案之外,您还需要对输入的数据/异常捕获进行某种验证以完成“存储”功能。
    • 上面的代码假定它从项目类中挑选属性——如果它们已经实例化,则实例没有__name__ 属性。但是你可以使用item.__class__.__name__
    【解决方案2】:

    感谢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 时,它返回正确的项目名称,例如['iron longsword'],打印用户强度变量时,打印对应的数量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      相关资源
      最近更新 更多