Aircraft war game framework 6--

Game framework to build

Target - the use of object-oriented design aircraft war game class

aims

  • Clear main responsibility
  • Realization of the main program
  • Ready game Elf group

01. clear main responsibility

  • Recalling the Quick Start case , a game master's duties can be divided into two parts:
    • Game initialization
    • Game Loop
  • Based on clear responsibilities, design PlaneGameclasses are as follows:

Here Insert Picture Description

Tip According duty package private method, the code is written a certain method to avoid too long

If one method is too long to write, read neither good nor good maintenance!

  • Game initialization - __init__()can call the following method:
method Responsibility
__create_sprites(self) Create all the elves and sprites group
  • Game loop - start_game()will call the following method:
method Responsibility
__event_handler(self) Event Listeners
__check_collide(self) Collision detection - bullet destroy the enemy, the enemy hero crashed
__update_sprites(self) Elf Group Update and Draw
__game_over() game over

02. World War II aircraft to achieve the main game class

2.1 Definition File duties

  • plane_main
    1. Packaging primary game class
    2. Creating game objects
    3. Start the game
  • plane_sprites
    • Package game all the need to use the wizard subclass
    • Games of tools

Code

  • New plane_main.pyfile, and set as executable
  • Write code base
import pygame
from plane_sprites import *


class PlaneGame(object):
    """飞机大战主游戏"""

    def __init__(self):
        print("游戏初始化")

    def start_game(self):
        print("开始游戏...")


if __name__ == '__main__':
    # 创建游戏对象
    game = PlaneGame()

    # 开始游戏
    game.start_game()

2.3 game initialization part

  • Complete __init__()code is as follows:
def __init__(self):
    print("游戏初始化")
    
    # 1. 创建游戏的窗口
    self.screen = pygame.display.set_mode((480, 700))
    # 2. 创建游戏的时钟
    self.clock = pygame.time.Clock()
    # 3. 调用私有方法,精灵和精灵组的创建
    self.__create_sprites()

def __create_sprites(self):
    pass

Instead of using a constant fixed value

  • Constant - the amount does not change
  • Variable - the amount may vary

Scenarios

  • 在开发时,可能会需要使用 固定的数值,例如 屏幕的高度700
  • 这个时候,建议 不要 直接使用固定数值,而应该使用 常量
  • 在开发时,为了保证代码的可维护性,尽量不要使用 魔法数字

常量的定义

  • 定义 常量 和 定义 变量 的语法完全一样,都是使用 赋值语句
  • 常量命名 应该 所有字母都使用大写单词与单词之间使用下划线连接

常量的好处

  • 阅读代码时,通过 常量名 见名之意,不需要猜测数字的含义
  • 如果需要 调整值,只需要 修改常量定义 就可以实现 统一修改

提示:Python 中并没有真正意义的常量,只是通过命名的约定 —— 所有字母都是大写的就是常量,开发时不要轻易的修改!

代码调整

  • plane_sprites.py 中增加常量定义
import pygame

# 游戏屏幕大小
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
  • 修改 plane_main.py 中的窗口大小
self.screen = pygame.display.set_mode(SCREEN_RECT.size)

2.4 游戏循环部分

  • 完成 start_game() 基础代码如下:
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:
            PlaneGame.__game_over()

def __check_collide(self):
    """碰撞检测"""
    pass

def __update_sprites(self):
    """更新精灵组"""
    pass
    
@staticmethod
def __game_over():
   """游戏结束"""

   print("游戏结束")
   pygame.quit()
   exit()

03. 准备游戏精灵组

3.1 确定精灵组

Here Insert Picture Description

3.2 代码实现

  • 创建精灵组方法
def __create_sprites(self):
    """创建精灵组"""
    
    # 背景组
    self.back_group = pygame.sprite.Group()
    # 敌机组
    self.enemy_group = pygame.sprite.Group()
    # 英雄组
    self.hero_group = pygame.sprite.Group()

  • 更新精灵组方法
def __update_sprites(self):
    """更新精灵组"""
    
    for group in [self.back_group, self.enemy_group, self.hero_group]:
    
        group.update()
        group.draw(self.screen)
Published 22 original articles · won praise 8 · views 269

Guess you like

Origin blog.csdn.net/MO__YE/article/details/104503744