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

生成稳定六边形网格遇阻:Pygame与Pyglet图形畸变问题

六边形网格生成问题(Pygame/Pyglet)

Pyglet效果展示

我已尝试解决六边形网格生成问题数周,最初使用Pygame,现尝试Pyglet,但均无法生成精准网格。

以下示例中仅为演示移动网格,却发现六边形形状不一致,持续偏移变形;Pygame中该问题更为显著,至今未找到解决方案。

我的代码片段如下:

import pyglet
from pyglet import shapes

window = pyglet.window.Window(1500, 1000)
batch = pyglet.graphics.Batch()

def calc_points(size: tuple[int,int], coord: tuple[int,int]=(0,0)) -> list[tuple[float,float]]:
    b, a = size
    a, b = 1/4*a, 1/2*b
    
    x0, y0 = coord

    x1, y1 = x0+b, y0+a
    x2, y2 = x1+b, y1+a
    y3     =       y2+a
    y4     =       y3+a
    
    return [
        (x0, y1),
        (x1, y0),
        (x2, y1),
        (x2, y3),
        (x1, y4),
        (x0, y3),
        (x0, y1)
    ]

def hex_mul(size: tuple[float,float], pos: tuple[float,float]) -> tuple[float,float]:
    """given size of hexagon and position in hexagon grid, outputs real coord"""
    x, y = pos
    b, a = size
    a, b = 1/2*a, 1/2*b

    coord = (x * 2 * b + y % 2 * b,
             y * 3 / 2 * a )

    return coord

from math import sqrt

size = 20.0
border = 2.0

size = (sqrt(3)/2*size,size)
border = (sqrt(3)/2*border,border)

reduced_size = (size[0] - border[0], size[1] - border[1])

hexagons = []
p = calc_points(reduced_size)

for y in range(200):
    for x in range(200):
        coord = hex_mul(size, (x,y))
        r_coord = (coord[0] + border[0] / 2, coord[1] + border[1] / 2)

        shape = shapes.Polygon(*p, color=(180,170,160,255), batch=batch)
        shape.position = r_coord
        hexagons.append(
            shape
        )

@window.event
def on_draw():
    for s in hexagons:
        x, y = s.position
        s.position = (x+0.8, y+0.7)
    window.clear()
    batch.draw()

pyglet.app.run()

已尝试的解决方法:

  • 调整Pygame与Pyglet中六边形网格生成参数
  • 尝试多种渲染与更新技术

预期结果

我期望生成稳定的六边形网格,移动时形状一致,无畸变偏移及持续间隙,但尝试后未在任一库中实现该效果。(若可能更倾向使用Pygame,因我更熟悉它。)

Pygame中应用平方根近似后效果


内容的提问来源于stack exchange,提问作者Daniel Sýkora

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:05:26