Basic Programming


You've been introduced to the idea of an object, but before you can delve any deeper into object-oriented programming, you need to know a little bit about some basic programming concepts. You already know that you should end any statement with a semicolon (;). What else do you need to know? Well, let's start with variables .

Variables

Variables have popped up a couple of times in the earlier chapters of this book, but in case you need a refresher, variables are just placeholders for information. You can put information into and take information out of a variable.

Variables have what is called scope. The scope of a variable is where it lives in the movie or when it is actually available for you to use. There are two types of variable scopes in Flash: global and local.

The information held in a global variable is available no matter where you are in a Flash movie. You do have to know how to access that variable (its path ), but as long as you do, you can use the information it holds. There are two ways to create a global variable. You can use the Set action or you can just assign a variable a value using the = operator. For example, the following two lines of code do exactly the same thingthey both assign a value of 10 to a variable called myNumber:

 set(myNumber, 10);  myNumber = 10; 

Not all variables need to be available at all times. In fact, sometimes it's preferable for variables to expire. For example, "i" is frequently used in programming as a counter. You don't need that counter to be available in memory after you're done with it. All you have to do is use the var action and create the variable inside a function. The syntax for creating a local variable is as follows :

 var i 

Next we take a look at how you use methods and functions in Flash 5.

Method Syntax

You've probably noticed that methods and functions have a set of closed parentheses following the name. For example, you might see loadMovie() or attachMovie(). You use the parentheses to pass information, usually referred to as parameters or arguments, into and out of the method being used. For example, the attachMovie() method takes three pieces of information: the name of the movie to be attached, the new name for the instance of the movie on the Stage, and the level number on which the movie should live. The syntax for attachMovie() looks like this:

 attachMovie("movieName","newName",1); 

Each method has its own requirements for the information, if any, that it needs. You'll quickly become familiar with these, but if you get stuck, just look up the method in the ActionScript Dictionary (Help > ActionScript Dictionary). You also can check the contents of Appendix A, "ActionScript Quick Reference," in this book.

Arrays

The fastest way to clear a group of nonprogrammers out of a room is to start talking about arrays. You don't need to fear arrays, however; they're actually easy to work with. Arrays are used to hold lists of information. You reference a specific item (element) in an array by referring to its index. The index tells you the item's place in line. Creating an array is easy; all you need to do is type the following:

 fruit = new Array(); 

This line of code creates a new empty array object called "fruit." You also can populate the array at the same time you create it by passing to it the list of information you want it to hold. For example:

 fruit = new Array("apples","oranges","bananas"); 

creates a new array with three elements:

 fruit[0] == apples;  fruit[1] == oranges;  fruit[2] == bananas; 

Notice that arrays begin their numbering system with 0. You just have to cope with that in programming. Get used to the idea of arrays; you'll be using them a great deal.

Curly Braces

Curly braces are the bane of new programmers. Don't worryyou can tame the curly brace beast , or at least come to terms with it.

Curly braces are used to group sections of code. That is their sole purpose in life. They always come in pairs, so any time you need to enclose a block of code in curly braces, type both braces at the same time and then separate them with a return. For example, when you call an onClipEvent() method, you want to perform a series of actions that are triggered by the clip event. Those actions need to be grouped like this:

 onClipEvent(enterFrame) {     first do this;      next do this;  } 

Do the curly braces have to be positioned in the manner shown? No, but after you get used to curly braces, it actually does make reading your code easier. Open your curly brace on the same line as the event or statement under which your code is being grouped and close the curly braces after the last line of grouped code.

Notice that the code inside the curly braces is indented. Indentation is a nicety, nothing more. You use it to make your code more readable. This becomes important as your code becomes more complex.

The next section explores some of the different types of loops you can use when scripting in Flash 5.

Loops

When you are programming, there are times when you'll want to run a certain block of code multiple times. For instance, you might want to output the numbers 120. One option would be to write 20 trace statements to print the numbers 120 in the Output window:

 trace(1);  trace(2);  trace(3);  trace(4);  .  .  .  trace(20); 

Although that is doable, there's an easier way. You can use something known as a loop . Loops are used to run the same code a set number of times. You tell the loop how many times you would like the code to run, and it "loops" through the code that many times (hence the name loop). Loops are particularly useful when you need to run the same code more than once. Loops are even more useful when the number of times you wish to run the code is variable or based on a changing condition. For example, you might want to output the numbers 1 x, where x is calculated earlier in your program. In this instance, you can't write a series of trace statements because you don't know in advance how many you need to write. This is a perfect time to use a loop. Loops are a simple and effective way to repeat code.

