• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 1. Introducing ActionScript > WRITING YOUR FIRST SCRIPT

WRITING YOUR FIRST SCRIPT

Now that we have all the information we need as well as a rough storyboard for our project, let’s begin assembling it.

1.
Open Windows Notepad or Apple Simple Text to create a new text file, and type the following: &electricBill=60.

In the first part of this exercise we’ll create the source for the data to be loaded into our movie when it plays. For our project, this data source contains a value representing the amount of the electric bill. When Flash loads this text file, it interprets this line of text and creates within the movie a piece of data (called a variable) named electricBill and assigns it a value of 60. The value of this variable will be used several ways in our project.

NOTE

Loading data into Flash from external sources is discussed in detail in Lesson 11, Getting Data In and Out of Flash. Variables are discussed in detail in Lesson 7, Using Dynamic Data.

2.
Name the text file Electric_Bill.txt and save it in the folder that contains the files for this lesson, then open electricbill1.fla in the Lesson01/Assets folder.

Because the focus of this book is ActionScript, not how to use Flash, you’ll find that with the exception of setting up scripts, our project elements are largely in place.

Our project’s main timeline contains five layers, each of which are 10 frames long. The layers will be named in such a way that their content is evident. Currently, the Actions layer is empty.

3.
Open the Property inspector, then select the text field in the upper left corner of the scene, just under the text that reads “Amount you owe is:”. In the Property inspector, give this text field an instance name of owed.

Since this text field will be used to display the amount of the electric bill, we’ve named it owed.

NOTE

In Flash 5, giving text fields variable names was the preferred way of identifying them for use in ActionScript. In Flash MX, however, text fields are now instances of the new Text Field object. As such, they are now identified using instance names. Although you can still assign variable names to text fields, some of the new functionality afforded Text Field objects will not be available if you do so. Thus, it’s better to use instance names to identify text fields.

4.
With the Property inspector still open, select the text field under the text that reads, “Amount you would like to pay is:”. In the Property inspector, give this text field an instance name of paid.

Looking at the Property inspector, you’ll notice that this is an Input Text field. It will be used to accept input from the user, specifically the amount he or she wants to pay toward the electric bill. We’ve entered zero (0) in this text field, so that’s the amount that will appear initially when our movie plays.

5.
With the Property inspector still open, select the text field at the bottom of the scene, under the Switch button. In the Property inspector, give this text field an instance name of message.

This text field will be used to display a custom message to our user, depending on how much he or she chooses to pay.

6.
Select the lightbulb movie clip instance and name it light.

Since our script will affect this movie clip instance, we must give the movie clip instance a name so that we can tell the script what to do with it. This movie clip instance has three frame labels (Off, On, and Hot) on its timeline that represent how it will look under various conditions. Initially, it will appear as Off.

In our script (which we’ll set up in a moment), we want the movie clip to remain at this label if the user pays less than what he or she owes—that is, the light won’t come on because the user hasn’t paid enough. If the user pays the exact amount, we want to send the clip’s timeline to the frame label On—that is, we want the light to come on. If the user pays too much, we want the clip’s timeline to go to the frame labeled Hot so that the light appears to be getting more juice than it needs.

Now that all of our scene elements are named, we’re ready to begin scripting; we’ll begin by instructing our movie to load the data from our external text file.

7.
With the Actions panel open (and set to Expert Mode), select Frame 1 of the Actions layer, and enter the following script:

							loadVariablesNum ("Electric_Bill.txt", 0);
						

NOTE

We suggest you leave the Actions panel in Expert Mode because it represents the easiest way to enter most of the scripts discussed in this book.

This line of script does one thing: It loads the variables from the Electric_Bill.txt file (which we created earlier) into Level 0, which is the movie file we’re working on now. The Electric_Bill.txt file contains a single variable named electricBill with a value of 60. Thus, after this line of script has executed, our movie will contain an electricBill variable with a value of 60. This process simply transfers the variables from our text file into our movie.

loadVariablesNum() is an action. We make it work a specific way by placing unique parameter values inside the parentheses. This particular action has two parameter settings, separated by a comma. The first setting is used to indicate the source containing the external data; the second is used to indicate the timeline into which to load the data. You’ll find that many ActionScript elements can accept multiple parameter settings in a similar fashion.

We’ve placed this script on Frame 1 of our movie so that it will be executed as soon as the movie begins playing—important since our movie needs the electricBill value in order for the script that we’ll be adding to the Light Switch button to work.

