写一段植物大战僵尸的python代码
以下是一个简单的植物大战僵尸的Python代码示例:
import random
# 定义植物类
class Plant:
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
def attack_zombie(self, zombie):
zombie.health -= self.attack
def is_dead(self):
return self.health <= 0
# 定义僵尸类
class Zombie:
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
def attack_plant(self, plant):
plant.health -= self.attack
def is_dead(self):
return self.health <= 0
# 初始化植物和僵尸
sunflower = Plant("Sunflower", 50, 10)
peashooter = Plant("Peashooter", 70, 15)
zombie = Zombie("Zombie", 100, 20)
# 游戏循环
while True:
# 植物攻击僵尸
sunflower.attack_zombie(zombie)
peashooter.attack_zombie(zombie)
# 判断僵尸是否死亡
if zombie.is_dead():
print("Zombie is defeated!")
break
# 僵尸攻击植物
zombie.attack_plant(sunflower)
zombie.attack_plant(peashooter)
# 判断植物是否死亡
if sunflower.is_dead() and peashooter.is_dead():
print("Plants are defeated!")
break
# 输出当前状态
print(f"Sunflower health: {sunflower.health}")
print(f"Peashooter health: {peashooter.health}")
print(f"Zombie health: {zombie.health}")
print("")
# 生成随机数控制回合速度
time.sleep(random.randint(1, 3))
这个代码示例中,我们定义了一个植物类和一个僵尸类,每个类都有自己的名字、生命值和攻击力。在游戏循环中,植物和僵尸相互攻击,直到其中一方死亡。每个回合结束后,程序会输出当前状态,然后通过随机生成的时间间隔控制回合速度。
请注意,这只是一个简单的示例,实际的植物大战僵尸游戏要复杂得多。你可以根据自己的需求和想法进一步扩展和改进代码
原文地址: http://www.cveoy.top/t/topic/hQTO 著作权归作者所有。请勿转载和采集!