Chapter 3: Programming Interactivity: Mouse Chaser


So we've got the basics down after Chapter 2, "Flash ActionScript," and we're ready for some more advanced programming concepts. After that, we'll be all set to start making games. But don't get ahead of yourself yet; take care in reading this chapter if the concepts are new to you. We're covering enough material in Chapters 2 and 3 to fill a semester-long programming course, and I don't want you to get too far too fast. I'm as anxious as you to write some games, but if we don't take care to get these foundational concepts, it will be impossible to implement the games you are dreaming about. With that said, let's get back to talking about programming.

Functions

Functions represent an important programming concept: reusability. Functions allow us to write a piece of script one time and then execute it as many times as we need to. Functions come in two types: built-in functions and user -defined functions. Built-in functions are defined by Flash and can be called by the programmer anywhere in our script. For example, a set of mathematical functions is used to find trigonometric values, square roots, exponentials, and so on. These functions are already written for you, and you can use them anytime you like. In contrast, the programmer defines user-defined functions. During the course of ActionScript programming, you will become familiar with most, if not all, of the built-in functions. You'll also become familiar with writing your own functions for use in your games. Let's look at both types.

Built-In Functions

Flash gives us a plethora of built-in functions that can do all sorts of things for us. You've already seen one: the trace function. Before we get into examples of built-in functions and their uses, we need to talk a bit about the organization of functions.

Function Organization

As I said before, Flash gives us a ton of functions to use. For our convenience, these functions are organized based on the purpose of the function. For example, all the functions that do mathematical computations are organized together. If you wanted to find the function that computes the square root of a number, you would look where all the other mathematical functions live, and there you would find the square root function.

The organization of functions uses what are called objects. Objects in Flash are somewhat complicated, and we'll be looking at them more closely in the future. For now, it's enough to say that an object is similar to a movie clip in that it can have properties and functions. Unlike a movie clip, however, an object does not represent anything on the stage. Instead, an object exists in ActionScript only and it is generally used to organize functions. For example, I've already told you that all the mathematical functions are grouped together; in fact, they are all organized inside the Math object.

If you slide open the Reference section of the Actions panel, you can see a list of everything available to you in ActionScript, including all the objects and their functions. Drag the reference section open and click on the word Objects. Doing so opens the list of object groupings that include Core, Movie, Client/Server, and Authoring. Click on Core, and you will see a list of all the core ActionScript objects. Now click on Math, and you will see two groupings: one for constants and one for methods. Click on Constants, and you will see a list of all the predefined constants used in mathematical calculations, which include things like pi and the square root of 2. Click on Constants again to close it, and then click Methods . Now you'll see a list of all the functions available on the Math object. Figure 3.1 shows a picture of this.

click to expand
Figure 3.1: The Math object contains many functions that you can use to do mathematical calculations.
Note  

When a function is attached to an object (movie clips are objects, too), the function is said to be a method of the object. In the future, I will use the terms function and method somewhat interchangeably. In general, a function, if it is attached to an object, is called a method.

To execute a function that is grouped in an object, you refer to the object name, followed by the function name , using dot notation. For example, to find the square root of a number, you could use the following script, which calls the sqrt function from the Math object:

 myNumber = 121; myResult = Math.sqrt(myNumber);    //take square root trace(myResult);                    //output result 

In this case, the variable myNumber is used when calling the sqrt function. This is called a function argument, and we'll discuss it soon. Let's finish talking about function organization first.

Some functions don't fit into the object organization very well, and as such, they are defined outside any objects. These functions are often called global functions . The trace function is an example of a global function.

To execute a global function, you simply call the function's name followed by a set of parentheses containing any arguments to the function.

Function Arguments

The key to using functions is function arguments. Function arguments are parameters that are not known to the function when it is written, but which will be known at run-time. By leaving some variables in your function undefined , you increase the reusability of the function. Let's look at the trace function as an example. Consider the following line of script:

 trace("functions are fun and useful"); 

The trace function takes one argument: a string. Because the trace function doesn't know what text is to be output, that variable is left undefined and is instead filled in at run-time by an argument to the function call. In this case, the literal string "functions are fun and useful" is given as the argument.

