You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pygame绘制多个Sprite精灵仅首个六边形正常其余仅显背景如何解决

问题根源

你在计算六边形顶点坐标时,错误使用了全局屏幕偏移量(x,y),而pygame.draw.polygon是在精灵独立的self.image Surface上绘制,该Surface的局部坐标系原点是自身左上角,不是全局屏幕原点。
第一个六边形的偏移量为(0,0),顶点刚好落在self.image范围内,可以正常显示;后续六边形偏移量逐渐增大,顶点坐标超出了self.image的尺寸边界,多边形实际被绘制到了Surface外,因此只能看到黑色的背景填充,看不到绿色六边形。

修复方案

将顶点坐标改为基于self.image的局部坐标计算,无需添加全局偏移x、y,全局位置通过self.rect控制即可,同时建议将Surface尺寸转为整数,避免隐式转换带来的偏移误差。
修改后的Hex类代码如下:

class Hex(pygame.sprite.Sprite):
    def __init__(self, s_len, op):
        super().__init__()
        x, y = op
        root3 = 1.73205080
        self.color = (125,200,24)
        self.op = op
        self.s_len = s_len
        # 基于image左上角(0,0)计算局部顶点坐标
        self.points = [(.5 * s_len, 0),
                       (1.5 * s_len, 0),
                       (2 * s_len, (root3 / 2) * s_len),
                       (1.5 * s_len, root3 * s_len),
                       (.5 * s_len, root3 * s_len),
                       (0, (root3 / 2) * s_len)]
        # 尺寸转为整数适配pygame Surface要求
        self.image = pygame.Surface([int(2 * s_len), int(root3 * s_len)])
        self.image.fill((0,0,0))
        pygame.draw.polygon(self.image, self.color, self.points)

        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)

修改后重新运行即可看到所有斜向排列的六边形正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:36:05