hexagon-city.html


001| ####################################################################################################
002| from sys import argv, stdout
003| from os import path
004| from time import perf_counter_ns
005| from math import sqrt, pi, sin,cos
006| from random import randint
007| from itertools import cycle
008| import matplotlib.pyplot as plt
009| from matplotlib.patches import RegularPolygon
010| from goodies import KWARG
011| ####################################################################################################
012| #TODO: boundary handling? (in hexgrid)
013| BasePath = r'C:\CJS\prj\Python\app\life'
014| 
015| ##------------------------------------------------------------------------------------------------##
016| Threads = [
017|     (0x33,0x66,0xcc), (   0,   0,   0),
018|     (0x7f,   0,   0), (0xff,   0,   0),
019|     (0xff,0x7f,   0), (0xff,0xff,   0),
020|     (0x7f,0xff,   0), (   0,0xff,   0),
021|     (   0,0xff,0x7f), (   0,0xff,0xff),
022|     (   0,0x7f,0xff), (   0,   0,0xff),
023|     (0x7f,   0,0xff), (0xff,   0,0xff),
024|     (0xff,0x7f,0xff), (0xff,0xff,0xff),
025| ]
026| 
027| ##================================================================================================##
028| def get_color_function (color_mode=0):
029|     '''Return a function that returns a color.'''
030|     match color_mode:
031|         case 1:
032|             # Cycle through the Thread colors...
033|             color = cycle(f'#{r:02x}{g:02x}{b:02x}' for r,g,b in Threads)
034|             return lambda x,y: next(color)
035|         case 2:
036|             # Generate a random color each time...
037|             return lambda x,y: f'#{randint(0,255):02x}{randint(0,255):02x}{randint(0,255):02x}'
038|         case 3:
039|             # Return Thread color indexed by column (X)...
040|             return lambda x,y: '#{0:02x}{1:02x}{2:02x}'.format(*Threads[x % len(Threads)])
041|         case 4:
042|             # Return Thread color indexed by column (Y)...
043|             return lambda x,y: '#{0:02x}{1:02x}{2:02x}'.format(*Threads[y % len(Threads)])
044| 
045|     # Always Gray...
046|     return lambda x,y: '#7f7f7f'
047| 
048| 
049| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
050| class hexpoint:
051|     '''A grid node with a grid key, XY coordinate, and (hexagon) shape.
051| 
051| Properties:
051|     key         - tuple; (row:int, col:int) key in grid dictionary
051|     xy          - tuple; (x:float, y:float) coordinates of shape in image
051|     shape       - RegularPolygon; shape from matplotlib
051|     odd_row     - int; 0=row number is even; 1=row number is odd
051|     odd_col     - int; 0=col number is even; 1=col number is odd
051|     state       - int; available for client use
051|     tag         - str; available for client use
051| '''

