8、定义父类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 19:02:57 浏览: 205
父类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 0
return self.weapon.attack()
```
子类Soldier和Magicer的定义如下:
```
class Soldier(Role):
pass
class Magicer(Role):
pass
```
父类武器Weapon的定义如下:
```
class Weapon:
def __init__(self, name):
self.name = name
def attack(self):
return 0
```
三个子类Sword,Knife,Mace的定义如下:
```
class Sword(Weapon):
def attack(self):
return 100
class Knife(Weapon):
def attack(self):
return 200
class Mace(Weapon):
def attack(self):
return 300
```
根据题目要求,我们可以编写以下代码:
```
soldiers = []
magicers = []
weapons = [Sword('剑'), Knife('刀'), Mace('狼牙棒')]
while len(soldiers) < 5 or len(magicers) < 5:
cmd = input('请输入指令:')
if cmd == 'A':
if len(soldiers) < 5:
name = input('请输入战士名称:')
soldier = Soldier(name)
soldiers.append(soldier)
print('创建战士成功!')
else:
print('战士已满,请重新输入指令!')
elif cmd == 'B':
if len(magicers) < 5:
name = input('请输入法师名称:')
magicer = Magicer(name)
magicers.append(magicer)
print('创建法师成功!')
else:
print('法师已满,请重新输入指令!')
elif cmd == '1':
weapon = weapons[0]
for role in soldiers + magicers:
if role.weapon is None:
role.set_weapon(weapon)
print(f'{role.name} 装备了 {weapon.name}!')
break
else:
print('所有角色都已装备武器,请重新输入指令!')
elif cmd == '2':
weapon = weapons[1]
for role in soldiers + magicers:
if role.weapon is None:
role.set_weapon(weapon)
print(f'{role.name} 装备了 {weapon.name}!')
break
else:
print('所有角色都已装备武器,请重新输入指令!')
elif cmd == '3':
weapon = weapons[2]
for role in soldiers + magicers:
if role.weapon is None:
role.set_weapon(weapon)
print(f'{role.name} 装备了 {weapon.name}!')
break
else:
print('所有角色都已装备武器,请重新输入指令!')
else:
print('无效指令,请重新输入!')
if all(role.weapon is not None for role in soldiers + magicers):
total_damage = sum(role.attack() for role in soldiers + magicers)
print(f'组队攻击,总伤害值为 {total_damage}!')
else:
print('还有角色未装备武器,请重新输入指令!')
```
运行以上代码,可以按照题目要求创建角色和武器,并组队攻击,输出攻击总值。
阅读全文