Unit 1 Drawing, Variables, Random
How can code be used as a creative and expressive medium?

2.3 Place elements at random positions

How can we use the random function to generate different designs?


Overview

In this learning activity, students will understand the concept of functions in a different way because unlike other functions we have been using (i.g. ellipse and rect) random will return a value. Rect() "returns" an image by generating it onto the canvas. The random() function will be one of many functions that will be used in future units in order to make sketches more complex and interactive.

Suggested Duration

45 minutes

Objectives

Students will be able to:

  • Use random() to generate different positioning, sizing and grayscale fill
  • Assign random() to a function
  • Use random() in the correct scope

Student Outcomes

Abstraction:

  • Describe how I might use patterns to express an idea.
  • Describe different things I tried in order to achieve a goal.
  • Explain why using patterns is necessary when creating with a computer.

Algorithms:

  • Describe more than one set of instructions that might complete a task.
  • Describe how instructions can have different outputs depending on inputs.
  • Explain why I used specific instructions to complete a task.

Programming:

  • Experiment with the commands of a programming language.
  • Explain why I chose specific commands to communicate my instructions.
  • Discuss what can and cannot be done with a specific set of commands.

Vocabulary

random() A function that returns a number in a given interval.
int() A mathematical function that converts the value into an integer.

Resources

Instructions

Place elements at random positions

We can also place our ellipse at a random position each time our program runs. To do this, we use p5's random function. This function is different from other functions we have been using (like ellipse and rect) in that it returns a value. Each time they are called:

  • random(50, 100) returns a number between 50 and 100
  • random(1, 5) returns a number between 1 and 5
When the first parameter is omitted, random assumes it is 0:
  • random(100) returns a number between 0 and 100
  • random(5) returns a number between 0 and 5

In the p5 editor, try running the following piece of code several times:

function setup(){ ellipse(random(100), 60, 60, 60); }

Now try these, and play with their values:

  • ellipse(random(100),random(100), 60, 60);
  • ellipse(random(300, 400), 60, 60, 60);
  • ellipse(random(20, 60), random(60, 120), 60, 60);

What happens if we replace the last two parameters with calls to random?