xxxxxxxxxx
78
let allDots = [];
let connectedLines = [];
let size = 5;
let spacing = 30;
function setup() {
createCanvas((size + 1) * spacing, (size + 1) * spacing);
resetPattern();
}
function draw() {
background(255);
stroke(220);
for (let i = 0; i < connectedLines.length; i++) {
let dot1 = allDots[connectedLines[i].x];
let dot2 = allDots[connectedLines[i].y];
line(dot1.x, dot1.y, dot2.x, dot2.y);
}
fill(0);
for (let i = 0; i < allDots.length; i++) {
ellipse(allDots[i].x, allDots[i].y, 5, 5);
}
}
function isAdjacent(dot1, dot2) {
return (abs(dot1.x - dot2.x) === spacing && dot1.y === dot2.y) ||
(dot1.x === dot2.x && abs(dot1.y - dot2.y) === spacing);
}
function DFS(dot, visited, lines) {
visited.add(dot);
for (let i = 0; i < allDots.length; i++) {
let adjacentDot = allDots[i];
if (!visited.has(adjacentDot) && isAdjacent(dot, adjacentDot)) {
lines.push(createVector(allDots.indexOf(dot), allDots.indexOf(adjacentDot)));
DFS(adjacentDot, visited, lines);
}
}
}
function connectAllDots() {
let startDot = allDots[0]; // You can choose any dot as the starting point
let visitedDots = new Set();
let lines = [];
DFS(startDot, visitedDots, lines);
if (visitedDots.size !== allDots.length) {
console.log("Not all dots are connected.");
}
return lines;
}
function resetPattern() {
allDots = [];
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
allDots.push(new Dot(i * spacing + spacing, j * spacing + spacing));
}
}
shuffle(allDots, true);
connectedLines = connectAllDots();
}
function mouseClicked() {
resetPattern();
}
class Dot {
constructor(x, y) {
this.x = x;
this.y = y;
}
}