One hour, one article, one literary meeting, python, and then do a plane war game

Posted by remmy82 on Fri, 18 Feb 2022 10:09:39 +0100

Note:

Students who want to study slowly can see mine Introduction to python to game practice column (updating)
Students who want to learn C can watch it Dahua series: C language (basically updated)
Students who want to learn C + + can watch it Dahua C + + (updating)
Those who want to do exercises can see it Detailed explanation of 100 cases of College Students' C language homework and exercises in vernacular

Introduction to the author

Author name: 1_bit

Introduction: CSDN blog expert, 2020 blog star TOP5, signed author of blue bridge. In 15-16 years, he had a live broadcast on the Internet and led a group of program Xiaobai on the road of programmers. Welcome to Xiaobai and I to inquire about my relevant information. If you are confused, you will find the answer. The series of tutorials will be changed to paid location when the traffic is reduced. It will not be when the traffic is large. Please hurry up to study~

Start learning

👸 Xiaoyuan: little C, I want to learn to play games. Is there any quick way? 😰

🐰 C: No, thanks.

👸 Xiaoyuan: I think they can all do a plane war directly. They said they learned it all at once. 😨

🐰 C: do you want to go through the content first? Or specific and comprehensive learning?

👸 Xiaoyuan: I want to have a little experience first. It's OK to learn comfortably and play for a while.

🐰 C: that's OK. It'll be done in an hour.

👸 Xiaoyuan: so fast? Then you just said no. 😣

🐰 Little C: you don't study comprehensively. It's no problem to study only the basic core. You can still do something in an hour.

👸 Xiaoyuan: let's start quickly.

🐰 C: let's learn python. What do you think?

👸 Xiaoyuan: Yes, just make a game.

🐰 C: I remember your computer has an environment and editor. We'll just use the original one.

👸 Xiaoyuan: what was it originally?

🐰 Little C: the vscode library we use is pygame.

👸 Xiaoyuan: Well, I see.

01 hello world

🐰 C: let's start from scratch. First, open our vscode and create a file called game Py to test the code.

👸 Xiaoyuan: Yes, I have built a new one.

🐰 Little C: let's write a hello world first.

👸 Xiaoyuan: what is hello world? 😰

🐰 Little C: it's a classic computer program. When the program runs, it will display hello world.

👸 Xiaoyuan: I see. How do you do that?

🐰 C: first of all, you should know that programming is actually using different "magic instructions" to create different things in the computer. The instruction used by python to display the content is print(). You can add what string you want to display with print().

👸 Xiaoyuan: is that right?

print(helloworld)

🐰 Little C: I need to mention here that strings in python need to be enclosed in double quotation marks.

👸 Xiaoyuan: I see. That's what you mean.

print("helloworld")

🐰 Xiao C: Yes, at this time, we can see the results by clicking the run button.

👸 Xiaoyuan: the result is here.

02 variable

🐰 Little C: let's go on. Next, let's learn a container to store values.

👸 Xiaoyuan: does the content of stored value mean anything?

🐰 C: Yes, you think about it. In the game, in fact, your blood volume is stored in a container and your nickname. Otherwise, you don't think there is anything stored. How can this thing be displayed?

👸 Xiaoyuan: hahaha, I didn't understand before, but now I understand. 😂

🐰 Small C: the variable is also super simple. We can directly give the variable a name and use an equal sign to save the value. Now you create a variable. What name do you think of?

👸 Xiaoyuan: just name it a.

🐰 Little C: what value do you want to save in this variable a?

👸 Xiaoyuan: then save a 10.

🐰 C: then the code can be written like this.

a=10

👸 Xiaoyuan: that's it? 😂

🐰 Small C: Yes, we create a variable directly with a name. Connect a value with an equal sign on the right side of the variable name, and the value will be stored in the variable.

👸 Xiaoyuan: that's easy. 😎

🐰 C: do you know how to store a string?

👸 Xiaoyuan: Yes, that's it.

a="1_bit"

🐰 C: why do you write that?

👸 Xiaoyuan: because a is a variable name, you can use an equal sign to save the value on the right of the equal sign to the variable on the left. At first, you said that the string needs double quotation marks in python. That's how it is written.

🐰 Little C: Yes, I understand it thoroughly. Let's start displaying the contents stored in variables.

👸 Xiaoyuan: not this one. How to display it?

🐰 Small C: it's very simple. Just use print() to fill in the variable name directly in the brackets of print().

👸 Xiaoyuan: is that right?

a="1_bit"
print(a)

🐰 C: Yes.

👸 Xiaoyuan: the result came out.

🐰 Small C: you can use print() to display a lot of content. For example, you can use commas to separate if you want to connect strings together. First, we create multiple variables.

a="1_bit"
b="2_bit"
c="3_bit"

👸 Xiaoyuan: so you can create several variables? 😲

🐰 C: Yes, python code is written line by line from top to bottom. Remember this. At the end of each sentence, you need to change to the next line to write.

👸 Xiaoyuan: I see.

