植物大战僵尸

import pygame
import random

--- 常量定义 ---
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
WHITE = (255, 255, 255)
GREEN = (0, 255, 0) # 植物颜色
RED = (255, 0, 0) # 僵尸颜色
BLACK = (0, 0, 0)

--- 类定义 ---
class Plant:
def init(self, x, y):
self.rect = pygame.Rect(x, y, 50, 50)

def draw(self, screen):
pygame.draw.rect(screen, GREEN, self.rect)

在植物上画个简单的叶子标记

pygame.draw.circle(screen, BLACK, (self.rect.x+15, self.rect.y+15), 5)

class Zombie:
def init(self):
self.rect = pygame.Rect(SCREEN_WIDTH, random.randint(50, 550), 40, 60)
self.speed = random.randint(1, 3)

def update(self):
self.rect.x -= self.speed

def draw(self, screen):
pygame.draw.rect(screen, RED, self.rect)

画个简单的僵尸眼睛

pygame.draw.rect(screen, BLACK, (self.rect.x+30, self.rect.y+10, 5, 5))

--- 主程序 ---
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("植物大战僵尸 - 入门版")
clock = pygame.time.Clock()

plants = []
zombies = []
spawn_timer = 0

running = True
while running:
screen.fill(WHITE)

  1. 事件处理
    for event in pygame.event.get():
    if event.type == pygame.QUIT:
    running = False

点击鼠标左键种植物

if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
plants.append(Plant(event.pos[0], event.pos[1]))

  1. 游戏逻辑更新
    spawn_timer += 1
    if spawn_timer > 60: # 每60帧生成一个僵尸
    zombies.append(Zombie())
    spawn_timer = 0

for z in zombies:
z.update()

简单的移除屏幕外僵尸逻辑

if z.rect.right < 0:
zombies.remove(z)

  1. 绘制画面
    for p in plants:
    p.draw(screen)
    for z in zombies:
    z.draw(screen)

【特殊标志】在此处显示你的学号后四位
假设学号后四位是 1234,你可以修改这里的数字
font = pygame.font.Font(None, 36) # 使用默认字体

为了防止没有字体文件报错,这里简单用文字表示,实际运行会有显示

text = font.render("ID: 1234", True, (0, 0, 255))
screen.blit(text, (10, 10))

pygame.display.flip()
clock.tick(60)

pygame.quit()

if name == "main":
main()

posted @ 2026-07-03 14:42  guoqiiiii  阅读(2)  评论(0)    收藏  举报