• 【python小游戏】飞机大作战源码分享(附完整源码+图片资源可直接运行)


    • 效果演示
      01
    • 源码
    1. plane_main1.py
    import pygame
    from plane_sprites import *
    import time
    
    class PlaneGame(object):
        """飞机大战主游戏"""
    
        def __init__(self):
            print("游戏初始化")
    
            # 1. 创建游戏的窗口
            self.screen = pygame.display.set_mode(SCREEN_RECT.size)
            # 2. 创建游戏的时钟
            self.clock = pygame.time.Clock()
            # 3. 调用私有方法,精灵和精灵组的创建,也是初始化
            self.__create_sprites()
    
            # 4. 设置定时器事件 - 创建敌机 设定敌机的刷新时间为1s,
            # 英雄子弹事件的刷新频率为0.5秒
            pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)
            pygame.time.set_timer(HERO_FIRE_EVENT, 300)
    
        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:
                # 1. 设置刷新帧率
                self.clock.tick(FRAME_PER_SEC)
                # 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:
                    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()
                # elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
                #     print("向右移动...")
    
            # 使用键盘提供的方法获取键盘按键 - 按键元组
            keys_pressed = pygame.key.get_pressed()
            # 判断元组中对应的按键索引值 1
            if keys_pressed[pygame.K_RIGHT]:
                self.hero.speed = 8
            elif keys_pressed[pygame.K_LEFT]:
                self.hero.speed = -8
            else:
                self.hero.speed = 0
    
        def __check_collide(self):
    
            # 1. 子弹摧毁敌机
            pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
    
            # 2. 敌机撞毁英雄
            enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
    
            # 判断列表时候有内容
            if len(enemies) > 0:
                # 让英雄牺牲
                self.hero.kill()
                m = "./sound/use_bomb.wav"
                pygame.mixer.music.load(m)
                pygame.mixer.music.play()
                time.sleep(2)
                # 结束游戏
                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__':
        # 创建游戏对象
        pygame.init()
        game = PlaneGame()
    
        # 启动游戏
        game.start_game()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    1. plane_sprites.py
    import random
    import pygame
    
    # 屏幕大小的常量对象
    SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
    # 刷新的帧率
    FRAME_PER_SEC = 15
    # 创建敌机的定时器常量,为事件定义不同名字的常量,从而能够区分,从24算起
    CREATE_ENEMY_EVENT = pygame.USEREVENT
    # 英雄发射子弹事件,为事件定义不同名字的常量,从而能够区分
    HERO_FIRE_EVENT = pygame.USEREVENT + 1
    
    
    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):
            # 在屏幕的垂直方向上移动
            self.rect.y += self.speed
    
    
    class Background(GameSprite):
        """游戏背景精灵"""
    
        def __init__(self, is_alt=False):
    
            # 1. 调用父类方法实现精灵的创建(image/rect/speed)
            super().__init__("./images/background.png")
    
            # 2. 判断是否是交替图像,如果是,需要设置初始位置
            if is_alt:
                self.rect.y = -self.rect.height
    
        def update(self):
    
            # 1. 调用父类的方法实现
            super().update()
    
            # 2. 判断是否移出屏幕,如果移出屏幕,将图像设置到屏幕的上方
            if self.rect.y >= SCREEN_RECT.height:
                self.rect.y = -self.rect.height
    
    
    class Enemy(GameSprite):
        """敌机精灵"""
    
        def __init__(self):
            # 1. 调用父类方法,创建敌机精灵,同时指定敌机图片
            super().__init__("./images/enemy1.png")
    
            # 2. 指定敌机的初始随机速度 1 ~ 3
            self.speed = random.randint(1, 3)
    
            # 3. 指定敌机的初始随机位置
            self.rect.bottom = 0
    
            max_x = SCREEN_RECT.width - self.rect.width  #减去自身宽度
            self.rect.x = random.randint(0, max_x)
    
        def update(self):
            # 1. 调用父类方法,保持垂直方向的飞行
            super().update()
    
            # 2. 判断是否飞出屏幕,如果是,需要从精灵组删除敌机
            if self.rect.y >= SCREEN_RECT.height:
                # print("飞出屏幕,需要从精灵组删除...")
                # kill方法可以将精灵从所有精灵组中移出,精灵就会被自动销毁
                self.kill()
    
        def __del__(self):
            # print("敌机挂了 %s" % self.rect)
            pass
    
    
    class Hero(GameSprite):
        """英雄精灵"""
    
        def __init__(self):
    
            # 1. 调用父类方法,设置image&speed
            super().__init__("./images/me1.png", 0)
    
            # 2. 设置英雄的初始位置
            self.rect.centerx = SCREEN_RECT.centerx
            self.rect.bottom = SCREEN_RECT.bottom - 120
    
            # 3. 创建子弹的精灵组
            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
    
        def fire(self):
            print("发射子弹...")
    
            for i in (0, 1, 2):
                # 1. 创建子弹精灵
                bullet = Bullet()
    
                # 2. 设置精灵的位置
                bullet.rect.bottom = self.rect.y - i * 20
                bullet.rect.centerx = self.rect.centerx
    
                # 3. 将精灵添加到精灵组
                self.bullets.add(bullet)
    
    
    class Bullet(GameSprite):
        """子弹精灵"""
    
        def __init__(self):
            # 调用父类方法,设置子弹图片,设置初始速度
            super().__init__("./images/bullet1.png", -5)
    
        def update(self):
            # 调用父类方法,让子弹沿垂直方向飞行
            super().update()
    
            # 判断子弹是否飞出屏幕
            if self.rect.bottom < 0:
                self.kill()
    
        def __del__(self):
            print("子弹被销毁...")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    1. test
    import pygame
    import time
    
    pygame.init()
    pygame.mixer.init()
    
    pingmu = pygame.display.set_mode([500, 365])
    m = "./sound/use_bomb.wav"
    pygame.mixer.music.load(m)
    pygame.mixer.music.play()
    time.sleep(5)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    SQL sever中的触发器
    机器学习入门到大神专栏总览
    C++20之Module(浅析)
    数据结构-----红黑树简介
    经典bloom算法(**布隆过滤器**)-levelDB拆分
    详解HTML5新增的多媒体标签
    c++ 继承
    C++11常用新特性——右值引用&&
    GDB/MI断点信息
    基于javaweb的房屋租赁后台管理系统
  • 原文地址:https://blog.csdn.net/weixin_62892290/article/details/134314539