Mouse events give it interactivity.When a user clicks a button, that is an event.. To make this happen, Flash allows us to attach event handlers as Object Actions to the instance of the
Trang 1Flash and XML shows designers and developers how to integrate these
powerful technologies and create dynamic web sites With this thoroughlyreadable guide you take Flash to the next level, interfacing ActionScriptwith XML Empower your Flash projects with dynamic content, backend
Trang 2Flash and XML is a tutorial that brings you up to speed on both
technologies, offering clear and concise explanations In addition, thisbook presents a number of important web technologies, including PHP,MySQL, and sockets It shows how to work with these technologies tocreate n-tier, interactive systems that access the full resources of theInternet
Sample projects (trivia game, XML browser, simple chat) showcase thecapabilities of Flash and XML together and demonstrate importantconcepts, approaches, and techniques
Trang 5
Valid XML and Well-Formed XML DTD Declarations
Trang 6Database Fundamentals
Background
Advantages of a DBMS Advantages of SQL
Adding Data to Tables
Reading Records from the Table Conclusion
Chapter 13.
Serving from SQL
Connecting to a Database Interaction with a Database Parsing Commands
Fetching a Row
Trial-and-Error Approach Scalable Alternative
Chapter 16.
Cookies
ActionScript XML Objects Stateless Persistence
Conclusion
Trang 7Simple Socket System Simple Socket Server
Tools and Sources
Network Tool
Trang 8Servers XML Tools PHP Tools MySQL Tools Flash
Trang 9Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks Where those
designations appear in this book, and Addison-Wesley was aware of atrademark claim, the designations have been printed with initial capitalletters or in all capitals
The authors and publisher have taken care in the preparation of thisbook, but make no expressed or implied warranty of any kind and
assume no responsibility for errors or omissions No liability is assumedfor incidental or consequential damages in connection with or arising out
of the use of the information or programs contained herein
The publisher offers discounts on this book when ordered in quantity forspecial sales For more information, please contact: Pearson EducationCorporate Sales Division 201 W 103rd Street
Trang 10For information on obtaining permission for use of material from thiswork, please submit a written request to: Pearson Education, Inc
Rights and Contracts Department 75 Arlington Street, Suite 300
Boston, MA 02116
Fax: (617) 848-7047
Text printed on recycled paper 1 2 3 4 5 6 7 8 9 10—DOC—0504030201First printing, October 2001
Dedication
To three we love— Shez, Judy, and Anna Leah Jacobson
Trang 11Flash can make fabulous introductions to fancy web sites High-gradewow factor fills the opening screens Colors are delicious, typefaces aretrendy, and movement is exquisite Rave music is looping and attitude iseverywhere Each intro is a unique work of art But they all have one
thing in common
Each has a button that says SKIP INTRO
Rarely is gratuitous glitz so clearly labeled When budgets tighten,
webmasters will not skip shopping cart, or skip catalog But they may skipintro
Trang 12The web is outgrowing its eye-candy phase, and so must Flash A website must be pretty to be viable, but it must be highly functional as well
Flash pros can't get by on gee-whiz animation or cool interfaces They'dbetter prepare to do some of the heavy lifting on the working web Flashscreens must interface with dynamic content, with back-end databases,with server-based applications, and even with other live users
XML provides a path
Trang 13Once you connect your Flash code to the outside world, your scope isunbounded And so is the list of things to learn
In this book we learn a lot We begin with Flash and XML We studynetworking protocols and PHP server scripting We learn sockets andSQL and a few fancy XML dialects We go on to achieve competence inmany other related technologies and put them together to build workingweb systems
Trang 14If you are creative and technical, this book is for you Maybe you have adesign background You learn whatever technology you need to realizeyour vision This book offers you skills that open fresh new worlds Let'shope your imagination can keep up
Maybe you have computer science training You're happy with simplegray buttons Your art is an elegant code design You are ready to putFlash to work with all the web technologies you already know
This book was written by authors who approach Flash from both angles
We want it to speak to both engineers and artists, and we struggled(often with each other) to support both perspectives
Trang 15We wrote this book because it wasn't there when we needed it
Trang 18For her sure guidance, for her sturdy belief in this book and her faith in itsauthors: Mary T O'Brien, Executive Editor at Addison-Wesley
For their able support: her editorial assistants, Alicia Carey and MariannKourafas
For his imaginative, clearheaded thinking on many aspects of this book,and especially for its handsome looks: Kevin Smith of stateless designs
verbatim
For their careful, knowledgeable, and lively technical review: ChristopherIan Smith, John Paul Rawlins, Todd Williamsen, Scott Hamlin, Mike
Callery, Jennifer Hall, and the accomplished Brendan Hall
For their rapid responsiveness and for an enjoyable week of debuggingFlash patches together: Zlavik Lozben and Eric J Wittman of
Macromedia
For his clean direction of Flash technology: Peter Santangeli (We can allthank him.)
For building Macromedia with his bare hands and his big mouth: our oldfriend Marc Cantor
For their enthusiasm and their insights: Colin Moock and other
FlashForward speakers, Urami and other macromedia.flash posters, and
Trang 19For their support—financial and creative—of the real-life version of thegame described in this book: webmaster Garth Moore and producer ZoëBurkholder of the ASPCA (animaland.org)
For permission to reprint his haiku: Walter Vereertbrugghen
And for their critical contribution to this project: the makers of fine
caffeinated beverages all over the world
Trang 20In this chapter, we learn to build simple interface elements and interactivestructures Both the elementary structures we build and the techniques
we learn are used and developed further throughout the book
This chapter is intended for readers who are new to Flash It brings them
up to speed quickly on editing conventions and ActionScript
fundamentals It also presents an overview of the design of data andexecution in the trivia game
Trang 21Flash is an interesting phenomenon It began with technology intendedfor pen computing This technology—which translated strokes into
drawings—was commercialized as SmartSketch, a personal computerdrawing package SmartSketch made it easy for artists to create picturesthat were defined as geometry, not as a screen of pixels The inventors ofthe program, such as, Jonathan Gay, understood the advantages of thistechnology—vector drawing—over the more familiar technique of pixelpainting Geometric descriptions scale perfectly and they are extremelyefficient It is easy to move these pictures from one computer to another.High-level drawing descriptions also make it easy to organize the
elements of a drawing—and to manipulate them mathematically
Easy manipulation means powerful animation SmartSketch evolved intoCelAnimator—a professional cartooning tool The cartooning world isfairly small—and was smaller still in the 1990s This vector animationprogram might have disappeared like its predecessors except for theemergence of the Internet Device independence and tiny bandwidthrequirements were a great fit for the web—which was starved for
animation
Macromedia was introducing its venerable animation system, Director, tothe Internet under the name Shockwave But pixel-based technologysuch as Director is inflexible and slow to load In 1996, Macromedia
acquired the product, then called FutureSplash They changed the name
to Flash and merged it into the Shockwave line
In succeeding years, more interactivity and much more scripting wereadded to Flash
After a few awkward attempts to develop a proprietary coding syntax,Flash ActionScript was stabilized by adopting ECMA-262 as the basis ofits language definition ECMA-262 is the international standard for webscripting (JavaScript is an ECMA-compliant language.)
This decision lowered the learning curve for developers and reduced a lot
Trang 22A second wise decision also involved the adoption of web standards.Macromedia chose XML to be Flash's data-communication technology.Suddenly Flash developers were able to easily interact with an enormousnumber of web services This changed the nature of Flash once more.Instead of a stand-alone web application, a Flash presentation can beintegrated into a complex system of web-enabled software Flash is nolonger limited to entertainment It is now ready to provide high-qualityinterfaces to all kinds of hard working web applications
Trang 23In this chapter, we do not attempt to conscientiously teach Flash graphicscreation That is the subject of many other books The chapter is noteven an overview of the subject In fact this chapter is more of an
underview We offer a mouse's-eye view of the construction of a fewsimple but sophisticated interface elements We don't suggest that ourmethods are the best approach to each problem Multifaceted softwarelike Flash invites creative approaches The approach we show here,based on much experience in team production of code and graphics, isone good approach Consider it as you develop your own
Project Design
The trivia quiz game that we will build throughout this book is complexand sophisticated It starts, however, with some simple ideas that arerecognizable in every later step of development
Before we start any code, even demonstration code, we need to think alittle about the design In general, a detailed planning phase is always agood investment But in this case, just a simple layout of hierarchy willsuffice
We organize a Game into a series of Quizzes (Figure 1.1) Each Quiz has several rounds A Round is the presentation of a Question, the
player's response, and the scoring The Question is presented in Q&A format: a single Q and multiple-choice A's.
Figure 1.1 Object Hierarchy of the Trivia Game
Trang 25A great strength of ActionScript is that execution is event driven Thingsthat happen in the outside world cause things to happen in Flash
Frame Events
The most common event is that time passes Of course, time passesrather continuously, but in Flash (as in video or film) time is broken into astream of regular intervals called frames In a typical Flash applicationthere are 12 frames per second Twelve times every second, Flash is
interrupted by a frame event (more precisely, a frame start event), which
starts a cascade of calculations Anything that is in the process of movingmust determine its new position and prepare to redisplay This is howanimation happens
Each movie has a timeline When a frame event occurs, it advances apointer along the timeline to execute any new script or effect any
changes scheduled for this frame
Mouse Events
Frame events give Flash animation Mouse events give it interactivity.When a user clicks a button, that is an event It is in fact a series of
events: First the cursor enters the button's hot spot (the Roll Over
event) Then the user depresses the button (the Press event) Then the user stops pressing (Release) and moves the cursor away (Roll Out) All
four events happen often within a half second, but each has a differentmeaning in the rapidly stabilizing language of user interface:
Roll Over: What is this?
Press: I think I want to perform this action
Release: Yes, I do! I am committed
Roll Out: Oh Well, now I am bored
Trang 26need
An instance is not a copy It is a new reference to the original unchangedprototype This very powerful concept is at the heart of Flash
architecture
Since the button states are in the prototype, all instances we create (bydragging the button into the scene) share the same states They behaveidentically, as long as their behavior is designed in the states
Trang 27some buttons close Some win and some lose
To make this happen, Flash allows us to attach event handlers as Object Actions to the instance of the button They can behave like the button
states, and they can do more They can identify seven mouse events, notjust three, and they can attach any ActionScript to those events on thatbutton Button state frames (in the button's prototype) usually define thebutton's appearance and its dynamics—how it looks, how it moves, andhow it sounds Event handlers (attached to the instance) usually specifywhat the button does, how it affects the rest of the world
Trang 28An answer option must be sensitive to the mouse Players click on one ofthe options and actions are performed It would also be good to havevisible and audible reaction to the various steps in the mouse click and tothe mouse rollover as well Flash gives us all these abilities and more inthe Button primitive To clearly understand how buttons operate, it is best
Trang 29the thickness to 3 We duplicate the Border layer and create Border-top and Border-bottom using cut and paste and rename We differentiate them by deletion so that Border-top has only the top and left line
segments and Border-bottom has the bottom and right segments The Border-top layer is colored brighter than the panel, while the Border- bottom layer is darker.
Trang 30unpleasant Rather than choosing colors from all over the spectrum, weshould seek a meaningful palette with subtle transitions
Button Sounds
Before moving on, let's add a finishing touch to this button: a bit of
audible response Ideally, we would like to hear a sound begin when the
button is pressed and conclude when it is released Like cha-klunk— sounding cha on press, klunk on release This is possible in Flash, but it
is not directly supported It is much easier to simply attach a sound to theDown frame Users will hear the sound—the whole sound—as soon asthey press the button Unfortunately, this means that they hear the sameconfirming cue when they press down but roll off (i.e., change their
minds) as when they solidly click and release the button (commit)
Create a Sound layer, which is simply an ordinary new layer that you name Sound (only for our own source clarity, not for Flash) Insert a
single keyframe in the Down frame Choose a sharp sound from thechoices in WINDOW/COMMON LIBRARY/SOUNDS A tiny Play button in thelibrary window allows you to preview each sound With the keyframehighlighted, merely drag the sound into the main window to integrate itinto the button (Figure 1.4)
Figure 1.4 Adding Sound to a Button
Trang 31lets you click your new button Close the window to return to the editor
Experiment with your own ideas to make the button lively and unique.Subtle tunings make big differences Get happy with your button andmove on
Trang 32We now build the interactive round In this case, the round has threepossible states:
to be creative Code can be tucked into many corners, and a clever
programmer can devise a tricky game of hide and seek
Hide and seek is fun in the back yard But it is annoying at the computerand deadly when many people are working together and facing real
deadlines
The challenges of making good software together are numerous enoughwithout inventing more So we direct our creativity elsewhere and
approach code placement with this strict discipline:
If you use ActionScript on any frame, put it in a reserved layer called
Code.
Put labels on the top layer— in the Code layer if there is one, or even a Label layer.
Sounds should also be in their own layer(s)
Object actions, such as button actions, are exceptions If the button isgoing to do anything, an event handler must be attached to the objectinstance, not to a keyframe in a timeline layer Any object action should
Trang 33Like the button, the Round will establish each of the three states as a
separate frame While Flash frames often represent tiny slices of time inthe progress of an animation, they frequently are used instead to
represent static screens and as targets in finite-state logic Often, theyare both
Make a Movie Clip symbol using INSERT/NEW SYMBOL
Create a Code layer Like the Sound layer earlier, this is an ordinary layer
to which we give a special name Other than as a reminder for ourselves(and a hint to fellow programmers) layer names have absolutely no
meaning
Trang 34In the Code layer, label three keyframes Start, Win, and Lose These
frames do not have to be consecutive It is easier to read the labels ifthey are not and if the LARGE option is chosen behind this tiny icon, found
Double-click on the Start keyframe This will open an Actions panel.
Trang 35freeze the movie on the first frame of the scene It will not animate It willsit patiently waiting for the user to create the events that bring it to life
To create the events, the user needs buttons to press
Button Instance
Make a layer for the first option Let's call it A0 Highlight a keyframe at the Start frame of A0, and drag in the AnswerButton we already built The AnswerButton is a symbol in the library If the library is not already open,
select WINDOW/LIBRARY
The button we see on the Start frame is an instance of the AnswerButton
symbol Many instances can exist for any symbol They share one copy
of the graphics, sound, and embedded code But each instance has itsown set of variables Each has independent properties And each
instance has unique actions attached to it That is our next step
Button Actions
Right-click on the button and open Object Actions (Figure 1.5) Since it ispossible to place actions on the keyframe as well as on the button itself,you must take care to double-click on the button, not the frame The
operations look similar but function differently The title of the ActionScriptpanel should be "Object Actions."
Figure 1.5 Adding Actions to an Object in Normal Mode
Trang 36Normal mode you can click on Go To and insert this function Choose theType of the goto as Frame Label and select the Lose frame.
The support from the Normal mode training wheels is welcome at first; ithelps remind us of options and syntax (was it "Roll Out" or
"rollOut"?) But it quickly becomes claustrophobic
This code will cause the movie to play the Lose frame whenever the
mouse release (the final part of a click) occurs with the cursor over thisbutton This functionality is all we need for now
Button Text
Now we need to put an actual answer on this option button
Highlight the keyframe (and defocus the button; Figure 1.6) Using theText tool, stretch a rectangle across the face of the button and type in thefirst answer option Right-click on the text to open the panel Character tochoose color, font, and size Paragraph lets you choose (for example) tocenter text
Figure 1.6 Adding Text to a Button
Trang 37Figure 1.7 Quadruplicated Buttons
Trang 38to abstract and automate these design steps, for example, when
programming an unknown number of buttons to space themselves outautomatically
Now it is the work of a few minutes to change the text so that we havefour distinct answers While we are at it, we had better include a question
in the Q layer (Figure 1.8)
Figure 1.8 Differentiating the Four Buttons