maze_1.html


001| '''\
001| Python Maze Maker.
001| 
001| Experimenting with computer maze generation.
001| Maze model splits doors into North/South and West/East arrays.
001| 
001|       0   1   2   3   4   5   6   7
001|     +---+---+---+---+---+---+---+---+
001|    0|   #   #   #   #   #   #   #   |
001|     +-@-+-@-+-@-+-@-+-@-+-@-+-@-+-@-+  @ n/s door
001|    1|   #   #   # X #   #   #   #   |
001|     +-@-+-@-+-@-+-@-+-@-+-@-+-@-+-@-+
001|    2|   #   #   #   #   #   #   #   |  # e/w door
001|     +-@-+-@-+-@-+-@-+-@-+-@-+-@-+-@-+
001|    3|   #   #   #   #   #   #   #   |
001|     +---+---+---+---+---+---+---+---+
001| 
001|     Cells    = [4,8]     X   = [1,3]
001|     NS Doors = [3,8]     N/S = [0,3] / [1,3]
001|     WE Doors = [4,7]     W/E = [1,2] / [1,3]
001| 
001| Coder@Sonnack.com
001| November 2013
001| '''

002| ####################################################################################################
003| from sys import argv, stderr
004| from random import random, shuffle
005| from PIL import Image, ImageDraw
006| from logger import logger, trace
007| from colors import *
008| ####################################################################################################
009| Log = logger('MazeMaker1')
010| 
011| NumberCols = 12
012| NumberRows = 10
013| 
014| RandomWall = lambda f: random() < f
015| 
016| DirectionString = ['North', 'East', 'South', 'West']
017| DirectionAbbrev = ['N', 'E', 'S', 'W']
018| 
019| ShowImageBeforeSave = False
020| 
021| 
022| ##------------------------------------------------------------------------------------------------##
023| class RandomWalk1 (object):
024|     max_steps   = 100   # max steps allows for a given path
025|     wall_change = 0.1   # probability of NOT changing direction when hitting wall
026|     occu_change = 0.1   # probability of NOT changing direction when hitting an occupied cell
027|     dir_change  = 1     ##TODO: this obviously needs rethinking
028| 
029|     def __init__ (self, mz):
030|         self.mz = mz
031|         self.row = 0
032|         self.col = 0
033|         self.direction = 2  # N,E,S,W
034|         self.tot_steps = 0
035|         self.dir_steps = 0
036|         self.path_list = []
037| 
038|     def carve_a_path (self, path_color):
039|         Log.debug()
040|         Log.debug('NEW PATH...')
041| 
042|         if 0 < len(self.path_list):
043|             if not self.find_a_path():
044|                 return
045|             Log.debug('using: (%d, %d)' % (self.row, self.col))
046| 
047|         # loop while forging a path...
048|         self.tot_steps = 0
049|         self.dir_steps = 0
050|         current_path = []
051|         while self.tot_steps < self.max_steps:
052|             s = DirectionAbbrev[self.direction]
053|             t = (self.tot_steps, self.dir_steps, s, self.row, self.col)
054|             Log.debug('STEP: %d (%d:%s) [%d, %d]' % t)
055|             current_path.append([self.row, self.col, 2])
056| 
057|             # test next cell...
058|             tc = self.test_cell[self.direction](self)
059|             if tc < 0:
060|                 # hit a wall...
061|                 Log.trace('Hit the wall!')
062|                 if self.wall_change < random():
063|                     if self.change_direction():
064|                         continue
065|                 break
066|             if 0 < tc:
067|                 # hit a traveled cell...
068|                 Log.trace('Hit another path!')
069|                 if self.occu_change < random():
070|                     if self.change_direction():
071|                         continue
072|                 break
073| 
074|             # next cell isn't occupied, knock down the wall and go there...
075|             self.move_to_next_cell[self.direction](self)
076|             # tag new cell...
077|             self.mz.set_cell(self.row,self.col, path_color)
078| 
079|             # increment counters...
080|             self.tot_steps = self.tot_steps + 1
081|             self.dir_steps = self.dir_steps + 1
082| 
083|             # consider a change of direction...
084|             if self.dir_change < (random() * self.dir_steps):
085|                 if self.change_direction():
086|                     self.dir_steps = 0
087| 
088|         # add path to pat list...
089|         self.path_list.append(current_path)
090| 
091|     def find_a_path (self):
092|         '''Travel existing paths to find a new row,col and direction.'''
093| 
094|         # create a random order to try paths from the path list...
095|         maze_path_seq = [x for x in range(len(self.path_list))]
096|         shuffle(maze_path_seq)
097|         # pick a maze path (from the random list)...
098|         for mx,maze_path in map(lambda ix: (ix, self.path_list[ix]), maze_path_seq):
099|             Log.trace('MazePath: %d (%d cells)' % (mx, len(maze_path)))
100| 
101|             # create a ramdom order to try cells from the maze path...
102|             maze_cell_seq = [x for x in range(len(maze_path))]
103|             shuffle(maze_cell_seq)
104|             # pick a maze cell (from the random list)...
105|             for cx,path_cell in map(lambda ix: (ix,maze_path[ix]), maze_cell_seq):
106|                 Log.trace('PathCell: %d [%d,%d (%d)]' % (cx, path_cell[0], path_cell[1], path_cell[2]))
107| 
108|                 # test the cell for a possible branch...
109|                 if path_cell[2] < 4:
110|                     self.row = path_cell[0]
111|                     self.col = path_cell[1]
112|                     Log.trace('testing: (%d, %d)' % (self.row, self.col))
113|                     if self.test_north_cell() == 0:
114|                         self.direction = 0
115|                         path_cell[2] = path_cell[2] + 1
116|                         return True
117|                     if self.test_east_cell() == 0:
118|                         self.direction = 1
119|                         path_cell[2] = path_cell[2] + 1
120|                         return True
121|                     if self.test_south_cell() == 0:
122|                         self.direction = 2
123|                         path_cell[2] = path_cell[2] + 1
124|                         return True
125|                     if self.test_west_cell() == 0:
126|                         self.direction = 3
127|                         path_cell[2] = path_cell[2] + 1
128|                         return True
129| 
130|         Log.debug('Unable to find a path!')
131|         return False
132| 
133|     def change_direction (self):
134|         if random() < 0.5:
135|             # try turning left...
136|             d = (self.direction - 1) % 4
137|             if self.test_cell[d](self):
138|                 # can't, try right...
139|                 d = (self.direction + 1) % 4
140|                 if self.test_cell[d](self):
141|                     # nope!
142|                     return False
143|             # cell is clear, this is good...
144|             Log.debug('NEW DIRECTION: %d' % d)
145|             self.direction = d
146|         else:
147|             # try turning right...
148|             d = (self.direction + 1) % 4
149|             if self.test_cell[d](self):
150|                 # can't, try left...
151|                 d = (self.direction - 1) % 4
152|                 if self.test_cell[d](self):
153|                     # nope!
154|                     return False
155|             # cell is clear, this is good...
156|             Log.debug('NEW DIRECTION: %d' % d)
157|             self.direction = d
158|         return True
159| 
160|     def test_north_cell (self):
161|         # special north edge test...
162|         if self.row == 0:
163|             return -1
164|         return self.mz.get_cell(self.row-1, self.col)
165| 
166|     def test_south_cell (self):
167|         if self.row == (NumberRows - 1):
168|         # special south edge test...
169|             return -1
170|         return self.mz.get_cell(self.row+1, self.col)
171| 
172|     def test_west_cell (self):
173|         # special west edge test...
174|         if self.col == 0:
175|             return -1
176|         return self.mz.get_cell(self.row, self.col-1)
177| 
178|     def test_east_cell (self):
179|         # special east edge test...
180|         if self.col == (NumberCols - 1):
181|             return -1
182|         return self.mz.get_cell(self.row, self.col+1)
183| 
184|     def move_to_north_cell (self):
185|         # knock down the wall...
186|         self.mz.set_north_door(self.row, self.col, 0)
187|         self.row = self.row - 1
188| 
189|     def move_to_south_cell (self):
190|         # knock down the wall...
191|         self.mz.set_south_door(self.row, self.col, 0)
192|         self.row = self.row + 1
193| 
194|     def move_to_west_cell (self):
195|         # knock down the wall...
196|         self.mz.set_west_door(self.row, self.col, 0)
197|         self.col = self.col - 1
198| 
199|     def move_to_east_cell (self):
200|         # knock down the wall...
201|         self.mz.set_east_door(self.row, self.col, 0)
202|         self.col = self.col + 1
203| 
204|     test_cell = [test_north_cell, test_east_cell, test_south_cell, test_west_cell]
205| 
206|     move_to_next_cell = [move_to_north_cell, move_to_east_cell, move_to_south_cell, move_to_west_cell]
207| 
208| 
209| 
210| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
211| class Maze (object):
212|     '''\
212| Maze class.
212| The maze is stored as three two-dimensional arrays:
212| 
212|     cells     - stores the state of the maze cell
212|     ns_doors  - stores the state of the north and south doors
212|     we_doors  - stores the state of the west and east doors
212| 
212| All data values are integers.  Array[row][col]: each row is an array of cols.
212| 
212| A cell non-zero cell value indicates some non-default status.
212| A non-zero value for a door means the door is closed (locked).
212| The value -1 indicates a maze outer wall, values above 0 indicate a locked state.
212| (The potential exists for multiple locked states; e.g. closed, closed+locked.)
212| 
212| The NS_Doors array has one less row -- no south-edge doors.
212| The WE_Doors array has one less column -- no east-edge doors.
212| 
212| There are no west-edge or north-edge doors, either, but the Doors arrays can
212| be thought of as EastDoors and SouthDoors arrays; except for the eastern and
212| southern edges, all cells have an east and south door. The west and north
212| doors are the east and south doors of the west and north cells, respectively.
212| 
212| For a given cell(row,col), the doors to that cell are:
212| 
212|     north door = NS_Doors(row-1, col  )  {{south door of north cell}}
212|     south door = NS_Doors(row  , col  )
212|     west door  = WE_Doors(row  , col-1)  {{east door of west cell}}
212|     east door  = WE_Doors(row  , col  )
212| 
212| '''

