Python实现飞机大战项目

时间:2022-09-04 11:11:57

本文实例为大家分享了Python实现飞机大战的具体代码,供大家参考,具体内容如下

plane_main.py

?
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
import pygame
from 飞机大战.plane_sprites import *
 
 
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.设置定时器时间 -创建敌机
        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:
            # 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()
        # 判断元组中对应的按键索引值
        if keys_pressed[pygame.K_RIGHT]:
            self.hero.speed = 10
        elif keys_pressed[pygame.K_LEFT]:
            self.hero.speed = -10
        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()
            # 结束游戏
            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()

plane_sprites.py

?
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
import random
import pygame
 
# 屏幕大小的常量
SCREEN_RECT = pygame.Rect(0, 0, 512, 768)
# 刷新的帧率
FRAME_PER_SEC = 60
# 创建敌机的定时器常量
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.调用父类方法实现精灵的创建
        super().__init__("./images/img_bg_level_5.jpg")
        # 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/img-plane_2.png")
        # 2.指定敌机的初始随机速度
        self.speed = random.randint(2, 5)
        # 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/hero2.png", 0)
        # 2.设置英雄的初始位置
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 20
        # 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):
        for i in (0, 1, 2):
            # 1.创建子弹精灵
            bullet = Bullet()
            # 2.设置精灵位置
            bullet.rect.bottom = self.rect.y - i*40
            bullet.rect.centerx = self.rect.centerx
 
            # 3.将子弹添加到精灵组
            self.bullets.add(bullet)
 
 
class Bullet(GameSprite):
    """子弹精灵"""
 
    def __init__(self):
 
        # 调用父类方法,设置子弹图片,设置初始速度
        super().__init__("./images/bullet_11.png", -5)
 
    def update(self):
        #  调用父类方法,让子弹垂直飞出屏幕
        super().update()
 
        #  判断子弹是否飞出屏幕
        if self.rect.bottom < 0:
            self.kill()
 
    def __del__(self):
        print("子弹被销毁")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_43693233/article/details/85252928