-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaze.py
More file actions
137 lines (107 loc) · 2.62 KB
/
maze.py
File metadata and controls
137 lines (107 loc) · 2.62 KB
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
# This program creates a maze by backtracking
from itertools import product, repeat, islice, tee, chain
import random
random.seed(100)
# Generate the pairings
NC = 12
NR = 12
N = NC * NR
def groups(it, n):
return zip(*([iter(it)] * n))
def pairwise(k):
a, b = tee(k)
next(b)
return zip(a, b)
indexes = list(groups(range(N), NC))
row_edges = chain(*map(pairwise, indexes))
col_edges = chain(*map(pairwise, zip(*indexes)))
edges = list(chain(row_edges, col_edges))
nodes = [[] for i in range(N)]
for a, b in edges:
nodes[b].append(a)
nodes[a].append(b)
connectivity = list(map(list, nodes))
#lolnodes = list(list(i) for i in nodes)
stack = []
to_visit = N - 1
visited = [False] * N
current = random.randrange(N)
while to_visit:
node = nodes[current]
neighbours = [n for n in node if not visited[n]]
if not visited[current]:
visited[current] = True
to_visit -= 1
if neighbours:
n = random.choice(neighbours)
nodes[n].remove(current)
node.remove(n)
stack.append(current)
current = n
elif stack:
current = stack.pop()
import turtle
t = turtle.Turtle()
points = list(product(range(NC), range(NR)))
def draw_maze():
t.speed(0)
turtle.tracer(10, 25)
t.pensize(3)
t.penup()
t.goto(0, 0)
t.pendown()
t.goto(20 * NC, 0)
t.goto(20 * NC, 20 * NR)
t.goto(0, 20 * NR)
t.goto(0, 0)
for i, ns in enumerate(nodes):
y1, x1 = points[i]
for n in (n for n in ns if n > i):
y2, x2 = points[n]
t.penup()
if n == i + 1:
t.goto(20 * x2, 20 * y1)
t.pendown()
t.goto(20 * x2, 20 * (y1 + 1))
else:
t.goto(20 * x1, 20 * y2)
t.pendown()
t.goto(20 * (x1 + 1), 20 * y2)
draw_maze()
start = random.randrange(N)
end = random.randrange(N)
y1, x1 = points[start]
y2, x2 = points[end]
t.penup()
t.goto(10 + 20 * x1, 10 + 20 * y1)
t.dot()
t.goto(10 + 20 * x2, 10 + 20 * y2)
t.dot()
t.penup()
t.goto(10 + 20 * x1, 10 + 20 * y1)
t.pencolor(1, 0, 0)
turtle.tracer(1)
t.speed(3)
t.pendown()
t.pensize(1)
DIRS = [+1, -NC, -1, +NC]
current, d = start, 0
t.seth(0)
def rt():
global d
t.rt(90)
d = (d + 1) % 4
def lt():
global d
t.lt(90)
d = (d - 1) % 4
def check():
nxt = (current + DIRS[d])
return nxt in connectivity[current] and nxt not in nodes[current]
def fd():
# Check if we can go forwards
global current
nxt = (current + DIRS[d])
if nxt in connectivity[current] and nxt not in nodes[current]:
current = nxt
t.fd(20)