Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import info.gridworld.grid.Location;
- import java.awt.Color;
- import java.util.*;
- public class Maze extends AbstractMaze
- {
- private static final Color WALL = Color.BLACK;
- private static final Color PATH = Color.WHITE;
- private static final Color BEGIN = Color.RED;
- private static final Color COMPLETED = Color.MAGENTA;
- private static final Color END = Color.GREEN;
- public Maze()
- {
- super();
- }
- @Override
- public void populateMaze()
- {
- int temp = (int)(Math.random() * getGrid().getNumRows());
- int temp2 = (int)(Math.random() * getGrid().getNumRows());
- for(int row = 1; row < getGrid().getNumRows() - 1; row++)
- {
- for(int col = 1; col < getGrid().getNumCols() - 1; col++)
- {
- getGrid().put(new Location(row, col), Math.random() < Math.random()? WALL : PATH);
- }
- }
- for(int x = 0; x <getGrid().getNumRows(); x++)
- {
- getGrid().put(new Location(x,0), WALL);
- getGrid().put(new Location(x, getGrid().getNumRows() - 1 ), WALL);
- }
- for(int x = 1; x <getGrid().getNumCols(); x++)
- {
- getGrid().put(new Location(getGrid().getNumCols() - 1 , x), WALL);
- getGrid().put(new Location(0 , x), WALL);
- }
- getGrid().put(new Location(temp, 0), BEGIN);
- getGrid().put(new Location(temp2, getGrid().getNumCols() - 1), END);
- }
- @Override
- public boolean solveMaze()
- {
- if(done(findFinish()))
- {
- return true;
- }
- boolean solve = false;
- Deque<Location> store = new LinkedList<>();
- store.push(getStart());
- while(!store.isEmpty() && !solve)
- {
- Location pos = store.peek();
- ArrayList<Location> moves = getNext(pos);
- if(moves.size() != 0)
- {
- Location change = moves.get(0);
- add(change, COMPLETED);
- store.push(change);
- if (done(findFinish()))
- {
- solve = true;
- }
- }
- else
- {
- store.pop();
- }
- }
- return solve;
- }
- private Location getStart()
- {
- for(Location location : getGrid().getOccupiedLocations())
- {
- if(getGrid().get(location).equals(BEGIN))
- {
- return location;
- }
- }
- return null;
- }
- private ArrayList<Location> getNext(Location temp)
- {
- ArrayList<Location> ans = new ArrayList<>();
- for (Location location : getGrid().getValidAdjacentLocations(temp))
- {
- if(getGrid().get(location).equals(PATH))
- ans.add(location);
- }
- return ans;
- }
- private boolean done(Location lo)
- {
- for(Location location : getGrid().getValidAdjacentLocations(findFinish()))
- {
- if(getGrid().get(location).equals(COMPLETED))
- {
- return true;
- }
- }
- return false;
- }
- private Location findFinish()
- {
- for(Location location : getGrid().getOccupiedLocations())
- {
- if(getGrid().get(location).equals(END))
- {
- return location;
- }
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement