酷代码 AI
菜单
服务商

Python 模拟猫狗大战:从属性设定到生死对决

```python class Animal: def __init__(self, nickname, breed, attack_power, health): self.nickname = nickname self.breed = breed self.attack_power = attack_power self.health = health def attack(self, other): other.health -= self.attack_power print(f"{self.nickname} attacks {other.nickname}!") if other.health <= 0: print(f"{other.nickname} has been killed by {self.nickname}!") def eat(self, food_value): self.health += food_value print(f"{self.nickname} eats and gains {food_value} health points.") class Cat(Animal): def __init__(self, nickname, breed, attack_power, health): super().__init__(nickname, breed, attack_power, health) class Dog(Animal): def __init__(self, nickname, breed, attack_power, health): super().__init__(nickname, breed, attack_power, health) # Example usage: cat1 = Cat("Tom", "Siamese", 10, 50) dog1 = Dog("Rex", "German Shepherd", 15, 60) cat1.attack(dog1) dog1.eat(20) cat1.attack(dog1) dog1.attack(cat1) cat1.eat(10) ``` 这个程序定义了一个基类 `Animal`,以及两个派生类 `Cat` 和 `Dog`。每个动物对象都有昵称、品种、攻击力和生命值属性。猫和狗可以相互攻击,减少对方的生命值,并且可以通过吃来增加自己的生命值。当生命值小于等于0时,会打印出被杀死的消息。 ######[AI写代码神器 | 453点数解答 | 2024-12-20 10:14:18]

相关提问
发财导航,免费问AI
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]