【发布时间】: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