🐰 Little C: then we can display the contents of these variables at the same time and directly use print(). Fill in several variables in the parentheses of the print() element and separate them with commas.

a="1_bit"
b="2_bit"
c="3_bit"
print(a,b,c)

👸 Xiaoyuan: it's displayed after I run it.

🐰 Small C: you can also fill in other strings in print() and output them as values.

👸 Xiaoyuan: that means you can use quotation marks to cause the string, right? Then separate them with commas?

🐰 Small C: Yes, so the string is also a value. As long as it is filled in, it can be output and displayed.

👸 Xiaoyuan: the code is like this. I ran it.

a="1_bit"
b="2_bit"
c="3_bit"
print("Output separately a b c Value of:",a,b,c)

03 variable operation

🐰 Small C: in fact, our variables can be added and subtracted, such as the following codes and results.

a=11
b=2
c=31
print(a+b)
print(a-b)
print(a*c)

👸 Xiaoyuan: I see. It's the same as in daily life.

🐰 Little C: actually, it's just that the basic operations are roughly the same. We can take a look at the following example.

a="11"
b="2"
c="31"
print(a+b)
print(a+b)
print(a+c)


👸 Xiaoyuan: why?

🐰 Small C: because two strings are added, this addition refers to connecting two strings, because string and number are two types. The double quoted 11 is the string 11, not the number 11. You have to understand this.

👸 Xiaoyuan: hahaha, I see. That is to say, numbers are also characters. Look at the performance in different forms. 😋

🐰 C: Yes.

04 logical judgment

🐰 Little C: next, we can look at the logical judgment. This is a very important knowledge point.

👸 Xiaoyuan: is it used a lot in the game?

🐰 Little C: there are a lot of logic to judge what you want to do.

👸 Xiaoyuan: then I'll study hard.

🐰 C: in fact, logical judgment is just like when you log in to the game, you need to judge your account password. Judge whether the account password is correct, log in to the game if it is correct, and quit the game if it is wrong. That's what it means.

👸 Xiaoyuan: I see.

🐰 Small C: logical judgment uses if in python. We can take this if as a magic sentence, and we can type it when we need logical judgment.

👸 Xiaoyuan: I see. It's like saying a spell. 😂

🐰 C: Yes. After we type if, we add a condition after if, and then end with a colon, just like the following.

a=11
if a==11:
    print("a Is equal to 11")

👸 Xiaoyuan: Well, first you create a variable a to store the value of 11, and then you use the if statement to give a condition that a==11, and then the colon ends. But I'd like to ask if you typed two equals here. Are you wrong?

🐰 Little C: No. In python, two equal signs are used to judge whether the left and right sides are equal, that is, to judge whether the coordinate a of the two equal signs is equal to 11 on the right.

👸 Xiaoyuan: I see. Then why should we leave a few spaces in front of the next print()?

🐰 Little C: think about it. If the condition is correct, should one sentence be executed, and if the condition is wrong, another code should be executed?

👸 Xiaoyuan: Yes.

🐰 C: in fact, if this condition is correct, print the next line after the colon ("a is equal to 11"). The previous use of several spaces means that this code belongs to the judgment structure of if, which is not the same as other codes. In this way, as long as the condition is wrong, it will not be executed in the if structure. If you put it outside, it will be executed.

👸 Xiaoyuan: I see. In this way, you can identify what is inside the if structure and what is inside the if structure.

🐰 Small C: Yes, the results will be displayed after running.

👸 Xiaoyuan: if I modify the value of a, he won't display it. Nothing is displayed. 😨

a=111
if a==11:
    print("a Is equal to 11")

🐰 Little C: in fact, we can type a lot of code in the if statement because the programming is flexible. For example, this example:

a=11
if a==11:
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")

👸 Xiaoyuan: do you want to leave the same blank space?

🐰 C: Yes, that means the same level. If you leave blank spaces, you will make mistakes.

👸 Xiaoyuan: I see.

🐰 Little C: if we want to know the judgment error at this time, we can add an else statement. If there is an error, the code inside the else statement will be displayed.

a=111
if a==11:
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
else:
    print("Wrong judgment")
    print("Wrong judgment")
    print("Wrong judgment")


👸 Xiaoyuan: I see. Must this else statement be followed immediately after the end of the if statement? And he is the head, there is no blank space.

🐰 C: Yes, because if and else are at the same level. If you also have a blank space, it can only be executed after the if statement is judged to be correct? In this way, else statements will never be executed, and it is also wrong to write in this way; Else can also follow elif. When we have multiple conditions, we can use elif statements.

👸 Xiaoyuan: let's take an example.

🐰 Little C: look below.

a=2
if a==11:
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
    print("a Is equal to 11")
elif a==2:
    print("a Is equal to 2")
    print("a Is equal to 2")
    print("a Is equal to 2")
elif a==3:
    print("a Is equal to 3")
    print("a Is equal to 3")
    print("a Is equal to 3")
else:
    print("Wrong judgment")
    print("Wrong judgment")
    print("Wrong judgment")

