Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today let’s take a look at Python’s most famous game library, PyGame. Learn two terms: Sprite and collision detection.

The letter Sprite is Sprite. Sprite is a two-dimensional graphic that can be used to make objects in games, such as characters, items, and everything else displayed in game art.

Collision detection detects whether there is a collision between two Sprites. For example, in the game to eat gold, eat beans, fight the enemy can use collision detection.

class Sprite(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([20, 20])
        self.image.fill((255, 0, 255))
        self.rect = self.image.get_rect()
        self.rect.center = pos
Copy the code

The above is the Sprite class definition. If you need more content, you can add it yourself. Or just inherit it.

pygame.init()
    clock = pygame.time.Clock()
    fps = 50
    bg = [0, 0, 0]
    size =[300, 300]
    screen = pygame.display.set_mode(size)
    player = Sprite([40, 50])
    # Define keys for player movement
    player.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN]
    player.vx = 5
    player.vy = 5

    wall = Sprite([100, 60])

    wall_group = pygame.sprite.Group()
    wall_group.add(wall)

    player_group = pygame.sprite.Group()
    player_group.add(player)

Copy the code

Initialize the game and divide the walls into wall_groups and players into player_groups. This is in preparation for collision detection.

while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
        key = pygame.key.get_pressed()
        for i in range(2):
            if key[player.move[i]]:
                player.rect.x += player.vx * [-1, 1][i]

        for i in range(2):
            if key[player.move[2:4][i]]:
                player.rect.y += player.vy * [-1, 1][i]
        screen.fill(bg)
        # first parameter takes a single sprite
        # second parameter takes sprite groups
        hit = pygame.sprite.spritecollide(player, wall_group, True)
        if hit:
        # if collision is detected call a function to destroy
            # rect
            player.image.fill((255, 255, 255))
Copy the code

The code above has key detection, such as pressing the exit key to end the game. Pressing up, down, left and right will move the Player. The pygame. Sprite. Spritecollide is collision detection function. Walls turn red when the player hits them.

The overall code is not that difficult. You are welcome to discuss procedural questions with me and answer any questions you may have. Follow the public number: poetic code, make a friend.