1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.vectomatic.svg.edu.client.maze;
19
20 import java.util.HashSet;
21 import java.util.Set;
22 import java.util.Stack;
23
24 import org.vectomatic.svg.edu.client.maze.RectangularMaze.RectangularCell;
25
26 import com.google.gwt.core.client.GWT;
27 import com.google.gwt.user.client.Random;
28
29 public class Maze {
30 private Cell cells[];
31 public Maze(Cell cells[]) {
32 this.cells = cells;
33 }
34 public Cell[] getCells() {
35 return cells;
36 }
37 public void perfectRandomize() {
38 long t1 = System.currentTimeMillis();
39
40 for (Cell cell : cells) {
41 for (Cell neighbor : cell.getNeighbors()) {
42 cell.setHasWall(neighbor, true);
43 ((RectangularCell)cell).setOnPath(false);
44 }
45 }
46
47
48 int visitedCount = 1;
49 Cell currentCell = cells[Random.nextInt(cells.length)];
50 Stack<Cell> stack = new Stack<Cell>();
51 while(visitedCount < cells.length) {
52 Cell cell = currentCell.getNeighborWithAllWalls();
53 if (cell != null) {
54 cell.setHasWall(currentCell, false);
55 stack.push(currentCell);
56 currentCell = cell;
57 visitedCount++;
58 } else {
59 currentCell = stack.pop();
60 }
61 }
62 long t2 = System.currentTimeMillis();
63 GWT.log("randomize = " + (t2 - t1));
64 }
65 public Stack<Cell> resolve(Cell start, Cell end) {
66 Set<Cell> visited = new HashSet<Cell>();
67 Stack<Cell> stack = new Stack<Cell>();
68 Cell currentCell = start;
69 stack.push(start);
70 visited.add(start);
71 while(currentCell != end) {
72 currentCell = stack.peek();
73 boolean pathExists = false;
74 for (Cell cell : currentCell.getNeighbors()) {
75 if ((!visited.contains(cell)) && (!cell.hasWall(currentCell))) {
76 stack.push(cell);
77 visited.add(cell);
78 pathExists = true;
79 break;
80 }
81 }
82 if (!pathExists) {
83 currentCell = stack.pop();
84 }
85 }
86 stack.pop();
87 return stack;
88 }
89 }