1. 二位坐标转六边形棋盘的方式
1-1这是“波动式”的
这种就是把【方格子坐标】“左右各错开半个格子”做到的
具体来说有如下几种情况
具体到庙算平台上,是很巧妙的用一个4位整数,前两位为x、后两位为y来进行表示
附上计算距离的代码
def get_hex_distance(x1, y1, x2, y2):"""计算六边形网格中两个点之间的曼哈顿距离。假设使用奇数行偏移坐标系(odd-r offset)。"""dx = x2 - x1dy = y2 - y1return max(abs(dx), abs(dy), abs(dx + dy))
有多种计算方式的话可以用以下代码测试【可以对照着上面的图一个个格子数需要走几步】
def get_hex_distance(x1, y1, x2, y2):"""计算六边形网格中两个点之间的曼哈顿距离。假设使用奇数行偏移坐标系(odd-r offset)。"""dx = x2 - x1dy = y2 - y1return max(abs(dx), abs(dy), abs(dx + dy))def get_grid_distance(row1, col1, row2, col2): # TODO: not sure"""计算两个坐标间距离:param pos1::param pos2::return:"""'''转换为立方坐标'''q1 = col1 - (row1 - (row1 & 1)) // 2r1 = row1s1 = 0 - q1 - r1q2 = col2 - (row2 - (row2 & 1)) // 2r2 = row2s2 = 0 - q2 - r2'''输出距离为曼哈顿距离的1/2'''return (abs(q1 - q2) + abs(r1 - r2) + abs(s1 - s2)) // 2def test_hex_distance():"""测试 get_hex_distance 和 get_grid_distance 函数的正确性。"""# 测试用例:六边形网格中的点及其预期距离test_cases = [# 格式: (x1, y1, x2, y2, expected_distance)((0, 0, 0, 0), 0), # 同一个点((0, 0, 1, 0), 1), # 相邻点((0, 0, 1, 1), 2), # ((0, 0, 2, 0), 2), # 两步距离((0, 0, 2, 2), 4), # ((0, 0, 3, 0), 3), # 三步距离((0, 0, 3, 3), 6), # ((1, 1, 4, 4), 6), # ]print("Testing get_hex_distance:")for (x1, y1, x2, y2), expected in test_cases:try:result = get_hex_distance(x1, y1, x2, y2)print(f"get_hex_distance({x1}, {y1}, {x2}, {y2}) = {result}, expected = {expected}")if result != expected:raise ValueError(f"Test failed for get_hex_distance({x1}, {y1}, {x2}, {y2})")except Exception as e:print(f"Test failed: {result} {(x1, y1, x2, y2, expected, 'get_hex_distance')}")print("\nTesting get_grid_distance:")for (row1, col1, row2, col2), expected in test_cases:try:result = get_grid_distance(row1, col1, row2, col2)print(f"get_grid_distance({row1}, {col1}, {row2}, {col2}) = {result}, expected = {expected}")if result != expected:raise ValueError(f"Test failed for get_grid_distance({row1}, {col1}, {row2}, {col2})")except Exception as e:print(f"Test failed: {result} {(row1, col1, row2, col2, expected, 'get_grid_distance')}")if __name__ == "__main__":test_hex_distance()
1-2这是斜的
此外还有几种,可以看看外国Red Blob Games的博客(链接在最下方)
2.三维立方体转三维方式
用三个坐标来唯一确定一个格子,这样也更加直观,也是一种方式
参考资料:
6边形网格地图,格子间的距离计算 | indienova 独立游戏https://indienova.com/u/npc233/blogread/11298
Hexagonal Gridshttps://www.redblobgames.com/grids/hexagons/