Page 3: Control Flow: Loops, Conditionals, and Functions

3. Control Flow: Loops, Conditionals, and Functions

Effective use of control flow structures is crucial for creating complex and organized p5.js sketches. This includes for loops for repetition, if/else statements for conditional logic, and custom functions for code modularity.

3.1. Repeating Elements with for Loops

Use a for loop to draw multiple similar elements without repeating code.

function setup() {
  createCanvas(400, 400);
  noLoop(); // Draw once
}

function draw() {
  background(0); // Black background
  stroke(255); // White lines
  
  for (let i = 0; i < width; i += 20) { // Draw vertical lines every 20 pixels
    line(i, 0, i, height);
  }
  
  for (let j = 0; j < height; j += 20) { // Draw horizontal lines every 20 pixels
    line(0, j, width, j);
  }
}

3.2. Decision Making with if/else

Conditional statements allow your sketch to behave differently based on certain criteria.

let x = 0;
let speed = 5;

function draw() {
  background(220);
  ellipse(x, height / 2, 50, 50);
  
  x += speed; // Move the ellipse
  
  // Reverse direction if it hits the edges
  if (x > width - 25 || x < 25) {
    speed *= -1;
  }
}

3.3. Organizing Code with Custom Functions

Create your own functions to break down complex tasks into smaller, manageable pieces, improving readability and reusability.

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  drawTarget(width / 2, height / 2, 100); // Draw target in the center
  drawTarget(50, 50, 40); // Draw smaller target at (50,50)
}

function drawTarget(x, y, size) {
  // Custom function to draw a target pattern
  for (let i = 0; i < 5; i++) {
    fill(i % 2 === 0 ? 255 : 0); // Alternate white and black
    ellipse(x, y, size - i * (size / 5), size - i * (size / 5));
  }
}