human1有很多的武器包括弓箭BowAndArrow、魔杖Wand和剑Sward每种武器都具备攻击和防守两个行为。在每种行为实现中打印相应的提示信息即可例如弓箭攻击力90防守力80。2有很多的人物角色包括射手Shooter、法师Mags和武士Knight。每种人物都包括姓名和武器两个属性具有战斗、移动和变更武器的行为。姓名属性是角色的身份如射手的name默认就是射手武器属性默认是射手用弓箭、法师
class Weapon: def init(self, name): self.name = name
def attack(self):
print(self.name + "攻击力90")
def defend(self):
print(self.name + "防御力80")
class BowAndArrow(Weapon): def init(self): super().init("弓箭")
def attack(self):
super().attack()
print("弓箭射程较远")
class Wand(Weapon): def init(self): super().init("魔杖")
def attack(self):
super().attack()
print("魔杖施法较快")
class Sword(Weapon): def init(self): super().init("剑")
def attack(self):
super().attack()
print("剑的威力很大")
class Character: def init(self, name, weapon=None): self.name = name if weapon is None: if isinstance(self, Shooter): weapon = BowAndArrow() elif isinstance(self, Mags): weapon = Wand() elif isinstance(self, Knight): weapon = Sword() self.weapon = weapon
def attack(self):
print(self.name + "使用" + self.weapon.name + "攻击")
def defend(self):
print(self.name + "使用" + self.weapon.name + "防御")
def move(self):
pass
class Shooter(Character): def init(self): super().init("射手")
def move(self):
print("骑马移动")
class Mags(Character): def init(self): super().init("法师")
def move(self):
print("瞬移移动")
class Knight(Character): def init(self): super().init("武士")
def move(self):
print("奔跑移动")
class Test: def init(self): self.team1 = [Knight(), Mags(), Shooter()] self.team2 = [Knight(), Mags(), Shooter()]
def start(self):
print("攻击团队1:")
for character in self.team1:
character.attack()
character.defend()
character.move()
print("攻击团队2:")
for character in self.team2:
if isinstance(character, Shooter):
character.weapon = Wand()
elif isinstance(character, Mags):
character.weapon = Sword()
elif isinstance(character, Knight):
character.weapon = BowAndArrow()
character.attack()
character.defend()
character.move()
test = Test() test.start()
原文地址: https://www.cveoy.top/t/topic/bfif 著作权归作者所有。请勿转载和采集!