forked from steciuk/PSZT-maze-solver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maze.py
301 lines (246 loc) · 11.6 KB
/
maze.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# df_maze.py
import random
from collections import defaultdict
class Cell:
"""A cell in the maze.
A maze "Cell" is a point in the grid which may be surrounded by walls to
the north, east, south or west.
"""
# A wall separates a pair of cells in the N-S or W-E directions.
wall_pairs = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}
def __init__(self, x, y):
"""Initialize the cell at (x,y). At first it is surrounded by walls."""
self.x, self.y = x, y
self.walls = {'N': True, 'S': True, 'E': True, 'W': True}
def __repr__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def has_all_walls(self):
"""Does this cell still have all its walls?"""
return all(self.walls.values())
def knock_down_wall(self, other, wall):
"""Knock down the wall between cells self and other."""
self.walls[wall] = False
other.walls[Cell.wall_pairs[wall]] = False
class Maze:
"""A Maze, represented as a grid of cells."""
num_map = []
graph = defaultdict(list)
path = None
def __init__(self, nx, ny, ix=0, iy=0, seed=None, one_route=True, wall_knock=0.25, from_file=False):
"""Initialize the not seeded maze grid.
The maze consists of nx x ny cells and will be constructed starting
at the cell indexed at (ix, iy).
"""
self.nx, self.ny = nx, ny
self.ix, self.iy = ix, iy
self.one_route = one_route
self.wall_knock = wall_knock
self.maze_map = [[Cell(x, y) for x in range(nx)] for y in range(ny)]
"""It only make sense to define 4 states for each cell, remembering state of two of its walls, cause adjacent
cells will store information about remaining walls.
__ __ -- --
| | - 0 | - 1 | | - 2 | - 3
-- --
"""
if seed is not None:
random.seed(seed)
if not from_file:
self.make_maze()
self.generate_graph()
@classmethod
def from_file(cls, filename):
"""Initialize maze from a file"""
try:
with open(filename, 'r') as f:
lines = f.read().splitlines()
num_map = [[x for x in line] for line in lines]
except:
print("There's no such file as {}! Maybe you wrote the name wrong?\n".format(filename))
return None
else:
maze = cls(len(num_map[0]), len(num_map), from_file=True)
maze.num_map = num_map
maze.maze_from_num_map()
maze.generate_graph()
return maze
# for testing
def print_cords(self):
for row in self.maze_map:
for cell in row:
print(str(cell.x) + ',' + str(cell.y), ' ', end='')
print()
def find_neighbours(self, cell):
"""Returns a list of neighbours you can move to"""
delta = [('E', (1, 0)), ('S', (0, 1)), ('W', (-1, 0)), ('N', (0, -1))]
neighbours = []
for direction, (dx, dy) in delta:
x2, y2 = cell.x + dx, cell.y + dy
if (0 <= x2 < self.nx) and (0 <= y2 < self.ny):
neighbour = self.cell_at(x2, y2)
neighbours.append((direction, neighbour))
return neighbours
def generate_graph(self):
"""Generates a graph representing the maze Dictionary<(Cell, set<Cell>)>"""
for row in self.maze_map:
for cell in row:
for neighbour in self.find_neighbours(cell):
if not cell.walls[neighbour[0]]:
if neighbour[1] not in self.graph[cell]:
self.graph[cell].append(neighbour[1])
def maze_from_num_map(self):
"""Generate cellular maze structure from a number map"""
for row in self.maze_map:
for cell in row:
state = self.num_map[cell.y][cell.x]
if state == '1':
cell.knock_down_wall(self.cell_at(cell.x + 1, cell.y), 'E')
elif state == '2':
cell.knock_down_wall(self.cell_at(cell.x, cell.y + 1), 'S')
elif state == '3':
cell.knock_down_wall(self.cell_at(cell.x + 1, cell.y), 'E')
cell.knock_down_wall(self.cell_at(cell.x, cell.y + 1), 'S')
def generate_num_map(self):
"""Generate number map from the cellular maze structure"""
for row in self.maze_map:
rowlist = []
for cell in row:
if not cell.walls['E'] and not cell.walls['S']:
rowlist.append('3')
elif not cell.walls['S']:
rowlist.append('2')
elif not cell.walls['E']:
rowlist.append('1')
else:
rowlist.append('0')
self.num_map.append(rowlist)
def generate_txt_save(self, filename):
"""Write nummap to a file"""
if not self.num_map:
self.generate_num_map()
with open(filename, 'w') as f:
f.write('\n'.join(map(''.join, self.num_map)))
def cell_at(self, x, y):
"""Return the Cell object at (x,y)."""
return self.maze_map[y][x]
def __str__(self):
"""Return a (crude) string representation of the maze."""
maze_rows = ['-' * self.nx * 2]
for y in range(self.ny):
maze_row = ['|']
for x in range(self.nx):
if self.maze_map[y][x].walls['E']:
maze_row.append(' |')
else:
maze_row.append(' ')
maze_rows.append(''.join(maze_row))
maze_row = ['|']
for x in range(self.nx):
if self.maze_map[y][x].walls['S']:
maze_row.append('-+')
else:
maze_row.append(' +')
maze_rows.append(''.join(maze_row))
return '\n'.join(maze_rows)
def write_svg(self, filename):
"""Write an SVG image of the maze to filename."""
aspect_ratio = self.nx / self.ny
# Pad the maze all around by this amount.
padding = 10
# Height and width of the maze image (excluding padding), in pixels
height = 500
width = int(height * aspect_ratio)
# Scaling factors mapping maze coordinates to image coordinates
scy, scx = height / self.ny, width / self.nx
def write_wall(ww_f, ww_x1, ww_y1, ww_x2, ww_y2):
"""Write a single wall to the SVG image file handle f."""
print('<line x1="{}" y1="{}" x2="{}" y2="{}"/>'
.format(ww_x1, ww_y1, ww_x2, ww_y2), file=ww_f)
def write_square(ww_f, ww_x1, ww_y1, ww_x2, ww_y2):
"""Write a single square for found path"""
print('<rect x="{}" y="{}" width="{}" height="{}"/>'
.format(ww_x1, ww_y1, ww_x2, ww_y2), file=ww_f)
# Write the SVG image file for maze
with open(filename, 'w') as f:
# SVG preamble and styles.
print('<?xml version="1.0" encoding="utf-8"?>', file=f)
print('<svg xmlns="http://www.w3.org/2000/svg"', file=f)
print(' xmlns:xlink="http://www.w3.org/1999/xlink"', file=f)
print(' width="{:d}" height="{:d}" viewBox="{} {} {} {}">'
.format(width + 2 * padding, height + 2 * padding,
-padding, -padding, width + 2 * padding, height + 2 * padding),
file=f)
print('<defs>\n<style type="text/css"><![CDATA[', file=f)
print('line {', file=f)
print(' stroke: #000000;\n stroke-linecap: square;', file=f)
print(' stroke-width: 2;\n}', file=f)
print('rect {', file=f)
print(' fill: #cc0000;\n}', file=f)
print(']]></style>\n</defs>', file=f)
if self.path is not None:
edge_cell = self.path.pop(0)
print('<rect x="{}" y="{}" width="{}" height="{}" style="fill: #00cc00"/>'
.format(edge_cell.x * scx, edge_cell.y * scy, scx + 1, scy + 1), file=f)
edge_cell = self.path.pop()
print('<rect x="{}" y="{}" width="{}" height="{}" style="fill: #0000cc"/>'
.format(edge_cell.x * scx, edge_cell.y * scy, scx + 1, scy + 1), file=f)
for cell in self.path:
x1, y1, h, w = cell.x * scx, cell.y * scy, scx + 1, scy + 1
write_square(f, x1, y1, h, w)
# Draw the "South" and "East" walls of each cell, if present (these
# are the "North" and "West" walls of a neighbouring cell in
# general, of course).
for x in range(self.nx):
for y in range(self.ny):
if self.cell_at(x, y).walls['S']:
x1, y1, x2, y2 = x * scx, (y + 1) * scy, (x + 1) * scx, (y + 1) * scy
write_wall(f, x1, y1, x2, y2)
if self.cell_at(x, y).walls['E']:
x1, y1, x2, y2 = (x + 1) * scx, y * scy, (x + 1) * scx, (y + 1) * scy
write_wall(f, x1, y1, x2, y2)
# Draw the North and West maze border, which won't have been drawn
# by the procedure above.
print('<line x1="0" y1="0" x2="{}" y2="0"/>'.format(width), file=f)
print('<line x1="0" y1="0" x2="0" y2="{}"/>'.format(height), file=f)
print('</svg>', file=f)
def find_unvisited_neighbours(self, cell):
"""Return a list of unvisited neighbours to cell."""
delta = [('E', (1, 0)),
('S', (0, 1)),
('W', (-1, 0)),
('N', (0, -1))]
neighbours = []
for direction, (dx, dy) in delta:
x2, y2 = cell.x + dx, cell.y + dy
if (0 <= x2 < self.nx) and (0 <= y2 < self.ny):
neighbour = self.cell_at(x2, y2)
if neighbour.has_all_walls():
neighbours.append((direction, neighbour))
return neighbours
def make_maze(self):
"""Generates a maze for constructed maze object"""
# Total number of cells.
n = self.nx * self.ny
cell_stack = []
current_cell = self.cell_at(self.ix, self.iy)
# Total number of visited cells during maze construction.
nv = 1
while nv < n:
neighbours = self.find_unvisited_neighbours(current_cell)
if not neighbours:
# We've reached a dead end: backtrack.
current_cell = cell_stack.pop()
continue
# Choose a random neighbouring cell and move to it.
direction, next_cell = random.choice(neighbours)
current_cell.knock_down_wall(next_cell, direction)
cell_stack.append(current_cell)
current_cell = next_cell
nv += 1
if not self.one_route:
for x in range(self.nx):
for y in range(self.ny):
if random.uniform(0, 1) < self.wall_knock:
current_cell = self.cell_at(x, y)
neighbours = self.find_neighbours(current_cell)
neighbour_to_knock = random.choice(neighbours)
current_cell.knock_down_wall(neighbour_to_knock[1], neighbour_to_knock[0])