🔄Lesson 6 - For Loops && Conditional Statements

How can we identify when our mouse is in a specific section of our canvas?

Overview

This lesson covers using for loops to divide the canvas into sections and compound conditional statements to determine if the mouse is located inside of one of the sections.

Lesson Objectives

Students will be able to:

  • Use for loops to create multiple shapes

  • Design a program which can be altered/adjusted by changing a variable value.

  • Create compound conditional statements using logical operator

Suggested Duration

1 period (45 minutes)

NYS Standards

9-12.CT.5 Modify a function or procedure in a program to perform its computation in a different way over the same inputs, while preserving the result of the overall program.

9-12.CT.8 -Develop a program that effectively uses control structures in order to create a computer program for practical intent, personal expression, or to address a societal issue.

9-12.DL.1 Type proficiently on a keyboard.

9-12.DL.2 Communicate and work collaboratively with others using digital tools to support individual learning and contribute to the learning of others.

Vocabulary

Compound Conditional - A conditional statement which requires more than one condition to be evaluated.

Refactoring - Improving the design and/or structure of your code without changing its functionality or intended output.

Rollover - A visual image or area that changes when the mouse cursor is placed over it.

Planning Notes

This is building on the previous lessons where students created a mouse theremin that controlled the volume and pitch of an oscillator. However, the changes in pitch were made by incrementing in hertz which is much more granular in regards to the changes in frequency that we hear. In this project, students will create an instrument where there will only be a small number of pitches that can be produced which we will later access through making an array that stores these pitch values.

Students will get a sense of what this project will look like by analyzing two different websites that have a similar design. They will then brainstorm what will need to be done in order to design their own version of this project.

This lesson will not involve working with sound in any way. It is going to focus on the visual component of the project which involves dividing the canvas into equal parts and highlighting that part in a different color when the mouse is over it (this is often referred to as a rollover). While it will only take about 10 lines of code to do this, students will use several programming concepts that have not yet been covered in this curriculum: For Loops, Conditional Statements, Logical Operators. This lesson does assume that students have had experience with these concepts prior to this lesson. There are opportunities provided to go over these concepts in more detail. However, if your students are not familiar with these concepts, it is recommended to take some additional time to go over them before trying to make this project.

This lesson also includes multiple opportunities for students to turn and talk to determine the solution to a problem or explain what the code is doing. The share outs that follow these discussions can be used as formative assessment opportunities. You could also consider incorporating these discussion responses into an interactive slide presentation (Nearpod, Peardeck etc) or some other tracking method. This will provide you with a better sense of how all students are doing in regards to the concepts covered instead of just those who are sharing out their responses. Consider any pre-existing routines or discussion protocols that you already have to help tailor this to fit your classroom best.

Materials

Theremin Website Compare/Contrast sheet

Divided Canvas For Loop Planning Document

Resources

ICM Lesson - For Loops

ICM Lesson - Conditional Statements

ICM Lesson - Logical Operators

Assessments

Formative:

  • Student brainstorming solutions to how to divide canvas into multiple sections.

  • Planning document for finding values needed to divide canvas equally

  • Refactoring For Loop code

  • The iteration and sequence of declaring and using variables in code

  • Knowing if the mouse is inside a specific area of the canvas

  • Constructing a compound conditional statement using logical operators and correct conditions.

New Code in this lesson

None of the code covered in this lesson should be new to your students. You should determine how much of a review they may need on these concepts before covering this lesson.

Do Now/Warm Up

Have students go to the following website:

You can also have students read some background information on Clara Rockmore to provide context for this Google Doodle:

Video of Clara Rockmore playing the Theremin

Students can skip the lesson part of the Doodle by clicking the play button in the bottom right hand corner and go right to the free-play section.

After playing around for 2-3 minutes on the website, students should use the Theremin Website Compare/Contrast sheet and write down what they see is similar to the original mouse theremin sketch that we made and what is different.

Students can bring up the mouse theremin sketches they made in an earlier lesson as an example

Design Planning

Have students share out observations they made for similarities first

Examples: Both use the mouse to control the pitch/volume / Both use oscillators

Have students share out observations they made about what was different in the Clara Rockmore Google Doodle. Emphasize specific observations relevant to the design:

  • You could only play certain notes

  • The screen was divided into sections.

  • Each section lights up when the mouse is over it.

There are other design elements that will not be directly covered but could be considered as an extension for more advanced students later on:

  • Glowing circle that follows the mouse

  • Note Names are inside of each section

