Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.lang.Math;
- public class RecursiveGen {
- private boolean[][][] maze;
- private ArrayList<int[]> stack;
- private int[] currentPos;
- private int w, h;
- private int totalCells;
- public RecursiveGen(int w, int h) {
- this.w = w;
- this.h = h;
- init();
- }
- private static int[][] dirTab = {
- {0, -1},
- {1, 0},
- {0, 1},
- {-1, 0}
- };
- public void init() {
- maze = new boolean[w][h][4];
- for (int i = 0; i < w; i++) {
- for (int v = 0; v < h; v++) {
- for (int n = 0; n < 4; n++) {
- maze[i][v][n] = true;
- }
- }
- }
- stack = new ArrayList<int[]>();
- currentPos = new int[] {0, 0};
- stack.add(currentPos);
- }
- public boolean[][][] step() {
- //System.out.println(currentPos[0] + ":" + currentPos[1]);
- int[] availableCells = getAvailableCells(currentPos, maze);
- if (availableCells.length > 0) {
- stack.add(currentPos);
- int choice = availableCells[random(0, availableCells.length - 1)];
- removeWalls(currentPos, choice, maze);
- totalCells++;
- currentPos = addCoords(currentPos, dirTab[choice]);
- //System.out.println(currentPos[0] + ":" + currentPos[1]);
- } else {
- currentPos = stack.remove(stack.size()-1);
- //System.out.println(" <=" + currentPos[0] + ":" + currentPos[1]);
- }
- //System.out.println(stack.size());
- return maze;
- }
- public boolean checkCompleted() {
- return (stack.size() == 0);
- }
- public int getProgress() {
- return (int)((totalCells*1f/w*h)/100+.5f);
- }
- public boolean[][][] getMaze() {
- return maze;
- }
- private int[] getAvailableCells(int[] pos, boolean[][][] m) {
- ArrayList<Integer> options = new ArrayList<Integer>();
- if (!(pos[0] == m.length-1 && pos[1] == m[0].length-1)) {
- for (int i = 0; i < 4; i++) {
- if (!cellUsed(addCoords(pos, dirTab[i]), m)) {
- options.add(i);
- }
- }
- } else {
- m[m.length-1][m[0].length-1][2] = false;
- //System.out.println("----====End Located====----");
- }
- int[] result = new int[options.size()];
- for (int i = 0; i < result.length; i++) {
- result[i] = options.get(i);
- }
- return result;
- }
- private void removeWalls(int[] pos, int dir, boolean[][][] m) {
- m[pos[0]][pos[1]][dir] = false;
- int[] nPos = addCoords(pos, dirTab[dir]);
- //m[pos[0] + dirTab[dir][0]][pos[1] + dirTab[dir][1]][(dir+2)%4] = false;
- m[nPos[0]][nPos[1]][(dir+2)%4] = false;
- }
- private boolean cellUsed(int[] pos, boolean[][][] m) {
- if (pos[0] == -1 || pos[1] == -1 || pos[0] == m.length || pos[1] == m[0].length) {
- return true;
- }
- for (int i = 0; i < 4; i++) {
- if (!m[pos[0]][pos[1]][i]) {
- return true;
- }
- }
- return false;
- }
- private int random(int low, int high) {
- return (int)(Math.random()*(high+1-low)) + low;
- }
- private int[] addCoords(int[] a, int[] b) {
- return new int[] {a[0]+b[0], a[1]+b[1]};
- }
- }
Add Comment
Please, Sign In to add comment