👸 Xiaoyuan: is elif followed by conditions? For example, a2 and a3?

🐰 Small C: Yes, when the if condition is judged wrong, it will be judged in turn. If the condition is judged correctly, the code in that condition will be executed. If all conditions are wrong, the else part will be executed.

👸 Xiaoyuan: I see. How much can I finish the basics? 😩

🐰 Little C: half finished. It's super fast. Hahaha.

👸 Xiaoyuan: OK, please continue.

🐰 Small C: actually, if can also be nested. For example, the following code.

a=2
b=3
if a==2:
    if b==3:
        print("Fully meet the requirements")
else:
    print("The first requirement is not met")

👸 Xiaoyuan: nesting means there is another if in the if?

🐰 Small C: Yes, but the if in it also has levels. To represent the code in the if, you still need to use several space intervals and shrink them in turn.

👸 Xiaoyuan: I see.

05 cycle

🐰 Little C: next, let's learn the cycle. When you want to run a piece or a piece of code repeatedly, we can use loops to save our code writing time, such as the following code.

i=0
while i<10:
    print("Hello")
    i=i+1

👸 Xiaoyuan: you first created a variable i, and then i don't understand.

🐰 Small C: while is a loop, just like you use if. Using while means that you want to start the loop; After while, there is a condition, that is, the code in the while loop will be cycled only when this condition is met. This condition ends with a colon. Does it feel that the form of while is very similar to that of if statement?

👸 Xiaoyuan: Yes, it feels the same. Then the last two are empty in the front and use the same space. Does it mean the code in the while loop structure?

🐰 Small C: Yes, this will execute the loop. Each loop will execute print("hello") and i=i+1. Since the condition is i < 10, i will add 1 for each cycle. The first cycle i is 0, the second cycle i is 1, and so on. It will certainly exceed 10. At this time, it will not cycle. Here is the result.

👸 Xiaoyuan: I see. Can loops also be nested?

🐰 C: Yes, but we don't need to talk about it for the time being. Because it's quick, we'll explain it later in the game production.

👸 Xiaoyuan: OK.

06 list

🐰 Little C: next, let's talk about a list. When we store values, we use variables to store one value, so we can use lists to store multiple values.

a=[99,6,7,85,2,3]
print(a)
print(a[0])
print(a[4])
a[0]="Hello"
print("The modified value is:",a)


🐰 Little C: here, a is the list. Then use an equal sign to put the values we want to store in brackets, and use commas to separate the values. At this time, we can create a list.

👸 Xiaoyuan: I see. It feels very simple. Then print(a) is the value of this list? 😢

🐰 Small C: Yes, and then print(a[0]) means to output the first element in the a list. In the list, 0 represents the first element 99, then 1 represents the second element 6, and so on. We use a variable name when outputting, and then use square brackets after it. Write the number of elements you want to display in square brackets to get this element, and then display and output the value.

👸 Xiaoyuan: I see. Then a[0] = "hello" means to re assign this position?

🐰 Little C: Yes, at this time, we can see that the content of the first element changes when all the values are finally output.

07 list and for loop

🐰 Little C: in fact, we can also use a loop to display the values of our list one by one. This loop is called for loop.

👸 Xiaoyuan: is there anything else you haven't finished? 😰

🐰 Little C: Yes, there is another for loop that hasn't been learned. Look at the following code example.

a=[99,6,7,85,2,3]
for v in a:
    print(v)


👸 Xiaoyuan: each value is output and displayed one by one.

🐰 C: Yes, the for in the code for v in a: means to start using the for loop. In the next v in a, you can understand that you can directly create a variable v here, and then enter the variable v into the list of a to take values one by one. First, the first value will be taken, and then each cycle will jump to the next value. At this time, we can take out this value, Use print() to display.

👸 Xiaoyuan: so it is. I understand. 😂

08 custom function

🐰 Little C: next, we start to write custom tools. In fact, print() can be called a function, which can be understood as a tool or a function. When we need to use these functions, we can just take the bytes and use them. Now we need to write a menu function. We don't need to write so much code every time we use the menu. We can use it directly.

👸 Xiaoyuan: so I can save a lot of time?

🐰 Small C: Yes, this is called a user-defined function. Write a function yourself. You can see the following code example.

def menu():
    print("This is a menu you can view")
    print("1.Enter the system")
    print("2.Exit the system")
    print("3.Delete system")
    print("4.Exit account")
    print("5.Close the software")

menu()

👸 Xiaoyuan: won't it be the content directly displayed by the print above at this time?

🐰 C: No, let me explain what this means first. We can see that def means that you start to create a user-defined function. After DEF is a function name, followed by a bracket, which is a form of defining a function. Then we can end it with a colon.

👸 Xiaoyuan: for example, if I want to create a function called abc, can I write it like this.

def abc():

🐰 Small C: Yes, and then start writing the code of this function on the next line under the colon. Similarly, you need to use spaces to indicate that this code belongs to the content of this function.

👸 Xiaoyuan: I see.

