-
Notifications
You must be signed in to change notification settings - Fork 0
/
maze.py
228 lines (175 loc) · 6.19 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
import random
import sys
import os
import time
import argparse
directions = ["N", "S", "E", "W"]
backmap = {"N":"S", "S":"N", "E":"W", "W":"E"}
ANIMATE = False
DEBUG = False
def clear():
""" cler
clear the screen
"""
# for windows
if os.name == 'nt':
_ = os.system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = os.system('clear')
def key_string(a):
""" key_string
The key_string function turns a [row,column] pair into a string
Args:
a (list): A [row,column] pair
Returns:
str: a string of the form "row,col"
"""
return str(a[0])+","+str(a[1])
def connect_neighbors(maze, this_cell, width, height):
""" connect_neighbors
The connect_neighbors function recursively deletes walls between cells
Args:
maze (dict): The maze itself
this_cell (list): A [row, column] coordinate pair
width (int): The width of the maze
height(int): The height of the maze
Returns:
dict: The maze
"""
if ANIMATE: print_maze(maze, width, height)
this_cell_key = key_string(this_cell)
row = this_cell[0]
col = this_cell[1]
# Mark this cell as visited
maze[this_cell_key]["Visited"] = True
#No? We have to process it then.
#Let's randomize our directions
random.shuffle(directions)
for n in directions:
do_next = False
if n == "N":
next_cell = [row-1, col]
elif n == "S":
next_cell = [row+1, col]
elif n == "E":
next_cell = [row, col+1]
elif n == "W":
next_cell = [row, col-1]
else:
# This is not possible. The code must never reach this point
print("Random direction chosen that is not N, S, E, or W: "+n, file=sys.stderr)
exit(1)
next_cell_key = key_string(next_cell)
if next_cell_key in maze:
if maze[next_cell_key]["Visited"] == True: continue
# Erase wall
maze[this_cell_key][n] = False
maze[next_cell_key][backmap[n]] = False
# Process next cell
if DEBUG: print(n+":"+ this_cell_key + " -> "+next_cell_key+ " "+str(maze[this_cell_key])+" -> "+str(maze[next_cell_key]))
connect_neighbors(maze, next_cell, width, height)
def make_maze(width, height):
""" make_maze
The make_maze function makes a maze.
The maze is a dictionary. Each element of the dictionary is a cell.
The key of each entry is the x,y location of the cell
Args:
width (int): The width of the maze
height(int): The height of the maze
Returns:
dict: The maze
"""
# Create an empty dictionary to hold the maze
ret_maze = {}
# Fill the matrix with fully walled cells
for row in range(height):
for col in range(width):
ret_maze[key_string([row,col])] = {"Visited": False, "N" : True, "S" : True, "E" : True, "W" : True}
# Start recursive exploration
random_cell = [random.randrange(height), random.randrange(width)]
if DEBUG: print("Starting with "+str(random_cell))
# This generates the complete matrix
connect_neighbors(ret_maze, random_cell, width, height)
# Opening in upper left
ret_maze[key_string([0,0])]["W"] = False
if ANIMATE: print_maze(ret_maze, width, height)
# Opening in lower right
ret_maze[key_string([height-1,width-1])]["E"] = False
if ANIMATE: print_maze(ret_maze, width, height)
return ret_maze
def print_maze(maze, width, height):
""" print_maze
The make_maze function makes a maze.
The maze is a dictionary. Each element of the dictionary is a cell.
The key of each entry is the x,y location of the cell
Args:
maze (dict): The maze itself
width (int): The width of the maze
height(int): The height of the maze
Returns:
-
"""
# Clear the screen
clear()
#Print the very top of the maze, which always has a boundary
for col in range(width):
if maze[key_string([0, col])]["N"] == True:
print("__", end="")
else:
print(" ", end="")
print("_")
# Print the rest of the maze
for row in range(height):
for col in range(width):
this_cell_key = key_string([row,col])
if maze[this_cell_key]["W"] == True:
print("|", end="")
else:
if row == height-1:
print("_", end="")
else:
print(" ", end="")
if maze[this_cell_key]["S"] == True:
print("_", end="")
else:
print(" ", end="")
if maze[key_string([row, width-1])]["E"] == True:
print("|")
else:
print(" ")
# If we are animating, everything needs to finish printing right now
sys.stdout.flush()
if ANIMATE: time.sleep(0.2)
def main(width, height, animation, random_seed):
random.seed(random_seed)
global ANIMATE
if animation: ANIMATE = True
# Make the maze
maze = make_maze(width, height)
# Print the maze
print_maze(maze, width, height)
if __name__ == "__main__":
#Set up defaults
width = 30
height = 30
animate = False
random_seed = time.time()
# Command-line options
parser = argparse.ArgumentParser()
parser.add_argument("-W", "--width", type = int, help = "width of maze")
parser.add_argument("-H", "--height", type = int, help = "height of maze")
parser.add_argument("-A", "--ANIMATE", action = "store_true", help="turn on animation of maze generation process")
parser.add_argument("-s", "--seed", type = int, help = "random seed")
parser.add_argument("-d", "--debug", action = "store_true", help= "turn on debug strings")
args = parser.parse_args()
#Set up arguments to call main
if args.ANIMATE: animate=True
if args.width != None and args.width > 0:
width = args.width
if args.height != None and args.height > 0:
height = args.height
if args.seed != None and args.seed > 0:
random_seed = args.seed
if args.debug: DEBUG = True
main(width, height, animate, random_seed)