xxxxxxxxxx
86
// Starter Code for "Embedded Iteration + Randomness"
//Create an 8x8 square grid such that when the user clicks
//circles appear in new locations where squares used to be
var boolDoRefresh;
function setup() {
createCanvas(420, 420);
boolDoRefresh = true;
}
//return a random color object
function randomColor(){
let r = int(random(0,255));
let g = int(random(0,255));
let b = int(random(0,255));
return color(r, g, b);
}
//return complement of color as color object
function complementaryColor(c){
let r = 255 - red(c);
let g = 255 - green(c);
let b = 255 - blue(c);
return color(r,g,b);
}
//mix color - takes in two color objects and returns color object of two mixed colors
function mixColor(c1, c2){
let r = int((red(c1) + red(c2))/2);
let g = int((green(c1) + green(c2))/2);
let b = int((blue(c1) + blue(c2))/2);
return color(r,g,b)
}
//creates square grid with random circles
function drawGrid(num){
noStroke();
background(255);
gridSquareSize = 420/num;
margin = gridSquareSize * 0.1;
drawSquareSize = gridSquareSize * 0.8;
let baseColor = randomColor(); //mixColor(randomColor(), color(255,255,255));
for ( i = 0; i < num; i++){
for ( j = 0; j < num; j++){
randomInt = Math.floor(Math.random() * 20);
if (randomInt == 1){
radius = drawSquareSize / 2;
x = margin + i*gridSquareSize + radius;
y = margin + j*gridSquareSize + radius;
let cc = complementaryColor(baseColor);
let c = randomColor();
let mc = mixColor(mixColor(c, cc), cc);
fill(cc);
ellipse(x, y, gridSquareSize - margin, gridSquareSize - margin);
}else{
x = margin + i*gridSquareSize;
y = margin + j*gridSquareSize;
let c = randomColor();
let mc = mixColor(mixColor(c, baseColor), baseColor);
fill(mc);
rect(x, y, drawSquareSize, drawSquareSize);
}
}
}
}
function draw() {
if (boolDoRefresh) {
drawGrid(10);
boolDoRefresh = false;
}
}
function mousePressed() {
boolDoRefresh = true;
clear();
}