Pygame学习 飞机大战

通过学习廖雪峰老师网课编写
主运行程序编写

import pygame
from plane_sprites import *
SCREEN_RECT = pygame.Rect(0, 0, 480, 720)
FRAME_PER_SEC = 60
CREATE_ENEMY_EVENT = pygame.USEREVENT
HERO_FIRE_EVENT = pygame.USEREVENT + 1


class planeGame(object):
    def __init__(self):
        print("游戏初始化")
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        self.clock = pygame.time.Clock()
        self.__create_sprites()
        pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
        pygame.time.set_timer(HERO_FIRE_EVENT, 500)

    def __create_sprites(self):
        bg1 = BackGround()
        bg2 = BackGround(True)
        self.back_group = pygame.sprite.Group(bg1, bg2)
        self.enemy_group = pygame.sprite.Group()
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)

    def start_game(self):
        print("游戏开始")
        while True:
            self.clock.tick(FRAME_PER_SEC)
            self.__event_handler()
            self.__check_collide()
            self.__update_sprites()
            pygame.display.update()

    def __event_handler(self):  # 事件监听
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                planeGame.__game_over()
            elif event.type == CREATE_ENEMY_EVENT:
                print("敌机出现...")
                enemy = Enemy()
                self.enemy_group.add(enemy)
            elif event.type == HERO_FIRE_EVENT:
                self.hero.fire()

        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_RIGHT]:
            self.hero.speed = 2
        elif keys_pressed[pygame.K_LEFT]:
            self.hero.speed = -2
        else:
            self.hero.speed = 0

    def __check_collide(self):  # 碰撞检测
        # 子弹组和敌机组碰撞,两者都销毁:
        pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
        # 敌机和英雄碰撞,两者都销毁,游戏结束:
        coll_list = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
        if len(coll_list) > 0:
            self.hero.kill()
            pygame.quit()
            planeGame.__game_over()

    def __update_sprites(self):  # 更新、绘制精灵组
        self.back_group.update()
        self.back_group.draw(self.screen)

        self.enemy_group.update()
        self.enemy_group.draw(self.screen)

        self.hero_group.update()
        self.hero_group.draw(self.screen)

        self.hero.bullets.update()
        self.hero.bullets.draw(self.screen)

    @staticmethod
    def __game_over():
        print("退出游戏")
        pygame.quit()
        exit()


if __name__ == '__main__':
    game = planeGame()
    game.start_game()

精灵类编写

import random
import pygame
SCREEN_RECT = pygame.Rect(0, 0, 480, 720)


class GameSprite(pygame.sprite.Sprite):

    def __init__(self, image_name, speed=1):
        super().__init__()  # 需要主动调用,否则无法使用父类的初始化方法
        self.image = pygame.image.load(image_name)
        self.rect = self.image.get_rect()  # 可以返回pygame.Rect(0,0,图像宽,图像高)的对象
        self.speed = speed

    def update(self):
        self.rect.y += self.speed  # 垂直方向移动


class BackGround(GameSprite):

    def __init__(self, is_alt=False):
        super().__init__(r".\images\background.png")
        if is_alt:
            self.rect.y = -self.rect.height  # 另一张放在正上方

    def update(self):
        super().update()
        if self.rect.y >= SCREEN_RECT.height:
            self.rect.y = -self.rect.height  # 交替滚动


class Enemy(GameSprite):

    def __init__(self):
        super().__init__(r".\images\enemy1.png")
        self.speed = random.randint(1, 3)  # 随机速度
        self.rect.bottom = 0
        max_x = SCREEN_RECT.width - self.rect.width
        self.rect.x = random.randint(0, max_x)  # 随机出现位置

    def update(self):
        super().update()
        if self.rect.y >= SCREEN_RECT.height:
            print("敌机飞出屏幕,从精灵组中删除")
            self.kill()

    def __del__(self):
        print("%s敌机挂了" % self.rect)  # 内置方法,死亡前自动调用


class Hero(GameSprite):

    def __init__(self):
        super().__init__(r".\images\me1.png", 0)
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 120  # 英雄在正中偏上120的位置
        self.bullets = pygame.sprite.Group()

    def update(self):  # 英雄飞机不垂直移动,所以不调用父类方法
        self.rect.x += self.speed
        #边界控制防止英雄飞机飞出屏幕
        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_RECT.right:
            self.rect.right = SCREEN_RECT.right  # right = x + width

    def fire(self):
        print("发射子弹...")
        for i in (0, 1, 2):  # 一次发射三枚子弹
            bullet = Bullet()
            bullet.rect.bottom = self.rect.y - i*20
            bullet.rect.centerx = self.rect.centerx  # 子弹在英雄飞机中心线,正上方20处
            self.bullets.add(bullet)


class Bullet(GameSprite):

    def __init__(self):
        super().__init__(r".\images\bullet1.png", -2)

    def update(self):
        super().update()
        if self.rect.bottom < 0:  # 子弹飞出屏幕后从精灵组删除
            self.kill()

    def __del__(self):  # 死亡前自动调用
        print("子弹飞出范围...")

你可能感兴趣的:(Pygame学习 飞机大战)