How do I draw a border around a sprite?

I use pygame and draw the map. I created the Tail class from Sprite and added all the tiles to the group to draw all at once. Now I want each tile to have a frame, but I don't understand how to do it.

Simplified example of my code:

import pygame
from pygame.rect import Rect
from pygame.sprite import Sprite, Group

# Константы
TAIL_SIZE = 80
WIN_W = 800
WIN_H = 600
TAIL_COLOR = (127, 255, 212)
BORDER_COLOR = (0, 0, 0)
MAP_SIZE = (5, 7)
FPS = 60


class Tail(Sprite):
    def __init__(self, x: int, y: int, w: int, h: int, group: Group):
        Sprite.__init__(self)
        self.color = TAIL_COLOR
        self.image = pygame.Surface((w, h))
        self.image.fill(self.color)
        self.rect = Rect(x, y, w, h)
        self.add(group)
        self.border_color = BORDER_COLOR


pygame.init()
sc = pygame.display.set_mode((WIN_W, WIN_H))
game_map = pygame.sprite.Group()
clock = pygame.time.Clock()

# Создадим карту из тайлов
y = 0
for line in range(MAP_SIZE[0]):
    x = 0
    for rect in range(MAP_SIZE[1]):
        big_x = x * TAIL_SIZE
        big_y = y * TAIL_SIZE
        Tail(x=big_x, y=big_y, w=TAIL_SIZE, h=TAIL_SIZE, group=game_map)
        x += 1
    y += 1

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

    game_map.draw(sc)
    pygame.display.update()
    clock.tick(FPS)

I can draw separate rectangles based on the number of tiles, but I can't help thinking that I could somehow just extend my Tail class so that the frame is drawn together with tile

UPD:
I tried adding the string pygame.draw.rect(self.image, self.border_color, self.rect, 1) to the Tail class. In my understanding, this would draw a frame on each image, but something went wrong and the frame is drawn only for the upper-left tile.

Author: Viktorov, 2019-07-10

1 answers

We need to change the class Tail so:

class Tail(Sprite):
    def __init__(self, x: int, y: int, w: int, h: int, group: Group):
        Sprite.__init__(self)
        self.color = TAIL_COLOR
        self.image = pygame.Surface((w, h))
        self.image.fill(self.color)
        self.rect = Rect(x, y, w, h)
        self.border = Rect(0, 0, w, h)
        self.add(group)
        self.border_color = BORDER_COLOR
        pygame.draw.rect(self.image, self.border_color, self.border, 1)

pygame.draw.rect(self.image, self.border_color, self.rect, 1) it didn't work, because self.image is the software surface on which we draw. It has a size of w by h and for all tiles except the very first one, the x and y coordinates go beyond the boundaries of this surface. According to this, the frame should always be drawn in the coordinates (0, 0). To do this, you can create a separate Rect(0, 0, w, h) and draw it.

 0
Author: Viktorov, 2019-07-11 07:42:52