根據我上面的評論,這裏是我實現的代碼。任何人都有建議來幫助我清理它,我很歡迎反饋意見。
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()
我所提供的答案,在這裏發現了同樣的問題:http://stackoverflow.com/a/15524441/2135355 –