-
Notifications
You must be signed in to change notification settings - Fork 14
/
MazeGenerator.java
94 lines (82 loc) · 2.75 KB
/
MazeGenerator.java
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
import java.util.ArrayList;
import java.util.Stack;
import java.util.Random;
import java.util.Arrays;
class MazeGenerator {
private Stack<Node> stack = new Stack<>();
private Random rand = new Random();
private int[][] maze;
private int dimension;
MazeGenerator(int dim) {
maze = new int[dim][dim];
dimension = dim;
}
public void generateMaze() {
stack.push(new Node(0,0));
while (!stack.empty()) {
Node next = stack.pop();
if (validNextNode(next)) {
maze[next.y][next.x] = 1;
ArrayList<Node> neighbors = findNeighbors(next);
randomlyAddNodesToStack(neighbors);
}
}
}
public String getRawMaze() {
StringBuilder sb = new StringBuilder();
for (int[] row : maze) {
sb.append(Arrays.toString(row) + "\n");
}
return sb.toString();
}
public String getSymbolicMaze() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dimension; i++) {
for (int j = 0; j < dimension; j++) {
sb.append(maze[i][j] == 1 ? "*" : " ");
sb.append(" ");
}
sb.append("\n");
}
return sb.toString();
}
private boolean validNextNode(Node node) {
int numNeighboringOnes = 0;
for (int y = node.y-1; y < node.y+2; y++) {
for (int x = node.x-1; x < node.x+2; x++) {
if (pointOnGrid(x, y) && pointNotNode(node, x, y) && maze[y][x] == 1) {
numNeighboringOnes++;
}
}
}
return (numNeighboringOnes < 3) && maze[node.y][node.x] != 1;
}
private void randomlyAddNodesToStack(ArrayList<Node> nodes) {
int targetIndex;
while (!nodes.isEmpty()) {
targetIndex = rand.nextInt(nodes.size());
stack.push(nodes.remove(targetIndex));
}
}
private ArrayList<Node> findNeighbors(Node node) {
ArrayList<Node> neighbors = new ArrayList<>();
for (int y = node.y-1; y < node.y+2; y++) {
for (int x = node.x-1; x < node.x+2; x++) {
if (pointOnGrid(x, y) && pointNotCorner(node, x, y)
&& pointNotNode(node, x, y)) {
neighbors.add(new Node(x, y));
}
}
}
return neighbors;
}
private Boolean pointOnGrid(int x, int y) {
return x >= 0 && y >= 0 && x < dimension && y < dimension;
}
private Boolean pointNotCorner(Node node, int x, int y) {
return (x == node.x || y == node.y);
}
private Boolean pointNotNode(Node node, int x, int y) {
return !(x == node.x && y == node.y);
}
}