How to create a hexagonal grid system with each grid mapped in an array and plot it?

40 Views Asked by At

I want to create a hexagonal system which can be easily plotted in python. I have consulted RedBlobGamesRedBlobGames but I really could not understand how to store it in an array form in Python. The array form is important so that I can manipulate it. Somewhat like this: Flat top hex mapping

import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
import numpy as np

coord = [[0,0,0],[0,1,-1],[-1,1,0],[-1,0,1],[0,-1,1],[1,-1,0],[1,0,-1]]
colors = [["Green"],["Blue"],["Green"],["Green"],["Red"],["Green"],["Green"]]
labels = [['yes'],['no'],['yes'],['no'],['yes'],['no'],['no']]

# Horizontal cartesian coords
hcoord = [c[0] for c in coord]

# Vertical cartersian coords
vcoord = [2. * np.sin(np.radians(60)) * (c[1] - c[2]) /3. for c in coord]

fig, ax = plt.subplots(1)
ax.set_aspect('equal')

# Add some coloured hexagons
for x, y, c, l in zip(hcoord, vcoord, colors, labels):
    color = c[0].lower()  # matplotlib understands lower case words for colours
    hex = RegularPolygon((x, y), numVertices=6, radius=2. / 3., 
                         orientation=np.radians(30), 
                         facecolor=color, alpha=0.2, edgecolor='k')
    ax.add_patch(hex)
    # Also add a text label
    ax.text(x, y+0.2, l[0], ha='center', va='center', size=20)

# Also add scatter points in hexagon centres
ax.scatter(hcoord, vcoord, c=[c[0].lower() for c in colors], alpha=0.5)

plt.show()

I found this script on StackOverflow but could not understand how to store the hex in array formats.

I have found out how to generate the tiles, but storing it is challenging. I want it in array format so that any easy implementation/image representation(in matrix format) and other algorithms(eg. Scanline algorithm) can be implemented on the array. Thanks in advance.

0

There are 0 best solutions below