Generating triangular/hexagonal coordinates (xyz)

后端 未结 5 1297
时光取名叫无心
时光取名叫无心 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:07

    This was a fun puzzle.

    O(radius2) but with (hopefully) a bit more style than Ofri's solution. It occurred to me that coordinates could be generated as though you were "walking" around the ring using a direction (move) vector, and that a turn was equivalent to shifting the zero around the move vector.

    This version also has the advantage over Eric's solution in that it never touches on invalid coordinates (Eric's rejects them, but this one never even has to test them).

    # enumerate coords in rings 1..n-1; this doesn't work for the origin
    for ring in range(1,4):
        # start in the upper right corner ...
        (x,y,z) = (0,-ring,ring)
        # ... moving clockwise (south-east, or +x,-z)
        move = [1,0,-1]         
    
        # each ring has six more coordinates than the last
        for i in range(6*ring):
            # print first to get the starting hex for this ring
            print "%d/%d: (%d,%d,%d) " % (ring,i,x,y,z)
            # then move to the next hex
            (x,y,z) = map(sum, zip((x,y,z), move))
    
            # when a coordinate has a zero in it, we're in a corner of
            # the ring, so we need to turn right
            if 0 in (x,y,z):
                # left shift the zero through the move vector for a
                # right turn
                i = move.index(0)
                (move[i-1],move[i]) = (move[i],move[i-1])
    
        print # blank line between rings
    

    Three cheers for python's sequence slicing.

提交回复
热议问题