Why is pygame.Surface.blit not displaying anything?

Question:

I have sone code to represent collision tests within python, using pygame Surfaces to represent what they look like:

import abc
import pygame
class Geometry(abc.ABC):
    def __init__(self, centre: tuple[int,int]):
        self.centre=centre
    @abc.abstractmethod
    def Draw(self, colour: tuple[int,int,int,int]) -> pygame.Surface:
        pass
class Line(Geometry):
    def __init__(self, start: tuple[int,int], end: tuple[int,int]):
        self.__start = start
        self.__end = end
        super().__init__(((start[0]+end[0])/2,(start[1]+end[1])/2))
    def Draw(self, colour: tuple[int,int,int,int]) -> pygame.Surface:
        sur = pygame.Surface((abs(end[0]-start[0]) or 3, abs(end[1]-start[1]) or 3), pygame.SRCALPHA)
        sur.fill(colour)
        return sur


pygame.init()
my_shape = Line((300, 300), (500, 300))
pos = tuple(my_shape.centre)
display = pygame.display.set_mode((600, 600), pygame.SRCALPHA)
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    display.fill((0, 0, 0))
    display.blit(my_shape.Draw((0, 0, 255, 0)), pos)
    pygame.display.flip()

However when runnning this code, I get a blank pygame window.

When I fill display, it works. But blitting the drawn shape onto the display does not.

Any problems with this code?

Asked By: HElpME

||

Answers:

The alpha channel of the color is 0, so the pygame.Surface is completely transparent. [blit(https://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit) blends the source Surface with the target Surface. Change the alpha channel:

display.blit(my_shape.Draw((0, 0, 255, 0)), pos)

display.blit(my_shape.Draw((0, 0, 255, 255)), pos)
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.