052| 
053|     def __init__ (self, key:tuple[int,int], coords:tuple[float,float]):
054|         '''Initialize. key=(row,col) coords=(x,y)'''
055|         self.key = key
056|         self.xy = coords
057|         self.shape = None
058|         self.odd_row = key[1] & 1
059|         self.odd_col = key[0] & 1
060|         self.state = 0
061|         self.tag = ''
062| 
063|     def __repr__ (self):
064|         return f'[{self.key[0]},{self.key[1]}]: ({self.xy[0]:.3f}, {self.xy[0]:.3f})'
065| 
066| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
067| class hexpoint0 (hexpoint):
068|     '''HexPoint neighbor directions for horizontal orientation.'''
069| 
070|     #TODO:ATTN: These need limits or to wrap around...
071|     @property
072|     def left_up (self):
073|         '''Key of immediate neighbor to upper left.'''
074|         x = self.key[0] if self.odd_row else self.key[0] - 1
075|         y = self.key[1] + 1
076|         return (x, y)
077| 
078|     @property
079|     def right_up (self):
080|         '''Key of immediate neighbor to upper right.'''
081|         x = self.key[0] + 1 if self.odd_row else self.key[0]
082|         y = self.key[1] + 1
083|         return (x, y)
084| 
085|     @property
086|     def left (self):
087|         '''Key of immediate neighbor to left.'''
088|         x = self.key[0] - 1
089|         y = self.key[1]
090|         return (x, y)
091| 
092|     @property
093|     def right (self):
094|         '''Key of immediate neighbor to right.'''
095|         x = self.key[0] + 1
096|         y = self.key[1]
097|         return (x, y)
098| 
099|     @property
100|     def left_down (self):
101|         '''Key of immediate neighbor to lower left.'''
102|         x = self.key[0] if self.odd_row else self.key[0] - 1
103|         y = self.key[1] - 1
104|         return (x, y)
105| 
106|     @property
107|     def right_down (self):
108|         '''Key of immediate neighbor to lower left.'''
109|         x = self.key[0] + 1 if self.odd_row else self.key[0]
110|         y = self.key[1] - 1
111|         return (x, y)
112| 
113| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
114| class hexpoint1 (hexpoint):
115|     '''HexPoint neighbor directions for vertical orientation.'''
116| 
117|     #TODO:ATTN: These need limits or to wrap around...
118|     @property
119|     def left_up (self):
120|         '''Key of immediate neighbor to upper left.'''
121|         x = self.key[0] - 1
122|         y = self.key[1] + 1 if self.odd_col else self.key[1]
123|         return (x, y)
124| 
125|     @property
126|     def left_down (self):
127|         '''Key of immediate neighbor to lower left.'''
128|         x = self.key[0] - 1
129|         y = self.key[1] if self.odd_col else self.key[1] - 1
130|         return (x, y)
131| 
132|     @property
133|     def above (self):
134|         '''Key of immediate neighbor above.'''
135|         x = self.key[0]
136|         y = self.key[1] + 1
137|         return (x, y)
138| 
139|     @property
140|     def below (self):
141|         '''Key of immediate neighbor below.'''
142|         x = self.key[0]
143|         y = self.key[1] - 1
144|         return (x, y)
145| 
146|     @property
147|     def right_up (self):
148|         '''Key of immediate neighbor to upper right.'''
149|         x = self.key[0] + 1
150|         y = self.key[1] + 1 if self.odd_col else self.key[1]
151|         return (x, y)
152| 
153|     @property
154|     def right_down (self):
155|         '''Key of immediate neighbor to lower right.'''
156|         x = self.key[0] + 1
157|         y = self.key[1] if self.odd_col else self.key[1] - 1
158|         return (x, y)
159| 
160| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
161| class hexgrid:
162|     '''Hex Grid class.
162| 
162| Uses Matplotlib to create a grid of hexagonal cells packed in honeycomb form.
162| The cells can be oriented "horizontally" (the default) or "vertically". The
162| orientation determines which (rows or cols) appears visually straight.
162| 
162| An instance includes a grid [dict with (row,col) keys] of hexpoint objects.
162| Each hexpoint has six properties giving the keys of its six neighbors.
162| The six directions depend on hexagon orientation. Four diagonals are always
162| present: left-up, right-up, left-down, right-down. In horizontal mode, the
162| other two are left and right. In vertical mode, they are above and below.
162| 
162| Each hexpoint has its hexagon patch, which provides access to shape properties.
162| 
162| Properties:
162|     grid            - dict; collection of points; uses (r,c) keys
162|     orient          - int; 0=horizontal; 1=vertical
162|     radius          - float; from hexagon center to any point
162|     color           - str; hexagon (initial) color
162|     bgcolor         - str; background color
162|     colorfunc       - int; color function id
162|     bordercolor     - str; hexagon border color
162|     borderwidth     - int; hexagon border width
162|     xsize           - int; number of cells horizontally  (# of columns!)
162|     ysize           - int; number of cells vertically    (# of rows!)
162|     dx              - float; horizontal distance between centers*
162|     dy              - float; vertical distance between centers*
162|     angle           - float; angle of hexagon (in radians)*
162|                       (* no keyword parameter)
162| '''

