简化版的植物大战僵尸游戏的Python实现

部署运行你感兴趣的模型镜像

植物大战僵尸简化版
下面是一个简化版的植物大战僵尸游戏的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文件夹来存储资源图像。
如果图像加载失败,游戏会使用默认的颜色矩形代替。

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码力金矿

谢谢您的打赏,我将会更好创作。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值