用Python写一个植物大战僵尸代码
时间: 2023-03-09 10:41:47 浏览: 123
这是一个 Python 实现的植物大战僵尸代码的示例:
```python
class Plant:
def __init__(self, name, damage, health):
self.name = name
self.damage = damage
self.health = health
def attack(self, zombie):
zombie.health -= self.damage
if zombie.health <= 0:
print(f'植物 {self.name} 攻击了僵尸,僵尸倒下了!')
else:
print(f'植物 {self.name} 攻击了僵尸,僵尸还剩余 {zombie.health} 点生命值。')
class Zombie:
def __init__(self, name, damage, health):
self.name = name
self.damage = damage
self.health = health
def attack(self, plant):
plant.health -= self.damage
if plant.health <= 0:
print(f'僵尸 {self.name} 攻击了植物,植物倒下了!')
else:
print(f'僵尸 {self.name} 攻击了植物,植物还剩余 {plant.health} 点生命值。')
# 创建植物
peashooter = Plant('豌豆射手', 10, 50)
sunflower = Plant('向日葵', 5, 30)
# 创建僵尸
zombie1 = Zombie('僵尸1', 20, 100)
zombie2 = Zombie('僵尸2', 15, 80)
# 植物攻击僵尸
peashooter.attack(zombie1)
sunflower.attack(zombie2)
# 僵尸攻击植物
zombie1.attack(peashooter)
zombie2.attack(sunflower)
```
希望这对你有帮助。
阅读全文