Lecture 17 | How to use mouse and keyboard to operate the game?

If a game cannot be operated with the mouse and keyboard, then we can only watch it as an animation.

Therefore, in a game, the operation of the mouse and keyboard is essential. Sometimes, the mouse and keyboard must be operated at the same time, such as FPS games, real-time strategy, etc. Mouse and keyboard operations need to be detected in real time in Pygame, which I mentioned in the previous section, and then we can operate the game screen.

We have two ways to detect and write keyboard events in Pygame, one is to use the event event operation, and the other is to use the keypressed function to perform keyboard judgment operations.

Let’s first try keyboard events that use events to operate. In the previous code, we have used events to determine whether to exit. Let’s look at the following code:

for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit() 

In this code, if the type of event.type is QUIT, pygame will exit. Then, by analogy, we can also write the following code in it:

if event.type == KEYDOWN:
    if event.key == pygame.K_w:
        .....

Here, we determine that the type of event is KEYDOWN, which is a keyboard press event. Then in the following code, we determine that the keyboard key value returned by the event is pygame.K_w. This K_w is the virtual keyboard defined in pygame. The key represents the key whose Key value is w on the keyboard, so as long as you press the w key, the corresponding operation will appear.

Let’s write a series of operation codes. Before writing the code, we must first define the rules.

Our purpose is to make the protagonist’s plane move. The so-called movement of the plane has been explained in the previous courses. If we want the plane to move on the screen, we need to correct the x-axis and y-axis of the plane.

Correspondingly, if the plane flies to the left, the x-axis of the plane needs to be reduced; if the plane flies to the right, the x-axis of the plane needs to be increased; if it flies upward, the y-axis of the plane needs to be decreased; if the plane flies downward, the , it is necessary to increase the y-axis of the aircraft. After we have clarified these contents first, we can write the keyboard operation code.

Let’s first correct the x-axis and y-axis of the aircraft. We need to define two variables xx and yy outside the game’s loop to correct the aircraft coordinates after keyboard operations.

xx = 0
yy = 0 

After defining these contents, let’s take a look at the definition of buttons.

if event.type == KEYDOWN:
            if event.key == pygame.K_w:
                yy -= 1
            if event.key == pygame.K_s:
                yy + = 1
            if event.key == pygame.K_a:
                xx -= 1
            if event.key == pygame.K_d:
                xx + = 1

First, like ordinary games, we use the WSAD keys on the computer keyboard as up, down, left, and right operation keys, so we determine a series of key values, such as K_w, K_s, etc., and then we see that xx, yy A series of operations, and then we perform the mapping and operations of the aircraft:

screen.blit(pln, (100 + xx, 300 + yy))

We see that the base coordinate value is (100, 300). We use keyboard operations to correct the positions of xx and yy. So far, we can see that as long as we press any button in WSAD, the aircraft will move to the specified position.

So if you think that the content of the keys ends here, you are wrong. As we said at the beginning today, there is another way to detect the keyboard class under Pygame. You can consider the following code.

key = pygame.key.get_pressed()
    if key[pygame.K_w]:
        yy -= 1
    if key[pygame.K_s]:
        yy + = 1
    if key[pygame.K_a]:
        xx -= 1
    if key[pygame.K_d]:
        xx + = 

Yes, we saw the pygame.key.get_pressed(); function. This function returns a Key value. Different from the event event, we can directly make judgments in each loop. The returned Key is a tuple type, which stores the values corresponding to various keys. If there is no button, all values are 0; if there is a button, one of the values is 1.

Let’s look at the following code. If the tuple of key value happens to be pygame.K_w, then the judgment result is true. Let’s print this content out and take a look.

print key

We printed the key and pressed the w button. Then, we can see the following output on the command line of the game interface:

?Find that 1 yet? That 1 is the corresponding K_w value. When key[pygame.K_w] is judged, a 1 is returned, which is True, then the operation of yy-=1 is generated. What follows is similar code, so I won’t repeat it again.

