-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathFinding_Visualizer.java
More file actions
597 lines (512 loc) · 15.6 KB
/
PathFinding_Visualizer.java
File metadata and controls
597 lines (512 loc) · 15.6 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.JComboBox;
import java.util.Queue;
import java.util.PriorityQueue;
public class PathFinding {
//FRAME
JFrame frame;
//GENERAL VARIABLES
private int cells = 10;
private int delay = 30;
private double dense = .5;
private double density = (cells*cells)*.5;
private int startx = -1;
private int starty = -1;
private int finishx = -1;
private int finishy = -1;
private int tool = 0;
private int checks = 0;
private int length = 0;
private int curAlg = 0;
private int WIDTH = 1000;
private final int HEIGHT = 1000;
private final int MSIZE = 400;
private int CSIZE = MSIZE/cells;
//UTIL ARRAYS
private String[] algorithms = {"Dijkstra","A*","BFS","DFS"};
private String[] tools = {"Start","Finish","Wall", "Eraser"};
//BOOLEANS
private boolean solving = false;
//UTIL
Node[][] map;
Algorithm Alg = new Algorithm();
Random r = new Random();
//BUTTONS
JButton searchB = new JButton("Start Search");
JButton resetB = new JButton("Reset");
JButton genMapB = new JButton("Generate Map");
JButton clearMapB = new JButton("Clear Map");
//DROP DOWN
JComboBox algorithmsBx = new JComboBox(algorithms);
JComboBox toolBx = new JComboBox(tools);
//PANELS
JPanel toolP = new JPanel();
//CANVAS
Map canvas;
//BORDER
Border loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
public static void main(String[] args) { //MAIN METHOD
new PathFinding();
}
public PathFinding() { //CONSTRUCTOR
clearMap();
initialize();
}
public void generateMap() { //GENERATE MAP
clearMap(); //CREATE CLEAR MAP TO START
for(int i = 0; i < density; i++) {
Node current;
do {
int x = r.nextInt(cells);
int y = r.nextInt(cells);
current = map[x][y]; //FIND A RANDOM NODE IN THE GRID
} while(current.getType()==2); //IF IT IS ALREADY A WALL, FIND A NEW ONE
current.setType(2); //SET NODE TO BE A WALL
}
}
public void clearMap() { //CLEAR MAP
finishx = -1; //RESET THE START AND FINISH
finishy = -1;
startx = -1;
starty = -1;
map = new Node[cells][cells]; //CREATE NEW MAP OF NODES
for(int x = 0; x < cells; x++) {
for(int y = 0; y < cells; y++) {
map[x][y] = new Node(3,x,y); //SET ALL NODES TO EMPTY
}
}
reset(); //RESET SOME VARIABLES
}
public void resetMap() { //RESET MAP
for(int x = 0; x < cells; x++) {
for(int y = 0; y < cells; y++) {
Node current = map[x][y];
if(current.getType() == 4 || current.getType() == 5) //CHECK TO SEE IF CURRENT NODE IS EITHER CHECKED OR FINAL PATH
map[x][y] = new Node(3,x,y); //RESET IT TO AN EMPTY NODE
}
}
if(startx > -1 && starty > -1) { //RESET THE START AND FINISH
map[startx][starty] = new Node(0,startx,starty);
map[startx][starty].setHops(0);
}
if(finishx > -1 && finishy > -1)
map[finishx][finishy] = new Node(1,finishx,finishy);
reset(); //RESET SOME VARIABLES
}
private void initialize() { //INITIALIZE THE GUI ELEMENTS
frame = new JFrame();
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(820,500);
frame.setTitle("Path Finding Visualizer");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
toolP.setBorder(BorderFactory.createTitledBorder(loweredetched,"Options"));
int space = 20;
int buff = 125;
toolP.setLayout(null);
toolP.setBounds(5,5,800,50);
searchB.setBounds(space,20, 120, 25);
toolP.add(searchB);
space+=buff;
resetB.setBounds(space,20,120,25);
toolP.add(resetB);
space+=buff;
//
genMapB.setBounds(space,20, 120, 25);
toolP.add(genMapB);
space+=buff;
//
clearMapB.setBounds(space,20, 120, 25);
toolP.add(clearMapB);
space+=buff;
algorithmsBx.setBounds(space,20, 120, 25);
toolP.add(algorithmsBx);
space+=buff;
toolBx.setBounds(space,20,120,25);
toolP.add(toolBx);
space+=buff;
frame.getContentPane().add(toolP);
//
canvas = new Map();
canvas.setBounds(10, 60, 600, 600);
frame.getContentPane().add(canvas);
searchB.addActionListener(new ActionListener() { //ACTION LISTENERS
@Override
public void actionPerformed(ActionEvent e) {
reset();
if((startx > -1 && starty > -1) && (finishx > -1 && finishy > -1))
solving = true;
}
});
resetB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetMap();
Update();
}
});
genMapB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
generateMap();
Update();
}
});
clearMapB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clearMap();
Update();
}
});
algorithmsBx.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
curAlg = algorithmsBx.getSelectedIndex();
Update();
}
});
toolBx.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
tool = toolBx.getSelectedIndex();
}
});
startSearch(); //START STATE
}
public void startSearch() { //START STATE
if(solving) {
switch(curAlg) {
case 0:
Alg.Dijkstra();
break;
case 1:
Alg.AStar();
break;
case 2:
Alg.BFS();
break;
case 3:
Alg.DFS();
break;
}
}
pause(); //PAUSE STATE
}
public void pause() { //PAUSE STATE
int i = 0;
while(!solving) {
i++;
if(i > 500)
i = 0;
try {
Thread.sleep(1);
} catch(Exception e) {}
}
startSearch(); //START STATE
}
public void Update() { //UPDATE ELEMENTS OF THE GUI
density = (cells*cells)*dense;
CSIZE = MSIZE/cells;
canvas.repaint();
}
public void reset() { //RESET METHOD
solving = false;
length = 0;
checks = 0;
}
public void delay() { //DELAY METHOD
try {
Thread.sleep(delay);
} catch(Exception e) {}
}
class Map extends JPanel implements MouseListener, MouseMotionListener{ //MAP CLASS
public Map() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g) { //REPAINT
super.paintComponent(g);
for(int x = 0; x < cells; x++) { //PAINT EACH NODE IN THE GRID
for(int y = 0; y < cells; y++) {
switch(map[x][y].getType()) {
case 0:
g.setColor(Color.GREEN);
break;
case 1:
g.setColor(Color.RED);
break;
case 2:
g.setColor(Color.BLACK);
break;
case 3:
g.setColor(Color.WHITE);
break;
case 4:
g.setColor(Color.CYAN);
break;
case 5:
g.setColor(Color.YELLOW);
break;
}
g.fillRect(x*CSIZE,y*CSIZE,CSIZE,CSIZE);
g.setColor(Color.BLACK);
g.drawRect(x*CSIZE,y*CSIZE,CSIZE,CSIZE);
}
}
}
@Override
public void mouseDragged(MouseEvent e) {
try {
int x = e.getX()/CSIZE;
int y = e.getY()/CSIZE;
Node current = map[x][y];
if((tool == 2 || tool == 3) && (current.getType() != 0 && current.getType() != 1))
current.setType(tool);
Update();
} catch(Exception z) {}
}
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
resetMap(); //RESET THE MAP WHENEVER CLICKED
try {
int x = e.getX()/CSIZE; //GET THE X AND Y OF THE MOUSE CLICK IN RELATION TO THE SIZE OF THE GRID
int y = e.getY()/CSIZE;
Node current = map[x][y];
switch(tool ) {
case 0: { //START NODE
if(current.getType()!=2) { //IF NOT WALL
if(startx > -1 && starty > -1) { //IF START EXISTS SET IT TO EMPTY
map[startx][starty].setType(3);
map[startx][starty].setHops(-1);
}
current.setHops(0);
startx = x; //SET THE START X AND Y
starty = y;
current.setType(0); //SET THE NODE CLICKED TO BE START
}
break;
}
case 1: {//FINISH NODE
if(current.getType()!=2) { //IF NOT WALL
if(finishx > -1 && finishy > -1) //IF FINISH EXISTS SET IT TO EMPTY
map[finishx][finishy].setType(3);
finishx = x; //SET THE FINISH X AND Y
finishy = y;
current.setType(1); //SET THE NODE CLICKED TO BE FINISH
}
break;
}
default:
if(current.getType() != 0 && current.getType() != 1)
current.setType(tool);
break;
}
Update();
} catch(Exception z) {} //EXCEPTION HANDLER
}
@Override
public void mouseReleased(MouseEvent e) {}
}
class Algorithm { //ALGORITHM CLASS
//BFS Algorithm
public void BFS()
{
ArrayList<Node> priority = new ArrayList<Node>(); //CREATE A PRIORITY QUE
priority.add(map[startx][starty]); //ADD THE START TO THE QUE
while(solving) {
if(priority.size() <= 0) { //IF THE QUE IS 0 THEN NO PATH CAN BE FOUND
solving = false;
break;
}
int hops = priority.get(0).getHops()+1; //INCREMENT THE HOPS VARIABLE
ArrayList<Node> explored = exploreNeighbors(priority.get(0), hops); //CREATE AN ARRAYLIST OF NODES THAT WERE EXPLORED
if(explored.size() > 0) {
priority.remove(0); //REMOVE THE NODE FROM THE QUE
priority.addAll(explored); //ADD ALL THE NEW NODES TO THE QUE
Update();
delay();
} else { //IF NO NODES WERE EXPLORED THEN JUST REMOVE THE NODE FROM THE QUE
priority.remove(0);
}
}
}
//DFS ALGORITHM
public void DFS()
{
}
public void Dijkstra() {
PriorityQueue<Node> priority=new PriorityQueue<>(new Comparator<Node>(){
@Override
public int compare(PathFinding.Node o1, PathFinding.Node o2) {
if(o1.getEuclidDist()<o2.getEuclidDist())
{
return 1;
}else if(o1.getEuclidDist()>o2.getEuclidDist()){
return -1;
}
return 0;
}
});
priority.add(map[startx][starty]); //ADD THE START TO THE QUE
while(solving) {
if(priority.isEmpty() ) { //IF THE QUE IS 0 THEN NO PATH CAN BE FOUND
solving = false;
break;
}
int hops = priority.peek().getHops()+1; //INCREMENT THE HOPS VARIABLE
ArrayList<Node> explored = exploreNeighbors(priority.peek(), hops); //CREATE AN ARRAYLIST OF NODES THAT WERE EXPLORED
if(explored.size() > 0) {
priority.remove(); //REMOVE THE NODE FROM THE QUE
priority.addAll(explored); //ADD ALL THE NEW NODES TO THE QUE
Update();
delay();
} else { //IF NO NODES WERE EXPLORED THEN JUST REMOVE THE NODE FROM THE QUE
priority.remove();
}
}
}
public void AStar() {
ArrayList<Node> priority = new ArrayList<Node>();
priority.add(map[startx][starty]);
while(solving) {
if(priority.size() <= 0) {
solving = false;
break;
}
int hops = priority.get(0).getHops()+1;
ArrayList<Node> explored = exploreNeighbors(priority.get(0),hops);
if(explored.size() > 0) {
priority.remove(0);
priority.addAll(explored);
Update();
delay();
} else {
priority.remove(0);
}
sortQue(priority); //SORT THE PRIORITY QUE
}
}
public ArrayList<Node> sortQue(ArrayList<Node> sort) { //SORT PRIORITY QUE
int c = 0;
while(c < sort.size()) {
int sm = c;
for(int i = c+1; i < sort.size(); i++) {
if(sort.get(i).getEuclidDist()+sort.get(i).getHops() < sort.get(sm).getEuclidDist()+sort.get(sm).getHops())
sm = i;
}
if(c != sm) {
Node temp = sort.get(c);
sort.set(c, sort.get(sm));
sort.set(sm, temp);
}
c++;
}
return sort;
}
public ArrayList<Node> exploreNeighbors(Node current, int hops) { //EXPLORE NEIGHBORS
ArrayList<Node> explored = new ArrayList<Node>(); //LIST OF NODES THAT HAVE BEEN EXPLORED
for(int a = -1; a <= 1; a++) {
for(int b = -1; b <= 1; b++) {
int xbound = current.getX()+a;
int ybound = current.getY()+b;
if((xbound > -1 && xbound < cells) && (ybound > -1 && ybound < cells)) { //MAKES SURE THE NODE IS NOT OUTSIDE THE GRID
Node neighbor = map[xbound][ybound];
if((neighbor.getHops()==-1 || neighbor.getHops() > hops) && neighbor.getType()!=2) { //CHECKS IF THE NODE IS NOT A WALL AND THAT IT HAS NOT BEEN EXPLORED
explore(neighbor, current.getX(), current.getY(), hops); //EXPLORE THE NODE
explored.add(neighbor); //ADD THE NODE TO THE LIST
}
}
}
}
return explored;
}
public void explore(Node current, int lastx, int lasty, int hops) { //EXPLORE A NODE
if(current.getType()!=0 && current.getType() != 1) //CHECK THAT THE NODE IS NOT THE START OR FINISH
current.setType(4); //SET IT TO EXPLORED
current.setLastNode(lastx, lasty); //KEEP TRACK OF THE NODE THAT THIS NODE IS EXPLORED FROM
current.setHops(hops); //SET THE HOPS FROM THE START
checks++;
if(current.getType() == 1) { //IF THE NODE IS THE FINISH THEN BACKTRACK TO GET THE PATH
backtrack(current.getLastX(), current.getLastY(),hops);
}
}
public void backtrack(int lx, int ly, int hops) { //BACKTRACK
length = hops;
while(hops > 1) { //BACKTRACK FROM THE END OF THE PATH TO THE START
Node current = map[lx][ly];
current.setType(5);
lx = current.getLastX();
ly = current.getLastY();
hops--;
}
solving = false;
}
}
class Node {
// 0 = start, 1 = finish, 2 = wall, 3 = empty, 4 = checked, 5 = finalpath
private int cellType = 0;
private int hops;
private int x;
private int y;
private int lastX;
private int lastY;
private double dToEnd = 0;
public Node(int type, int x, int y) { //CONSTRUCTOR
cellType = type;
this.x = x;
this.y = y;
hops = -1;
}
public double getEuclidDist() { //CALCULATES THE EUCLIDIAN DISTANCE TO THE FINISH NODE
int xdif = Math.abs(x-finishx);
int ydif = Math.abs(y-finishy);
dToEnd = Math.sqrt((xdif*xdif)+(ydif*ydif));
return dToEnd;
}
public int getX() {return x;} //GET METHODS
public int getY() {return y;}
public int getLastX() {return lastX;}
public int getLastY() {return lastY;}
public int getType() {return cellType;}
public int getHops() {return hops;}
public void setType(int type) {cellType = type;} //SET METHODS
public void setLastNode(int x, int y) {lastX = x; lastY = y;}
public void setHops(int hops) {this.hops = hops;}
}
}