Python 小作品-植物大战僵尸

这篇博客介绍了使用Python编程语言实现的一个简单的植物大战僵尸小游戏。通过面向对象的设计,作者创建了包括地图、豌豆射手、僵尸在内的基本元素,并实现了功能封装,使得代码易于理解和维护。
import pygame
import time
import random
import sys
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 560

# 地图类 v1.2 完善地图类
class Map:
    images_list = ['imgs/map1.png','imgs/map2.png']
    def __init__(self, x, y, image_index):
        self.position = (x,y)
        self.image = pygame.image.load(Map.images_list[image_index])
        # v1.5 新增是否能种植的属性
        self.can_grow = True
    # 将当前地图的图片加入到窗口
    def display_map(self):
        MainGame.window.blit(self.image,self.position)

# 植物类 (父类)
class Plant(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.live = True

# 向日葵类 v1.4 完善向日葵类
class Sunflower(Plant):
    def __init__(self,x,y):
        super(Sunflower, self).__init__()
        self.image = pygame.image.load('imgs/sunflower.png')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.price = 50
        self.hp = 100
        # v1.6 时间计数器
        self.time_count = 0

    # v1.6 新增功能:生成阳光
    def produce_money(self):
        self.time_count += 1
        if self.time_count == 25:
            MainGame.money += 5
            self.time_count = 0
    # 向日葵加入到窗口中
    def display_sunflower(self):
        MainGame.window.blit(self.image,self.rect)


# 豌豆射手类
# v1.5 完善 豌豆射手类
class PeaShooter(Plant):
    def __init__(self,x,y):
        super(PeaShooter, self).__init__()
        # self.image 为一个 surface
        self.image = pygame.image.load('imgs/peashooter.png')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.price = 50
        self.hp = 200
        # v1.7 发射计数器
        self.shot_count = 0

    # v1.7 增加射击方法
    def shot(self):
        # v1.9 记录是否应该射击
        should_fire = False
        for zombie in MainGame.zombie_list:
            if zombie.rect.y == self.rect.y and zombie.rect.x < 800 and zombie.rect.x > self.rect.x:
                should_fire = True
        # 如果活着
        if self.live and should_fire:
            self.shot_count += 1
            # 计数器到25发射一次
            if self.shot_count == 25:
                # 基于当前豌豆射手的位置,创建子弹
                peabullet = PeaBullet(self)
                # 将子弹存储到子弹列表中
                MainGame.peabullet_list.append(peabullet)
                self.shot_count = 0

    # 将豌豆射手加入到窗口中的方法
    def display_peashooter(self):
        MainGame.window.blit(self.image,self.rect)

# 豌豆子弹类
# v1.6 新增子弹类的功能
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值