xxxxxxxxxx
82
// demo of minimum spanning tree
let canvasWidth = 600;
let canvasHeight = 400;
let margin = 10;
let reached = [];
let unreached = [];
class TreePoint {
constructor(x, y) {
this.x = x;
this.y = y;
}
treeDraw() {
fill('blue');
stroke(255);
strokeWeight(8);
// point(this.x, this.y);
console.log('circle', this.x, this.y, 5);
circle(this.x, this.y, 5);
}
}
function setup() {
const canvas = createCanvas(canvasWidth, canvasHeight);
for (let i = 0; i < 20; i++) {
let tp = new TreePoint(
round(10 + random(width- 20)),
round(10 + random(height-20))
);
unreached.push(tp);
}
reached.push(unreached[0]);
unreached.splice(0, 1);
let nextStepButton = createButton('Next Step');
nextStepButton.position(5, canvasHeight + 5);
nextStepButton.mousePressed(nextStep);
noLoop();
}
function nextStep() {
if (unreached.length > 0) {
let record = Infinity;
let closestReached;
let closestUnreached;
for (let r of reached) {
for (let u of unreached) {
let d = dist(r.x, r.y, u.x, u.y);
if (d < record) {
record = d;
closestReached = r;
closestUnreached = u;
}
}
}
stroke(0, 0, 255);
strokeWeight(3);
console.log('line:', closestReached.x, closestReached.y, closestUnreached.x, closestUnreached.y)
line(closestReached.x, closestReached.y, closestUnreached.x, closestUnreached.y);
reached.push(closestUnreached);
unreached.splice(unreached.indexOf(closestUnreached), 1);
}
redraw();
}
function draw() {
background(245);
for (let tp of reached) {
tp.treeDraw();
}
for (let tp of unreached) {
tp.treeDraw();
}
}