xxxxxxxxxx
145
const GREEN = "#779556";
const CREAM = "#EBECD0";
const NODE_COLOR = "#15465C";
const ACTIVE_NODE_COLOR = "#F52D1F";
const WIRE_COLOR = "#262D31";
const ACTIVE_WIRE_COLOR = "#E66E49";
let W = 0;
let destMatrix = Array(8)
.fill()
.map(() => Array(8).fill());
let drawnEdges = new Set();
const calculateDestMatrix = () => {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
let destList = [];
let dirs = [
[-1, -2],
[-1, 2],
[-2, -1],
[-2, 1],
[1, -2],
[1, 2],
[2, -1],
[2, 1],
];
for (let [di, dj] of dirs) {
if (i + di < 0 || i + di > 7 || j + dj < 0 || j + dj > 7) continue;
destList.push([i + di, j + dj]);
}
destMatrix[i][j] = destList;
}
}
};
const drawBoard = () => {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
noStroke();
if ((i + j) % 2 == 1) fill(GREEN);
else fill(CREAM);
rect(i * W, j * W, W, W);
}
}
};
const drawNodes = (x, y, radius) => {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
stroke(WIRE_COLOR);
fill(NODE_COLOR);
if (i == y && j == x) fill(ACTIVE_NODE_COLOR);
let offset = W / 2;
circle(j * W + offset, i * W + offset, radius);
}
}
};
const drawConnections = (x, y) => {
let offset = W / 2;
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
noFill();
stroke(WIRE_COLOR);
for (let [neigh_i, neigh_j] of destMatrix[i][j]) {
const edgeKey1 = `${i},${j},${neigh_i},${neigh_j}`;
const edgeKey2 = `${neigh_i},${neigh_j},${i},${j}`;
if (!drawnEdges.has(edgeKey1)) {
line(
i * W + offset,
j * W + offset,
neigh_i * W + offset,
neigh_j * W + offset
);
drawnEdges.add(edgeKey1);
drawnEdges.add(edgeKey2);
}
}
}
}
stroke(ACTIVE_WIRE_COLOR);
strokeWeight(5);
// repaint the selected wires
for (let [neigh_i, neigh_j] of destMatrix[y][x]) {
line(
x * W + offset,
y * W + offset,
neigh_j * W + offset,
neigh_i * W + offset
);
}
};
const drawViz = () => {
drawBoard();
drawnEdges = new Set();
// set active x,y using the mouse
let x = floor(map(mouseX, 0, width, 0, 7.99));
let y = floor(map(mouseY-100, 0, width, 0, 7.99));
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x > 7) x = 7;
if (y > 7) y = 7;
// draw connections
strokeWeight(4);
drawConnections(x, y);
// draw nodes
strokeWeight(2);
drawNodes(x, y, W * 0.2);
};
function setup() {
createCanvas(800, 900);
W = width / 8;
calculateDestMatrix();
}
function draw() {
background(CREAM);
translate(0, 100);
push();
noStroke();
fill(WIRE_COLOR);
textSize(35);
textAlign(CENTER, CENTER);
text("Knight's Graph Visualization", width/2, -100+40);
textSize(16);
text("By Gholamrezadar", width/2, -100+50+25);
pop();
drawViz();
}