飞机大战python实现(面向对象)

飞机大战:
以下代码是根据网上教程学习并且实践的代码,仅供学习和交流
一、创建plane_sprites.py

import random
import pygame
# 设置定时器
CREATE_ENEMY_EVENT = pygame.USEREVENT
HERO_FIRE_EVENT = pygame.USEREVENT + 1
# 根据背景图设置背景矩形
SCREEN_RECT = pygame.Rect(0, 0, 512, 768)
# 敌机,子弹,和英雄路径
Path_Enemy = "./images/enemy/enemy.png"
Path_Bullet = "./images/bullet/10.png"
Path_Hero = "./images/hero/hero.png"

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()
        self.speed = speed

    def update(self, *args):
        self.rect.y += self.speed

class Background(GameSprite):
    """游戏背景精灵"""
    def __init__(self, is_alt=False):
        super().__init__("./images/bg/bg.jpg")
        if is_alt == True:
            self.rect.y = -self.rect.height

    def update(self, *args):
        super().update()
        if self.rect.y == self.rect.height:
            self.rect.y = -self.rect.height

class Enemy(GameSprite):
    """敌人的飞机精灵类"""
    def __init__(self):
        # 1.调用父类的方法
        super().__init__(Path_Enemy)
        self.speed = random.randint(1, 8)
        self.Max_0 = SCREEN_RECT.width - self.rect.width
        self.rect.x = random.randint(0, self.Max_0)
        self.rect.y = -self.rect.height
        self.rect.bottom = 0

    def update(self, *args):
        super().update()
        if self.rect.y >= SCREEN_RECT.height:
            # 及时清理出内存
            self.kill()

class Hero(GameSprite):
    """英雄精灵"""
    def __init__(self):
        # 1. 调用父类的方法
        super().__init__(Path_Hero, speed=2)

        # 2. 设置英雄的初始位置
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 100
        self.Bullets_group = pygame.sprite.Group()

    def update(self, *args):
        self.rect.x += self.speed
        if self.rect.x < 0:
            self.rect.x = 0
        if self.rect.x > SCREEN_RECT.width -self.rect.width:
            self.rect.x = SCREEN_RECT.width - self.rect.width

    def fire(self):
        """发射子弹"""
        bullet1 = Bullet()
        bullet2 = Bullet()
        bullet1.rect.x = self.rect.centerx
        bullet1.rect.y = self.rect.y - 40
        bullet2.rect.x = self.rect.centerx - 16
        bullet2.rect.y = self.rect.y - 40
        # 这里选择发射两枚平行子弹
        self.Bullets_group.add(bullet1, bullet2)

class Bullet(GameSprite):
    """设置子弹类"""
    def __init__(self):
        super().__init__(Path_Bullet, speed=-4)
        self.rect.y += self.speed

    def update(self, *args):
        super().update()
        if self.rect.bottom < 0:
            print(self.rect)
            self.kill()

二、创建Plane_main.py

Path_bg = "./images/bg/bg.jpg"

bg = pygame.image.load(Path_bg)
SCREEN_RECT = pygame.Rect(0, 0, 512, 768)

class GameMain():
    def __init__(self):
        pygame.init()
        # 设置游戏的窗口
        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)
        # 设置敌机精灵组:
        self.enemy_group = pygame.sprite.Group()
        print("游戏初始化")

    def __create_sprites(self):
        # 创建背景精灵组
        bg1 = Background()
        bg2 = Background(True)
        self.bg_group = pygame.sprite.Group(bg1, bg2)
        # 创建英雄的精灵组
        self.he = Hero()
        self.he_group = pygame.sprite.Group(self.he)

    def start_game(self):
        print("游戏开始!")
        while True:
            # 1. 设置刷新帧率
            self.clock.tick(60)
            # 2. 事件监听
            self.__event_handler()
            # 3. 碰撞检测
            self.__check_collide()
            # 4. 更新/绘制精灵组
            self.__update_sprites()
            # 5. 更新显示
            pygame.display.update()

    def __event_handler(self):
        """事件监听"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.__game_over()
            elif event.type == CREATE_ENEMY_EVENT:
                self.enemy_group.add(Enemy())
            elif event.type == HERO_FIRE_EVENT:
                self.he.fire()
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_RIGHT]:
            self.he.speed = 2
        elif keys_pressed[pygame.K_LEFT]:
            self.he.speed = -2
        else:
            self.he.speed = 0

    def __check_collide(self):
        """碰撞检测"""
        pygame.sprite.groupcollide(self.enemy_group, self.he.Bullets_group, True, True)
        if pygame.sprite.groupcollide(self.enemy_group, self.he_group, True, True):
            self.__game_over()

    def __update_sprites(self):
        # 更新背景
        self.bg_group.update()
        self.bg_group.draw(self.screen)
        # 更新敌机
        self.enemy_group.update()
        self.enemy_group.draw(self.screen)
        # 更新英雄
        self.he_group.update()
        self.he_group.draw(self.screen)
        # 更新子弹
        self.he.Bullets_group.update()
        self.he.Bullets_group.draw(self.screen)

    @staticmethod
    def __game_over():
        print("游戏结束!")
        pygame.quit()
        exit()

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

三、说明:
代码只需用到4张照片,分别是enemy(敌机),hero(本机),bg(背景)以及bullet(子弹),图片资源来自网上,只需要到网上去搜索保存,在代码中修改Path即可(其中背景需要改变矩形边框的width和height)
效果图如下:
飞机大战python实现(面向对象)_第1张图片

你可能感兴趣的:(飞机大战python实现(面向对象))