There are two types of loops of which you need to be aware. The first type is a conditional loop . A conditional loop repeats a chunk of code until a certain condition is methence the name. For instance, suppose you want to run a piece of code until a variable, myNumber, is less than 10. This situation is perfect for one type of conditional loop the while loop . A while loop is a conditional loop in which the condition is checked before entering the loop and before every iteration of the loop. It's always a good idea to initialize your variables so that you know the value with which you're starting. In this case, myNumber has an initial value of 0. The while loop would look like this:

 myNumber = 0;  while (myNumber < 10) {     trace(myNumber);      myNumber++;  } 

This block of code essentially says, "For as long as myNumber is less than 10, run my code." The actual code that's being processed prints the current value of myNumber in the Output window and increments myNumber by 1 on each pass through the loop. You can test this for yourself. Just open a new Flash movie, select frame 1, and in the Actions panel, enter the code in the previous code block. When you test your movie, Flash prints the numbers 09.

The other type of conditional loop is the do . . . while loop. This loop is very similar to the while loop in that it also runs code until a certain condition is met. The difference between the while and do . . . while loops is that the do . . . while loop checks the condition after the code is run, and the while loop checks the condition before the code is run. This means that a do . . . while loop always runs its code at least one time. We can write the previous loop as a do . . . while loop, and it would look like this:

 myNumber = 0;  do {     trace(myNumber);      myNumber++;  } while (myNumber < 10); 

This loop does essentially the same thing as the previous loop. However, it checks the state of myNumber at the end of the loop instead of at the beginning. This type of loop is very helpful in situations in which you know that you want the code to run at least once.

The second type of loop is an iterative loop . These loops are simply counting loops. Iterative loops repeat a block of code a certain number of times. For instance, if you wanted to repeat some code five times, and there is no condition as there are in conditional loops, you would set up an iterative loop to handle it.

The most commonly used iterative loop is the for loop. In the for loop, you specify the starting point, ending point, and an increment factor. The increment factor specifies how you want to step through the loop.

When we look at the code this time, you'll do something a little different. Say that myNumber already has a value of 10 and that you want to loop through a piece of code that many times. You can use a counter"i" commonly is usedto monitor how many times the loop has processed, as shown in the following code:

 myNumber = 10;  for (i=1; i<=myNumber; ++i) {     trace(i);  } 

There are three parts to the opening statement of the for loop. The first part, i=1, simply initializes the variable to 1. The second part, i<=myNumber, is a conditional expression that the loop uses to determine if it is done. After every pass through the loop, this condition is checked to see if i is still less than or equal to myNumber. When i is greater than myNumber, the loop is exited. The last part, ++i, increments i by 1 every time the loop is processed.

As you can see, working with loops is fairly simple. As an added bonus, using loops makes your code more efficient, readable, reusable, and modular. Practice with loops on your own until you're comfortable with them. You'll be seeing them again in this and subsequent chapters.

Dot Syntax

If you want to access any of the properties or methods of an object, you use dot syntax. In dot syntax, you write the name of the object, a dot (period), and the property or method you want to access. Here is an example of what a statement in dot syntax looks like:

 myObject.myMethod(); 

In this example, myMethod is a method of the object myObject. This statement simply tells your program to run the code that exists in myMethod. Using dot syntax is like giving your program directions on how to get to the code you want it to run next. Think of it as giving a person directions. For example, if you want someone to retrieve a package from your office desk, and he or she doesn't know where your desk is, you might give him or her the following directions:

  1. Enter the building.

  2. Go to the fifth floor.

  3. Go to my desk.

  4. Pick up the package.

In dot syntax, the same directions would look like this:

 building.5thFloor.desk.pickUpPackage(); 

Without the directions, the person would not know where to get the package from, and therefore, would be unable to perform the task. The same holds true in programming. If your program doesn't know where to get the code, it is unable to run that code. Thus, by using dot syntax, you are giving your program the information it needs to run the code you requested .

Note

The same dot syntax can be used to access properties of an object (as in myObject.myProperty ).


Note

In Flash 5,ActionScript can be attached to either frames in a timeline or to objects themselves . Depending on which you have selected, the Actions panel says either Frame Actions or Object Actions.


Exercise 14.1 Creating a Shopping List Object