8.
Add a keyframe to Frame 10 of the Actions layer. Then, with the Actions panel open, enter the following script on that keyframe:

							owed.text = electricBill;
							stop ();
						

As set up in the last step, Frame 1 contains an action that will load the variables in the Electric_Bill.txt file. The movie’s timeline continues to play as the text file loads; then, when it reaches Frame 10, the above actions are executed.

The first action will set the value displayed in the owed text field instance to equal the value of electricBill . You’ll remember that owed is the instance name we assigned to the text field in the upper-left corner of our project, and that electricBill is the variable loaded in from our text file with a value of 60. Thus, this line of script will cause the number 60 to appear in the owed text field.

As mentioned earlier, text fields are now considered objects in Flash MX. As such, they also have numerous properties. One of the new properties of a text field instance is its text property. This property is used to designate the text displayed in an instance. The above script demonstrates how this property is used to set the text displayed in the text field instance named owed. Notice how a dot (.) separates the object name from the name of its property. In ActionScript, this is how you specify that you want to work with something specific concerning the object—in this case, one of its properties.

The first line also demonstrates the use of an operator between two elements, an object property and a variable (and its value). Here, the equals sign (=) is used to tell the script to assign the value of the electricBill variable to the text property of the owed text field instance.

The last action in the script simply stops the timeline from playing. Because this action does not require any unique parameter values, the parentheses are left empty.

TIP

You’ll notice that there’s a span of several frames between the frame containing the action to load the variables from the text file and the Frame 10 action that actually uses the electricBill variable that’s been loaded. This allows time for the text file to actually load. If we tried to use the electricBill variable before the text file had finished loading, we would encounter problems. In fact, our movie might act as if the text files had never loaded. A frame cushion, as we’ve created here, is one way to prevent problems. We’ll discuss other ways in later lessons.

Now it’s time to set up the script for our Light Switch button.

9.
With the Actions panel open, select the Light Switch button and enter the following script:

							on (press) {
							amountPaid = Number(paid.text);
							amountOwed = Number(owed.text);
							}
						

The first thing to notice about this script is that it executes when the button it’s attached to is pressed. Following this event is an opening curly brace ({), a couple lines of script, then a closing curly brace (}). These curly braces are used to say, “Do these two things as the result of the button being pressed.”

The above script accomplishes two things: First, a variable named amountPaid is created and its value is set to equal that displayed in the paid text field instance— though with a twist. Normally, anything entered in a text field is considered text. Thus, even if a value of 100 appears in the text field as numerals, it’s considered text (consisting of the characters 1, 0, and 0, or “100” with quotes) rather than the number 100 (without quotes).

NOTE

The fact that Flash considers everything entered in a text field to be text is a default behavior. Even though the user may not add quotes when typing into a text field, Flash invisibly adds them so that the movie knows that the value is a text value.

You can think of the Number() function as a specialized tool that allows you to convert a text value to a numerical value in such a way that ActionScript recognizes it as a number instead. You need to place the text that you want to convert between the parentheses of the function. For example:

							myNumber = Number("945");
						

This will convert the text “945” to the number 945 (no quotes) and assign that number value to the variable named myNumber . In the above script, we used the Number() function and placed a reference to the text value to be converted between the parentheses of the function. Thus, if the user types “54” (text initially) into the paid field, the Number function causes amountPaid to be given a value of 54 (no quotes, thus the number 54) as well.

NOTE

The Number() function does have its limitations: You can only use it to convert something that is potentially a number in the first place. For example, Number("dog") results in NaN (not a number) because a numeric conversion is not possible.

The next line in the script does essentially the same thing, only the value of amountOwed is set to equal the converted-to-a-number value displayed in the owed text field instance. You’ll remember that this text field instance displays the amount of the electric bill, or “60”. Thus, after the conversion takes place, amountOwed is given a value of 60.

The reason for converting the values in the text fields in this way is that most of the rest of the script will be using them to make mathematical evaluations/calculations— which means it needs to see them as numbers, not text, in order for them to work.

In summary, when the button is pressed, the text values displayed in the paid and owed text fields are converted to numbers. These number values are assigned to the variables named amountPaid and amountOwed , respectively. These variable values will be used in the remainder of the script.

10.
With the Actions panel still open, add the following lines of script to the script created in the previous step. Add them within the curly braces ({}), just below where it says amountOwed = Number(owed.text); :

							if (amountPaid < amountOwed) {
							difference = amountOwed - amountPaid;
							light.gotoAndStop ("Off");
							message.text = "You underpaid your bill by " + difference + " dollars.";
							} else if (amountPaid > amountOwed) {
							difference = amountOwed - amountPaid;
							light.gotoAndStop ("Hot");
							message.text = "You overpaid your bill by " + difference + " dollars.";
							} else {
							light.gotoAndStop ("On");
							message.text = "You have paid your bill in full.";
							}
						

					  

