Generating triangular/hexagonal coordinates (xyz)

后端 未结 5 1298
时光取名叫无心
时光取名叫无心 2020-12-02 07:50

I\'m trying to come up with an iterative function that generates xyz coordinates for a hexagonal grid. With a starting hex position (say 0,0,0 for simplicity), I want to cal

5条回答
  •  独厮守ぢ
    2020-12-02 08:10

    Another possible solution, that runs in O(radius2), unlike the O(radius4) of tehMick's solution (at the expense of a lot of style) is this:

    radius = 4
    for r in range(radius):
        print "radius %d" % r
        x = 0
        y = -r
        z = +r
        print x,y,z
        for i in range(r):
            x = x+1
            z = z-1
            print x,y,z
        for i in range(r):
            y = y+1
            z = z-1
            print x,y,z
        for i in range(r):
            x = x-1
            y = y+1
            print x,y,z
        for i in range(r):
            x = x-1
            z = z+1
            print x,y,z
        for i in range(r):
            y = y-1
            z = z+1
            print x,y,z
        for i in range(r-1):
            x = x+1
            y = y-1
            print x,y,z
    

    or written a little more concisely:

    radius = 4
    deltas = [[1,0,-1],[0,1,-1],[-1,1,0],[-1,0,1],[0,-1,1],[1,-1,0]]
    for r in range(radius):
        print "radius %d" % r
        x = 0
        y = -r
        z = +r
        print x,y,z
        for j in range(6):
            if j==5:
                num_of_hexas_in_edge = r-1
            else:
                num_of_hexas_in_edge = r
            for i in range(num_of_hexas_in_edge):
                x = x+deltas[j][0]
                y = y+deltas[j][1]
                z = z+deltas[j][2]            
                print x,y,z
    

    It's inspired by the fact the hexagons are actually on the exterior of a hexagon themselves, so you can find the coordinates of 1 of its points, and then calculate the others by moving on its 6 edges.

提交回复
热议问题