我正在用六角形瓷砖制作游戏,并决定使用三角形/六边形网格.我发现
this问题帮助我生成坐标,并稍微修改了代码,将所有坐标存储为字典中的键,其值为“.”. (floor)或“X”(wall,)并包括一个打印出地图的字符串表示的函数,其中每个非空白字符代表一个六边形图块.这是新代码:
deltas = [[1,-1],[0,1,[-1,0],1],-1,[1,0]] class HexGrid(): def __init__(self,radius): self.radius = radius self.tiles = {(0,0): "X"} for r in range(radius): a = 0 b = -r c = +r for j in range(6): num_of_hexas_in_edge = r for i in range(num_of_hexas_in_edge): a = a+deltas[j][0] b = b+deltas[j][1] c = c+deltas[j][2] self.tiles[a,b,c] = "X" def show(self): l = [] for y in range(20): l.append([]) for x in range(60): l[y].append(".") for (a,c),tile in self.tiles.iteritems(): l[self.radius-1-b][a-c+(2*(self.radius-1))] = self.tiles[a,c] mapString = "" for y in range(len(l)): for x in range(len(l[y])): mapString += l[y][x] mapString += "\n" print(mapString)
import hexgrid hg = hexgrid.HexGrid(radius)
并访问这样的坐标:
hg.tiles[a,c]
这似乎现在工作正常,但我确信以这种方式存储地图肯定存在一些缺点.如果有任何缺点,请指出它们,并提出更好的存储方式?非常感谢你的时间.
解决方法
使用阵列进行存储可以节省一些cpu时间,但差异可能是微不足道的.
但是,您错过了一种管理此类地图的简单方法.将其视为行和列,只是单元格的形状略有不同.
+--+--+--+--+--+--+--+ \/ \/ \/ \/ \/ \/ \/ Even row /\ /\ /\ /\ /\ /\ /\ Odd row +--+--+--+--+--+--+--+
或者对于六边形:
__ __ __ __ / \__/ \__/ \__/ \__ Even row \__/ \__/ A\__/ \__/ Odd row / \__/ F\__/ B\__/ \__ Even row \__/ \__/ X\__/ \__/ Odd row / \__/ E\__/ C\__/ \__ Even row \__/ \__/ D\__/ \__/ Odd row / \__/ \__/ \__/ \__ Even row \__/ \__/ \__/ \__/ Odd row
然后,您可以将数据存储为常规2D数组.奇数行向右偏移.5,你需要弄清楚X的邻居步骤:上面:A =(0,-2),右上:B =(1,-1),右下:C = (1,1),下:D =(0,2),左下:E =(0,左上:F =(0,-1)
如果你没有浪费一点内存,你也可以将其他列留空,并且邻居变得更简单:(0,(1,( 0,( – 1,1)