Chapter 1. A Gentle Introduction for Non-ProgrammersI'm going to teach you to talk to Flash. Not just to program in Flash but to say things to it and to listen to what it has to say in return. This is not a metaphor or simply a rhetorical device. It's a philosophical approach to programming. Programming languages are used to send information to and receive information from computers. They are collections of vocabulary and grammar used to communicate, just like human languages. Using a programming language, we tell a computer what to do or ask it for information. It listens, tries to perform the requested actions, and gives responses. So while you may think you are reading this book in order to "learn to program," you are actually learning to communicate with Flash. But, of course, Flash doesn't speak English, French, German, or Cantonese. Flash's native language is ActionScript, and you're going to learn to speak it. Learning to speak a computer language is sometimes considered synonymous with learning to program. But there is more to programming than learning a language's syntax. What would it be like if Flash could speak English -- if we didn't need to learn ActionScript in order to communicate with it? What would happen if we were to say, "Flash, make a ball bounce around the screen?" Flash couldn't fulfill our request because it doesn't understand the word "ball." Okay, okay, that's just a matter of semantics. What Flash expects us to describe is the objects in the world it knows: movie clips, buttons, frames, and so on. So, let's rephrase our request in terms that Flash recognizes and see what happens: "Flash, make the movie clip named ball_one bounce around the screen." Flash still can't fulfill our request without more information. How big should the ball be? Where should it be placed? In which direction should it begin traveling? How fast should it go? Around which part of the screen should it bounce? For how long? In two dimensions or three? Hmm . . . we weren't expecting all these questions. In reality, Flash doesn't ask us these questions. Instead, when Flash can't understand us, it just doesn't do what we want it to, or it yields an error message. For now, we'll pretend Flash asked us for more explicit instructions, and reformulate our request as a series of steps:
Even though we gave our instructions in English, we still had to work through all the logic that governs our bouncing ball in order for Flash to understand us. Obviously, there's more to programming than merely the syntax of programming languages. Just as in English, knowing lots of words doesn't necessarily mean you're a great communicator. Our hypothetical English-speaking-Flash example exposes four important aspects of programming:
Most programming has nothing to do with writing code. Before you write even a single line of ActionScript, think through exactly what you want to do and write out your system's functionality as a flowchart or a blueprint. Once your program has been described sufficiently at the conceptual level, you can translate it into ActionScript. In programming -- as in love, politics, and business -- effective communication is the key to success. For Flash to understand your ActionScript, you have to get your syntax absolutely correct down to the last quote, equal sign, and semicolon. And to assure that Flash knows what you're talking about, you must refer only to the world it knows using terms it recognizes. What may be obvious to you is not obvious to a computer. Think of programming a computer like talking to a child: take nothing for granted, be explicit in every detail, and list every step that's necessary to complete a task. But remember that, unlike children, Flash will do precisely what you tell it to do and nothing that you don't tell it to do. 1.1. Some Basic PhrasesOn the first day of any language school you'd expect to learn a few basic phrases ("Good day," "How are you," etc.). Even if you're just memorizing a phrase and don't know what each word means, you can learn the effect of the phrase and can repeat it to produce that effect. Once you've learned the rules of grammar, expanded your vocabulary, and used the words from your memorized phrases in multiple contexts, you can understand your early phrases in a richer way. The rest of this chapter will be much like that first day of language school -- you'll see bits and pieces of code, and you'll be introduced to some fundamental programming grammar. The rest of the book will build on that foundation. You may want to come back to this chapter when you've finished the book to see just how far you've traveled. 1.1.1. Creating CodeFor our first exercise, we'll learn how to add four simple lines of code to a Flash movie. Nearly all ActionScript programming takes place in the Actions panel. Any instructions we add to the Actions panel are carried out by Flash when our movie plays. Open the Actions panel now by following these steps:
The Actions panel is divided into two sections: the Script pane (on the right) and the Toolbox pane (on the left). The Script pane houses all our code. The Toolbox pane provides us with quick access to the Actions, Operators, Functions, Properties, and Objects of ActionScript. You'll likely recognize the Basic Actions, shown in Figure 1-1, from prior Flash versions. Figure 1-1. Flash 5 Basic ActionsBut there's lots more to discover in the Toolbox pane: Figure 1-2 shows all available Actions, including some old friends from Flash 2, 3, and 4. If you continue exploring the Toolbox pane, you'll even find things like Sound, Array, and XML. By the end of this book, we'll have covered them all. Figure 1-2. Expanded ActionsThe Toolbox pane's menus may be used to create ActionScript code. However, in order to learn the syntax, principles, and structural makeup of ActionScript, we'll be typing all our code.
We'll be breaking Actions down to give you a programmer's perspective on those structures. Throughout the book, I use the appropriate programming term to describe the Action at hand. For example, instead of writing, "Add a while Action," I'll write, "Create a while loop." Instead of writing, "Add an if Action," I'll write, "Make a new conditional." Instead of writing, "Add a play Action," I'll write, "Invoke the play( ) function (or method)." These distinctions are an important part of learning to speak ActionScript. Ready to get your hands dirty? Let's say hello to Flash. 1.1.2. Say Hi to FlashBefore you can type code into the Actions panel, you must disengage the ActionScript autopilot as follows:
Howdya like that? You're already an expert. When you enter Expert Mode, the Parameters pane at the bottom of the Actions Panel disappears. Don't worry -- we're not programming with menus so we won't be needing it. Next, select frame 1 of layer 1. Your ActionScript (a.k.a., code) must always be attached to a frame, movie clip, or button; selecting frame 1 causes subsequently created code to be attached to that frame. In Expert Mode, you can type directly into the Script pane on the right side of the Actions panel, which is where we'll be doing all our programming. And now, the exciting moment -- your first line of code. It's time to introduce yourself to Flash! Type the following into the Script pane: var message = "Hi there, Flash!"; That line of code constitutes a complete instruction, known as a statement . On the line below it, type your second and third lines of code, shown following this paragraph. Replace your name here with your first name (whenever you see italicized code in this book it means you have to replace that portion of the code with your own content): var firstName = "your name here"; trace (message); Hmmm. Nothing has happened yet. That's because our code doesn't do anything until we export a .swf file and play our movie. Before we do that, let's ask Flash to say hi back to us. Type your fourth line of code under the lines you've already typed (man, we're really on a roll now . . . ): trace ("Hi there, " + firstName + ", nice to meet you."); Okay, Flash is ready to meet you. Select Control Test Movie and see what happens. Some text should appear in the Output window as shown in Figure 1-3. Figure 1-3. Flash gets friendly1.1.3. Keeping Track of Things ( Variables)Remember how I said programming was really just communicating with a computer? Well it is, but perhaps with a little less personality than I've been portraying so far. In your first line of code: var message = "Hi there, Flash!"; you didn't really say hi to Flash. You said something more like this:
Perhaps not as friendly as saying hi, but it illustrates one of the true foundations of programming: Flash can remember something for you, provided that you label it so that it can be found later. For example, in your second line of code, we had Flash remember your first name, and we named the reference to it firstName. Flash remembered your name and displayed it in the Output window when you tested your movie. The fact that Flash can remember things for us is crucial in programming. Flash can remember any type of data, including text (such as your name), numbers (such as 3.14159), and more complex datatypes that we'll discuss later. 1.1.3.1. Official variable nomenclatureTime for a few formal terms to describe how Flash remembers things. So far you know that Flash remembers data. An individual piece of data is known as a datum. A datum (e.g., "Hi there, Flash!") and the label that identifies it (e.g., message) are together known as a variable. A variable's label is called its name, and a variable's datum is called its value. We say that the variable stores or contains its value. Note that "Hi there, Flash!" is surrounded by double quotation marks (quotes) to indicate that it is a string of text, not a number or some other datatype. In your first line of code, you specified the value of the variable message. The act of specifying the value of a variable is known as assigning the variable's value, or generally, assignment . But before you can assign a value to a variable, you must first create it. We formally bring variables into existence by declaring them using the special keyword var, which you used earlier. So, in practice, here's how I might use more formal terms to instruct you to create the first line of code you created earlier: Declare a new variable named message, and assign it the initial value "Hi there, Flash!" Then you should write: var message = "Hi there, Flash!"; 1.1.4. The Wizard Behind the Curtain (the Interpreter)Recall your first two lines of code: var message = "Hi there, Flash!"; var firstName = "your name here"; In each of those statements, you created a variable and assigned a value to it. Your third and fourth lines, however, are a little different: trace (message); trace ("Hi there, " + firstName + ", nice to meet you."); These statements use the trace( ) command. You've already seen the effect of that command -- it caused Flash to display your text in the Output window. In the third line, Flash displayed the value of the variable message. In the last line, Flash also converted the variable firstName to its value (whatever you typed) and stuck that into the sentence after the words "Hi there." The trace( ) command, then, causes any specified data to appear in the Output window (which makes it handy for determining what's going on when a program is running). The question is, what made the trace( ) command place your text in the Output window? When you create a variable or issue a command, you're actually addressing the ActionScript interpreter, which runs your programs, manages your code, listens for instructions, performs any ActionScript commands, executes your statements, stores your data, sends you information, calculates values, and even starts up the basic programming environment when a movie is loaded into the Flash Player. The interpreter translates your ActionScript into a language that the computer understands and uses to carry out your code. During movie playback, the interpreter is always active, dutifully attempting to understand commands you give it. If the interpreter can understand your commands, it sends them to the computer's processor for execution. If a command generates a result, the interpreter provides that response to you. If the interpreter can't understand the command, it sends you an error message. The interpreter, hence, acts like ActionScript's switchboard operator -- it's the audience you're addressing in your code and the ambassador that reports back to you from Flash. Let's take a closer look at how the interpreter works by examining how it handles a simple trace( ) action. Consider this command as the interpreter would: trace ("Nice night to learn ActionScript."); The interpreter immediately recognizes the keyword trace from its special list of legal command names. The interpreter also knows that trace( ) is used to display text in the Output window, so it also expects to be told which text to display. It finds "Nice night to learn ActionScript." between parentheses following the word trace and thinks "Aha! That's just what I need. I'll have that sent to the Output window right away!" Note that the command is terminated by a semicolon ( ;). The semicolon acts like the period at the end of a sentence; with few exceptions, every ActionScript statement should end with a semicolon. With the statement successfully understood and all the required information in hand, the interpreter translates the command for the processor to execute, causing our text to appear in the Output window. That's a gross oversimplification of the internal details of how a computer processor and an interpreter work, but it illustrates these points:
You've only just been introduced to the interpreter, but you'll be as intimate with it as you are with a lover before too long: lots of fights, lots of yelling -- "Why aren't you listening to me?!" -- and lots of beautiful moments when you understand each other perfectly. Strangely enough, my dad always told me the best way to learn a new language is to find a lover that speaks it. May I, therefore, be the first to wish you all the best in your new relationship with the ActionScript interpreter. From now on I'll regularly refer to "the interpreter" instead of "Flash" when describing how ActionScript instructions are carried out. 1.1.5. Extra Info Required (Arguments)You've already seen one case in which we provided the interpreter with the text to display when issuing a trace( ) command. This approach is common; we'll often issue a command and then provide the interpreter with ancillary data used to execute that command. There's a special name for a datum sent to a command: an argument, or synonymously, a parameter. To supply an argument to a command, enclose the argument in parentheses, like this: command(argument); When supplying multiple arguments to a command, separate them with commas, like this: command(argument1, argument2, argument3); Supplying an argument to a command is known as passing the argument. For example, in the code gotoAndPlay(5), gotoAndPlay is the name of the command, and 5 is the argument being passed (in this case the frame number). Some commands, such as stop( ), require parentheses but do not accept arguments. We'll learn why in Chapter 9, "Functions". 1.1.6. ActionScript's Glue (Operators)Let's take another look at your fourth line of code, which contains this trace( ) statement: trace ("Hi there, " + firstName + ", nice to meet you."); See the + (plus) signs? They're used to join (concatenate) our text together and are but one of many available operators. The operators of a programming language are akin to conjunctions ("and," "or," "but," etc.) in human languages. They're devices used to combine and manipulate phrases of code. In the trace( ) example, the plus operator joins the quoted text "Hi there, " to the text contained in the variable firstName. All operators link phrases of code together, manipulating those phrases in the process. Whether the phrases are text, numbers, or some other datatype, an operator nearly always performs some kind of transformation. Very commonly, operators combine two things together, as the plus operator does. But other operators compare values, assign values, facilitate logical decisions, determine datatypes, create new objects, and provide various other handy services. When used with two numeric operands, the plus sign (+) and the minus sign ( -), perform basic arithmetic. The following displays "3" in the Output window: trace(5 - 2); The less-than operator checks which of two numbers is smaller or determines which of two letters is alphabetically first: if (3 < 300) { // Do something... } if ("a" < "z") { // Do something else... } The combinations, comparisons, assignments, or other manipulations performed by operators are known as operations. Arithmetic operations are the easiest operations to understand because they follow basic mathematics: addition (+), subtraction (-), multiplication (*), and division (/ ). But some operators will be less recognizable to you because they perform specialized programming tasks. Take the typeof operator, for example. It tells us what kind of data is stored in a variable. So, if we create a variable x, and give it the value 4, we can then ask the interpreter what datatype x contains, like this: var x = 4; trace (typeof x); When that line of code is executed in Flash, we get the word "number" in the Output window. Notice that we provide the typeof operator with a value upon which to operate, but without using parentheses: typeof x. You might therefore wonder whether or not x is an argument of typeof. In fact, x plays the same role as an argument (it's an ancillary piece of data needed in the computation of the phrase of code), but in the context of an operator, the argument-like x is officially called an operand. An operand is an item upon which an operator operates. For example, in the expression 4 + 9, the numbers 4 and 9 are operands of the + operator. Chapter 5, "Operators", covers all of the ActionScript operators in detail. For now just remember that operators link phrases of code in some kind of transformation. 1.1.7. Putting It All TogetherLet's review what you've learned. Here, again, is line one: var message = "Hi there, Flash!"; The keyword var tells the interpreter that we're declaring (creating) a new variable. The word message is the name of our variable. The equals sign is an operator that assigns the text string ("Hi there, Flash!") to the variable message. The text "Hi there, Flash!" hence, becomes the value of message. Finally, the semicolon (;) tells the interpreter that we're finished with our first statement. Line two is pretty much the same as line one: var firstName = "your name here"; Here we're assigning the text string you typed in place of your name here to the variable firstName. A semicolon ends our second statement. We then use the variables message and firstName in lines three and four: trace (message); trace ("Hi there, " + firstName + ", nice to meet you."); The keyword trace signals the interpreter that we'd like some text displayed in the Output window. We pass the text we want displayed as an argument. The opening parenthesis marks the beginning of our argument. In line four, the argument itself includes two operations, both of which use the plus operator. The first operation joins its first operand, "Hi there, " to the value of its second operand, firstName. The second operation joins ", nice to meet you." to the result of the first operation. The closing parenthesis marks the end of our argument, and the semicolon once again indicates the end of our statement. Blam! Your first ActionScript program. That has a nice ring to it, and it's an important landmark. Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|