Have students focus on the two non-sound related design elements first

  • Dividing the canvas into sections

  • Highlight each section when the mouse is over it.

Give them 5 minutes to brainstorm how to do this in p5.js and what type of code they would need. This can be a good opportunity to assess where students are at to help tailor this lesson to your class ability level. For example, if students say they could make several rectangles for the sections but think they need to make each one individually, this is a good indicator that you will need to cover for loops. However, if most students recognize the need for a for loop, then you may not need to spend much time going over the structure and syntax.

Dividing Canvas into Sections - For Loops

Have students open a new sketch in the p5.js Web editor and name it Mouse Instrument.

The first thing we want to do is divide up the canvas into equal sections with each section representing a specific pitch, as we saw in the Theremin app and Clara Rockmore Google Doodle. The way we will do this is by making multiple rectangles of equal size that go from left to right and span the height of the canvas. It may help to share an image so students have a clear idea of what they are going to do.

Example:

To do this, we are going to use a for loop which allows us to execute a specific piece of code a specific number of times.

Optional: If needed, take this opportunity to review the syntax and structure of a for loop. If your students are more comfortable with this structure, you can move along to the next step.

The code we want inside our for loop is to create multiple rectangles to divide up the canvas. If needed, review the syntax to make a rectangle by having students check the documentation. Inform students that some of the arguments we pass into the rect( ) function will remain the same each time through the for loop while other arguments will have to be different each time. Allow 1-2 minutes to consider which will change and which will remain the same.

The two arguments that will remain the same each time will be the starting y position and the height of the rectangle. Since we want it to span the entire canvas, it will always start at 0 (the top of the canvas) and we can use the built in variable height for the height of the rectangle.

The two arguments that will change each time will be the starting x position for each rectangle (each rectangle needs to start in a different place on the x axis to cover the whole canvas) and the width of the rectangle (each rectangle needs to be the same size width and the sum of the width of all the rectangles needs to be equal to the width of the canvas).

Allow 5 minutes to work in pairs to figure this out. Provide planning document with canvas visual to assist. Have students try to figure out what numbers we would need for each rectangle if we wanted to divide the canvas (assuming the canvas width is 400 pixels) into 5 equal sized rectangles. (warning: There will be math!)

Have students share out responses on how they figured out the answer.

Answer:

Rectangle Width: 80

Starting X position: 0, 80, 160, 240, 320

To find the width, students will have divided the canvas size (400) by the number of rectangles we want (5) - 400/5 = 80

(Mention to students they will want to remember this for later)

Then to find the starting X position for each rectangle, begin at 0 and count up by 80 five times - 0, 0 + 80 = 80, 80 + 80 = 160, 160 + 80 = 240, 240 + 80 = 320

Explain to students that this second part is basically what our for loop is going to do for us.

Present first way this can be done:

for(let i = 0; i < width; i += 80){
    rect(i, 0, 80, height);
}

Refactoring

Although this code works, it is very specific to this one situation where we want 5 rectangles across the canvas that is 400 pixels across the X axis. What if we decided we want 6 rectangles? We shouldn’t have to go back and do all that math to figure out how to divide up the canvas into 6 parts.

Refactoring code means to change/modify parts of our code to make it shorter, more effective, modular, and/or adaptable to different situations. While we are going to stick with the example of 5 rectangles for now, we want to leave open the possibility that we might want to change this later on, so we want to write our code in a way that makes it easy for us to do this without having to change a lot of numbers or other lines of code.

In this program, it is going to be better if the variable i in the for loop is acting as a counter of the number of times we want to execute the code (in this case, how many rectangles we want to make)

for(let i = 0; i < 5; i++)

Have students turn and talk to discuss how they could alter the code in the rect( ) function to get the same results if our for loop looks like this.

Provide 2-3 minutes to talk and then have students share responses. It would be recommended to get volunteers as it is possible some pairs may not find a solution.

Note: Depending on how many students are able to determine how this works, you can choose to have students share out or walk them through it.

When we make the counter variable i increment by 1 each time through our loop, the value of i each time would be:

If we look at the starting points we got for each rectangle, we can see that each one is what we get if we multiple the rectangle width (80) by the value of i each time through the loop:

Therefore, we can just multiply i by the width of the rectangle to get the x starting point for each rectangle:

for(let i = 0; i < 5; i++){
    rect(i*80, 0, 80, height);
}

Another thing we can refactor is the width of each rectangle. Have a student remind us of how we got the number 80 when students shared out solutions earlier.

“Divide the canvas size (400) by the number of rectangles we want (5)”

