Alien invasion armed spaceship (3)

Table of contents

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


Preface

  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 Mapping

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 new module called game_functions , which will store a number of functions that make the game Alien Invasion run. By creating the module game_functions , you can make 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 the 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. 

# 定义监查事件函数
def check_events():
    """响应按键和鼠标事件"""
    # 监听键盘和鼠标事件
    for event in pygame.event.get():  # 使用方法pygame.event.get()。所有键盘和鼠标事件都将促使for循环运行
        if event.type == pygame.QUIT:  # 如果玩家单机游戏窗口关闭按钮,则将检测到pygame.QUIT事件
            sys.exit()  # 监测到事件后,退出游戏

 2.3, Modify alien_invasion.py file

2.3.1, Import module

import game_functions as gf  # 导入game_functions模块

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

2.3.2, Call function

gf.check_events()  # 调用gf.模块中的check_events()函数

                            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 

To further simplify run_game() , the code for updating the screen is moved to a function called update_screen() and placed in the module game_functions.py :

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 game background, spaceship and other event codes

                                Cut the remaining code in the while part

# 每次循环时都重绘屏幕
    screen.fill(S_settings.bg_color)
    ship.blitme()  # 调用ship.blitme()将飞船绘制到屏幕上
    # 让最近绘制的屏幕可见
    pygame.display.flip()
    """命令Pygame让最近绘制的屏幕可见。在这里,它在每次执行while循环时都绘制一个空屏幕,并擦去旧屏幕,使得只有新屏幕可见。在我们移动游戏元
素时,pygame.display.flip()将不断更新屏幕,以显示元素的新位置,并在原来的位置隐藏元素,从而营造平滑移动的效果。"""

2.4.3, calling function

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

 gf.update_screen(S_settings, screen, ship)  # 调用gf.模块中的update_screen()函数 

 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

Whenever the player presses a key, an event will be triggered in Pygame . Events are obtained through the method pygame.event.get()
, so in the function check_events() , we need to specify which types of events we want to check.
Every time we press build, a KEYDOWN event will be registered.
When a KEYDOWN event is detected . If we press the right button, then we increase the rect.centerx value of the spacecraft and 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:   # 如果事件为KEYDOWN事件
            if event.key == pygame.K_RIGHT:  # 如果是游戏的特定键
                # 向右移动飞船
                ship.rect.centerx += 1

3.1.2, Modify alien_invasion.py file

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

 gf.check_events(ship)  # 调用gf.模块中的check_events()函数

 3.2, allowing constant 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 will have the game detect the pygame.KEYUP event so we know when the player releases the right arrow key;
We will then use a combination of KEYDOWN and KEYUP events, along with a flag called moving_right to achieve continuous movement.
When the ship is not moving, the flag moving_right will be False . When the player presses the right arrow key, we set this flag to
True ; 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 .

 # 移动标志
        self.moving_right = False  # 因为飞船初始为不动的状态,所以直接设置为false

    def update(self):
        """根据移动标志调整飞船的位置"""
        if self.moving_right:  # 当飞船事件为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     # 按下右键件后将moving_right设置为True
    # 监测是否松开键
        elif event.type == pygame.KEYUP:     # 响应KEYUP事件
            if event.key == pygame.K_RIGHT:  # 如果是松开键,并且松开的是右键
                ship.moving_right = False    # 松开右键后将moving_right设置为False

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

Finally, we need to modify the while loop in alien_invasion.py so that the spacecraft's
methodupdate ()
 ship.update()  # 飞船移动

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, do the 3.1 keystroke response there:

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 so much.

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.  

Guess you like

Origin blog.csdn.net/weixin_72543266/article/details/132640084