-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlabyrinth_generator.py
92 lines (65 loc) · 1.89 KB
/
labyrinth_generator.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
#!/usr/bin/env python
# coding=utf-8
#
# Python Script
#
# Copyleft © Manoel Vilela
#
#
from __future__ import print_function
from random import shuffle, randrange
WIDTH, HEIGHT = 12, 14
def make_maze(w=WIDTH, h=HEIGHT):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
nowalls = []
def walk(x, y):
vis[x][y] = 1
d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
shuffle(d)
for (x_n, y_n) in d:
if vis[x_n][y_n]:
continue
nowalls.append((x, y, x_n, y_n))
walk(x_n, y_n)
walk(randrange(h), randrange(w))
return(nowalls)
def draw_maze(nowalls, w=WIDTH, h=HEIGHT):
ver = [["| "] * w + ['|'] for _ in range(h)] + [[]]
hor = [["+--"] * w + ['+'] for _ in range(h + 1)]
for (x, y, x_n, y_n) in nowalls:
# print(x, y, x_n, y_n)
if x_n == x:
ver[x][max(y, y_n)] = " "
if y_n == y:
hor[max(x, x_n)][y] = "+ "
arrange = []
for (a, b) in zip(hor, ver):
l = ''.join(a + ['\n'] + b).split('\n')
arrange.extend(l)
return arrange
def random_replace(maze, block):
from random import randint
x, y = randint(1, len(maze) - 2), randint(0, len(maze[0]) - 1)
print('Random end: ', x, y)
if maze[x][y] == ' ':
maze[x] = maze[x][:y] + block + maze[x][y + 1:]
else:
maze = random_replace(maze, block)
return maze
def translate(maze):
from re import sub
return [sub(r'[\-\+\|]', 'W', x) for x in maze]
def draw(maze):
for x, line in enumerate(maze):
print('{:>2}'.format(x), line)
def generate(blocks='EPC'):
nw = make_maze()
maze = draw_maze(nw)
# nwabs = nowallsabs(nw)
for block in blocks:
maze = random_replace(maze, block)
draw(maze)
translated = translate(maze)
return translated
if __name__ == '__main__':
generate()