Coordinates of the edges of a honeycomb grid in python

579 Views Asked by At

I was sitting the whole day, trying to solve this problem. First, I will show you, what kind of pattern I am trying to get:

enter image description here

As you can see, I am tryig to get the coordinates of the corners of all the hexagons in the whole rectangle, respectively the red circles (I guess, you can see, where I tried going without me marking all of them). The distance from grey line to grey line equals one and a hexagon as a diameter of 3. I already tried with the following code to get at least the pattern of the red circles without limiting them to the rectangle:

x_start = 0
y_start = 0
width = 9
height = 9

#here I catch all the neighbours of one position I guess

def positions(x_start, y_start, width, height):
    positions_list = []
    
    for x in range(x_start, width + 1):
        for y in range(y_start, height + 1):
            positions_list +=[(x_start - 1, y_start),
                              (x_start - 1/2, y_start - 1),
                              (x_start + 1/2, y_start - 1),
                              (x_start + 1, y_start),
                              (x_start + 1/2, y_start + 1),
                              (x_start - 1/2, y_start + 1)]
            x_start += 1
            y_start += 1
    return positions_list
    print(positions_list)

positions(x_start, y_start, width, height)

But how do I change my code in order to get all coordinates in the rectangle? Preferably as a list like

[(0,0), (0.5, 1), (0, 1), ...]

Alternatively, I tried this:

import numpy

def positions(x_start, y_start, width, height):
    position_list = []
    
    for x in numpy.arange(x_start, width + 0.1, 0.5):
        for y1 in range(0, height+1, 2):
            position_list += [(x_start, y_start)                         ]
        for y2 in range(1, height+1, 2): 
            position_list += [(x_start, y_start)
    return positions_list
    print(positions_list)

positions(x_start, y_start, width, height)

But I did got no output. I hope my question is understandable. I am quite desperate.

With kind regards :)

1

There are 1 best solutions below

0
metz_lisa On

Someone else found a way for me to do it more elegantly:

def positions(w,h):
    poss = []
    for y in range(0,h+1):
        if y%2 == 0:
            poss = [(x,y) for x in range(0,w+1)] + poss
        else:
            x = 0.5
            while x<=w:
                poss = [(x,y)] + poss
                x = x+1
    return poss


print(positions(5,5))