🐰 Little C: calling a function means using a function. You can use it directly by using the function name plus a pair of parentheses. At this time, it is equivalent to running the code in the function, and the content is displayed at this time.

👸 Xiaoyuan: what do you mean if you don't use it, it won't work?

🐰 C: Yes, that's what I mean.

👸 Xiaoyuan: I see.

🐰 Small C: actually, the function can also accept parameters. Just like you use print(), you need to pass in data to display. You can also accept parameters by creating a function yourself. In fact, the parameters are like cooking with an electric rice cooker in your life. You need rice to cook. This rice is the parameter of the function of the electric rice cooker.

👸 Xiaoyuan: I see. How do you do that?

🐰 Small C: very simple. Create variables in parentheses of custom functions. If there are multiple variables, use commas to separate them.

👸 Xiaoyuan: you mean so? 😂

def abc(a,b):

🐰 Small C: Yes, for example, the following code.

def abc(a,b):
    print(a+b)

abc(1,2)

👸 Xiaoyuan: at this time, 1 is equal to saving in a, and then 2 is equal to saving in b, right?

🐰 Small C: Yes, if you only want the function as a calculation without output, we can use a function called return to return the value. For example, the following code.

def abc(a,b):
    return a+b

c=abc(1,2)
print(c)

👸 Xiaoyuan: you mean return will return the result of a+b?

🐰 Small c: Yes, at this time, c can receive. After abc(1,2) is calculated, it is equal to 3. Finally, the content of output c can be seen to be equal to 3.

👸 Xiaoyuan: I see.

09 classes and objects

🐰 Little C: what we need to learn next is object-oriented.

👸 Xiaoyuan: what is object-oriented? I have no object. 😨

🐰 Little C: in fact, object-oriented doesn't mean you need an object. In fact, we can create a type. After instantiation, this type is an object.

👸 Xiaoyuan: I don't understand. It's so difficult. 😭

🐰 Little C: actually, it's not difficult. Look at the following example.

class human:
    name=""
    age=0
    def say(self):
        print("hello")
    def myInfo(self):
        print("myName:",self.name,"myAge:",self.age)

👸 Xiaoyuan: I can't understand it at all. It's so difficult.

🐰 C: let me explain to you one by one. The class in the above code means to create a class now, and human is the name of the class.

👸 Xiaoyuan: you mean when class is the keyword, followed by the name of this type?

🐰 Small C: Yes, in this human type, there are two attributes; One attribute is called name and the other is called age.

👸 Xiaoyuan: just like normal variables, a name stores an empty string and an age stores an age.

🐰 Xiao C: Yes, here, name is used to store name and age is used to store age. Next, there are two methods, one is say and the other is myInfo.

👸 Xiaoyuan: are these two custom functions? Why is the parameter self?

🐰 Small C: this self can be understood as the meaning of the current type. Among the parameters of the parent user-defined function, we can take it as indicating that the user-defined function belongs to this class.

👸 Xiaoyuan: you mean adding self means that it is the current method of this type?

🐰 Xiao C: Yes, the rule is to do so. You can see the code print("myName:",self.name,"myAge:",self.age). Self means the current type, self Name means the variable name in the current type. We can understand that the decimal point is "de". Self Name is the name variable in the current type.

👸 Xiaoyuan: I see. 😂

🐰 Little C: let's take a look at the following usage methods.

class human:
    name=""
    age=0
    def say(self):
        print("hello")
    def myInfo(self):
        print("myName:",self.name,"myAge:",self.age)

xiaoM=human()
xiaoM.say()
xiaoM.myInfo()
xiaoM.name="XiaoMing"
xiaoM.age=18
xiaoM.myInfo()

🐰 Small C: xiaoM=human() is to create a human object. For example, if a person is a type, then a specific person is an object. Now the type human creates a specific object and stores it in the variable xiaoM.

👸 Xiaoyuan: Well, I see. Only with types can we create a specific object.

🐰 C: Well, then we can use this type of method through this object, because this object belongs to this type. For example, xiaom say() means to use the say() method in this type, and then xiaom Myinfo(); Of course, we can also use xiaom Name = "Xiaoming" give the value of the name attribute in this object, and then use myinfo to output. At this time, the value changes.

👸 Xiaoyuan: Well, I see. Hahaha. 😎

10 start playing pygame

🐰 Little C: let's start writing a little game.

👸 Xiaoyuan: so fast?

🐰 C: Yes, it's ready to write. First of all, we need to make preparations. We use pip command in the command window to install the game library pygame. Your computer already has pygame, so we don't need this step.

pip install pygame

👸 Xiaoyuan: Yes.

🐰 Little C: next, our first step is to introduce pygame.

import pygame

🐰 Little C: import is like your hand. Then pygame is a tool name. Connecting it is to take this tool for use.

👸 Xiaoyuan: I see.

🐰 Little C: next, we need to initialize. Initialization is just like you need to create a character to play a game. This is initialization.

import pygame

pygame.init() 
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is an airplane game")

🐰 Little C: the second init in the above code means initialization.

