2011-07-12 77 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()