2011-07-12 78 views
8

编辑:将示例映射包装在代码块中,以便格式正确。在六角形网格上找到相邻的邻居

好吧,我试图写一个非常简单的A *算法在六角网格上。我明白了,可以做A *部分。事实上,我的A *适用于方形网格。我无法环绕我的大脑是找到六边形的邻居。下面是该heagonal电网

0101  0301 
    0201  0401 
0102  0302 
    0202  0402 

等布局等

所以,我需要在写,鉴于它的十六进制坐标,可以产生邻居列表的六角类帮助。它需要能够生成“掉落”网格的邻居(比如20x20网格中的0000或2101),因为这就是我的A *如何跨多个地图并排放置。所以东西会与此代码段工作:

星球=十六进制( '0214') 打印(planet.neighbors()) [ '六角0213', '六角0215', '六角0115',“十六进制0315','十六进制0116','十六进制0316']

+0

我所提供的答案,在这里发现了同样的问题:http://stackoverflow.com/a/15524441/2135355 –

回答

6

这取决于你如何定义你的十六进制磁贴的坐标。

让我们来看看。

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

在这种情况下,偶数行和奇数行的邻居定义是不同的。 (X,Y-1),(X-1,Y),(X-1,Y-1) (X,Y),(X,Y + 1),(X + 1,Y + 1)

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

+0

好吧,我想我以下。这一次真的让我发疯,而且我一直在思考它的相当一段时间。你能看看我格式化的例子吗? – Jonathanb

+0

我看到,它非常相似,我的瓷砖是“垂直的”,你的是“水平的”,只是与Y交换X,并且认为列而不是行。 –

+0

谢谢。我现在正处于天气状况,但只要我真的把代码写好了,我会在这个答案下面发表评论,以防其他人需要类似的帮助。我只是无法摆脱概念上的障碍.... – Jonathanb

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()