163|     def __init__ (self, **props):
164|         '''Initialize Hex City parameters.'''
165|         self.grid = {}
166|         self.orient = KWARG('orient', 0, int, props)
167|         self.radius = KWARG('radius', 1.0, float, props)
168|         self.xdim = KWARG('xdim', 8.00, float, props)
169|         self.ydim = KWARG('ydim', 5.00, float, props)
170|         self.color = KWARG('color', '#7f7f7f', str, props)
171|         self.bgcolor = KWARG('bgcolor', '#bfbfbf', str, props)
172|         self.colorfunc = KWARG('colorfunc', 0, int, props)
173|         self.bordercolor = KWARG('bordercolor', '#000000', str, props)
174|         self.borderwidth = KWARG('borderwidth', 1.0, float, props)
175|         # Properties that depend on orientation...
176|         if self.orient:
177|             self.xsize = KWARG('xsize', 27, int, props)
178|             self.ysize = KWARG('ysize', 13, int, props)
179|             self.dx = self.radius * 1.5
180|             self.dy = self.radius * sqrt(3)
181|             self.angle = pi/6
182|         else:
183|             self.xsize = KWARG('xsize', 24, int, props)
184|             self.ysize = KWARG('ysize', 15, int, props)
185|             self.dx = self.radius * sqrt(3)
186|             self.dy = self.radius * 1.5
187|             self.angle = 0.0
188|         # Generate the grid...
189|         self._make_grid()
190|         self._make_board()
191| 
192|     def save (self, fname, fpath=BasePath):
193|         '''Save the board to a PNG image file.'''
194|         fn = path.join(fpath,fname) if fpath else fname
195|         self.fig.savefig(fn)
196|         print(f'wrote: {fn}')
197| 
198|     @property
199|     def dims (self): return (self.xdim, self.ydim)
200| 
201|     @property
202|     def size (self): return (self.xsize, self.ysize)
203| 
204|     def __len__ (self): return len(self.grid)
205| 
206|     def __iter__ (self): return iter(self.grid)
207| 
208|     def __getitem__ (self, key):
209|         '''Get item from grid via its (r,c) key.'''
210|         if key in self.grid:
211|             return self.grid[key]
212|         return None
213| 
214|     def __setitem__ (self, key, value):
215|         raise NotImplementedError("Sorry! Not allowed to set grid hexpoints.")
216| 
217|     def __delitem__ (self, key):
218|         raise NotImplementedError("Sorry! Not allowed to delete grid hexpoints.")
219| 
220|     def __repr__ (self):
221|         '''Show ourself.'''
222|         return f'<{type(self).__name__} {self.xsize}x{self.ysize} [{self.orient}] {id(self):08x}>'
223| 
224|     def _make_grid (self):
225|         '''Generate the row-column grid.'''
226|         self.grid.clear()
227|         if self.orient:
228|             # For columns...
229|             for xx in range(self.xsize):
230|                 odd_col = xx & 1
231|                 # For cells in column...
232|                 for yy in range(self.ysize - odd_col):
233|                     # Key is the rectangular grid (row,col) pair...
234|                     key = (xx, yy)
235| 
236|                     # Shift odd cols downwards...
237|                     my = (self.dy/2.0) if odd_col else 0.0
238|                     xy = ((self.dx * xx), my + (self.dy * yy))
239| 
240|                     # Add hexpoint (to grid)...
241|                     self.grid[key] = hexpoint1(key, xy)
242|         else:
243|             # For rows...
244|             for yy in range(self.ysize):
245|                 odd_row = yy & 1
246|                 # For cells in row...
247|                 for xx in range(self.xsize - odd_row):
248|                     # Key is the rectangular grid (row,col) pair...
249|                     key = (xx, yy)
250| 
251|                     # Shift odd rows to the right...
252|                     mx = (self.dx/2.0) if odd_row else 0.0
253|                     xy = (mx + (self.dx * xx), (self.dy * yy))
254| 
255|                     # Add hexpoint (to grid)...
256|                     self.grid[key] = hexpoint0(key, xy)
257| 
258|     def _make_board (self):
259|         '''Generate the Matplotlib "Axis" image.'''
260|         # Hexagon patch properties...
261|         patch_props = dict(
262|             numVertices=6,
263|             radius=self.radius,
264|             orientation=self.angle,
265|             linewidth=self.borderwidth,
266|             edgecolor=self.bordercolor,
267|         )
268|         # Board coloring function...
269|         color_function = get_color_function(self.colorfunc)
270| 
271|         # Create a Matplotlib figure and axis plot...
272|         self.fig, self.ax = plt.subplots()
273|         self.fig.set_figwidth(self.xdim)
274|         self.fig.set_figheight(self.ydim)
275|         self.fig.suptitle('Hexagon City')
276|         self.fig.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0)
277|         self.fig.patch.set_facecolor(self.bgcolor)
278| 
279|         self.ax.set_aspect('equal')
280|         self.ax.axis('off')
281|         self.ax.set_xlim(-self.dx, self.dx*self.xsize)
282|         self.ax.set_ylim(-self.dy, self.dy*self.ysize)
283| 
284|         # For each point in the grid...
285|         for point in self.grid.values():
286|             # Create a hexagon patch...
287|             point.shape = RegularPolygon(point.xy, **patch_props)
288| 
289|             # Set its color...
290|             point.shape.set_facecolor(color_function(*point.key))
291| 
292|             # Add it to the plot...
293|             self.ax.add_patch(point.shape)
294| 
295| 
296| ##================================================================================================##
297| def do_array_of_cols (fname='hexagon-cols.png', fpath=BasePath):
298|     '''Special: Create a field of hexagons - color cols.'''
299|     # Create hexagons (vertical orientation, column coloring function)...
300|     HexCity = hexgrid(orient=1, colorfunc=3)
301| 
302|     # Save the image...
303|     HexCity.save(fname=fname, fpath=fpath)
304| 
305|     return HexCity
306| 
307| ##================================================================================================##
308| def do_array_of_rows (fname='hexagon-rows.png', fpath=BasePath):
309|     '''Special: Create a field of hexagons - color rows.'''
310|     # Create hexagons (horizontal orientation, row coloring function)...
311|     HexCity = hexgrid(orient=0, colorfunc=4)
312| 
313|     # Save the image...
314|     HexCity.save(fname=fname, fpath=fpath)
315| 
316|     return HexCity
317| 
318| ##================================================================================================##
319| def make_ray (hg:hexgrid, gx:hexpoint, dfunc:property, steps:int=3) -> list:
320|     # Start with given cell...
321|     ray = [gx]
322|     # Take three steps...
323|     for _ in range(steps):
324|         # Get the neighbor's key...
325|         k = dfunc.fget(ray[-1])
326|         # Append it to the ray
327|         ray.append(hg.grid[k])
328|     return ray[1:]
329| 
330| ##================================================================================================##
331| def color_ray (gs:list, color:str) -> None:
332|     # Ray 1; bold color...
333|     gs[0].shape.set_facecolor(color)
334|     # Ray 2; medium color...
335|     color = color.replace('ff','cc')
336|     gs[1].shape.set_facecolor(color)
337|     # Ray 3; faint color...
338|     color = color.replace('cc','66')
339|     gs[2].shape.set_facecolor(color)
340| 
341| ##================================================================================================##
342| def do_horizontal_demo (fname='hexagon-city-h.png', fpath=BasePath):
343|     '''Demo hexagon grid - Horizontal orientation.'''
344| 
345|     # Create hexagons (horizontal orientation, gray cells)...
346|     HexCity = hexgrid(orient=0, colorfunc=0)
347| 
348|     # Demo access by grid key...
349|     HexCity[(12,6)].shape.set_facecolor('red')
350|     HexCity[(12,7)].shape.set_facecolor('yellow')
351|     HexCity[(13,8)].shape.set_facecolor('yellow')
352|     HexCity[(14,8)].shape.set_facecolor('yellow')
353|     HexCity[(15,8)].shape.set_facecolor('yellow')
354|     HexCity[(16,8)].shape.set_facecolor('yellow')
355|     HexCity[(17,8)].shape.set_facecolor('yellow')
356|     HexCity[(17,9)].shape.set_facecolor('yellow')
357|     HexCity[(18,10)].shape.set_facecolor('white')
358| 
359|     # Demo access through neighbors...
360|     g0 = HexCity[(4,5)]
361|     g0.shape.set_facecolor('#ffffff')
362| 
363|     g1s = make_ray(HexCity, g0, hexpoint0.left_up)
364|     g2s = make_ray(HexCity, g0, hexpoint0.right_up)
365|     g3s = make_ray(HexCity, g0, hexpoint0.right)
366|     g4s = make_ray(HexCity, g0, hexpoint0.right_down)
367|     g5s = make_ray(HexCity, g0, hexpoint0.left_down)
368|     g6s = make_ray(HexCity, g0, hexpoint0.left)
369| 
370|     color_ray(g1s, '#ff0000')
371|     color_ray(g2s, '#ffff00')
372|     color_ray(g3s, '#00ff00')
373|     color_ray(g4s, '#00ffff')
374|     color_ray(g5s, '#0000ff')
375|     color_ray(g6s, '#ff00ff')
376| 
377|     # Save the image...
378|     HexCity.save(fname=fname)
379| 
380|     return HexCity
381| 
382| ##================================================================================================##
383| def do_vertical_demo (fname='hexagon-city-v.png', fpath=BasePath):
384|     '''Demo hexagon grid - Vertical orientation.'''
385| 
386|     # Create hexagons (vertical orientation, gray cells)...
387|     HexCity = hexgrid(orient=1, colorfunc=0)
388| 
389|     # Demo access by grid key...
390|     HexCity[(14,4)].shape.set_facecolor('red')
391|     HexCity[(15,4)].shape.set_facecolor('yellow')
392|     HexCity[(16,5)].shape.set_facecolor('yellow')
393|     HexCity[(16,6)].shape.set_facecolor('yellow')
394|     HexCity[(16,7)].shape.set_facecolor('yellow')
395|     HexCity[(16,8)].shape.set_facecolor('yellow')
396|     HexCity[(16,9)].shape.set_facecolor('yellow')
397|     HexCity[(17,9)].shape.set_facecolor('yellow')
398|     HexCity[(18,10)].shape.set_facecolor('white')
399| 
400|     # Demo access through neighbors...
401|     g0 = HexCity[(4,5)]
402|     g0.shape.set_facecolor('#ffffff')
403| 
404|     g1s = make_ray(HexCity, g0, hexpoint1.left_up)
405|     g2s = make_ray(HexCity, g0, hexpoint1.above)
406|     g3s = make_ray(HexCity, g0, hexpoint1.right_up)
407|     g4s = make_ray(HexCity, g0, hexpoint1.right_down)
408|     g5s = make_ray(HexCity, g0, hexpoint1.below)
409|     g6s = make_ray(HexCity, g0, hexpoint1.left_down)
410| 
411|     color_ray(g1s, '#ff0000')
412|     color_ray(g2s, '#ffff00')
413|     color_ray(g3s, '#00ff00')
414|     color_ray(g4s, '#00ffff')
415|     color_ray(g5s, '#0000ff')
416|     color_ray(g6s, '#ff00ff')
417| 
418|     # Save the image...
419|     HexCity.save(fname=fname, fpath=fpath)
420| 
421|     return HexCity
422| 
423| ##================================================================================================##
424| def do_create_image (orient=0, colorfunc=0, fname='hexagon-city.png', fpath=BasePath):
425|     '''Create a playing field of hexagons.'''
426|     HexCity = hexgrid(orient=orient, colorfunc=colorfunc)
427| 
428|     # Save the image...
429|     HexCity.save(fname=fname, fpath=fpath)
430| 
431|     return HexCity
432| 
433| ##================================================================================================##
434| def main (command, *args):
435|     print(f'command: {command}')
436| 
437|     if command == 'main': return do_create_image(colorfunc=0)
438|     if command == 'show': return do_create_image(colorfunc=1, fname='hexagon-show.png')
439|     if command == 'rand': return do_create_image(colorfunc=2, fname='hexagon-random.png')
440| 
441|     if command == 'rows': return do_array_of_rows()
442|     if command == 'cols': return do_array_of_cols()
443| 
444|     if command == 'horz': return do_horizontal_demo()
445|     if command == 'vert': return do_vertical_demo()
446| 
447|     return hexgrid()
448| ####################################################################################################
449| if __name__ == '__main__':
450|     print(argv[0])
451|     cmnd = argv[1] if 1 < len(argv) else ''
452|     args = argv[2:]
453|     print()
454|     rv = main(cmnd, *args)
455|     print()
456|     print(f'{rv!s}')
457|     print()
458| ####################################################################################################
459| '''eof'''
460|