Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
101
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 2

userAccountsArray[“msmithe”] = {group:”moderator”, joined:”2004/09/09”, posts:943};

trace(userAccountsArray[“nderksen”].group); // Outputs: guest

trace(userAccountsArray[“jberg”].joined); // Outputs: 2003/02/18

trace(userAccountsArray[“msmithe”].posts); // Outputs: 943

This code creates a lookup table, indexed by username, where any attribute for any username can be accessed with a single line of code.

Similarly, a regular indexed array can be used to store objects:

var highScoresList:Array = new Array(); highScoresList.push({score:2030045, name:”Jeffrey Berg”}); highScoresList.push({score:1980320, name:”Mary Smithe”}); highScoresList.push({score:10034, name:”Nathan Derksen”});

trace(highScoresList[0].name); // Outputs: Jeffrey Berg

trace(highScoresList[0].score); // Outputs: 2030045

It’s a very practical construct that can be used any time records of data need to be kept in memory.

Because objects and associative arrays are interchangeable, and because all ActionScript classes inherit from the Object class, it follows that this syntax can be used elsewhere as well, such as with the MovieClip class. The normal syntax for creating a new text field in a movie clip is as follows:

this.createTextField(“myTextField”, 1, 0, 0, 200, 50); this.myTextField.text = “The quick brown fox”;

// Outputs: The quick brown fox

The associative array syntax is quite similar:

this.createTextField(“myTextField”, 1, 0, 0, 200, 50); this[“myTextField”].text = “The quick brown fox”;

// Outputs: The quick brown fox

The keyword this points to the main timeline, and the createTextField() method adds a property to the base movie clip that points to the text field. The associative array syntax for movie clips becomes very useful when creating an arbitrary number of text fields or movie clips on the timeline, as the following example shows:

for (var i:Number = 0; i < 5; i++)

{

this.createTextField(“myTextField” + i, i, 0, i*20, 200, 50); this[“myTextField” + i].text = “Text field number “ + i;

}

48

Getting Started with ActionScript 2.0

This code creates five text fields on the timeline, each separated by 20 pixels vertically, and each containing the text Text field number: <n>, where <n> is the number indicating the order in which the field was created.

Without the associative array syntax, the more involved eval() method would be needed to create these fields. eval()is a means of accessing variables whose names are constructed on-the-fly. This book doesn’t cover eval() functionality, which is fairly complex, because the associative array syntax is much less confusing.

Try It Out

Storing Data for a Photo Viewer

Creating structures to store data is central to many Macromedia Flash applications. Imagine a photo viewer for showing your photos to friends: You would need to store a filename for the image, perhaps a file size to show onscreen, and a description of the photo.

Here’s how you can work with such a data structure:

1.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.

2.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:

#include “tryItOut_trackData.as”

3.Select File Save As, name the file tryItOut_trackData.fla, choose an appropriate directory, and save it.

4.Create a new script file by selecting File New and choosing ActionScript File from the New Document panel.

5.Select File Save As and ensure it is showing the directory containing the Flash project file. Give the file the name tryItOut_trackData.as and save it.

6.Enter the following code into the new ActionScript file:

var photoArray:Object = new Object();

photoArray[“weddingPhoto1”] = new Object(); photoArray[“weddingPhoto1”].fileName = “weddingPhoto1.jpg”; photoArray[“weddingPhoto1”].fileSize = 150; photoArray[“weddingPhoto1”].description = “Exchanging of the rings.”;

photoArray[“westIndiesVacation1”] = new Object(); photoArray[“westIndiesVacation1”].fileName = “vacation1.jpg”; photoArray[“westIndiesVacation1”].fileSize = 64; photoArray[“westIndiesVacation1”].description = “Arriving at the airport ;

in sweltering heat.”;

trace(photoArray[“weddingPhoto1”].fileName);

trace(photoArray[“weddingPhoto1”].fileSize);

trace(photoArray[“westIndiesVacation1”].description);

7.Save the file (File Save), return to the Flash project file, and select Control Test Movie.

49

Chapter 2

How It Works

You use an associative array to store the details of each photo. Each photo is given an ID that is used for all future access to its data. The first line sets up the associative array. The second line sets up the object that is going to store the details for the first photo. The third, fourth, and fifth lines assign data to the object for the first photo. The process in lines 2–5 is repeated for each photo to be placed in the photo album.

The trace() statements show how to access individual elements within the associative array. The photoArray[“weddingPhoto1”] reference stores an object that holds all of the properties for the photo with the id weddingPhoto1. Each property can be accessed through dot notation.

In the next chapter, you see how you can do useful work with this data structure by looping through each element.

The output from this code should look like the following:

trace(photoArray[“weddingPhoto1”].fileName); // Outputs: weddingPhoto1.jpg

trace(photoArray[“weddingPhoto1”].fileSize);

// Outputs: 150

trace(photoArray[“westIndiesVacation1”].description); // Outputs: Arriving at the airport in sweltering heat

Summar y

This chapter introduced you to the ActionScript language. Of course, you’ll be learning a lot more about it as you work through the book. Points to remember from this chapter, though, include the following:

