我正在开发一个RPG,我想找到捕获用户输入的最佳方法并根据用户的选择创建类实例。我首先介绍武器及其属性的列表。我已经用字典完成了。
melee_weapons = {'Broad Sword': {'damage':30, 'cost':25},
'Great Sword': {'damage':40, 'cost':45}, 'Spear': {'damage':20, 'cost':15}}
然后我有这个简单的武器课。
class Weapon:
def __init__(self, name, damage, cost):
self.name = name
self.damage = damage
self.cost = cost
接下来,我有所有武器类别的实例:
broad_sword = Weapon('Board Sword', 30, 25)
great_sword = Weapon('Great Sword', 40, 45)
最后,我有要求输入的功能:
def weapon_selection():
print(weapons + ranged_weapons)
wp = int(input('What weapon would you like to pick? Enter the corresponding number'))
if wp == 1:
Character.weapon = broad_sword
elif wp == 2:
Character.weapon = great_sword
此方法没有固有的问题,但是,如果有更快或更直观的方法,我将不胜感激。
答案 0 :(得分:0)
不需要字典
melee_weapons = {'Broad Sword': {'damage':30, 'cost':25},
'大剑':{'伤害':40,'成本':45},'矛':{'伤害':20,'成本':15}}
当您手动在行中提供此信息时
broad_sword = Weapon('Board Sword', 30, 25)
great_sword = Weapon('Great Sword', 40, 45)
如果您想实现字典,为什么不创建类实例,如:
user_input = 'Great Sword' # or something similar
user_weapon = Weapon(weapon_list[user_input], weapon_list[user_input]['damage'], weapon_list[user_input]['cost'])
这样,用户提供密钥,您便可以自动生成武器,而无需手动为字典中的每个输入创建武器实例