Week 4 - Loops and Functions

Note: We will take breaks at least once an hour

Today’s Schedule

  • questions
  • review assignments
  • map and constrain
  • loops
  • review differences between them
  • build pong
  • simple functions

New commands

  • constrain()

Constrain limits a variable’s range.

  • map()

Map changes the range of a variable (or reverses it).

Example:

background(map(mouseX,0,width,0,255));

Another example:

background(map(mouseX,0,width,255,0));

Loops

In previous classes we talked about coding iteratively. Iteration is the process of repeating steps over and over. Sometimes when we code we want to repeat an action again and again. Sometimes when we code we want to repeat an action again and again.
Sometimes when we code we want to repeat an action again and again.
Sometimes when we code we want to repeat an action again and again.

Question: Why do we need loops?

Two main kinds - FOR Loops and WHILE Loops

Anatomy of a while loop
while (something == true) {
  //do this
}

Warning: Don’t get stuck in an infinite loop! Make sure there is an exit condition

Example

int y = 10;

while (y < height){
    rect(100, y, 100, 10);

    y = y + 20;
}
Anatomy of a for loop

(Initialization; Test; Iterate Expression)

for (int i = 0; i < 100; i++){
    println(i);
}

When to use an if statement or for loop

If you are testing whether something is true

When you are asking a question, use an if statement.

Examples: Is my ball off screen? Is the color black?

If you need to make lots of things, use a for a loop

Examples: I need 300 circles.

The difference between a loop and the draw cycle repeating

Variable Scope

Local vs Global variables

So far when we have written variables we have been declaring them at the top of our program before our setup(). When we create variables this way we are creating global variables. Like the name global implies, these are variables that can be used everywhere, at any time. They are the easiest variables to use.

In addition to global variables are local variables. To understand what this is, it’s important to understand what we mean by the term block of code. In programming, sections of our code can be broken down into chunks or blocks. The code inside of setup(){ } is a block of code. So is the code inside draw(){ } and the code inside mousePressed(){.

TL;DR

Variables declared inside a block are local! They can only be used inside that function.

Put your global variables at the top before setup!

Variables declared outside a function block are global. They can be be used by all functions.

More info on local vs global variables can be found in your book in Chapter 6 Section 5.

Building a more complex program: Pong

We’ll build off our previous work with a ball that wraps around our screen to turn it into a basic version of Pong.

Wrapping

How do we detect that our ball is off the screen? We need to look at its x and y position. We can break this down into 4 checks with if statements.

  • If our ball is offscreen to the left (the x position is what?)
  • If our ball is offscreen to the right (the x position is what?)
  • If our ball is offscreen to the top (the y position is what?)
  • If our ball is offscreen to the bottom (the y position is what?)
if (x > width){ //if our ball's x is offscreen to the right
  x = 0; //then we reset it to the left side of the screen
}

We can do this for all four sides.

Bouncing

Now that we have our 4 if statements to detect if we have hit the edge of the screen, we can modify our code to have the ball bounce instead of wrap.

To do this, we need to modify our ball’s movement.

How do we move our ball to the right?

x = x + 1;

What if we want to move left?

x = x - 1;

We can make a variable called xspeed that can change at different times.

float x = 100;
float xspeed = 1;
  
void draw(){
  x = x + xspeed

  if (x > width){ //if offscreen to the right
    xspeed = xspeed * -1; 
    //flips our xspeed between a negative and positive number
  }
}

We also want to have the ball flip direction if it goes offscreen to the left.

if (x < 0){ //if offscreen to the left
    xspeed = xspeed * -1; 
    //flips our xspeed between a negative and positive number
}

This code is almost exactly the same.

It’s best practice to combine them together.

if ((x > width) || (x < 0)){
    xspeed = xspeed * -1; 
    //flips our xspeed between a negative and positive number
}

We can do this for the ball’s y value as well. See uploaded starter pong code for example.

Controlling the player

We can use keyPressed() function to detect key presses.

void keyPressed(){
  if (key == CODED){
    if (keyCode == UP){
      println("you've pressed up");
      //code to move up goes here
    }
  }
}

The variable keyCode is used to detect special keys such as the arrow keys (UP, DOWN, LEFT, and RIGHT) as well as ALT, CONTROL, and SHIFT. Info from the reference page on keyCode.

When working with keyCodes it is useful to first check to make sure a key is coded. We do this by nesting our code inside an if statement to make sure the key is coded.

How do you move the player up? Decrease the player’s Y. And vice versa for moving down.

Homework

  • Re-read Chapter 6 - Loops
  • Read Chapter 7 - Functions

  • see Moodle for Pong homework assignment to create a complete 2 player version.

Start with our starter “boring pong” code from class.

  1. Add a score variable. Increase the score every time you hit the ball.

  2. Add a lives variable. Start with 3 lives. When you die, cover the screen in black. (Advanced: make an interesting kill/death screen).

  3. When you hit the ball, make the ball change to a new random color. Make the ball speed get a bit faster. (Advanced: try using some randomness to make the ball more unpredictable, but don’t make it too random or it gets too hard to play).

  4. Add a second player. Add a score for the second player. Have a different ending (maybe a different screen background color?) for each of the different players’ death.

  5. Advanced students: decrease a player’s paddle height each time they miss the ball. Add a win screen if either player gets a score of 10.

  6. OPTIONAL bonus for all: make an interesting design. Change colors, sizes or try out other changes to make the gameplay or design more unique.