13. Advanced Boolean Logic and Random Numbers

Conditions give your applications the ability to change behaviors based on different circumstances. When working with more complex logic patterns, you need to use special operators. In this chapter, you’ll review these operators and use them in conditional tests.

One of the most common ways to work with advanced logic is when you build random chance into your programs. This is customary for games and other interactive content. In this chapter, you’ll learn how to generate random numbers and how to use them in your projects.

Using Logic Operators

When you are testing conditions, you are limited to testing a pair of values. Often-times you want to test a combination of conditions in a single statement.

In the drag and drop example from Chapter 12, you were testing where an object was dropped based on the x axis. If you wanted to capture if the object was dropped within a specific region, you would have some pretty complex code:

package {
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    public class Booleans extends MovieClip {
        var circle:DragCircle;
        public function Booleans():void {
             _init();
        }
        private function _ init():void {
            circle = new DragCircle();
            circle.x = 50;
            circle.x = 50;
            addChild(circle);
            circle.addEventListener(MouseEvent.MOUSE_DOWN, drag);
            circle.addEventListener(MouseEvent.MOUSE_UP, drop);
        }
        private function drag(e:MouseEvent):void {
            circle.startDrag();
        }
        private function drop(e:MouseEvent):void {
            circle.stopDrag();
            if (circle.x > 100) {
                if (circle.y > 100) {
                    if (circle.x < 450) {
                        if (circle.y < 300) {
                            trace("The circle is within the rectangle!");
                        }
                    }
                }
            }
        }
    }
}

Managing all of those nested condition statements to test the circle’s location can get tricky, and you could easily have a situation where you test them in a different order and therefore exit the sequence prematurely.

To make this code easier to understand and more concise, you can use logical operators that can combine multiple testing pairs to create more complex tests.

The AND Operator

Probably the most common operator is the AND, which is represented by a pair of ampersands, &&. You can use these ampersands to link multiple conditional tests together. This operator requests that the conditions on either side must both be true for the entire test to be true.

Let’s look at a section of code that highlights the AND operator:

trace ( 2 == 2 && 3 == 3 );
trace ( 2 == 3 && 3 == 3 );

These lines evaluate as the following in the Output panel:

true
false

This code evaluates each condition test, and when both are finished, it compares the results and asks if the one on the left AND the one on the right are both true. If they are, then the entire test is true. If they aren’t, then the entire test is false.

In this case, 2 is equal to 2, and 3 is equal to 3, so you have two trues, which means that the whole test is true. In the second example, 2 is not equal to 3, so that is false, and the second test is true because 3 is equal to 3. Although the second test is true, the first is false, so when you use && the entire condition evaluates as false.

The OR Operator

In addition to AND, there is also the OR operator, which is represented by two vertical lines (also known as pipes), ||. In the following section of code, the test will pass if any of the individual tests are true:

trace ( 2 == 2 || 3 == 3 );
trace ( 2 == 3 || 3 == 3 );

These two lines evaluate to the following in the Output panel:

true
true

At least one of the tests on the left or right are true, so both tests pass.

The NOT Operator

The NOT operator is a little different from its siblings. It takes the current Boolean value of an object and reverses it. To use this, you take the variable that contains the Boolean value and you add an exclamation point, !, as a prefix to the variable name:

var myTest = 2 == 2 || 3 == 3;
trace ( !myTest );

This code produces the opposite of the test result:

false

The NOT operator is very helpful at creating toggle switches. MoveClips have several properties that have true or false values (visible is one example). Using the NOT operator, you can toggle between these values:

myMovie.visible = !myMovie.visible;

This code takes the current value, reverses it, and assigns it back to itself.

Building Complex Conditionals

Now that you understand the AND and OR operators, you can adjust the drag and drop example to test if objects are dropped within a specific range of x and y coordinates:

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();
            if (_dragCircle.x > 100 && _dragCircle.x < 450 && _dragCircle.y > 100 && _dragCircle.y < 300) {
                trace("The circle is within the rectangle!");
            }
        }
    }
}

Notice that you can string the && operators to create more complex examples. In this example, all four of the tests need to pass for the entire condition to pass. This format is much more concise and easier to understand than a set of nested if statements.

Generating Random Numbers

