xxxxxxxxxx
81
// Coding Train / Daniel Shiffman
// Buffon's Needle Pi Day 2023 Challenge
// https://thecodingtrain.com/challenges/176-buffon-needle
// https://youtu.be/h5ZNcAPXxew
// Code: https://editor.p5js.org/codingtrain/sketches/eMaEGlfmu
let count = 3;
function setup() {
createCanvas(720, 360);
noLoop();
}
function mousePressed() {
redraw();
// save(`graph${count}.png`);
count++;
}
function draw() {
clear();
background(255);
let buffer = 8;
let x = width / buffer;
let w = width - (2 / buffer) * width;
let h = w / PI;
let y = height - h / 2;
strokeWeight(2);
stroke(0);
line(x, y, x, y - h);
line(x, y, x + w, y);
noStroke();
fill(0);
textFont("courier");
textSize(24);
textAlign(CENTER, CENTER);
text("0", x, y + 20);
text("π/2", x + w / 2, y + 20);
text("π", x + w, y + 20);
text("0", x - 20, y);
text("½", x - 20, y - h / 2);
text("1", x - 20, y - h);
textSize(48);
text("θ", x + w + 48, y);
text("x", x, y - h - 48);
if (count > 0) {
strokeWeight(2);
stroke(0);
fill(45, 197, 244, 150);
rect(x, y - h / 2, w, h / 2);
}
strokeWeight(4);
stroke(0);
noFill();
if (count > 1) {
fill(240, 99, 164);
}
beginShape();
for (let a = 0; a <= PI; a += PI / 20) {
let px = map(a, 0, PI, x, x + w);
let py = map((1 / 2) * sin(a), 0, 1, y, y - h);
vertex(px, py);
}
endShape();
strokeWeight(8);
stroke(0);
point(x, y);
point(x + w / 2, y);
point(x + w, y);
point(x, y - h / 2);
point(x, y - h);
}