functions breakdown: functions purpose modularity declaring and defining a function calling a...

22
Functions csc 23 animation scripting

Upload: dominique-carroway

Post on 14-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Functions

csc 233animation scripting

Page 2: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Functions

Functions breakdown:Functions purposeModularityDeclaring and defining a functionCalling a functionParameter passingReturning a valueReusability

2

Page 3: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Functions

Functions are a means of taking the parts of our program and separating them out into modular pieces, making our code easier to read, as well as revise.

Functions can go by other names such as:proceduresmethodssubroutines

We have been somewhat limited to two main functions :

setup();draw();

3

Page 4: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Why use functions?

Isn't your draw()method getting a bit long? Two key principles of good programming:

1) Modularity: The break down of code into smaller parts

*The code becomes more manageable and readable

*Also reduces the number of local variables inside a module

2) ReusabilityDuplicated code (copy/paste?) is not good

Because you must maintain it in multiple places

Wouldn't it be better to put duplicate code in a new function

and ‘call’ it from multiple places

4

Page 5: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Modularity

What is a function?Simply, it's a named block of codeSome examples that you already know are:setup() background()draw() ellipse()mousePressed() rect()There are more to these functions, but it has

been tucked away out of sight. We simply use them by adding

in values that the function uses within itself.

i.e.background(R, G, B);

But we have not been too concerned with that part..

Until now.

5

Page 6: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Pseudocode to Functions

Before writing a function, think about the different parts or key actions of your program. If we were to write a simple game like space invaders we could break down the code into smaller key parts such as:

Each time through draw:Erase backgroundDraw SpaceshipDraw enemiesMove spaceship

Get keyboard command Move spaceship

Move enemies

Some functions are ‘built-in’ like we have seenThe good news is you can write your own functions!

6

Page 7: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Pseudocode to Functions

This is how it might look after you have broken down

your program into functions:

7

// Modularizedvoid draw() { background(0); drawSpaceShip(); drawEmenies(); moveShip(); moveEnemies();}

All the code for each function is "tucked away" out of sight. This makes for cleaner more organized code and easier to debug!

Page 8: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Try this:Modular ‘Pong’ Planning

Let's think about what functions might be used in the game of pong?1) Decide on the ‘rules’

One player or two player?One player exampleTwo player example

2) Write Pong pseudocode (or flow chart)3) Decide on function names

For user-defined functions

4) Think about variables you will needLocal (inside a function) or ‘global’?Create names you can remember

8

Page 9: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

The Function ‘Definition’

The parts of a functionReturn type Function name Parameters area start block

