我正在try 创建一种从本质上擦除曲面上的图形的方法.我的功能适用于包含PNG的曲面,但当我使用相同的方法删除由pygame.draw.lines()绘制的曲面时,它不会被擦除.

这两个表面之间的主要区别是一个是透明的,另一个不是.我想我可能并不完全理解PYGAME透明表面是如何工作的.

不工作undraw():

class MovementComponent(AbstactComponent):
    def __init__(self) -> None:
        super().__init__()
        game_surfaces = GameSurfaces() #singleton class that rerenders all of the surfaces in order
        self.movement_surface = game_surfaces.movement_surface
        self.path_surface = pg.Surface(self.movement_surface.get_size(), pg.SRCALPHA)
        self.path_surface.set_alpha(150)

    def draw_movement(self):
        if len(self.queue()) >= 2:
            tile_centers = []
            for tile in self.queue():
                tile_centers.append(tile.center_pixel)

            pg.draw.lines(
                self.path_surface, 
                self.character.color, 
                False, tile_centers, 3
            )
            
            self.movement_surface.blit(self.path_surface, (0,0))

    def undraw_movement(self):
        empty = pg.Color(0,0,0,0)
        self.path_surface.fill(empty)
        self.movement_surface.blit(self.path_surface, (0,0))

另一个零部件中的工作展开:

class SpriteComponent(AbstactComponent):
    NORMAL_SIZE = (55,55)

    def __init__(self, image: pg.image):
        surfaces = GameSurfaces()
        self.char_surface = surfaces.character_surface
        self.pixel_pos: (int,int) = None

        self.standard_image = pg.transform.scale(image, self.NORMAL_SIZE)
        self.empty = pg.Color(0,0,0,0)

    def draw(self, pixel_pos: (int, int)):
        self.pixel_pos = pixel_pos
        top_left_pixel = self.get_topleft_pos(pixel_pos)
        self.char_surface.blit(self.standard_image, top_left_pixel)

    def undraw(self, pixel_pos: (int, int)=None):
        pixel_pos = pixel_pos if pixel_pos else self.pixel_pos
        top_left_pixel = self.get_topleft_pos(self.pixel_pos)
        rect_to_clear = pg.Rect(top_left_pixel, self.NORMAL_SIZE)
        self.char_surface.fill(self.empty, rect_to_clear)

推荐答案

透明Surface与背景混合.但是,在删除时,您希望完全覆盖背景.因此,您必须使Surface暂时不透明再次删除.如果您使用参数None调用set_alpha,则先前设置的透明度将再次取消:

class MovementComponent(AbstactComponent):
    # [...]

    def undraw_movement(self):
        empty = pg.Color(0,0,0,0)
        self.path_surface.fill(empty)
        self.path_surface.set_alpha(None)
        self.movement_surface.blit(self.path_surface, (0,0))
        self.path_surface.set_alpha(150)

Python相关问答推荐

KNN分类器中的GridSearchCV

过滤绕轴旋转的螺旋桨

如何在PIL、Python中对图像应用彩色面膜?

是pandas.DataFrame使用方法查询后仍然排序吗?

由于瓶颈,Python代码执行太慢-寻求性能优化

如何使用上下文管理器创建类的实例?

替换字符串中的多个重叠子字符串

优化器的运行顺序影响PyTorch中的预测

为什么抓取的HTML与浏览器判断的元素不同?

如何在图中标记平均点?

如何在BeautifulSoup/CSS Select 器中处理regex?

在pandas/python中计数嵌套类别

Pandas:填充行并删除重复项,但保留不同的值

Polars map_使用多处理对UDF进行批处理

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

如何使用大量常量优化代码?

Python:从目录内的文件导入目录

如何提高Pandas DataFrame中随机列 Select 和分配的效率?

利用SCIPY沿第一轴对数组进行内插

分解polars DataFrame列而不重复其他列值