Part 1: ActionScript Foundation From Chapters 1 to 5, the basics of ActionScript will introduce the basics of ActionScript. This part is mainly introduced, and you don't require you to fully remember. As long as there is a probably impression (at least know There is such a thing, you can find it when you need it). Many things can only be fully understood and familiar during the actual application, so I hope you can often try to write a little thing (starting from the modification example) In addition, don't complain about what special effects I have not used to teach ActionScript, because I haven't come to the step. The narrow imitation is unable to teach you real skills, don't believe it, you can try not to read the book of Hemingway To imitate the style of Hai Mingwei to write articles (such as imitation "death in the afternoon"). Creativity is based on the building. For familiar C , readers can skip this part. Of course, if you want to quickly You can also skip this part. Have time, or look good. Chapter 1: Code format and specification 1.1 Code format ActionScript Each row statement is in a semicolon ";" end. Different from the Basic language, ActionScript statement with C , Java, Pascal, allows you to write a multi-line writing, that is, allowing a very long statement into two or more code rows, as long as there is a semicolon at the end. The only disadvantage that allows statement branch writing is (at least many Familiar with Basic's persevering): The statement cannot forget the semicolon. The unique limit of statement branch is the string cannot be cross-line, that is, the two sections must be in the same line. Branch writing long statement is also a good typeset, for example The following statement segment (currently do not need to understand what the following statement is meaning, not comment behind the double slam): DuplicateMovieClip ("myoldmovieclip", // old MoVieClip instance name "MynewMovieClip", 999); // New replication The instance name and the hierarchical setProperty ("MyneWMovieClipNameisneWMC", // To modify the MovieClip instance name _alpha, "30"; // Modify its transparency of 30% but seems to be automatically formatted in Flash MX is not very perfect. The above code can be passed, but it will be erroneous when using the automatic format. The problem is inserting the comment statement between it. After all, I wrote the example, I don't have a good Flash MX's grammar specification (but according to the syntax of the C language) It's absolutely no problem), so please remember: Only in the statement is very long or Multi-line writing is used very complicated. --------------------------------------- ---------------------------------------- A good programmer will understand in the program Add a comment in the code. But maybe you will say: It doesn't matter, I know what I wrote. But if you read this code after 1 month? It is obvious, you can't remember. So many more What is the trouble? Give the ActionScript Code Add Note Use the following format: statements; // This is a single-line comment, starting with the double slash, the back of this line is a comment content statements; / * This is also a comment. Can be wrapped * / as simple (but very useful). Note / * and * / are not recommended (because it must be paired, so it will often cause errors). ------------- -------------------------------------------------- ----------------- Another way to increase the code readability is to use the code version. Below is a code with high readability: // calculate X Function function function function f (x) {if (x <= 0) {// If x is less than or equal to 0 RETURN 1; // Returns 1} else {RETURN X * f (x-1);
/ / Otherwise, the returned grade result}} Flash MX must be arranged by the programmer itself, while the Flash MX's Action panel has more auto format buttons, you can use it from moving formatting code (also also Syntax check, fairly convenient). Formatted options can be set in the dialog box corresponding to the Action panel pop-up menu. The following is a point for the Actions panel: Expenditure, the font font is best "Song", 9pt. However, in the Chinese system, the next line number and code seem to always be aligned. 1.2 Syntax Highlighting is the functionality of many programming languages for IDE (integrated development environment). Flash It also has this function. The color of the syntax coloring can be set in the dialog box corresponding to the preferences item of the ACTION panel pop-up menu. In this regard, there is nothing more detailed. Just hope that everyone can use grammar to find errors and read Code. The new Code Hint is not unfamiliar for readers familiar with Visual Studio 6.0 version. For example, enter "." After entering an object name, it will display the relevant properties and Method list; Enter "(", entered "(", will display the relevant function format. Specific you can experience yourself when you enter code. 1.3 Syntax specification 1.3.1 Keyword keyword is the basics of any language program Constructing unit. It is a reserved word, cannot be used as other purposes (can not be used as a custom variable, function, object name). The keywords in the ActionScript of Flash are not a lot, below their list: Flash MX ActionScript Keyword BREAK Take out the class (Class) Case (CASE) CASE Define a Switch statement Condition Select Bliction Document NEW Using Constructor Creating a new object Continue Jump to the next item of the cyclic body Return Return Value DEFAULT Definition Switch Statement DEFAULT Switch Defines a Multi-Category Selection Sector DELETE Clear The Memory Resource Objects Objects The Objects The Objects of the Current Code The IF statement returns a statement block TypeOf back to the object Type for definition one Ring VAR declares a local variable (LOCAL VARIABLE) Function Defines a Function Block Void Declaration Return Value Type Uncertain IF Define A conditional statement block While defines a conditional loop word block in an object or an array to create a loop with a loop with a pair The statement block of the specified object is not asking you to carry them down like a back word (this is why China's education is so bad), just hope that everyone will remember: There are some keywords in Flash The word cannot be used freely. This is useful when analyzing errors (especially for beginners). 1.3.2 Semixer sensitive Same as C and Java, ActionScript is case sensitive. This means: if: IF It is not equal to if IF. If I use IF in the code, an error will occur when running and checking. Avoiding this situation is actually very simple: pay more attention to whether the code is automatically colored by syntax, but Syntax Highlighting. But For variables, instance names, Action Label, ActionScript is not case sensitive. Neglior, I still recommend that everyone keeps a case when writing code. This is a very good habit . 1.3.3 Operators In addition to keywords, the most important part of the program language is the operator. Don't say that I am dead, because you don't understand these things, you can't do anything. Below is the list of operators, operators Priority (ie, when several operators appear in the same expression), which one is active first) from top to date: operator description
One dollar (unary) (unary) logic is not! Logic NOT NOT Logic is not logical, non-(Flash 4 format) post-second (POST) decreased () Function call [] Array (Array) Element. Structure (Structure) Member Prime (PRE) Equal (pre) Decrement NEW Creating Object Delete Delete Object TypeOf Get Object Type VoID Returns Undefined Value * Multiplication / Sampling (removal) add ADD string (String) connection (past & - minus << Press-to-point left shift >> Press-to-right shift >>> Position right shift (no symbol unsigned, with 0 fill)
// Returns 51.3.4 Constant constant is the amount that does not change in the program operation. For example, value 1, 2, 3 ..., logic value true, false, etc. In addition, there are some constants built in the system, specific You can see the content of the help file. 1.3.5 Expression is the most common statement in ActionScript is an expression, which is usually composed of variable names, operators, and constants. Below is a simple expression: x = 0; on the left is variable Name (x), the middle is an operator (assignment operator "=", the right side is constant (value 0). This is a very simple assignment expression. This expression we can declare a variable, One step is prepared. The expression is divided into assignment expressions, arithmetic expressions, and logical expressions. The assignment expression has been explained, that is, a value for the variable. Arithmetic expression as the name is the expression of mathematical operations, for example:: 1 3 (return value is value 4). Logical expression is a logical operation expression, for example: 1> 3. Only logical expressions return logic values. The front 1> 3 return value is false, That is, 1 is more than 3 is a fake. You can form a composite expression together with multiple expressions. Generally, this expression is also used. For example: t = 3 * 3 (2 3); x = 1 > 3; The second line above is a logical-assignment composite expression. First, Flash calculates the value of logical expression 1> 3, then assigns the value to X (ie x = false. For composite expressions) The order of operation can refer to the above operator table. To change the order of operations (the first line of example), this is consistent with other languages. Chapter 2: Variables and Data Types 2.1 Variables 2.1.1 Define Variable Variables What is it? Probably it is to store the container of information (more precisely pointing to a pointer to a storage location in memory space, but can be understood, why bother to remember such an abstract definition). As long as it can be stored Information and can change the information in various ways. I am not a teacher in the university. I know that the students die hard back, the actual thing is not, "all for exam". There is also one Concept: What is initialization variable? It is a valid value to indicate its content and data type when defined. Just as the following example, a string variable is defined: mYString = "I don't know what is initialization Variables "; it's as simple, but also the problem that the variable name must be a valid identifier (see, for example, the character not allowed by numbers and not allowed). The variable name cannot be similar to the ActionScript keyword and constant Same. Variable names must be unique in its scope (SCOPE) (what we will mention below is a role). -------------------- -------------------------------------------------- ---------- Squiry here habits, currently based on C standards, combined with ActionScript characteristics change: variable data type habits prefix example string (String) SZ or STR szAddress, szName, strComment values (Number) n or i nCount, nSerialNumber logical value (Boolean) b bVisible, bFlag, bEnabled array object is named according to the data type of the array - Button objects btn btnPlay, btnPost MovieClip objects mc mcBall, mcMotion TextField objects TXT TXTENTRY, TXTPASSWORD SOUND Object SND SNDBACKGROUND, SNDCLICK Why use these fixed prefix? In order to facilitate the reading and communication of the code, you can avoid most of the unrecriminal naming errors. So, please try to do it as much as possible when writing the code. (In this book, because of the example of the sample code in the previous part, this naming method is not used.) 2.1.2 variable scope is also what variable is accessible, it is as if it is in C &
Like the task in Renegade, the ID Card without Security Level 3 can not enter the area of the security level 3. The scope is generally three: Timeline, local (LOCAL), Global. -------------------------------------------------- ------------------------------ For timeline ranges, just like the above examples, = assignment and declare, of course You can also use SET action (Flash 4, not recommended method, unless you think that the code is not long): set (MyString, "I don't know what is the initialization variable"); Timeline range variable declaration, in declaring it It is accessible within the time line of the entire level (Level). ----------------------------------- -------------------------------------------- What is a local variable? I also often ask yourself. Local variables are in declaring its statement block (eg, a function body) is accessible variable, usually used to avoid conflicts and save memory, declare it can use var keyword: function localvar () {var myLocalstring = "This is a local string variable"; "INSIDE:" myLocalstring;} localvar (); trace ("Outside:" mylocalstring); The above Mylocalstring string variable is in the function tail The memory will be automatically cleared. So the time outside the TRACE statement is empty ("Outside:", and the trace in the function is returned: "INSIDE: This is a local string variable." If you delete the VAR keyword Then myLocalstring is a variable of timeline. After running, INSIDE and OUTSIDE are "this is a local string variable". In the following function, we will also mention the content of local variables. Maybe you pay attention There is a trace action in the function. It can send the value of the specified variable to the output window in the test mode (Testing Movie, Ctrl Enter Competence) to check whether the code for processing the variable is normal at runtime. This is a very convenient examination method, Used frequently when testing code. If you encounter unclear functions and keywords, you can open the reference panel to display the cursor location keyword or built-in function and the object of the object via the ACTION panel. It can also open it through a combination of Shift F1. Below is a reference panel: --------------------------------- ---------------------------------------------- global variables, As the name, it is the variable that can be accessed throughout Movie. Its declaration is special: _global.myglobalString = "This is a global string variable"; the statement uses a _Global identifier and some title (DOT SYNTAX, will be behind) Chapter Discussion). _Global identifier is new in Flash 6, used to create global variables, functions, objects, and classes (Class, you don't know what is, you can look at C books). Generally, Global is an object that is listed in parallel with the bottom-up _LEVEL0. All global variables, functions, objects are actually equivalent to its properties, methods, sub-objects. About its specific content can be reviewed, usually, we only need to use it. The global variable will be used by the same time line variable and local variable shield (OBSCURED), then we have to access it through other ways. Take a look at the example below: // Define global variables _global.x = "Global "
// A simple function function show () {trace ("There is no local variable function:" x); var x = "local"; trace ("There is a function of local variable:" x); Trace "Call the timeline variable when there is a local variable:" this.x);} // Test trace ("------ no timeline range variable ------"; show (); trace "Direct calls:" x); // Set timel variable x = "timeline"; // Test Trace ("----- Time line range variable -------"; show (); "Direct call:" x); Trace ("When there is a time line range variable, the global variable is called:" _Global.x); it can be seen from the results of the above example, there is a current timeline range When the variable of the same name with the global variable, only the variable variables can be accessed directly through the variable name. At this time, the global variable should be called with _Global. Variables. The same part variable will also block the timeline variable (at this time Use this. Variable name to call the timeline variable) and global variables (at this time you can use _Global. Variable name to call global variables). 2. 1. It is very simple to use variables in the code, and the readers who have a bit programming base can be used. Do it. Use an example to illustrate the use of variables in ActionScript: function vars (x) {if (x <5) {// If x is less than 5X = x 1; // x plus 1} else {x = 10; / / otherwise assigning 10} trace ("x =" x); returnix;} VARS (2); VARS (6); trace ("x =" x); // Test X whether it is a local variable The parameter in the function declaration does not require a VAR declaration to automatically act as a local variable (eg X) in the above example. You can see the last sentence of the above example (the return value is empty). We can see that the function defined above Four operations for local variable x (declared in function parameters): assignment: is the content stored in variables. Operation: Use operator operations and return results. The X = X 1 in the above example can be considered A composite statement (X 1) and an assignment (x = ...) composite statement. For logical operations (the condition of the above IF statement), returned to the logical value true or false (like x <5 in x Return true for 4 moments). Function and command call: as above ("x =" x); in the same, X is passed as a parameter Number, it represents the actual content it stores (the same in Return X;). The use of variables in ActionScript has a lot of flexibility, and we will explain the different data types. 2.2 Common data type 2.2.1 String | String a string is a series of characters, such as "this" is a string. Defining a string variable is simple, just assign a string data to it when initialization : chapter = "Chapter 2"; Section = "Section 2"; section_name = "FAQ"; FULL_NAME = Section "Add section_name 999; // Connecting string IF (TypeOf (full_name) String "{full_name =" type error! ";} trace (" full_name = " full_name);
The value of FULL_NAME of the fourth line above is the previous two variables (section and section_name) and a constant (999) operation result (using and add operators, their functions are the same). Please note that this line The value of the last side of the code is not the same type of data. If this data type is checked in the PASCAL, this line code is wrong. But ActionScript can automatically convert it into a string format, without special Function (of course, the safest way is to use the Tositions TSTRING () function of the Number object or the string () function). It can be seen that ActionScript is a language of weak type check (ie, unstrust to limit the operation between various data types. And passing), this is a bit similar, but it is more than a little more. In the latter, I use an IF statement to test whether the code with 999 is running normally (ie check if the value returned by the expression is a string, although There is not this necessary in practice). Note that I use a dedicated logic operator NE, of course, this is just to express the particularity of the string data type, in practical application! = That is, for Typeof Operators, we will explain in detail at the end of this chapter. -------------------------------------- -------------------------------------------- in practical applications, Some special characters cannot be directly entered in the string, such as directly entering quotation marks directly in the string (the integrity of the string). At this time, we need to use the escape character (escaping). To use escape Character, first enter a backslash (/), then enter the corresponding code. The detailed code list is as follows: Symnial character represents Character / B Randide Character (ASCII 8) / F page (ASCII 12) / N Runout (ASCII 10) / R Enter (ASCII 13) / T Table (ASCII 9) / "Double Quotes Character / 'Single Number Character // Single Ram Character / 000 - / 377 Binary Representation" X00 - / XFF hexadecimal character / u0000 - / u000 - / ufff hexadecimal represented 16-bit Unicode characters, for example: Trace ("He Said: /" i don / 'T Care About You. / "NNand SHE SMILED: / "really? /" "; you The actual content within the string of the above code can be read according to the above control list. The output after the run is: He SAID: "I don't Care About You." And she smiled: "really?" Can be seen, turn The righteous characters are converted to the actual character. This is the role of the escape character, and the readers who have learned C should be familiar. 2.2.2 Numerical | NumberActionScript Numeric data in NumberActionScript is double precision floating point number (not understanding It doesn't matter, anyway, I know that it is a value, it is just a scope limit). Any corresponding operation can be performed on numeric data. Such examples: a = 1; b = 2; SUM = a b; // A, B Zi IF (SUM> 0) {// If the result is greater than 0square_root = math.sqrt (sum); // Use the square root function of the Math object to see the square root of SUM ("SUM =" SUM); Trace ("Square_root =" Square_root); End. 2.2.3 Logical Variables | Boolean logical variables are also called Boolean variables (coming from their English name). It only has two values: true and false. In the case of necessary cases ActionScript automatically converts its value to 1 and 0, you can also assign it with 1 and 0 (this may be generated to be compatible with the Windows API function) .a = 10; b1 = 1; b2 = FALSE;
IF (b1 == true) {a = a b1;} else {b2 =! b2;} trace ("a =" a); trace ("b1 =" b1); trace ("b2 =" B2); the above code mixes the calculation of the numerical and logical variables. A = A B1 adds the logic value B1 (TRUE 1) to a, B2 =! B2 is to reflect against B2 (ie, by false) To true or by true to false, because there are only two cases: true or false). You can try to modify the value of B1 to see different effects. 2.2.4 Object | Object object is ActionScript An important data type. Something is more clear, it is a class in most programming languages. In fact, the MovieClip used in Flash is actually a predefined class, but it is some special. About it Objects We will introduce in later chapters. 2.2.5 Video | MovieClip movie is the only data type used in FLASH to reference image elements. You can operate through the various properties and methods of the MovieClip object (Method). Example (Instance). We will also explain in detail behind the movie. 2.2.6 empty | NULL? I said "empty", that is, there is nothing. This type of data is this, and it only has a value: Null. What is it used? It is used to indicate that a variable has not been assigned to indicate a variable that does not contain data to indicate that a function does not return a value to indicate a function of a function. Don't think it is Significance, it is very useful when it involves a specific program problem. 2.2.7 Undefined | undefined undefined type with null almost, there is only one value: undefined. It is used to indicate that a variable has not been assigned. 2.3 TypeOf operation In practical applications, we often encounter the case of data types that need to be determined to determine specific variables and objects. Flash provides a good use of TypeOf to solve this problem. Especially for custom functions, the type of parameters is very Important steps. Parameter type return value (string) String String Movieclip movileclip button Object Textfield Object Number Number Boolean Boolean Object Object Functio n Function Undefined Undefined Null Null TypeOf operator is high, can be operated before logical or arithmetic operators. The following is the example of its specific application: // constant Type Trace ("Numerical constant 36 type: " TypeOf 26); Trace (" String Constant What Type: " TypeOf" What "; // General TypeOf Operators can be used like , -, add, etc. // but to avoid errors or suggest you Use parentheses, such as TRACE ("Logic constant TRUE:" typeof (true)); // Type of object ("object object ());" TypeOf (Object ())); trace ("" NEW STRING () Type: " TypeOf New String ()); // Note The type of NEW operator priority than the method of TypeOf high // depends on its return value trace (" Math.SQRT () method Type : " TypeOf Math.SQRT ()); Trace (" Math.Tostring () method: " TypeOf Math.toString ()); // Null Null Type Trace (" Null Type: "
TYPEOF NULL); // Here I use a multi-level TypeOf to see the type of TypeOf returned ("TypeOf return value:" typeof (typeof null); you can also try to change the code yourself See what other things TypeOf is. Chapter 3: Conditions and Circles Chapter 3: Conditions and Circulations 3.1 Summary ActionScript Conditions and Circular Perspective with IF, Else, Else IF, For, While, Do ... while, For ... in and switch. They are called the process control action in Flash, but in fact, their essentials are not different from other program languages. Because the conditions and loop statements are the most basic in the program language, too The most practical statement, so you have to explain it here. For readers who have programming experience with C and Java, you can view it casual. 3.2 Conditional statement 3.2.1 IFIF can be said to be the most basic condition judgment in program language Statement. Whether there is any figure in any language. You can understand its format by the following example: Name = "SIC"; // below is the IF statement if (name == "sic" {trace ("author"; } The IF statement determines whether the statement in the brace is performed by judging whether the logical expression in the incomplete parentheses is true. If the logical expression name == "SiC" is true, it is in the output window (Output Window) The "author" is displayed, otherwise it will not be executed. Then let us imagine the effect of the following example: if (1) {trace ("always execute";} If you still remember the content of the previous data type, then you should be seen The if statement at this time is basically redundant, because for constant 1, the value of logical expression is constant (actually 1 is the value of the logical value True). However, for constant 0, it will always be false. You can Try to change 1 in the above example to a string constance (for example, "hi!" See what the effect will have. An example: name = "sic"; // below is the IF statement if (name = "SIC "{Trace";} More than this example is the difference between the first example? The difference is that the first use ==, and this is used =. For this example, if the IF is always To true. Think why? The problem is to use the assignment operator = rather than the logical operator ==. For assignment operations, the logical value returned is always True This is also a mistake for beginners. Be sure to pay attention to the distinguishing operator = and logical operators ==. Otherwise, you will encounter some inexplicable errors and problems, and the syntax check can not find errors (because assignments It is also an effective conditional expression). So keep in mind that the equality logic operators of ActionScript are == rather than = .3.2.2 if ... Else If you want another operation when it is not established? Do it very simple, add an else statement block after the if statement: Name = "Unknown"; // below is IF ... ELSE statement IF (Name == "SIC" {trace ("author"; } Else {trace ("unknown"; What should I do if it is determined? Al do it, use the else if resolution: Name = "sam"; // below is if ... Else IF statement IF (name == "sic" {trace ("author";} else if (Name == "Flash MX"
{Trace ("Flash MX is the software name."; Else if (Name! = "Unknown" {trace ("Who" Name "?";} else {trace ("unknown";} You can pick any Multiple else IFs are judged by multiple conditions, and the last ELSE statement can be available (according to actual needs). The only shortcoming is that ELSE IF is too much slower (a big in other program languages) Question). At this time, it will appear to switch. 3.2.4 SwitchWitch is a very good command in Visual Basic. It can perform different operations by judging different conditional expressions. But in ActionScript is not so big Flexible. Because the conditions of Switch in ActionScript are fixed to ===, that is, it is absolutely equal to (including the data type), unlike conditions operators such as>,> = in VB. So, else IF is still very useful in cases that need to be judged to be smaller than smaller. Now let's take a look at the example below: MyNumber = 3; // Assignment Give MyNumber / / below Switch Statement Switch (MyNumber) {Case 1: TRACE "This is the number I want to get."; Break; Case 2: Trace ("This number is smaller than me."; Break; Case 3: Trace ("This is my number."; Break; default: trace ("This is not the number I want." The example above is a complete Switch statement block. In the back of the CASE key, it is necessary to meet the conditions, if it is not satisfied, ActionScipt will find if there is a default statement, if there is , Execute the statement. In addition, you may have discovered that there is a BREAK keyword after each statement block, why? The Case project (including defualt block) and the statement is executed. The following is a modified example: MyNumber = 3; // Assignment Give MyNumber // The following is the Switch statement Switch (MyNumber) {Case 1: Trace ( "This is the number I want to get."; Case 2: Trace ("This number is smaller than me."; C ASE 3: TRACE ("This is my number."; default: trace ("This is not the number I want." Running this example, you will find that "this is my number" and "this Not the number I want ". Why? Because there is no BREAK, after running the Case 3: Picture Block, the condition selection statement will continue, and the Default block is used as the default condition, it will always be executed, thus There is such a result. Some common program errors will come. There is also a Continue command for loop in ActionScript, which can jump directly to the conditional detection portion of the cycle (ie immediately perform the next loop immediately. Conditional judgment). This command is not commonly used, so there is no explanation here. Interested readers can check the Flash's ActionScript Dictionary.3.3 loop statement 3.3.1 for For For loop, I think most readers will not be unfamiliar. Below is A block of natural numbers for 1 to 100.var sum = 0; // below is for loop for (var i = 1; i <= 100; i ) {Sum = SUM I;} Trace ("SUM = " SUM);
Obviously, this is very different from the Basic's for statement. It also has some differences with Pascal. The contents of the brackets are divided into three parts: initial values; cycle conditions; loop value change method. It is nothing to say for the initial value. , Casually, the cycle condition continues to circulate under conditions, as long as you know the logical expression; the loop value can be changed by any assignment statement. The following is a modified example: var sum = 0; // below is for circulating for (var i = 2; i <100; i = 2) {SUM = SUM I; // Trace (i);} trace ("Sum =" SUM); in the previous example The initial value I is changed to 2, and the conditions are changed to <100 (ie, the 100) is changed, and the loop value is changed to each addition. After running, look at the results, the result is all the double numbers in the opening section of 1 to 100. If you don't know the work mechanism within the circulation, you can delete the on-the---step (i) in the in -ctudes; the double slash before running the code, running the code in the output window. So if the initial value What will I do? You can change I = 2 to i = 100. You also have a for ... IN loop, which involves the contents of array and objects, will be introduced later. 3.3.3. 2 While & Do ... while tells that for general programming whiles. But you will find its value when you need it. WHILE loops follow the steps below: Check the after whiling Whether the conditions are true. If the conditions are established, the statement within the statement block is run. Otherwise, the loop is ending, running the statement behind the cyclic body. After running the statement in the mean, return to the first step. N = 0; // below while Cycle while (n <5) {n ;} trace ("n =" n); the above example running result is n = 5. When N is less than 5, the condition is established, so it runs N (ie N increase) 1) When n is equal to 5, because the cycle conditions are not established, the loop is stopped, and the back TRACE statement is performed. ------------------------- -------------------------------------------------- ----- While has a structure, that is, do ... while loop. Take a look at the output of this example, you can understand how the Do ... While loop works .n = 0; // below is DO ... while loop DO {n ;} while (n> 5) Trace ("n =" n); you will find that the result is n = 1, even if we give N = 0 does not satisfy the condition of n> 5, the cyclic body also executes (N ). This example shows that the DO ... While loop is a conditional post-test statement, and then executes the code and then detects whether the condition is established. Using this feature, we can meet some special programming. But just these are not enough, we also need some other things to meet the needs of repetition, that is, the function. Chapter 4: Function Chapter 4: Function 4.1 Function Basic The concept has finally finished writing the data type and condition and the circulatory statement section, and now you can talk about the function. The function is the code that can be reused in the program. You can pass the value or object you need to pass to the function by parameters, then by The function gets the result. From another perspective, the purpose of the function is to simplify the burden of programming, reduce the amount of code, and improve efficiency. And a function of a well-written function is like a "black box"
You just know how to call it, don't use the specific function of it. 4.2 Creating your own function 4.2.1 Function Definition (Definition) To create a function, you need to have a definition of function. For ActionScript, There is no return value type, what is good to be discussed, and the following is a definition of a simple function: // Calculate the function of the rectangular area Function AreaOfBox (A, B) {Return A * B; // Here, the result} // Test function area = area = area = area = area}; "Area =" area); now analyze the structure defined by the function. Function Keyword Description This is a function definition, not a period of execution Code. Then thereafter is the name of the function: isaofbox. The number of functions behind the function name is the parameter list (or no parameters, but parentheses must be there). The tight braces are the implementation code of the function, That is, an ActionScript statement. If the function needs to return a value, you can use the return key to add the variable name, expression, or constant name to return. In a function, there are multiple return statements, but whenever, as long as it is executed After any return, the function will terminate itself without going down. If there is no return statement, the end of the final statement is completed after the final statement is executed. Because the specificity of ActionScript, the parameter definition of the function does not require a statement of parameter type. That is, you can not specify the parameter type. This saves a lot of trouble, and there is some problem. Although the penultimate number in the previous example is changed to Area = AreaOfBox ("3", 6); also get 18 results However, this is very unfavorable to the program (if the A B is used in the function, it will become the connection operation of the string, and the results will naturally be wrong). So, sometimes the type inspection in the function is indispensable. In the function body, the number of variables is used to represent the object to be operated. The operation of the parameter in the function is the operation of the parameter passed to the function. A * b in the previous example is transformed when you call the function Treatment for the actual value of the parameters 3 * 6. ---------------------------------------------------------------------------------------------------- ---------------------------------------- Function There is also a creation method called function. Declaration (Function Litral is not declared by a formal function declaration, in an expression through unnamed functions): Areaofbox = function (A, b) {RETURN A * B;}; trace ("Area =" AreaOfBox (2, 3)); this form of declaration is often used in the object's method or the function library function declaration . In the help of Flash MX, the function defines some of the example code about this declaration, please note. --------------------------- -------------------------------------------------- --- The above is a function of the return value, uses the return key in the end of the function. The function may not return any value. Such an example: // Function area without returns Function Areaofbox (A, B) {_root .area = a * b;} // Test function Areaofbox (3, 6); trace ("area =" _ root.area); its result is 18, but the final result is to pass the specified under _root The variable isa. The following example is simpler: / / calculate the function of the rectangular area function Simplefunc () {trace ("Nothing"; // Here, return the result} // Test function Simplefunc ();
The final output is a string in Trace. That is, the function can have no return value, but a collection of operations. The use of functions is highly flexible. ------------------------------ -------------------------------------------------- ---------------------- The same variables, the function can also have global. As long as you give it ahead of the declaration _Global: / / Calculate the global function of the rectangular area _Global.areaofbox = function (a, b) {return a * b; // Return the result} // Test function isa = area} (3, 6); trace ("Area =" area); Please note: The keyword THIS that appears in the function body is the MovieClip that calls the function, rather than the MovieClip where the function is located. This is easy to ignore the result of undesirable results. If you want to specify the representatives of this Objects are used to use function.call () and function.Apply () methods. Talking in the later Arguments object introduction. 4.2.2 Function parameters Check for ensuring the correctness of the function, we must detect users Whether to give enough or correct types. Below is the code after the above example is changed: / / Calculate the global function of the rectangular area _Global.areaofbox = function (a, b) {// output two parameters It is used to understand the following TypeOf statement trace ("A B =" (A B)); // Detecting the parameters enough and the type correct IF (a == undefined || b == undefined || Typeof (A B)! = "Number" {trace ("
The result of the output can be seen this. ----------------------------------------- -------------------------------------- In addition to user-defined functions in ActionScript, There is a predefined built-in function. For different objects, there are different functions (or methods) can be called. The following is a list of system built-in functions with the highest priority: function Description Boolean converts the parameter value to logic Value (also called Boolean) Escape converts the parameters into a string and encoded with URL format (all non-standard characters will be converted to the hexadecimal value beginning with the% end) Eval Returns the object indicated by the parameter, parameters It is constant, expressions, attributes, etc. (this often used when DuplicateMovieClip) GetProperty returns the specified property value GetTimer returned from the animation to start running from the animation to the current milliseconds Getversion returns Flash version and operating system information isfinite returned Whether the parameter is a poor (logical return value) ISNAN returns whether the parameter is a value (logical return value) NUMBER converts the parameters to the value PARSEFLOAT converts the string to floating point numbers, returns NAN if it is not converted Not a number, not a value) PARSEINT converts the string into an integer, returns a nan if it is not converted (often used for numerical enhance transformation, the floating point number transformation will be converted to an integer) String converts the parameters to string TargetPath Return characters The path of the specified object of the string format Unescape Returns more information on the string of the string decoded with the URL format. Please refer to Flash's action Dictionary. To understand how to get information through the most short method. 4.3 call function 4.3.1 Direct call declaration The function is to use it. How to use it like the example in the above example. Enter the function name and the parameters it needs, then assign the return value to a variable. However, the simplest method is too directly call the function. Instead of assigning a value, the call statement of the function will be processed as the same constant as the return value data type. That is to say, the function of the return value can be used as a variable of the returned value data type. For example, TRACE in the previous example ("Area =" AreaOfbox (3, "6"); the result is unchanged. The defined function can repeatedly call in its scope, each call Different parameters can be given. For parametric functions, as long as you enter its function names () to call it. For example, the following example: // Get Flash version information trace (Getversion ()); Calling a system built-in-no-parameter function, it will return the current Flash version. For custom non-return value functions, it is also directly called like this. Sometimes, even if there is no enough parameters, the functionality can still be used For example: // check if the parameter is a value trace (isnan ()); in the previous example, we do not give functions, but the function can still handle and return true (because there is no parameter is equal to a NULL type Constant, because NULL is not a numeric type, so the last return value is true). For the areaofbox function in the previous example, you can try less a parameter to see what the result is. 4.3.2 via Call And Apply Method Call in Flash ActionScript function (function) actually built-in object. So we can call it in its Call and Apply method: // Function Areaofbox (a, b) {this.Value = a * b; // Assign the result to the value of the object represented by this value} // creates a new object object_1 = new object (); object_1.value = 0; / / to add the value attribute for the object and give the initial value 0Object_2 = Object_1;
// Copy an Object_2 by Object_1, at which point the Value property of both is 0 // test functions AreaOfBox.call (Object_1, 3, 6); Trace ("Object_1.Value = Object_1.Value); array_ab = [4, 5]; // Create a parameter array areaaofbox.Apply (Object_2, array_ab); trace ("Object_2.value =" Object_2.value); Why call functions through CALL and Apply? This is not more direct than the previous Trouble? Indeed, this is more troublesome, but you noticed that the first parameter I used? You can specify what objects represent in the function body in the function body, which is use call and apply Benefits (About the objects and this content will be mentioned in the following chapters, here is not mentioned here). This advantage is only in the actual programming. You can experience it. Here is just a brief introduction, let you have a basic concept. If the THIS keyword is not used in the function, the first parameter is replaced with null. In this example, the first return value is placed in the value attribute of Object_1, and the other will be placed in the value attribute of Object_2. Pass The first parameter of Call and Apply We let the ThIs in the function represent two objects of Object_1 and Object_2. The actual parameter behind the first parameter is determined in accordance with the number and type of the parameters to call the function. As for Call The difference from Apply has been understood: APPLY's actual parameter is passed through an array. 4.4 arguments object Arguments object, as the name refer to parameter object, which contains the parameters of the function call. As an array object, it Only three properties: Property Description Arguments.callee is being called to the function arguments.caller is performing this calling function arguments.length passed to the number of parameters of the called function to help you understand more clearly Callee and Caller's relationship: // A function of square and function function sum1 (x) {// We use X> 0 as the condition IF (x> 0) {// through Callee (because you are The called function) / / will The parameter minus 1 (otherwise it will be cycled) Return X * x arguments.callee (x-1);} else {return 0;}} // Another function of cubic and function function sum2 (=) {IF X> 0) {// We directly call the square function Return SQR (x);} else {return 0;}} // seek square function (interact with SUM2) Function SQR (x) {IF (x> 0 ) {// seek square, then call the SUM2 function in turn by Caller (that is, the function of the square function) returnix x * x arguments.caller (x-1);}} // Compare two effects Trace ("Correct parameters -------------"; Trace ("SUM (3) =" SUM1 (3) ":" Sum2 (3)); trace SUM (4.7) = " SUM1 (4.7) ": " Sum2 (4.7)); Trace (" SUM (100) = " Sum1 (100) ": " Sum2 (100)); Trace (" Error Parameters --------------- ";" SUM (-1) = " Sum1 (-1) ": Sum2 (-1)); Trace "SUM (0) =
" SUM1 (0) ": " Sum2 (0)); the drawing of Callee and Caller can be explicitly explicitly explicitly explicitly expressed in the drawing of the call. One is the reference to the reference. Call the function of the function. Callee is often used in the recursive of the function (ie cycle call itself). Call itself by callee can avoid the function name of the change in the modified function, but forget the change in the function name in the body. Caller Commonly used in multiple functions, it can also be used to determine who the caller is (this can define whether the caller range and other functions can call this function). As for arguments.length, there is nothing, it is to return the current call office. The number of parameters passed. 4.5 Other features of the function 4.5.1 The parameters used in the function are partial variables, which will be removed from memory after the function call is completed. You can also use var in the function. Declare other local variables. If you use a global or other variables in a function, you must pay attention to whether or not the local variables in the function, and it is preferred to indicate that they are not the local variables of the function and their sources. Function test (a) {var b = "word"; // Defines local variables BC = "text here"; // Defines variables CTRACE ("---- From internal access variable ----"; trace ("a = " a); // Display parameter atrace (" b = " b); // Display local variable BTRACE (" c = " c); // Display Variable C} // Call Function Test (" Symbol " Trace ("---- From External Access Variable ----"; Trace ("a =" a); trace ("b =" b); trace ("c =" c); As a result, it can be seen that the parameters A and local variables B are only accessible within the function body, and the variable c defined inside the function can be accessed outside the function body. 4.5.2 Scope of the scope function is where it defines its code. Object or timeline range. Global function is actually equivalent to a sub-function based on the _Global global object. If you want to call other locations (ie, the function within the same object layer), the path (PATH) must be used. Such as in a sub-MovieClip To call the function in _root, you must use the following format: _root.myfunction (); C2.MYFunction (); It is more clear that you define a function in an object or hierarchy, it is equal to adding a sub-function (or method) or hierarchy. To call this function, you must specify the objects it belong to or hierarchy. This also enables the use of the same function name to create functions in different objects (variables and objects). About the contents of the path Refer to the following chapters. 4.5.3 Function Reduce in ActionScript, when you redefine a function, this function will be rewritten as a new version, the old function is overwritten. When you call it again, It is a new function. As for function overload (C characteristics) This thing is not in ActionScript, so it doesn't have to spend it. The content of the function is briefly introduced here. In the next chapter we will discuss A very useful array in practical applications. Chapter 5: Array Chapter 5: Array 5.1 What is an array? Finally, the data type, condition cycle statement, and function section, can now talk about the array. So, what is an array? I don't understand how to define it. So from C
The textbook has been copied: the array consists of many identical types of data items and index variables. The array is not a basic data type, which is a collection type consisting of data types. Forget, so many words, people will be around Or is it probably: Array is a collection of many objects, the type of object can be numeric, string, other objects, and more. You can access the specified element by serial number (called index, index) for each element. It The function is the same as the variable, and it is also a place to store data. It is just a "concentration camp". The array inactions in theActionscript is actually the type of object built in the system. The reason why it is necessary to speak it in advance, because Its use is very wide (also because it is placed in the foundation part in C textbook). For example, you can use it to store a list or a series of coordinates. 5.2 Creating an array to now I have not let everyone Look at the length of the number, is it worth spending so much time, then let us look at its true face: Team_member = new array (); team_member [0] = "sic"; team_member [1] = " REDO "; Team_member [2] =" crab_d "; trace (team_member); // Displays the array content is the definition statement of array Team_member, which defines an array containing 3 strings (ie, the array length is 3). Give In its assignment statement, in square brackets behind Team_member are the index of each element (index is started by 0). In fact, create an example of an Array object through the new keyword, which we will in the chapter of the subject It is mentioned here, please remember it. Like C and Java, the array index in ActionScript is started by 0. You should pay special attention to the programming, because this is also one of the common mistakes of beginners. If you feel above The statement is too cumbersome, then the above example can be changed to the following form: Team_member = New Array ("SiC", "REDO", "CRAB_D"; trace (team_member); // Displays the contents of the array. The same is the same, It's just a little simpler. If you want more simple, use the following method: Team_member = ["SiC", "REDO", "CRAB_D"]; trace (team_member); // Display array content attention, here the code It is square bracket. When using array in the future, different methods can be selected according to the specific situation, but the most used is still this As for the designated length of the empty array of specified lengths with the New Array (Array Length) because the practical value is not high (although it may be used when reading external data), and it is also easy to understand, so it will not be discussed, the method is the same.----------------------------------------------- -------------------------------- sometimes we want to include multiple elements in an element (ie, elements is An array), this time you use a multi-dimensional number. For multidimensional arrays, the simplest creation method is to use square brackets: // Don't forget what the following Var represents anything, if you really want to see data types That chapter Var Team_member = [["SiC", "No Warehouse", 1011], ["REDO", "Game Killer", 2172], ["CRAB_D", "Help", 1012]; TRACE (Team_member. Join ("/ n"); // Displays the contents of the array content (ie, the sub-array) is separated by / N (newline) when the trace output is separated. Also in the number of elements in each sub-array may be different, This is not exemplified here. 5.3 Access Array Actually access arrays is simple, the first example of the assignment statement has shown this. To modify the value of an element in an array, you only need to use an array name [index number] = New value;
Format assignment. If you want to reference a certain element like a variable, you only need to use the array name [index number] to indicate that the element will be done. For multi-dimensional array, the format is a group name [Index number 1] [Index 2] [index No. 3] ... (how many square brackets look at the array element you have to visit). The following is a simple example: var team_member = [["SiC", "no business", 1011 ], ["Redo", "Game Killer", 2172], ["CRAB_D", "Help", 1012]; Team_member [1] = ["Undo", "Game Intisang", 2171]; // Modify 2 elements (sub-array) Team_member [2] [1] = "care"; // Modify "Help" TRACE (Team_member.join ("/ n"); // Display array content ---- -------------------------------------------------- -------------------------- Has a little convenient for ordinary users is: ActionScript array object is dynamic, no C language static array and Dynamic array (after all, it will not be complex to let users allocate memory). That is, you can easily add or remove array elements: Team_member = new array ("SiC", "Redo", "CRAB_D "// There is only 3 elements of the team_member [3] =" you "; // Add the fourth element, pay attention to the index of 4-1 = 3trace (team_member); // Display the number of array contents Added 4 elements "you" (note is not the third, the index number starts from 0). From TRACE results, you can see this. ----------------- -------------------------------------------------- ------------- For multidimensional arrays, you can only add new elements through parent elements (note that newly added elements can have different number children): var team_member = [["SIC", "No Warehouse", 1011], ["Redo", "Game Killer", 2172], ["CRAB_D", "Help", 1012]]; Team_member [3] = ["You", "unknown" ]; // Add new element Team_member [0] [3] = ["yeah!"]; // Add a new sub-array to existing elements (child number) Team_member [0] [3] [1] = " HMM? "; // Add a new element to the new sub-array trace (Team_member.join (" / n "); the above example cannot use Trace to show" YEAH! "And" HMM? "Composed. Arranges (they are displayed immediately with the parent group, and also separated by commas). You can be in Debug Movie (debug movies, Ctrl Shift
Enter View the contents of the Team_member array in the _level0 in the _LEVEL0. Note that the animation is paused after entering the debug mode, and the array has not been defined. When you press F8 to view its content. Here is a point to the Debugger panel: ----------------------------------------- ---------------------------------------- ActionScript array has a very special advantage: You can use a field name. This array is more like a two-dimensional data table (but actually this is an array of objects. Note that the braces are used when defining each child element rather than brackets). Var Team_member = new array () Team_member [0] = {Name: "SiC", Job: "Adminder Tourists", SN: 1011}; Team_member [1] = {Name: "Redo", Job: "Game Killer", SN: 2172}; team_member [2] = {Name: "CRAB_D", Job: "Help", SN: 1012}; trace (Team_member [1] .name); // Displays the TRACE statement behind the Name field in the second element Shows the second The content of the Name field of an element. But actually this is the second element of the array through the Team_member [1], and then references the value of its attribute Name through the point syntax. You can view this array via Debugger Content. About the specific content of the object will be explained in later chapters. 5.4 Array Object (Array) In the previous section, the array is also a system built-in object, then we want to discuss what special nature of the array as an object. As a Objects, naturally there will be some properties and methods available. Below is their list: Property Description Array.Length Returns Array Length Method Description Array.concat Connection Specifies the array and parameters of each array into new Array and return. Array.join connects all elements in the array into a string. Array.pop removes the last element of the array and returns its value. Array.push adds an element at the end of the array and returns a new array length. Array.Reverse reversal Group elements. (Quite convenient, especially when writing certain effects) Array.shift removes the first element of the array and returns its value. Array.SLICE returns the specified portion of the array with a new array. (No Affected the original array) Array.Sort alignment. (Except for the necessary sorting function) Array.Sorton Sort by the field name to the array. Array.Splice Add and / or remove array elements. Array.tostring Return to comma "," Separated array element list string. Array.unshift adds one or more elements to the beginning of the array and returns a new array length. This is the most commonly used length. When writing a loop, sometimes we cannot determine to handle The number of elements of arrays, at this time, you can get its number through the Length attribute. As for other methods, you can check the details of the help and refer to check the details of the information in the view. / / Show_Member ( Comment) {if (my_team! = undefined) {// Verify that the array has trace (my_team.join ("," add "<<" add comment); // After the array content, I added a note, which is convenient for output Time Identification} else {trace ("array is not defined!";}}}} {IF (THE_ARRAY! = Undefined &&)
The_Array.Length> 2) {// Confirm the array exists and length is greater than 2for (i = 0; I the_Array [i] = i add ":" Add the_Array [i]; // The operator here does not understand, look back See Chapter Chapter 1}} else {trace ("Array does not exist or only one element!";}} // test function work is normal show_member (); add_number (my_team); // Create an array my_team = new array (); MY_TEAM = ["SIC", "REDO", "CRAB_D"]; show_member ("has 3 elements"; // calls the splice method for array objects, delete Redo, add UNDO and Eden // First parameter to delete The first element of index, the second parameter is the number of elements to delete the number of (1) of the number of (1, 1, "undo", "eden" to be added to the deleted position. ("Call SPLICE Method Modified Array" // Call Function Processing Array Add_Number (My_TEAM); SHOW_MEMBER ("Add a number of serial numbers"; // Reverse array my_team.reverse (); show_member ("Reverse Array "; // Remove the first and last element MY_TEAM.SHIFT (); my_team.pop (); show_team.pop (); show_member (" Array to remove the head tail element "; // Add element MY_TEAM.UNSHIFT (" 6: Doggie "," 7: Zero "; show_member (" Add an element at the beginning "; // Add an element MY_TEAM.PUSH at the end (" 7: WHO? "," 0: ghost "; show_member (" Add an element at the end "; / / Sort by ascending order, you can order only one Reverse method, you can call MY_TEAM.SORT (); show_member ("Sort by Range); the above example is longer than our previous example. First look at the front We declare the two functions. The first function mainly outputs the contents of the array through the Trace. I use a join method to connect the array element to the specified character. Return in the string. In order to ensure that the group is not passed to the function The parameter name is incorrect or the definition failed, and I used a conditional statement before output to determine whether the parameter is undefined (not defined, recalling before The content mentioned in the data type introduction). The second function is primarily used to demonstrate the use of the Length attribute. The FOR cycle determines whether to reach the array by using the LENGTH attribute. Since Length will change from the difference, The FOR cycle can handle array of arbitrary lengths, but do not have to worry about the subscript crossed problem (that is, use an excessive or too small index value when the array element is called. The following is the statement that the test function is working properly. I Deliberately call these two functions when the array has not been defined, the result returns the error message we preset in the function (if the function does not determine if the parameter is defined, flash will return the error message). Then it is test Subject part. These parties need to explain, they will take note of the comments. About the splice method used in which Flash's ActionScript Dictionary or the References panel. In the future, I find unfamiliar things in someone else's code. Flash itself with help files. Then, the contents of the array are simply introduced here. The base section of ActionScript is over, followed by object-oriented programming content. ************ *************************** Requests of BeGingRadientfill's Matrix for the usage of MovieClip.begingRadientfill.
Here is the explanation of Chinese version of Help: MovieClip.BegingRadientFill Availability Flash Player 6. Usage MyMovieClip.BegingRadientFill (FillType, Colors, Alphas, Ratios, Matrix) Parameters FillType string "linear" or string "radial". Colors an array including RGB hexadecimal color values to be used in gradation (for example, red is 0xff0000, blue is 0x0000FF, etc.). A array of alphas, including Alpha values corresponding to color in colors arrays; valid values are 0 to 100. If the value is less than 0, Flash uses 0. If the value is greater than 100, Flash uses 100. An array of Ratios color quotas; effective values are 0 to 255. This value defines a percentage of the width of the color sample at the color by 100%. Matrix a variant matrix, an object with one of the following two groups: A, B, C, D, E, F, G, H, I, which are used to describe the following form 3 x 3 matrix: AB CD e fg Hi The following example uses the BeGingRadientFill method, which is an object with these properties. _Root.createemptyMovieClip ("grad", 1); with (_root.grad) {colors = [0xff0000, 0x0000FF]; alphas = [100, 100]; ratios = [0, 0xff]; matrix = {a: 200, b : 0, C: 0, D: 0, E: 200, F: 0, G: 200, H: 200, I: 1}; BeGingradientfill ("Linear", Colors, Alphas, Ratios, Matrix; Moveto (100,100 ); lineto (100, 300); LineTo (300, 300); LINETO (300, 100); lineto (100, 100); endfill ();} If the MatrixType property does not exist, the remaining parameters are required; if any of these functions will be lacking failure. This matrix scales, translation, rotation, and inclination are graded in units defined at (-1, -1) and (1, 1). MatrixType, X, Y, W, H, R. These attributes indicate the following enrollment: MatrixType is a string "Box", X is the horizontal position of the registration point of the parent clip of the gradient left upper corner, Y is the vertical position of the registration point of the parent clip of the gradient left upper corner, W is the width of the gradient, H is the height of the gradient, and R is the angle of rotation of the gradient (in an arc). The following example uses a BeGingRadientFill method, which is an object with these properties.