植物大战僵尸简化版
下面是一个简化版的植物大战僵尸游戏的Python实现,使用Pygame库来创建游戏窗口和处理图形渲染。
import pygame
import random
import os
import sys
from pygame.locals import *
# 初始化pygame
pygame.init()
# 游戏常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BROWN = (139, 69, 19)
PATH_Y = 300 # 僵尸行走路径的Y坐标
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("植物大战僵尸 - 简化版")
clock = pygame.time.Clock()
# 加载资源
def load_image(name, scale=1):
try:
image = pygame.image.load(name).convert_alpha()
if scale != 1:
new_width = int(image.get_width() * scale)
new_height = int(image.get_height() * scale)
image = pygame.transform.scale(image, (new_width, new_height))
return image
except pygame.error as e:
print(f"无法加载图像: {name}")
print(e)
return pygame.Surface((50, 50))
# 植物类
class Plant(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = load_image("plant.png", 0.5)
if self.image.get_width() == 50: # 如果加载失败,使用默认矩形
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.shoot_timer = 0
def update(self):
# 每隔一段时间发射豌豆
self.shoot_timer += 1
if self.shoot_timer >= 60: # 每60帧发射一次
self.shoot()
self.shoot_timer = 0
def shoot(self):
# 创建一个豌豆并添加到组中
pea = Pea(self.rect.centerx, self.rect.centery)
all_sprites.add(pea)
peas.add(pea)
# 豌豆类
class Pea(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = load_image("pea.png", 0.3)
if self.image.get_width() == 50: # 如果加载失败,使用默认矩形
self.image.fill((0, 128, 0)) # 深绿色
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = 7
def update(self):
self.rect.x += self.speed
# 如果豌豆飞出屏幕,移除它
if self.rect.right > SCREEN_WIDTH:
self.kill()
# 僵尸类
class Zombie(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = load_image("zombie.png", 0.5)
if self.image.get_width() == 50: # 如果加载失败,使用默认矩形
self.image.fill(BROWN)
self.rect = self.image.get_rect()
self.rect.x = SCREEN_WIDTH
self.rect.y = PATH_Y - self.rect.height // 2
self.health = 100
self.speed = 1
def update(self):
self.rect.x -= self.speed
# 如果僵尸到达屏幕左侧,游戏结束
if self.rect.left <= 0:
game_over("僵尸突破防线!")
def damage(self, amount):
self.health -= amount
if self.health <= 0:
self.kill()
return True
return False
# 游戏结束函数
def game_over(message):
font = pygame.font.SysFont(None, 72)
text = font.render(message, True, WHITE)
text_rect = text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
screen.blit(text, text_rect)
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
sys.exit()
# 检查资源文件夹是否存在,如果不存在则创建
if not os.path.exists("resources"):
os.makedirs("resources")
# 设置资源路径
plant_img_path = "resources/plant.png"
pea_img_path = "resources/pea.png"
zombie_img_path = "resources/zombie.png"
# 如果资源文件不存在,创建占位图像
if not os.path.exists(plant_img_path):
pygame.image.save(pygame.Surface((100, 100), pygame.SRCALPHA), plant_img_path)
if not os.path.exists(pea_img_path):
pygame.image.save(pygame.Surface((30, 10), pygame.SRCALPHA), pea_img_path)
if not os.path.exists(zombie_img_path):
pygame.image.save(pygame.Surface((100, 150), pygame.SRCALPHA), zombie_img_path)
# 创建精灵组
all_sprites = pygame.sprite.Group()
plants = pygame.sprite.Group()
peas = pygame.sprite.Group()
zombies = pygame.sprite.Group()
# 放置一些植物
for i in range(5):
plant = Plant(100 + i * 150, PATH_Y - 50)
all_sprites.add(plant)
plants.add(plant)
# 游戏主循环
running = True
zombie_spawn_timer = 0
while running:
# 保持循环运行在正确速度
clock.tick(FPS)
# 处理输入事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新
all_sprites.update()
# 随机生成僵尸
zombie_spawn_timer += 1
if zombie_spawn_timer >= 120: # 每120帧生成一个僵尸
zombie = Zombie()
all_sprites.add(zombie)
zombies.add(zombie)
zombie_spawn_timer = 0
# 检查豌豆和僵尸的碰撞
hits = pygame.sprite.groupcollide(peas, zombies, True, False)
for pea, zombie_list in hits.items():
for zombie in zombie_list:
if zombie.damage(10): # 僵尸受到10点伤害
pass # 如果僵尸死亡,可以在这里添加奖励分数等逻辑
# 渲染
screen.fill(BLACK)
pygame.draw.line(screen, WHITE, (0, PATH_Y), (SCREEN_WIDTH, PATH_Y), 2) # 僵尸路径
all_sprites.draw(screen)
# 更新屏幕
pygame.display.flip()
pygame.quit()
如何运行游戏
确保已安装Python和Pygame库。如果未安装Pygame,可以通过以下命令安装:
PlainText
复制
pip install pygame
将上述代码保存为一个Python文件(如zombie_game.py)。
运行文件:
PlainText
复制
python zombie_game.py
游戏说明
游戏中会自动生成植物(豌豆射手)和僵尸。
植物会定期发射豌豆攻击僵尸。
僵尸会从右侧向左侧移动,尝试突破防线。
如果僵尸到达屏幕左侧,游戏结束。
注意事项
游戏会自动创建一个resources文件夹来存储资源图像。
如果图像加载失败,游戏会使用默认的颜色矩形代替。

2万+

被折叠的 条评论
为什么被折叠?



