Lesson Three: Organization Chapter 7: Functions Learning Processing Daniel Shiffman Presentation by Donald W. Smith Graphics from text
Lesson Three: Organization 7: Functions Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability 8: Objects Learning Processing: Slides by Don Smith
Modularity What is a function? A named block of code Sometimes called a ‘module’, ‘method’ or a ‘procedure’ Some examples that you know are: setup() background() draw() ellipse() mousePressed() rect() In pseudocode, they might be‘high-level’ headings: Erase background Draw Spaceship Draw enemies Move spaceship based on user keyboard command Move enemies Learning Processing: Slides by Don Smith
Pseudocode to Functions // Modularized draw() void draw() { background(0); drawSpaceShip(); drawEmenies(); moveShip(); moveEnemies(); } Each time through draw: Erase background Draw Spaceship Draw enemies Move spaceship Get keyboard command Move enemies Some functions are ‘built-in’ You can write your own! Learning Processing: Slides by Don Smith
Why use functions? Is your draw()method getting a bit long? Two key principles of good programming: 1) Modularity Break down code into smaller parts More manageable and readable Reduce the number of local variables inside a module 2) Reusability Duplicated code (copy/paste?) is not good Must maintain in multiple places Better to put duplicate code in a new function and ‘call’ it from multiple places Learning Processing: Slides by Don Smith
Exercise 7.1: Modular ‘Pong’ Planning What functions might be used in the game of pong? 1) Decide on the ‘rules’ One player or two player? One player example Two player example 2) Write Pong pseudocode (or flow chart) 3) Decide on function names For user-defined functions 4) Think about variables you will need Local (inside a function) or ‘global’? Create names you can remember Learning Processing: Slides by Don Smith
The Function ‘Definition’ Make a named ‘block’ with the following parts: Return type Function name Parameters area start block void drawShip ( ) { // Variables and code go here } // end drawShip This 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 Name with the same rules as variables (letters, digits, _) Do not use ‘reserved’ words or already used names Learning Processing: Slides by Don Smith
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 functions In this case, inside draw() You call functions by using the function name: Return type Function name Arguments area semicolon <empty> drawShip ( ) ; Learning Processing: Slides by Don Smith
Exercise 7-2: Write and call a function Display a multi-part graphic (or a Zoog!) Learning Processing: Slides by Don Smith
Bouncing Ball without Functions Group code into related ‘chunks’ Learning Processing: Slides by Don Smith
Bouncing Ball with Functions Name the ‘chunks’, declare functions, call them! Learning Processing: Slides by Don Smith
Functions with Arguments and Parameters What if you wanted to use a function to do slightly different things? Some examples you have seen that pass arguments to functions include: 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? Learning Processing: Slides by Don Smith
Arguments and Parameters Wikipedia Reference: http://en.wikipedia.org/wiki/Parameter_(computer_science) The book (and many professionals) confuse the two words. Per most texts and Wikipedia: Arguments are ‘sent’ Parameters are ‘received’ Argument comes before Parameter // drawBlackCircle receives size parameter void drawBlackCircle(int diameter) { fill(0); // passes arguments to ellipse() ellipse(50, 50, diameter, diameter); } Learning Processing: Slides by Don Smith
Multiple Arguments void draw() { background(0); // Pass drawCar four arguments drawCar( 100,100,64, color(200,200,0) ); drawCar( 50 ,75 ,32, color(0,200,100) ); drawCar( 80 ,175,40, color(200,0,0) ); } // drawCar receives four parameters void drawCar(int x, int y, int thesize, color c) { // Using a local variable "offset" int offset = thesize/4; // Draw main car body … Learning Processing: Slides by Don Smith
Passing Variables void draw() { background(0); int size = 32; // Pass drawCar four arguments drawCar( 100,100,size, color(200,200,0) ); size = size + 16; drawCar( 50 ,75 ,size, color(0,200,100) ); drawCar( 80 ,175,size, color(200,0,0) ); } // drawCar receives four parameters void drawCar(int x, int y, int thesize, color c) { // Using a local variable "offset" int offset = thesize/4; // Draw main car body … Learning Processing: Slides by Don Smith
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 integer a 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 Learning Processing: Slides by Don Smith
Exercise 7-5: Write a function definition: void draw() { float curHourly = 12.25; float raisePct = 9.0; showNewHourly(curHourly, raisePct); } // Make a comment line above the name // return type function name ( parameters ) { // Indented code goes here // Print the new hourly rate } Write your own showNewHourly()function definition to match the function call Learning Processing: Slides by Don Smith
Exercise 7-6: Bouncing Car int globalX = 0; int globalY = 100; int speed = 1; void draw() { background(0); // Call move // Call bounce // Call drawCar with global X and Y and other params; } Write your own function calls to match the functions move, bounce and drawCar Learning Processing: Slides by Don Smith
What am I really passing? Can the receiving function change the variable that you pass? That might be… dangerous… Here are the rules in Processing and Java: All primitive types (int, float, double, char…) are passed by copying the contents of the variable inside the argument into the new parameter variable. Learning Processing: Slides by Don Smith
Pass by Value (Animated) Name of Presentation - Net TeleTrain Pass by Value (Animated) Let's take a closer look at how this works. void draw() { int n = 10; println(n); byValue(n); println(n); } // end draw() void byValue(int num) { num = 73; println(n); } // end byValue() RAM 10 n 10 num 73 August 2002
Wuzzit Do? Learning Processing: Slides by Don Smith
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 block void 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 } Learning Processing: Slides by Don Smith
Assigning the return value to a variable draw calls sum with arguments sum receives values into parameters sum method calculates local total sum method returns copy of total draw assigns returned val to answer void draw() { int answer; answer = sum( 17, 42, 52); println(answer); noLoop(); } int sum(int a, int b, int c) { int total = a + b + c; return total; Learning Processing: Slides by Don Smith
A useful example: Distance between 2 pts float distance(float x1, float y1, float x2, float y2) { float dx = x1 – x2; // one side of the right triangle float dy = y1 – y2; // other side of the right triangle float d = sqrt(dx*dx + dy*dy); // hypoteneuse length return d; } Processing has a dist()function that does the same thing… Learning Processing: Slides by Don Smith
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