定义父类Role,定义属性name, 两个子类Soldier和Magicer 定义父类武器Weapon, 定义属性name, 方法attack()攻击 三个子类Sword,Knife,Mace(狼牙棒), 其中 Sword的attack伤害值为100 Knife的attack伤害值为200 Mace的attack伤害值为300 其中战士Soldier和法师Magicer可以使用任意一种武器 从控制台输入指令 1>输入A,创建Soldier 2>输入B,创建Magicer 3>输入1,创建Sword 4>输入2,创建Knife 5>输入3,创建Mace 当战士和法师满5个时,而且每个角色配备自己选择的武器, 组队去攻击,求攻击总值
时间: 2023-04-03 11:02:37 浏览: 140
父类Role的定义如下:
```
class Role:
def __init__(self, name):
self.name = name
self.weapon = None
def set_weapon(self, weapon):
self.weapon = weapon
def attack(self):
if self.weapon is None:
return
else:
return self.weapon.attack()
```
子类Soldier和Magicer的定义如下:
```
class Soldier(Role):
def __init__(self, name):
super().__init__(name)
class Magicer(Role):
def __init__(self, name):
super().__init__(name)
```
父类Weapon的定义如下:
```
class Weapon:
def __init__(self, name):
self.name = name
def attack(self):
pass
```
子类Sword、Knife和Mace的定义如下:
```
class Sword(Weapon):
def __init__(self, name):
super().__init__(name)
def attack(self):
return 100
class Knife(Weapon):
def __init__(self, name):
super().__init__(name)
def attack(self):
return 200
class Mace(Weapon):
def __init__(self, name):
super().__init__(name)
def attack(self):
return 300
```
下面是主程序的实现:
```
soldiers = []
magicers = []
weapons = []
while True:
command = input("请输入指令:")
if command == "A":
if len(soldiers) < 5:
name = input("请输入战士的名字:")
soldier = Soldier(name)
soldiers.append(soldier)
print("创建战士成功!")
else:
print("战士已满!")
elif command == "B":
if len(magicers) < 5:
name = input("请输入法师的名字:")
magicer = Magicer(name)
magicers.append(magicer)
print("创建法师成功!")
else:
print("法师已满!")
elif command == "1":
name = input("请输入武器的名字:")
weapon =
阅读全文