请写一个植物大战僵尸的python代码
时间: 2024-03-06 17:48:40 浏览: 17
以下是一个简单的植物大战僵尸游戏的Python代码,仅供参考:
```python
import random
# 植物类
class Plant:
def __init__(self, name, cost, hp, damage):
self.name = name
self.cost = cost
self.hp = hp
self.damage = damage
# 植物攻击僵尸
def attack(self, zombie):
zombie.hp -= self.damage
print(f"{self.name}对{zombie.name}造成了{self.damage}点伤害!")
if zombie.hp <= 0:
print(f"{zombie.name}被{self.name}击败了!")
return True
else:
return False
# 僵尸类
class Zombie:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
# 僵尸攻击植物
def attack(self, plant):
plant.hp -= self.damage
print(f"{self.name}对{plant.name}造成了{self.damage}点伤害!")
if plant.hp <= 0:
print(f"{plant.name}被{self.name}击败了!")
return True
else:
return False
# 游戏类
class Game:
def __init__(self):
self.plants = []
self.zombies = []
self.round = 1
# 添加植物
def add_plant(self, plant):
self.plants.append(plant)
# 添加僵尸
def add_zombie(self, zombie):
self.zombies.append(zombie)
# 游戏开始
def start(self):
print("游戏开始!")
while True:
# 显示当前局数
print(f"第{self.round}轮:")
# 显示可用植物
print("可用植物:")
for i, plant in enumerate(self.plants):
print(f"{i + 1}. {plant.name} ({plant.cost}阳光)")
# 显示可用僵尸
print("可用僵尸:")
for i, zombie in enumerate(self.zombies):
print(f"{i + 1}. {zombie.name} ({zombie.hp}血量)")
# 选择植物
while True:
plant_index = input("请选择植物(输入数字,0表示不选):")
if plant_index.isdigit() and int(plant_index) >= 0 and int(plant_index) <= len(self.plants):
break
else:
print("输入有误,请重新输入!")
if plant_index == "0":
print("不出战植物!")
else:
plant = self.plants[int(plant_index) - 1]
print(f"选择了{plant.name}!")
# 选择僵尸
while True:
zombie_index = input("请选择僵尸(输入数字):")
if zombie_index.isdigit() and int(zombie_index) >= 1 and int(zombie_index) <= len(self.zombies):
break
else:
print("输入有误,请重新输入!")
zombie = self.zombies[int(zombie_index) - 1]
print(f"选择了{zombie.name}!")
# 植物攻击
if plant.attack(zombie):
self.zombies.remove(zombie)
# 僵尸攻击
for zombie in self.zombies:
if zombie.attack(random.choice(self.plants)):
self.plants.remove(plant)
# 判断游戏是否结束
if len(self.plants) == 0:
print("游戏结束,僵尸胜利!")
break
elif len(self.zombies) == 0:
print("游戏结束,植物胜利!")
break
# 进入下一轮
print()
self.round += 1
# 创建植物和僵尸
peashooter = Plant("豌豆射手", 100, 10, 5)
sunflower = Plant("向日葵", 50, 5, 0)
zombie = Zombie("普通僵尸", 20, 2)
# 创建游戏并添加植物和僵尸
game = Game()
game.add_plant(peashooter)
game.add_plant(sunflower)
game.add_zombie(zombie)
# 开始游戏
game.start()
```