400/5 = 80

We know that there is already a built in variable for the width of the canvas, width. So we can make a new variable to hold the value of the width divided by the number of rectangles we want.

let rectWidth = width/5;

We can then replace the number 80 in our code with this variable:

let rectWidth = width/5;
for(let i = 0; i < 5; i++){
    rect(i*rectWidth, 0, rectWidth, height);
}

This will also save us any additional changes if we decide to change the size of the canvas.

Ask students to now consider what we would have to change if we wanted to divide the canvas into 6 circles.

Answer: We would need to change the two 5s in our code to 6.

Since both of these 5s represent the same idea (the number of rectangles), we could also make this a variable so that if we want to change the number of rectangles, we just change the value of that variable. This also means if later on we need to refer to the number of rectangles for some reason, we can also use this variable.

Right above the rectWidth variable, make a variable called numRects.

let numRects = 5;

Ask students why we put it above the variable rectWidth and not below.

Point out that we must declare this variable before the rectWidth variable because that variable will be used to determine the value of the rectWidth variable.

Now change both 5s to the variable numRects

let numRects = 5;
let rectWidth = width/numRects;
for(let i = 0; i < numRects; i++){
    rect(i*rectWidth, 0, rectWidth, height);
}

Have students experiment with changing the value of the numRects variable and see how it affects the result on the canvas. They will see that all they need to do is change that one value and it will divide up the canvas into that number of equal sections.

Adding Color with mouse rollover - Conditional Statements

The next step is to add a visual component to our project by highlighting the rectangle that the mouse is currently hovering over. This is often referred to as a rollover. Explain to students as “IF the mouse is inside the rectangle, make it red. Otherwise, make the rectangle white.” Ask what will we need in our code to do this. Students should be familiar with the concept of a conditional statement for this lesson, so the word “IF” should be a give away that we will need a conditional statement.

Optional: If needed, take this opportunity to review the syntax and structure of a conditional statement. If your students are more comfortable with this structure, you can move along to the next step.

Write as pseudocode to remind students of conditional statement syntax:

Ask students how do we know if the mouse is inside a certain rectangle. Allow 2-3 minutes to turn and talk to discuss. Reconvene to share responses.

We need to know that the mouse is inside of the 4 sides of the rectangle. Since the top and bottom of our rectangle is also the top and bottom of the canvas, we do not need to worry about that part. So we just need to know if the mouse is between the left and right side of our rectangle.

What variable tells us where the mouse is on the x axis? - mouseX

Discuss how we know the values of the left and right side of our rectangle. The left side is the same as our x starting position. The right side would be our x starting point plus the width of the rectangle.

Have students check the code and determine which part tells us the x starting point of a given rectangle and the width of a given rectangle. Get volunteers to share out

x starting point = i*rectWidth

Rectangle width = rectWidth

In order to code this, we need a compound conditional statement.This means there is more than one condition which needs to be met.

Condition #1 - Is the value of mouseX greater than the x starting point?

Condition #2 - Is mouseX less than the x starting point plus the width of the rectangle?

This will require a logical operator in our conditional statement - && (AND)

Remind students that this operator is used when there are multiple conditions that both need to be true in order for the code inside the condition to execute.

Now that we have worked this out, we can enter the code into our sketch. Inform students we will put this conditional statement inside of our for loop, so it will work for all our rectangles on the canvas. Present students with this prompt and give them time to work it out.

Remind them of the code we already have that can be used for our conditional statement:

x starting point = i*rectWidth

Rectangle width = rectWidth

Position of mouse on x axis = mouseX

Final result:

if(mouseX > i*rectWidth && mouseX < i*rectWidth + rectWidth){
    fill('red');
} else {
    fill('white');
}

Final Sketch Code

Wrap Up

Have students reflect on the steps that it took to get us to this point. Ask them to think about some of the things we did which could be used as best practices in the future.

Possible responses could include:

  • Drawing out our idea before we code it

  • Refactoring to make our code more efficient

  • Using variables instead of specific values in case we need to make changes later

  • Pseudocoding

Have students try to elaborate on why they found these practices to be beneficial. The hope is that if they are able to articulate why they found a certain method of coding to be helpful, they will be more likely to incorporate that into future coding projects.

Next lesson they will be adding sound to this project.

Extensions

Challenge for students who finish early:

Refactor the code to do the same thing without having an else statement

Solution:

fill('white');
if(mouseX > i*rectWidth && mouseX < i*rectWidth + rectWidth){
    fill('red');
}

Last updated