Chapter I: the base of ActionScript

Source: Internet
Author: User
Tags class definition
introduce: Using ActionScript, you can create flash programs to do anything you can think of. But before we get to the broader range, let's take a look at the basics. Good news when ActionScript's commands have well-defined patterns, sharing the same syntax, structure, and concepts. Mastering the basics of grammar can make you a better master of ActionScript.     This chapter will focus on the common features and issues, whether you are a beginner or an expert, here are some knowledge that will allow you to deal with all the ActionScript projects encountered problems.     This book assumes that you have correctly installed Flex Buidler 2 to your computer, and if you have experience with the 3.0 version of ActionScript before, that would be great.      When you enter Flex Builder 2, the Eclipse IDE will show you the Welcome interface, as well as some initial choices and flex,actionscript3.0 information to show you, such as documents, introductory tutorials, and so on. You can click on the tab's small "X" to close it. Now that you're in the Eclipese IDE, you're ready to write code, but we'll start there.     Flex Builder2 allows you to create three types of Engineering: Flex Project,flex Library Project,actionscript project. The difference is that flex project allows us to enter the entire Flex Framework, which contains all the flex components, layout management, transformations, formatting, headers, data bonding, and other materials necessary to create RIA programs. The Flex program is written in the Mxml file, and the Mxml file describes the connection and layout between components, using ActionScript as the business logic, although you can use the ActionScript knowledge learned in this book to your Flex program, But the book is focused on ActionScript engineering.     If you are familiar with the Flash8 or previous Flash IDE, now get a little embarrassed when you turn on Flex Builder2, there is no timeline, no library, no drawing tools, no color tools. You have to use code to express everything, and that's why it's called ActionScript Project, not flash project. So now let's start our own first project. Create a ActionScript Engineering Question: You have turned on Flex Builder 2 and want to create a ActionScript engineering solution: Use the new ActionScript project. Discussion: A ActionScript project typically consists of at least one class file, a folder called Bin containing SWF and HTML files. And there are internal settings inside to let the compiler know how everything is compiled. Flex Builder 2 For you to consider everything when you create a new project. You have several ways to create new projects, you can use the menu File-new-actionscript project, or you can just click on the New button on the corner to create a new project, you can open the new list by clicking the arrow next to New. Its function is exactly the same as new. No matter what sequence you're in, you should have opened a new ActionScript Project dialog box, and now you're prompted to enter a project name, such as Exampleapplication, and once you create the project, you'll notice that main The Application Cup gives the same name as the project, with the as extension. Clicking the Next button prompts you to set the appropriate user-class file save path, additional library files, and specify your output folder instead of Bin, and now you just need to use the default and click Exit to close the wizard. Flex Builder 2 Now creates all the necessary files and folders, and compiles your project using the default compilation settings, in Navigation view, you should now see a project called Exampleapplication, It contains an empty bin file. A class file called Exampleapplication.as. The IDE automatically creates this file for you and has been automatically opened for you in the editing window, and in the outline window you can see the structure of the class, including methods, attributes, and some import statements. To run your program, you can press one or two buttons, one is to want the bug button, this button makes you debug your program, meaning you can output some additional information to the console to debugging your application, using the trace statement. The other one is a green circle with an arrow in it that runs your program. The top two buttons can create a. swf file and an HTML file, and then load the HTML file inside your browser. Of course, you haven't added any code to your program at the moment, so you'll see that the browser doesn't show anything. But in order to detect that you have done all the work, you should be able to get a blue background page.   setting properties for an applicationQuestion: You want to change the size of the output. swf file, background color, frame rate. Workaround: Set ActionScript and metadata properties inside the class file. Discussion: Unlike previous Flash, the ActionScript3.0 compiler is actually a command-line compiler. Technically, you can create all the class and library files on the command line, but it will be much simpler if you let eclipse do these things for you. When you create a new ActionScript project, it sets the default scale 500*375 and frame rate 24 per second, and is the background color as you see, you can change any of these settings, or, as you might think, there are many ways to do this thing. The first method is to set the compilation parameters of ActionScript, you can click ActionScript in the Navigation window, then right-click, select Properties, select ActionScript Compiler in the open window. The open window allows you to set several options for how the compiler works for you. Look at the text box labeled "additonal compiler Argument", and any data you want to pass to the compiler can be passed to the command line. Here are some of the most common parameters you need to use:
-default-size Width Height
-default-background-color Color
-default-frame-rate fps
We set the following:-default-size 600-default-background-color 0xffffff-default-frame-rate 31 Here we set the size of the. swf file to 800* 600, the second set the background color to white, the last one to set the frame rate of 31fps, multiple parameters one after another write on it, such as:-default-size 600 800–defualt-background-color 0xfffff– Defualt-rate 31 The second way to change these parameters is to use the metadata,metadata of your main class file, which is composed of statements that are not directly interpreted as ActionScript, but the compiler uses it to determine how to compile the final output file. The metadata corresponding to the previous statement looks like this: [SWF (width= ", height=", backgroundcolor= "#ffffff", framerate= "31")] This section is placed inside the main package , but to be placed outside of any class definition, we usually put it before or after the import. where to place ActionScript Code Question: You have a actionproject project now, and you need to know where to write the code so that it can perform well. Solution: Put the code inside the constructor or add the method to the class. Discussion: in ActionScript1.0 and 2.0. You'll have a lot of options for setting up your code, in timelines, on buttons, or in movie clips, in internal. As files, using #include, or using external class files. ACTIONSCRIOPT3.0 is purely class based, so all code must be in the method inside the class. When you create a new ActionScript project, the main class is created accordingly and opens the file in Code view, which should look like this: package {       Import Flash.display.Sprite;     [SWF (height= "," width= "", backgroundcolor= "#2fffff", framerate= ")]"         public class ExampleApplication1 extends Sprite        {                      Public Function ExampleApplication1 ()                       {                                                         }       } Maybe you're already familiar with ActionScript2.0, but there's something new here, and we'll go into the second chapter detailing these different places, so let's look at some of the basics of kind. The first thing you need to be aware of IS Package The word, packages, is used to organize some of the functions associated with the classes together. In actionscript2.0,packages the class file is organized through the directory structure, in the ActionScript3.0, you must show the specified package, for example, you may have a few side-written classes, want to put them in the same package, the statement here looks like the following:   such as package com.as3cb.utils{} If you do not specify a package name, your class is created by default in the highest package, you can also use the Package keyword and braces in the package. Next, place the import statement, import a class file so that this class can be used by other code, and you set a shortcut, you do not have to use this class each time using the full pathname, and only need to use the class name. For example, you can use the Import statement: Import Com.as3ab.utils.StringUtils, and then you can use StringUtils instead of other paths (if you are familiar with. NET programming, here's the concept very Easy). Because each class inherits from the Sprite class by default, we must import the Flash.display. Next up is the main class, Exampleapplication, you may have noticed the keyword public, although you cannot have a private class in a package, but you must indicate that a class is public. Note that the main class inherits the Sprite class, and that a. swf itself is a sprite or movie clip, That's why you can call another. swf file in one of the. swf files, because this is just an embedded sprite or movie clip. This main class represents the entire. swf file, so it must inherit from the Sprite class or from other classes that inherit from sprite (such as MovieClip). Finally, there is a public function (or method) whose name is the same as the name of the main class containing it, the method called the constructor (constructor), and the constructor of a class is executed automatically when an instance of this class is created, in which case It executes when the. swf file is loaded into Flash player. So, where should you put the code? Generally, you start by putting some code in the constructor, here's a simple example, we simply draw some random lines on the screen: package {    Import FLASH.DISPLAY.SPRIte     public class Exampleapplication extends Sprite {        public function Exampleapplication ( ) {            Graphics.linestyle (1, 0, 1);             for (Var i:int=0;i<100;i++) {                 Graphics.lineto (Math.random (  ) *, Math.random ( ) * 400);            }        } &NBSP;&NBSP;&NBSP} to save and run the program, you will see some messy lines in the browser, as you can see, the constructor executes immediately after the file is loaded into Flash player. In practice, you rarely have the opportunity to write the code in the constructor, ideally the constructor will only contain a call to another initialization method, reference Creating reusable CodeAnd generalization methods to improve reusableSection. As a novice, now that you know how to get into the code, here are some primer of terms. These definitions are very brief, to give some inspiration to the novice, if you want to see some detailed definition, please refer to the Help documentation. Parameters:........ function........ How to send information to the console Problem: You need to output a message or some data value to be resolved at runtime: Use the Tarce function, give the function a parameter, and then run your program, and you will see the output in the console (console). Discussion: You can output a message, or a data value, or a parameter value, just pass the values to the trace's parameters, as you did in the previous ActionScript version. For example: Trace ("Hello, World"); Trace (UserName); Trace ("My name is" + UserName + ".");. After the SWF file is loaded into the browser, it will find no way to display the information about the output, fortunately, it is possible that this function has been built inside Flex Builder 2 and we can see the output through the console window. Console output is the same as output in the Flash IDE, although it appears when you start to run Eclipse. The only thing we use with the trace and console windows is when you debug your program, and that's where the. swf file contains other features that allow you to interact with the console in the background and pass some information to the background to display it. The example below creates a variable, assigns it a value, and then prints it to the console, where some string data is used package {    import flash.display.Sprite;      public class Exampleapplication extends Sprite {        public function Exampleapplication ( ) {            var userName: String = "Bill Smith";             Trace ("My name is" + UserName + ".");        }    }     Now, if you debug your program, it will load in the browser as usual, close the browser back to eclipse, and you can see the data you want to output in the console window.     If you start the debug version of the program, you must have a debug version of Flash Player, if you do not have the debug version of Flash Player, you will see the error message prompts you that you must download it from HTTP ://www.adobe.com/support/flashplayer/downloads.html.     attached, the debug version of Flash Player can write the output to a file, Flash Player uses a configuration file is mm.cfg, this file because the operating system will be different places, as follows: Windows XP    c:/documents and settings/[user name]/mm.cfg Windows 2000. C:/mm.cfg Mac OS X MacHD:Library:Application Support:macromedia:mm.cfg mm.cfg allows you to configure some of the following parameters: Traceoutputfileenable: can be set to 0 or 1, 1 is written to the file, 0 is not traceoutputfilename: write the path to the file, if not configured, is written to a file called Flashlog.txt in the folder where Mm.cfg is located tracereportingenable: The default is 0 for not writing the error to the log, and 1 for writing to the log maxwarning: Controlling the number of errors written to the log, by default, by 0, If it is a number larger than 0, take that number as the Mm.cfg file contains at least the following line: traceoutputfileenable=1 If you want to specify an extra variable, you must write separate lines:
Traceoutputfileenable=1
Traceoutputfilename=c:/flex.log
Handling Events    Question: You want some code to repeat execution    resolution: Add a listener to Enterframe Evevt and associate a method as event handling handler    Discussion: Dealing with Enterframe events in ActionScript2.0 is very simple, you simply create a Timelinie function called Onenterframe, which executes automatically each time a new frame starts. In ActionScript3.0, you have to have more control over it in a. swf file, but just a little bit of work.    If you are familiar with the Eventdispatcher class in 2.0, you now have a better idea of 3.0 processing events, in fact, Eventdispatcher has evolved from an external class into a class that is now the basis, just like sprites.     to respond to Enterframe event, you must tell the application to listen the event and tell the application what to do when the event occurs, The whole can be implemented through the AddEventListener method, its definition: AddEventListener (type:string, listener:function), it has some other parameters of the version, the whole is just the most commonly used one. The      type parameter is the type of envent you want to listen, where this argument is "Enterframe". However, using strings here can sometimes cause errors, causing the compiler to not capture. For example, if you accidentally mistake the name of the event, your application is constantly listen the wrong event and will never hear it. To eliminate these errors, you can use some of the static properties of the event class, and if you have the event class import in, you can invoke the AddEventListener method as follows: Addevnetlistener (event.enter_ Frame,onenterframe);     Now, if you enter the wrong time name, the compiler complains that no such event can be found.     the second parameter, Onenterframe, relates to a method of another class. It is customary for us to add on to the name of the event's handling method, which accepts ainstance when it is invoked, therefore, you must import the event class to receive an event object when this method is defined: import flash.evnets.Event; The Private function Onenterframe (event:event) {}     event parameter contains some of the required information that may be useful for processing, even if you do not use the information, you must receive this parameter.     Here's an example for drawing random lines, using all the concepts mentioned above:
Package {
Import Flash.display.Sprite;
Import flash.events.Event;
public class Exampleapplication extends Sprite {
Public Function exampleapplication () {
Graphics.linestyle (1, 0, 1);
AddEventListener (Event.enter_frame, onenterframe);
}
Private Function Onenterframe (event:event): void {
Graphics.lineto (Math.random () *, Math.random () * 400);
}
}
}
events in response to mouse and keyboard Problem: We want to respond to mouse and keyboard events: Listen discussion of the mouse and keyboard time: Handling mouse and keyboard events is very similar to handling Enterframe events, as described in the front, but still requires some work. In the case of mouse, the main class does not receive the event directly, so we have to accept it with another object in the presentation list. (In the fifth chapter we will give a detailed introduction) The following example creates a Sprite, adds it to the display list, and then draws a rectangle inside it: Package {    import flash.display.Sprite;     import flash.events.MouseEvent;     public class Exampleapplication extends Sprite {        private var _sprite:sprite;         Public Function exampleapplication ( ) {             _sprite = new Sprite ( );             AddChild (_sprite);             _sprite.graphics.beginfill (0XFFFFFF);             _sprite.graphics.drawrect (0, 0, 400, 400);           &nbsp _sprite.graphics.endfill ( ); Note that the mouse event is defined in the MouseEvent class, and the incident-handling method accepts an instance of a MouseEvent class, so you must import the MouseEvent class and you can add listeners to this sprite: _ Sprite.addeventlistener (Mouseevent.mouse_down, OnMouseDown);       _sprite.addeventlistener (mouseevent.mouse_up, onMouseUp)     then, Defines two event handler functions OnMouseDown and Onmouseup:private function OnMouseDown (event:mouseevent): void {             _sprite.graphics.linestyle (1, 0, 1);             _sprite.graphics.moveto (MouseX, Mousey);             _sprite.addeventlistener (mouseevent.mouse_ Move, OnMouseMove);        }         Private Function OnMouseUp ( event:mouseevent): void         {             _spRite.removeeventlistener (Mouseevent.mouse_move, OnMouseMove); The        }     onmousedown method sets the line Style property and moves the paint cursor to the mouse position. The third mouse event MouseMove event is added next. The     onmouseup method removes the previous listen event using the RemoveEventListener method, and its syntax is the same as that of AddEventListener, But its main purpose is to tell the application to stop listen specific events.     Finally, define onmousemove shutdown classes and package:
Private Function OnMouseMove (event:mouseevent): void {
_sprite.graphics.lineto (MouseX, Mousey);
}
So far we have created a simple event driver. Next we use an example to illustrate the KeyDown event, the corresponding key to the number of characters out of the console. This example also shows how to use the data contained inside the Evnet object passed to the method, noting that the keyboard event uses the class KeyboardEvent.
Package {
Import Flash.display.Sprite;
Import flash.events.KeyboardEvent;
public class Exampleapplication extends Sprite {
Public Function exampleapplication () {
Stage.focus = this;
AddEventListener (Keyboardevent.key_down, OnKeyDown);
}
Private Function OnKeyDown (event:keyboardevent): void {
Trace ("Key down:" + event.charcode);
}
}
}
using mathematical operation symbols    Problem: You need to change something at some point, such as the sprite position and rotation.     Workaround: Use the assignment operator to add an attribute, or, add one or minus 1 operations, you can use the prefix expression or suffix expression to achieve the same goal. The assignment operator saves the data on the right to the variable on the left, or it is saved to a property.     Therefore, if you modify the data on the right, the left side will also change accordingly. Although the code below looks strange (I don't think it's surprising, hehe), for people familiar with basic Glgebra, this is very common in our usual use://ADD 6 to the current value of quantity, and as Sign that's new//value back to quantity. For example, if quantity is 4, this//statement sets it to 10.     Quantity = quantity + 6; However, in our usual use, we prefer to use a more convenient match operator.    For example +=,-=,*=,/= they are very popular, they have the same effect as above. There are also, for example, the addition and self reduction and C language is basically the same: Var quanlity:number=5 quanlity++;6 Quanlity--:5 back to our original problem, we use these operators to change the value of a property, such as: Private F     Unction Onenterframe (event:event) {_sprite.rotation = 5;} Note that in ActionScript3.0, you must add events to the main class. equivalence detection and worth comparison      Question: Do you want to detect whether two values are equal     solve: compare two values using equivalent or strict equivalence comparison operators to detect if a value is valid, use isNaN ().     discussion: Equivalence expressions always return a bool-type value to indicate whether the comparison of two values is equal, and the equivalent operators are both regular and rigorous. The equivalence and non-equivalence operators of a rule check that two values in an expression are equal, and if their type is different, convert them to the same data type to perform the detection. For example, we detect 6== "6", which is equal because the 6 of the string has been converted to an int type 6:trace (5 = = 6);   /Displays:false Trace (6 = 6) before performing the detection; nbsp;  //Displays:true trace (6 = "6");  //displays:true trace (5 = = "6");  //displays:false &nbsp ;  Note In the default configuration, the top code is not compiled, this is because our compiler performs a rigorous check, resulting in the compiler will be more stringent check type. The compiler complains that there is a comparison between the string type and the int type in the code. To turn off the strict mark bit, go back to the settings section of the compiler parameters we introduced before, and remove the Enable Compile-time type checking strict. This is only done here, in most cases we need this kind of detection, in order to prevent some of our negligence errors.    logical Unequal operation symbol returns FALSE when two values are equal and returns True when unequal, if two values that need to be compared are converted to the same type before the comparison is performed: Trace (5!= 6);    Displays:true Trace (6!= 6);   //Displays:false trace (6!= "6");  //Displays:false Trace (5!= "6");  //displays:true    here also needs the strict switch.    from another aspect, sayYou turn off the strict switch, but you want to do some strict comparisons on a piece of code, you can use the strict equivalent and the not equivalent operation symbol, = = = and. = =. These action symbols first check that the two-valued type of the comparison is the same, and that different types cause these action symbols to return false or ture. Trace (6 = = 6);    //Displays:true trace (6 = = "6");  //Displays:false Trace (6!== 6);    //Displays:false

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.