Download presentation
Presentation is loading. Please wait.
Published byDominique Carroway Modified over 9 years ago
2
Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability 2
3
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: procedures methods subroutines We have been somewhat limited to two main functions : setup(); draw(); 3
4
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) Reusability Duplicated 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
5
What is a function? Simply, it's a named block of code Some 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
6
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 background Draw Spaceship Draw enemies Move spaceship Get keyboard command Move spaceship Move enemies Some functions are ‘built-in’ like we have seen The good news is you can write your own functions! 6
7
This is how it might look after you have broken down your program into functions: 7 // Modularized void 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!
8
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 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 8
9
The parts of a function Return type Function name Parameters area start block void drawShip ( ) { // Variables and code go here } // end block 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 below draw() Name with the same rules as variables (letters, digits, _) Do not use ‘reserved’ words or already used names 9
10
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: drawShip( ); // this calls the function 10
11
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 function void drawBlackCircle ( ) { //declared outside of the function fill(0); ellipse ( 250, 150, 75,75); }
12
Group code into related ‘chunks’ 12
13
13 // Declare all global variables (stays the same) int x = 0; int speed = 1; // Setup does not change void 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 ball void move() { // Change the x location by speed x = x + speed; } // A function to bounce the ball void bounce() { // If we have reached an edge, reverse speed if ((x > width) || (x < 0)) { speed = speed * - 1; } // A function to display the ball void display() { stroke(0); fill(175); ellipse(x,100,32,32); }
14
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
15
see web notes for example 15
16
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
17
/* 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
18
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 18
19
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 } 19
20
void 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) } 20 1. draw calls sum with arguments 2. sum receives values into parameters 3. sum method calculates local total 4. sum method returns copy of total 5. draw assigns returned value to answer
21
21 /* write your own function that calculates sales tax*/ // define global variable float yourCharge; void setup(){ yourCharge = tax( 1.00, 3.00, 5.00); // calls tax function and passes arguments to function println ("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.
22
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 Smith22
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.