Some functions take more than one argument. For example, the exponential function requires two arguments: one for the base and one for the exponent to raise it to. This function is named pow , and it is, of course, found within the Math object. When more than one argument is used in calling a function, they are given as a comma-separated list. Let's see an example of this:

 myBase = 2; for(i = 0; i < 10; ++i){     myResult = Math.pow(myBase, i);    //calculate 2 to the power i     trace("2 raised to the power " + i +" is " + myResult); //output result } 

In this example, we're calculating all the powers of 2 from 0 “9. We do this in a loop, calling the Math.pow function with myBase as the base and the loop index i as the exponent. These variables are handed to the function as arguments in a comma-separated list.

Notice the way trace is used here, though. I'm using the addition operator to concatenate several pieces of data together into one large string to hand to the trace function. Flash knows that trace requires a string, so it automatically converts the number variables i and myResult into strings and then concatenates them together.

The Actions panel gives us some help when we are calling functions. The first thing it does, after we type the name of a predefined object followed by the dot operator, is pop up a list of all known members of that object. You can use this list to select the member you need. And if you type the first letter or two of the member name, Flash highlights a member of the list that has those same first letters . If the correct one is highlighted, you can simply press Enter to have Flash finish the member name for you. Figure 3.2 shows a picture of this convenient feature.

click to expand
Figure 3.2: When we type the name of a predefined object followed by the dot operator, Flash gives us a pop-up box listing all known member names .

Another way Flash helps us remember things can be seen in Figure 3.3. After we type the name of the function and the opening parenthesis, Flash pops up a little label that tells us the names of the arguments. Because the arguments are named to reflect their use, this is a convenient way to help us remember the order and use of each one.

click to expand
Figure 3.3: Flash helps us remember arguments by giving us a hint when we are typing.

Return Value

If you notice in the previous script example where we called the Math.pow function, that function call is being assigned to a variable. This is made possible by what is called a return value .

All functions can return a value if they want to. When the function is defined, if it calculates something that might be needed by the script that called it, the function can use a return statement to send the value of some variable or literal back to the script that called it. In the case of an exponent calculation, we need to know the result, so a return value is used to hand that result back out of the function after it's calculated.

Some functions don't return anything. trace is one such example. There is nothing that needs to be returned from the trace function. trace does everything internally, so nothing is returned. If you try to assign the result of the trace function ”or any function that returns nothing ”to some variable, nothing happens.

The General Form of a Function

Now that we know about functions, arguments, and return values, we can describe the general form of a function. This is simply a documentation standard that we use to describe functions. It does not represent real code that we type into the Actions panel, but instead, it is used only in this book and the ActionScript Dictionary. In the future when I describe a new function to you, I will give you the general form of the function before any examples; this will help you quickly understand the requirements to use the function. Here is the way I will write the general form of a function when I describe one:

 returnType objectName.functionName(  argument1  ,  argument2  , ... [,  optionalArgument1  ...]); 

Notice that some parts are in italic. These are pieces that you could substitute your own variables and strings for. In the future, general forms of functions will be presented this way. A piece that is typed in literally is not italicized, but one that needs to be substituted for something in your script is italicized.

The first thing to see is the returnType . This indicates the type of variable that is returned from the function. Because functions can return any variable type, this label helps us quickly identify the type of data returned. If no data is returned, the returnType identifier is labeled void.

The next thing to see is the objectName . This exists only if the function is not global and is instead contained inside some object. The general form of trace , for example, has no objectName , whereas the pow function has the object name Math .

The third thing to see is the functionName . Obviously, the function must have some kind of identification so we can tell Flash what function we want. This parameter serves to do that.

The fourth and final thing to see is the argument list. The first two arguments are given in a comma-separated list followed by an ellipsis. That indicates that there can be more arguments than just those two. In fact, the function can have as many arguments as the programmer who created it wants it to have. After that comes another argument, which is inside brackets. These brackets indicate that the argument is optional. In Flash, the arguments are required unless they are specified in brackets in the general form.

The following are the general forms of some functions you'll use often:

 void trace(  outputString  ); 

This, of course, is the general form of the trace function. It returns nothing, as indicated by the void return type. It's a global function as indicated by the lack of an object name and dot modifier before the function name. It requires only one argument: the string to be output:

 number Math.pow(  base  ,  exponent  ); 

This is the general form of the exponential function. The return type is a number ”the result of the calculation. The object containing the function is Math , and the function name is pow . There are two arguments: one for the base and one for the exponent:

 number getTimer(); 

This is the general form of the function to determine the number of milliseconds that have elapsed since the movie began playing. Its return type is a number milliseconds since the beginning of play. It's a global function, so no object name is given. The function name is getTimer , and there are no arguments.

As you can see by looking through the reference section of the Actions panel or the ActionScript Dictionary, there are a lot of functions. There is no reason to go over them all now; in fact, we'll never use some of them. Instead, we'll investigate the functions we need as we need them. Let's have a look at user-defined functions.

User-Defined Functions

The user-defined function is a staple tool in any modern programming language. It allows you to write a piece of code one time and then reuse it anywhere in the rest of your program that you might need it. When writing programs, you'll quickly find yourself writing almost the same code many times in a row. When this happens, it should clue you in that what you really should be doing is writing a function once and then calling that function every time you need it.

A function is defined simply by a block of code, set apart from the rest of your script. A function is never executed unless it is called somewhere in your script. The following is an example of two simple function definitions: one to initialize a variable, and one to increment it and print out the value:

 function initializeCounter(){     counter = 1;     trace("Counter has be initialized to 1"); } function incrementCounter(){     counter++;     trace("Counter has been incremented and its value is now "+ counter); } 

So what is going on here? First we have a function declaration. That means we are telling Flash, "Hey, we have a function. This is its name, and this is its code block." After we have declared the function, Flash knows about it and we can call it anywhere else in our script.

The first function is called initializeCounter , and its purpose is simply to reset the counter variable back to 1. The second function is called incrementCounter , and its job is to add 1 to the counter variable and then output its current value. Notice that I'm using the addition operator to concatenate the string with the variable inside the trace command. Flash knows that trace requires a string variable, so it turns the counter variable, which is a number, into a string and then sticks it on the end of the first string, which we typed in by hand as a literal.

Now that we have these two functions declared, we can use them anywhere. We'll add a bit of script after the function declarations that actually calls (invokes) them:

 initializeCounter(); for(i = 0; i < 5; ++i){     incrementCounter(); } 

If you put all that script in a movie and test it, you'll see output that looks like Figure 3.4.

click to expand
Figure 3.4: User-defined functions are written once but can be called many times from anywhere in your script.

There is a second way to define a function. It involves assigning a nameless function to a reference. I use both types interchangeably, and you should be familiar with each. The following is the alternative way to declare the initializeCounter function:

 initializeCounter = function(){     counter = 1;     trace("Counter has be initialized to 1"); } 

We'll be using functions extensively throughout the rest of this book, so you'll want to make sure they make sense. Try writing a few of your own just to play around. Make sure you have a grasp on the concept before moving on. Let's take a look at how we can use arguments and return types with user-defined functions.

Function Arguments

It is possible to use arguments with your own user-defined functions. We define function arguments as a comma-separated list of variable names in the definition of the function. The arguments that are passed to the function when it is called are copied into the variables that appear in the definition. Let's see an example of a function definition that takes two arguments:

 function foo(argument1, argument2){     trace(argument1 +  " and " + argument2 + " are the arguments"); } foo(10, "hello");         //function call to foo foo("Flash is fun", 100/40);     //function call to foo foo(50);                   //function call to foo 

As you can see, the foo function requires two arguments: argument1 and argument2 . After the definition, foo is called three times with different arguments. Notice in Figure 3.5 that the output of the third line where one argument is omitted contains a black line where the value should be. You'll need to be careful to use your own functions with the proper arguments because Flash doesn't check you on this. When you use the built-in functions, however, Flash is able to determine that you don't have enough arguments and issues an error.

click to expand
Figure 3.5: This is the output from several calls to the function we have defined. Notice the missing argument in the third line.
Note  

In the previous example, we used a mathematical calculation as the argument to a function, as in foo("Flash is fun", 100/40); .When we do this, the math (100/40) is calculated before the call to foo . The function foo is called with the result of 100/40.

In the previous paragraph, I said that the variables used when calling a function are copied into the actual function arguments. That means that if you alter one of the arguments inside the function, the copy is altered and not the original variable. Consider the following script:

 function foo(x){     x++;     trace(x); } myValue = 10; foo(myValue); trace(myValue); 

In this example, a function called foo is defined to take one argument, x . Inside the function, the argument is incremented and then the value is output with trace . After the definition of foo , a variable, myValue , is declared and assigned a value of 10. foo is then called on myValue , which then has its value output. The program executes as follows : First, foo is called with myValue as an argument. That makes a copy of myValue into x , which is incremented and output. Because this is a copy, the value of myVariable does not change; only the value of x changes. This is demonstrated by the final output statement, which prints the value of myVariable after the function foo has finished.

Return Value

Just as with built-in functions, user-defined functions can have a return value. In ActionScript, we tell our function to return a value with the keyword return . One thing to notice is that after you tell Flash to return something from a function, the value is returned immediately . That means that no other script in the function will execute, and the point of execution in your program will return to the line following the original function call. Let's look at an example:

 function division(dividend, divisor){     myResult = dividend/divisor;     return myResult;     trace("just did division"); } myNumber = division(40,3.6);    //function call to division trace(myNumber);      //output result 

What we have here is a function to execute a division. The function takes two arguments: a dividend and a divisor. The dividend is divided by the divisor, and the result is returned from the function. The last line in the function definition outputs a message with the trace function.

When the division function is called with 40 and 3.6 and the output is traced, the result looks like Figure 3.6. Notice that the "just did division" message is not output. That's because in the previous line, we called the return keyword, which terminates the function's execution and returns the result. Don't call return until you are completely finished with the work needed in the function.

click to expand
Figure 3.6: This is the result of a call to our division function. Notice that the "just did division" message is not displayed.

We've just had a serious look at functions, both built-in and user-defined. You'll see countless examples of both types as we go on. For now, let's talk about a related subject that we must master to be able to property write our own functions.




Macromedia Flash MX 2004 Game Programming
Macromedia Flash MX 2004 Game Programming (Premier Press Game Development)
ISBN: 1592000363
EAN: 2147483647
Year: 2004
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net