“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

This series of columns will reinforce your Knowledge of Python by constantly writing games.

This column aims to sharpen your knowledge of Python while quickly mastering PyGame, so come along.

Read the code first

The following code is used to achieve keyboard control object motion, the content of the analysis class refer to the following.

import pygame

pygame.init()

w, h = 500.300
pygame.display.set_mode((w, h))

screen = pygame.display.get_surface()

Load the background image
bg = pygame.image.load("./imgs/bg.png")

# Adjust the image
bg = pygame.transform.scale(bg, (w, h))

# Load the ball
ball_img = pygame.image.load("./imgs/ball.png")

# create Sprite
ball = pygame.sprite.Sprite()
ball.image = ball_img
ball.rect = ball.image.get_rect()
ball.rect.x, ball.rect.y = w / 2, h / 2

# elves group
player_group = pygame.sprite.Group()
player_group.add(ball)

# Game on
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            quit()

        if event.type == pygame.KEYDOWN:
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT]:
                ball.rect.x -= 10
            elif keys[pygame.K_RIGHT]:
                ball.rect.x += 10
            elif keys[pygame.K_UP]:
                ball.rect.y -= 10
            elif keys[pygame.K_DOWN]:
                ball.rect.y += 10

    # Interface drawing
    screen.blit(bg, (0.0))
    player_group.draw(screen)
    pygame.display.update()
Copy the code

** Pygame.display.get_surface ()** Gets the current game window and returns a Surface object.

screen = pygame.display.set_mode((500.300))
Copy the code

bg = pygame.transform.scale(bg, (w, h))

The material pictures to zoom in, using the rapid scaling, handling of pixels is not careful, if you want to produce more smooth the image, it is recommended to use pygame. Transform. Smoothscale () function.

Pygame.image.load (“./imgs/ball.png”) is easy to understand and loads an image material.

Pygame.sprite.sprite () is the first time I encountered a very core concept of PyGame, sprites, which I will use over and over again. With sprites, there is no way to avoid Sprite diagrams, which will be covered in more detail in the next blog post, but with some basic impressions. Sprite objects use the following properties and methods:

  • self.image: Displays the picture, if set toPygame. Surface (40 [40])That means that the Sprite object is a40x40The rectangular;
  • self.image.fill([color]): color;
  • self.rect: Display location. Obtain the value before you set this parameterimageThe rectangular region of,self.rect = self.image.get_rect(), and then set it, for exampleThe self. The rect. Topleft = (0, 0)Represents the upper left corner(0, 0).topleftThe equivalent properties aretopright,bottomleft,bottomrightYou can set the angular coordinates directly, and you can go throughself.rect.top,self.rect.bottom,self.rect.right,self.rect.leftSet them separately.
  • self.update: Updates Sprite behavior.

Ball.image.get_rect () retrieves the rectangular area of the image material in the following format:

ball.rect = ball.image.get_rect()
print(ball.rect)
ball.rect.x, ball.rect.y = w / 2, h / 2
print(ball.rect)
Copy the code

Comparison of data before and after moving:

<rect(0, 0, 40, 40)>
<rect(250, 150, 40, 40)>
Copy the code

Pygame.sprite.group () Sprite class, when there are a large number of Sprite objects in the game, in order to unified management, introduced the concept of Sprite Group, first understand as a simple container can be.

Keys = pygame.key.get_pressed() retrieves the state of all the keys on the keyboard, which returns a tuple of 0,1:, if a position of 1 is pressed.

For example, printing keys yields the following result

Gets the key pressed by the keyboard, and then performs the specified action

if keys[pygame.K_LEFT]:
	ball.rect.x -= 10
elif keys[pygame.K_RIGHT]:
    ball.rect.x += 10
elif keys[pygame.K_UP]:
    ball.rect.y -= 10
elif keys[pygame.K_DOWN]:
    ball.rect.y += 10
Copy the code

Material can be arbitrarily prepared, and the final effect is to press the arrow key on the keyboard to achieve the operation of the target picture.

I hope you learned something new in this extra column series.

If you have any questions, you can contact the eraser to solve them. Let’s play games together. The amount of practice for this column is about 1 hour every day.