👸 Xiaoyuan: does the decimal point mean the init method in pygame? You can initialize it directly? 😰

🐰 C: Yes, pygame display. set_ The code of mode ((600800)) can be understood as pygame. One of the tools is called display, which has a g function of creating a window called set_mode, we're setting_ Enter the width and height of the screen in mode and use parentheses to enclose the width and height to create a screen, where 600 is the width and 800 is the height; After creating the screen, give the screen a variable, and then you can operate the screen through this variable.

👸 Xiaoyuan: it's simple and easy to understand. 😎

🐰 Little C: the next code is pyGame display. set_caption ("this is an airplane game"), set_caption is another function of display. You can set the title and directly pass the string into set as a parameter_ Caption is OK.

👸 Xiaoyuan: I see.

11 main game loop

🐰 Little C: next, we need to start the content of the main loop of the game. All games listen to what you do in the game through a loop. At this time, we can use the while loop to give a true condition. True means that the condition is always correct.

👸 Xiaoyuan: you mean you need to create a loop and always see what the player presses and does?

🐰 C: Yes, look at the code below.

import pygame

pygame.init() 
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is an airplane game")

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()

🐰 Little C: there is a for loop in the while loop to get all the events in the game. pygame.event.get() will get all the things that the player has done. Get them one by one through the for loop. The event variable will get these contents each time. Use if to judge the type of event. If it is exit QUIT in the pyGame game, execute exit() to exit the whole program.

12 game material addition

👸 Xiaoyuan: Well, can you also detect the up, down, left and right buttons? So you can move?

🐰 C: Yes, but now we need to add backgrounds and characters to the game. These are pictures. We can create backgrounds and protagonist objects by loading picture resources. We can call these elements elves.

👸 Xiaoyuan: fairy, nice name. 😢

🐰 C: look at the code below.

import pygame

bg=pygame.image.load(r'E:\2dsrc\src\img\bg.png')
hero=pygame.image.load(r'E:\2dsrc\src\img\hero1.png')
enemy=pygame.image.load(r'E:\2dsrc\src\img\enemy1.png')
enemy_boom=pygame.image.load(r'E:\2dsrc\src\img\enemy1_down1.png')
bullet=pygame.image.load(r'E:\2dsrc\src\img\bullet1.png')

heroX=250
heroY=680

pygame.init() 
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is an airplane game")

while True:
    screen.blit(bg,(0,0))
    screen.blit(hero,(heroX,heroY))
    
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()

🐰 Little C: the code above is pygame image. Load means to use the load function of the image tool in pygame. Load means to load pictures; Just pass in the path of the picture in the load method. Here I load five pictures respectively, one is the background picture, one is the protagonist picture, one is the enemy picture, one is the explosion picture after the enemy is hit, and one is the bullet picture.

👸 Xiaoyuan: do you put it under the same path on my computer?

🐰 C: Yes, if you don't have pictures, you can chat with brother bit (blogger) privately https://blog.csdn.net/A757291228 ), he will send it uniformly.

👸 Xiaoyuan: I see.

🐰 Little C: let's go on to screen blit (BG, (0,0)) code and screen blit (hero, (herox, heroy)) code. These two codes use blit method. blit method is one of the functions of screen, that is, we can draw the picture we loaded on the screen; The first parameter of blit is the picture parameter, and the second parameter is the X and Y coordinates of the whole screen, that is, where to start painting; The bigger x, the more right, and the bigger y, the more down.

👸 Xiaoyuan: then why is there a black screen after I run the code? 😭

🐰 Little C: that's because we need to refresh. We need to refresh the whole interface after each cycle, otherwise we won't show the effect of painting. You add a code at the end of the while loop, pyGame display. Update (), as shown below.

import pygame

bg=pygame.image.load(r'E:\2dsrc\src\img\bg.png')
hero=pygame.image.load(r'E:\2dsrc\src\img\hero1.png')
enemy=pygame.image.load(r'E:\2dsrc\src\img\enemy1.png')
enemy_boom=pygame.image.load(r'E:\2dsrc\src\img\enemy1_down1.png')
bullet=pygame.image.load(r'E:\2dsrc\src\img\bullet1.png')

heroX=250
heroY=680

pygame.init() 
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is an airplane game")

while True:
    screen.blit(bg,(0,0))
    screen.blit(hero,(heroX,heroY))

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()
    pygame.display.update()

👸 Xiaoyuan: come out.

13 control character movement

🐰 C: then let's control the plane to move left and right.

👸 Xiaoyuan: look forward to it.

🐰 Small C: we create a function to detect whether the user has pressed up, down, left and right.

import pygame

bg=pygame.image.load(r'E:\2dsrc\src\img\bg.png')
hero=pygame.image.load(r'E:\2dsrc\src\img\hero1.png')
enemy=pygame.image.load(r'E:\2dsrc\src\img\enemy1.png')
enemy_boom=pygame.image.load(r'E:\2dsrc\src\img\enemy1_down1.png')
bullet=pygame.image.load(r'E:\2dsrc\src\img\bullet1.png')

