在六边形网格上查找相邻邻居

2022-01-18 00:00:00 python hexagonal-tiles grid tiles

问题描述

将示例地图包装在代码块中,以便格式正确.

Wrapped the example map in a code block so the formatting is correct.

好的,我正在尝试在六边形网格上编写一个极其简单的 A* 算法.我了解,并且可以做 A* 部分.事实上,我的 A* 适用于方形网格.我无法思考的是寻找带有六边形的邻居.这是 heagonal 网格的布局

Ok, I'm trying to write an extremely simple A* algorithm over a hexagonal grid. I understand, and can do the A* portion. In fact, my A* works for square grids. What I can't wrap my brain around is finding neighbors with hexagons. Here's the layout for the heagonal grid

0101     0301
    0201      0401
0102     0302
    0202      0402

等等等等

所以,我需要帮助的是编写一个 Hexagon 类,给定它的十六进制坐标,可以生成邻居列表.它需要能够生成会脱离"网格的邻居(例如 20x20 网格中的 0000 或 2101),因为这就是我的 A* 跟踪并排放置的多个地图的方式.所以可以使用这个代码片段的东西:

So, what I need help with is writing a Hexagon class that, given it's hex coordinates, can generate a list of neighbors. It needs to be able to generate neighbors which would 'fall off' the grid (like 0000 or 2101 in a 20x20 grid) because that's how my A* tracks across multiple maps laid side-by-side. So something that would work with this code snippet:

行星 = 十六进制('0214')打印(行星.邻居())['Hex 0213', 'Hex 0215', 'Hex 0115', 'Hex 0315', 'Hex 0116', 'Hex 0316']

planet = Hex('0214') print(planet.neighbors()) ['Hex 0213', 'Hex 0215', 'Hex 0115', 'Hex 0315', 'Hex 0116', 'Hex 0316']


解决方案

这取决于你如何定义你的十六进制图块的坐标.

It depends on how you define the coordinates of your hex tiles.

让我们看看.

  ,   ,   ,   ,
 /  /  /  / 
| A1| A2| A3| A4|
  /  /  /  /
  | B1| B2| B3|
 /  /  /  / 
| C1| C2| C3| C4|
  /  /  /  /
  '   '   '   '

在这种情况下,偶数行和奇数行的邻居定义是不同的.

In this case, neighbor definition is different for even and odd rows.

对于 Y 为偶数的单元格 (X,Y),邻居是:(X,Y-1),(X+1,Y-1),(X-1,Y),(X+1,Y),(X,Y+1),(X+1,Y+1)

For a cell (X,Y) where Y is even, the neighbors are: (X,Y-1),(X+1,Y-1),(X-1,Y),(X+1,Y),(X,Y+1),(X+1,Y+1)

对于 Y 为奇数的单元格 (X,Y),邻居是:(X-1,Y-1),(X,Y-1),(X-1,Y),(X+1,Y),(X-1,Y+1),(X,Y+1)

For a cell (X,Y) where Y is odd, the neighbors are: (X-1,Y-1),(X,Y-1),(X-1,Y),(X+1,Y),(X-1,Y+1),(X,Y+1)

相关文章