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

Beginning ActionScript 2.0 2006

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

Chapter 3

2.

3.

4.

5.

Replace the variables with the values that they hold:

5 == 5

||

10 == 9

&&

true == false

Evaluate the highest priority operations (==):

true

||

false

&&

false

Evaluate the next highest priority operation (&&):

 

true

||

 

false

 

Evaluate the last operator (||): true

|| evaluates to true if the value on at least one side of the operator is true.

In the second trace, brackets have been added to make the order in which the operators are evaluated more explicit, and to force the || operator to take precedence over the && operator:

1.The starting expression:

(myNum1 == 5 || myNum2 == 9) && myBoolean == false

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

( 5 == 5 || 10 == 9 ) && true == false

3.Evaluate the highest operators (==) within the brackets:

(

true

||

false ) && true == false

4.Evaluate the next highest operator (||) within the brackets:

(

true

) && true == false

5.With the operations within the brackets concluded, their result is now part of the simpler expression, and the highest remaining operator (==) is evaluated:

true

&&

false

6.Evaluate the final operator (&&): which gives the value true only if both of the values next to the operator are true.

false

&& evaluates to true only if the values on both sides of it are true.

Although the two expressions are essentially identical, changing the order in which the operators are evaluated results in different outcomes. If you are ever unsure about the order in which an operator is evaluated, just add brackets to enforce the order you want used. The operators within round brackets are always evaluated before operators outside the brackets.

58

Understanding ActionScript Expressions and Loops

Macromedia Flash allows any data to be compared to any other data, but comparing anything other than numbers, strings, and Booleans leads to unpredictable results. Take the example of comparing two Date objects representing the same date as follows:

var date1:Date = new Date(2010, 1, 1); var date2:Date = new Date(2010, 1, 1);

trace(date1 == date2); // Outputs: false

The issue is that the variables date1 and date2 do not contain actual dates; they simply contain a number representing where each Date object is located in memory. Two separate Date objects cannot exist at exactly the same point in memory, so the comparison between date1 and date2 will always be false. To compare the actual dates, use a string or a numerical representation of the dates:

var date1:Date = new Date(2010, 1, 1); var date2:Date = new Date(2010, 1, 1);

trace(date1.getTime() == date2.getTime()); // Outputs: true

Calling getTime()on a Date object outputs a number that can be compared (see Figure 3-1).

date1

memory location = 3948299820

date2

memory location = 5436701263

Figure 3-1

Jan 1, 2010

date1.getTime()= 1265011200000

Jan 1, 2010

date2.getTime()= 1265011200000

The following sections look at some standard conditional statements.

Using if..then..else

The main conditional statement used in any program is if..then..else (if an expression is true, then statement x is called; otherwise (else), statement y is called):

if (expression)

{

// Statements to be called if the expression is true

}

else

{

// Statements to be called if the expression is false

}

59

Chapter 3

If the expression evaluates to true, all the statements in the first set of braces are run, otherwise all the statements in the second set of braces are run. The else portion of the statement is optional. If it is only important to act on a true statement, only the first set of braces needs to be included:

if (expression)

{

// Statements to be called if the expression is true

}

if..then..else statements may be nested within each other. The inner statement executes only if the expression in the outer statement evaluates to true:

if (myAge >= 18)

{

if (haveLicense == true)

{

// Statements to be called if myAge >= 18 and haveLicense == true

}

}

There are different ways to write the same set of conditions. The preceding example can be re-written to remove the nesting:

if (myAge >= 18 && haveLicense == true)

{

// Statements to be called if myAge >= 18 and haveLicense == true

}

Numerous reasons exist for why you would or would not use nesting. Non-nested statements, for instance, provide a slight performance advantage because there’s only one expression to evaluate. The code is also more compact. Nesting makes complex expressions more readable by breaking them into smaller statements.

Overall, how you structure your if statements is more a matter of personal preference and style. Some situations lend themselves to one style over another, but there are always multiple ways to structure the same set of decisions. Recognizing when to use one style over the other simply takes practice.

Using switch..case

Many cities have a recycling program where people can place items destined for recycling in specially provided bins and bags. The blue bin hold cans and containers, the blue bag holds newsprint, and the yellow bag holds glossy paper products, for example. For each item to be tossed, a decision is made regarding what to do with it. Glass bottles and milk cartons go in the blue bin, newspapers go in the blue bag, magazines go in the yellow bag, and oil-soaked pizza boxes go to the trash. This scenario could be coded using the following if statements:

if (garbagePiece == “glass bottle”)

{

trace(“Put in blue bin”);

}

60

Understanding ActionScript Expressions and Loops

else if (garbagePiece == “newspaper”)

{

trace(“Put in blue bag”);

}