Since we added these lines of script within the curly braces of the on(press) event, they are also executed when the button is pressed.

This part of the script is essentially broken into three parts, identified by the following lines:

							if (amountPaid < amountOwed)
							else if (amountPaid > amountOwed)
							else
						

These three lines represent a series of conditions the script will analyze when executed. The condition to be analyzed is specified between the parentheses. Underneath each of these lines in the script (between additional curly braces) are several lines of indented script, which represent the actions that will be executed if that particular condition proves true. Here’s how it works:

When our Light Switch button is pressed, we want our script to determine whether the amount the user enters to pay is more, less, or equal to the amount owed. That’s what the three conditions our script analyzes are all about. Let’s review the first condition, which looks like this:

							if (amountPaid < amountOwed) {
							difference = amountOwed - amountPaid;
							light.gotoAndStop ("Off");
							message.text = "You underpaid your bill by " + difference + " dollars.";
							}
						

					  

The first line is a less-than operator (<) used to compare the value of one variable to another. It basically states, “If the amount the user enters to pay (amountPaid ) is less than the amount he or she owes (amountOwed ), take the actions below.” These actions are only executed if this condition is true . And if they are executed, it’s as a group, which is why they’re placed within their own set of curly braces. The first action creates a variable named difference and assigns it a value of amountOwed minus amountPaid . If the user has entered 40 as the amount to pay, difference would have a value of 20 (amountOwed – amountPaid , or 60 – 40). It’s important to note that any equation to the right of the equals sign is calculated prior to assigning the calculated value to the item to the left. The next line tells the light movie clip instance to go to and stop at the frame labeled Off. Since this action is only executed if the user underpays his or her bill, it’s appropriate that the light stays off. The last line will generate a custom message to be displayed in the message text field.

We call this a custom message because of the way the message is constructed within the script. Note the use of the difference variable in this line: The value of difference is inserted in the middle of this message between the two sections of quoted text and the plus signs. If difference has a value of 20 (as described above), this message would read:

“You underpaid your bill by 20 dollars.”

Remember that anything within quotes is considered plain text. Because difference is not enclosed in quotes, ActionScript knows that it references a variable’s name and thus will insert that variable’s value there. The plus sign (+) is used to concatenate (join) everything to create a single message. The equals sign is used to assign the final, concatenated value to the text property of the message text field.

If the amount the user enters to pay is the same as what’s owed, or more, this part of the script is ignored and the next part of the script is analyzed. It reads as follows:

							else if (amountPaid > amountOwed) {
							difference = amountOwed - amountPaid;
							light.gotoAndStop ("Hot");
							message.text = "You overpaid your bill by " + difference + " dollars.";
							}
						

					  

The first line here states, “If the amount the user enters to pay is more than the amount he or she owes, take the actions below.” The actions executed here are just variations on the ones discussed above—with a couple of minor differences: The first difference is that the light movie clip instance is sent to the frame labeled Hot, which displays a light bulb getting too much energy to signify that the user has overpaid. The second difference comes in the wording of the custom message. Instead of saying underpaid, here it says overpaid. The actions in this section are only executed if the user pays more than what’s owed. If that’s not the case, these actions are ignored and the last part of the script is analyzed. It reads as follows:

							else {
							light.gotoAndStop ("On");
							message.text = "You have paid your bill in full.";
							}
						

You’ll notice that here the script doesn’t begin by asking if amountPaid is more or less than amountOwed (as did the first two sections). This is because the script wouldn’t be carrying out this analysis if the user had entered the exact amount owed—that is, this part of the script will only execute if neither of the first sections do.

In the end, when the button is pressed, only one of these three actions will execute. As a result, the light movie clip instance will appear a certain way and a custom message will appear in the message text field.

When the Light Switch button is released, we want to reset the elements in our scene so that they appear as they did when the movie first played. Let’s add that functionality.

11.
With the Actions panel open and the Light Switch button still selected, enter the following script at the end of the current script:

							on (release) {
							light.gotoAndStop ("Off");
							message.text = "";
							}
						

This script is triggered when the button is released. It will send the light movie clip instance to the frame labeled Off and empty the message text field, returning these scene elements to their original state.

12.
Save this file as electricBill2.fla.

We’ll use this file in the next exercise in this lesson.


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint