-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
683 lines (579 loc) · 24.9 KB
/
main.js
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
const rows = 20;
const columns = 30;
const grid_holder = document.getElementById("grid-holder");
const reset_button = document.getElementById("reset-button");
const solve_button = document.getElementById("calculate-button");
errorMessage("This is where error messages will appear!")
//-----------------------------------------------------------------------------------------------------------------------------------------------
// all non algorithmic functions that make the viruals of the page
//-----------------------------------------------
function MakeGrid(rows, columns) {
this.columns = columns;
this.rows = rows;
grid = "<table id='grid'>"
for (let i = 0; i < rows; i++) {
row_no = i + 1
row = '\n\n <tr>'
if (i===10) {
for (let i = 0; i < columns; i++) {
column_no = i + 1
if (i===2){
row += `\n <td id="${Number(row_no)}-${Number(column_no)}" class="start-node"> </td>`
} else if (i===27){
row += `\n <td id="${Number(row_no)}-${Number(column_no)}" class="finish-node"> </td>`
} else {
row += `\n <td id="${Number(row_no)}-${Number(column_no)}" class="regular-node"> </td>`
}
}
} else {
for (let i = 0; i < columns; i++) {
column_no = i + 1
row += `\n <td id="${Number(row_no)}-${Number(column_no)}" class="regular-node"> </td>`
}
}
row += '\n\n </tr>'
grid+=row
}
grid += '</table>'
grid_holder.innerHTML = '';
grid_holder.innerHTML = grid;
}
MakeGrid(rows, columns)
//-----------------------------------------------
// Array to track node movemenet
start_visited = [] // All nodes visited by start node movement (will chose last one!)
finish_visited = [] // All nodes visited by finish node movement (will chose last one!)
// Variable to track the process
var isUnderGo = false
// Variables to add and move nodes
var isRegularClicked = false;
var isStartClicked = {'state':false, 'source':''}
var isFinishClicked = {'state':false, 'source':''};
//-----------------------------------------------
function EditGrid() {
// Reset lists
start_visited.length = 0;
finish_visited.length = 0;
// Reset lists
// Prevent default
$("td").mousedown(function() {
event.preventDefault()
});
$("tr").mousedown(function() {
event.preventDefault()
});
$("table").mousedown(function() {
event.preventDefault()
});
// Regular node & Wall node
//-----------------------------------------------
function RegularNode() {
$(".regular-node").mousedown(function() {
if (isUnderGo) {
//pass
} else {
let node = event.target;
let node_class = node.className;
let node_id = node.id;
// Add wall node
if (node_class === 'regular-node') {
document.getElementById(String(node_id)).className = 'wall-node';
} else if (node_class === 'wall-node') {
document.getElementById(String(node_id)).className = 'regular-node';
}
// Add wall node
isRegularClicked = true;
}
})
}
$(".regular-node").mouseup(function() {
if (isUnderGo) {
//pass
} else {
isRegularClicked = false;
RegularNode() // Refresh list
}
})
//-----------------------------------------------
//-----------------------------------------------
// Start node
function StartNode() {
$(".start-node").mousedown(function() {
if (isUnderGo) {
//pass
} else {
let node = event.target;
let node_class = node.className;
let node_id = node.id;
isStartClicked['state'] = true;
isStartClicked['source'] = String(node_id);
//console.log(isStartClicked['source'])
}
})
}
//-----------------------------------------------
//-----------------------------------------------
// Finish node
function FinishNode() {
$(".finish-node").mousedown(function() {
if (isUnderGo) {
//pass
} else {
let node = event.target;
let node_class = node.className;
let node_id = node.id;
isFinishClicked['state'] = true;
isFinishClicked['source'] = String(node_id);
//console.log(isFinishClicked['source'])
}
})
}
//-----------------------------------------------
//-----------------------------------------------
// Mouse up
$("td").mouseup(function() {
if (isUnderGo) {
//pass
} else {
isStartClicked['state'] = false;
isFinishClicked['state'] = false;
StartNode() // Refresh list
FinishNode() // Refresh list
}
})
//-----------------------------------------------
//-----------------------------------------------
$("td").mouseenter(function() {
if(isUnderGo) {
//pass
} else {
let node = event.target;
let node_class = node.className;
let node_id = node.id;
// Regular node and Wall node
if (isRegularClicked) {
if (node_class === 'regular-node') {
document.getElementById(String(node_id)).className = 'wall-node';
} else if (node_class === 'wall-node') {
document.getElementById(String(node_id)).className = 'regular-node';
}
} else {
//pass
}
// Start node
if (isStartClicked['state']) {
if (node_class === 'finish-node') {
// pass
} else {
document.getElementById(isStartClicked['source']).className = 'regular-node';
start_visited.push(node_id);
if (start_visited.length > 1) {
document.getElementById(String(start_visited[start_visited.length - 2])).className = 'regular-node';
}
document.getElementById(String(start_visited[start_visited.length - 1])).className = 'start-node';
}
}
// Finish node
if (isFinishClicked['state']) {
if (node_class === 'start-node') {
// pass
} else {
document.getElementById(isFinishClicked['source']).className = 'regular-node';
finish_visited.push(node_id);
if (finish_visited.length > 1) {
document.getElementById(String(finish_visited[finish_visited.length - 2])).className = 'regular-node';
}
document.getElementById(String(finish_visited[finish_visited.length - 1])).className = 'finish-node';
}
}
}
});
//-----------------------------------------------
}
EditGrid()
//-----------------------------------------------
// Pathfinding status
var isProcessing = false;
//-----------------------------------------------
// Reset Grid
reset_button.onclick = function() {
if (isProcessing) {
//pass
} else {
//console.log("RESET GRID!");
MakeGrid(rows, columns);
isUnderGo = false;
EditGrid()
}
}
// Conduct Search
solve_button.onclick = function() {
if (isProcessing) {
//pass
} else {
isUnderGo = true;
ComputeGrid();
}
}
//-----------------------------------------------
// Maze holder
var maze = []
//-----------------------------------------------
function ComputeGrid() {
if (document.getElementById('algo-choice').value === 'choose'){
errorMessage("please choose a valid algorithm!")
isUnderGo = false;
return; //exit function
} else {
errorMessage("no errors!")
}
var algo_choice = document.getElementById('algo-choice').value;
isProcessing = true;
nodes = document.getElementsByTagName('td');
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].className === 'start-node') {
i_node_type = 'start'
} else if (nodes[i].className === 'finish-node') {
i_node_type = 'finish'
// Change the wall statement for real thing
} else if (nodes[i].className === 'wall-node') {
i_node_type = 'wall'
} else {
i_node_type = 'regular'
};
let push_value = {node_pos:[Number(String(nodes[i].id).split("-")[0]), Number(String(nodes[i].id).split("-")[1])], node_type:i_node_type};
maze.push(push_value);
}
if (algo_choice === 'depth-first') {
new DepthFirst(maze, 10).search()
} else if (algo_choice === 'breadth-first') {
new BreadthFirst(maze, 10).search()
} else if (algo_choice === 'a-star') {
new AStar(maze, 10).search()
}
};
//-----------------------------------------------
//-----------------------------------------------
// Display an error with the user's actions
function errorMessage(message) {
document.getElementById('error-box').innerHTML = `<p id="error">${message}</p>`
}
//-----------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------
class AStar {
constructor(maze, ms) {
this.maze = maze;
this.queue = [];
this.speed = ms;
}
search() {
console.log(this.maze);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------
class DepthFirst {
constructor(maze, ms) {
this.maze = maze;
this.queue = [""];
this.speed = ms; // speed search visualization
this.directions = ["l", "r", "u", "d"]; // order in which a path is extended (remember newest found valid path is appended to front)
this.visited = [] // array to avoid repeated extension of already extended paths
this.path = ""; // our current best path
this.start_node = this.maze[this.maze.findIndex(x => x.node_type === 'start')].node_pos; // start node
this.end_node = this.maze[this.maze.findIndex(x => x.node_type === 'finish')].node_pos; // end node
this.iteration = 0; // counting iterations
this.visited_old = [];
}
//-----------------------------------------------
search() {
while(this.is_end(this.path) === false) {
if (this.queue.length === 0) {
this.queue.push("");
}
this.path_main = this.queue[0] // last value in queue
for (let i = 0; i < this.directions.length; i++) {
this.try_path = this.path_main + this.directions[i];
if (this.validate(this.try_path)) {
this.queue.unshift(this.try_path); // append to the beginning of the queue
} else {
//pass
}
}
console.log(this.queue)
this.queue.pop(); // Removes last value from array
console.log(this.queue)
}
}
//-----------------------------------------------
//-----------------------------------------------
validate (path) {
this.path = path
this.validate_node = this.start_node;
for (let i = 0; i < this.path.length; i++) {
if (this.path[i] === "l") {
this.validate_node = [this.validate_node[0], this.validate_node[1]-1]
} else if (this.path[i] === "r") {
this.validate_node = [this.validate_node[0], this.validate_node[1]+1]
} else if (this.path[i] === "u") {
this.validate_node = [this.validate_node[0]-1, this.validate_node[1]]
} else if (this.path[i] === "d") {
this.validate_node = [this.validate_node[0]+1, this.validate_node[1]]
} else {
console.log("Incorrect directions in path!")
}
}
// If node already extended, dont do it again
if (this.visited.findIndex(x => JSON.stringify(x) === JSON.stringify(this.validate_node)) !== -1) {
//console.log('exists')
this.visited.push(this.validate_node);
return false
} else {
this.visited.push(this.validate_node);
}
if (this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node)) === -1 || this.maze[this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node))].node_type === 'wall') {
return false
} else {
return true
}
}
//-----------------------------------------------
//-----------------------------------------------
is_end(path) {
this.path = path;
this.validate_node = this.start_node;
for (let i = 0; i < this.path.length; i++) {
if (this.path[i] === "l") {
this.validate_node = [this.validate_node[0], this.validate_node[1]-1]
} else if (this.path[i] === "r") {
this.validate_node = [this.validate_node[0], this.validate_node[1]+1]
} else if (this.path[i] === "u") {
this.validate_node = [this.validate_node[0]-1, this.validate_node[1]]
} else if (this.path[i] === "d") {
this.validate_node = [this.validate_node[0]+1, this.validate_node[1]]
} else {
console.log("Incorrect directions in path!")
}
}
// if the node is not on the canvas then false
if (this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node)) === -1) {
return false
}
// if the node is the finish (final) node then return true
if (this.maze[this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node))].node_type === 'finish') {
// Visualize the search and then show the path that was found
visualize_search(this.visited, this.sleep, this.path, this.start_node, this.finish_node, true);
isUnderGo = false;
isProcessing = false;
this.maze = NaN;
maze.length = 0;
return true
}
return false
}
//-----------------------------------------------
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------
class BreadthFirst {
constructor(maze_in, ms) {
this.maze = maze_in;
this.queue = [""]; // Queue holds valid routes
this.speed = ms;
this.directions = [ "l", "r", "u", "d"];
this.visited = [] // Extended list to prevent extending into nodes that were already extended
this.path = "" // Will be the final shortest path
this.start_node = this.maze[this.maze.findIndex(x => x.node_type === 'start')].node_pos;
this.finish_node = this.maze[this.maze.findIndex(x => x.node_type === 'finish')].node_pos;
this.iteration = 0; // Used to see if path does not exist
this.visited_old = [] // For visualization when there is no path available
}
//-----------------------------------------------
search() {
while(this.is_end(this.path) === false) {
// I AM TOO LAZY TO FIX PROBLEM, SO I LEAVE IT LIKE THIS
if (this.queue.length === 0) { // Weird thing happening with nodes, switch up order and start over
this.queue.push("");
this.change_direction = this.directions[0];
this.directions.shift();
this.directions.push(this.change_direction);
this.iteration += 1;
if (this.iteration === 1) {
this.visited_old = this.visited.concat();
}
this.visited.length = 0;
if (this.iteration > 3) {
errorMessage("There is no path available");
isUnderGo = false;
isProcessing = false;
this.maze = NaN;
maze.length = 0;
visualize_search(this.visited_old, this.sleep, this.path, this.start_node, this.finish_node, false);
break
}
}
this.path = this.queue[0];
for (let i = 0; i < this.directions.length; i++) {
this.try_path = this.queue[0] + this.directions[i];
if (this.validate(this.try_path)) {
this.queue.push(this.try_path);
} else {
//pass
}
}
this.queue.shift(); // Removes first value from the queue, which is how queues work. FIFO (First In First Out)
}
}
//-----------------------------------------------
//-----------------------------------------------
validate (path) {
this.path = path
this.validate_node = this.start_node;
for (let i = 0; i < this.path.length; i++) {
if (this.path[i] === "l") {
this.validate_node = [this.validate_node[0], this.validate_node[1]-1]
} else if (this.path[i] === "r") {
this.validate_node = [this.validate_node[0], this.validate_node[1]+1]
} else if (this.path[i] === "u") {
this.validate_node = [this.validate_node[0]-1, this.validate_node[1]]
} else if (this.path[i] === "d") {
this.validate_node = [this.validate_node[0]+1, this.validate_node[1]]
} else {
console.log("Incorrect directions in path!")
}
}
// If node already extended, dont do it again
if (this.visited.findIndex(x => JSON.stringify(x) === JSON.stringify(this.validate_node)) !== -1) {
//console.log('exists')
this.visited.push(this.validate_node);
return false
} else {
this.visited.push(this.validate_node);
}
if (this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node)) === -1 || this.maze[this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node))].node_type === 'wall') {
return false
} else {
return true
}
}
//-----------------------------------------------
//-----------------------------------------------
is_end(path) {
this.path = path;
this.validate_node = this.start_node;
for (let i = 0; i < this.path.length; i++) {
if (this.path[i] === "l") {
this.validate_node = [this.validate_node[0], this.validate_node[1]-1]
} else if (this.path[i] === "r") {
this.validate_node = [this.validate_node[0], this.validate_node[1]+1]
} else if (this.path[i] === "u") {
this.validate_node = [this.validate_node[0]-1, this.validate_node[1]]
} else if (this.path[i] === "d") {
this.validate_node = [this.validate_node[0]+1, this.validate_node[1]]
} else {
console.log("Incorrect directions in path!")
}
}
// if the node is not on the canvas then false
if (this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node)) === -1) {
return false
}
// if the node is the finish (final) node then return true
if (this.maze[this.maze.findIndex(x => JSON.stringify(x.node_pos) === JSON.stringify(this.validate_node))].node_type === 'finish') {
// Visualize the search and then show the path that was found
visualize_search(this.visited, this.sleep, this.path, this.start_node, this.finish_node, true);
isUnderGo = false;
isProcessing = false;
this.maze = NaN;
maze.length = 0;
return true
}
return false
}
//-----------------------------------------------
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------
// Function to visualize path
async function visualize_path(path, sleep_time, start, finish) {
path_ids = [start];
// Convert string path into a list of path nodes (coordinates)
for (let i = 0; i < path.length; i++) {
if (path[i] === "l") {
push_node = [path_ids[path_ids.length - 1][0], path_ids[path_ids.length - 1][1]-1];
if (JSON.stringify(push_node) === JSON.stringify(finish)) {
break
}
path_ids.push(push_node);
} else if(path[i] === "r") {
push_node = [path_ids[path_ids.length - 1][0], path_ids[path_ids.length - 1][1]+1];
if (JSON.stringify(push_node) === JSON.stringify(finish)) {
break
}
path_ids.push(push_node);
} else if (path[i] === "u") {
push_node = [path_ids[path_ids.length - 1][0]-1, path_ids[path_ids.length - 1][1]];
if (JSON.stringify(push_node) === JSON.stringify(finish)) {
break
}
path_ids.push(push_node);
} else if (path[i] === "d") {
push_node = [path_ids[path_ids.length - 1][0]+1, path_ids[path_ids.length - 1][1]];
if (JSON.stringify(push_node) === JSON.stringify(finish)) {
break
}
path_ids.push(push_node);
} else {
console.log("INCORRECT DIRECTIONS GIVEN --> CANNOT VISUALIZE PATH")
}
}
if (JSON.stringify(path_ids[0]) === JSON.stringify(start)) {
path_ids.shift() // Removing start node from beginning or array
}
for (let i = 0; i < path_ids.length; i++) {
if (JSON.stringify(path_ids[i]) === JSON.stringify(finish)) {
//pass
} else {
await sleep(100);
document.getElementById(`${path_ids[i][0]}-${path_ids[i][1]}`).className = 'path';
}
}
}
//-----------------------------------------------
//-----------------------------------------------
// Function to visualize the search (all the nodes being searched)
async function visualize_search(visited_nodes, sleep_time, path, start_node, finish_node, visualize_instruction) {
this.visited_nodes = visited_nodes;
for (let i = 0; i < this.visited_nodes.length; i++) {
if (this.visited_nodes[i][0] > 20 || this.visited_nodes[i][0] < 1 || this.visited_nodes[i][1] > 30 || this.visited_nodes[i][1] < 1) {
//pass
} else {
let search_node_id = `${this.visited_nodes[i][0]}-${this.visited_nodes[i][1]}`
if (document.getElementById(search_node_id).className === 'finish-node') {
break
}
if (document.getElementById(search_node_id).className === 'wall-node' || document.getElementById(search_node_id).className === 'start-node' || document.getElementById(search_node_id).className === 'finish-node') {
//pass
} else {
await sleep(sleep_time);
document.getElementById(search_node_id).className = 'visited';
}
}
};
// Show path that was found (if it was found)
if (visualize_instruction === true) {
visualize_path(path, sleep_time, start_node, finish_node);
} else {
//pass
}
}
//-----------------------------------------------
//-----------------------------------------------
// Sleep for time --> milli-seconds (ms)
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
//-----------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------