Save I need help with this maze gui that I wrote in java I a
Save
I need help with this maze gui that I wrote in java, I am trying to find the shortest path but I dont know how to implement the FindshortestPath Method.
I was given this as a stragedy to solve the findshortestpathMethod():
Create two LinkedLists of MazeMap objects. One will be the list of map objects for cells at distance x from the center. The other will be the list of map objects for cells at distance x + 1.
Initialize the list at distance x to contain a MazeMap object which refers to the center cell of the maze. Since this map object refers to the center cell, it does not need to refer to any other MazeMap object, so its MazeMap reference can be set to null. Set the center cell’s visited field to true to indicate that this cell has already been added to the map.
Set up a loop to run until the maze entrance is mapped. This loop does the following:
Set up a loop to process each map object from the list at distance x. This loop does the following:
i.Get the cell from the map object
ii.If this cell is the entrance cell, set the entrance and break out of the loop!
iii.Check each direction from this cell and for an accessible neighbor cell
Get a reference to that neighbor cell
If the neighbor cell has not already been visited
Set the cell’s visited field to true so its only processed once
Create a MazeMap object that refers to this neighbor cell
Make this MazeMap object refer to the current map object being processed – ie the cell one step closer to center
Add this MazeMap object to the list at distance x + 1
List at distance x has been processed. The list at distance x + 1 is now complete, so make the list at distance x refer to list at distance x + 1. Then create a new empty list for the list at distance x + 1.
At this point, the entrance points at the map object which refers to cell 1,1. That map object also refers to a map object which is one step closer to the center. Write a loop that traverses this trail of references until it reaches the end (a null reference). For each map object:
Get the cell referred to.
Call the drawCircle method with a color, the cell’s row and column, and SMALL.
Call the delay method with a SHORT delay. This slows down the drawing process so you can watch the path being displayed.
Advance to the next map object in the list.
here is the code so far*********
here is my code: ******mazeApp*******
package mazepackage;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextInputDialog;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MazeApp extends Application
{
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 768;
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
// The graphics context is needed to enable drawing on the canvas
private GraphicsContext gc;
// boundary of drawing canvas, 0% border
// private static final double BORDER = 0.05;
private static final double BORDER = 0.00;
private double xmin, ymin, xmax, ymax;
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage)
{
Group root = new Group();
Canvas canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
gc.setLineWidth(2);
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
root.getChildren().add(canvas);
TextInputDialog tid = new TextInputDialog();
tid.setTitle(\"Maze Size\");
tid.setHeaderText(\"Enter maze size between 10 and 50\");
tid.showAndWait();
int size = Integer.parseInt(tid.getResult());
if (size > 50)
size = 50;
if (size < 10)
size = 10;
primaryStage.setTitle(\"Maze Application\");
primaryStage.setScene(new Scene(root));
primaryStage.setResizable(false);
// Make sure that the application goes away when then window is closed
primaryStage.setOnCloseRequest(e -> System.exit(0));
primaryStage.show();
Maze maze = new Maze(this, size);
// Must solve the maze in a separate thread or else
// the GUI wont update until the end.....
Thread solver = new Thread(
new Runnable () {
public void run()
{
while(true)
{
maze.buildAndDrawMaze();
maze.findShortestPath();
try
{
Thread.sleep(5000);
}
catch(Exception e) { }
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
}
}
});
solver.start();
}
/**
* Sets the pen color to the specified color.
*
* @param color the color to make the pen
*/
public void setPenColor(Color color) {
gc.setStroke(color);
}
/**
* Sets the pen color to the specified color.
*
* @param color the color to make the pen
*/
public void setFillColor(Color color) {
gc.setFill(color);
}
/**
* Sets the <em>x</em>-scale to the specified range.
*
* @param min the minimum value of the <em>x</em>-scale
* @param max the maximum value of the <em>x</em>-scale
* @throws IllegalArgumentException if {@code (max == min)}
*/
public void setXscale(double min, double max) {
double size = max - min;
if (size == 0.0) {
throw new IllegalArgumentException(\"the min and max are the same\");
}
xmin = min - BORDER * size;
xmax = max + BORDER * size;
}
/**
* Sets the <em>y</em>-scale to the specified range.
*
* @param min the minimum value of the <em>y</em>-scale
* @param max the maximum value of the <em>y</em>-scale
* @throws IllegalArgumentException if {@code (max == min)}
*/
public void setYscale(double min, double max) {
double size = max - min;
if (size == 0.0) {
throw new IllegalArgumentException(\"the min and max are the same\");
}
ymin = min - BORDER * size;
ymax = max + BORDER * size;
}
// helper functions that scale from user coordinates to screen coordinates and back
private double scaleX(double x) {
return width * (x - xmin) / (xmax - xmin);
}
private double scaleY(double y) {
return height * (ymax - y) / (ymax - ymin);
}
private double factorX(double w) {
return w * width / Math.abs(xmax - xmin);
}
private double factorY(double h) {
return h * height / Math.abs(ymax - ymin);
}
private double userX(double x) {
return xmin + x * (xmax - xmin) / width;
}
private double userY(double y) {
return ymax - y * (ymax - ymin) / height;
}
/**
* Draws a line segment between (<em>x</em><sub>0</sub>,
* <em>y</em><sub>0</sub>) and (<em>x</em><sub>1</sub>,
* <em>y</em><sub>1</sub>).
*
* @param x0 the <em>x</em>-coordinate of one endpoint
* @param y0 the <em>y</em>-coordinate of one endpoint
* @param x1 the <em>x</em>-coordinate of the other endpoint
* @param y1 the <em>y</em>-coordinate of the other endpoint
*/
public void line(double x0, double y0, double x1, double y1) {
gc.strokeLine(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1));
}
/**
* Draws one pixel at (<em>x</em>, <em>y</em>). This method is private
* because pixels depend on the display. To achieve the same effect, set the
* pen radius to 0 and call {@code point()}.
*
* @param x the <em>x</em>-coordinate of the pixel
* @param y the <em>y</em>-coordinate of the pixel
*/
private void pixel(double x, double y) {
gc.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);
}
/**
* Draws a filled circle of the specified radius, centered at (<em>x</em>,
* <em>y</em>).
*
* @param x the <em>x</em>-coordinate of the center of the circle
* @param y the <em>y</em>-coordinate of the center of the circle
* @param radius the radius of the circle
* @throws IllegalArgumentException if {@code radius} is negative
*/
public void filledCircle(double x, double y, double radius) {
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2 * radius);
double hs = factorY(2 * radius);
if (ws <= 1 && hs <= 1) {
pixel(x, y);
} else {
gc.fillOval(xs - ws / 2, ys - hs / 2, ws, hs);
}
}
****************maze.java********************
package mazepackage;
import java.util.LinkedList;
import java.util.Random;
import javafx.scene.paint.Color;
public class Maze {
private int N; // dimension of maze
private MazeCell[][] maze;
private Random rand = new Random();
// Used to signal the maze has been solved
private boolean done;
// time in milliseconds (from currentTimeMillis()) when we can draw again
// used to control the frame rate
private long nextDraw = -1;
private MazeApp mf;
// Define constants for the circle size
private final double BIG = 0.375;
private final double SMALL = 0.25;
// Define constants for the delay times
private final int SHORT = 30;
private final int LONG = 500;
public Maze(MazeApp ma, int n) {
N = n;
mf = ma;
mf.setXscale(0, N + 2);
mf.setYscale(0, N + 2);
}
public void buildAndDrawMaze() {
createMaze();
buildMaze();
drawMaze();
}
// create the initial data structures that contain the maze data
private void createMaze() {
maze = new MazeCell[N + 2][N + 2];
for (int i = 0; i < N + 2; i++) {
for (int j = 0; j < N + 2; j++) {
maze[i][j] = new MazeCell(i, j);
}
}
// initialize border cells as already visited
for (int x = 0; x < N + 2; x++) {
maze[x][0].visited = true;
maze[x][N + 1].visited = true;
}
for (int y = 0; y < N + 2; y++) {
maze[0][y].visited = true;
maze[N + 1][y].visited = true;
}
}
// build the maze
private void buildMaze(int x, int y) {
maze[x][y].visited = true;
// while there is an unvisited neighbor
while (!maze[x][y + 1].visited || !maze[x + 1][y].visited
|| !maze[x][y - 1].visited || !maze[x - 1][y].visited) {
// pick random neighbor (could use Knuth\'s trick instead)
while (true) {
int r = rand.nextInt(4);
if (r == 0 && !maze[x][y + 1].visited) {
maze[x][y].nth = false;
maze[x][y + 1].sth = false;
buildMaze(x, y + 1);
break;
} else if (r == 1 && !maze[x + 1][y].visited) {
maze[x][y].est = false;
maze[x + 1][y].wst = false;
buildMaze(x + 1, y);
break;
} else if (r == 2 && !maze[x][y - 1].visited) {
maze[x][y].sth = false;
maze[x][y - 1].nth = false;
buildMaze(x, y - 1);
break;
} else if (r == 3 && !maze[x - 1][y].visited) {
maze[x][y].wst = false;
maze[x - 1][y].est = false;
buildMaze(x - 1, y);
break;
}
}
}
}
// build the maze starting from lower left
private void buildMaze() {
buildMaze(1, 1);
// Make sure visited is reset to false
for (int x = 1; x < N + 1; x++) {
for (int y = 1; y < N + 1; y++) {
maze[x][y].visited = false;
}
}
// delete some random walls
for (int i = 0; i < N; i++) {
int x = 1 + rand.nextInt(N - 1);
int y = 1 + rand.nextInt(N - 1);
maze[x][y].nth = maze[x][y + 1].sth = false;
}
}
// draw the initial maze
private void drawMaze() {
drawCircle(Color.RED, N / 2, N / 2, BIG);
drawCircle(Color.RED, 1, 1, BIG);
// Draw the walls in black
mf.setPenColor(Color.BLACK);
for (int x = 1; x <= N; x++) {
for (int y = 1; y <= N; y++) {
if (maze[x][y].sth) {
mf.line(x, y, x + 1, y);
}
if (maze[x][y].nth) {
mf.line(x, y + 1, x + 1, y + 1);
}
if (maze[x][y].wst) {
mf.line(x, y, x, y + 1);
}
if (maze[x][y].est) {
mf.line(x + 1, y, x + 1, y + 1);
}
}
}
delay(LONG);
}
private void delay(int t) {
// sleep until the next time we\'re allowed to draw
long millis = System.currentTimeMillis();
if (millis < nextDraw) {
try {
Thread.sleep(nextDraw - millis);
} catch (InterruptedException e) {
System.out.println(\"Error sleeping\");
}
millis = nextDraw;
}
// when are we allowed to draw again
nextDraw = millis + t;
}
private void drawCircle(Color c, double x, double y, double size) {
mf.setFillColor(c);
mf.filledCircle(x + 0.5, y + 0.5, size);
}
public void findShortestPath() {
// Your code goes here!!!!!
}
}
class MazeCell {
// nth, sth, est, wst used to identify walls - true indicates wall present
boolean nth, sth, wst, est;
// used to indicate that a cell has already been processed
boolean visited;
// used to facilitate finding the neighbors of a cell
int row, col;
public MazeCell(int i, int j) {
row = i;
col = j;
// All walls are initially present for every cell
nth = sth = est = wst = true;
// Initially no cells have been visited
visited = false;
}
}
class MazeMap {
MazeCell nFromCenter = null;
MazeMap nMinus1FromCenter = null;
}
**** end of code****
please help with only the \"FINDSHORTESTPATH();\" method please! thanks!
Solution
Answer:
import java.io.*;
public class DetectedShortestPathInMaze
{
static int number_of_rows=10; static int number_of_columns=10;
static int begin_of_row=5; static int begin_of_coloumn=3;
static int end_of_row=1; static int end_of_coloumn=6;
static int taken_maze[][]={{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,1,0,1,1,0,1,1,1},
{1,0,0,0,0,1,0,0,0,1},
{1,0,1,1,1,0,0,1,1,1},
{1,0,1,1,1,1,0,1,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}};
static int shortestpath[]=new int[number_of_rows*number_of_columns];
static int length_short;
boolean visitedalready(int row, int col, int detectedpathsofar[], int detectedlengthsofar){
int x;
int goal = row*number_of_columns+col;
for (x=0;x<detectedlengthsofar;x++)
if (detectedpathsofar[x]==goal) return true;
return false;
}
public void displayupdatedpath(int takenpath[], int takenlength){
int r,c;
for (r=0;r<number_of_rows;r++){
for(c=0;c<number_of_columns;c++){
if (taken_maze[r][c]==1)
System.out.print(\"|\");
else if (r==begin_of_row && c==begin_of_coloumn)
System.out.print(\"S\");
else if (r==end_of_row && c==end_of_coloumn)
System.out.print(\"X\");
else if (visitedalready(r,c,takenpath,takenlength))
System.out.print(\"o\");
else
System.out.print(\" \");
}
System.out.println(\"\");
}
}
public void searchnewpath(int row, int col, int detectedpathsofar[], int detectedlengthsofar){
if (row<0 || col<0 || row>=number_of_rows || col>=number_of_columns)
return;
if (taken_maze[row][col]==1) return ;
if (visitedalready(row, col, detectedpathsofar, detectedlengthsofar)) return;
int takenpath[]=new int[detectedlengthsofar+1];
System.arraycopy(detectedpathsofar, 0, takenpath, 0, detectedlengthsofar);
takenpath[detectedlengthsofar++]=row*number_of_columns+col;
if (row==end_of_row && col==end_of_coloumn){
System.out.println(\"Detected path of length \"+detectedlengthsofar+\":\");
displayupdatedpath(takenpath, detectedlengthsofar);
if (detectedlengthsofar<=length_short){
length_short=detectedlengthsofar;
System.arraycopy(takenpath, 0, shortestpath, 0, detectedlengthsofar);
System.out.println(\" The new shortest path is of length \" + detectedlengthsofar);
}
System.out.println(\"\");
return;
}
searchnewpath(row-1, col, takenpath, detectedlengthsofar);
searchnewpath(row, col-1, takenpath, detectedlengthsofar);
searchnewpath(row, col+1, takenpath, detectedlengthsofar);
searchnewpath(row+1, col, takenpath, detectedlengthsofar);
}
public static void main(String[] args)
{
int r,c,x;
int detectedpathsofar[];
int detectedlengthsofar;
DetectedShortestPathInMaze obj=new DetectedShortestPathInMaze();
detectedpathsofar=new int[obj.number_of_rows*obj.number_of_columns];
for (x=0;x<obj.number_of_rows*obj.number_of_columns;x++){
obj.shortestpath[x]=-1;
detectedpathsofar[x]=-1;
}
obj.length_short=obj.number_of_rows*obj.number_of_columns+1;
detectedlengthsofar=0;
System.out.println(\"The Maze Is Shown As Below:\");
for (r=0;r<obj.number_of_rows;r++){
for (c=0;c<obj.number_of_columns;c++){
if (r==begin_of_row && c==begin_of_coloumn)
System.out.print(\"S\");
else if (r==end_of_row && c==end_of_coloumn)
System.out.print(\"x\");
else if (obj.taken_maze[r][c]==0)
System.out.print(\" \");
else System.out.print(\"|\");
}
System.out.println(\"\");
}
System.out.println(\"\");
System.out.println(\"Searching For Paths\");
obj.searchnewpath(begin_of_row, begin_of_coloumn, detectedpathsofar, detectedlengthsofar);
System.out.println(\"\");
System.out.println(\"The shortest path was found with the following of length \"+ obj.length_short);
obj.displayupdatedpath(obj.shortestpath, obj.length_short);
}
}