Variables are the basic means of holding data. The type of data held in the variable determines what kinds of things can be done with that data.

You can make use of white space to help make your code more readable.

Strong typing helps you find type-related errors quickly. All variables should include a type definition when they are first declared.

Dot syntax enables you to call methods and properties from an object. Commands can be chained together by “connecting the dots.”

An array holds a sequential list of data.

An associative array is not really an array, but an unordered list key/value pairs.

An object can be used to store arbitrary data as property/value pairs.

An associative array can store a list of objects as a convenient way of storing data records.

50

Getting Started with ActionScript 2.0

Exercises

1.Determine which of the following variable declarations are not valid and why.

a.var my_var:Number = 0;

b.var someOtherVar:Integer = 0;

c.myString:String;

d.var 1stPlaceFinisher:String;

e.var _width:Number = 25;

f.var isFinished:Boolean = “false”;

2.Work through the order in which the operators are evaluated in the following statement:

totalAmount = (numItemsPickedUp - numItemsPrepaid) * perItemCost + handlingFee;

3.If the values for the preceding statement are numItemsPickedUp, 10; numItemsPrepaid, 5; perItemCost, 20; and handlingFee, 30, determine — without running the code — what value would be assigned to totalAmount.

totalAmount = (numItemsPickedUp - numItemsPrepaid) * perItemCost + handlingFee;

4.Predict the outcome of the following:

var birdsArray:Array = new Array(“finch”, “blue jay”); birdsArray.push(“warbler”);

birdsArray.splice(2, 0, “crow”); birdsArray.splice(0, 1); trace(birdsArray.join(“-”));

51

3

Understanding ActionScript

Expressions and Loops

So far you’ve learned about the basic structure of the ActionScript language and the core data element, the variable, but you’ve seen only scenarios in which every line of code executes exactly once. In this chapter, you add a very important set of tools, including the capability to use the contents of variables to make decisions about which lines of code to execute and the capability to loop repeatedly through blocks of code.

The concepts of decision making and looping through code are referred to as flow control. A program’s flow is the sequence in which lines of code are executed. Through some of the statements that ActionScript provides, you can control that flow.

This chapter starts by exploring the capability to make decisions in code.

Making Decisions

Throughout the course of your day, you make decisions about what to do. When you wake up, do you drink one cup of coffee or two? Which pair of shoes will you wear? Do you drive or walk to your morning destination? Your entire day is composed of many decisions all performed in sequence.

In the same way, a program is composed of logic used to make many decisions, except you have to provide the guidelines needed to make those decisions. These guidelines are called conditionals and are simple logical rules that spell out those guidelines in an unambiguous way. Conditionals are composed of three elements:

Expressions — An expression is a precise specification of the decision to be made. Each decision requires one expression to describe it.

Operators — An operator is used within an expression to impose conditions on the decision, such as to make a comparison, or to specify that there are multiple parts to a decision. One expression can consist of any number of operators.

Chapter 3

Statements — A statement is code that executes if the expression evaluation results in a true (yes) decision. A conditional can contain any number of statements grouped inside a pair of curly brackets.

The overall makeup of a conditional is as follows:

if (numPhotos == 0)

{

trace(“There are no photos”);

}

In this example, the expression is numPhotos == 0, where you test whether the contents of the numPhotos variable equals the number zero. The two = symbols together form the “is equal to” conditional operator, and the line with the trace() code is a statement that is executed only if the expression numPhotos == 0 evaluates to true.

The = operator and the == operator are completely different and frequently get mixed up. The = operator assigns the contents of one variable to another variable, whereas the == operator compares two variables to see if they contain the same data. If you use the = operator within an if statement by accident, the expression always returns true.

Expressions

An expression is the means to formally describe a decision. In the real world, a decision can be at least yes, no, or maybe. For a computer, a decision can consist only of yes (true) or no (false). An expression always results in a single value of true or false. With the expression myHair == “brown”, for example, the value stored in the variable myHair is retrieved first and then compared with the string value “brown” to see if they are equal. Depending on the result of the comparison, a true or false value is returned.

Putting together a single decision comparing two values at once is pretty straightforward, but when two, three, or more decisions are placed into a single expression, things can quickly get complex. (Don’t worry, though — shortly you learn techniques for dealing with complex expressions.)

The ultimate output of an expression is a single true or false value and nothing else. If the whole expression evaluates to true, all the statements are executed; if it evaluates to false, none of the statements is executed and the next line of code after the closing curly bracket is executed.

Consider the following examples. First, two string values are compared:

var typeOfPants:String = “jeans”; if (typeOfPants == “dress pants”)

{

trace(“Wearing dress pants”);

}

This expression compares the contents of the typeOfPants variable with the string value “dress pants”. The variable contains the value “jeans”, so the expression becomes “jeans” == “dress

54

Understanding ActionScript Expressions and Loops

pants”. Because the values on either side of the equal-to operator are different, the result of the comparison is the value false, and the statement between the curly brackets is skipped.

Here’s an example that compares two numbers:

