This section is selected from the first step in "Flash MX Professional 2004 (Chen Bing)
Chapter 18 Understanding Programming Work in Flash
Mom, this big door is so good, where is it? Baby, it leads to the world, which is a world full of magic, enters there, you will become a great magician.
After learning the study of the previous seventeenth chapter, we finally came to the door of the programming world, the door opened, obviously, it has been waiting for us.
18.1 Thinking about software designers
I believe that there are many people in you only have little or completely without programming, otherwise, you will not choose this "first step" I wrote. We already know that use ActionScript in Flash to write scripts and have no difference in programming with other languages. To finally exercise into an excellent software designer, the first thing you have to do is to always remind yourself to think about a problem like a software designer.
18.1.1 Don't always think about escape programming
For programming in Flash, we must think about the problem like software designers. The most important thing is to always think about an evading program to achieve your thoughts, many people always try to try to use non-programmed means. To complete all the problems he faced, for this, he can spend a lot of time at a very amount of time, he will think of the unclear bypassing the programming, if these methods can be called algorithm, absolute Will surprise Many software designers.
In fact, in many cases, using programming methods can save a lot of time by non-programming methods, and will have a more real effect. A typical example is to express a variety of random motion, for example, a lot of snowflakes falling, and the fish is booming.
18.1.2 Serious writing design instructions
To think about the problem like software designers, you have to work hard to describe the idea you want to implement using logical clear languages. This process is a very important process of writing design instructions in software development.
It sounds a little arrogant, but after you have completed a detailed design manual, 95% of your work has been completed. Whenever someone asks me if I can implement it, I always answer, as long as he can describe it in detail, I can compose it. For development in Flash, all of the design manual is a detailed and rigorous description of how Flash movies will perform and perform. A good manual will spend a lot of time and work, but this is worth it. When it is completed, it will assume the responsibility of the work blueprint.
One person's information about what extent is to which the degree of idea may be different from the other, but the more detail. When you put an additional energy in the early stage of your work, it will not only save you at this road, it will also reduce the opportunity to rework.
One problem with the presence of an extremely detailed manual is that you are hard to fully describe the final procedure, because a written manual is huge to the final Flash movie. Simple, just describe the color in a drawing or a sound that describes a song without some music devices, there is an explanation error. But this does not mean that you should abandon the entire process of writing instructions. Instead, you only need to write it enough to make you grasp it depending on it. In addition, you must know that the work you have done will generate a leverage for future work. Lost, things that are thousands of miles is often caused by unrescribed design specification.
18.1.3 To think of other possibilities
Sometimes, an implementation seems to have a clear logic, which seems to be obvious to write the program in accordance with the algorithms and logic you designed, but when the development progresses to a step, you seem to have encountered a wall, can't further further Many beginner programming people will put a lot of time here, constantly check the logic and program code of the algorithm of the design, and finally fall into the quagmire. However, an experienced software designer will soon realize that it may have a fundamental mistake in the initial judgment. Many times, behind the complex things are simple logic, while the back of the simple things is hidden with complex logic. Thoroughly abandon your original algorithm, change a thinking, try to guess another possibility, you will find that the wall begins to disappear.
People are always looking to solve things with a simple way, the same, this is the right idea, but sometimes, when a simple method does not pass, you have to realize that this matter may use complex methods. Can be realized. Don't always think about it, you always think that there are other possibilities.
18.2 Important concepts in object-oriented software development
In the fourth chapter, I have already introduced what is an object-oriented software development. You should still remember the example of "people" as an object, and when the road is evil dog, the evil dog is happened. He can call "Running" method to act as a response to this event. But no matter what, I don't want to make you tapping the object-oriented software development. In fact, object-oriented meaning is far-reaching, involving many important concepts, only fully understands the meaning of these concepts, you really understand what is object-oriented. Many concepts you should know, but limited to space, I will explain the most important nine in this section. Object-oriented software development nine most basic concepts: class, objects, attributes, methods, abstractions, packages, inheritance, polymorphism, and events.
18.2.1 Classs and objects
Class is the software of the object, which is a template for creating an object. For example, if a person is seen as an object, the species can be seen as a class. Class definitions describe structures including data and functions, and objects are created by them. A class represents a set of similar objects. Object is an example of a class.
Why do you need a class, imagine a situation, if we want to write a flash game, there are some small people who can act independent, these villains have the same physical characteristics and activity capabilities, then, if we want for each small If a person writes a program, the workload is undoubtedly huge and repeated. In this case, we should create a "small person" class, which will generate a small person from the "small" class whenever a new small person is needed.
It is said that you must think of the relationship between components and instances. That's right, the relationship between classes, and objects is the same as the relationship between components and instances, because the components are actually the built-in class of Flash.
18.2.2 Properties and Methods
The attribute is data, and the method is a function. Attribute is something you know, and the method is the class complete. The properties and methods are the responsibilities of the class. Object-oriented software development is based on this concept: the system should be created by an object, the object has data and functions. The property defines the data, and the method is defined.
Obviously, in an object-oriented development, the most important job is to define the class. When you define a class, you must define its properties and methods. The definition of attributes should be directly clear and need to define its name and data type. The definition of the method is the process of creating a function. As needed, you can create a method of accepting parameters and returning values.
18.2.3 Abstract
The world is very complicated, in order to deal with its complexity, in software design, when we need to establish mathematical models on things, we need to generalize or abstract things. Or people as an object, from the perspective of recruitment, we need to know the name, gender, age, educational background, work experience, contact information, and personality characteristics; and from the perspective of blind date, you need to know this person. Age, height, appearance, educational background, family background, and even eight characters. Still the same person, just a different abstraction of him (or her), what abstract to a matter will depend on the procedure you want to design. Abstraction is a process of analyzing, which is the process of drawing a clear frame around a thing. Abstract should contain features, attributes, methods that are interested in applications, and ignore other factors. That's why recruiting abstraction contains educational background and work experience, but will not contain the reason for the birth. The abstract process is to define the process of knowing and going to finish.
18.2.4 Package
Although abstraction tells us that for recruitment, we should store the candidate's educational background and work experience, but it did not tell us how to complete these things. The encapsulation solves how to model the system function. In the object-oriented world, we have to model the system into classes, and the classes must also be modeled as attributes and methods. The process of designing how to accomplish these things is called package.
The package describes how to divide the function in the system. We don't need to know how the object is implemented. The package suggests that we can build a system in any way. If necessary, it can also modify its internal structure again in the future, as long as the interface between the different function components in the system does not change, the change in the system is not changed. Other features of the system will have an impact.
The package is a process of applying the frame around the thing. You can define anything you want to define, but you don't need to inform the outside world. For example, when you go to the bank to access cash, you don't need to know how the bank's data center uses mainframes, small machines, and PCs to record your account information, how do they use the database and operating systems, It is also important because they have already encapsulated the functionality of the account service. You only need to go to the counter, you can pay the bank's staff. By hiding the details of the implementation of the account function, banks can freely change the functionality at any time without having to replace the passbook of each user.
In order to make the application easy to maintain and increase security and robustness, access to the properties and methods of the class is required. Basic ideas are as follows: If a class wants to get information about another class, you must first conscription, instead of it directly. Considering that in the real world is actually working in this way. If you want to know the name of other people, what should you do? Is it directly asked about his name, or stealing his wallet to see his ID card?
18.2.5 inheritance
There is often similarity between different classes. Two or more classes also share the same properties and / or the same approach. Because we don't want to repeat the code, we will use this similar mechanism. Inheritance is this mechanism, which makes you easy to reuse existing data and code.
For example, students have name, address, mobile phone, can also run quickly. At the same time, teachers have these things. There is no doubt that we can develop classes about students and teachers to run them together. In fact, just develop a Student class first, once it runs, make a copy, just call the Teacher class, and make some appropriate modifications. This is easy, but it is not perfect. What happens if the source code in the Student class occurs? You will have to correct mistakes in two places. This will be a borus work. If only one code copy is used for development and maintenance, isn't this better?
This is the idea of inheritance. With inheritance, you can define a class to encapsulate the similarity between students and teachers. The new class will have attribute Name, Address, MobileTelephone, and method Run. We can name this class as Person.
Once the Person class is defined, the Student and Teacher class can be inherited from it. We call Person's superclass for Student and Teacher classes, while Student and Teacher classes are subclasses of the Person class. Any super class knows and completed things, the subclass knows. Therefore, since the Person class is able to race when you encounter a disgusted dog, Student and Teacher class can also.
18.2.6 polymorphism
Let us consider this example. You love your girlfriend, you say "Dear, I Love You", your girlfriend hugs you, you have got a kiss, you think this is very good. Then, you came to the street. I saw a very temperament beauty. You also said that "Dear, I love you" with my girlfriend, you will immediately get your nerves and morality. Some suggestions for aspects. Subsequently, you came to the hospital, say "Dear, I love you" for an old Chinese medicine, and the old Chinese medicine will not hesitate to pull your wrist, starting to put the pulse for you. You think, wait until when I encounter these objects and say "Dear, I love you", this situation will definitely happen - this is a polymorphism.
Polymorphism allows objects to collaborate with other objects when you don't know the type of other objects in advance. From this experience you can learn a few interesting experience:
First, polymorphism hinders your interaction with other objects. You don't distinguish the type of other objects, you treat them in the same way. Your idea is that other objects are people. Polymorphism is a concept that allows this situation.
Second, different objects do different responses in their own way. Your girlfriend hugs you and give you a kiss; strange beauty gives you advice on nerves and morality; and old Chinese medicine gives you the pulse. The same message reaches different objects, each of which is different. In fact, from the perspective of each object, they do what they should do.
Third, the polymorphism can achieve a consistent and appropriate method name. Although each object responds to "Dear, I Love You" in an appropriate manner, but it is still necessary to implement the different versions of the method.
The polymorphism mainly includes two aspects: the operator's overload: the same operator can act on a variety of object types. Function name overload: The same function name can act on different object types and produce different effects.
18.2.7 Event
The operation of object-oriented software is performed as an event, which is called "event driver". For example, when you appreciate the flash animation, it is actually a "enter frame" event, in which these events, the Flash Player will deliver the content in each frame, so you can see the picture.
Similarly, when you click on the button, a button event occurs, the script in the button event is executed, the role of these scripts may be to bring you to a specific scenario, a specific frame, or link to a certain URL.
In object-oriented programming, the entire software is driven by events, which means that if there is no incident, your program will be difficult, but it always has some things in the program, even if all others There will be no events, and there will be time to happen at all times.
In the actual development in this book, you will see the actual use of all of these object-oriented concepts.
18.3 Good programming style
Although you will develop advanced object-oriented software, some good programming styles that have been summarized in the process of processes will be out of time (at least in a foreseeable future). This section will teach you the rules of these four seas, these rules are not mandatory, but it is not doubt that you will make your life easily. A good style means programming in an easy-to-maintain manner. Your code should be easy to make anyone understand it. This is not that other people need to see these code you have written (of course, this situation may happen), but said that when you need to debug or modify the error, you can quickly understand that you have developed. what. People always lose their self-control attempt to build certain things and ignore useful finishing work. The action of grass rate will cause infinite troubles, so you should always try our best to follow good programming styles. Of course, "good" can't get easy, "good" usually means a lot of work. Here, good means: good name, reduce repetition, always comment, and separation of code and data. 18.3.1 Good name
What is a good name? The concept of good names in the world is very different from the concept of good name in our daily life. In our daily life, a good name tends to mean very much to scrutinize: or express your parents' good desire, or the dictionary explanation. But a good name in a daily life is very bad in the program, one such name cannot provide additional information other than the name.
In the programming world, it is determined whether a good name is able to provide more information with a minimum character. In Flash, we can also name the thing is very much, each button or movie clip instance, each text instance, you can need naming; each variable, each function, every class, name. In Flash, when you name a thing, you should try to let this name reflect all of this important information. For example: Fishcountermc acts as a movie clip in a statistical fish tank is very nice. After many days, when you see this name again, you can get a lot of important information in an instant. First, one eye-catching, we can know that this name refers to a movie clip (MC represents movieclip), so this name is the name of a movie editing instance, secondly, we can see that this is a movie used to count Clip (according to Counter), in the end, we can inference this counter should be a statistical fish (according to FISH). When naming for a variable, it will be useful to reflect the data type of this variable in the variable name. Childage_num as a name of a variable used to save your child's age, it is good, from Num this suffix we can realize that this variable should be saved is a digital data type.
Sometimes, in order to give things a more meaningful name, pass more information, you will find that the name is getting more and longer, this is not a good thing, too long name will also cause reading difficulties. Because too much of the names, you will make you can't see the logic of the program, so treat anything, you should keep an appropriate attitude, many times, you need to pass more information and prevent too long names Compromise between them.
18.3.2 Reduce repetition
To make things simple, every programming work should only appear once in your movie. If your same code appears two, then your update and modify the work will double. You will learn some ways to achieve this, for example, save the script in the library, saved in a function or introducing a movie from the outside. At any time, when you plan to copy and paste the code, a little voice should sound in your mind - "Stop!". There will always be a more concise approach waiting for you. Reduced repetition also means refining code, try to complete the same job with fewer code. I don't think about it, when you look back for your program for debug bug, every line of code you check must be translated in your mind, and less, you will feel better. Usually, you can do some things at all steps or less code. Compare two code segments in code 1 and code 2, they achieve the same effect, but the code in code 2 is more refined.
Code 1: On (Release) {SetProperty ("Highlight", _x, getproperty ("Highlight", _x) 10; TellTarget ("Highlight") {gotoistStop (getProperty (", _ currentframe) 1);}}
Code 2: On (Release) {highlight._x = 10; highlight.nextframe ();}
Those scripts in the code one are the same effect as the script in code 2, but there is no necessary complexity. This except that there is no more significance in addition to the worship of players who have a lot of choice, there is no more meaning.
It is true that there is no way to legally the best way, but there is no doubt that reducing duplicate and refining code is beneficial. Of course, you don't have to repeat the reduction, refining code is too completely thorough. The requirements for streamlined code should not be more important than readability. It is very easy to completely lose self-control and ultimately ending on a pile of code that you can't read. I will never pick up in a completed code segment that work - because, it is true that this is the best consideration. Second, your code is usually maintained by you, so the code you can read and understand is the most important. Do everything possible to use the code you understand. If this sometimes means your code, it can only be went by it. As time goes by, you will slowly see your code is gradually shortement.
Sometimes, when I examine those programs that are just a few months ago, I will also question the methods I have used - but this is just because I am always progressing. If you plan to wait until your technology is perfect, you will wait too long. So in this way, the time will prove that you can progress.
18.3.3 Always comment
In Flash, the comment is the text starting with / /. Note is ignored in Flash. Note is not the characteristics of Flash, open any computer book involved in programming, and you will find discussions in the importance of comments. Indeed, the comment is very important, how to emphasize it will not be. Comments can make you only know how per-segment of the code after several months or even years, and you can continue to develop and maintain the procedures; if you need, let others understand your code, he (she) will Look at your kindness, feel your heart, vowed to be a good boy like you (or a girl).
I think I am a bad boy, because I often don't know full annotations to my code until I let it run. But no matter what, did not continue to delay this, it is very important to me, because after I wrote it, I will do it about everything about this code. Without a comment, the understanding of the code will become more difficult. So, spend some time to comment your code, even if you have completed your code, the enthusiasm has declined. Compare the code that is not annotated in the code three in the code and the same number of code four but notes. Although you may not understand the details of these codes, if there is a problem here, you will be able to easily identify the part of the problem. Code 3: OnClipevent (Keyup) {if (Key.getascii () == 13 | Key.GetASCII () == 0) {Return;} IF (key.getascii () == 8) {g (cur.charat) Cur.length-2) == "" "{_Root.WordThistime -;} cur = cur.slice (0, cur.length-2) Mbchr (8); if (_Root.Wrongplace [_Root.Place-1 ] == "x") {_root.wrongplace.pop (); _root.wrongs ---;} _root.place> 0 && _Root.Place--; return;}}
Code 4: OnClipEvent (Keyup) {// ignore these character IF (key.getascii () == 13 | key.getaScii () == 0) {return;} // If they click Return button IF (Key.getaScii () == 8) {// Delete a space? IF (cur.lend (cur.length-2) == "" "{ot.wordthistime -;} // Delete the last character cur = cur.slice (0, cur.length-2) MBCHR (8) ; // Do they have modified a mistake? IF (_root.wrongplace [_root.wrace-1] == "x") {_root.wrongplace.pop (); _root.wrongs--;} // retreat _Root.Place> 0 && _root.Place- -; // Leave return;}}
The code three is difficult to understand before being annotated. The code four shows that there are not many annotations that make things clear, even if you still don't understand the potential meaning of these codes.
18.3.4 Separation Code and Data
All programming designers should strive to keep code (simple to program scripts) and data (or specific projects, such as text and graphics). Separation. By maintaining the separation of code and data, you can make your programming results into other projects. Similarly, when you want to change the content -, for example, do the entire project with different languages - you only need to replace the data without having to touch (or destroy) those code. This is great idea but sometimes it is difficult to achieve.
Assuming that there are some graphics buttons in your Flash site, these graphics buttons will display a floating tool tips when the user places his mouse pointer to the button. If you hold the code (make the script that appear in the tool prompt) and data (the text that will appear in the tooltip in the tool prompt). You can easily transplant this feature to another language, and you do just use another language to replace tooltips. Ideally, you save all the texts of all the tools in the same location, which will make the transplantation work more easily. The main purpose of this ideology is that you should try to make a major change in any of the code or data will have another impact on another. You can treat code data as a modular form. There are other modular forms - including Flash LoadMovie (), which enables you to play separate .swf files in a larger movie. In addition to the coded data separation mentioned, there are many other advantages. First, by modular your Flash movie, users don't need to wait for the download of the entire movie. They can download those who are interested in those. In addition, modularization also enables a work that can be cleaned into several independent parts, making these portions can be developed simultaneously. Thinking such a situation, if your entire movie is constructed only by one basic file, you can only work at the same time. Therefore, it can be seen that there are many advantages in code data separation and some modular forms, and you should try to keep the problem as modular thinking. 18.4 ActionScript terminology
We already know the terms of ActionScript, such as class, objects, attributes, methods, events, scripts, and more. The terminology commonly used in some ActionScript will be introduced in this section so that I will not feel unfamiliar.
Identifier - is a string that conforms to a specific rule requirement. Specifically, the first character of this string must be letters, underscore (_) or dollar symbols ($), and the following characters must be letters, numbers, underscores or dollar symbols. The names of all those who need to be named in the program should be an identifier of the name (for example: variable or instance).
Example - means an object. The instance of the class is the object. Many people are always unclear, objects, and examples of the relationship. Remember, the object is generated from the class it belongs. For example, when we create a student object, we said that it is instantified from the Student class.
Function - is a reusable code segment. A function completes a specific task. You can deliver parameters to the function, or return the value from the function.
Parameters - is a placeholder for the value transfer value. In the following area function, X and Y are two parameters of the function.
Function Area (X, Y) {Return X * Y;}
When you call the Area function like this, pass the two values to this function through its parameter, which is calculated in a function and returns its operation results to the call location. RectangleArea = Area (2, 3); There are still many terms in ActionScript, I will explain again when I have involved them.