Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.marcbeckhäuser.maze;
- import java.awt.*;
- import java.util.ArrayList;
- import java.util.List;
- import ch.aplu.jgamegrid.*;
- import ch.aplu.util.*;
- public class MazeActor extends Actor {
- private final Location startLocation = new Location(0, 1);
- private final Location exitLocation;
- private List<Location> visitedLocations;
- private Location previousLoc = startLocation;
- private GameGrid gamegrid;
- public MazeActor(GameGrid gamegrid) {
- exitLocation = new Location(gamegrid.getNbHorzCells() - 1, gamegrid.getNbVertCells() - 2);
- visitedLocations = new ArrayList<Location>();
- this.gamegrid = gamegrid;
- }
- public void startSearch() {
- TextActor distanceMark = new TextActor("");
- gamegrid.addActor(distanceMark, new Location(0, 0));
- gamegrid.setPaintOrder(MazeActor.class, TextActor.class);
- searchWay(startLocation, 0);
- }
- public void act() {
- Monitor.wakeUp();
- }
- private void searchWay(Location loc, int distance) {
- Monitor.putSleep();
- if (visitedLocations.contains(exitLocation) || visitedLocations.contains(loc))
- return;
- else {
- visitedLocations.add(loc);
- setLocationFacing(loc);
- if (loc.equals(exitLocation)) {
- return;
- } else {
- TextActor distanceMark = new TextActor("" + distance);
- distanceMark.setLocationOffset(new Point(-7, 0));
- gamegrid.addActorNoRefresh(distanceMark, loc);
- if (canMove(new Location(loc.x, loc.y - 1))) // UP
- searchWay(new Location(loc.x, loc.y - 1), distance + 1);
- if (canMove(new Location(loc.x - 1, loc.y))) // LEFT
- searchWay(new Location(loc.x - 1, loc.y), distance + 1);
- if (canMove(new Location(loc.x, loc.y + 1))) // DOWN
- searchWay(new Location(loc.x, loc.y + 1), distance + 1);
- if (canMove(new Location(loc.x + 1, loc.y))) // RIGHT
- searchWay(new Location(loc.x + 1, loc.y), distance + 1);
- if (!visitedLocations.contains(exitLocation)) {
- gamegrid.removeActorsAt(loc, TextActor.class);
- TextActor wrongMark = new TextActor("x", Color.red, Color.white, new Font("TimesNewRoman", Font.PLAIN, 12));
- distanceMark.setLocationOffset(new Point(-8, 0));
- gamegrid.addActorNoRefresh(wrongMark, loc);
- setLocationFacing(loc);
- }
- }
- }
- }
- private void setLocationFacing(Location loc) {
- setDirection(previousLoc.getCompassDirectionTo(loc));
- previousLoc = loc;
- setLocation(loc);
- }
- private boolean canMove(Location location) {
- Color c = getBackground().getColor(location);
- return (!c.equals(Color.black));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement