python植物大战僵尸代码
pythonimport random
import time
class Plant:
def __init__(self, name, health, damage):
self.name = name
self.health = health
self.damage = damage
def attack(self, zombie):
print(f"{self.name} 攻击了 {zombie.name},造成 {self.damage} 点伤害")
zombie.health -= self.damage
class Zombie:
def __init__(self, name, health, damage):
self.name = name
self.health = health
self.damage = damage
def attack(self, plant):
print(f"{self.name} 攻击了 {plant.name},造成 {self.damage} 点伤害")
plant.health -= self.damage
def main():
sunflower = Plant("Sunflower", 50, 10)
pea_shooter = Plant("Pea Shooter", 40, 15)
zombie = Zombie("Regular Zombie", 60, 8)
while sunflower.health > 0 and pea_shooter.health > 0 and zombie.health > 0:
print("\n-- 植物大战僵尸 --")
print(f"{sunflower.name} 生命值: {sunflower.health}")
print(f"{pea_shooter.name} 生命值: {pea_shooter.health}")
print(f"{zombie.name} 生命值: {zombie.health}")
sunflower.attack(zombie)
pea_shooter.attack(zombie)
zombie.attack(sunflower)
zombie.attack(pea_shooter)
time.sleep(1)
if sunflower.health <= 0 and pea_shooter.health <= 0:
print("僵尸获胜!")
else:
print("植物获胜!")
if __name__ == "__main__":
main()
如果你对植物大战僵尸游戏的开发感兴趣,可以考虑使用游戏开发框架,例如Pygame。Pygame是一个基于Python的游戏开发库,可以帮助你更容易地创建游戏界面、处理用户输入、实现动画效果等。
pythonimport pygame
import sys
import random
# 初始化Pygame
pygame.init()
# 游戏窗口大小
WIDTH, HEIGHT = 800, 600
# 颜色定义
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("植物大战僵尸")
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 渲染背景
screen.fill(WHITE)
# 在窗口上绘制植物和僵尸
pygame.draw.rect(screen, RED, (100, 100, 50, 50)) # 植物
pygame.draw.rect(screen, RED, (600, 100, 50, 50)) # 僵尸
# 更新显示
pygame.display.flip()
# 控制游戏帧率
pygame.time.Clock().tick(30)