Skip to content

Instantly share code, notes, and snippets.

@nataliefreed
Created September 28, 2016 02:06
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nataliefreed/56cf657280914602b4e0d64266031c8c to your computer and use it in GitHub Desktop.
Example of choosing a random function in P5
/*
Example of choosing a random function
Notice this program re-randomizes the row of shapes every time it's run!
*/
function setup() {
createCanvas(800, 400);
background(50);
//draw some shapes to test. These aren't randomized
flower(100, 75, 40, color(255, 0, 0, 150));
roundedSquare(150, 75, 40, color(0, 0, 255, 150));
//put the shape functions into an array
var shapeFunctions = [flower, roundedSquare];
//shift down a little
translate(100, 200);
//loop 7 times, picking a new random shape each time
//also randomize color!
for(var i=0;i<7;i++) {
//this line of code is the key to this example: pick a random number between
//0 and the length of the array, use this to retrieve one of the items in
//the array (a shape drawing function) and save it to the randomShape variable
var randomShape = shapeFunctions[int(random(0, shapeFunctions.length))];
//pick a random color with opacity 100
var randomColor = color(random(0, 255), random(0, 255), random(0, 255), 100);
//the randomShape variable now refers to a function we can run
randomShape(0, 0, 75, randomColor);
//move in x between shapes
translate(100, 0);
}
}
function draw() {
}
function flower(x, y, r, color) {
noStroke();
fill(color);
var petals = 11;
for(var p=0;p<petals;p++) {
push();
var angle = p*(TWO_PI/petals);
translate(x+r/3*cos(angle), y+r/3*sin(angle));
rotate(angle);
ellipse(0, 0, 2/3*r, r/3);
pop();
}
}
function roundedSquare(x, y, w, color) {
rectMode(CENTER); //draw square from center
noStroke();
fill(color);
rect(x, y, w, w, w/10); //5th parameter is corner radius
rect(x, y, w/1.5, w/1.5, w/10); //5th parameter is corner radius
rect(x, y, w/3, w/3, w/10); //5th parameter is corner radius
rectMode(CORNER); //set back to default square drawing mode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment