xxxxxxxxxx
// Step 1: Define the necessary variables
let numColumns, numRows;
let rectSize = 50;
let colors = [];
// Step 2: Setup function to initialize variables and canvas
function setup() {
createCanvas(500, 500);
numColumns = width / rectSize;
numRows = height / rectSize;
// Step 2a: Initialize colors
for (let i = 0; i < numColumns; i++) {
colors[i] = [];
for (let j = 0; j < numRows; j++) {
colors[i][j] = color(random(255), random(255), random(255));
}
}
}
// Step 3: Draw function to create the pattern
function draw() {
background(255);
// Step 3a: Nested for loops to draw rectangles in a grid
for (let i = 0; i < numColumns; i++) {
for (let j = 0; j < numRows; j++) {
fill(colors[i][j]);
rect(i * rectSize, j * rectSize, rectSize, rectSize);
}
}
}
// Step 4: Add interactivity via keyboard or mouse
function keyPressed() {
// Step 4a: Change colors on key press
if (key === 'c') {
for (let i = 0; i < numColumns; i++) {
for (let j = 0; j < numRows; j++) {
colors[i][j] = color(random(255), random(255), random(255));
}
}
}
}
// Step 5: Add randomness to the pattern
function mousePressed() {
// Step 5a: Randomly change individual cell color on mouse press
let randomColumn = floor(random(numColumns));
let randomRow = floor(random(numRows));
colors[randomColumn][randomRow] = color(random(255), random(255), random(255));
}