As mentioned earlier, the principle of games is the element of random chance. To add that aspect to your project you need to work with random numbers. The Math class has a specific method that is critical for anyone adding random elements into a game or other application.

A random number generator creates numbers at random that add the element of chance to applications. The random number generator is accessed through the random method of the Math class.

1. Create a new project in Flash Professional CS5.5.

2. Create a Document class for the project (this example is named RandomNumber) and enter in the following ActionScript code:

package {
    import flash.display.MovieClip;
    public class RandomNumber extends MovieClip {
        public function RandomNumber():void {
            init();
        }
        private function init():void {
            trace ( Math.random() );
        }
    }
}

3. Run the project.

4. In the Output panel you will get a random decimal number that will resemble the following:

0.5108420490287244

The random method generates a decimal number between 0 and 1. You can use this number to create random numbers of different ranges. You can modify this to generate a number from 1 to 6, like a die.

5. Update the code, as follows:

package {
    import flash.display.MovieClip;
    public class RandomNumber extends MovieClip {
        public function RandomNumber():void {
            init();
        }
        private function init():void {
            trace ( Math.random() * 6 );
        }
    }
}

In this code, you are taking a randomly generated number and multiplying it by a factor of 6 to proportionally extend its range from 0 to 6.

6. Run the program several times, and you’ll get a series of random numbers that resemble the following:

2.5428863195702434
4.439002267085016
2.601632511243224
1.4373473664745688
0.963768957182765
3.0498380083590746
1.1904680645093322
1.5892081037163734

Unfortunately, this isn’t exactly what you want. A die doesn’t have decimal values, so you need some way to drop the decimals. Luckily the Math class has a method that can help: the floor method.

7. Add the floor method to the previous code, as highlighted below:

package {
    import flash.display.MovieClip;
    public class RandomNumber extends MovieClip {
        public function RandomNumber():void {
            init();
        }
        private function init():void {
            trace ( Math.floor(Math.random() * 6) );
        }
    }
}

8. Run the project again a few times. You get something similar to the following:

3
2
5
0
1
4

You’re close, but not quite there yet. Why? Because a die doesn’t have the number 0, and if you run this over and over again, you’ll notice that you’ll never get the number 6. That is because you are stripping the decimal from the number. The random range is between 0 and 1. When you multiply this by 6, you will never get the number 6. You might get 5.9999, but when you use floor, you strip off the .9999 and get 5. You get a zero, because you could get a number like 0.9999, but that will become 0 when using the floor method. To correct this, simply add 1 and shift the range up by one digit.

9. Adjust the random number generator, as highlighted below:

package {
    import flash.display.MovieClip;
    public class RandomNumber extends MovieClip {
        public function RandomNumber():void {
            init();
        }
        private function init():void {
            trace ( Math.floor(Math.random() * 6) + 1 );
        }
    }
}

10. Run the project several times, and you will now get numbers that are like the numbers on a die:

4
6
6
3
5
1

That is more like it! You’re ready for Vegas!

In addition to the floor method, the Math class contains two other ways to drop decimals: the ceil and round methods. The ceil method stands for ceiling, which bumps the value of the number to the next whole number if there is any decimal at all. So a number like 5.00001 would become 6 if you used the ceil method. The random method follows traditional rounding rules. If the number has a decimal of .5 or above, it is rounded up. If it is below .5, it is rounded down.

Wrapping Up

In this chapter, you learned how to make complex logical evaluations using the AND and OR logical operators. In addition, you learned how to reverse Boolean values with the NOT operator. You learned how to generate random numbers using the Math.random method to build random chance in your programs.

Here are some tips to help you with the topics from this chapter:

• Use the AND and OR operators to combine conditional statements together to form a single true or false response.

• Use the AND operator, &&, if you want to ensure that all the conditions you are testing evaluate as true.

• Use the OR operator, ||, if you want to ensure that at least one of the conditions you are testing evaluates as true.

• Use the NOT operator, !, as a prefix on a variable name to reverse its Boolean value.

• Use the Math.random method to create a random decimal number from 0 to 1.

• Multiply and add values to your random number to adjust the range of your random number generator.

• Use the Math.floor, Math.ceil, or Math.random methods to drop decimals from your numbers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.218.242