void drawShip ( ) { // Variables and code go here} // end blockThis is also called ‘declaring’ the function

You are ‘telling’ the compiler that there is a new named block of code and how it works

Other Rules:Define function outside all other functions below draw()Name with the same rules as variables (letters, digits, _)Do not use ‘reserved’ words or already used names

9

Page 10: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Calling a Function

Now that we have a function, let’s use it:void draw() { drawShip(); // note the semicolon!}

You ‘Call’ functions from ‘inside’ other functionsIn this case, inside draw()You call functions by using the function name:drawShip( ); // this calls the function

10

Page 11: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Try this:Let's write our first function

11

void drawBlackCircle ( ) { // this declares and names the functions and begins the bock of code

fill(0); ellipse ( 250, 150, 75,75);} // end block drawBlackCircle function

The function will be declared outside of setup() and draw() but it has to be called from within a function.

The entire code

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

void draw(){ background( 150); drawBlackCircle ( ); // calls the function} // end draw block

// declares the functionvoid drawBlackCircle ( ) { //declared outside of the function fill(0); ellipse ( 250, 150, 75,75);}

Page 12: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Bouncing Ball without Functions

Group code into related ‘chunks’

12

Page 13: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Bouncing Ball with Functions

13

// Declare all global variables (stays the same)int x = 0;int speed = 1;

// Setup does not changevoid setup() { size(200,200); smooth();}

void draw() { background(255); move(); // Instead of writing out all the code

in draw(), we simply call three functions. bounce(); display();}

// Where should functions be placed?// You can define your functions anywhere in

the code outside of setup() and draw().// However, the convention is to place your

function definitions below draw().

// Declare functions below draw()// A function to move the ballvoid move() { // Change the x location by speed x = x + speed;}

// A function to bounce the ballvoid bounce() { // If we have reached an edge, reverse

speed if ((x > width) || (x < 0)) { speed = speed * - 1; }}

// A function to display the ballvoid display() { stroke(0); fill(175); ellipse(x,100,32,32);}

Page 14: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

debugging

Another great benefit functions have is the ease of debugging. We can simply turn off, by commenting out, parts of the program to determine if that particular function is working properly.

void draw(){background(0);// move();// bounce(0);display();

}By adding function calls one by one and executing the sketch each time, we

can more easily deduce the location of the problematic code.

14

Page 15: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

draw a rocket ship using function example

see web notes for example

15

Page 16: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Functions with Arguments and Parameters

What if you wanted to use a function to do slightly different things?Some examples you have seen pass arguments to functions such as:

size(200,200);color(100,150,0);ellipse(x, y, width, height);More?

What if you wanted to write your own function that receives parameters?

See example:

16

Page 17: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Functions with Arguments and Parameterscode example on website

/* this will take different arguments for color and size and send to function makecircle*/

void setup(){ size (500, 500);smooth();

}

void draw(){ background(255); drawCircle(?, ?, ?, ?, ?); // fill in the arguments: color is a hexidecimal or 8 bit grey value //make other versions of the elllipse

} //function definition void drawCircle(int x, int y, int itsWidth, int itsHeight, color c){ fill (c); ellipse (x,y, itsWidth, itsHeight); } /*once you have created a single ellipse use the function over and over again to create more ellipses but with difference */

17

Page 18: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Keys to Passing Arguments

You must pass the same number of arguments as defined in the function parameter list.When an argument is passed, it must be of the same type as declared within the parameters in the function definition.

An integer must be passed into an integera floating point into a floating point..

The value you pass as an argument to a function can be a:

Literal value (20, 5, 4.3, etc.), Variable (x, y, size, etc.)The result of an expression (8 + 3, 4 * x/2, random(0,10), etc.)

Parameters act as local variables inside the receiving function

They are only accessible within that function

18

Page 19: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Return types

Up until now, you have used a mysterious keyword named void before all of your functions

void setup() {void draw() {void byValue(int num) {void drawCar(int x, int y, int thesize, color c) {

Remember the parts of a function definition?Return type Function name Parameters area start blockvoid drawShip ( ) {

Here is an example that ‘return’ an int:int sum(int a, int b, int c) { int total = a + b + c; return total; // Return a copy of a local variable}

Page 20: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Assigning the return value to a

variablevoid draw() { int answer; (5)answer = (1) sum( 17, 42, 52 ); println(answer); noLoop();}

(2)int sum(int a, int b, int c) { int total = a + b + c; (3) return total; (4) }

1. draw calls sum with arguments2. sum receives values into parameters

3. sum method calculates local total4. sum method returns copy of total5. draw assigns returned value to answer

Page 21: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

You try: sales tax calculator

21

/* write your own function that calculates sales tax*/

// define global variablefloat yourCharge;

void setup(){yourCharge = tax( 1.00, 3.00, 5.00); // calls tax function and passes arguments to functionprintln ("Your total charge is = " + yourCharge);}

// define function for sales tax/////////////float tax( float a, float b, float c){ // receives the arguments and runs the method to solve float subtotal = a + b + c; // total items cost float taxRate = .0625; // tax rate float tax = subtotal * taxRate; //total tax amount needed float totalCharge = subtotal + tax; return totalCharge; }

You write the function using above info.

Page 22: Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability

Summary Functions are useful for many tasks

1) Break code into smaller ‘named’ chunks 2) Prevent duplication of code 3) Make useful ‘utilities’ that can be reused

Processing is really a ‘function library’ Provides functions such as line(), ellipse(), rect()

You can write code inside functions that Processing calls▪ setup() and draw()

You can define your own functions Pass ‘arguments’ to functions to tell them what to

do They are received as ‘parameters’ Primitive types are passed by value

Functions can return values

Learning Processing: Slides by Don Smith 22