Pygame飞机大战(五)——定义敌机的类,并且创建敌机

同样的,先来分析下敌机都有哪些属性,其实三种机型都是类似的,了解一个之后,其他的其实都没有问题的:

  1. 主体的图片和坠毁的图片
  2. 坠毁的音效(大型敌机还有一个出场的音效)
  3. 敌机的状态,被消灭了就需要复活
  4. 敌机移动和边界的判断
  5. 发射子弹(这里篇幅可能会太长,所以讲敌机子弹的部分也省略了,添加的方法其实都是类似的)

下面我们就以大型敌机为例,因为大型敌机还有一个出场的音效,其他的是没有的,他是一个自带BGM的飞机:

class BigEnemy(pygame.sprite.Sprite):
    def __init__(self,screen_size):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("images/enemy3_n1.png").convert_alpha()    # 加载敌机的图片,是有两张的,可以像己方飞机一样有动画效果,这里先省略,可以自己添加
        self.destroy_images = []        # 创建坠毁动画的列表
        self.destroy_images.extend([    # 将敌机坠毁图片添加到列表中
            pygame.image.load("images/enemy3_down1.png").convert_alpha(),
            pygame.image.load("images/enemy3_down2.png").convert_alpha(),
            pygame.image.load("images/enemy3_down3.png").convert_alpha(),
            pygame.image.load("images/enemy3_down4.png").convert_alpha(),
            pygame.image.load("images/enemy3_down5.png").convert_alpha(),
            pygame.image.load("images/enemy3_down6.png").convert_alpha()])
        self.rect = self.image.get_rect()
        self.width, self.height  = screen_size[0], screen_size[1]
        self.speed = 1
        self.active = True  # 表示敌机的生存状态
        self.energy = 20    # 设置血量
        
        # 敌机的位置是随机出现的
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\    
                                        randint(-15*self.height, -5*self.height)
        self.mask = pygame.mask.from_surface(self.image)

        self.fly_sound = pygame.mixer.Sound("sound/enemy3_flying.wav")    # 加载出场音效
        self.fly_sound.set_volume(0.2)    # 设置音效的音量
        self.down_sound = pygame.mixer.Sound("sound/enemy3_down.wav")     # 加载坠毁的音效
        self.down_sound.set_volume(0.6)    # 设置坠毁音效的音量

    def move(self):
        if self.rect.top < self.height - 60:
            self.rect.top +=  self.speed
        else:
            self.reset()
        if self.rect.bottom == -50:    # 当飞机里窗体顶端还有50像素的时候播放出场音效
            self.fly_sound.play()

    def reset(self):
        self.active = True        # 重置敌机的状态
        self.energy = 20
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\
                                        randint(-15*self.height, -5*self.height)

    def play_sound(self):            # 播放音效
        self.fly_sound.stop()        # 坠毁了,需要先暂停出场音效
        self.down_sound.play()       # 播放坠毁音效

我们看下怎么实现效果:

import pygame
import sys
from pygame.locals import *
import myclass

pygame.init()
screen_size = width, height = 480, 700
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('飞机大战')
bg = pygame.image.load('./images/background.png').convert()

pygame.mixer.music.load('./sound/game_music.ogg')
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(-1)

# 生成大型敌机的方法
def add_big_enemies(group1, group2, num):
    for big_enemy_num in range(num):    # 这里的num是指飞机的数量
        each_big_enemy = myclass.BigEnemy(screen_size)    # 创建大型敌机
        group1.add(each_big_enemy)    # 将敌机添加到组中
        group2.add(each_big_enemy)

def main():
    clock = pygame.time.Clock()

    heroPlane = myclass.myPlane(screen, screen_size)

    enemies = pygame.sprite.Group()    # 创建全部敌机的组
    
    big_enemies = pygame.sprite.Group()          # 创建大型敌机的组
    add_big_enemies(big_enemies, enemies, 2)     # 生成敌机

    bullet1 = []
    bullet1_index = 0
    BULLET1_NUM = 5
    for i in range(BULLET1_NUM):
        bullet1.append(myclass.Bullet(heroPlane.rect.midtop,True))

    big_destroy_index = 0    # 用来存储动画播放的下标

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        key_pressed = pygame.key.get_pressed()
        if key_pressed[K_UP]:
            heroPlane.moveUp()
        if key_pressed[K_DOWN]:
            heroPlane.moveDown()
        if key_pressed[K_LEFT]:
            heroPlane.moveLeft()
        if key_pressed[K_RIGHT]:
            heroPlane.moveRight()

        screen.blit(bg,(0,0))
        heroPlane.animation()

        if not (heroPlane.delay % 10):
            bullet1[bullet1_index].reset(heroPlane.rect.midtop)
            bullet1_index = (bullet1_index + 1) % BULLET1_NUM

        for each in bullet1:
            each.move()
            screen.blit(each.image, each.rect)

        # 绘制大型飞机
        for each in big_enemies:
            if each.active == True:    # 如果飞机是活着的
                each.move()            # 改变飞机的位置
                screen.blit(each.image, each.rect)    # 在窗体上绘制飞机
            else:    # 飞机被击毁了
                if not (heroPlane.delay % 3):    # 切换图片稍微延时一会儿
                    screen.blit(each.destroy_images[big_destroy_index], each.rect)  # 绘制坠毁图片
                    big_destroy_index = (big_destroy_index + 1) % 6  # 这里是因为坠毁图片一共有六张
                    if big_destroy_index == 0:    # 如果是最后一张
                        each.play_sound()         # 播放音效
                        each.reset()              # 重生飞机

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

