2016-01-23 59 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'],并且当打印用户强度变量时,它会打印重复量。