// Demo of A* algorithm import ai.pathfinder.*; Pathfinder astar; ArrayList path = new ArrayList(); int w = 20; int h = 20; int spacing; PFont font; void setup(){ size(400, 400); spacing = width / w; smooth(); rectMode(CENTER); astar = new Pathfinder(); astar.offsetX = spacing/2; astar.offsetY = spacing/2; astar.setCuboidNodes(w, h, spacing); for(int i = 0; i < 150; i++){ Node temp = getRandomNode(); temp.walkable = false; } astar.radialDisconnectUnwalkables(); } void draw(){ background(80); drawNodes(); drawPath(); // uncomment the line below to see the Connectors // drawConnectors(); } void mousePressed(){ Node a = getRandomNode(); Node b = a; while(b == a){ b = getRandomNode(); } path = astar.aStar(a, b); } Node getRandomNode(){ Node n = null; while(true){ n = (Node)astar.nodes.get((int)random(astar.nodes.size())); if(n.walkable) break; } return n; } void drawNodes(){ stroke(10); fill(255); strokeWeight(1); for(int i = 0; i < astar.nodes.size(); i++){ Node temp = (Node)astar.nodes.get(i); if(temp.walkable){ rect(temp.x, temp.y, spacing, spacing); } } } void drawPath(){ strokeWeight(20); noFill(); stroke(40, 230, 40, 150); if(path != null){ beginShape(); for(int i = 0; i < path.size(); i++){ Node temp = (Node)path.get(i); vertex(temp.x, temp.y); } endShape(); } } void drawConnectors(){ strokeWeight(1); stroke(50,50,250); for(int i = 0; i < astar.nodes.size(); i++){ Node n = (Node)astar.nodes.get(i); if(n.walkable){ for(int j = 0; j < n.links.size(); j++){ Connector c = (Connector)n.links.get(j); line(n.x, n.y, c.n.x, c.n.y); } } } }