-
Notifications
You must be signed in to change notification settings - Fork 0
/
maze-gen-two.awk
executable file
·77 lines (68 loc) · 2.14 KB
/
maze-gen-two.awk
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
#!/usr/bin/env gawk -f
#
# Copyright (c) 2023 Jegors Čemisovs
# License: MIT License
# Repository: https://github.com/rabestro/awk-maze-generator
#
# These variables are initialized on the command line (using '-v'):
# - Rows
# - Cols
# - Seed (optional)
BEGIN {
OFS = ""
Rows = Rows ? Rows : 8
Cols = Cols ? Cols : 16
Seed ? srand(Seed) : srand()
Width = 2 * Cols + 1
Height = 2 * Rows + 1
create_grid()
generate_maze(1, 1)
arrange_doors()
print_maze()
}
function create_grid( row, col) {
for (row = 0; row < Height; row++)
for (col = 0; col < Width; col++)
Grid[row, col] = 1
}
function print_maze( row, col) {
for (row = 0; row < Height; row++) {
for (col = 0; col < Width; col++)
$(col + 1) = symbol(row, col)
print
}
}
# Recursive backtracking algorithm
function generate_maze(row, col, directions,randDir,dx,dy,newRow,newCol) {
Grid[row, col] = 0
directions = "NESW"
while (length(directions) > 0) {
randDir = substr(directions, int(rand() * length(directions)) + 1, 1)
sub(randDir, "", directions)
dx = dy = 0
if (randDir == "N") dy = -2
if (randDir == "E") dx = 2
if (randDir == "S") dy = 2
if (randDir == "W") dx = -2
newRow = row + dy
newCol = col + dx
if (newRow > 0 && newRow < Height && newCol > 0 && newCol < Width && Grid[newRow, newCol]) {
Grid[row + dy / 2, col + dx / 2] = 0
generate_maze(newRow, newCol)
}
}
}
function arrange_doors() {
MazeEntrance = 1 + 2 * int(rand() * Rows)
MazeExit = 1 + 2 * int(rand() * Rows)
}
function symbol(row, col, n,e,s,w) {
if (!Grid[row, col]) return " "
if (is_door(row, col)) return "⇨"
n = row ? Grid[row - 1, col] : 0
e = col < Width - 1 ? Grid[row, col + 1] : 0
s = row < Height - 1 ? Grid[row + 1, col] : 0
w = col ? Grid[row, col - 1] : 0
return substr(" │─└││┌├─┘─┴┐┤┬┼", 1 + n + 2 * e + 4 * s + 8 * w, 1)
}
function is_door(row, col) {return row == MazeEntrance && col == 0 || row == MazeExit && col == Width - 1}