if __name__ == '__main__':
    main()

我们再来整理一下,创建敌机的步骤:

  1. 先创建一个大的敌方飞机组,所有的敌方飞机最终都要添加到这个组里面
  2. 然后每种敌机都有一个小的组,然后根据我们定义的数量,生成敌机,并添加到两个组里面
  3. 绘制飞机,首先判断飞机的状态,如果是正常飞行的状态,直接绘制就好了,如果被击毁了,每隔三个指令周期切换一张图片,形成坠毁的动画效果
  4. 最后播放坠毁音效,然后重生

我们最后来看一下全部的敌方飞机类和整体实现代码:

类和实现代码是分开的:

  • 实现代码:main.py
  • 定义的类:myclass.py
import pygame
from random import *

# 小型敌机
class SmallEnemy(pygame.sprite.Sprite):
    def __init__(self, screen_size):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("images/enemy1.png").convert_alpha()
        self.destroy_images = []
        self.destroy_images.extend([
            pygame.image.load("./images/enemy1_down1.png").convert_alpha(),
            pygame.image.load("./images/enemy1_down2.png").convert_alpha(),
            pygame.image.load("./images/enemy1_down3.png").convert_alpha(),
            pygame.image.load("./images/enemy1_down4.png").convert_alpha()])
        self.rect = self.image.get_rect()
        self.width, self.height = screen_size[0], screen_size[1]
        self.speed = 2
        self.active = True
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\
                                        randint(-5*self.height,0)
        self.mask = pygame.mask.from_surface(self.image)

        self.down_sound = pygame.mixer.Sound("sound/enemy1_down.wav")
        self.down_sound.set_volume(0.3)

    def move(self):
        if self.rect.top < self.height - 60:
            self.rect.top +=  self.speed
        else:
            self.reset()

    def reset(self):
        self.active = True
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\
                                        randint(-5*self.height,0)
    def play_sound(self):
        self.down_sound.play()

# 中型敌机
class MidEnemy(pygame.sprite.Sprite):
    ENERGY = 10
    def __init__(self,screen_size):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("images/enemy2.png").convert_alpha()
        self.destroy_images = []
        self.destroy_images.extend([
            pygame.image.load("./images/enemy2_down1.png").convert_alpha(),
            pygame.image.load("./images/enemy2_down2.png").convert_alpha(),
            pygame.image.load("./images/enemy2_down3.png").convert_alpha(),
            pygame.image.load("./images/enemy2_down4.png").convert_alpha()])
        self.rect = self.image.get_rect()
        self.width, self.height = screen_size[0], screen_size[1]
        self.speed = 1
        self.active = True
        self.energy = MidEnemy.ENERGY
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\
                                        randint(-10*self.height, -self.height)
        self.mask = pygame.mask.from_surface(self.image)

        self.down_sound = pygame.mixer.Sound("sound/enemy2_down.wav")
        self.down_sound.set_volume(0.3)

    def move(self):
        if self.rect.top < self.height - 60:
            self.rect.top +=  self.speed
        else:
            self.reset()

    def reset(self):
        self.active = True
        self.energy = MidEnemy.ENERGY
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\
                                        randint(-10*self.height,0)

    def play_sound(self):
        self.down_sound.play()

# 大型敌机
class BigEnemy(pygame.sprite.Sprite):
    ENERGY = 20
    def __init__(self,screen_size):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("images/enemy3_n1.png").convert_alpha()

        self.destroy_images = []
        self.destroy_images.extend([
            pygame.image.load("./images/enemy3_down1.png").convert_alpha(),
            pygame.image.load("./images/enemy3_down2.png").convert_alpha(),
            pygame.image.load("./images/enemy3_down3.png").convert_alpha(),
            pygame.image.load("./images/enemy3_down4.png").convert_alpha(),
            pygame.image.load("./images/enemy3_down5.png").convert_alpha(),
            pygame.image.load("./images/enemy3_down6.png").convert_alpha()])
        self.rect = self.image.get_rect()
        self.width, self.height  = screen_size[0], screen_size[1]
        self.speed = 1
        self.active = True
        self.energy = BigEnemy.ENERGY
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\
                                        randint(-15*self.height, -5*self.height)
        self.mask = pygame.mask.from_surface(self.image)

        self.fly_sound = pygame.mixer.Sound("sound/enemy3_flying.wav")
        self.fly_sound.set_volume(0.2)
        self.down_sound = pygame.mixer.Sound("sound/enemy3_down.wav")
        self.down_sound.set_volume(0.6)

    def move(self):
        if self.rect.top < self.height - 60:
            self.rect.top +=  self.speed
        else:
            self.reset()
        if self.rect.bottom == -50:
            self.fly_sound.play()

    def reset(self):
        self.active = True
        self.energy = BigEnemy.ENERGY
        self.rect.left, self.rect.top = randint(0, self.width - self.rect.width),\
                                        randint(-15*self.height, -5*self.height)

    def play_sound(self):
        self.fly_sound.stop()
        self.down_sound.play()
