-
Notifications
You must be signed in to change notification settings - Fork 1
/
maze.py
119 lines (90 loc) · 2.82 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
import random
import sys
from collections import deque
sys.setrecursionlimit(10**6)
HEIGHT, WIDTH = 19, 19
# Make a pathway outline of the maze.
# "0": open
# "11": wall
maze = [["0"]*WIDTH]
for _ in range(HEIGHT-2):
m = ["0"] + ["11"]*(WIDTH - 2) + ["0"]
maze.append(m)
maze.append(["0"]*WIDTH)
dx = [(1, 2), (-1, -2), (0, 0), (0, 0)] # x-axis vector
dy = [(0, 0), (0, 0), (1, 2), (-1, -2)] # y-axis vector
def make_maze(y, x):
array = list(range(4))
random.shuffle(array) # Randomly decide on a preferred direction
for i in array:
# Two squares ahead
nx = x + dx[i][1]
ny = y + dy[i][1]
if ny < 1 or ny >= HEIGHT: # outside the map
continue
if nx < 1 or nx >= WIDTH: # outside the map
continue
if maze[ny][nx] == "0": # Two squares ahead of you are already open
continue
for j in range(2): # dig a path
ax = x + dx[i][j]
ay = y + dy[i][j]
maze[ay][ax] = "0"
make_maze(ny, nx) # Move to the point where you dug.
def get_random_start():
sx = random.randint(1, WIDTH)
# sx, sy must be odd
sx = sx if sx % 2 == 1 else sx-1
sy = 1
return sx, sy
def get_goal(sx, sy):
q = deque([(sy, sx)])
gy, gx = 1, 1 # goal positioon
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
# array with the distances of each square
# distance is -1 if not visited
dist = [[-1]*WIDTH for _ in range(HEIGHT)]
dist[sy][sx] = 0
max_dist = 0 # the longest distance
while q:
y, x = q.popleft() # Retrieving an element from the top
for i in range(4):
ny = y+dy[i]
nx = x+dx[i]
if ny <= 0 or nx <= 0 or ny >= HEIGHT or nx >= WIDTH:
continue
if maze[ny][nx] == "11":
continue
# Update the distance if you haven't visited yet
if dist[ny][nx] == -1:
q.append((ny, nx))
dist[ny][nx] = dist[y][x]+1
if max_dist < dist[ny][nx]: # update the longest distance
gy, gx = ny, nx
max_dist = dist[ny][nx]
return gx, gy
def main():
# make a maze
sx, sy = get_random_start()
maze[sy][sx] = "0"
make_maze(sy, sx)
maze[sy][sx] = "15" # player is at start
# Replace a pathway to a wall outline of the maze.
for i in range(WIDTH):
maze[0][i] = "11"
maze[HEIGHT-1][i] = "11"
for j in range(HEIGHT):
maze[j][0] = "11"
maze[j][-1] = "11"
# set a goal
gx, gy = get_goal(sx, sy)
maze[gy][gx] = "8"
# write data to text file
with open("maze.txt", "w") as f:
for m in maze:
row = ", ".join(m)
row += "\n"
f.write(row)
if __name__ == "__main__":
main()