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

12 投票
2 回答
9658 浏览
提问于 2025-04-16 21:19

编辑:把示例地图放在代码块里,这样格式看起来更对。

好吧,我正在尝试在一个六边形网格上写一个非常简单的A*算法。我理解A*算法的原理,也能实现它。实际上,我的A*算法在方形网格上是可以工作的。但我搞不清楚的是,如何在六边形网格中找到邻居。下面是六边形网格的布局:

0101     0301
    0201      0401
0102     0302
    0202      0402

等等等等。

所以,我需要帮助的是写一个六边形类,这个类可以根据它的六边形坐标生成一个邻居列表。它需要能够生成那些会“掉出”网格的邻居(比如在一个20x20的网格中,像0000或2101这样的坐标),因为我的A*算法需要在多个并排的地图上进行跟踪。所以我需要一个能和下面这段代码一起工作的东西:

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

2 个回答

2

根据我上面的评论,这里是我写的代码。如果有人有建议可以帮我改进一下,我非常欢迎你们的反馈。

class Hexagon():
"""Implements a class of hexagon from a hex map which is vertically tiled.
This hexagon is able to return a list of it's neighbors. It does not care 
if the neighbors are hexes which actually exist on the map or not, the map is
responsible for determining that."""

def __init__(self,grid_number):
    self.name = grid_number
    self.x = int(grid_number[0:2])
    self.y = int(grid_number[2:4])

def neighbors(self):
    ret_list = []
    if self.x % 2 == 0:
        temp_list = [[self.x,self.y-1],
              [self.x-1,self.y],  [self.x+1,self.y],
              [self.x-1,self.y+1],[self.x+1,self.y+1],
                    [self.x,self.y+1]]
        for i in temp_list:
            ret_list.append(format(i[0],'02d') + format(i[1],'02d'))

    elif self.x % 2 == 1:
        temp_list = [[self.x,self.y-1],
              [self.x-1,self.y-1],[self.x+1,self.y-1],
              [self.x-1,self.y],[self.x+1,self.y],
                    [self.x,self.y+1]]
        for i in temp_list:
            ret_list.append(format(i[0],'02d') + format(i[1],'02d'))

    return ret_list

def main():
    hex1 = Hexagon('0201')
    hex2 = Hexagon('0302')
    if hex1.neighbors() == ['0200','0101','0301','0102','0302','0202']:
        print("Works for even columns.")
    else:
        print("Failed for even columns.")
        print(hex1.neighbors())

    if hex2.neighbors() == ['0301','0201','0401','0202','0402','0303']:
        print("Works for odd columns.")
    else:
        print("Failed for odd columns.")
        print(hex2.neighbors())

if __name__ == '__main__':
    main()
10

这要看你是怎么定义六边形瓦片的坐标的。

我们来看看。

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

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

对于一个坐标为 (X,Y) 的单元格,如果 Y 是偶数,那么它的邻居是: (X,Y-1),(X+1,Y-1),(X-1,Y),(X+1,Y),(X,Y+1),(X+1,Y+1)

而如果 Y 是奇数,那么它的邻居是: (X-1,Y-1),(X,Y-1),(X-1,Y),(X+1,Y),(X-1,Y+1),(X,Y+1)

撰写回答