import pygame
import sys
from pygame.locals import *
import myclass

pygame.init()
screen_size = width, height = 480, 700
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('飞机大战')
bg = pygame.image.load('./images/background.png').convert()

pygame.mixer.music.load('./sound/game_music.ogg')
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(-1)

# 生成大型敌机的方法
def add_big_enemies(group1, group2, num):
    for big_enemy_num in range(num):    # 这里的num是指飞机的数量
        each_big_enemy = myclass.BigEnemy(screen_size)    # 创建大型敌机
        group1.add(each_big_enemy)    # 将敌机添加到组中
        group2.add(each_big_enemy)

# 生成中型飞机
def add_mid_enemies(group1, group2, num):
    for mid_enemy_num in range(num):
        each_mid_enemy = myclass.MidEnemy(screen_size)
        group1.add(each_mid_enemy)
        group2.add(each_mid_enemy)

# 生成大型飞机
def add_small_enemies(group1, group2, num):
    for small_enemy_num in range(num):
        each_small_enemy = myclass.SmallEnemy(screen_size)
        group1.add(each_small_enemy)
        group2.add(each_small_enemy)

def main():
    clock = pygame.time.Clock()

    heroPlane = myclass.myPlane(screen, screen_size)

    enemies = pygame.sprite.Group()    # 创建全部敌机的组
    
    big_enemies = pygame.sprite.Group()          # 创建大型敌机的组
    add_big_enemies(big_enemies, enemies, 2)     # 生成敌机

    mid_enemies = pygame.sprite.Group()
    add_mid_enemies(mid_enemies, enemies, 4)

    small_enemies = pygame.sprite.Group()
    add_small_enemies(small_enemies, enemies, 15)

    bullet1 = []
    bullet1_index = 0
    BULLET1_NUM = 5
    for i in range(BULLET1_NUM):
        bullet1.append(myclass.Bullet(heroPlane.rect.midtop,True))

    small_destroy_index = 0
    mid_destroy_index = 0
    big_destroy_index = 0

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        key_pressed = pygame.key.get_pressed()
        if key_pressed[K_UP]:
            heroPlane.moveUp()
        if key_pressed[K_DOWN]:
            heroPlane.moveDown()
        if key_pressed[K_LEFT]:
            heroPlane.moveLeft()
        if key_pressed[K_RIGHT]:
            heroPlane.moveRight()

        screen.blit(bg,(0,0))
        heroPlane.animation()

        if not (heroPlane.delay % 10):
            bullet1[bullet1_index].reset(heroPlane.rect.midtop)
            bullet1_index = (bullet1_index + 1) % BULLET1_NUM

        for each in bullet1:
            each.move()
            screen.blit(each.image, each.rect)

        # 绘制大型飞机
        for each in big_enemies:
            if each.active == True:    # 如果飞机是活着的
                each.move()            # 改变飞机的位置
                screen.blit(each.image, each.rect)    # 在窗体上绘制飞机
            else:    # 飞机被击毁了
                if not (heroPlane.delay % 3):    # 切换图片稍微延时一会儿
                    screen.blit(each.destroy_images[big_destroy_index], each.rect)  # 绘制坠毁图片
                    big_destroy_index = (big_destroy_index + 1) % 6  # 这里是因为坠毁图片一共有六张
                    if big_destroy_index == 0:    # 如果是最后一张
                        each.play_sound()         # 播放音效
                        each.reset()              # 重生飞机

        for each in mid_enemies:
            if each.active == True:
                each.move()
                screen.blit(each.image, each.rect)
            else:
                if not (heroPlane.delay % 3):
                    screen.blit(each.destroy_images[mid_destroy_index], each.rect)
                    mid_destroy_index = (mid_destroy_index + 1) % 4
                    if mid_destroy_index == 0:
                        each.play_sound()
                        each.reset()

        for each in small_enemies:
            if each.active == True:
                each.move()
                screen.blit(each.image, each.rect)
            else:
                if not (heroPlane.delay % 3):
                    screen.blit(each.destroy_images[small_destroy_index], each.rect)
                    small_destroy_index = (small_destroy_index + 1) % 4
                    if small_destroy_index == 0:
                        each.play_sound()
                        each.reset()

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

if __name__ == '__main__':
    main()

你可能感兴趣的:(Python,#,pygame游戏开发,python,pygame)