xxxxxxxxxx
178
function removeFromArray(arr,elt){
for(var i = arr.length - 1; i >= 0; i--){
if(arr[i] == elt){
arr.splice(i,1);
}
}
}
function heuristic(a,b){
//var d = dist(a.i,a.j,b.i,b.j);
var d = abs(a.i-b.i) + abs(a.j-b.j);
return d;
}
var grid = [];
var openSet = [];
var closedSet = [];
var path = [];
var rows = 50;
var cols = 50;
var start;
var end;
var w,h;
var current;
function Spot(i,j){
this.i = i;
this.j = j;
this.f = 0;
this.g = 0;
this.h = 0;
this.neighbors = [];
this.previous = undefined;
this.wall = false;
if(random(1) < 0.3){
this.wall = true;
}
this.show = function(c){
fill(c);
if(this.wall){
fill(0);
}
noStroke(0);
rect(this.i * w,this.j * h,w,h)
}
this.addNeighbors = function(grid){
if(i<cols - 1){
this.neighbors.push(grid[this.i+1][this.j]);
}
if(i>0){
this.neighbors.push(grid[this.i-1][this.j]);
}
if(j < rows-1){
this.neighbors.push(grid[this.i][this.j+1]);
}
if(j > 0){
this.neighbors.push(grid[this.i][this.j-1]);
}
}
}
function setup() {
createCanvas(400, 400);
console.log('A*');
w = width/cols;
h = height/rows;
for(let i = 0; i < cols; i++){
grid[i] = [];
for(let j = 0; j < rows; j++){
grid[i][j] = new Spot(i,j);
}
}
for(let i = 0; i < cols; i++){
for(let j = 0; j < rows; j++){
grid[i][j].addNeighbors(grid);
}
}
start = grid[0][0];
end = grid[cols-1][rows-1];
start.wall = false;
end.wall = false;
openSet.push(start);
}
function draw() {
aStar();
}
function aStar(){
for(var i = 0; i <4; i++){
if(openSet.length > 0){
var winner = 0;
for(var i = 0; i < openSet.length; i++){
if(openSet[i].f < openSet[winner].f){
winner = i;
}
}
current = openSet[winner];
if(current == end){
noLoop();
console.log("done");
}
removeFromArray(openSet,current);
closedSet.push(current);
var neighbors = current.neighbors;
for(let i = 0; i < neighbors.length; i++){
var neighbor = neighbors[i];
if(!closedSet.includes(neighbor) && !neighbor.wall){
var tempG = current.g + 1;
if(openSet.includes(neighbor)){
if(tempG < neighbor.g){
neighbor.g = tempG;
}
}else{
neighbor.g = tempG;
openSet.push(neighbor);
}
neighbor.h = heuristic(neighbor,end);
neighbor.f = neighbor.g + neighbor.h;
neighbor.previous = current;
}
}
}else{
console.log('No Solution')
noLoop();
//no solution
}
}
//background(0);
for(let i = 0; i < cols; i++){
for(let j = 0; j < cols; j++){
grid[i][j].show(color(255));
}
}
for(let i = 0; i < closedSet.length; i++){
var d = heuristic(closedSet[i],end);
closedSet[i].show(color(map(d,cols+rows,0,100,255),map(d,cols+rows,0,0,255),0));
}
for(let i = 0; i < openSet.length; i++){
openSet[i].show(color(0,200,0));
}
path = [];
var temp = current;
path.push(temp);
while(temp.previous){
path.push(temp.previous);
temp = temp.previous;
}
for(let i = 0; i < path.length; i++){
path[i].show(color(0,0,255));
}
}