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| BasePath = r'C:\CJS\prj\Python\app\life'
013| 
014| ##------------------------------------------------------------------------------------------------##
015| Threads = [
016|     (0x33,0x66,0xcc), (   0,   0,   0),
017|     (0x7f,   0,   0), (0xff,   0,   0),
018|     (0xff,0x7f,   0), (0xff,0xff,   0),
019|     (0x7f,0xff,   0), (   0,0xff,   0),
020|     (   0,0xff,0x7f), (   0,0xff,0xff),
021|     (   0,0x7f,0xff), (   0,   0,0xff),
022|     (0x7f,   0,0xff), (0xff,   0,0xff),
023|     (0xff,0x7f,0xff), (0xff,0xff,0xff),
024| ]
025| 
026| ##================================================================================================##
027| def get_color_function (color_mode=0):
028|     '''Return a function that returns a color.'''
029|     match color_mode:
030|         case 1:
031|             # Cycle through the Thread colors...
032|             color = cycle(f'#{r:02x}{g:02x}{b:02x}' for r,g,b in Threads)
033|             return lambda x,y: next(color)
034|         case 2:
035|             # Generate a random color each time...
036|             return lambda x,y: f'#{randint(0,255):02x}{randint(0,255):02x}{randint(0,255):02x}'
037|         case 3:
038|             # Return Thread color indexed by column (X)...
039|             return lambda x,y: '#{0:02x}{1:02x}{2:02x}'.format(*Threads[x % len(Threads)])
040|         case 4:
041|             # Return Thread color indexed by column (Y)...
042|             return lambda x,y: '#{0:02x}{1:02x}{2:02x}'.format(*Threads[y % len(Threads)])
043| 
044|     # Always Gray...
045|     return lambda x,y: '#7f7f7f'
046| 
047| 
048| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
049| class hexpoint:
050|     '''A grid node with a grid key, XY coordinate, and (hexagon) shape.
050| 
050| Properties:
050|     key         - tuple; (row:int, col:int) key in grid dictionary
050|     xy          - tuple; (x:float, y:float) coordinates of shape in image
050|     shape       - RegularPolygon; shape from matplotlib
050|     odd_row     - int; 0=row number is even; 1=row number is odd
050|     odd_col     - int; 0=col number is even; 1=col number is odd
050|     state       - int; available for client use
050|     tag         - str; available for client use
050| '''

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

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