You need to enable JavaScript to run this app. pygame.Surface.blit无显示问题:代码故障排查请求
优惠活动
大模型
产品
解决方案
定价
更多

pygame.Surface.blit无显示问题:代码故障排查请求

问题分析与修复方案

核心问题1:颜色完全透明

你调用my_shape.Draw((0, 0, 255, 0))时,颜色的第四个参数(alpha通道)设为0,这会让绘制的图形完全透明,自然看不到任何内容。需要把alpha值改成255(完全不透明)或者其他非0值,比如(0, 0, 255, 255)。

核心问题2:访问未定义变量导致错误

Line类的Draw方法中直接使用了end和start,但这两个变量并没有在该方法的作用域内定义——你在__init__里定义的是私有变量self.__start和self.__end,所以这里会抛出NameError。需要把代码里的start和end替换为self.__start和self.__end:

def Draw(self, colour: tuple[int,int,int,int]) -> pygame.Surface:
    sur = pygame.Surface((abs(self.__end[0]-self.__start[0]) or 3, abs(self.__end[1]-self.__start[1]) or 3), pygame.SRCALPHA)
    sur.fill(colour)
    return sur

核心问题3:绘制逻辑错误(用矩形模拟线段)

当前的Draw方法是创建一个矩形Surface来模拟线段,这和实际的线段绘制逻辑不符:

  • 对于你测试的水平线段(300,300)到(500,300),创建的Surface宽度是200、高度是3,然后直接blit到中心位置(400,300),这会让Surface的左上角对齐(400,300),导致整个矩形向右下方偏移,线段的实际位置完全不对。
  • 正确的做法是在Surface上绘制线段,并且blit时计算偏移量,让Surface的中心对齐几何中心。

额外问题:中心坐标类型错误

在Geometry的__init__里,你计算的中心坐标是浮点数(比如(300+500)/2=400.0),而pygame的blit位置需要整数坐标,会触发警告。建议转换成整数:

super().__init__(((start[0]+end[0])//2, (start[1]+end[1])//2))
完整修复后的代码
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:
        width = abs(self.__end[0] - self.__start[0]) or 1
        height = abs(self.__end[1] - self.__start[1]) or 1
        sur = pygame.Surface((width, height), pygame.SRCALPHA)
        # 计算Surface内的线段起点和终点
        draw_start = (0, 0)
        draw_end = (width, 0) if self.__end[0] > self.__start[0] else (0, height)
        pygame.draw.line(sur, colour, draw_start, draw_end, width=2)
        return sur


pygame.init()
my_shape = Line((300, 300), (500, 300))
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))
    surface = my_shape.Draw((0, 0, 255, 255))
    # 计算正确的blit位置,让Surface中心对齐几何中心
    pos = (my_shape.centre[0] - surface.get_width()//2, my_shape.centre[1] - surface.get_height()//2)
    display.blit(surface, pos)
    pygame.display.flip()

内容的提问来源于stack exchange,提问作者HElpME

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:35:23