Until now, all the examples you have been working with run in a straight line. You aren’t changing courses during the execution of the code based on varying conditions. Often, you will want to do specific actions if certain conditions are met, and if they aren’t met, you want to do other actions instead. This type of action is called Boolean logic.
In this chapter, you’ll learn more about the Boolean variable type and see how you can use it to determine if certain conditions are true or false based on equality operators. You can then apply these operators to blocks of code that will execute differently based on the results of these evaluations.
Boolean variables can contain only two values: true or false. They can’t contain numbers, strings, or other objects; just true or false.
To create a Boolean value, you define it as a Boolean variable type. Let’s do that now in a new project:
1. Create a new project in Flash Professional CS5.5.
2. Create a new Document class called Booleans that extends the MovieClip class.
3. Update the Booleans class to contain the following code:
package {
import flash.display.MovieClip;
public class Booleans extends MovieClip {
public function Booleans():void {
_init();
}
private function _init():void {
trace("Booleans Class Created");
}
}
}
To create a Boolean variable, you need to create a private variable named _isCorrect
. A lot of Boolean variables begin with the word “is” because it helps form a question: “Is this correct?” To which there can be two responses, yes or no (true and false).
4. Add a private variable for the Boolean as highlighted in the code before:
package {
import flash.display.MovieClip;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean
public function Booleans():void {
_init();
}
private function _init():void {
trace("Booleans Class Created");
}
}
}
Now you can assign a value to this variable using the keywords true
or false
.
5. Set the variable so the initial value is false
as highlighted in the following code:
package {
import flash.display.MovieClip;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean
public function Booleans():void {
_init();
}
private function _init():void {
trace("Booleans Class Created");
_isCorrect = false;
}
}
}
Notice that when the value is set, you don’t use quotation marks because this isn’t a string, but a special value that is unique to the Boolean variable type.
You can use either true
or false
as the value for the Boolean variable type. Later in the chapter, you’ll learn ways to generate these Boolean values.
From here on out, all the code you will be using is located within the init
method of the class and the entire contents of the class won’t be displayed unless there are updates outside the init
method.
In ActionScript, you can test if two items are equal to each other using equality statements. These equality statements can come in several forms.
The first is the equality statement, or ==
, which tests if items are equal to each other. Using the previous example, look how the code within the _init
method is updated:
private function _init():void {
_isCorrect = (5 == 5);
trace(_isCorrect);
}
When this code runs, the Output panel displays true. You are testing whether the number 5 is equal to the number 5, which is true. The true
value is generated by the equality statement ==
and is then assigned to the _isCorrect
Boolean variable.
You can adjust this slightly to test for the equality of a variable’s value. Update the code as highlighted below:
private function _init():void {
var myValue:Number = 5;
isCorrect = (myValue == 5);
trace(_isCorrect);
}
Now you are testing to see if the value of the Number myValue
is equal to 5. In this case it is, so you get the result true
.
If the myValue
changes, you get something different:
private function _init():void {
var myValue:Number = 4;
isCorrect = (myValue == 5);
trace(_isCorrect);
}
Now you get the value of false
, because myValue
equals 4, which is not equal to 5. Since the equality test fails, it generates the value of false
.
Several operator statements can test varying conditions of inequality. Using these different operators you can test if two values are not equal, if one is greater than the other, if one is less than the other, or a combination of these:
private function __init():void {
var myValue:Number = 4;
trace ( myValue != 4 ); // false
trace ( myValue < 5 ); // true
trace ( myValue > 4 ); // false
trace ( myValue <= 4 ); // true
trace ( myValue >= 4 ); // true
}
Each of these statements tests for varying levels of inequality. Just like the equality statement, ==
, these will result in either a true or a false.
Line 3 contains the inequality statement, !=
.
trace ( myValue != 4 ); // false
This asks a simple question, is this value not equal to the other? If they are not equal, then the statement evaluates as true
; it is true that they are not equal. If they are equal, as they are in this example, the value violates the test and the result is false
.
Lines 4 and 5 are testing if one value is greater or less than the other:
trace ( myValue < 5 ); // true
trace ( myValue > 4 ); // false
Line 4 is asking if the value 5 is greater than the variable myValue
. Since myValue
equals 4, the number 5 is indeed greater than myValue
, so the result is true. Line 5 does the opposite, testing for if the value 4 is less than myValue
. As you can see, it returns a value of false
. That is because it technically isn’t less than myValue
, it is equal, so the test fails and results in false.
trace ( myValue <= 4 ); // true
trace ( myValue >= 4 ); // true
That is why both evaluate as true because the value of 4 is equal to the value of myValue
. You’ll notice that the less than or greater than symbol preceeds the equals sign. This won’t work if they are in the wrong order, so be sure to put the equals sign last.
To show how equality works, you’re going to create a demo that combines drag and drop of an object and tests if it is dropped at a certain location. You’ll use this to show how equality works as well as how you can use conditional statements based on the results of the conditional tests.
You first need to create an object to drag around.
1. In the FLA file, create a simple circle, and create a new linked object in the Library called DragCircle
.
2. Convert the new object to a symbol and ensure the registration point is at the center (Figure 12.1).
You have created the object in the Library, but you’ll be re-creating it using ActionScript in the class, so you don’t need it on the Stage.
3. Delete the object on the stage.
4. Create the following code in the Document class Booleans
package {
import flash.display.MovieClip;
import DragCircle;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean;
private var _dragCircle:MovieClip;
public function Booleans():void {
_init();
}
private function _init():void {
_dragCircle = new DragCircle();
_dragCircle.x = 100;
_dragCircle.y = 100;
addChild(_dragCircle);
}
}
}
5. Run the project. You should see something similar to Figure 12.2.
Notice that you defined the instance of the circle in the class definition, and then created the instance with the new
statement later on in the _init
method. Also, for good measure, the DragCircle
class was added at the top. This isn’t required since the DragCircle
is automatically created by Flash (since you haven’t defined), but it makes the code clearer by including it here.
You want to be able to drag and drop the object using the mouse. In ActionScript, every MovieClip has two methods that allow you to do exactly that: startDrag
and stopDrag
. You can use these methods in combination with the mouse events that you want to have trigger the beginning and ending of the drag action.
1. Add the code that will start the drag, as shown by the following highlighted code:
package {
import flash.display.MovieClip;
import DragCircle;
import flash.events.MouseEvent;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean;
private var _dragCircle:MovieClip;
public function Booleans():void {
_init();
}
private function _init():void {
_dragCircle = new DragCircle();
_dragCircle.x = 100;
_dragCircle.y = 100;
addChild(_dragCircle);
_dragCircle.addEventListener(MouseEvent.MOUSE_DOWN, drag);
_dragCircle.addEventListener(MouseEvent.MOUSE_UP, drop);
}
private function drag(e:MouseEvent):void {
e.target.startDrag();
}
private function drop(e:MouseEvent):void {
e.target.stopDrag();
}
}
}
The new code adds two event listeners that are attached to the mouse down and mouse up events of the dragCircle
instance. Each of these accesses the private methods named drag
and drop
. These methods accept a MouseEvent
parameter that we call e
. In the drag
method, you access the target of the event (the _dragCircle
instance) and use the startDrag
method. This begins the drag action on the object. In the drop
method, you discontinue the dragging of the object using the dropDrag
method.
In order to prevent errors, you need to import the MouseEvent class at the top. They may have been added for you automatically as you typed your code.
2. Run the project. You can click and drag the circle around the screen. If you click and drag anywhere else, nothing will happen.
This is the basic code you’ll build in the following examples.
Let’s add a little feedback that reports the x and y coordinates of the object when you drop the circle.
1. Update the class code to send the x and y coordinate information to the Output panel:
package {
import flash.display.MovieClip;
import DragCircle;
import flash.events.MouseEvent;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean;
private var _dragCircle:MovieClip;
public function Booleans():void {
_init();
}
private function _init():void {
_dragCircle = new DragCircle();
_dragCircle.x = 100;
_dragCircle.y = 100;
addChild(_dragCircle);
_dragCircle.addEventListener(MouseEvent.MOUSE_DOWN, drag);
_dragCircle.addEventListener(MouseEvent.MOUSE_UP, drop);
}
private function drag(e:MouseEvent):void {
e.target.startDrag();
}
private function drop(e:MouseEvent):void {
e.target.stopDrag();
trace("The circle is located at " + _dragCircle.x + "," + _dragCircle.y);
}
}
}
2. Run the project.
3. Drag the circle around the Stage and drop it. When you release the mouse, the Output panel will display the coordinates of the circle.
Now that you have the basics in place, let’s add some condition testing and see how it works. Imagine you want to create a simple exercise that tests if the circle is dropped past 200 on the x axis. In other words, you want to test if the _dragCircle
object’s x coordinate is greater than 200.
1. Add a trace
statement that will output the result of a simple conditional test based on the _dragCircle.x
parameter:
package {
import flash.display.MovieClip;
import DragCircle;
import flash.events.*;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean;
private var _dragCircle:MovieClip;
public function Booleans():void {
_init();
}
private function _init():void {
_dragCircle = new DragCircle();
_dragCircle.x = 100;
_dragCircle.y = 100;
addChild(_dragCircle);
_dragCircle.addEventListener(MouseEvent.MOUSE_DOWN, drag);
_dragCircle.addEventListener(MouseEvent.MOUSE_UP, drop);
}
private function drag(e:MouseEvent):void {
_dragCircle.startDrag();
}
private function drop(e:MouseEvent):void {
_dragCircle.stopDrag();
trace("The circle is located at " + _dragCircle.x + "," + _dragCircle.y);
trace( _dragCircle.x > 200 );
}
}
}
2. Drag the circle and drop it in various locations. You’ll get the final location, but also a true or false indicating whether the x coordinate is greater than 200.
If you drag and drop the object at different locations, you’ll get a variety of different responses:
The circle is located at 122,151
false
The circle is located at 365,107
true
The circle is located at 354,265
true
The circle is located at 279,176
true
The circle is located at 103,328
false
The circle is located at 65,72
false
Unfortunately, outputting true and false isn’t very useful. You need to do some specific actions with the test result. This is where conditional statements come in, and the first one is called the if
statement.
if
StatementThe if
statement does one thing. It asks a single question, and if the answer to that question is true, it executes a branch of code. The code that tested for the location of the circle worked, but it wasn’t very useful. Using an if
statement, you can adjust the code so it can execute some specific code based on the results of the conditional test. Refer to Figure 12.3 as you step through the following anatomy of an if
statement.
You start an if
statement with—you guessed it: if
(callout 1). You then use a set of parentheses around the conditional test you want to evaluate (callout 2). You can evaluate only one condition at a time, so there can only be a single true or false result in your condition. You then have a set of curly braces that denote the code block that is placed after the if
statement. If the condition is true, the code inside the code block will run (callout 4). If it is false, it will ignore the code block and keep running the program.
1. Insert the highlighted if
statement in the example project:
package {
import flash.display.MovieClip;
import DragCircle;
import flash.events.*;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean;
private var _dragCircle:MovieClip;
public function Booleans():void {
_ init();
}
private function _init():void {
_dragCircle = new DragCircle();
_dragCircle.x = 100;
_dragCircle.y = 100;
addChild(_dragCircle);
_dragCircle.addEventListener(MouseEvent.MOUSE_DOWN, drag);
_dragCircle.addEventListener(MouseEvent.MOUSE_UP, drop);
}
private function drag(e:MouseEvent):void {
_dragCircle.startDrag();
}
private function drop(e:MouseEvent):void {
_dragCircle.stopDrag();
trace("The circle is located at " + _dragCircle.x + "," + _dragCircle.y);
if ( _dragCircle.x > 200 ) {
trace("The circle is placed after the 200 x coordinate.");
}
}
}
}
2. Run the project. The Output panel will display something similar to the following:
The circle is located at 100,114
The circle is located at 209,134
The circle is placed after the 200 x coordinate.
The circle is located at 320,134
The circle is placed after the 200 x coordinate.
The circle is located at 68,200
This information is more useful than the previous true or false statements. Let’s explore the if
statement and learn how it works:
if ( _dragCircle.x > 200 ) {
trace("The circle is placed after the 200 x coordinate.");
}
The if
statement kicks off the question. Inside the parentheses, you create a single conditional statement that will evaluate as a single true or false. Then you start a new code block with curly braces and place the code that will run if the condition is true, followed by a closing curly brace.
This reads as: If dragCircle
’s x coordinate is greater than 200, then run this branch of code.
If your code block is only one line of code, you can omit the curly braces. You may encounter this in more complex code:
if ( _dragCircle.x > 200 ) trace("The circle is placed after the 200 x coordinate.");
Generally, programmers use the code blocks with the indented code, making the code easier to read.
if...else
StatementSo this code sample gives us feedback only if the coordinate is greater than 200. As you can see, when it isn’t, it gives you nothing. What you want to do is have an alternative branch of code run if the condition is false. You can control this using the else
statement.
1. Add the highlighted else
statement in the following code:
package {
import flash.display.MovieClip;
import DragCircle;
import flash.events.*;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean;
private var _dragCircle:MovieClip;
public function Booleans():void {
_ init();
}
private function _init():void {
_dragCircle = new DragCircle();
_dragCircle.x = 100;
_dragCircle.y = 100;
addChild(_dragCircle);
_dragCircle.addEventListener(MouseEvent.MOUSE_DOWN, drag);
_dragCircle.addEventListener(MouseEvent.MOUSE_UP, drop);
}
private function drag(e:MouseEvent):void {
_dragCircle.startDrag();
}
private function drop(e:MouseEvent):void {
_dragCircle.stopDrag();
trace("The circle is located at " + _dragCircle.x + "," + _dragCircle.y);
if ( _dragCircle.x > 200 ) {
trace("The circle is placed after the 200 x coordinate.");
} else {
trace("The circle is placed before or on the 200 x coordinate.");
}
}
}
}
The else
statement is added after the end of the closing block of the if
statement. If the condition that is tested at the start of the if
statement is false, the first code block is ignored, and instead, the code block after the else
statement runs.
Here is another way to look at it:
if (condition test)
{
// Run this code if the condition test is true
} else {
// Run this code if the condition test is false
}
As you can see from the code, either the first or the second code block is displayed:
The circle is located at 90,161
The circle is placed before or on the 200 x coordinate.
The circle is located at 283,174
The circle is placed after the 200 x coordinate.
The circle is located at 410,277
The circle is placed after the 200 x coordinate.
The circle is located at 39,317
The circle is placed before or on the 200 x coordinate.
if...else if
StatementThere is one final statement that you can use to evaluate code based on testing conditions, and that is the else if
statement. The purpose of the else if
statement is to continually test values until no more values work, and then end with an optional else
statement.
For example, if you wanted to update the example to test if the dropped circle is past multiple specific points, you can adapt the code to continue evaluating conditions.
1. Update the code with the following highlighted code:
package {
import flash.display.MovieClip;
import DragCircle;
import flash.events.*;
public class Booleans extends MovieClip {
private var _isCorrect:Boolean;
private var _dragCircle:MovieClip;
public function Booleans():void {
_init();
}
private function _init():void {
_dragCircle = new DragCircle();
_dragCircle.x = 100;
_dragCircle.y = 100;
addChild(_dragCircle);
_dragCircle.addEventListener(MouseEvent.MOUSE_DOWN, drag);
_dragCircle.addEventListener(MouseEvent.MOUSE_UP, drop);
}
private function drag(e:MouseEvent):void {
_dragCircle.startDrag();
}
private function drop(e:MouseEvent):void {
_dragCircle.stopDrag();
trace("The circle is located at " + _dragCircle.x + "," + _dragCircle.y);
if ( _dragCircle.x > 400 ) {
trace("The circle is placed after the 400 x coordinate.");
} else if ( _dragCircle.x > 200 ) {
trace("The circle is placed after the 200 x coordinate.");
} else {
trace("The circle is placed before or on the 200 x coordinate.");
}
}
}
}
2. Run the project. You’ll get an Output similar to the following:
The circle is located at 142,111
The circle is placed before or on the 200 x coordinate.
The circle is located at 225,149
The circle is placed after the 200 x coordinate.
The circle is located at 495,185
The circle is placed after the 400 x coordinate.
The circle is located at 80,215
The circle is placed before or on the 200 x coordinate.
The application is testing multiple conditions in succession. First it is testing if the x coordinate is greater than 400. If it is, it runs the first code block; if it isn’t, it tests another condition: is the x coordinate greater than 200? If it is, it runs the second code block; if it isn’t, it runs the final code block after the else
statement. The final else
statement is optional and can be omitted if you don’t want to have a catchall code block in your else if
conditional test.
Again, to help illustrate this, here’s an annotated version:
if (condition test 1)
{
// Run this code if test 1 is true, then end
} else if (condition test 2) {
// Run this code if test 1 is false, and test 2 is true, then end
} else {
// Run this code if condition test 1 and 2 are false
}
Something you need to be careful of is that as soon as a condition is met, it ends the entire sequence. Take this for example:
if ( _dragCircle.x > 200 ) {
trace("The circle is placed after the 200 x coordinate.");
} else if ( _dragCircle.x > 400 ) {
trace("The circle is placed after the 400 x coordinate.");
} else {
trace("The circle is placed before or on the 200 x coordinate.");
}
If the x coordinate is 500, the first condition tests true, but the second condition isn’t tested at all, which is not what you wanted. To prevent this, you need to make sure that the conditions test in an order that makes sense, or if you are unsure, create multiple testing conditions with multiple if
statements:
if ( _dragCircle.x > 200 ) {
trace("The circle is placed after the 200 x coordinate.");
}
if ( _dragCircle.x > 400 ) {
trace("The circle is placed after the 400 x coordinate.");
}
if ( _dragCircle.x <= 200 ){
trace("The circle is placed before or on the 200 x coordinate.");
}
Now with these multiple testing conditions, all of them will be tested, regardless of whether any one of them are true or false. Generally, the elegance of the else
statement will let you test if something is true and do something, or false and do something else; however there are times that you will want to create multiple if
statement conditions as well.
In this chapter you learned about working with Boolean values and using them to test for conditions using equality and inequality operators. Finally, you were able to use these new operators to build constructs in your code that let you execute different blocks of code based on the results of the conditional tests. As a bonus, you also learned how to use drag and drop behaviors with MovieClips. This was a lot for a single chapter, good job!
The following rules will help you work with Boolean variables and conditionals.
• Remember that Boolean values true
and false
do not use quotation marks.
• Use equality and inequality operators to test conditions between various values.
• Use the startDrag
and stopDrag
methods on MovieClip instances to create drag and drop examples.
• To execute specific code if a condition is true, use the if
statement.
• To execute specific code if a condition is true, and another set if the condition is false, use the if
statement in combination with the else
statement.
• To test multiple conditions in a sequence, use the if
and else if
statements in a testing sequence.
• Plan your testing sequences, especially in more complex situations to ensure that the flow of the test will catch all the testing options. Map them out on paper before starting to write code.
18.221.172.50