public void configureCell(int row, int column, Set<ExitDirections> exitDirections) { MazeNode node = mazeGrid.get(row).get(column); MazeNode linkMe = null; for (ExitDirections dir : exitDirections) { switch (dir) { case NORTH: linkMe = (row > 0) ? mazeGrid.get(row - 1).get(column) : null; break; case SOUTH: linkMe = (row < height - 1) ? mazeGrid.get(row + 1).get(column) : null; break; case EAST: linkMe = (column < width - 1) ? mazeGrid.get(row).get(column + 1) : null; break; case WEST: linkMe = (column > 0) ? mazeGrid.get(row).get(column - 1) : null; break; } if (linkMe != null) { node.getExits().add(linkMe); linkMe.getExits().add(node); } } }
public Maze(int width, int height) { for (int i = 0; i < height; i++) { mazeGrid.add(new ArrayList<MazeNode>()); for (int j = 0; j < width; j++) { MazeNode node = new MazeNode(); node.setGridRow(i); node.setGridColumn(j); mazeGrid.get(i).add(node); } } this.height = height; this.width = width; }
public static void main(String[] args) { JFrame frame = new JFrame("Maze View"); Random random = new Random(); long startTime = System.nanoTime(); MazeNode maze = MazeNode.generate(random, 100, 100); System.out.println("Gen : " + elapsedMs(startTime) + "ms"); startTime = System.nanoTime(); int sx = 0; // random.nextInt(maze.width); int sy = 0; // random.nextInt(maze.height); int dx = maze.width - 1; // random.nextInt(maze.width); int dy = maze.height - 1; // random.nextInt(maze.height); Path path = PathSolver.solve(maze, sx, sy, dx, dy); System.out.println("Solve : " + elapsedMs(startTime) + "ms"); int pathSize = 0; PathCell pathIt = path.first; while (pathIt != null) { pathSize++; pathIt = pathIt.next; } System.out.println("Path Size: " + pathSize); frame.add(new JScrollPane(new MazeView(maze, sx, sy, dx, dy, path))); frame.setSize(500, 500); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); SwingUtilities.invokeLater(() -> frame.setVisible(true)); }
public void saveMaze(String fileName) throws FileNotFoundException { PrintWriter writer = new PrintWriter(fileName); writer.println(width + DELIMITER + height); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { MazeNode node = mazeGrid.get(i).get(j); writer.print(node.getGridRow() + DELIMITER + node.getGridColumn()); for (MazeNode link : node.getExits()) { if (link.getGridColumn() - j == 1) { writer.print(DELIMITER + ExitDirections.EAST.name()); } else if (link.getGridColumn() - j == -1) { writer.print(DELIMITER + ExitDirections.WEST.name()); } else if (link.getGridRow() - i == 1) { writer.print(DELIMITER + ExitDirections.SOUTH.name()); } else if (link.getGridRow() - j == -1) { writer.print(DELIMITER + ExitDirections.NORTH.name()); } } writer.println(""); } } writer.flush(); writer.close(); }