else if (garbagePiece == “magazine”)

{

trace(“Put in yellow bag”);

}

else if (garbagePiece == “milk carton”

{

trace(“Put in blue bin”);

}

else if (garbagePiece == “pizza box”)

{

trace(“Put in garbage bin”);

}

The switch..case statement makes multiple simple comparisons with one piece of data, but without a whole mess of if statements to do it. The switch..case syntax gives the following code:

switch (garbagePiece)

{

case “glass bottle”: trace(“Put in blue bin”); break;

case “newspaper”:

trace(“Put in blue bag”); break;

case “magazine”:

trace(“Put in yellow bag”); break;

case “milk carton”: trace(“Put in blue bin”); break;

case “pizza box”:

trace(“Put in garbage bin”);

}

As you can see, switch..case statements are more readable and more efficient. The general syntax is as follows:

switch (variable)

{

case “value1”:

//Statements for value 1 break;

case “value2”:

//Statements for value 2 break;

default:

// Default statements

}

61

Chapter 3

The variable can contain only a string or a numerical value, and each possible value to test for starts with the case “value”: statement and ends with the break; statement. An optional default block contains statements that are run only if the data contained by the variable is not matched by any of the case statements.

The break statement indicates that there are no further statements for that case and breaks out of that particular switch statement entirely. If break is not included after every case statement, program flow continues to the next statement, even if it is part of the next case block. This might seem a bit strange, but there’s good reason for it. By omitting break statements in strategic locations, multiple values can be compared against the variable and each match can execute the same code, as the following example shows:

switch (garbagePiece)

{

case “plastic pop bottle”: trace(“Crush pop bottle”);

case “glass bottle”: case “aluminum cans”: case “milk carton”:

trace(“Put in blue bin”); break;

case “newspaper”:

case “non glossy flyer”: trace(“Put in blue bag”); break;

case “magazine”: case “glossy flyer”:

trace(“Put in yellow bag”); break;

default:

trace(“Put in garbage bin”);

}

Here, glass bottles, plastic pop bottles, aluminum cans, and milk cartons go in the blue bin, newspapers and non-glossy flyers go in the blue bag, magazines and glossy flyers go in the yellow bag, and everything else, including pizza boxes, goes into the garbage bin. In addition, plastic pop bottles are crushed before being put into the blue bin.

Figure 3-2 steps through a switch..case statement for plastic pop bottle.

62

Understanding ActionScript Expressions and Loops

var garbagePiece:String = “plastic pop bottle”; switch (garbagePiece)

{

case “plastic pop bottle” trace(”Crush pop bottle”)

case “glass bottle”:

case “aluminum cans”: case “milk carton”:

trace(”Put in blue box”);

break; case “newspaper”:

case “non glossy flyer”: trace(”Put in blue bag”); break;

case “magazine”: case “glossy flyer”:

trace(”Put in yellow bag”); break;

default:

trace(”Put in garbage bin”);

}

// Next statement

Figure 3-2

First, each case statement is stepped through until a match is found. Once found, lines of code continue to be run until a break statement is reached, at which point the switch statement ends. In this case, the output is

Crush pop bottle

Put in blue bin

In Figure 3-3, each case statement is compared to the string banana peel.

63

Chapter 3

var garbagePiece:String = “banana peel”; switch (garbagePiece)

{

case “plastic pop bottle” trace(”Crush pop bottle”)

case “glass bottle”:

case “aluminum cans”:

case “milk carton”:

trace(”Put in blue box”); break;

case “newspaper”:

case “non glossy flyer”: trace(”Put in blue bag”); break;

case “magazine”:

case “glossy flyer”:

trace(”Put in yellow bag”); break;

default:

trace(”Put in garbage bin”);

}

// Next statement

Figure 3-3

This time no match is found, so once the default: statement is reached, all subsequent code is executed until the closing switch brace. The output from this code segment is simply

Put in garbage bin

Try It Out

Handling Keystrokes in a Game

If you want to use Macromedia Flash to develop games, one of the things you need to be able to do is map key presses to an action to perform. The switch..case statement is perfectly suited for this. Follow these steps to see how simple it is to set up:

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:

64

Understanding ActionScript Expressions and Loops

#include “tryItOut_decisions.as”

3.Select File Save As, name the file tryItOut_decisions.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 .fla file. Name the new file tryItOut_decisions.as and save it.

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

var keyListener:Object = new Object(); keyListener.onKeyDown = function()

{

var pressedKeyCode:Number = Key.getCode(); trace(“Pressed key number: “ + pressedKeyCode); switch (pressedKeyCode)

{

case Key.LEFT: // left arrow movePlayerLeft(); trace(“moving left”); break;

case Key.UP: // up arrow movePlayerUp(); trace(“moving up”); break;

case Key.RIGHT: // right arrow movePlayerRight(); trace(“moving right”); break;

case Key.DOWN: // down arrow movePlayerDown(); trace(“moving down”); break;

case Key.ENTER: case Key.SHIFT: case Key.CONTROL: case Key.SPACE: fire();

trace(“firing”);

break; case Key.TAB:

switchWeapons(); trace(“switching weapons”); break;

case Key.ESCAPE: pauseGame(); trace(“pausing game”); break;

}

};

Key.addListener(keyListener);

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

65

Chapter 3

The Macromedia Flash test environment blocks some of the keystrokes used here, preventing all of the conditions from working. To enable your code to successfully receive notification of every key press while in the test movie mode, select Control Disable Keyboard Shortcuts before running the movie. (You need to do this only in the test environment.) This issue does not come up when interacting with a movie running in a browser or as a standalone executable.

How It Works

This code uses an event listener to capture events generated by the keyboard. A listener is simply a chunk of code that “listens” for a particular event to occur, and then acts on that event. (Listeners are discussed in greater detail in the “Handling Events” section in the next chapter.) The first line creates a generic object to act as a listener. The second line creates an event handler for a specific event — in this case, the onKeyDown event. The last line assigns the listener to the Key() object, which is built into the Flash player and which broadcasts key press events to all interested listeners.

In the event handler code, the first line captures the code associated with the pressed key, and the switch..case statement decides what action should be taken based on the key that’s pressed. Notice that while the top-most trace() statement gives a numerical value for each key, none of the case statements seem to refer to an actual number. The named references to the keys are called static constants, and they contain the key code numbers for non-character keys on the keyboard. For instance, Key.ENTER returns the number 13, and Key.ESCAPE returns the number 27. Using these static constants makes code more readable and means that you do not have to remember obscure character codes.

Press the Enter, Shift, Ctrl, and space keys while the movie is running and you will see the output “firing” every time. The case statements that test for ENTER, SHIFT, and CONTROL have no break statement, so if one of those three conditions is matched, the flow of execution falls through, executing all statements until the next break statement is reached.

The optional default statement isn’t used here because there’s no concern about what happens when any other keys are pressed. As a result, any keys pressed that don’t match one of the case conditions are simply ignored by the switch statement.

Understanding Loops

Good programmers are lazy by nature. That doesn’t mean that they do not get things done; it means that they get things done in the most efficient way possible. If a task needs to be done repeatedly, they will find a way to automate it. The loop is the programmatic means to automate a task, and is fundamental to working with arrays and searching through data. Macromedia Flash provides four loop statements that you can work with: for, for..in, while, and do..while.

The for Loop

The workhorse of the loop statements is the for statement, and it’s the one that you will no doubt become very familiar with. Its primary use is for iterating through indexed arrays, which is likely what you will be doing the most. The basic structure of the for statement is as follows:

66

Understanding ActionScript Expressions and Loops

for (init; condition; iterator)

{

// Statements

}

The init portion contains the initializing code that runs once before the loop begins. The condition is an expression that is evaluated before every iteration of the loop that tests to see whether it should continue looping or break out of the loop completely. The iterator causes the variable(s) used in the condition to change, and is executed for every iteration. The statements contained between the braces run for every pass of the loop.

Here’s an example of a classic for loop:

var fruitArray:Array = new Array(“Apple”, “Orange”, “Pear”); var numFruit:Number = fruitArray.length;

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

{

trace(i + “: “ + fruitArray[i]);

}

//Outputs:

//0: Apple

//1: Orange

//2: Pear

The execution of this loop is broken down as follows:

1.The initialization code var i:Number = 0; is run, setting the contents of the variable i to zero.

2. Comparison between i and numFruit is performed. With i = 0 and numFruit = 3, then 0 < 3 is true, and execution of the loop proceeds.

3.

4.

5.

The trace() function displays 0: Apple.

The iterator is executed, and the variable i now contains the value 1.

Comparison between i and numFruit is performed. With i = 1 and numFruit = 3, then 1 < 3 is true, and execution of the loop proceeds.

6.

7.

8.

The trace() function displays 1: Orange.

The iterator is run, and the variable i now contains the value 2.

Comparison between i and numFruit is performed. With i = 2 and numFruit = 3, then 2 < 3 is true, and execution of the loop proceeds.

9.

10.

11.

The trace() function displays 2: Pear.

The iterator is run, and the variable i now contains the value 3.

Comparison between i and numFruit is performed. With i = 3 and numFruit = 3, then 3 < 3 is false, and execution of the loop stops.

The convention for naming variables used for loop indices is to use the letters i through n.

67