Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop Session 5 Methods and Functions Often, in programming, you will encounter sections of code that you will want to use more than once. In these cases it is extremely helpful to place the code in a container called a method or a function. This allows the group of blocks to be ran or “called” using only a single block. Methods and functions serve two main purposes in programming: to simplify code and make it easier to change (see the presentation notes for a detailed explanation of these benefits). Methods and functions, while identical in other programming languages, do have one distinct difference in Alice; methods are a collection of blocks that do things, while functions are a collection of blocks that return a value. Functions do not directly affect the objects in the world. Methods Methods can be created by selecting an object, clicking the methods tab, and clicking “create new method.” You are then prompted to enter a name for the new method: I recommend you choose a name that briefly describes what the method does. (i.e. A good name for a method that moves a character while animating its legs could be called “walk”) Methods - example Let’s construct a quick example: create a method that simulates a strobe effect using the existing light in the world. In the object tree, select the light object and click the methods tab. Create a new method called “strobe.” Move to the properties tab and drag the brightness block to the body area of the new strobe method and enter 0 for the value. This will turn the light off. Call your new strobe method by clicking the methods tab and dragging the strobe method to replace “world.my first method” in the Events area. Methods – Parameter Drag another brightness block to the strobe method just below the previous one, only this time set the brightness to 1. If the method was called right now it would turn the light off and then turn it back on once. To make it alternate continuously, we’re going to use an infinite loop and place both blocks inside. The strobe is probably slower than you expect; we need a way of easily changing the speed or delay between the on and off states of the light. With the strobe method open, click “create new parameter” on the right side of the window, name it “delay”, set type to number, and click ok. Set the duration of both set brightness blocks to the delay parameter by clicking more, mouse-over duration, mouse-over expressions, and click delay. Methods – Parameter cont. Now, whenever you call the strobe method the delay parameter must be supplied. This is what your finished strobe method should look like: Ownership Methods and functions are, in a sense, “owned” by the object that is selected when they are created. This can be restrictive if the method affects an object other than the one that “owns” it. For example, if you are creating a method that makes an airplane fly, you would want to make sure the method is owned by the airplane and not the runway or other object in the scene. However, methods owned by the world object are accessible by any object in the scene. Subsequently, methods and functions unrelated to any specific object should be owned by world. Functions Functions are used to calculate and return a value. A real life example of a function would be finding the area of a rectangle. To find the area of a rectangle, you first need two values: the length and the width. Once those values are known, simply multiply them together and the result is the area. This task could easily be made into a function called “findAreaOfRectangle” and would expect two parameters called “length” and “width.” inside the body of the function, the two parameter variables would be multiplied and stored in a third variable called “area.” The function would then return the value of the area back to the location that the function was called from. Although most functions will make use of parameters, they aren’t always necessary as evidenced by the existence of default Alice functions such as “mouse distance from left edge” or “random number.” Functions Functions, like methods, are created by selecting an object, clicking the functions tab, and clicking “create new function. Unlike methods, functions require a return type to be selected upon creation. Functions Since functions must return something, they must return a specific type of something. If we created a function that added two numbers and returned the result, we would expect it to return a number, not a string, Boolean, or other value. Functions can not affect the world directly. You can not call methods from functions but you can call functions from methods. Functions exist only to return a value. Methods and Functions Example In session 0, you created a car that moved across the screen while it’s wheels rotated. Now, we’re going to rewrite that program using methods and functions. If you can’t find your saved project from session 0, please go back and recreate it. It’s small and, hopefully, shouldn’t take too long. First, we’re going to create a method called “drive” for the car. Make sure the car is selected then create the method. Using the clipboard, move all the blocks to this new method and replace “world.myfirstmethod” with a call to the drive method in the Events area. Methods and Functions Example We want to be able to control the speed and distance traveled by the car so let’s add those as parameters to the drive method. With the drive method open in the method editor, click the “create new parameter” button on the right side. Both parameters will be numbers (speed and distance) so create both of type Number. Replace the number of meters in the move block with the distance parameter from the top of the method editor. Methods and Functions Example We need to determine a duration for the blocks in the drive method. All we know is the speed and distance, but duration can easily be found by dividing distance by speed. Do this for all five blocks. The clipboard may speed up the process. Now we need to calculate the rotation of the wheels. Create a new function for the vehicle object named “angularDistance” of type Number. Add the two parameters, speed and distance, like you did for the drive method. Methods and Functions Example In order to determine how many times the wheels should rotate for the given distance, we need to first find the circumference of the wheel. If we remember that circumference is pi * diameter, this will be easy to calculate. By selecting one of the wheels, you can access a function called “object’s width” or “object’s height.” Since a wheel is round, either of these functions should return a value that will suffice for the diameter (these number are not exact which may lead to inaccurate wheel rotation speed). Now that we have the circumference of the wheel, we will now be able to calculate the total number of rotations. Methods and Functions Example Now that the function is complete, we can use it in the drive method. Place the new angular distance function in the revolutions area of all four wheel turn methods. Set the distance parameter of the function to the distance variable in the drive method. This finished drive method should look similar to this: By changing the parameters in the drive method call in the Events area, we can easily affect the vehicle’s movements. Project 5 Add an additional parameter to the drive method named “direction” that will accept either forward or backward and affect the object in the expected way. (Optional) Create a function to calculate duration based on distance and speed and use it in the last example in this session. Day 3 Questions What would you use to store a response from the user? How does a function differ from a method in Alice? Parameters can be used with both methods and functions. ( true/__false) What type of variable would you use to store the value returned by the function named “isWorking”? What should be used to group the blocks that make a character throw a ball? Are methods and functions absolutely necessary or do they just simplify programming? Answer Key What would you use to store a response from the user? variable How does a function differ from a method in Alice? a function returns a value where as a method does something, functions cannot affect the world Parameters can be used with both methods and functions. ( X true/__false) What type of variable would you use to store the value returned by the function named “isWorking”? boolean What should be used to group the blocks that make a character throw a ball? method Are methods and functions absolutely necessary or do they just simplify programming? simplify programming