Python - Project - small game - officially entering the development stage - phase 1 main program & background mobile

5. Structure of main program

Top level design is very important. The following figure is our design

We need to develop two files
1.main 'main program (entry)
2.sprites processing Wizard (Toolkit)

Main program construction

  • How to type the code? Here are all the codes,
# Here is the code in the file
import pygame
# One time import Kit
from plane_sprites import *

class PlaneGame(object):
    """Airplane battle main game"""

    def __init__(self):
        # This is to point to the private method. When initializing
        print("Game initialization")

        # 1. Draw game window
        # Don't write a fixed number. We set a constant to save it. This is a development skill. How to define it?
        # Just use the assignment statement to finish the constant. There is an underline link between all letter sized words. python doesn't have a real constant. We make one through the naming convention. To be clear, it's a conventional way. When others see this kind of thing, they know that the constant shown will not be modified at will. Our constants are all defined in the toolkit , 2 is not in the main program
        # Watch out. SSCREEN_RECT is an object. We get the size ancestor through the object
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        # 2. Set the clock of the game, which is also the module of pygame
        self.clock = pygame.time.Clock()
        # 3. Call private methods, create sprites and Sprite groups,

# Note that the private method starts with one or two underscores
    def __create_sprites(self):
    def start_game(self):
        print("Game begins...")
        while True:
            # The following codes are all independent private methods to simplify the business logic of start me
            # 1. Set refresh frame rate
            self.clock.tick(FRAME_PER_SEC) # Note that the refresh rate here is also a constant
            # 2. Event monitoring
            # 3. Collision detection
            # 4. Update / draw sprite group
            # 5. The update shows that this is very important,
# The following methods are all our private methods
    def __event_handler(self):
        # Monitor whether users click our highlight button
        for event in pygame.event.get():

            # Determine whether to quit the game
            if event.type == pygame.QUIT:
                PlaneGame.__game_over() # How to call static methods? Use the current class name point method

    def __check_collide(self):

    def __update_sprites(self):

    # This is a human static method, this is a modifier, indicating that it is a static method
    def __game_over():
        print("Game over")


# Enter main and add shortcut key to perform the operation of rewinding this file
if __name__ == '__main__':
    # Create game objects
    game = PlaneGame()

    # start games

The preliminary construction of the spirit group

import pygame

# Define a constant for screen size
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
# Refresh frame rate

# Written in parentheses means to inherit the parent class
class GameSprite(pygame.sprite.Sprite):
    """The game elves in the aircraft war, according to the design UML Writing code"""
#Note that to override the init method here, we pass parameters in the init initialization method (line function)
    def __init__(self, image_name, speed=1):

        # Call the initialization method of the parent class. When our parent class is not the object base class, we must call the super() object to call the initialization init method of the parent class

        # Define the attributes of the object, which record the position, speed and movement of the sprite respectively
        self.image = pygame.image.load(image_name)
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self):
        # Move in the vertical direction of the screen
        self.rect.y += self.speed

6 background development

One of the core algorithms to realize the movement of game background is to reset the position and go back
Prepare two pictures. When the first picture goes to the end, immediately reset the second one to the top of the first one. This will create a moving animation effect

Now we want to design a background motion class that inherits the sprite class

class Background(GameSprite):#We inherit the parent class. And amplification function
    """Game background Wizard"""

    def __init__(self, is_alt=False):
# Algorithm: encapsulated business logic: call this method twice to create two image objects. Let's make a mark. If it's true, it's the second one. When we create it, we need to change the position, so we get two pic ture s in different positions

        # 1. Call the parent method to create the sprite (image/rect/speed)

        # 2. Judge whether it is an alternate image. If it is, you need to set the initial position
        if is_alt:
            self.rect.y = -self.rect.height

    def update(self): # Override method of parent class

        # 1. Call the method implementation of the parent class, move vertically

        # 2. Judge whether to move out of the screen. If you move out of the screen, set the image to the top of the screen
        # The core algorithm is here. If the first picture exceeds, move it back immediately
        if self.rect.y >= SCREEN_RECT.height:
            self.rect.y = -self.rect.height

Code implementation is calling our background Wizard
Create sprites and Sprite groups in our "create sprites" method
Call Update in __update_sprites and draw method to draw elves.

The specific implementation is in the main program:

# Note that the private method starts with one or two underscores
    def __create_sprites(self):

        # Create background sprites and Sprite groups

        # This is an optimized code. We take all the packages that can be encapsulated away
        # bg1 = Background("./images/background.png")
        # bg2 = Background("./images/background.png")
        # bg2.rect.y = -bg2.rect.height
# Encapsulated business logic: call this method twice to create two image objects. Let's make a mark. If it's true, it's the second one. When we create it, we need to change the position, so we get two pic ture s in different positions

        bg1 = Background()
        bg2 = Background(True)
        # Screen Wizard

        # Background sprite group
        self.back_group = pygame.sprite.Group(bg1, bg2)

    def __update_sprites(self):

        # Call its two methods notice that the second method is to draw a place under the bed (the current screen object)


Focus ~ ~ encapsulate the function implementation of the unwanted class and do not expose it

Tags: Python

Posted on Sun, 05 Apr 2020 08:16:15 -0700 by Chrisww