maze.html
001| """Maze Object Class.
001|
001| The Maze model consists of cells surrounded by walls. Any wall can have
001| door connecting an adjacent cell. Doors can potentially have multiple
001| states (open, closed, closed+locked, etc).
001|
001| The Maze object supports a three-dimensional maze. Such a maze has
001| multiple levels. Cells have (potentially) top and/or bottom doors
001| that connect to cells in the level above or below.
001|
001| Internally, the Maze object maintains four arrays:
001|
001| Maze Cells [rows , cols ]
001| North/South Doors [rows+1, cols ]
001| West/East Doors [rows , cols+1]
001| Bottom/Top Doors [rows , cols ] * (levels + 1)
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| e.g. Cell = [1,3]
001| N/S Door = [1,3]/[2,3] {0,0}/{+1,0}
001| W/E Door = [1,3]/[1,4] {0,0}/{0,+1}
001| B/T Door = [1,3]/[1,3] [Level]/[Level+1]
001|
001| Classes:
001| MazeObject (object)
001| MazeNavigator (object)
001| MazeGen1 (MazeNavigator)
001| MazeSolver (MazeNavigator)
001| MazeImageGif (object)
001| MazeImagePng (object)
001| MazePOV (object)
001| MazeXML (MazeNavigator)
001| MazeCubeObject (object)
001|
001| Coder@Sonnack.com
001| September 16, 2014
001| """
002|
003| from sys import argv, stdout
004| from random import random, shuffle
005| from PIL import Image, ImageDraw
006| from logger import logger, info, debug, trace
007| import colors
008|
009| Log = logger('MAZE')
010|
011| Limit = lambda lst,ix: max(0, min(len(lst)-1, ix))
012|
013| RandomWall = lambda f: random() < f
014|
015|
016|
017|
018| class MazeObject (object):
019| """Maze Object class.
019|
019| properties:
019| dims - (rows, cols)
019| cells - Maze Cells matrix
019| ns_walls - North-South walls matrix
019| we_walls - West-East walls matrix
019| entry_cell - Row-Col of Maze Entry cell
019| exit_cell - Row-Col of Maze Exit cell
019|
019| methods:
019| rows () - Number of rows
019| cols () - Number of cols
019| size () - Size tuple (rows, cols)
019| area () - Number of cells (rows x cols)
019| all_cells_occupied () - Test if all cells non-zero
019| set_entry_and_exit () - As the name implies
019|
019| cell (row, col) - Get a cell's value
019| set_cell (row, col, state) - Set a cell's value
019| set_all_cells (state) - Set all cells to state
019|
019| wall_n (row, col) - Get a wall's value
019| wall_e (row, col)
019| wall_s (row, col)
019| wall_w (row, col)
019|
019| set_wall_n (row, col, state) - Set wall's value to state
019| set_wall_e (row, col, state)
019| set_wall_s (row, col, state)
019| set_wall_w (row, col, state)
019| set_all_walls (state) - Set all walls to state
019|
019| print_maze (fp) - Print ASCII maze to fp
019| visit_cells (visitor) - Visit cells by row and col
019| function Visitor(row,col, cell):cell
019| visit_maze (visitor) - Visit cells, walls, and corners
019| object Visitor.[various]
019| (see MazeObject.MazeVisitor)
019| """
020|
021| cell_syms = [' ', ' @ ', ' # ', ' $ ', ' ? ']
022| hwall_syms = [' ', '---', '-o-', '-x-']
023| vwall_syms = [ ' ' , '|' , 'o' , 'x' ]
024| corner_sym = '+'
025|
026| NoWall = int(0)
027| MazeWall = int(1)
028|
029| LockedCell = int(-1)
030| EmptyCell = int(0)
031| MazeEntry = int(1)
032| MazeExit = int(2)
033| MazePath = int(3)
034| MazeMarker = int(4)
035| PathMarker = int(5)
036| PathTag = int(6)
037| PathTemp = int(7)
038|
039| def __init__ (self, rows, cols):
040| """Create new Maze Object instance."""
041| self.dims = (rows, cols)
042| self.entry_cell = (0, 0)
043| self.exit_cell = (self.dims[0]-1, self.dims[1]-1)
044|
045| self.set_all_cells(MazeObject.EmptyCell)
046| self.set_all_walls(MazeObject.MazeWall)
047|
048| def rows (self): return self.dims[0]
049| def cols (self): return self.dims[1]
050| def size (self): return self.dims
051| def area (self): return (self.dims[0] * self.dims[1])
052|
053| def cell (self, row, col):
054| """Get a cell's value."""
055| return self.cells[row][col]
056|
057| """Get a wall's value."""
058| def wall_n (self, row, col): return self.ns_walls[row ][col ]
059| def wall_e (self, row, col): return self.we_walls[row ][col+1]
060| def wall_s (self, row, col): return self.ns_walls[row+1][col ]
061| def wall_w (self, row, col): return self.we_walls[row ][col ]
062|
063| def set_entry_and_exit (self):
064| """Set Entry and Exit cell and wall values."""
065|
066| self.set_cell(self.entry_cell[0], self.entry_cell[1], MazeObject.MazeEntry)
067| self.set_cell(self.exit_cell[0] , self.exit_cell[1] , MazeObject.MazeExit)
068|
069| self.set_wall_w(self.entry_cell[0], self.entry_cell[1], MazeObject.MazeEntry)
070| self.set_wall_e(self.exit_cell[0] , self.exit_cell[1] , MazeObject.MazeExit)
071|
072| def set_cell (self, row, col, state):
073| """Set a cell's value."""
074| self.cells[row][col] = state
075|
076| def set_all_cells (self, state):
077| """Set all maze cells to the same state."""
078| self.cells = [[state for col in range(self.dims[1])] for row in range(self.dims[0])]
079|
080| """Set a wall's value."""
081| def set_wall_n (self, row, col, state): self.ns_walls[row ][col ] = state
082| def set_wall_e (self, row, col, state): self.we_walls[row ][col+1] = state
083| def set_wall_s (self, row, col, state): self.ns_walls[row+1][col ] = state
084| def set_wall_w (self, row, col, state): self.we_walls[row ][col ] = state
085|
086| def set_all_walls (self, state):
087| """Set all maze walls to the same state."""
088| self.ns_walls = [[state for col in range(self.dims[1]) ] for row in range(self.dims[0]+1)]
089| self.we_walls = [[state for col in range(self.dims[1]+1)] for row in range(self.dims[0]) ]
090|
091| def all_cells_occupied (self):
092| """Test to see if all cells are occupied."""
093| for maze_row in self.cells:
094| for maze_cell in maze_row:
095| if maze_cell == MazeObject.EmptyCell:
096| return False
097| return True
098|
099| def print_maze (self, fp=stdout):
100| """Dump an ASCII version of the maze to the given file pointer."""
101| for row in range(self.dims[0]):
102|
103| for col in range(self.dims[1]):
104| w = Limit(self.hwall_syms, self.wall_n(row,col))
105| fp.write(self.corner_sym)
106| fp.write(self.hwall_syms[w])
107| fp.write(self.corner_sym)
108| fp.write('\n')
109|
110| for col in range(self.dims[1]):
111|
112| w = Limit(self.vwall_syms, self.wall_w(row,col))
113| fp.write(self.vwall_syms[w])
114|
115| c = Limit(self.cell_syms, self.cell(row,col))
116| fp.write(self.cell_syms[c])
117|
118| w = Limit(self.vwall_syms, self.wall_e(row,col))
119| fp.write(self.vwall_syms[w])
120| fp.write('\n')
121|
122| for col in range(self.dims[1]):
123| w = Limit(self.hwall_syms, self.wall_s(row,col))
124| fp.write(self.corner_sym)
125| fp.write(self.hwall_syms[w])
126| fp.write(self.corner_sym)
127| fp.write('\n')
128|
129| def __str__ (self):
130| """Always implement toString!"""
131| s = '%d x %d (%d,%d) -> (%d,%d)'
132| t = (self.dims[0], self.dims[1], self.entry_cell[0], self.entry_cell[1], self.exit_cell[0], self.exit_cell[1])
133| return s % t
134|
135| def __repr__ (self):
136| """Return a JSON-like string."""
137| s = '{MazeObject:{rows:%d, cols:%d, entry:(%d,%d), exit:(%d,%d)}}'
138| t = (self.dims[0], self.dims[1], self.entry_cell[0], self.entry_cell[1], self.exit_cell[0], self.exit_cell[1])
139| return s % t
140|
141| def visit_cells (self, visitor):
142| """Visit all the cells in the maze."""
143| for row in range(self.dims[0]):
144| for col in range(self.dims[1]):
145| self.cells[row][col] = visitor(row,col,self.cells[row][col])
146|
147| def visit_maze (self, visitor):
148| """Visit Maze. Visitor must support: print_start, print_cell, print_wall_{NESW}, print_corner, print_eol, print_end."""
149| visitor.print_start(self)
150| for row in range(self.dims[0]):
151|
152| for col in range(self.dims[1]):
153| visitor.print_corner(row, col)
154| visitor.print_wall_n(row, col, self.wall_n(row,col))
155| visitor.print_corner(row, col+1)
156| visitor.print_eol(row, col+1)
157|
158| for col in range(self.dims[1]):
159|
160| visitor.print_wall_w(row, col, self.wall_w(row,col))
161|
162| visitor.print_cell(row, col, self.cell(row,col))
163|
164| visitor.print_wall_e(row, col, self.wall_e(row,col))
165| visitor.print_eol(row, col+1)
166|
167| for col in range(self.dims[1]):
168| visitor.print_corner(row+1, col)
169| visitor.print_wall_s(row, col, self.wall_s(row,col))
170| visitor.print_corner(row+1, col+1)
171| visitor.print_eol(row+1, col+1)
172| visitor.print_end()
173|
174| class MazeVisitor (object):
175| """Simple Maze Visitor class."""
176| def __init__ (self, sout):
177| self.sout = sout
178| def print_start (self, obj):
179| self.sout.write('\n')
180| def print_end (self):
181| self.sout.write('\n')
182| def print_corner (self, row, col):
183| self.sout.write('+')
184| def print_eol (self, row, col):
185| self.sout.write('\n')
186| self.sout.flush()
187| def print_cell (self, row, col, val):
188| ix = Limit(MazeObject.cell_syms, val)
189| self.sout.write(MazeObject.cell_syms[ix])
190| def print_wall_n (self, row, col, val):
191| ix = Limit(MazeObject.hwall_syms, val)
192| self.sout.write(MazeObject.hwall_syms[ix])
193| def print_wall_s (self, row, col, val):
194| ix = Limit(MazeObject.hwall_syms, val)
195| self.sout.write(MazeObject.hwall_syms[ix])
196| def print_wall_w (self, row, col, val):
197| ix = Limit(MazeObject.vwall_syms, val)
198| self.sout.write(MazeObject.vwall_syms[ix])
199| def print_wall_e (self, row, col, val):
200| ix = Limit(MazeObject.vwall_syms, val)
201| self.sout.write(MazeObject.vwall_syms[ix])
202|
203| def visit_maze_demo (self, fp=stdout):
204| """X: Maze Visitor idea -- entry method."""
205| self.visit_maze(self.MazeVisitor(fp))
206|
207|
208|
209|
210| class MazeCubeObject (object):
211| """3D Maze Object class."""
212|
213| def __init__ (self, rows, cols, levels):
214| """Create new Maze Cube Object instance."""
215| super().__init__(rows, cols)
216|
217| self.bt_walls = []
218| for lvl in range(levels):
219| a = [[MazeObject.MazeWall for col in range(self.dims[1])] for row in range(self.dims[0])]
220| self.bt_walls.append(a)
221|
222|
223|
224|
225|
226| class MazeNavigator (object):
227| """Maze Navigator class.
227|
227| Tools for moving around the maze. Also a base class for generator and solver tools.
227|
227| Properties:
227| mz - Maze Object
227| curr_row - Current Location Row
227| curr_col - Current Location Column
227| direction - Current Location Direction [0-3]
227|
227| Abbrev = ['N','E','S','W']
227| North = 0
227| East = 1
227| South = 2
227| West = 3
227|
227| Methods:
227| set_location (r,c) - Set current location
227| set_direction (d) - Set current direction
227| get_location () - Get current location (returns a tuple)
227| get_direction () - Get current direction
227| reset_to_entry () - Reset current position and direction
227|
227| turn_left () - Set current direction 90 degrees to the left
227| turn_right () - Set current direction 90 degrees to the right
227| left_direction () - Get index of direction to our current left
227| right_direction () - Get index of direction to our current right
227|
227| move_to_next_cell () - Move to the next cell
227| move_to_north_cell () - Move to the cell to the north
227| move_to_south_cell () - Move to the cell to the south
227| move_to_west_cell () - Move to the cell to the west
227| move_to_east_cell () - Move to the cell to the east
227| move_to_cell - Array for indexed access and "next" function
227|
227| get_curr_cell () - Get value of current cell
227| get_next_cell () - Get value of next cell
227| get_north_cell () - Get value of cell to the north
227| get_south_cell () - Get value of cell to the south
227| get_west_cell () - Get value of cell to the west
227| get_east_cell () - Get value of cell to the east
227| get_left_cell () - Get value of cell on the left
227| get_right_cell () - Get value of cell on the right
227| get_cell - Array for indexed access and "next/left/right" functions
227|
227| set_curr_cell (val) - Set value of current cell
227| set_next_cell (val) - Set value of next cell
227| set_north_cell (val) - Set value of cell to the north
227| set_south_cell (val) - Set value of cell to the south
227| set_west_cell (val) - Set value of cell to the west
227| set_east_cell (val) - Set value of cell to the east
227| set_left_cell (val) - Set value of cell on the left
227| set_right_cell (val) - Set value of cell on the right
227| set_cell - Array for indexed access and "next/left/right" functions
227|
227| get_next_wall () - Get value of next wall
227| get_left_wall () - Get value of wall on the left
227| get_right_wall () - Get value of wall on the right
227| get_north_wall () - Get value of wall to the north
227| get_south_wall () - Get value of wall to the south
227| get_west_wall () - Get value of wall to the west
227| get_east_wall () - Get value of wall to the east
227| get_wall - Array for indexed access and "next/left/right" functions
227|
227| set_next_wall (val) - Set value of next wall
227| set_north_wall (val) - Set value of wall to the north
227| set_south_wall (val) - Set value of wall to the south
227| set_west_wall (val) - Set value of wall to the west
227| set_east_wall (val) - Set value of wall to the east
227|
227| """
228| Abbrev = ['N', 'E', 'S', 'W']
229| North = 0
230| East = 1
231| South = 2
232| West = 3
233|
234| def __init__ (self, mz, row=0, col=0, direction=East):
235| """New MazeNavigator instance."""
236| self.mz = mz
237| self.curr_row = row
238| self.curr_col = col
239| self.direction = direction
240|
241|
242|
243|
244| def get_location (self):
245| """Get the current location."""
246| return (self.curr_row, self.curr_col)
247|
248| def get_direction (self):
249| """Get the current direction."""
250| return self.direction
251|
252| def set_location (self, row, col):
253| """Directly set the current location."""
254| self.curr_row = row
255| self.curr_col = col
256|
257| def set_direction (self, d):
258| """Directly set the current direction. (Accepts index number or letter.)"""
259| if isinstance(d, str):
260| d = self.Abbrev.index(d.upper())
261| self.direction = d
262| return self.direction
263|
264| def reset_to_entry (self):
265| """Reset current location and direction to the entry cell."""
266| self.curr_row = self.mz.entry_cell[0]
267| self.curr_col = self.mz.entry_cell[1]
268| self.direction = MazeNavigator.East
269|
270|
271|
272|
273| def turn_left (self):
274| """Turn left. (Result depends on current direction.)"""
275| self.direction = self.left_direction()
276| return self.direction
277|
278| def turn_right (self):
279| """Turn right. (Result depends on current direction.)"""
280| self.direction = self.right_direction()
281| return self.direction
282|
283| def left_direction (self):
284| """Get index of direction to our current left."""
285| return (self.direction - 1) % 4
286|
287| def right_direction (self):
288| """Get index of direction to our current right."""
289| return (self.direction + 1) % 4
290|
291|
292|
293|
294| def move_to_north_cell (self):
295| """Move to north cell."""
296| self.curr_row = self.curr_row - 1
297| if self.curr_row < 0:
298| raise Exception('Moved beyond the North Wall!')
299|
300| def move_to_south_cell (self):
301| """Move to south cell."""
302| self.curr_row = self.curr_row + 1
303| if self.mz.dims[0] <= self.curr_row:
304| raise Exception('Moved beyond the South Wall!')
305|
306| def move_to_west_cell (self):
307| """Move to east cell."""
308| self.curr_col = self.curr_col - 1
309| if self.curr_col < 0:
310| raise Exception('Moved beyond the West Wall!')
311|
312| def move_to_east_cell (self):
313| """Move to east cell."""
314| self.curr_col = self.curr_col + 1
315| if self.mz.dims[1] <= self.curr_col:
316| raise Exception('Moved beyond the East Wall!')
317|
318| """Array of move-to functions for indexed access."""
319| move_to_cell = [move_to_north_cell, move_to_east_cell, move_to_south_cell, move_to_west_cell]
320|
321| def move_to_next_cell (self):
322| """Move to next cell. (Depends on current direction.)"""
323| return self.move_to_cell[self.direction](self)
324|
325|
326|
327|
328| def get_curr_cell (self):
329| """Get current cell's value."""
330| return self.mz.cell(self.curr_row, self.curr_col)
331|
332| def get_north_cell (self):
333| """Get north cell's value."""
334|
335| if self.curr_row == 0:
336| return -1
337| return self.mz.cell(self.curr_row-1, self.curr_col)
338|
339| def get_south_cell (self):
340| """Get south cell's value."""
341|
342| if self.curr_row == (self.mz.dims[0] - 1):
343| return -1
344| return self.mz.cell(self.curr_row+1, self.curr_col)
345|
346| def get_west_cell (self):
347| """Get west cell's value."""
348|
349| if self.curr_col == 0:
350| return -1
351| return self.mz.cell(self.curr_row, self.curr_col-1)
352|
353| def get_east_cell (self):
354| """Get east cell's value."""
355|
356| if self.curr_col == (self.mz.dims[1] - 1):
357| return -1
358| return self.mz.cell(self.curr_row, self.curr_col+1)
359|
360| """Array of neighbor cell getters for indexed access."""
361| get_cell = [get_north_cell, get_east_cell, get_south_cell, get_west_cell]
362|
363| def get_next_cell (self):
364| """Get next cell's value. (Depends on current direction.)"""
365| return self.get_cell[self.direction](self)
366|
367| def get_left_cell (self):
368| """Get left cell's value. (Depends on current direction.)"""
369| d = self.left_direction()
370| return self.get_cell[d](self)
371|
372| def get_right_cell (self):
373| """Get right cell's value. (Depends on current direction.)"""
374| d = self.right_direction()
375| return self.get_cell[d](self)
376|
377|
378|
379|
380| def set_curr_cell (self, val):
381| """Set current cell's value."""
382| self.mz.set_cell(self.curr_row, self.curr_col, val)
383|
384| def set_north_cell (self, val):
385| """Set north cell's value."""
386|
387| if self.curr_row == 0:
388| return -1
389| return self.mz.set_cell(self.curr_row-1, self.curr_col, val)
390|
391| def set_south_cell (self, val):
392| """Set south cell's value."""
393|
394| if self.curr_row == (self.mz.dims[0] - 1):
395| return -1
396| return self.mz.set_cell(self.curr_row+1, self.curr_col, val)
397|
398| def set_west_cell (self, val):
399| """Set west cell's value."""
400|
401| if self.curr_col == 0:
402| return -1
403| return self.mz.set_cell(self.curr_row, self.curr_col-1, val)
404|
405| def set_east_cell (self, val):
406| """Set east cell's value."""
407|
408| if self.curr_col == (self.mz.dims[1] - 1):
409| return -1
410| return self.mz.set_cell(self.curr_row, self.curr_col+1, val)
411|
412| """Array of neighbor cell setters for indexed access."""
413| set_cell = [set_north_cell, set_east_cell, set_south_cell, set_west_cell]
414|
415| def set_next_cell (self, val):
416| """Set next cell's value. (Depends on current direction.)"""
417| return self.set_cell[self.direction](self, val)
418|
419| def set_left_cell (self, val):
420| """Set left cell's value. (Depends on current direction.)"""
421| d = self.left_direction()
422| return self.set_cell[d](self, val)
423|
424| def set_right_cell (self, val):
425| """Set right cell's value. (Depends on current direction.)"""
426| d = self.right_direction()
427| return self.set_cell[d](self, val)
428|
429|
430|
431|
432| def get_north_wall (self):
433| """Get north wall."""
434| return self.mz.wall_n(self.curr_row, self.curr_col)
435|
436| def get_south_wall (self):
437| """Get south wall."""
438| return self.mz.wall_s(self.curr_row, self.curr_col)
439|
440| def get_west_wall (self):
441| """Get west wall."""
442| return self.mz.wall_w(self.curr_row, self.curr_col)
443|
444| def get_east_wall (self):
445| """Get east wall."""
446| return self.mz.wall_e(self.curr_row, self.curr_col)
447|
448| """Array of wall cell getters for indexed access."""
449| get_wall = [get_north_wall, get_east_wall, get_south_wall, get_west_wall]
450|
451| def get_next_wall (self):
452| """Get next wall. (Depends on current direction.)"""
453| return self.get_wall[self.direction](self)
454|
455| def get_left_wall (self):
456| """Get left wall. (Depends on current direction.)"""
457| d = self.left_direction()
458| return self.get_wall[d](self)
459|
460| def get_right_wall (self):
461| """Get right wall. (Depends on current direction.)"""
462| d = self.right_direction()
463| return self.get_wall[d](self)
464|
465|
466|
467|
468| def set_north_wall (self, val):
469| """Set north wall."""
470| self.mz.set_wall_n(self.curr_row, self.curr_col, val)
471|
472| def set_south_wall (self, val):
473| """Set south wall."""
474| self.mz.set_wall_s(self.curr_row, self.curr_col, val)
475|
476| def set_west_wall (self, val):
477| """Set west wall."""
478| self.mz.set_wall_w(self.curr_row, self.curr_col, val)
479|
480| def set_east_wall (self, val):
481| """Set east wall."""
482| self.mz.set_wall_e(self.curr_row, self.curr_col, val)
483|
484| """Array of wall cell setters for indexed access."""
485| set_wall = [set_north_wall, set_east_wall, set_south_wall, set_west_wall]
486|
487| def set_next_wall (self, val):
488| """Set next wall. (Depends on current direction.)"""
489| return self.set_wall[self.direction](self, val)
490|
491| def __str__ (self):
492| """Always implement toString!"""
493| s = '[%d, %d] facing: %s (%s)'
494| t = (self.curr_row,self.curr_col, self.Abbrev[self.direction], self.mz)
495| return s % t
496|
497|
498|
499|
500|
501| class MazeGen1 (MazeNavigator):
502| """Maze Generator #1.
502|
502| Properties:
502| mz - Maze object
502| tot_steps - Number of steps taken
502| dir_steps -
502| path_list - List of paths through the maze
502| cb_builder - Callback function
502|
502| Methods:
502| generate_maze ()
502|
502| Internal Methods:
502| carve_a_path (cell_value) - carve a single path in the maze
502| find_a_path () - find a random cell on a path for branching to a new path
502| change_direction () - turn left or right (50/50 either way)
502|
502| """
503| max_steps = 100
504| wall_change = 0.1
505| occu_change = 0.1
506| dir_change = 1
507|
508| def __init__ (self, mz, row=0, col=0):
509| super().__init__(mz, row, col)
510| self.mz = mz
511| self.tot_steps = 0
512| self.dir_steps = 0
513| self.path_list = []
514| self.cb_builder = None
515|
516| def generate_maze (self):
517| """Generate a maze by carving paths in it."""
518| self.mz.set_all_cells(MazeObject.EmptyCell)
519| self.mz.set_cell(self.curr_row, self.curr_col, MazeObject.MazeEntry)
520| self.reset_to_entry()
521|
522|
523| for ix in range(self.mz.dims[0] * self.mz.dims[1]):
524| self.carve_a_path(MazeObject.MazeMarker)
525| if self.mz.all_cells_occupied():
526| Log.info('Finished after %d iterations.' % ix)
527|
528| self.mz.set_all_cells(MazeObject.EmptyCell)
529| self.mz.set_entry_and_exit()
530| self.set_location(*self.mz.exit_cell)
531| if self.cb_builder:
532| self.cb_builder(self)
533| return
534|
535| Log.error('NOT DONE AFTER %d ITERATIONS!' % ix)
536|
537| def carve_a_path (self, cell_value):
538| """Carve a path through the maze. Set each cell in the path to cell_value."""
539| Log.debug()
540| Log.debug('NEW PATH...')
541|
542| if 0 < len(self.path_list):
543| if not self.find_a_path():
544| return
545| Log.debug('using: (%d, %d)' % (self.curr_row, self.curr_col))
546|
547|
548| self.tot_steps = 0
549| self.dir_steps = 0
550| current_path = []
551| while self.tot_steps < self.max_steps:
552| s = self.Abbrev[self.direction]
553| t = (self.tot_steps, self.dir_steps, s, self.curr_row, self.curr_col)
554| Log.trace('STEP: %d (%d:%s) [%d, %d]' % t)
555| current_path.append([self.curr_row, self.curr_col, 2])
556| if self.cb_builder:
557| self.cb_builder(self)
558|
559|
560| tc = self.get_next_cell()
561| if tc < 0:
562|
563| Log.trace('Hit the wall!')
564| if self.wall_change < random():
565| if self.change_direction():
566| continue
567| break
568| if 0 < tc:
569|
570| Log.trace('Hit another path!')
571| if self.occu_change < random():
572| if self.change_direction():
573| continue
574| break
575|
576|
577| self.set_next_wall(MazeObject.NoWall)
578| self.move_to_next_cell()
579|
580| self.set_curr_cell(cell_value)
581|
582|
583| self.tot_steps = self.tot_steps + 1
584| self.dir_steps = self.dir_steps + 1
585|
586|
587| if self.dir_change < (random() * self.dir_steps):
588| if self.change_direction():
589| self.dir_steps = 0
590|
591|
592| n = len(current_path)
593| Log.debug('New Path: %d step%s' % (n, '' if n == 1 else 's'))
594| self.path_list.append(current_path)
595|
596| def find_a_path (self):
597| """Randomly pick a cell on an existing path to branch from. Set the new row,col and direction."""
598|
599|
600| maze_path_seq = [x for x in range(len(self.path_list))]
601| shuffle(maze_path_seq)
602|
603|
604| for mx,maze_path in map(lambda ix: (ix, self.path_list[ix]), maze_path_seq):
605| Log.trace('MazePath: %d (%d cells)' % (mx, len(maze_path)))
606|
607|
608| maze_cell_seq = [x for x in range(len(maze_path))]
609| shuffle(maze_cell_seq)
610|
611|
612| for cx,path_cell in map(lambda ix: (ix,maze_path[ix]), maze_cell_seq):
613| Log.trace('PathCell: %d [%d,%d (%d)]' % (cx, path_cell[0], path_cell[1], path_cell[2]))
614|
615|
616| if path_cell[2] < 4:
617| self.curr_row = path_cell[0]
618| self.curr_col = path_cell[1]
619| Log.trace('testing: (%d, %d)' % (self.curr_row, self.curr_col))
620| if self.get_north_cell() == 0:
621| self.direction = self.North
622|
623| return True
624| if self.get_east_cell() == 0:
625| self.direction = self.East
626|
627| return True
628| if self.get_south_cell() == 0:
629| self.direction = self.South
630|
631| return True
632| if self.get_west_cell() == 0:
633| self.direction = self.West
634|
635| return True
636|
637| Log.debug('Unable to find a path!')
638| return False
639|
640| def change_direction (self):
641| """Turn Left/Right (50% random choice) or Right/Left if first choice not possible. Return True if successful."""
642| if random() < 0.5:
643|
644| if self.get_left_cell() == MazeObject.EmptyCell:
645|
646| d = self.turn_left()
647| else:
648|
649| if self.get_right_cell() == MazeObject.EmptyCell:
650|
651| d = self.turn_right()
652| else:
653|
654| return False
655| else:
656|
657| if self.get_right_cell() == MazeObject.EmptyCell:
658|
659| d = self.turn_right()
660| else:
661|
662| if self.get_left_cell() == MazeObject.EmptyCell:
663|
664| d = self.turn_left()
665| else:
666|
667| return False
668|
669| Log.trace('NEW DIRECTION: %d' % d)
670| return True
671|
672|
673|
674|
675|
676| class MazeSolver (MazeNavigator):
677| """Maze Solving class.
677|
677| This uses the left-hand rule to move through the maze and find the exit.
677| Once it does, the "right edge" of the path is the direct path through
677| the maze.
677|
677| Methods:
677| solve_maze () - front-end for .solve() method; returns a maze-path
677|
677| Internal Methods:
677| solve (maze-path) - solve the maze using left-hand rule [RECURSIVE!]
677|
677| """
678| def __init__ (self, mz, row=0, col=0):
679| """New MazeSolver instance."""
680| super().__init__(mz, row, col)
681| self.messages = []
682| self.cb_builder = None
683|
684| def solve_maze (self):
685| """Solve the maze."""
686| a = []
687| Log.info('SOLVE MAZE')
688| self.reset_to_entry()
689| self.solve(a)
690|
691| self.mz.visit_cells(lambda r,c,v:MazeObject.EmptyCell if v==MazeObject.PathMarker else v)
692|
693| for r,c,d in a[1:-1]:
694| self.mz.set_cell(r,c, MazeObject.MazePath)
695| if self.cb_builder:
696| self.cb_builder(self)
697| Log.info('Maze Solved! (path-length: %d)' % len(a))
698| return a
699|
700| def solve (self, maze_path):
701| """Solve maze using left-hand rule. [RECURSIVE!]"""
702| Log.debug('[%d,%d]' % (self.curr_row, self.curr_col))
703| c = self.get_curr_cell()
704|
705| if c == MazeObject.MazeExit:
706| Log.trace('[%d,%d] EXIT' % (self.curr_row, self.curr_col))
707| t = (self.curr_row, self.curr_col, self.direction)
708| maze_path.append(t)
709| return True
710|
711| if c == MazeObject.EmptyCell:
712| self.set_curr_cell(MazeObject.PathMarker)
713| if self.cb_builder:
714| self.cb_builder(self)
715|
716|
717| if self.get_left_wall() == 0:
718| Log.trace('[%d,%d] turn left' % (self.curr_row, self.curr_col))
719| t = (self.curr_row, self.curr_col, self.direction)
720| self.turn_left()
721| self.move_to_next_cell()
722| maze_path.append(t)
723|
724| rv = self.solve(maze_path)
725| if rv: return True
726| self.curr_row, self.curr_col, self.direction = maze_path.pop()
727|
728|
729| if self.get_next_wall() == 0:
730| Log.trace('[%d,%d] go straight' % (self.curr_row, self.curr_col))
731| t = (self.curr_row, self.curr_col, self.direction)
732| self.move_to_next_cell()
733| maze_path.append(t)
734|
735| rv = self.solve(maze_path)
736| if rv: return True
737| self.curr_row, self.curr_col, self.direction = maze_path.pop()
738|
739|
740| if self.get_right_wall() == 0:
741| Log.trace('[%d,%d] turn right' % (self.curr_row, self.curr_col))
742| t = (self.curr_row, self.curr_col, self.direction)
743| self.turn_right()
744| self.move_to_next_cell()
745| maze_path.append(t)
746|
747| rv = self.solve(maze_path)
748| if rv: return True
749| self.curr_row, self.curr_col, self.direction = maze_path.pop()
750|
751|
752| Log.trace('STUCK! Gotta back up now!')
753| return False
754|
755|
756|
757|
758|
759| class MazeImageGif (object):
760| """Maze GIF Image class.
760|
760| properties:
760| mz - Maze object
760| im - Image object
760| draw - ImageDraw object
760| pixels - Pixel dimensions of image
760| pmin,pmax - ULC,LRC of Maze plot area
760| p0,p1 - ULC,LRC of current cell
760|
760| methods:
760| draw_maze ()
760| show ()
760| save (fn, mode='GIF')
760|
760| set_current_cell (row, col) - required first before using paint methods
760| paint_cell (color) - set cell color
760| paint_north_wall () - set cell north wall
760| paint_east_wall () - set cell east wall
760| paint_south_wall () - set cell south wall
760| paint_west_wall () - set cell west wall
760|
760| str(obj) - properties string
760| repr(obj) - JSON-like string
760|
760| """
761| HorzSpace = 20
762| VertSpace = 20
763|
764| WallColor = colors.ixColorBlack
765| GridColor = colors.ixColorLightBlue
766|
767| def __init__ (self, mz):
768| """Create new Maze Image instance. NOTE: x=cols, y=rows!"""
769| self.mz = mz
770|
771| self.pixels = (self.HorzSpace * (self.mz.dims[1]+2), self.VertSpace * (self.mz.dims[0]+2))
772| self.pmin = (self.HorzSpace, self.VertSpace)
773| self.pmax = (self.pixels[0] - self.HorzSpace, self.pixels[1] - self.VertSpace)
774|
775| self.p0 = (self.pmin[0] , self.pmin[1])
776| self.p1 = (self.pmin[0]+self.HorzSpace, self.pmin[1]+self.VertSpace)
777|
778| self.im = Image.new('P', self.pixels, colors.ixColorWhite)
779|
780| pal = []
781| for c in colors.ColorPalette: pal.extend(c)
782| self.im.putpalette(pal)
783|
784| self.draw = ImageDraw.Draw(self.im)
785|
786| self.draw.rectangle((0,0)+(self.pixels[0]-1,self.pixels[1]-1), outline=colors.ixColorBlack)
787| self.draw.rectangle((1,1)+(self.pixels[0]-2,self.pixels[1]-2), outline=colors.ixColorGray100)
788| self.draw.rectangle((2,2)+(self.pixels[0]-3,self.pixels[1]-3), outline=colors.ixColorGray200)
789|
790| for ix in range(1, self.mz.dims[1]):
791| pp = ix * self.HorzSpace
792| self.draw.line([(self.pmin[0]+pp, self.pmin[1]), (self.pmin[0]+pp, self.pmax[1])], fill=self.GridColor)
793|
794| for ix in range(1, self.mz.dims[0]):
795| pp = ix * self.VertSpace
796| self.draw.line([(self.pmin[0], self.pmin[1]+pp), (self.pmax[0], self.pmin[1]+pp)], fill=self.GridColor)
797|
798| for row in range(1, self.mz.dims[0]+2):
799| py = row * self.VertSpace
800| for col in range(1, self.mz.dims[1]+2):
801| px = col * self.HorzSpace
802| self.draw.rectangle((px-1,py-1)+(px+1,py), fill=colors.ixColorBlack, outline=colors.ixColorBlack)
803|
804| self.draw.line([(self.pmin[0], self.pmin[1]), (self.pmax[0], self.pmin[1])], fill=colors.ixColorDarkBlue, width=2)
805| self.draw.line([(self.pmin[0], self.pmax[1]), (self.pmax[0], self.pmax[1])], fill=colors.ixColorDarkBlue, width=2)
806| self.draw.line([(self.pmin[0], self.pmin[1]), (self.pmin[0], self.pmax[1])], fill=colors.ixColorDarkBlue, width=2)
807| self.draw.line([(self.pmax[0], self.pmin[1]), (self.pmax[0], self.pmax[1])], fill=colors.ixColorDarkBlue, width=2)
808|
809| def draw_maze (self):
810| """Draw a maze."""
811|
812| for row in range(self.mz.dims[0]):
813| for col in range(self.mz.dims[1]):
814|
815| v = self.mz.cell(row, col)
816| if 0 < v:
817| self.set_current_cell(row, col)
818| self.paint_cell(v)
819|
820| for row in range(self.mz.dims[0]):
821| for col in range(self.mz.dims[1]):
822|
823| self.set_current_cell(row, col)
824|
825| if self.mz.wall_n(row, col):
826| self.paint_north_wall()
827| if self.mz.wall_w(row, col):
828| self.paint_west_wall()
829|
830| if self.mz.wall_e(row, col):
831| self.paint_east_wall()
832|
833| for col in range(self.mz.dims[1]):
834|
835| self.set_current_cell(row, col)
836| if self.mz.wall_s(row, col):
837| self.paint_south_wall()
838|
839| def set_current_cell (self, row, col):
840| """Set current cell for drawing operations."""
841| if (row < 0) or (self.mz.dims[0] <= row):
842| raise Exception("Row is out of bounds!")
843| if (col < 0) or (self.mz.dims[1] <= col):
844| raise Exception("Col is out of bounds!")
845| cx = self.pmin[0] + (col * self.HorzSpace)
846| cy = self.pmin[1] + (row * self.VertSpace)
847| self.p0 = (cx,cy)
848| self.p1 = (cx+self.HorzSpace, cy+self.VertSpace)
849|
850| def paint_cell (self, color):
851| """Paint current cell."""
852| self.draw.rectangle([self.p0, self.p1], fill=color, outline=colors.ixColorBlack)
853|
854| def paint_north_wall (self):
855| """Draw north wall in current cell."""
856| self.draw.line([(self.p0[0], self.p0[1]), (self.p1[0], self.p0[1])], fill=self.WallColor, width=2)
857|
858| def paint_south_wall (self):
859| """Draw south wall in current cell."""
860| self.draw.line([(self.p0[0], self.p1[1]), (self.p1[0], self.p1[1])], fill=self.WallColor, width=2)
861|
862| def paint_west_wall (self):
863| """Draw west wall in current cell."""
864| self.draw.line([(self.p0[0], self.p0[1]), (self.p0[0], self.p1[1])], fill=self.WallColor, width=2)
865|
866| def paint_east_wall (self):
867| """Draw east wall in current cell."""
868| self.draw.line([(self.p1[0], self.p0[1]), (self.p1[0], self.p1[1])], fill=self.WallColor, width=2)
869|
870| def show (self):
871| """Display the image using default image viewer."""
872| self.im.show()
873| return self
874|
875| def save (self, fn, mode='GIF'):
876| """Save GIF file."""
877| self.im.save(fn, mode)
878| return self
879|
880| def __str__ (self):
881| """Always implement toString!"""
882| s = '%s (%d,%d) %s'
883| t = (self.im.format, self.im.size[0], self.im.size[1], self.im.mode)
884| return s % t
885|
886| def __repr__ (self):
887| """Return a JSON-like string."""
888| s = '{MazeImageGif:{format:"%s", size:%s, mode:"%s", addr:%x}}'
889| t = (self.im.format, str(self.im.size), self.im.mode, self.__hash__())
890| return s % t
891|
892|
893|
894|
895|
896| class MazeImagePng (object):
897| """Maze Image class.
897|
897| properties:
897| mz - Maze object
897| im - Image object
897| draw - ImageDraw object
897| pixels - Pixel dimensions of image
897| pmin,pmax - ULC,LRC of Maze plot area
897| p0,p1 - ULC,LRC of current cell
897|
897| methods:
897| draw_maze ()
897| show ()
897| save (fn, mode='PNG')
897|
897| set_current_cell (row, col) - required first before using paint methods
897| paint_cell (color) - set cell color
897| paint_north_wall () - set cell north wall
897| paint_east_wall () - set cell east wall
897| paint_south_wall () - set cell south wall
897| paint_west_wall () - set cell west wall
897|
897| str(obj) - properties string
897| repr(obj) - JSON-like string
897|
897| """
898| HorzSpace = 20
899| VertSpace = 20
900| WallColor = colors.ColorBlack
901|
902| def __init__ (self, mz):
903| """Create new Maze Image instance. NOTE: x=cols, y=rows!"""
904| self.mz = mz
905|
906| self.pixels = (self.HorzSpace * (self.mz.dims[1]+2), self.VertSpace * (self.mz.dims[0]+2))
907| self.pmin = (self.HorzSpace, self.VertSpace)
908| self.pmax = (self.pixels[0] - self.HorzSpace, self.pixels[1] - self.VertSpace)
909|
910| self.p0 = (self.pmin[0] , self.pmin[1])
911| self.p1 = (self.pmin[0]+self.HorzSpace, self.pmin[1]+self.VertSpace)
912|
913| self.im = Image.new('RGB', self.pixels, colors.ColorWhite)
914| self.draw = ImageDraw.Draw(self.im)
915|
916| self.draw.rectangle((0,0)+(self.pixels[0]-1,self.pixels[1]-1), outline=colors.ColorBlack)
917| self.draw.rectangle((1,1)+(self.pixels[0]-2,self.pixels[1]-2), outline=colors.ColorGray100)
918| self.draw.rectangle((2,2)+(self.pixels[0]-3,self.pixels[1]-3), outline=colors.ColorGray200)
919|
920| for ix in range(1, self.mz.dims[1]):
921| pp = ix * self.HorzSpace
922| self.draw.line([(self.pmin[0]+pp, self.pmin[1]), (self.pmin[0]+pp, self.pmax[1])], fill=colors.ColorFaintBlue)
923|
924| for ix in range(1, self.mz.dims[0]):
925| pp = ix * self.VertSpace
926| self.draw.line([(self.pmin[0], self.pmin[1]+pp), (self.pmax[0], self.pmin[1]+pp)], fill=colors.ColorFaintBlue)
927|
928|
929|
930|
931|
932|
933|
934|
935| self.draw.line([(self.pmin[0], self.pmin[1]), (self.pmax[0], self.pmin[1])], fill=(192,192,192), width=2)
936| self.draw.line([(self.pmin[0], self.pmax[1]), (self.pmax[0], self.pmax[1])], fill=(192,192,192), width=2)
937| self.draw.line([(self.pmin[0], self.pmin[1]), (self.pmin[0], self.pmax[1])], fill=(192,192,192), width=2)
938| self.draw.line([(self.pmax[0], self.pmin[1]), (self.pmax[0], self.pmax[1])], fill=(192,192,192), width=2)
939|
940| cell_colors = {
941| MazeObject.LockedCell: (63,63,63),
942| MazeObject.EmptyCell: colors.ColorWhite,
943| MazeObject.MazeEntry: colors.ColorGreen,
944| MazeObject.MazeExit: colors.ColorRed,
945| MazeObject.MazePath: (255,239, 63),
946| MazeObject.MazeMarker: (191,255,255),
947| MazeObject.PathMarker: (191,191,191),
948| MazeObject.PathTag: (127,191,255),
949| MazeObject.PathTemp: (207,207,63),
950| }
951|
952| def draw_maze (self):
953| """Draw a maze."""
954|
955| for row in range(self.mz.dims[0]):
956| for col in range(self.mz.dims[1]):
957|
958| v = self.mz.cell(row, col)
959| if 0 < v:
960| c = self.cell_colors[v % len(self.cell_colors)]
961| self.set_current_cell(row, col)
962| self.paint_cell(c)
963|
964| for row in range(self.mz.dims[0]):
965| for col in range(self.mz.dims[1]):
966|
967| self.set_current_cell(row, col)
968|
969| if self.mz.wall_n(row, col):
970| self.paint_north_wall()
971| if self.mz.wall_w(row, col):
972| self.paint_west_wall()
973|
974| if self.mz.wall_e(row, col):
975| self.paint_east_wall()
976|
977| for col in range(self.mz.dims[1]):
978|
979| self.set_current_cell(row, col)
980| if self.mz.wall_s(row, col):
981| self.paint_south_wall()
982|
983| def set_current_cell (self, row, col):
984| """Set current cell for drawing operations."""
985| if (row < 0) or (self.mz.dims[0] <= row):
986| raise Exception("Row is out of bounds!")
987| if (col < 0) or (self.mz.dims[1] <= col):
988| raise Exception("Col is out of bounds!")
989| cx = self.pmin[0] + (col * self.HorzSpace)
990| cy = self.pmin[1] + (row * self.VertSpace)
991| self.p0 = (cx,cy)
992| self.p1 = (cx+self.HorzSpace, cy+self.VertSpace)
993|
994| def paint_cell (self, color):
995| self.draw.rectangle([self.p0, self.p1], fill=color, outline=colors.ColorFaintBlue)
996|
997| def paint_north_wall (self):
998| """Draw north wall in current cell."""
999| self.draw.line([(self.p0[0], self.p0[1]), (self.p1[0], self.p0[1])], fill=self.WallColor, width=3)
1000|
1001| def paint_south_wall (self):
1002| """Draw south wall in current cell."""
1003| self.draw.line([(self.p0[0], self.p1[1]), (self.p1[0], self.p1[1])], fill=self.WallColor, width=3)
1004|
1005| def paint_west_wall (self):
1006| """Draw west wall in current cell."""
1007| self.draw.line([(self.p0[0], self.p0[1]), (self.p0[0], self.p1[1])], fill=self.WallColor, width=3)
1008|
1009| def paint_east_wall (self):
1010| """Draw east wall in current cell."""
1011| self.draw.line([(self.p1[0], self.p0[1]), (self.p1[0], self.p1[1])], fill=self.WallColor, width=3)
1012|
1013| def show (self):
1014| self.im.show()
1015| return self
1016|
1017| def save (self, fn, mode='PNG'):
1018| self.im.save(fn, mode)
1019| return self
1020|
1021| def __str__ (self):
1022| """Always implement toString!"""
1023| s = '%s (%d,%d) %s'
1024| t = (self.im.format, self.im.size[0], self.im.size[1], self.im.mode)
1025| return s % t
1026|
1027| def __repr__ (self):
1028| """Return a JSON-like string."""
1029| s = '{MazeImagePng:{format:"%s", size:%s, mode:"%s", addr:%x}}'
1030| t = (self.im.format, str(self.im.size), self.im.mode, self.__hash__())
1031| return s % t
1032|
1033|
1034|
1035|
1036|
1037| class MazePOV (object):
1038| """Maze POV-Ray Binding class. This class is a Maze Visitor."""
1039| PovCell = '0,\n'
1040| PovPole = '1, <%+f,%+f,%+f>, <%+f,%+f,%+f>,\n'
1041| PovBox = '2, <%+f,%+f,%+f>, <%+f,%+f,%+f>,\n'
1042|
1043| CellSize = 1.0
1044| WallThickness = 0.16 / 2.0
1045| PoleThickness = 0.20 / 2.0
1046| PoleHeight = 1.025
1047|
1048| def __init__ (self, rows, cols):
1049| self.sout = stdout
1050| self.solution = []
1051|
1052| self.mz = MazeObject(rows, cols)
1053| self.mg = MazeGen1(self.mz)
1054| self.mg.generate_maze()
1055| self.mz.print_maze(fp=Log.fp)
1056|
1057| self.ms = MazeSolver(self.mz)
1058| self.ms.solve(self.solution)
1059| self.mz.print_maze(fp=Log.fp)
1060|
1061| def write_data_file (self, filename):
1062| self.sout = open(filename, mode='w', encoding='utf-8')
1063| try:
1064| self.mz.visit_maze(self)
1065| except:
1066| raise
1067| finally:
1068| self.sout.close()
1069| Log.info('wrote: %s' % filename)
1070| pass
1071|
1072| def print_corner (self, row, col):
1073| Log.trace('Corner: %d, %d' % (row,col))
1074| x1 = row-self.PoleThickness
1075| y1 = -0.5
1076| z1 = col-self.PoleThickness
1077| x2 = row+self.PoleThickness
1078| y2 = self.PoleHeight
1079| z2 = col+self.PoleThickness
1080| self.sout.write(self.PovPole % (x1,y1,z1, x2,y2,z2))
1081|
1082| def print_eol (self, row, col):
1083| Log.trace('EOL: %d, %d' % (row,col))
1084| self.sout.write('\n')
1085|
1086| def print_cell (self, row, col, val):
1087| Log.trace('Cell: %d, %d' % (row,col))
1088| self.sout.write(self.PovCell)
1089|
1090| def print_wall_n (self, row, col, val):
1091| Log.trace('Wall.N: %d, %d' % (row,col))
1092| if val == 1:
1093| x1 = row-self.WallThickness
1094| y1 = 0
1095| z1 = col
1096| x2 = row+self.WallThickness
1097| y2 = 1
1098| z2 = col+self.CellSize
1099| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1100| if 1 < val:
1101| x1 = row-self.WallThickness
1102| y1 = 0.8
1103| z1 = col
1104| x2 = row+self.WallThickness
1105| y2 = 1
1106| z2 = col+self.CellSize
1107| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1108|
1109| def print_wall_s (self, row, col, val):
1110| Log.trace('Wall.S: %d, %d' % (row,col))
1111| if val == 1:
1112| x1 = (row+self.CellSize)-self.WallThickness
1113| y1 = 0
1114| z1 = col
1115| x2 = (row+self.CellSize)+self.WallThickness
1116| y2 = 1
1117| z2 = col+self.CellSize
1118| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1119| if 1 < val:
1120| x1 = (row+self.CellSize)-self.WallThickness
1121| y1 = 0.8
1122| z1 = col
1123| x2 = (row+self.CellSize)+self.WallThickness
1124| y2 = 1
1125| z2 = col+self.CellSize
1126| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1127|
1128| def print_wall_w (self, row, col, val):
1129| Log.trace('Wall.W: %d, %d' % (row,col))
1130| if val == 1:
1131| x1 = row
1132| y1 = 0
1133| z1 = col-self.WallThickness
1134| x2 = row+self.CellSize
1135| y2 = 1
1136| z2 = col+self.WallThickness
1137| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1138| if 1 < val:
1139| x1 = row
1140| y1 = 0.8
1141| z1 = col-self.WallThickness
1142| x2 = row+self.CellSize
1143| y2 = 1
1144| z2 = col+self.WallThickness
1145| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1146|
1147| def print_wall_e (self, row, col, val):
1148| Log.trace('Wall.E: %d, %d' % (row,col))
1149| if val == 1:
1150| x1 = row
1151| y1 = 0
1152| z1 = (col+self.CellSize)-self.WallThickness
1153| x2 = row+self.CellSize
1154| y2 = 1
1155| z2 = (col+self.CellSize)+self.WallThickness
1156| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1157| if 1 < val:
1158| x1 = row
1159| y1 = 0.8
1160| z1 = (col+self.CellSize)-self.WallThickness
1161| x2 = row+self.CellSize
1162| y2 = 1
1163| z2 = (col+self.CellSize)+self.WallThickness
1164| self.sout.write(self.PovBox % (x1,y1,z1, x2,y2,z2))
1165|
1166| def print_start (self, obj):
1167| Log.debug('START')
1168|
1169| def print_end (self):
1170| Log.debug('END')
1171| self.sout.write('3,%d,' % len(self.solution))
1172| for t in self.solution:
1173| self.sout.write('<%f,0,%f>,' % (t[0],t[1]))
1174| self.sout.write('\n')
1175|
1176| self.sout.write('\n99\n')
1177| self.sout.flush()
1178|
1179|
1180|
1181|
1182|
1183| class MazeXML (MazeNavigator):
1184| """Maze XML Binding class.
1184|
1184| methods:
1184| get_xml - get row/col XML (emits maze in any state)
1184| get_xml_paths - get maze path XML (requires generated maze)
1184|
1184| internal methods:
1184| travel_maze - travels all maze paths [RECURSIVE!]
1184|
1184| ATTN: This is probably broken now.
1184| """
1185| XmlHeader = r'<?xml version="1.0" encoding="UTF-8"?>'
1186| XmlDocument = r'<document application="Maze" type="%s">'
1187| XmlDocEnd = r'</document>'
1188|
1189| XmlRow0 = r'<row index="%d">'
1190| XmlRow1 = r'</row>'
1191| XmlCell = r'<cell row="%d" col="%d" val="%d" />'
1192| XmlWall = r'<wall row="%d" col="%d" val="%d" />'
1193|
1194| def __init__ (self, mz, row=0, col=0):
1195| super().__init__(mz, row, col)
1196|
1197| def get_xml (self):
1198| a = []
1199| a.append(self.XmlHeader)
1200| a.append(self.XmlDocument % 'Cell Dump')
1201| a.append('<property type="comment" text="Maze Dump..." />')
1202|
1203|
1204| a.append('<cells rows="%d" cols="%d">' % (self.mz.rows(), self.mz.cols()))
1205| for rx,row in enumerate(self.mz.cells):
1206| a.append(self.XmlRow0 % rx)
1207| for cx,cell in enumerate(row):
1208| t = (rx, cx, cell)
1209| a.append(self.XmlCell % t)
1210| a.append(self.XmlRow1)
1211| a.append('</cells>')
1212|
1213|
1214| a.append('<ns_walls rows="%d" cols="%d">' % (len(self.mz.ns_walls), len(self.mz.ns_walls[0])))
1215| for rx,row in enumerate(self.mz.ns_walls):
1216| a.append(self.XmlRow0 % rx)
1217| for cx,cell in enumerate(row):
1218| t = (rx, cx, cell)
1219| a.append(self.XmlWall % t)
1220| a.append(self.XmlRow1)
1221| a.append('</ns_walls>')
1222|
1223|
1224| a.append('<we_walls rows="%d" cols="%d">' % (len(self.mz.we_walls), len(self.mz.we_walls[0])))
1225| for rx,row in enumerate(self.mz.we_walls):
1226| a.append(self.XmlRow0 % rx)
1227| for cx,cell in enumerate(row):
1228| t = (rx, cx, cell)
1229| a.append(self.XmlWall % t)
1230| a.append(self.XmlRow1)
1231| a.append('</we_walls>')
1232|
1233| a.append(self.XmlDocEnd)
1234| return '\n'.join(a)
1235|
1236| def get_xml_paths (self):
1237| a = []
1238| a.append(self.XmlHeader)
1239| a.append(self.XmlDocument % 'Maze Paths')
1240| a.append('<property type="comment" text="Maze Tree..." />')
1241| t = []
1242| self.reset_to_entry()
1243| self.travel_maze(t, a)
1244| a.append(self.XmlDocEnd)
1245| return '\n'.join(a)
1246|
1247| def travel_maze (self, maze_path, buff):
1248| """Export Maze path tree. NOTE: Maze must be created! [RECURSIVE!]"""
1249| Log.trace('Node: [%d,%d] (%s)' % (self.curr_row, self.curr_col, self.Abbrev[self.direction]))
1250|
1251| buff.append('<node row="%d" col="%d" val="%d">' % (self.curr_row, self.curr_col, self.get_curr_cell()))
1252|
1253| if self.curr_row or self.curr_col:
1254| self.set_curr_cell(MazeObject.PathMarker)
1255|
1256|
1257| if self.get_left_wall() == 0:
1258| Log.trace('[%d,%d] (%s) turn left' % (self.curr_row, self.curr_col, self.Abbrev[self.direction]))
1259| t = (self.curr_row, self.curr_col, self.direction)
1260| self.turn_left()
1261| self.move_to_next_cell()
1262| maze_path.append(t)
1263|
1264| rv = self.travel_maze(maze_path, buff)
1265| self.curr_row, self.curr_col, self.direction = maze_path.pop()
1266|
1267|
1268| if self.get_next_wall() == 0:
1269| Log.trace('[%d,%d] (%s) go straight' % (self.curr_row, self.curr_col, self.Abbrev[self.direction]))
1270| t = (self.curr_row, self.curr_col, self.direction)
1271| self.move_to_next_cell()
1272| maze_path.append(t)
1273|
1274| rv = self.travel_maze(maze_path, buff)
1275| self.curr_row, self.curr_col, self.direction = maze_path.pop()
1276|
1277|
1278| if self.get_right_wall() == 0:
1279| Log.trace('[%d,%d] (%s) turn right' % (self.curr_row, self.curr_col, self.Abbrev[self.direction]))
1280| t = (self.curr_row, self.curr_col, self.direction)
1281| self.turn_right()
1282| self.move_to_next_cell()
1283| maze_path.append(t)
1284|
1285| rv = self.travel_maze(maze_path, buff)
1286| self.curr_row, self.curr_col, self.direction = maze_path.pop()
1287|
1288| Log.trace('Node Exit')
1289| buff.append('</node>')
1290|
1291|
1292|
1293|
1294| """eof"""
1295|