用python写一个植物大战僵尸
时间: 2024-05-08 12:20:22 浏览: 72
Python编写植物大战僵尸
好的,我们开始讨论。以下是一个简单的植物大战僵尸游戏的Python代码示例:
```python
import random
# 游戏角色包括植物和僵尸
class Character:
def __init__(self, health, damage):
self.health = health
self.damage = damage
def attack(self, enemy):
enemy.health -= self.damage
# 植物类有不同类型,如豌豆射手、向日葵等等
class Plant(Character):
pass
# 僵尸类也有不同类型,如普通僵尸、路障僵尸等等
class Zombie(Character):
pass
# 游戏环境类,包括场地大小和各种游戏对象
class Environment:
def __init__(self, row, column):
self.row = row
self.column = column
self.plants = []
self.zombies = []
# 初始化场地,随机放置植物和僵尸
for i in range(row):
for j in range(column):
if random.random() < 0.2:
self.plants.append(Plant(100, 10))
if random.random() < 0.1:
self.zombies.append(Zombie(100, 5))
# 游戏主逻辑,每个回合植物和僵尸均会攻击对方
def run(self):
while len(self.plants) > 0 and len(self.zombies) > 0:
for plant in self.plants:
if len(self.zombies) == 0:
break
zombie = random.choice(self.zombies)
plant.attack(zombie)
if zombie.health <= 0:
self.zombies.remove(zombie)
for zombie in self.zombies:
if len(self.plants) == 0:
break
plant = random.choice(self.plants)
zombie.attack(plant)
if plant.health <= 0:
self.plants.remove(plant)
# 游戏结束后输出结果
if len(self.zombies) == 0:
print("Plants win")
else:
print("Zombies win")
```
您可以按照自己的需求修改和扩展此示例。
阅读全文