heroX=250
heroY=680
stepX=0 #New in this part
stepY=0 #New in this part

pygame.init() 
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is a game")


def keydown_envent(event,stepX,stepY):#New in this part
    if event.key == pygame.K_RIGHT:
        stepX=5
    elif event.key == pygame.K_LEFT:
        stepX=-5
    elif event.key == pygame.K_UP:
        stepY=-5
    elif event.key == pygame.K_DOWN:
        stepY=5
    return stepX,stepY


while True:
    heroX=heroX+stepX
    heroY=heroY+stepY
    
    screen.blit(bg,(0,0))
    screen.blit(hero,(heroX,heroY))

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()
        if event.type==pygame.KEYDOWN:#New in this part
            stepX,stepY=keydown_envent(event,stepX,stepY)
    pygame.display.update()

🐰 Small C: I added comments in the new part of the above code, mainly adding a Keydown_ The envent method is used to detect the processing after the press event. We can see that if event is used in the event traversal of the for loop type==pygame. Keydown: check whether the user presses the key, and then we pass it to Keydown through this event_ Process in the envent method to judge whether the user pressed the right key K_RIGHT, left key K_LEFT, up key K_UP, down key K_DOWN. If you right-click, you will increase the x coordinate value of the next drawing picture, and the next key will increase the y coordinate value, and so on, so there is the following code in the while loop.

heroX=heroX+stepX
heroY=heroY+stepY

👸 Xiaoyuan: I feel a little like the one who draws in the book. After turning the page number, I see the picture differently every time. The characters painted can move.

14 increase enemy aircraft

🐰 Little C: Yes, that's the principle. We then add enemies.

import pygame,random

bg=pygame.image.load(r'E:\2dsrc\src\img\bg.png')
hero=pygame.image.load(r'E:\2dsrc\src\img\hero1.png')
enemy=pygame.image.load(r'E:\2dsrc\src\img\enemy1.png')
enemy_boom=pygame.image.load(r'E:\2dsrc\src\img\enemy1_down1.png')
bullet=pygame.image.load(r'E:\2dsrc\src\img\bullet1.png')

heroX=250
heroY=680
stepX=0 
stepY=0 

enemy_speed=2#New in this part
enemy_objs=[]#New in this part

pygame.init() 
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is an airplane game")


def keydown_envent(event,stepX,stepY):
    if event.key == pygame.K_RIGHT:
        stepX=5
    elif event.key == pygame.K_LEFT:
        stepX=-5
    elif event.key == pygame.K_UP:
        stepY=-5
    elif event.key == pygame.K_DOWN:
        stepY=5
    return stepX,stepY

def enemy_show(enemy_objs,startY=-40):#New in this part
    if len(enemy_objs)<5:
        while len(enemy_objs)<5:
            enemy_X=random.randint(0,500)
            enemy_pos=[enemy_X,startY]
            screen.blit(enemy,enemy_pos)
            enemy_objs.append(enemy_pos)
    else:
        i=0
        for pos in enemy_objs:
            screen.blit(enemy,pos)
            enemy_objs[i]=[pos[0],pos[1]+enemy_speed]
            i=i+1
    return enemy_objs

while True:
    heroX=heroX+stepX
    heroY=heroY+stepY
    
    screen.blit(bg,(0,0))
    screen.blit(hero,(heroX,heroY))
    enemy_objs=enemy_show(enemy_objs)  #New in this part

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()
        if event.type==pygame.KEYDOWN:#New in this part
            stepX,stepY=keydown_envent(event,stepX,stepY)
    pygame.display.update()

🐰 Small C: an enemy is added to the above code_ Show method, enemy_ The show method passed in an enemy_ The objs list is used to record the enemy object created, enemy_ The show method receives two parameters, and the other is the default y coordinate. In enemy_ In show, if the number of enemy planes is less than 5, the while loop is directly used to create, and the X and Y values of the created object are stored in enemy_ In the objs list, we only need to control the position coordinates of each enemy aircraft to control the movement of the enemy aircraft.

if len(enemy_objs)<5:
        while len(enemy_objs)<5:
            enemy_X=random.randint(0,500)
            enemy_pos=[enemy_X,startY]
            screen.blit(enemy,enemy_pos)
            enemy_objs.append(enemy_pos)

👸 Xiaoyuan: you mean that to control the movement of the enemy aircraft, you only need to control the coordinate points in the record to draw, so it is equal to the enemy aircraft moving? 😭

🐰 C: Yes. If they only need to add the coordinates of the enemy's y axis, can they do it according to the coordinates of the enemy's y axis_ The else part of the show method.

def enemy_show(enemy_objs,startY=-40):#New in this part
    if len(enemy_objs)<5:
        while len(enemy_objs)<5:
            enemy_X=random.randint(0,500)
            enemy_pos=[enemy_X,startY]
            screen.blit(enemy,enemy_pos)
            enemy_objs.append(enemy_pos)
    else:
        i=0
        for pos in enemy_objs:
            screen.blit(enemy,pos)
            enemy_objs[i]=[pos[0],pos[1]+enemy_speed]
            i=i+1
    return enemy_objs

