Pygame - 给精灵添加边框

Pygame - add border to sprite

我有点困惑。我有一个继承自 pygame.sprite.Sprite class 的 class。当精灵出现在屏幕上时,我想在它周围添加一个边框,但是边框没有出现

class Bird(pygame.sprite.Sprite):
    def __init__(self, filename, x, y):
        super().__init__()
        
        self.image = pygame.image.load('bird.png')
        self.rect = self.image.get_rect(topleft = (x, y))

    def draw(self, screen):
        pygame.draw.rect(screen, red, self.rect, 2)

当我在游戏循环中调用精灵时,没有出现边框

bird_group.draw(screen)
bird_group.update()

我想我做错了什么但不确定是什么!

pygame.sprite.Group.draw does not call the draw method of the Sprite. [pygame.sprite.Group.draw() uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects — you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]

因此你必须在 image:

上绘制矩形
class Bird(pygame.sprite.Sprite):
    def __init__(self, filename, x, y):
        super().__init__()
        
        self.image = pygame.image.load('bird.png')
        self.rect = self.image.get_rect(topleft = (x, y))
        pygame.draw.rect(self.image, red, self.image.get_rect(), 2) # image.get_rect() not rect!

边框绘制在 self.image 上。它不能被删除。您必须使用 2 张图像并切换图像:

class Bird(pygame.sprite.Sprite):
    def __init__(self, filename, x, y):
        super().__init__()
        
        self.image_no_border = pygame.image.load('bird.png')
        self.image_border = self.image.copy()
        pygame.draw.rect(self.image_border, red, self.image.get_rect(), 2) 

        self.border = True
        self.image = self.image_border if self.border else self.image_no_border
        self.rect = self.image.get_rect(topleft = (x, y))

    def click(self, pos):         
        if self.rect.collidepoint(pos):
            self.border = not self.border 
            self.image = self.image_border if self.border else self.image_no_border