简版——》未美化
import pygame
import sys
import random
# 初始化Pygame
pygame.init()
# 设置屏幕
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("植物大战僵尸 - 简化版")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 200, 0)
RED = (255, 0, 0)
# FPS
clock = pygame.time.Clock()
# 资源信息
PLANT_SIZE = 50
ZOMBIE_SIZE = 50
BULLET_SIZE = 10
BULLET_SPEED = 10
ZOMBIE_SPEED = 2
# 创建植物类
class Plant:
def __init__(self, x, y):
self.x = x
self.y = y
self.cooldown = 0 # 射击冷却时间
def draw(self):
pygame.draw.rect(screen, GREEN, (self.x, self.y, PLANT_SIZE, PLANT_SIZE))
def shoot(self):
if self.cooldown == 0: # 检查是否可以射击
bullets.append(Bullet(self.x + PLANT_SIZE, self.y + PLANT_SIZE // 2))
self.cooldown = 60 # 设置为1秒冷却
else:
self.cooldown -= 1 # 减少冷却倒计时
# 创建僵尸类
class Zombie:
def __init__(self, x, y):
self.x = x
self.y = y
self.hp = 5 # 僵尸血量
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, ZOMBIE_SIZE, ZOMBIE_SIZE))
def move(self):
self.x -= ZOMBIE_SPEED # 向左移动
# 创建子弹类
class Bullet:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
pygame.draw.circle(screen, WHITE, (self.x, self.y), BULLET_SIZE)
def move(self):
self.x += BULLET_SPEED # 向右移动
# 初始化
plants = [] # 存储植物
zombies = [] # 存储僵尸
bullets = [] # 存储子弹
spawn_counter = 100 # 僵尸生成冷却时间
# 主游戏循环
while True:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 点击鼠标左键放置植物
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mx, my = pygame.mouse.get_pos()
plants.append(Plant(mx - PLANT_SIZE // 2, my - PLANT_SIZE // 2))
# 生成僵尸
if spawn_counter == 0:
zombie_y = random.randint(0, screen_height - ZOMBIE_SIZE)
zombies.append(Zombie(screen_width, zombie_y))
spawn_counter = 150 # 每隔一段时间生成一个僵尸
else:
spawn_counter -= 1
# 更新植物逻辑
for plant in plants:
plant.draw()
plant.shoot()
# 更新僵尸逻辑
for zombie in zombies[:]:
zombie.move()
zombie.draw()
# 检查僵尸是否走到屏幕左侧
if zombie.x < 0:
zombies.remove(zombie)
# 定义一个子弹移除列表
bullets_to_remove = []
# 更新子弹逻辑
for bullet in bullets[:]:
bullet.move()
bullet.draw()
# 子弹离开屏幕时,将其加入移除列表
if bullet.x > screen_width:
bullets_to_remove.append(bullet)
# 检查子弹是否击中僵尸
for zombie in zombies[:]:
if zombie.x < bullet.x < zombie.x + ZOMBIE_SIZE and \
zombie.y < bullet.y < zombie.y + ZOMBIE_SIZE:
zombie.hp -= 1
if zombie.hp <= 0: # 僵尸死亡
zombies.remove(zombie)
bullets_to_remove.append(bullet) # 将子弹加入移除列表
break
# 移除所有需要移除的子弹
for bullet in bullets_to_remove:
if bullet in bullets:
bullets.remove(bullet)
# 刷新屏幕
pygame.display.flip()
clock.tick(60)
评论 (0)