👸 Xiaoyuan: Well, I see. So enemy_ How much speed is the speed? I think you defined this value as 5.

🐰 C: Yes. You can run the code and try it.

👸 Xiaoyuan: the enemy plane is coming down. That's great. 😎

15 bullets

🐰 Little C: let's start adding bullets now. In fact, adding bullets is also very simple. We just need to know the position of our protagonist, and then make the bullet draw on the head of this position. After drawing, the distance after each refresh is - 10, so that the bullet can fly up.

👸 Xiaoyuan: Yes, I feel I can write. 😎

🐰 Little C: let's continue to look at the code. We set the space bar as the bullet firing button. At this time, we add the response of space event in the event method, and then draw a bullet.

import pygame,random

bg=pygame.image.load(r'E:\2dsrc\src\img\bg.png')
hero=pygame.image.load(r'E:\2dsrc\src\img\hero1.png')
enemy=pygame.image.load(r'E:\2dsrc\src\img\enemy1.png')
enemy_boom=pygame.image.load(r'E:\2dsrc\src\img\enemy1_down1.png')
bullet=pygame.image.load(r'E:\2dsrc\src\img\bullet1.png')

heroX=250
heroY=680
stepX=0 
stepY=0 
bullets_pos=[]#New in this part
enemy_speed=2
enemy_objs=[]

pygame.init() 
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is an airplane game")


def keydown_envent(event,stepX,stepY,hero_pos):
    bullet_pos=[]#New in this part 
    if event.key == pygame.K_RIGHT:
        stepX=5
    elif event.key == pygame.K_LEFT:
        stepX=-5
    elif event.key == pygame.K_UP:
        stepY=-5
    elif event.key == pygame.K_DOWN:
        stepY=5
    elif event.key == pygame.K_SPACE:#New in this part
        bullet_pos=[hero_pos[0],hero_pos[1]+10]
    return stepX,stepY,bullet_pos

def enemy_show(enemy_objs,startY=-40):
    if len(enemy_objs)<5:
        while len(enemy_objs)<5:
            enemy_X=random.randint(0,500)
            enemy_pos=[enemy_X,startY]
            screen.blit(enemy,enemy_pos)
            enemy_objs.append(enemy_pos)
    else:
        i=0
        for pos in enemy_objs:
            screen.blit(enemy,pos)
            enemy_objs[i]=[pos[0],pos[1]+enemy_speed]
            i=i+1
    return enemy_objs

while True:
    bullet_pos_=[]#New in this part
    heroX=heroX+stepX
    heroY=heroY+stepY
    
    screen.blit(bg,(0,0))
    screen.blit(hero,(heroX,heroY))
    enemy_objs=enemy_show(enemy_objs)  

    i=0
    for v in bullets_pos:#New in this part 
        bullets_pos[i]=[v[0],v[1]-10]
        screen.blit(bullet,(bullets_pos[i][0]+45,bullets_pos[i][1]))
        distance_b=[bullets_pos[i][0]+45,bullets_pos[i][1]]
        i=i+1

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()
        if event.type==pygame.KEYDOWN:#New in this part
            stepX,stepY,bullet_pos_=keydown_envent(event,stepX,stepY,[heroX,heroY])
            if len(bullet_pos_)>0:
                bullets_pos.append(bullet_pos_)
    pygame.display.update()

🐰 Small C: we have added the processing of response spaces in the method of responding to keys. We will record the target position bullet of the current protagonist_ pos=[hero_pos[0],hero_ POS [1] + 10], and then return as the return value. After returning, judge bullet_pos_ Whether the length after receiving the value is greater than 1. If it is greater than 1, it indicates that the space has been pressed, and it is recorded in bullets_pos list; Then use the loop to traverse the position of each bullet, and then subtract a value from the Y axis to launch the bullet.

i=0
for v in bullets_pos:#New in this part 
    bullets_pos[i]=[v[0],v[1]-10]
    screen.blit(bullet,(bullets_pos[i][0]+45,bullets_pos[i][1]))
    distance_b=[bullets_pos[i][0]+45,bullets_pos[i][1]]
    i=i+1

👸 Xiaoyuan: what does + 45 mean?

🐰 Small C: because our aircraft will occupy a certain width, + 45 is to keep the bullet fired in the middle of the aircraft head.

👸 Xiaoyuan: I see. My bullet came out. 😎

16 add hit destroy

🐰 Little C: let's start adding hit and destroy. Hit and destroy is actually to judge the distance between the bullet and the enemy aircraft. We can use the Euclidean distance and write a method.

def distance(bx,by,ex,ey):
    a=bx-ex
    b=by-ey
    return math.sqrt(a*a+b*b)

👸 Xiaoyuan: I don't know what to do.

🐰 C: hahaha, this problem is not the content of this article. If you don't understand the formula, you can search it, or use this method directly.

👸 Xiaoyuan: no problem.

