xxxxxxxxxx
142
// Coding Train
// Coding Challenge - 167 (Prime Spiral)
// Community Contribution
// https://mathworld.wolfram.com/PrimeSpiral.html
let numPoints = 1;
let offset;
let hoveredNum = null;
let zoom = 1;
let visType = 0;
let zoomEl, visTypeEl;
const spacing = 40;
const size = 20;
const isPrime = (num) => {
for (let i = 2, s = Math.sqrt(num); i <= s; i++)
if (num % i === 0) return false;
return num > 1;
};
function setup() {
createCanvas(windowWidth, windowHeight);
textSize(40);
textFont("monospace");
textAlign(CENTER, CENTER);
offset = createVector(0, 0);
zoomEl = createSlider(0.001, 1, 1, 0.001);
zoomEl.input((v) => (zoom = v.target.value));
zoomEl.position(0, 0);
visTypeEl = createSelect()
visTypeEl.option("HSB Colors", 0)
visTypeEl.option("Change at every turn", 1)
visTypeEl.option("Reset at every turn", 2)
visTypeEl.option("White", 3)
// visualisations defined on line 73
visTypeEl.position(0, 20)
visTypeEl.changed(ev => {
visType = ev.target.value;
restartAnimation()
})
strokeWeight(2);
}
function draw() {
hoveredNum = null;
let pos = createVector(0, 0);
let stepsTillTurn = 1;
let state = 0;
numTurns = 0;
let px = 0,
py = 0;
const mPos = mouse();
background(0);
translate(width / 2, height / 2);
// Dynamic Movement and Zoom
scale(zoom);
translate(offset);
// Mouse pos debug
// ellipse(mPos.x, mPos.y, 20);
for (let i = 1; i <= numPoints; i++) {
push();
colorMode(HSB);
satVal = 100
briVal = 100;
// Different Visualisations
if (visType == 0) hueVal = i
if (visType == 1) hueVal = numTurns*90
if (visType == 2) hueVal =360* (i % stepsTillTurn)/stepsTillTurn
if (visType == 3) hueVal = 0, satVal = 0, briVal = 100
// console.log(numTurns)
let col = color(hueVal % 360, satVal, briVal);
pop();
if (isPrime(i)) {
if (p5.Vector.mult(pos, spacing).dist(mPos) < size) {
push();
fill(255, 0, 0);
hoveredNum = i;
}
noStroke();
fill(col);
ellipse(pos.x * spacing, pos.y * spacing, size);
}
stroke(col);
line(px * spacing, py * spacing, pos.x * spacing, pos.y * spacing);
px = pos.x;
py = pos.y;
if (state === 0) pos.x++;
if (state === 1) pos.y--;
if (state === 2) pos.x--;
if (state === 3) pos.y++;
if (i % stepsTillTurn == 0) {
state = (state + 1) % 4;
numTurns++;
if (numTurns % 2 == 0) {
stepsTillTurn++;
}
}
}
noFill();
stroke(255);
endShape();
resetMatrix();
fill(0, 150);
stroke(127);
rect(width - 100, 0, 100, 50);
fill(255);
noStroke()
text(hoveredNum || "", width - 50, 25);
numPoints++;
}
/**
Get mouse position, accounting for scale and translation
*/
function mouse() {
return createVector(
(mouseX - width / 2) / zoom - offset.x,
(mouseY - height / 2) / zoom - offset.y
);
}
/** Restart the animation from start */
function restartAnimation() {
numPoints = 0
}