Alien invasion armed spaceship (3)

Directory

Table of contents

Preface

mind Mapping

Project article list

1. Refactoring: module game_functions

2. Create the game_functions.py file

2.1, Import module

2.2. Transfer the exit game event

2.3, Modify alien_invasion.py file

2.3.1, Import module

2.3.2, Call function

2.4, Create the function update_screen() in the game_functions.py file

2.4.1, Create update_screen() function

2.4.2. Transfer game background, spaceship and other event codes

2.4.3, calling function

3. Spaceship moves

3.1, key response

3.1.1, Modify the game_functions.py file

3.1.2, Modify alien_invasion.py file

3.2, allowing constant movement

3.2.1, Design ideas

3.2.2, Implementation of ideas

3.2.2.1, modify ship.py file

3.2.2.2, Modify the game_functions.py file

3.2.3, Modify the alien_invasion.py file to call the function

3.3, Production effect display

4. Summary


Foreword

After several months of study, I have some experience in learning Python. I want to train and evaluate my development capabilities through several slightly larger projects. I will continue to learn and practice Python programming from entry to practice today. Projects in this book.

In this project, I will interpret some of the methods and structures used in the project, and what I learn is my own.

Mind map

Project article list

Alien invasion armed spaceship (1)

Alien invasion armed spaceship (2)

1, Refactoring: module game_functions

In large projects, it is often necessary to refactor existing code before adding new code. Refactoring aims to simplify the structure of existing code so that

It’s easier to scale. In this section we will create a file called
New module for game_functions
, which will store a large number of functions that make the game Alien Invasion run. Create module by
game_functions
,Can
alien_invasion.py
too long and make its logic easier to understand.

Here we will reconstruct the function and put some previously written code into the function to facilitate the management of the code and the game.

2, create game_functions.py file

2.1,import module

import sys
import pygame

2.2, transfer the exit game event

Then we cut the code that controls the game exit in the alien_invasion.py file.

# Define monitoring event function
def check_events():
    """Response to key and mouse events"""
    #Listen to keyboard and mouse events
    for event in pygame.event.get(): # Use method pygame.event.get(). All keyboard and mouse events will cause the for loop to run
        if event.type == pygame.QUIT: # If the player closes the single-player game window button, the pygame.QUIT event will be detected
            sys.exit() # After detecting the event, exit the game

2.3, modify alien_invasion.py file

2.3.1,import module

import game_functions as gf # Import game_functions module

Import the module in the alien_invasion.py file to facilitate calling the exit game function

2.3.2, call function

gf.check_events() # Call the check_events() function in the gf. module

Make a function call at the location where you cut the code before

2.4, create the function update_screen() in the game_functions.py file

for further
Simplify run_game()
, the code that updates the screen will be moved below to a file called
update_screen()
function, and place this function in the module
game_functions.py
middle:

2.4.1, Create update_screen() function

Note that three parameters need to be included, which are to control the screen color, the spaceship and the screen of the display window.

def update_screen(S_settings, screen, ship):

2.4.2, transfer the game background, spaceship and other event codes

Cut the remaining code in the while part

# Redraw the screen each time through the loop
    screen.fill(S_settings.bg_color)
    ship.blitme() # Call ship.blitme() to draw the ship to the screen
    # Make the most recently drawn screen visible
    pygame.display.flip()
    """Instructs Pygame to make the most recently drawn screen visible. Here, it draws an empty screen every time it executes the while loop and erases the old screen so that only the new screen is visible. Before we move the game element
When the element is running, pygame.display.flip() will continuously update the screen to show the new position of the element and hide the element in its original position, creating a smooth moving effect. """

2.4.3, Call function

Since the module has been imported above, you only need to call the module.

 gf.update_screen(S_settings, screen, ship) # Call the update_screen() function in the gf. module 

3. Spaceship moves

Next, let the player move the spacecraft left and right. We’ll write code that responds when the user presses the left or right arrow key. We will first focus on moving to the right and then use the same principles to control movement to the left. Learn how to control the movement of screen images by following the steps below.

