-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maze.java
115 lines (94 loc) · 3.53 KB
/
Maze.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.util.Scanner;
public class Maze
{
public static final int EMPTY = 0;
public static final int WALL = 1;
public static final int START = 2;
public static final int END = 3;
public static final int VISITED = 4;
public static final char NORTH = 'n';
public static final char EAST = 'e';
public static final char SOUTH = 's';
public static final char WEST = 'w';
public static void main(String[] args)
{
int[][] grid = {
{ WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL},
{END, EMPTY, EMPTY, WALL, EMPTY, EMPTY, EMPTY, EMPTY, WALL, WALL},
{ WALL, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, WALL, EMPTY, WALL, WALL},
{ WALL, WALL, WALL, WALL, EMPTY, WALL, EMPTY, WALL, EMPTY, WALL},
{ WALL, EMPTY, EMPTY, EMPTY, EMPTY, WALL, EMPTY, EMPTY, EMPTY, WALL},
{ WALL, WALL, EMPTY, WALL, WALL, EMPTY, EMPTY, WALL, EMPTY, WALL},
{ WALL, WALL, EMPTY, EMPTY, EMPTY, EMPTY, WALL, WALL, EMPTY, END},
{ WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL},
};
Viewer.view(grid);
String solution;
Scanner sc = new Scanner(System.in);
System.out.println("Find a solution to get from ^^ to $$, using the characters "
+ "'" + NORTH + "', '" + EAST + "', '" + SOUTH + "' and '" + WEST + "'"
+ " (for north, east, south and west).");
System.out.print("Your solution: ");
solution = sc.nextLine();
int row = 1;
int col = 0;
boolean done = false;
boolean solved = false;
int charIndex = 0;
int solutionLength = solution.length();
while(!done && charIndex < solutionLength)
{
char direction = solution.charAt(charIndex);
System.out.println("Location: (" + row + ", " + col
+ "), next direction: '" + direction + "'");
switch(direction)
{
case Maze.NORTH:
row--;
break;
case Maze.EAST:
col++;
break;
case Maze.SOUTH:
row++;
break;
case Maze.WEST:
col--;
break;
default:
System.out.println("You have no idea where you're going."); // Invalid direction.
}
if(row < 0 || col < 0
|| row >= grid.length || col >= grid[row].length)
{
done = true;
System.out.println("You fall into the chasm of doom."); // Out of bounds.
}
else
{
switch(grid[row][col])
{
case Maze.EMPTY:
grid[row][col] = Maze.VISITED;
break;
case Maze.WALL:
System.out.println("You stumble blindly into a solid concrete wall.");
break;
case Maze.END:
done = true;
System.out.println("SOLVED!");
break;
default:
// Do nothing
}
}
charIndex++;
}
if(!solved)
{
System.out.println("You have failed to escape. Future archeologists gaze
upon your remains in bafflement."); // Did not reach the end.
}
Viewer.view(grid);
}
}