How to Make a Maze in Java

104 17
    • 1). Create the maze's opening script:

      public class Maze {
      private int N;
      private boolean[][] north;
      private boolean[][] east;
      private boolean[][] south;
      private boolean[][] west;
      private boolean[][] visited;
      private double size;
      private boolean done = false;

      public Maze(int N) {
      this.N = N;
      StdDraw.setXscale(0, N+2);
      StdDraw.setYscale(0, N+2);
      init();
      generate();
      }

    • 2). Establish a failsafe that prevents the program from revisiting cells:
      private void init() {
      // initialize border cells as already visited
      visited = new boolean[N+2][N+2];
      for (int x = 0; x < N+2; x++) visited[x][0] = visited[x][N+1] = true;
      for (int y = 0; y < N+2; y++) visited[0][y] = visited[N+1][y] = true;

    • 3). Establish all cells in the maze as being present:
      // initialize all cells as present
      north = new boolean[N+2][N+2];
      east = new boolean[N+2][N+2];
      south = new boolean[N+2][N+2];
      west = new boolean[N+2][N+2];
      for (int x = 0; x < N+2; x++)
      for (int y = 0; y < N+2; y++)
      north[x][y] = east[x][y] = south[x][y] = west[x][y] = true;
      }

    • 4). Include maze generation lines of code:
      private void generate(int x, int y) {
      visited[x][y] = true;

      while (!visited[x][y+1] || !visited[x+1][y] || !visited[x][y-1] || !visited[x-1][y]) {

      while (true) {
      double r = Math.random();
      if (r < 0.25 && !visited[x][y+1]) {
      north[x][y] = south[x][y+1] = false;
      generate(x, y + 1);
      break;
      }
      else if (r >= 0.25 && r < 0.50 && !visited[x+1][y]) {
      east[x][y] = west[x+1][y] = false;
      generate(x+1, y);
      break;
      }
      else if (r >= 0.5 && r < 0.75 && !visited[x][y-1]) {
      south[x][y] = north[x][y-1] = false;
      generate(x, y-1);
      break;
      }
      else if (r >= 0.75 && r < 1.00 && !visited[x-1][y]) {
      west[x][y] = east[x-1][y] = false;
      generate(x-1, y);
      break;
      }
      }
      }
      }

    • 5). Create variables and unique lines of code to personalize the basic Java maze-creating script, such as a line that randomly deletes portions of walls, randomly creates portions of walls, or even a script that inserts teleportation points to other areas of the maze.

Source...

Leave A Reply

Your email address will not be published.