var numPhotos:Number = 2; if (numPhotos > 1)

{

trace(“There is more than one photo”);

}

The expression compares the contents of the numPhotos variable, 2, with the number 1. The operator used is > (greater than), which returns true if the value on the left is larger than the value on the right. The 2 is indeed greater than 1, so the expression returns true and the trace() statement is executed.

The greater than (>) and less than (<) operators are frequently confused. The open part of the symbol always faces the larger value, and the pointed end points to the smaller value.

The next example compares two Boolean values:

var isDaytime:Boolean = true; if (isDaytime == false)

{

trace(“It is not daytime”);

}

This example compares the contents of the isDaytime variable (true) with the value false. (Remember, == is the equal operator; = is the assignment operator.) true does not equal false, so the comparison operator returns an overall value of false, and the trace() statement is skipped.

Building Expressions

Just as there are no limits to the kinds of decisions you can make throughout your day, there are no limits to the numbers of different expressions you can build. You can use expressions to make mathematical comparisons or determine whether one number falls within a range of numbers, to evaluate what to do based on user input, and to evaluate several criteria at once.

Take a look at a couple of examples:

var weaponType1:String = “pen”; var weaponType2:String = “sword”;

trace(weaponType1.length > weaponType2.length); // Outputs: false

This expression returns true only if the number of characters in the word pen is greater than the number of characters in the word sword.

var numSitups:Number = 5; trace(numSitups >= 0 && numSitups <= 10); // Outputs: true

55

Chapter 3

The expression returns true if the value held in numSitups is from the number 0 to the number 10, inclusive. This is the standard way of checking to see if the value of a variable falls between a specific range of numbers.

The expression involves several operators, so pay attention to the order in which operators are evaluated. According to the operator listing earlier in this chapter, the >= (greater than or equal to) and <= (less than or equal to) operators have higher priority than the && (logical AND) operator, so those are evaluated first. The variable numSitups contains the value 5, so the comparison numSitups >= 0 becomes 5 >= 0, which is true because 5 is greater than or equal to 0. The comparison numSitups <= 10 becomes 5 <= 10, which is true because 5 is less than or equal to 10. The results of these two comparisons are used by the && (logical AND) operator, reducing the expression to true && true. The && operator returns true only if the values on both sides are true, as is the case in this example.

The process that the Flash player uses to evaluate your expressions involves simplifying until only a true or false value remains. Here’s how it works:

1.The starting expression:

numSitups >= 0 && numSitups <= 10

2.Replace the variables with the values that they hold:

5 >= 0 && 5 <= 10

3.Evaluate the highest priority operators:

true && true

4.Evaluate the remaining operator:

true

Chapter 2 introduced operators in ActionScript code and included a table that described them in the order in which they are evaluated in expressions

That was a lot of detail for a single evaluation, but it’s important that you understand what happens when an expression is evaluated.

The following example incorporates a mathematical operator in the form of a subtraction:

var currentRecord:Number = 10; var numRecords:Number = 11;

trace(currentRecord <= numRecords - 1); // Outputs: true

This expression involves a computation and then a comparison. First, the mathematical operation takes place, where 1 is subtracted from the contents of numRecords (11), returning a value of 10. The result of the computation is compared to the contents of currentRecord (10) using the <= (less than or equal to) operator — 10 <= 10 — which evaluates to true.

Expressions can be used to modify program behavior based on the result of user actions, as the following example shows:

56

Understanding ActionScript Expressions and Loops

var lastClickTime:Number = 235246; var thisClickTime:Number = 235370; var shiftPressed:Boolean = false;

trace(thisClickTime – lastClickTime < 1500 && shiftPressed == true); // Outputs: false

This expression evaluates two things and requires that they both be true for the whole expression to be true.

1.The starting expression:

thisClickTime – lastClickTime < 1500 && shiftPressed == true

2.Replace the variables with the values that they hold:

235370 – 235246 < 1500 && false == true

3.Evaluate the highest priority operator(s) — in this case, subtraction:

126 < 1500 && false == true

4.Evaluate the next highest operators (the less than and the equals operators). The == operator returns true only if the values on both sides are the same.

true && false

5.Evaluate the last operator (&&). The && operator returns true only if the values on both sides are true.

false

When multiple comparisons are used, it may help to use round brackets (parentheses) to clarify the order in which the comparisons are to be performed. Comparisons within brackets are always evaluated first. Compare the following two variations of the same expression:

var recordNum1:Number = 5; var recordNum2:Number = 10; var skipCheck:Boolean = true;

trace(recordNum1 == 5 || recordNum2 == 9 && skipCheck == false);

// Output: true

trace((recordNum1 == 5 || recordnum2 == 9) && skipCheck == false);

// Output: false

The order in which the comparisons are made in the first trace() is not obvious. It is unclear whether the || (OR) operation is performed before the && (AND) operation, or vice versa. It turns out that the && operator is evaluated before the || operator. The first expression is evaluated in the following order:

1.The starting expression:

recordNum1 == 5 || recordNum2 == 9 && skipCheck == false

57