Hey, I want to write a program that randomly draws dots on the window and then connects them. The special thing about it is: the lines are not allowed to cross each other.
What the result should look like:
What the result looks like:
You have to press the Spacebar to connect the dots.
Here is the code:
ArrayList<Dot> dots;
ArrayList<Dot> connections;
Dot start;
Dot current;
void setup() {
size(600, 600);
dots = new ArrayList<Dot>();
connections = new ArrayList<Dot>();
spawnDots();
//thread("spawnDots");
}
void spawnDots() {
for (int i = 0; i < 10; i++) {
Dot d = new Dot(random(width), random(height));
d.calcDistToCenter();
dots.add(d);
//delay(250);
}
start = dots.get(0);
current = start;
connections.add(start);
}
void draw() {
background(0);
for (int i = 0; i < dots.size(); i++) {
Dot d = dots.get(i);
d.show();
}
noFill();
strokeWeight(2);
stroke(255, 127);
beginShape();
for (Dot d : connections) {
vertex(d.pos.x, d.pos.y);
}
endShape();
}
void keyPressed() {
if (key == ' ') {
calcNextDot();
}
}
void calcNextDot() {
int winnerIndex = 0;
float winnerDist = 9999999;
for (int i = 0; i < dots.size(); i++) {
Dot d = dots.get(i);
d.calcDistTo(current.pos);
float f = d.distToCenter + d.distToCurrent;
if (f < winnerDist && connections.contains(d) == false) {
winnerDist = f;
winnerIndex = i;
}
}
connections.add(current);
current = dots.get(winnerIndex);
}
class Dot {
PVector pos;
boolean selected = false;
float size = 5;
float distToCenter = 0;
float distToCurrent = 0;
Dot(float x, float y) {
pos = new PVector(x, y);
}
void show() {
stroke(255);
if (start == this) {
stroke(255, 9, 0);
}
if (current == this) {
stroke(0, 255, 255);
}
strokeWeight(size);
point(pos.x, pos.y);
}
void calcDistToCenter() {
distToCenter = dist(pos.x, pos.y, width/2, height/2);
//println(distToCenter);
}
void calcDistTo(PVector p) {
distToCurrent = PVector.dist(pos, p);
}
}
Edit: Sorry I forgot the “Dot” class now its there