Let's say you want to create a new array object to hold a shopping list. The Array object has a method called push that "pushes" new information into the array. The first step is to create your array and populate it. The Array object also happens to have a built-in property, called length, that contains the number of elements in the array.

  1. Create a new file.

  2. Select frame 1 in Layer 1, and launch the Actions panel.

  3. Even if you've never used ActionScript before, this exercise is easiest to do using Expert mode. From the Options menu in the Actions panel, select Expert Mode (see Figure 14.2).

    Figure 14.2. Use the Options menu to switch the Actions panel into Expert mode.

    graphics/14fig02.gif

  4. Now you're ready to create your first object. Type the following in the Actions list:

     ShoppingList = new Array(); 
  5. You've just created a new instance of the Array object. (Okay, you really haven't created it yet, but you will as soon as you test your movie.) Right now, the array is empty. Add information to the array using the push() method. Press Return or Enter to add a blank line, and, under the line where you initialized your array, type the following:

     ShoppingList.push("bread");  ShoppingList.push("milk");  ShoppingList.push("toilet paper"); 
  6. To actually see the values of the elements in the ShoppingList array, you need to write a couple lines of code that will print out the contents of your array in the Output window. For this, you'll use a trace action. (See Figure 14.3.) Under the last item you added to the ShoppingList, add the following lines:

     trace(ShoppingList.length);  for (i=0; i < ShoppingList.length; i++) {     trace (ShoppingList[i]);  } 

    The first line prints the number of elements in the ShoppingList array. This is a check for you.

    Figure 14.3. Create a new Array object and use the push method to add information to it. Use the trace action to display the information you just added to the object in the Output window.

    graphics/14fig03.gif

    Note

    If you want to display the properties in dynamic text fields rather than in the Output window, you have to pass the values of the properties into variables and use the variables in the text fields. You can't directly access a property, even using dot syntax, from a text field.

    Tip

    Whenever you are working with blocks of code, as soon as you insert the opening curly brace, add the closing curly brace. This helps save you from syntax errors.

  7. Before you test your new code, you should check for any syntax errors. Open the Options menu (black triangle, upper-right corner) on the Actions panel and choose Check Syntax. You also can press Ctrl+T (Windows) or Cmd+T (Macintosh).

    Warning

    The Ctrl+T and Cmd+T shortcuts work this way only when you are working in the Actions panel. Outside the Actions panel, they launch the Character panel.

  8. If you get the This Script Contains No Errors message, proceed to Step 10. Otherwise , check the Output window and start debugging. (See Figure 14.4.) Check the code in Listing 14.1 if you are having problems.

    Figure 14.4. The Output window shows the result of the trace action you set up for the ShoppingList object.

    graphics/14fig04.gif

    Tip

    When you're working with ActionScript, both spelling and case count! If you're having problems, triple check both.

    Tip

    The trace action is incredibly useful when you are testing and debugging ActionScript in Flash. You can use it to output strings of information, expressions, or both.

  9. Save your file as shoppinglist.fla and test your movie.

Your shopping list pops up in the Output window. If it doesn't, go back and check your code. It should be exactly the same as the code shown in Listing 14.1, minus the comments.

Listing 14.1 The Complete ActionScript for Creating and Displaying the Items in the ShoppingList Array Object, with Added Comments
 // Create a new instance of the Array object  //  ShoppingList = new Array();  //  // Add new items to the ShoppingList array  //  trace (ShoppingList.length);  ShoppingList.push("bread");  ShoppingList.push("milk");  ShoppingList.push("toilet paper");  //  // List the items in the array in the Output Window  //  for (i=0; i < ShoppingList.length; i++) {     trace (ShoppingList[i]);  } 

Note

Comments in Flash ActionScript (and in C, C++, JavaScript, and Java for that matter) are preceded by two forward slashes. Anything on the line after the slashes is not interpreted by Flash. If you want to comment multiple lines at one time, all you have to do is enclose the entire comment block like this: /* your comments here */ . (The ending period is not part of the code.)


Tip

Adding comments to your code not only improves readability, but also helps you document your thought process as you develop. You might have heard this phrase: "Real coders don't comment." Real coders who don't comment should be slapped. Wading through year-old code and trying to remember why you did something is a real pain. Make life easier on yourself and those who come after you. Comment your code.


If you've been working in Flash 5 for a while, you've noticed that this same dot syntax is also used to set and retrieve properties and variables of movie clips. It's used in this manner becauseyou guessed itmovie clips are objects. The only difference between movie clip objects and other objects in Flash 5 is that instances of movie clip objects can't be created by using the "new" action. Instead, new movie clip objects are created by using the attachMovie or duplicateMovie actions. In addition, movie clip objects can't be removed like normal objects; instead, they are destroyed with the removeMovieClip method.

Static Objects