213|     def __init__ (self, rows, cols):
214|         self.dims = (rows, cols)
215|         self.cells  = [ [int(0) for col in range(self.dims[1]) ] for row in range(self.dims[0])  ]
216|         self.ns_doors = [ [int(1) for col in range(self.dims[1])   ] for row in range(self.dims[0]-1) ]
217|         self.we_doors = [ [int(1) for col in range(self.dims[1]-1) ] for row in range(self.dims[0])   ]
218| 
219|     def write_image(self, fn):
220|         im = MazeImg(self.dims)
221|         # paint the maze...
222|         for rx,row in enumerate(self.cells):
223|             for cx,col in enumerate(row):
224|                 # set current cell...
225|                 im.set_current_cell(rx, cx)
226|                 if 1 < col:
227|                     im.paint_cell(ColorPalette[col])
228|                 # north wall...
229|                 if (rx == 0) and self.get_north_door(rx,cx):
230|                     im.draw_north_wall()
231|                 # south wall...
232|                 if self.get_south_door(rx,cx):
233|                     im.draw_south_wall()
234|                 # west wall...
235|                 if (cx == 0) and self.get_west_door(rx,cx):
236|                     im.draw_west_wall()
237|                 # east wall...
238|                 if self.get_east_door(rx,cx):
239|                     im.draw_east_wall()
240|         im.save(fn)
241|         if ShowImageBeforeSave: im.show()
242|         return im
243| 
244|     def all_cells_occupied (self):
245|         for maze_row in self.cells:
246|             for maze_cell in maze_row:
247|                 if maze_cell == 0:
248|                     return False
249|         return True
250| 
251|     def get_cell (self, row, col):
252|         '''Get state of cell(row,col).'''
253|         self._test_row_col(row, col)
254|         return self.cells[row][col]
255| 
256|     def set_cell (self, row, col, state):
257|         '''Set state of cell(row,col).'''
258|         self._test_row_col(row, col)
259|         self.cells[row][col] = state
260| 
261|     def set_north_door (self, row, col, state):
262|         '''Set state of north door of cell(row,col).'''
263|         self._test_row_col(row, col)
264|         if row == 0:
265|             raise Exception("Can't set north wall door!")
266|         self._test_ns_door_row_col(row-1,col)
267|         self.ns_doors[row-1][col] = state
268| 
269|     def get_north_door (self, row, col):
270|         '''Get state of north door of cell(row,col).'''
271|         if row == 0:
272|             return -1 # north wall
273|         self._test_ns_door_row_col(row-1,col)
274|         return self.ns_doors[row-1][col]
275| 
276|     def set_south_door (self, row, col, state):
277|         '''Set state of south door of cell(row,col).'''
278|         self._test_row_col(row, col)
279|         if (self.dims[0]-1) <= row:
280|             raise Exception("Can't set south wall door!")
281|         self._test_ns_door_row_col(row,col)
282|         self.ns_doors[row][col] = state
283| 
284|     def get_south_door (self, row, col):
285|         '''Get state of south door of cell(row,col).'''
286|         if (self.dims[0]-1) == row:
287|             return -1 # south wall
288|         self._test_ns_door_row_col(row,col)
289|         return self.ns_doors[row][col]
290| 
291|     def set_west_door (self, row, col, state):
292|         '''Set state of west door of cell(row,col).'''
293|         self._test_row_col(row, col)
294|         if col <= 0:
295|             raise Exception("Can't set west wall door!")
296|         self._test_we_door_row_col(row,col-1)
297|         self.we_doors[row][col-1] = state
298| 
299|     def get_west_door (self, row, col):
300|         '''Get state of west door of cell(row,col).'''
301|         if col == 0:
302|             return -1 # west wall
303|         self._test_we_door_row_col(row,col-1)
304|         return self.we_doors[row][col-1]
305| 
306|     def set_east_door (self, row, col, state):
307|         '''Set state of east door of cell(row,col).'''
308|         self._test_row_col(row, col)
309|         if (self.dims[1]-1) <= col:
310|             raise Exception("Can't set east wall door!")
311|         self._test_we_door_row_col(row,col)
312|         self.we_doors[row][col] = state
313| 
314|     def get_east_door (self, row, col):
315|         '''Get state of east door of cell(row,col).'''
316|         if (self.dims[1]-1) == col:
317|             return -1 # east wall
318|         self._test_we_door_row_col(row,col)
319|         return self.we_doors[row][col]
320| 
321|     def _test_row_col (self, row, col):
322|         '''Test (row,col) for access to cell state data.'''
323|         if (row < 0) or (self.dims[0] <= row):
324|             raise Exception("Row (%d) is out of bounds!" % row)
325|         if (col < 0) or (self.dims[1] <= col):
326|             raise Exception("Col (%d) is out of bounds!" % col)
327| 
328|     def _test_ns_door_row_col (self, row, col):
329|         '''Test (row,col) for access to north/south door data.'''
330|         if (row < 0) or ((self.dims[0]-1) <= row):
331|             raise Exception("Row (%d) is out of bounds!" % row)
332|         if (col < 0) or (self.dims[1] <= col):
333|             raise Exception("Col (%d) is out of bounds!" % col)
334| 
335|     def _test_we_door_row_col (self, row, col):
336|         '''Test (row,col) for access to east/west door data.'''
337|         if (row < 0) or (self.dims[0] <= row):
338|             raise Exception("Row (%d) is out of bounds!" % row)
339|         if (col < 0) or ((self.dims[1]-1) <= col):
340|             raise Exception("Col (%d) is out of bounds!" % col)
341| 
342| 
343| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
344| class MazeImg (object):
345|     '''Image class.'''
346|     HorzSpace = 20
347|     VertSpace = 20
348|     WallColor = ColorBlack
349| 
350|     def __init__ (self, _dims):
351|         '''Create new Maze Image instance.  NOTE: x=cols, y=rows!'''
352|         # Calculate pixel parameters based on rows and columns...
353|         self.dims = _dims
354|         self.pixels = (self.HorzSpace * (self.dims[1]+2), self.VertSpace * (self.dims[0]+2))
355|         self.pmin = (self.HorzSpace, self.VertSpace)
356|         self.pmax = (self.pixels[0] - self.HorzSpace, self.pixels[1] - self.VertSpace)
357|         # current square is ULC...
358|         self.p0 = (self.pmin[0]               , self.pmin[1])
359|         self.p1 = (self.pmin[0]+self.HorzSpace, self.pmin[1]+self.VertSpace)
360|         # Create image object...
361|         self.im = Image.new('RGB', self.pixels, ColorWhite)
362|         self.draw = ImageDraw.Draw(self.im)
363|         # Draw outer border...
364|         self.draw.rectangle((0,0)+(self.pixels[0]-1,self.pixels[1]-1), outline=ColorBlack)
365|         self.draw.rectangle((1,1)+(self.pixels[0]-2,self.pixels[1]-2), outline=ColorGray100)
366|         self.draw.rectangle((2,2)+(self.pixels[0]-3,self.pixels[1]-3), outline=ColorGray200)
367|         # vertical rules...
368|         for ix in range(1, self.dims[1]):
369|             pp = ix * self.HorzSpace
370|             self.draw.line([(self.pmin[0]+pp, self.pmin[1]), (self.pmin[0]+pp, self.pmax[1])], fill=ColorLightBlue)
371|         # horizontal rules...
372|         for ix in range(1, self.dims[0]):
373|             pp = ix * self.VertSpace
374|             self.draw.line([(self.pmin[0], self.pmin[1]+pp), (self.pmax[0], self.pmin[1]+pp)], fill=ColorLightBlue)
375|         # margins
376|         self.draw.line([(self.pmin[0], self.pmin[1]), (self.pmax[0], self.pmin[1])], fill=ColorDarkGreen, width=2) # th
377|         self.draw.line([(self.pmin[0], self.pmax[1]), (self.pmax[0], self.pmax[1])], fill=ColorDarkGreen, width=2) # bh
378|         self.draw.line([(self.pmin[0], self.pmin[1]), (self.pmin[0], self.pmax[1])], fill=ColorDarkGreen, width=2) # lv
379|         self.draw.line([(self.pmax[0], self.pmin[1]), (self.pmax[0], self.pmax[1])], fill=ColorDarkGreen, width=2) # rv
380| 
381|     def set_current_cell (self, row, col):
382|         '''Set current cell for drawing operations.'''
383|         if (row < 0) or (self.dims[0] <= row):
384|             raise Exception("Row is out of bounds!")
385|         if (col < 0) or (self.dims[1] <= col):
386|             raise Exception("Col is out of bounds!")
387|         cx = self.pmin[0] + (col * self.HorzSpace)
388|         cy = self.pmin[1] + (row * self.VertSpace)
389|         self.p0 = (cx,cy)
390|         self.p1 = (cx+self.HorzSpace, cy+self.VertSpace)
391| 
392|     def paint_cell (self, color):
393|         self.draw.rectangle([self.p0, self.p1], fill=color, outline=ColorBlack)
394| 
395|     def draw_north_wall (self):
396|         '''Draw north wall in current cell.'''
397|         self.draw.line([(self.p0[0], self.p0[1]), (self.p1[0], self.p0[1])], fill=self.WallColor, width=3)
398| 
399|     def draw_south_wall (self):
400|         '''Draw south wall in current cell.'''
401|         self.draw.line([(self.p0[0], self.p1[1]), (self.p1[0], self.p1[1])], fill=self.WallColor, width=3)
402| 
403|     def draw_west_wall (self):
404|         '''Draw west wall in current cell.'''
405|         self.draw.line([(self.p0[0], self.p0[1]), (self.p0[0], self.p1[1])], fill=self.WallColor, width=3)
406| 
407|     def draw_east_wall (self):
408|         '''Draw east wall in current cell.'''
409|         self.draw.line([(self.p1[0], self.p0[1]), (self.p1[0], self.p1[1])], fill=self.WallColor, width=3)
410| 
411|     def show (self):
412|         self.im.show()
413|         return self
414| 
415|     def save (self, fn, mode='GIF'):
416|         self.im.save(fn, mode)
417|         return self
418| 
419|     def __str__ (self):
420|         s = '%s (%d,%d) %s'
421|         t = (self.im.format, self.im.size[0], self.im.size[1], self.im.mode)
422|         return s % t
423| 
424|     def __repr__ (self):
425|         s = '{Img:{format:"%s", size:%s, mode:"%s", addr:%x}}'
426|         t = (self.im.format, str(self.im.size), self.im.mode, self.__hash__())
427|         return s % t
428| 
429| 
430| 
431| ##------------------------------------------------------------------------------------------------##
432| def simple_manual_demo (mz):
433|     # open doors...
434|     mz.set_east_door (0,0, 0)
435|     mz.set_east_door (0,1, 0)
436|     mz.set_east_door (0,2, 0)
437|     mz.set_south_door(0,3, 0)
438|     mz.set_west_door (1,3, 0)
439|     mz.set_south_door(1,2, 0)
440|     mz.set_south_door(2,2, 0)
441|     mz.set_south_door(3,2, 0)
442|     mz.set_west_door (4,2, 0)
443|     mz.set_south_door(4,1, 0) ## 4,1
444|     mz.set_south_door(5,1, 0)
445|     mz.set_south_door(6,1, 0)
446|     mz.set_east_door (7,1, 0)
447|     mz.set_north_door(7,2, 0)
448|     mz.set_north_door(6,2, 0)
449|     # dead end
450|     mz.set_north_door(4,1, 0) ## 4,1
451|     mz.set_north_door(3,1, 0)
452|     mz.set_north_door(2,1, 0)
453|     mz.set_west_door (1,1, 0)
454|     mz.set_south_door(1,0, 0)
455|     mz.set_south_door(2,0, 0)
456|     mz.set_south_door(3,0, 0)
457|     mz.set_south_door(4,0, 0)
458|     mz.set_south_door(5,0, 0)
459|     mz.set_south_door(6,0, 0)
460|     # etc...
461| 
462| 
463| ##================================================================================================##
464| def Main ():
465|     fns = []
466|     for tx in range(50):
467|         Log.info(tx)
468|         mz = Maze(NumberRows, NumberCols)
469|         # Set start cell...
470|         mz.set_cell(0,0, ixColorGreen)
471|         # set end cell...
472|         mz.set_cell(NumberRows-1, NumberCols-1, ixColorLightMagenta)
473|         mz.set_north_door (NumberRows-1, NumberCols-1, 0)
474| 
475|         #simple_manual_demo(mz)
476| 
477|         maze_maker = RandomWalk1(mz)
478|         Log.info()
479| 
480|         for ix in range(2000):
481|             maze_maker.carve_a_path(1)
482|             if mz.all_cells_occupied():
483|                 Log.info('Finished after %d iterations.' % ix)
484|                 break
485| 
486|         Log.info('Path List:')
487|         for ix,p in enumerate(maze_maker.path_list):
488|             #Log.info('%: %s' % (ix, str(p)))
489|             Log.info(p)
490|             Log.info()
491|         Log.info()
492| 
493|         fn = 'out\\maze-%02d.gif' % tx
494|         fns.append(fn)
495|         mz.write_image(fn)
496| 
497|     return fns
498| 
499| 
500| ##================================================================================================##
501| if __name__ == '__main__':
502|     print('autorun: %s' % argv[0])
503|     Log.start('maze-maker-1.log')
504|     Log.level(trace())
505|     try:
506|         obj = Main()
507|         Log.info()
508|     except Exception as e:
509|         print >> stderr, e
510|         Log.error(e)
511|     finally:
512|         Log.end()
513| 
514| ####################################################################################################
515| '''eof'''
516|