Python学习笔记之实战小项目--飞机大战游戏(三)

       前面两篇推文,飞机大战游戏(一)和(二),实际上是属于热身,从中理解了图像的绘制,游戏的循环以及时钟,简单的图像动画实现,和比较重要的精灵和精灵组,下面会比较系统地来搭建飞机大战游戏。

        

目标

1、游戏框架的搭建

2、实现游戏背景的滚动式效果

3、实现敌机随机出现效果

一、游戏框架的搭建

首先  我们要明确游戏主程序的主要职责:游戏初始化、游戏循环

(1)游戏初始化:

        a.设置游戏屏幕

        b.创建一个游戏时钟

        c.创建精灵和精灵组

(2)游戏循环:

        a.设置刷新帧率

        b.进行事件监听

        c.碰撞检测

        d.更新和绘制精灵组

而上面两个主要主要职责是在一个创建的PlaneGame类中实现的

PlaneGame

游戏初始化

__init__():

游戏屏幕

游戏时钟

创建精灵(组)

游戏循环

start_game(self):

__event_handler(self)

__check_collide(self)

__update_sprites(self)

__game_over()

其次  

    我们需要创建plane_main.py和plane_sprites.py文件

plane_main.py文件主要作用:

    封装PlaneGame类,以及创建游戏对象,启动游戏;

plane_sprites.py文件主要作用:

    封装游戏中所有需要使用的精灵子类,以及一些游戏主文件中需要的其他东西,在上一篇推文中我们已经在其中定义了一个GameSprite类,可以直接拿过来用

 # 创建游戏类
class PlaneGame(object):

    def __init__(self):

        print("游戏初始化...")

        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        self.clock = pygame.time.Clock()
        self.__create_sprites()
 def start_game(self):
        print("游戏开始...")

        while True:

            self.clock.tick(SCREEN_UPDATE_FQ)
            self.__event_handler()
            self.__check_collide()
            self.__update_sprites()

            pygame.display.update()

另:start_game(self)中游戏循环中所调用的方法,都是在PlaneGame类中定义的私有方法,由于篇幅较长,这里就不在贴了,完整的见文末微信公众号:noobcoders  关注获取。

二、实现游戏背景交替滚动

原理:游戏启动后,让背景图像连续向下滚动,形成英雄飞机不断向上飞行的错觉

实现方法:

 1、创建两张背景图像精灵

              第1张完全与屏幕重合

              第2张在屏幕正上方

 2、两张图像一起向下运动

 3、当任意背景图像的rect.y>=屏幕

       高度,说明该图像已移动到屏幕下方

 4、将移动到屏幕下方的这张图像设置到

       屏幕上方rect.y = -rect.height

代码操作:

1、先在plane_sprites.py文件中创建一个BackGround类

# 创建背景精灵类
class BackGround(GameSprite):

    def __init__(self, is_alt=False):

        super(BackGround, self).__init__("./image/background.png")
        if is_alt:
            self.rect.y = -self.rect.height

    def update(self):
        super(BackGround, self).update()
        if self.rect.y >= SCREEN_RECT.height:
            self.rect.y = -self.rect.height

2、在PlaneGame类中的__create_sprites(self)方法中创建背景精灵

 def __create_sprites(self):
        """创建背景精灵"""
        background1 = BackGround()
        background2 = BackGround(True)

        # 创建背景精灵组
        self.background_group = pygame.sprite.Group(background1, background2)

3、在PlaneGame类中的__update_sprites(self)方法中更新和绘制背景精灵

 def __update_sprites(self):
        self.background_group.update()
        self.background_group.draw(self.screen)

三、实现敌机随机出场效果

原理:

1、游戏启动后,每隔1秒出现一架敌机

2、每架敌机向屏幕下方飞行,且飞行速度随机

3、每架敌机出现的水平位置也是随机的

实现思路:

1、使用pygame中的定时器

2、使用random库

3、创建敌机Enemy类

(一)通过pygame.time中的方法

     set_timer(eventid,millisecond)创建定时器

     eventid:需要基于pygame.USEREVENT指定

     millisecond:定时器间隔时间,单位毫秒

在PlaneGame中的__init__方法中创建定时器

在planes_sprites中定义:

        ENEMY_ENVENT=pygame.USEREVENT

  # 创建敌机定时器
  pygame.time.set_timer(ENEMY_EVENT, 1000)

(二)在plane_sprites中先import random,再创建敌机Enemy类

  # 创建敌机精灵类
class Enemy(GameSprite):

    def __init__(self):
        super(Enemy, self).__init__("./image/enemy1.png")

        # 设置敌机随机速度
        self.speed = random.randint(1, 5)

        # 指定敌机初始位置
        self.rect.bottom = 0

        # 敌机随机出现的范围
        move_range = SCREEN_RECT.width - self.rect.width
        self.rect.x = random.randint(0, move_range)

(三)在PlaneGame类中的__event_handler方法中,监听定时器事件,当定时器事件出现时,则使用Enemy类创建敌机对象

      def __event_handler(self):
        """事件监听"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                PlaneGame.__game_over()
            elif event.type == ENEMY_EVENT:
                print("敌机出场...")

                # 创建敌机
                enemy = Enemy()
                self.enemy_group.add(enemy)

(四)在PlaneGame类中的__update_sprites方法中,更新和绘制敌机精灵

    def __update_sprites(self):
        self.background_group.update()
        self.background_group.draw(self.screen)

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

更多飞机大战游戏的源码以及python相关的实战小项目的学习笔记,可关注微信公众号:noobcoders 获取

                                                            

猜你喜欢

转载自blog.csdn.net/weixin_42546061/article/details/81111081