🐰 Small C: then we add the distance calculation when the bullet moves. If the bullet is less than a certain distance from the enemy aircraft after moving, it is OK to display the explosion picture at the enemy aircraft position.

i=0
for v in bullets_pos:
    bullets_pos[i]=[v[0],v[1]-10]
    screen.blit(bullet,(bullets_pos[i][0]+45,bullets_pos[i][1]))
    distance_b=[bullets_pos[i][0]+45,bullets_pos[i][1]]
    ei=0
    for ep in enemy_objs:#New in this part 
        if distance(distance_b[0],distance_b[1],ep[0],ep[1])<60:
            screen.blit(enemy_boom,(ep[0],ep[1]))
            enemy_objs[ei]=[random.randint(0,500),-50]
        ei=ei+1
    i=i+1

🐰 Little C: actually, after moving, we cycle the position of each enemy aircraft. If the distance reaches, we will display the explosion picture at that position, and change this position to the initial position to fall again.

👸 Xiaoyuan: hahaha, OK. 😎

🐰 Little C: then we'll finish this, and we won't say anything else.

👸 Xiaoyuan: OK, thank you, little C.

🐰 Small C: the complete code is as follows (changed).

import pygame,random,math

bg=pygame.image.load(r'E:\2dsrc\src\img\bg.png')
hero=pygame.image.load(r'E:\2dsrc\src\img\hero1.png')
enemy=pygame.image.load(r'E:\2dsrc\src\img\enemy1.png')
enemy_boom=pygame.image.load(r'E:\2dsrc\src\img\enemy1_down1.png')
bullet=pygame.image.load(r'E:\2dsrc\src\img\bullet1.png')

pygame.init() #initialization
screen=pygame.display.set_mode((600,800))
pygame.display.set_caption("This is an airplane game")

heroX=250
heroY=680
stepX=0
stepY=0

enemy_speed=2
enemy_objs=[]
enemy_objs1=[]
enemy_objs2=[]
enemy_objs3=[]
bullets_pos=[]
bullet_speed=[]

def enemy_show(enemy_objs,startY=-40):
    if len(enemy_objs)<5:
        while len(enemy_objs)<5:
            enemy_X=random.randint(0,500)
            enemy_pos=[enemy_X,startY]
            screen.blit(enemy,enemy_pos)
            enemy_objs.append(enemy_pos)
    else:
        i=0
        for pos in enemy_objs:
            screen.blit(enemy,pos)
            enemy_objs[i]=[pos[0],pos[1]+enemy_speed]
            i=i+1
    return enemy_objs
    
def screen_border(X,Y):
    #Left and right screens
    if X<0:
        X=0
    elif X>500:
        X=500
    #Up and down screen
    if Y<0:
        Y=0
    elif Y>700:
        Y=700
    return X,Y

def distance(bx,by,ex,ey):
    a=bx-ex
    b=by-ey
    return math.sqrt(a*a+b*b)
    
def keydown_envent(event,stepX,stepY,hero_pos):
    bullet_pos=[]
    if event.key == pygame.K_RIGHT:
        stepX=5
    elif event.key == pygame.K_LEFT:
        stepX=-5
    elif event.key == pygame.K_UP:
        stepY=-5
    elif event.key == pygame.K_DOWN:
        stepY=5
    elif event.key == pygame.K_SPACE:
        bullet_pos=[hero_pos[0],hero_pos[1]+10]
    print('space:',bullet_pos)
    return stepX,stepY,bullet_pos
    
while True:
    bullet_pos_=[]
    heroX=heroX+stepX
    heroY=heroY+stepY
    heroX,heroY=screen_border(heroX,heroY)
    
    screen.blit(bg,(0,0))
    screen.blit(hero,(heroX,heroY))      
    enemy_objs=enemy_show(enemy_objs)   
    #enemy_objs1=enemy_show(enemy_objs1,-300)
    #enemy_objs2=enemy_show(enemy_objs2,-600)
    #enemy_objs3=enemy_show(enemy_objs3,-900)
    print(bullets_pos)
    i=0
    for v in bullets_pos:
        bullets_pos[i]=[v[0],v[1]-10]
        screen.blit(bullet,(bullets_pos[i][0]+45,bullets_pos[i][1]))
        distance_b=[bullets_pos[i][0]+45,bullets_pos[i][1]]
        ei=0
        for ep in enemy_objs:
            if distance(distance_b[0],distance_b[1],ep[0],ep[1])<60:
                print('\n\n\n\n\n\n\n\n\n\n\n\n boom')
                screen.blit(enemy_boom,(ep[0],ep[1]))
                enemy_objs[ei]=[random.randint(0,500),-50]
            ei=ei+1
        i=i+1
    
    
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()
        if event.type==pygame.KEYDOWN:
            stepX,stepY,bullet_pos_=keydown_envent(event,stepX,stepY,[heroX,heroY])
            if len(bullet_pos_)>0:
                bullets_pos.append(bullet_pos_)
      
    pygame.display.update()
    
    
    

Topics: Python Game Development pygame