11

编辑:将示例地图包装在代码块中,以便格式正确。

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

0101     0301
    0201      0401
0102     0302
    0202      0402

等等等等

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

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

4

2 回答 2

9

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

让我们来看看。

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

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

对于 Y 为偶数的单元格 (X,Y),邻居是:(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)

于 2011-07-12T08:22:46.510 回答
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()
于 2011-07-17T04:10:55.627 回答