Not all the built-in objects are used to create new objects. Some of them, in particular Key, Math, Mouse, and Selection, you use directly. These are known as static objects. For example, say you want to use the Math object's sqrt method to get a number's square root. All you would have to type is the following:

 Answer = Math.sqrt(9);  trace(Answer); 

Of course, you need the trace action only if you want to check your results in the Output window.

Array Syntax

Creating objects, as you can tell, is pretty easy. After you get used to it, using dot syntax is easy too. As it happens, there's a second way to access the methods and properties of an object. This is frequently referred to as array syntax because it's based on the same method you use to access the elements of an array.

Each element in an array has a unique number associated with it, like lines on a piece of paper. The numbers start with 0 for the first element and simply increment by 1 from there. If you want to access the first element of your array, you use the array access operator [] like this:

 first = ShoppingList[0];  trace (first); 

The result in the Output window is bread.

When you use array syntax to access an object's methods or properties, you don't reference them by number; you use the actual name of the method or property. This is sometimes referred to as an associative array. Thus, if you want to get the length property of your ShoppingList object using array syntax, you type the following:

 size = ShoppingList["length"];  trace (size); 

The result is exactly the same as accessing the length property with dot syntax. It's just a different approach.

Note

You can use array syntax and dot syntax together when accessing a property of an object. For example, suppose ShoppingList was a property of a larger object called Groceries. You could access the same length property of ShoppingList by using the following code:

 size = Groceries.ShoppingList["length"];  trace (size); 

This code would result in the same output, despite using both dot syntax and array syntax in the same statement. Again, it's just another approach.


Calling methods using array syntax is very similar; you just need to have the parentheses after the access operator:

 ShoppingList["push"]("juice"); 

Notice that you are passing strings, not expressions, into these operators. Because it is just a string that you are passing into the array access operators, you can do all sorts of interesting and useful things. For example, the next example does exactly what the previous one does, just in a slightly different way. In this example, you pass the name of the method into a variable. You then use the variable in place of the method name:

 action = "push";  ShoppingList[action]("juice"); 

Note

Strings in Flash are a series of characters , numbers, or punctuation marks enclosed in double or single quotation marks. Strings are interpreted literally. Expressions are variables or numbers (or both) that are evaluated to produce a value. The value can be either numeric or character. Consider the following:

 x = "one";  y = "two";  combo = (x + " and " + y);  Trace (combo); 

The strings "one" and "two" are passed into the variables x and y. The variables x and y are evaluated in the expression being passed into the variable combination. The result is the string "one and two" in the Output window (see Figure 14.5).

Figure 14.5. The Output window shows the result of concatenation of ( x + " and " + y ).

graphics/14fig05.gif


Look at the following example of code. It does something similar. It is attached to a button, and when you press the button, you dynamically generate 10 randomly placed instances of the shoppingBag movie clip on the Stage.

 on(release) {     for (i=0; i < 10; i++) {         _root.attachMovie("shoppingBag", "mybag" + i, i);          _root["mybag" + i]._x = Math.floor(550*Math.random()+10);          _root["mybag" + i]._y = Math.floor(300*Math.random()+20);          _root["mybag" + i].myinstance = "mybag"+i;      }  } 

You actually can see this snippet of code in action. Open shoppingBag.swf from the Chapter_14/Assets folder. The blue button in the lower-left corner has this snippet of code attached to it. Press the button and you can see the dynamically generated instances of the shoppingBag. Notice that each instance of the shoppingBag has its own unique namemybag followed by a number. The shopping bag is actually draggable, so if you can't see all the instances of the shopping bag, feel free to drag the bags around.

Array syntax is useful because movie clips are objects themselves (this includes the main timeline!). The variables that are held in a movie clip are actually properties of that object. By using a special keyword, this (which means "the object I am currently in"), you can easily access any variable dynamically by using array syntax. Consider the following code:

 dairy = "milk;"  vegetable = "beans";  fruit = "mango";  myFood = fruit;  trace(this[myFood]); 

You guessed it! This code will print "mango" in the Output window.

Extending Objects

With ActionScript, you can add your own methods and properties to an object any time you want. If you wanted to add a new property called "type" to your ShoppingList object, you would simply type the following:

 ShoppingList.type = "Grocery list"; 

Adding new methods to an object isn't quite as straightforward, but it is still fairly simple. First of all, you need to create the actual function:

 function oddSize(){     return (this.length%2);  } 

Note

The percent symbol (%) in the oddSize function is known as the modulo operator . The modulo operator takes the value of the expression on the left and divides it by the value of the expression on the right. It then returns the remainder.


