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

时间:2016-01-23 01:49:09

标签: python python-2.7 game-development

我很好地开发了基于文本的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.

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

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

2 个答案:

答案 0 :(得分: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类 - 它们具有所有属性等。

答案 1 :(得分: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'],并且在打印用户强度变量时,会打印出repsective数量。

相关问题