Seeing this, you may want to ask, there are many games that have key combinations. For example, if I press the Ctrl key and then press the w key, the corresponding operation will appear. How to implement this?

Think about it, can we write two buttons under the same judgment statement? Yes, you guessed it right, you can indeed write it like this. This is the effect of key combination.

if key[pygame.K_w] and key[pygame.K_LCTRL]:
    yy -= 2 

Here we see that as long as w and the left CTRL are pressed at the same time (LCTRL means Left Control, which means left Control), then the coordinate value of yy will be subtracted by 2, and we will know the result after one operation. . Therefore, key combinations can be connected in the same judgment using and.

Then, things don’t end here. Please write these codes on your own computer and do some experiments. The first way is event judgment, and the second way is key press judgment. What is the difference between these two methods?

See the difference? If you do what I say, you will find that in the first method, as long as you press a key, the aircraft will move one space in the specified direction. However, if you keep pressing this key, the aircraft will not move. It has to wait until you press the keyboard again. In the second method, as long as you keep pressing this button, the aircraft will keep moving to the specified position.

What exactly is the problem?

The problem is that event judgment first judges KEYDOWN. When you press the key, KEYDOWN has been judged. Then we enter the judgment of the key type of the event. However, if you keep pressing the keyboard at this time, the KEYDOWN event has not been judged. Arouse, so holding the button down has no effect, so you have to press the keyboard, release it, and press it again for the plane to move.

In the second method, in the loop, as long as the keyboard is pressed, a tuple will be returned to the key, and then the judgment will continue. Therefore, as long as we keep pressing the keyboard, judgment will be made until the pressed keyboard is Until WSAD.

Next, we have to do some mouse operations. We have also introduced the operation of the mouse in the previous courses. Let’s review it again and add some new content.

Today we are going to paste a picture at the mouse position and move it as the mouse moves. Let’s first look at the following code:

mouse = 'mouse.png'
mouse_cursor = pygame.image.load(mouse).convert_alpha()
mouse_scale = pygame.transform.scale(mouse_cursor, (40, 40))
 
While True:
    #Get x, y values
    x-= mouse_scale.get_width() / 2
    y-= mouse_scale.get_height() / 2
    screen.blit(mouse_scale, (x, y))
    ...

First we need to define an image named mouse.png, then load the image and process alpha blending, which we have explained in previous lessons.

Then we saw a function called pygame.transform.scale. The meaning of this function is that we need to rescale the mouse surface, where the scaled size length and width are (40, 40), and return a new surface.

Then in the loop, we get the center point of the surface, which is to calculate the x and y values that need to draw the mouse. We need to get the length and width of the picture and divide it by 2. Finally, blit starts mapping. The effect we see is Such.

So what if we want to determine the mouse buttons? Let’s review what we talked about last time. The mouse buttons are also judged in a similar way:

x, y = pygame.mouse.get_pos()
  if pygame.mouse.get_pressed()[0]:
      .... 

The values of x and y used in the previous code are obtained here.

We see that the pygame.mouse.get_pos() function obtains two values, x and y coordinates. The following code is to obtain the content of the mouse click. The get_pressed function subscript 0 returns whether it was a left click, and the subscript 1 returns Whether it is a middle click, subscript 2 returns whether it is a right click, and finally make a judgment.

Summary

Today’s content basically ends here. Let’s sort out and summarize the content.

The first is the judgment of keyboard events. Here there will be situations where you press the keyboard to perform operations. The problem lies in the judgment of KEYDOWN events. But if you need to determine whether the key has been pressed, you can use the get_pressed function.

Key combinations can be written under the same judgment and connected using and to make judgments.

get_pressed will return a tuple, which stores all key values. As long as you determine whether the key value is True, you will determine whether there is a key.

You can also use the get_pressed function for mouse operations, which also returns a tuple, where the subscripts 0, 1, and 2 represent the left, middle, and right buttons respectively.