dictionary - Best Way to Store a Triangular/Hexagonal Grid in Python -


i'm making game hexagonal tiles, , have decided upon using triangular/hexagonal grid. found this question helped me generate coordinates, , modified code store coordinates keys in dictionary values of either "." (floor) or "x" (wall,) , included function prints out string representation of map each non-blank character represents hexagonal tile. new code:

deltas = [[1,0,-1],[0,1,-1],[-1,1,0],[-1,0,1],[0,-1,1],[1,-1,0]] class hexgrid(): def __init__(self, radius): self.radius = radius self.tiles = {(0, 0, 0): "x"} r in range(radius): = 0 b = -r c = +r j in range(6): num_of_hexas_in_edge = r in range(num_of_hexas_in_edge): = a+deltas[j][0] b = b+deltas[j][1] c = c+deltas[j][2] self.tiles[a,b,c] = "x" def show(self): l = [] y in range(20): l.append([]) x in range(60): l[y].append(".") (a,b,c), tile in self.tiles.iteritems(): l[self.radius-1-b][a-c+(2*(self.radius-1))] = self.tiles[a,b,c] mapstring = "" y in range(len(l)): x in range(len(l[y])): mapstring += l[y][x] mapstring += "\n" print(mapstring) 

with code, can generate coordinates within radius so:

import hexgrid hg = hexgrid.hexgrid(radius) 

and access coordinate this:

hg.tiles[a,b,c] 

this seems work fine now, i'm sure there must disadvantages storing map way. if there disadvantages, please point them out, , maybe present better way store map? lot time.

using array storage may save cpu time, difference neglible.

however, missed simple way of managing such map. consider rows , columns, cells have different shapes.

+--+--+--+--+--+--+--+ \/ \/ \/ \/ \/ \/ \/ row /\ /\ /\ /\ /\ /\ /\ odd row +--+--+--+--+--+--+--+ 

or hexagons:

 __ __ __ __ / \__/ \__/ \__/ \__ row \__/ \__/ a\__/ \__/ odd row / \__/ f\__/ b\__/ \__ row \__/ \__/ x\__/ \__/ odd row / \__/ e\__/ c\__/ \__ row \__/ \__/ d\__/ \__/ odd row / \__/ \__/ \__/ \__ row \__/ \__/ \__/ \__/ odd row 

then can store data regular 2d array. odd rows offset .5 right, , need figure out neighborship steps x: above: a = (0,-2), right: b = (1,-1), bottom right: c = (1,1), below: d = (0,2), bottom left: e = (0,1), top left: f = (0,-1)

if ok wasting bit of memory, can leave every other column empty, , neighborship becomes bit simpler: (0,-2), (1,-1), (1,-1), (0,-2), (-1,-1), (-1,1)


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -