Pygame image transparency confusion [duplicate]

Solution 1:

If you copy a transparent Surface to another Surface the target Surface has to provide transparency respectively per pixel alpha.

You can enable additional functions when creating a new surface. Set the SRCALPHA flag to create a surface with an image format that includes a per-pixel alpha. The initial value of the pixels is (0, 0, 0, 0):

my_surface = pygame.Surface((width, height), pygame.SRCALPHA)

Use the following image

and adapt the method image_at of the class SpriteSheet. Use pygame.SRCALPHA:

class SpriteSheet:
    # [...]

    def image_at(self, rectangle, colorkey = None):
        """Load a specific image from a specific rectangle."""
        # Loads image from x, y, x+offset, y+offset.
        rect = pygame.Rect(rectangle)
        
        image = pygame.Surface(rect.size, pygame.SRCALPHA) # <----
        
        image.blit(self.sheet, (0, 0), rect)
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image

Or use convert_alpha():

class SpriteSheet:
    # [...]

    def image_at(self, rectangle, colorkey = None):
        """Load a specific image from a specific rectangle."""
        # Loads image from x, y, x+offset, y+offset.
        rect = pygame.Rect(rectangle)
        
        image = pygame.Surface(rect.size).convert_alpha() # <----
        image.fill((0, 0, 0, 0))                          # <---
        
        image.blit(self.sheet, (0, 0), rect)
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image

See also:

  • How can I make an Image with a transparent Backround in Pygame?
  • How do I blit a PNG with some transparency onto a surface in Pygame?

Note that chess pieces can also be drawn through a Unicode text.
See Displaying unicode symbols using pygame