Python--Project combat--game frame construction

Source: Internet
Author: User
Tags constant definition event listener

Goal--using object-oriented design aircraft war game class

Goal
    • Clear Main program Responsibilities
    • Implementing the Main program class
    • Prepare the game Sprite Group
01, clear the main program responsibility
    • Review the QuickStart case , the responsibility of a game main program can be divided into two parts
      • Game initialization
      • Game Loop
    • According to clear responsibilities, the design PlaneGame class is as follows:

tips to encapsulate a private method according to responsibilities , you can avoid the code of one method being too verbose; If a method is written too long, it is not good to read or to maintain.

    • Game Initialization -the __init__() method is called:
Method Responsibilities
__event_handler(self) Event Monitoring
__check_collide(self) Collision detection--bullets destroy enemy planes, enemy planes crash heroes
__update_sprites(self) Sprite Group Update and draw
__game_over() Game Over
02, to achieve aircraft vs. main Game Class 2.1 clear document Responsibilities

    • plane_main
      • 1, encapsulating the main game class
      • 2. Create a Game object
      • 3, start the game
    • plane_sprites
      • Encapsulates all the sprite subclasses that need to be used in the game
      • tools to provide games
Code implementation
    • Create plane_main.py a new file and set it to executable
    • Writing the underlying code
import pygamefrom Aircraft_War.plane_sprites import *class PlaneGame(object):    """飞机大战主游戏"""    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    def start_game(self):        print("游戏开始...")if __name__ == ‘__main__‘:    # 创建游戏对象    game = PlaneGame()    # 启动游戏    game.start_game()
Use constants instead of fixed values
    • Constant--the quantity that does not change
    • Variable--The amount that can be changed

Application Scenarios

    • At development time, you may want to use a fixed value , such as the height of the screen700
    • At this time, it is recommended not to use fixed values directly, but to use constants
    • When developing, try not to use magic numbers in order to maintain code maintainability

Definition of constants

    • The syntax for defining constants and defining variables is exactly the same as using assignment statements
    • The command for a constant should be that all letters are uppercase, and the words are underlined between the words

The benefits of constants

    • When reading code, you don't need to guess the meaning of a number by means of a constant name .
    • If you need to adjust the value , you only need to modify the constant definition to achieve uniform modification

hint : Python does not have a really meaningful constant, just by naming the convention--all letters are capitalized in time constants, not easy to modify when developing!

Code Adjustment

    • plane_sprites.pyincrease the definition of a constant in
plane_sprites.py
import pygame# 屏幕大小的常量SCREEN_RECT = pygame.Rect(0, 0, 480, 700)# 刷新的帧率FRAME_PER_SEC = 60class 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
plan_main.py
Import pygamefrom aircraft_war.plane_sprites Import *class planegame (object): "" "Aircraft vs. Main game" "Def __init__ (self): Print ("Game Initialization") # 1, create a game window # self.screen = Pygame.display.set_mode ((480, $)) Self.screen = Pygam E.display.set_mode (screen_rect.size) # 2, create game clock Self.clock = Pygame.time.Clock () # 3, call private method, Sprite and Sprite Group Create Self.__create_sprites () def __create_sprites (self): Pass def start_game (self): print ("game starts.        .") While True: # 1, set refresh frame rate Self.clock.tick (frame_per_sec) # 2, Event listener Self.__event_ha            Ndler () # 3, Collision Detection Self.__check_collide () # 4, update/Draw Sprite Group Self.__update_sprites () # 5, update display pygame.display.update () def __event_handler (self): for event in Pygame.event.get () : # Determine whether to exit the game if Event.type = = Pygame.  Quit:planegame.__game_over () def __check_collide (self):      Pass Def __update_sprites (self): pass @staticmethod def __game_over (): Print ("Game Over") p Ygame. QUIT () exit () if __name__ = = ' __main__ ': # Create game Object games = Planegame () # Start Game game.start_game ()

Python--project combat--game frame setup

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.