You use the this keyword to reference the object in which this method will be placed. This object returns a 1 if there are an odd number of elements in this array; it returns a 0 otherwise. Now you need to make this function a method of your object by typing the following code:

 ShoppingList.oddSize = oddSize; 

That's all there is to it! You also can use this technique to override the built-in method for an object. For example, the Array object has a built-in method called reverse that is used to reverse all the elements currently in the array. If you wanted to replace the Array object's reverse method with your own, all you would have to do is create a function and then attach it to the array object. You will learn in a bit why attaching the method in this manner overrides the built-in method. The function below can be used to reverse an array:

 function list_reverse(){     for (var i=0;i<(this.length/2);++i){          temp = this[i];           this[i] = this[this.length-1-i];           this[this.length-1-i] = temp;      }  }  list = new Array();  list.reverse = list_reverse; 

Note

Are you a nonprogrammer and curious about what the code in the list_reverse function is actually doing? This is one of those for loops that was discussed earlier in this chapter. The variable i is initialized to 0. As long as i is less than the length of the array you are using (divided by 2), the statements in the loop are executed. Every time you pass through the loop, i gets incremented by 1. For an array with a length of 4, here are the values on each pass:

i

this.length/2

temp

this[i]

this[this.length-1-i]

2

4-1-0=3

this[3]=0

1

2

1

4-1-1=2

this[2]=1

2

2

2

4-1-2=1

this[1]=2

3

2

3

4-1-3=0

this[0]=3

In this piece of code, notice that you can't just swap the numbers one for the other; first you have to hand them off to an intermediary called temp. Think of it this way: If I am holding a box and you are holding a box (these are heavy boxestwo hands required), we can't exchange boxes without one of us handing our box to someone else. It's the same way with variables; the value of i has to be passed to a temporary holder while the values are being updated.


Although all this is fine and good for individual objects, sometimes you might want to extend every object of a particular type. For example, you might want to add a new method to every Array object in your movie.

Extending Prototype Objects

To understand how you can extend prototype objects, you need to understand how Flash "finds" the methods and properties of an object. Consider the following code:

 ShoppingList.oddsize(); 

In this code, Flash would first look to see if oddsize is attached to ShoppingList. If it isn't, Flash doesn't give up! It then looks in a special (and not particularly obvious) place: the prototype object inside this object's prototype object.

Say what? Look at it this waythe prototype object Array already exists. The Array object contains another object named prototype. Any properties or methods that are inside the prototype object are automatically available to any objects that are created based on the Array object.

Flash plays "hunt the property (or method)" in the following manner:

  1. Check the object itself.

  2. Check the object named prototype within the object's prototype object.

Take a look at an example. If you want to add a new property called "priority" to every single Array object in your whole movie, you can type the following:

 Array.prototype.priority = "urgent"; 

The really neat thing about this is that it affects all Array objects, even the ones that were created before you entered this code. That's power.

Finally, to round out this section on extending objects, you can add a method to all your Array objects that tells you if your arrays have 15 or fewer items in them (so you can go through the express line!).

 function expressLine(){     return(this.length<=15);  }  Array.prototype.expressLine = expressLine; 

Now all your arrays have a method to verify whether there are fewer than 15 items in the array.

Passing by Value versus Passing by Reference

There's one more important concept that you need to understand about using objects before you get into creating your own prototype objects. You need to understand the difference between passing by value and passing by reference. When you use a variable to send a value to a function like the one in the following code, do you know what happens?

 function square(x){     x = x *x;      return (x);  }  a = 10;  b = square(a); 

The variable a gets passed to the function by value. In other words, the value of the variable is sent into the function and the actual variable isn't touched. The variable a is never modified because the multiplication inside the function is happening to a copy of the variable. The value of the variable a remains 10. The value of the variable b is modified because that's the variable to which the function returns the value. Variable b is 100 after this function is called. Although all normal variables are passed by value in this manner, objects are not.

Objects are passed by reference. This means that rather than making a copy of the object, Flash passes a reference (not a copy) to the original object into the function. Consider the following code:

 function addBread(list){     list.push("bread");  }  ShoppingList = new Array();  addBread(ShoppingList); 

In this case, ShoppingList is being passed to the addBread function by reference, so the push action inside the function actually adds to the ShoppingList object! After this function is called, the ShoppingList object has the value bread as the first, and only, item in the array. Thus, any time you have to pass an object to a function, make sure you don't modify the object unless you want the original to be modified.



Inside Flash
Inside Flash MX (2nd Edition) (Inside (New Riders))
ISBN: 0735712549
EAN: 2147483647
Year: 2005
Pages: 257
Authors: Jody Keating

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