Alien invasion armed spaceship (2)

Table of contents

Table of contents

Preface

mind Mapping

Project article list

1. Set the background color

1.1, background color specification

RGB 

1.2, fill the entire screen with background color

2. Create a settings class

2.1, create settings.py file

2.2, modify alien_invasion.py file

2.2.1, Import module 

 2.2.2, modify alien_invasion.py file parameters

3. Add spaceship image

3.1. Create the Ship class

3.1.1, initialize the spacecraft and obtain its initial position

3.1.2, draw the spacecraft at the specified position

3.2. Draw the spaceship on the screen 

3.2.1, Import module

 3.2.2, Create a spaceship

3.2.3, Draw the spacecraft to the screen

2.2.4, display results 

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)

1. Set the background color

1.1, background color specification

          In order to avoid the current game screen being completely black , set a common color for the screen.

   Because the color only needs to be specified once, we only need to specify the color before the while loop. Here is the code from the last time. If you are not sure, you can read the previous article.

                  Here is bg_color, which is the background color, followed by the RGB parameters. 

 pygame.display.set_caption("外星人入侵")

    # 设置背景色(RGB)
    bg_color = (220, 226, 241)

    # 开始游戏的主循环
    while True:  # 永真使得游戏一直执行

RGB 

Here is another knowledge point, RGB

In Pygame , colors are specified in RGB values, which consist of red, green, and blue values , where each value
The possible value ranges are 0~255 . The color values ​​(255, 0, 0) represent red, (0, 255, 0) represent green, and (0, 0, 255) represent blue. By combining different RGB values, 16 million colors can be created . In the color values ​​( 220, 226, 241 ) it sets the background to a sea-sky blue.

Recommend here

11 eye protection colors that can reduce eye fatigue_with color codes and RGB values 

1.2, fill the entire screen with background color

Call the method screen.fill()   in pygame , and then pass in the color parameter of bg_color to fill the screen with the background color;
Note: This method only accepts one argument and one color.
 # 监听键盘和鼠标事件
        for event in pygame.event.get():  # 使用方法pygame.event.get()。所有键盘和鼠标事件都将促使for循环运行
            if event.type == pygame.QUIT:  # 如果玩家单机游戏窗口关闭按钮,则将检测到pygame.QUIT事件
                sys.exit()  # 坚持到事件后,退出游戏

        # 每次循环时都重绘屏幕
        screen.fill(bg_color)
        # 让最近绘制的屏幕可见
        pygame.display.flip()

2. Create a settings class

2.1, create settings.py file

  Every time we add new features to the game, we need to introduce some new settings. In order to make it easier for us to maintain and use, and to make the game easier to modify, we create a settings.py file to facilitate all classes in the game. are stored in this file.

class Settings():
    """存储《外星人入侵》的所有设置的类"""

    def __init__(self):
        """初始化游戏的设置"""
        # 屏幕设置
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (220, 226, 241)

     Here we add a Settings class, and then initialize the screen width, height and color parameters in the class

2.2, modify alien_invasion.py file

In order to make settings.py and this file use each other, we need to make changes to this file.

2.2.1, Import module 

 First we need to import the Settings class into the setting.py file. This line of code is at the top, the location of the imported library.

from settings import Settings  # 从settings.py文件导入Settings类

 2.2.2, modify alien_invasion.py file parameters

 pygame.init()  # 初始化背景设置,让Pygame能够正确地工作
    S_settings = Settings()  # 创建Setting实例赋值给S_Setting
    # 创建一个名为screen的显示窗口,实参(1200, 800)是一个元组,指定了游戏窗口的尺寸,宽1200像素,高800像素
    screen = pygame.display.set_mode((S_settings.screen_width, S_settings.screen_height))

            Here, we create a Settings() instance and assign it to, S_Setting.

Then we need to change the parameters in brackets to use instances to access them.

   If you are not very familiar with class knowledge or have forgotten it, you can review it by reading an article I wrote.

Python basic syntax: class notes 

3. Add spaceship image

  Now add the spaceship to the game. To draw the player's ship on the screen, we will load an image and use
Pygame method blit() draws it. Of course, when choosing game materials, be careful not to infringe and choose appropriate pictures. Here I give a picture of the spaceship that comes with the game. It is a spaceship that looks like this as the material of the game.
 

3.1. Create the Ship class

  After we select the ship picture, considering that we need to perform many operations on the ship, here we first create a ship.py file, and then create a ship module, which contains the Ship class to manage most of the behaviors of the ship.

Below we mainly perform the following operations:

import pygame


class Ship():
    def __init__(self, screen):
        """初始化飞船并设置其初始位置"""
        self.screen = screen

        # 加载飞船图像并获取其外接矩形
        self.image = pygame.image.load('ship.bmp')  # 加载飞船图像
        self.rect = self.image.get_rect()  # 获取图像的矩形
        self.screen_rect = screen.get_rect()  # 获取屏幕的矩形

        # 将每艘新飞船放在屏幕底部中央
        self.rect.centerx = self.screen_rect.centerx  # 设置飞船的横坐标为屏幕中心点的横坐标
        self.rect.bottom = self.screen_rect.bottom  # 设置飞船的纵坐标为屏幕底部的纵坐标

    def blitme(self):
        """在指定位置绘制飞船"""
        self.screen.blit(self.image, self.rect)  # 绘制飞船图像到指定的矩形位置上

3.1.1, initialize the spacecraft and obtain its initial position

  First initialize the screen, and then load the spacecraft image. We need to obtain the image and the rectangle of the screen.

Then to locate the spacecraft position, the module in pygame is used.

The code is as above: 

3.1.2, draw the spacecraft at the specified position

 Here we use the blit method to draw

The code is as above: 

3.2. Draw the spaceship on the screen 

3.2.1, Import module

First, we continue to import the ship module in the alien_invasion.py file

from ship import Ship          # 从ship.py文件导入Ship类

 3.2.2, Create a spaceship

Then we instantiate the ship in the bottom code. To avoid creating a ship every time, we create it before while.

 pygame.display.set_caption("外星人入侵")
    
    # 创建一艘飞船
    ship = Ship(screen)

    # 开始游戏的主循环
    while True:  # 永真使得游戏一直执行

3.2.3, Draw the spacecraft to the screen

      Based on the previous code, call the blitme method to draw the spacecraft. This is also a knowledge point related to classes. Use objects to call methods after instantiation.

 # 每次循环时都重绘屏幕
        screen.fill(S_settings.bg_color)
        ship.blitme()  # 调用ship.blitme()将飞船绘制到屏幕上

2.2.4, display results 

At this point, we can see the small spaceship at the bottom in the center. Of course, I did not display the background of the picture as a transparent color. I just need to handle it by myself.

4. Summary

This article is mainly a continuation of the previous article, adding changes to the game background, and then making two frameworks for class management in subsequent game projects. The purpose is to facilitate the management of some settings in the game. As well as management related to game spaceships.

A word a day

No matter what everyone in the world says, I believe that my own feelings are the most correct. No matter what others think, I will never disrupt my own rhythm. I can stick to what I like, but I can't last long if I don't like 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/132549005