-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolve.js
113 lines (86 loc) · 2.24 KB
/
solve.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
var openSet=[];
var closedSet=[];
var start;
var end;
var path=[];
function solve(){
//solve();
console.log("solve");
if(openSet.length>0){
var winner=0;
for(var i=0;i<openSet.length;i++){
if(openSet[i].f < openSet[winner].f)
winner=i;
}
curr=openSet[winner];
if(curr===end)
{
//noLoop();
console.log("DONE!!");
}
removeFromArray(openSet,curr);
closedSet.push(curr);
var neighboursForCurrent=curr.neighbours;
for(var j=0;j< neighboursForCurrent.length;j++){
var neighbour=neighboursForCurrent[j];
if(neighbour!=null){
if(!closedSet.includes(grid[neighbour]) && !hasWall(curr,grid[neighbour],j) ){
var tempG= curr.g+ heuristic(curr,grid[neighbour]);
// Is this a better path than before?
var newPath = false;
if(openSet.includes(grid[neighbour])){
if(tempG< grid[neighbour].g)
grid[neighbour].g=tempG;
newPath = true;
}
else{
grid[neighbour].g=tempG;
newPath=true;
openSet.push(grid[neighbour]);
}
// Yes, it's a better path
if (newPath) {
grid[neighbour].h=heuristic(grid[neighbour],end);
grid[neighbour].f= grid[neighbour].h+grid[neighbour].g;
grid[neighbour].previous = curr;
}
}
}
}
}
else{
console.log("No solution");
noLoop();
}
}
function removeFromArray(arr, e){
for(var i=arr.length-1;i>=0;i--){
var c=arr[i];
if(c.x==e.x && c.y==e.y )
arr.splice(i,1); //winner=i;
}
}
function checkInArray(arr, e){
for(var i=arr.length-1;i>=0;i--){
var c=arr[i];
if(c.x==e.x && c.y==e.y )
return true; //winner=i;
}
return false;
}
function getDist(a,b){
return dist(a.x,a.y,b.x,b.y);
}
function heuristic(a,b){
var distance= abs(a.x-b.x) + abs(a.y-b.y);
return dist(a.x,a.y,b.x,b.y);
}
function hasWall(a,b,i){
console.log(a.x,a.y,b.x,b.y,i);
var wallForA=a.walls[i];
var wallForB=b.walls[(i+3)%6];
if(wallForA== true && wallForB==true){
return true;
}
else return false;
}