Week 5 - Functions

Note: We will take breaks at least once an hour

Today’s Schedule

  • reviews: variables, conditionals, loops
  • questions
  • review Pong
  • Functions
  • basic function
  • functions with parameters
  • hw: Program an monster chasing AI
  • hw: make an office hour appointment

Everything we’ve covered so far

  • variables
    • types (int, float, char, boolean)
    • random(min,max);
      • it is a float
    • casting from one variable type to another
  • Conditionals
    • if statements
      • if, else if, else
  • Loops
  • Logical operators (and, or, not)
  • functions

Functions

Functions are chunks of code that go together. They are modular and reusable!

You can think of a function as a subsection of code for a specific purpose. This helps you break your code down into manageable chunks, so the logic is clearer.

You can re-use these chunks as many times as you want.

There are two uses of the word function.

For example, ellipse() is a function we can use. Someone wrote the code underlying this function so that we can call an ellipse and draw an ellipse to the screen.

We also can create our own user-defined functions. These are functions we write ourselves.

Just creating a function does not run that function. We define a function, and we must also call that function to use it.

void setup(){
  size(400,400);
}

void draw(){
  myFunction(); //we call our code here
}

void myFunction(){
  //code goes in here
}

In this above program our setup runs once and creates our canvas. Then draw begins running. It sees a function call for myFunction() and then jumps down to void myFunction(){ ... } to run the function code. After it runs the function, it jumps back to the following line of draw.

Generally it’s good practice to give your functions clear names, like void moveBall(){ ... }.

So a simple program may look like this:

  • start with global variables
  • then comes your setup function
  • then comes your looping draw function, which typically will call other functions
  • then you define all of your user-defined functions. Give them names that describe what they do.

Why use functions?

When you code your program using functions you can slowly build up your program will smaller modular parts, as if you are snapping together different functionality with legos. As you complete a function you can add a function call into your draw (for example) and test it. If the function doesn’t work, or you are getting bugs that you need to find, you can always comment out (turn off) a function call. This makes it easier to debug.

As your program grows more complex you can add more functions or update functions. This helps you build up more complex programs without getting lost in the code.

Arguments!

In a programming context, arguments are values that are passed into a function. They are input that will be used by a function. Not all functions have arguments (meaning that not all functions need an input).

Example

function drawToCorner(int x, int y){
  //the first argument gets passed to x as an int. 
  //The second gets passed to y as an int.
  line(x, y, 0, 0); //draws a line from x,y to the top left corner
}

drawToCorner(100,200); // 100 gets passed to x, 200 passed to y
drawToCorner(50,120); //50 gets passed to x, 120 passed to y

This is not an interesting example, but it shows how to pass in arguments.

See class code examples

More about Arguments

  • You must pass as many arguments as defined in the function’s parameters
  • Your argument’s types (the value you pass) must match the function’s parameter types
  • You can pass in literal values or variables

Stopping Draw with noLoop();

noLoop(); stops draw() so that it only executes once

You can restart it with loop();

Return Types

What does void mean?

Parts of a function

  1. Return type
  2. Function name
  3. Argument(s)

Return Type - what kind of result you want out of this function. A type is an integer, float, char, etc.

Name - self-explanatory. You give it a name of your choice.

Arguments - Optional data input to a function to be used by that function.

Here is a function:

returnType functionName(parameters){
  //code of function
}

The returnType is the type of output it expects to receive. If no output is needed, the return type is void.

Example

int multiplyMe(int a, int b){
    int total = a * b;
    return total; //A RETURN STATEMENT IS REQUIRED!
}

int gimmeTheNum = multiplyMe(7, 6);
println(gimmeTheNum); //42
int newNum = multiplyMe(2, 100);
println(newNum); //200

Homework

HW Reading from Learning Processing

  • Chapter 8 - Objects
  • Chapter 9 - Arrays

Homework Challenge: Simple AI

For this challenge, you will be coding a simple AI character that will chase a player.

The player is a creature in a hostile environment. It needs to collect apples in order to survive. There is an enemy creature that is trying to capture the player. It continually moves toward the player no matter what the player does. If it captures the player by moving into its space, it has vanquished the player and the game ends.

  1. Write the program functionality needed out in pseudocode. What are the order of operations/flow? Draw it as a flow chart if that would help.
  2. Start by creating a simple stand-in for a player, such as a simple shape with color. What variables do you need? Are they global or local? What type are these variables?
  3. Now do the same for the “enemy AI.” Choose a shape and color that will contrast with the player and create needed variables.
  4. Add interaction with mouse keys. When you hold down a key, move the player. Add Left-Right-Up-Down arrow keys. Make sure you code this so the player is able to continously move as long as a key is pressed down.
  5. Now have the enemy AI chase the player. If the player is to the left, move the enemy left. When the player is right, move the enemy right. When the player is above, move the enemy up. When player is below, move the enemy down. Alter the enemy’s speed so that the player has at least a bit of a chance to get away.
  6. When the enemy has reached the player, make the screen red. Game over.

Advanced:

This section is optional. It is intended for math/CS majors and anyone else interested.

A. Make sure you’ve implemented detecting keypress in draw so that the player is moving as long as a valid arrow key is held down. –oops, Lee’s note: I already required this above. Sorry

B. Add in a reset() function so that when the player is captured, the game starts over.

C. Add in a bat. The bat moves around to an adjacent space randomly each time draw runs. If it touches the player, the bat drops the player at a random position on the screen (it could even be on top of the monster!) and then randomizes its own location and appears somewhere else on screen.

D. Add a goal, a green apple, randomly placed at start. Create a score variable. When the player reaches the green apple their score increases by 1. Then move its location and draw the apple somewhere else randomly on the level. And lastly, speed up the enemyAI by 1!

If the player is captured, use println to print out the final score and reset the score as the game begins again.