这是我第一次使用StackOverflow,因此如果我做错了事,我深表歉意。
我在Python(不是3)中遇到问题,我不知道如何描述它,我正在尝试通过另一个变量调用包含类的变量。
这是代码:
import random
class Weapon:
def __init__(self, name, num, dx, dmg):
self.name = str(name)
self.name = self.name.lower()
self.xd = int(num)
self.dx = int(dx)
self.dmg = str(dmg)
weapon_list.append(self.name)
def attack(self):
#Defining Variables
crit = None
fail = None
display = True
#Ask user for AC and Bonus
ac = int(input("What is the AC?: "))
bon = int(input("What is the bonus?: "))
#Roll attack
roll_num = random.randrange(1,20,1)
#Crit Fail Manager
if roll_num == 1:
fail = True
display = False
#Crit Manager
elif roll_num == 20:
print("Crit!")
crit = True
display = False
#Add Bonus
roll_num += bon
#Print roll if not crit or fail
if display:
print(self.name + ": " + str(roll_num))
#If fail print Crit Fail
if fail:
print("Crit Fail!")
#Else if roll is larger than AC, roll damage
elif roll_num >= ac:
if not crit:
print("Hit!")
#Ask user for new bonus
bon = int(input("What is the bonus?: "))
roll_num = 0
#Roll damage and add bonus
for i in range(self.xd):
roll_num += random.randrange(1,self.dx,1)
roll_num += bon
#If a crit, add bonus crit damage
if crit:
roll_num += self.dx
#If not a fail, print damage roll
if not fail:
print(self.name + ": " + str(roll_num) + " " + self.dmg)
#Miss if roll is smaller than AC
else:
print("Miss")
weapon_list = []
battleaxe = Weapon("Battleaxe", 1, 8, "slashing")
glaive = Weapon("Glaive", 1, 10, "slashing")
"""
This is where the problem is arising, I know what the issue is, but I don't
know how to fix it without making a giant list
"""
print("Which weapon do you wish to use?")
for i in range(len(weapon_list)):
print(" > " + weapon_list[i].capitalize())
weapon = str(input("> "))
weapon = weapon.lower()
if weapon in weapon_list:
print("Valid Weapon")
for i in range(len(weapon_list)):
if weapon == weapon_list[i]:
print(weapon_list[i])
weapon_list[i].attack()
我知道为什么会出现错误,武器清单[i]会调用类名称的字符串版本,而不是类所包含的变量,但是我不知道如何在不列出所有武器的情况下解决问题在if和elif语句中的weapon_list中。
例:
if weapon == glaive.name:
glaive.attack()
elif weapon == battleaxe.name:
battleaxe.attack()
#And so on...
那就是我的问题“如何在不列出if语句列表的情况下调用包含类的变量”
最佳答案
您可以使用dict
而不是列表作为:
weapon_dict = {}
weapon_dict = {weapon.name: weapon}
当您收到输入时,可以将其用作:
weapon_dict[weapon_input].attack()