python猫狗大战代码
时间: 2023-09-02 12:12:24 浏览: 88
以下是一个简单的 Python 猫狗大战代码示例:
```python
import random
class Animal:
def __init__(self, name, strength):
self.name = name
self.strength = strength
def attack(self):
return self.strength * random.uniform(0.5, 1.5)
class Cat(Animal):
def __init__(self, name, strength):
super().__init__(name, strength)
self.type = "cat"
def meow(self):
print("Meow!")
class Dog(Animal):
def __init__(self, name, strength):
super().__init__(name, strength)
self.type = "dog"
def bark(self):
print("Woof!")
def battle(animal1, animal2):
print(f"{animal1.type.capitalize()} {animal1.name} vs {animal2.type.capitalize()} {animal2.name}!")
while animal1.strength > 0 and animal2.strength > 0:
if random.random() < 0.5:
print(f"{animal1.type.capitalize()} {animal1.name} attacks {animal2.type} {animal2.name}!")
animal2.strength -= animal1.attack()
else:
print(f"{animal2.type.capitalize()} {animal2.name} attacks {animal1.type} {animal1.name}!")
animal1.strength -= animal2.attack()
if animal1.strength > animal2.strength:
print(f"{animal1.type.capitalize()} {animal1.name} wins!")
else:
print(f"{animal2.type.capitalize()} {animal2.name} wins!")
cat1 = Cat("Fluffy", 10)
dog1 = Dog("Buddy", 15)
cat1.meow()
dog1.bark()
battle(cat1, dog1)
```
这个程序演示了一个简单的猫狗大战游戏,其中 Animal 类表示所有动物的基类,而 Cat 和 Dog 类则表示具体的猫和狗。每个动物都有一个攻击力属性和一个攻击方法,攻击力在每次攻击时都会乘以一个随机因素,以模拟攻击的随机性。战斗函数使用一个 while 循环模拟战斗,当一方的攻击力小于或等于 0 时,战斗结束,输出胜利方。最后,我们创建了一个猫和狗实例,然后让它们互相攻击。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)