请用Python写3个类:人,狗,武器。 人类初始化包括姓名,年龄,性别,并使用武器,人的血值是100,包括2个方法 人使用武器打狗,人自己疗伤(血值每次增加30)。每个方法后都打印人、狗还剩余多少血值。 狗类初始化包括姓名,年龄,攻击值,狗的血值是100;包括1个方法,人咬狗,攻击值根据狗的不同类型大小不同。 武器类,初始化不同武器,包括3个方法,其实不同方法的武器及杀伤力分别昌:棍30,刀40,枪45。
时间: 2023-05-20 15:07:14 浏览: 109
class Person:
def __init__(self, name, age, sex, weapon):
self.name = name
self.age = age
self.sex = sex
self.weapon = weapon
self.hp = 100
def use_weapon_to_attack_dog(self, dog):
attack = self.weapon.attack()
dog.get_hurt(attack)
print("{} used {} to attack {}, {}'s hp={}, {}'s hp={}".format(self.name, self.weapon.__class__.__name__, dog.name, self.name, self.hp, dog.name, dog.hp))
def heal(self):
self.hp += 30
if self.hp > 100:
self.hp = 100
print("{} healed, {}'s hp={}".format(self.name, self.name, self.hp))
class Dog:
def __init__(self, name, age, attack_value):
self.name = name
self.age = age
self.attack_value = attack_value
self.hp = 100
def bite(self, person):
attack = self.attack_value
person.hp -= attack
if person.hp < 0:
person.hp = 0
print("{} bit {}, {}'s hp={}, {}'s hp={}".format(self.name, person.name, person.name, person.hp, self.name, self.hp))
def get_hurt(self, attack):
self.hp -= attack
if self.hp < 0:
self.hp = 0
class Weapon:
def attack(self):
pass
class Stick(Weapon):
def attack(self):
return 30
class Knife(Weapon):
def attack(self):
return 40
class Gun(Weapon):
def attack(self):
return 45
# example usage
person = Person("Tom", 20, "male", Knife())
dog = Dog("Wangcai", 3, 10)
person.use_weapon_to_attack_dog(dog)
dog.bite(person)
person.heal()
阅读全文