3.1, key response

3.1.1, modify the game_functions.py file

When the player presses a button, the
Pygame
trigger an event. Events are passed through methods
pygame.event.get()
get

is taken, so in the function
check_events()
, we need to specify which types of events we want to check for.

We will register one every time we press build
KEYDOWN
event.

When it is detected that a
KEYDOWN
event. If we press the right button, then we will increase the size of the spacecraft
rect.centerx
value to move the spacecraft to the right:

Here we need to pass in a ship parameter to the function that checks the event, because the keys affect the parameters of the ship

def check_events(ship):
 elif event.type == pygame.KEYDOWN: # If the event is a KEYDOWN event
            if event.key == pygame.K_RIGHT: # If it is a specific key of the game
                # Move the spaceship to the right
                ship.rect.centerx + = 1

3.1.2, modify alien_invasion.py file

Since the ship parameter is passed in to check_events(ship):, you must pass the parameter to the function that controls the running of the game.

 gf.check_events(ship) # Call the check_events() function in the gf. module

3.2, allow continuous movement

3.2.1, Design Ideas

When the player holds down the right arrow key, we make the spacecraft continue to move to the right until the player releases it.

We’ll let the game detect
pygame.KEYUP
event so we know when the player releases the right arrow key;

We will then use a combination of
KEYDOWN and KEYUP
event, and an event named
moving_right
sign to achieve continuous movement.

When the spacecraft is stationary, the sign
moving_right
will be
False
. When the player presses the right arrow key, we set this flag to

True
; and when the player releases, we reset this flag to
False
.

3.2.2, Implementation of ideas

3.2.2.1, modify ship.py file

Modify the code in the ship.py file and add the movement flag and update function

We first define the movement flag as False when running the code for the first time, initially define it, and define the movement function. The code in the movement function is cut from the place where it was moved in the previous step 3.1.1. Because that part will be modified later .

 # Move flag
        self.moving_right = False # Because the spacecraft is initially in a motionless state, it is directly set to false

    def update(self):
        """Adjust the position of the spacecraft according to the movement mark"""
        if self.moving_right: # The spaceship moves when the spaceship event is True
            self.rect.centerx + = 1

3.2.2.2, modify the game_functions.py file

Here, we first change the modified place and press the right button to change the initial setting of False to True.

And added monitoring responds to the event of releasing the button, and when the right button is released, it will be set to False.

 ship.moving_right = True # Set moving_right to True after pressing the right button
    # Monitor whether the key is released
        elif event.type == pygame.KEYUP: # Respond to KEYUP event
            if event.key == pygame.K_RIGHT: # If the key is released, and the right button is released
                ship.moving_right = False # Set moving_right to False after releasing the right button

3.2.3, Modify the alien_invasion.py file to call the function

Finally, we need to modify
alien_invasion.py
middle
while
loop so that each time the loop is executed the ship’s

method
update()

 ship.update() # Ship movement

Here we place the called function before changing the screen:

The ship’s position will be updated after a keyboard event is detected (but before the screen is updated). In this way, when the player inputs, the position of the spacecraft

The position will be updated, ensuring that the ship is drawn to the screen using the updated position.

3.3, Production effect display

For the first time, without setting up constant movement, do3.1 Key ResponseThere:

When we right-click once, it will only move a small square circled 1 in the picture.

After adding constant movement:

We can move Circle 2 by a large amount.

4, Summary

This article is mainly a reconstruction of some of the previously written code to facilitate more and more functions in the future, and simplification of the code, which provides convenience for further management of subsequent code.

It has also added the function of moving the spaceship to the right, and added that if you hold down the button without moving, the spaceship will keep moving to the right, making the game more reasonable.

Generally speaking, it cultivated my thinking in the project production process and gave me a clearer understanding of the project development process.

A word a day

It’s not a waste of time if you can have fun wasting it.

If my study notes are useful to you, please like and save them. Thank you for your support. Of course, you are also welcome to give me suggestions or supplement the shortcomings in the notes. It will be of great help to my study. Thank you.