我正在尝试根据用户输入使用变量来调用对象属性。这是一款文字游戏。例如,想法是玩家键入“帽子”,此功能检查玩家对象的self.inventory = []中名为“帽子”的Item对象,如果存在这样的对象,它将把Item对象附加到玩家对象的对应属性,在这种情况下为self.helm = []。
为此,我尝试使equipItem等于装备类的类类型的变量,该类类型应与玩家对象的装备属性之一相同。
move = input("To equip, unequip, or an use item, type [item name]. To trade
in item for XP, type 't [item name]'. Type 'x' to exit inventory:
").lower().split()
print(move[0])
for i in currentPlayer.inventory:
print(i.name)
if i.name == move[0]:
print(i)
equipItem = i.itemClass
currentPlayer.equipItem.append(i)
currentPlayer.inventory.remove(i)
print(currentPlayer.equipItem)
但是,这当然会引发错误,因为不是玩家属性中的“ equipItem”。所以我的问题是我如何才能获得想要的结果?我可以使用变量来调用对象属性吗?
我知道这很可能很老套,无论如何我都不喜欢这种方法,所以也欢迎其他方法的建议!
下面的玩家类和物品类:
class Player:
def __init__(self, name):
self.name = name
self.health = 10
self.maxHealth = 10
self.inventory = [Item(1, 1), Item(2, 2)]
self.weapon = [Item(0, 1)]
self.helm = [Item(1, 0)]
self.shield = [Item(5, 0)]
self.boots = [Item(3, 0)]
self.greaves = [Item(4, 0)]
self.gloves = [Item(6, 0)]
self.cuirass = [Item(2, 0)]
self.defaultPotion = []
self.attack = 5 + self.weapon[0].attack
armorClass = self.helm[0].defense + self.shield[0].defense +
self.boots[0].defense + self.greaves[0].defense +
self.gloves[0].defense
+ self.cuirass[0].defense
self.defense = 1 + armorClass
self.level = 1
self.experience = 0
self.offensiveMagic = 0
self.defenseiveMagic = 0
self.offensiveCombat = 0
self.weightClass = 10
def __str__(self):
return self.name
class Item:
def __init__(self, itemType, subType):
#denotes type of item (wepaon, gloves, etc)
self.itemType = allItems[itemType]
#denotes item name and stats (sword, attack value, etc)
self.subType = self.itemType[subType]
#denotes how item is used (euip, consume, etc)self.subType = 0:
if subType == 0:
self.itemClass = 'weapon'
elif subType == 1:
self.itemClass = 'helm'
elif subType == 2:
self.itemClass = 'cuirass'
elif subType == 3:
self.itemClass = 'boots'
elif subType == 4:
self.itemClass = 'greaves'
elif subType == 5:
self.itemClass = 'shield'
elif subType == 6:
self.itemClass = 'gloves'
self.name = self.subType['name']
self.attack = self.subType['attack']
self.defense = self.subType['defense']
# self.equip = 'no'
def __str__(self):
return self.itemType
return self.name
return self.attack
return self.defense