/** * A* pathfinding algorithm * * @param grid the grid to be used for pathfinding * @param x target x coordinate in grid form * @param y target y coordinate in grid form * @return The next move to make for the ghost */ public Node pathFind(Grid grid, int x, int y) { // Set target x, y Node.tx = x; Node.ty = y; Node current = null, temp; int block; PriorityQueue<Node> opened = new PriorityQueue<Node>(); HashSet<Node> closed = new HashSet<Node>(); temp = new Node( this.x / Board.BLOCKSIZE, this.y / Board.BLOCKSIZE, 0); // current location of ghost temp.init(); temp.setDir(dx, dy); opened.offer(temp); while (!opened.isEmpty()) { current = opened.poll(); // get best node closed.add(current); // add node to closed set (visited) if (current.hCost == 0) // if future cost is 0, then it is target node break; block = grid.screenData[current.y][current.x]; // If can move, not abrupt, and unvisited, add to opened if ((block & 1) == 0 && current.dir != 3) // Can move and not abrupt { temp = current.getChild(-1, 0); // get child node if (!closed.contains(temp)) // Unvisited opened.add(temp); } if ((block & 2) == 0 && current.dir != 4) { temp = current.getChild(0, -1); if (!closed.contains(temp)) opened.add(temp); } if ((block & 4) == 0 && current.dir != 1) { temp = current.getChild(1, 0); if (!closed.contains(temp)) opened.add(temp); } if ((block & 8) == 0 && current.dir != 2) { temp = current.getChild(0, 1); if (!closed.contains(temp)) opened.add(temp); } } // if current.parent == null, then ghost is on pacman. Handle it by moving randomly // current.parent.parent == null, then current is best next move while (current.parent != null && current.parent.parent != null) current = current.parent; return current; }
@Test public void constructorTestNode() { Node n = new Node(Type.ROOM); n.setDir(DoorDirection.NORTH); ZoneModel zm = new ZoneModel(n); assertEquals(zm.getType(), Type.ROOM); assertTrue(zm.hasDoor(0)); n.setDir(DoorDirection.EAST); zm = new ZoneModel(n); assertTrue(zm.hasDoor(1)); n.setDir(DoorDirection.SOUTH); zm = new ZoneModel(n); assertTrue(zm.hasDoor(2)); n.setDir(DoorDirection.WEST); zm = new ZoneModel(n); assertTrue(zm.hasDoor(3)); n.setType(Type.CORRIDOR); zm = new ZoneModel(n); assertFalse(zm.hasDoor(0)); assertFalse(zm.hasDoor(1)); assertFalse(zm.hasDoor(2)); assertFalse(zm.hasDoor(3)); }