在六边形网格上找到相邻的邻居

时间:2011-07-12 08:06:43

标签: python grid tiles hexagonal-tiles

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

好的,我正在尝试在六边形网格上编写一个非常简单的A *算法。我明白了,可以做A *部分。事实上,我的A *适用于方格网格。我无法包裹我的大脑是找到六边形的邻居。这是海格网格的布局

0101     0301
    0201      0401
0102     0302
    0202      0402

等等

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

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

2 个答案:

答案 0 :(得分:7)

这取决于您如何定义六角形瓷砖的坐标。

让我们看看。

  ,   ,   ,   ,
 / \ / \ / \ / \
| 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 )

答案 1 :(得分: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()