Programming
This article is excerpted from the first step of Flash MX Professional 2004 (Chen Bing)
The 18th chapter understands the programming work in the Flash
Mom, this door is so majestic and glorious, where does it lead?
Baby, it leads to the world of programming, a world full of magic, into which you become a great magician.
After a full 17 chapters of study, we finally came to the door of the programming world, the door is open, obviously, it has been waiting for our arrival.
18.1 Thinking about things like software designers
I believe many of you have little or no programming basis, otherwise you will not choose the first step I wrote. We already know that scripting in Flash using ActionScript is no different than programming in other languages. And the first thing you need to do to become a great software designer is to always remind yourself to think like a software designer.
18.1.1 don't always want to avoid programming.
For programming in Flash, to be able to think like a software designer, the most important thing is not always trying to avoid programming to achieve your ideas, many people always try to use the non-programming means to complete all the problems he faces, for this, he can at any cost, can spend a lot of time , he would come up with countless workarounds for bypassing programming, which would have surprised many software designers if they could also be called algorithms.
In fact, in many cases, programming methods can save a lot of time in a programming way and produce more realistic results. A typical example is the performance of random motions, such as the falling of a large number of snowflakes and the swimming of fish.
18.1.2 carefully write the design instructions
To think like a software designer, try to describe the idea you want to achieve in a logically clear language. This process is very important in software development process of writing design instructions.
It sounds arrogant, but after you have completed a detailed design specification, 95% of your work is done. Whenever someone asks me if an idea can come true, I always answer that if he can describe it in detail, I can make it up. For Flash development, a design specification is a detailed and rigorous description of how flash movies will be executed and performed. A good manual will take a lot of time and work, but it's worth it. When it is finished, it will assume responsibility for the blueprint of the work.
The idea that a person's information should be detailed to what extent may be different from another person, but the more detailed the better. When you put extra energy into your work, it will not only save you time along the way, it will also reduce the chance of rework.
One of the problems with writing a very detailed specification is that it is difficult to describe the final procedure adequately because a written specification differs enormously from the final Flash movie. To put it simply, it is impossible to describe the color of a drawing in a language alone or to describe a song without certain musical devices, and there is an explanation error. But that doesn't mean that you should give up the whole process of writing the instructions hastily. Instead, you just have to write it in detail enough to make sure you can rely on it to start working on it. In addition, you must know that the work you have done earlier will be leveraged for future work. Near misses, striking difference things are often caused by irresponsible design instructions.
18.1.3 to think that there are other possibilities.
Sometimes, an implementation seems to have a clear logic, it seems obvious that you should write the program according to the algorithm and logic you designed, but when the development progresses to a certain step, you seem to encounter a wall, can not be further, a lot of beginners programming people will invest a lot of time here, Repeatedly check the logic of their own design algorithm and program code compilation, to its countless minor repairs, and eventually into the mire.
However, an experienced software designer will soon realize that his initial judgment may be fundamentally wrong. Many times, there is simple logic behind complex things, and complex logic lurks behind simple things. Completely discard your original algorithm, change your mind, try to guess another possibility, you will find that the wall began to disappear.
People are always willing to do things in a simple way, as well as programming, and that's the right thing to do, but sometimes when a simple method doesn't work, you have to realize that it may be done in a complex way.
Don't always think of things as simple as that, always think of other possibilities.
18.2 Important concepts in object-oriented software development
In the fourth chapter I have simply introduced what is object-oriented software development, you should remember the example of "man" as an object, and when the inattention vicious dog was driven by a vicious dog, he could invoke the "run Away" method as a response to the event.
But anyway, I don't want to make you despise object-oriented software development because of these examples. In fact, the object-oriented meaning is far-reaching and involves many important concepts, and only if you fully understand the meaning of these concepts, you really understand what is called object-oriented. Many of the concepts you should know, but limited to space, in this section I will explain the most important of the nine.
Nine basic concepts in object-oriented Software development: Classes, objects, attributes, methods, abstractions, encapsulation, inheritance, polymorphism, and events.
18.2.1 Classes and objects
A class is a software abstraction of an object and a template for creating an object. For example, if a person is regarded as an object, then the human species can be regarded as a class. A class definition describes a structure, including data and functionality, that is created by the object. A class represents a set of similar objects. An object is an instance of a class.
Why the need for class, imagine such a situation, if we want to write a flash game, there should be some autonomous activities of the villain, these people have the same physical characteristics and activity ability, then, if we want to write for each villain, then the workload is undoubtedly huge and repetitive. In this case, we should create a "villain" category, the future whenever you need a new villain from the "villain" class to generate a villain can be.
In this case, you must have thought of the relationship between the component and the instance. Yes, the relationship between classes and objects is the same as for components and instances, because the components are actually the built-in classes of flash.
18.2.2 Properties and methods
The property is data, and the method is a function. Attributes are things that the class knows, and methods are things that the class accomplishes. Properties and methods are the responsibility of the class. object-oriented software development is based on the concept that the system should be created by objects, and that objects have data and functionality. property defines the data, and the method defines the functionality.
Obviously, in object-oriented development, the most important task is to define classes. When you define a class, you must define its properties and methods. The definition of a property should be straightforward, and you need to define its name and data type. The definition of a method is the process of creating a function, and as needed, you can create a method that accepts parameters and can return a value.
18.2.3 Abstract
The world is very complex, in order to deal with its complexity, in software design, when it is necessary to establish mathematical models of things, we need to generalize or abstract things. Or people as the object, from the perspective of recruitment, we need to know the person's name, sex, age, educational background, work experience, contact, and personality traits, and from a blind date, you need to know the person's age, height, appearance, educational background, family background, and even birthday. or the same person, just a different abstraction of him (or her), the abstraction of a thing will depend on the program you want to design.
Abstraction is a process of analysis, a process of drawing a clear framework around things. Abstractions should include features, properties, methods that are of interest to the application and ignore other factors. This is why the abstraction of recruitment includes educational background and work experience, but does not include the reasons for the birthday. The process of abstraction is the process of defining what the class knows and wants to accomplish.
18.2.4 Package
Although abstraction tells us that we should store the candidate's educational background and work experience for recruiting, it doesn't tell us how to do it. Encapsulation solves the problem of how to model system functionality. In an object-oriented world, we want to model systems as classes, and classes to be modeled as properties and methods. The process of how the design class will accomplish these things is called encapsulation.
Encapsulation describes the problem of how to partition functionality in a system. We don't need to know how objects are implemented internally. Encapsulation implies that we can build the system in any way and, if necessary, modify its internal structure again in the future, as long as the interface between the different functional components in the system does not change, then the changes to one functional part of the system will not affect the other functional parts of the system.
Encapsulation is the process of painting the frame around the object black. You can define anything you want to define, but you don't need to tell the outside world what you are doing. For example, when you go to a bank to access cash, you don't need to know how a bank's data center uses mainframes, minicomputer, and PCs to record your account information, what databases and operating systems they use, and it doesn't matter, because they already encapsulate the functionality of the account service. You just have to walk to the counter and pass the Passbook to the bank's staff. By hiding the details of the function of the account, the bank is free to change the functionality at any time without having to change every user's passbook.
To make your application easier to maintain and increase security and robustness, you need to restrict access to the properties and methods of the class. The basic idea is as follows: If a class wants to get information about another class, it must first ask for permission rather than just bring it in. Think about it, in the real world is actually in accordance with this method of work. If you want to know someone else's name, what should you do? Do you ask the person for his name, or do you steal his wallet and see his ID card?
18.2.5 inheritance
There is often a similarity between different classes. More than two classes often share the same attributes and/or the same method. Because we don't want to write code over and over again, we're going to use this similarity mechanism. Inheritance is the mechanism that makes it easy to reuse existing data and code.
For example, students have names, addresses, mobile phones, and can also run. At the same time, teachers also have these things. There is no doubt that we can develop classes about students and teachers and let them run together. In fact, you only need to develop the student class first, once it runs, make a copy, called the Teacher class, and make some appropriate changes to it. It's easy, but it's not perfect. What would happen if the source code in the student class was wrong? You will have to correct your mistakes in two places. It's going to be a boring job. Wouldn't it be better if there was only one copy of the Code for development and maintenance?
This is the thought of inheritance. With inheritance, you can define a class to encapsulate the similarity between students and teachers. The new class will have property name, address, Mobiletelephone, and method run. We can name this class person.
Once you have defined the person class, you can inherit the student and teacher classes from it. We call the person the superclass of the student and teacher classes, while the student and teacher classes are subclasses of the person class. Any superclass knows and completes things, subclasses also know. Therefore, since the person class can run when it encounters a vicious dog, the student and teacher classes can.
18.2.6 polymorphism
Let's consider this example. You love your girlfriend, you say to her "Dear, I love You", your girlfriend hug you warmly, you also got a kiss, you think this is very good. Then you come to the street and you see a beautiful woman with a temperament, and you say "dear, I love you" to the woman, and you will get some advice about your nerves and morals right away. Then, you come to the hospital, to an old Chinese medicine said "dear, I Love You", the old Chinese medicine will not hesitate to pull your wrist, start for your pulse. You think that whenever I encounter these objects and say, "Dear, I love you," This is certainly going to happen-this is polymorphism.
Polymorphism allows an object to collaborate with other objects without knowing the type of other objects in advance.
There are a few interesting lessons you can learn from this experience:
First, polymorphism hinders your interaction with other objects. You don't discriminate between the types of other objects, you treat them the same way. Your idea is that other objects are people. Polymorphism is a concept that allows this to happen.
Second, different objects respond differently in their own way. Your girlfriend hugs you and kisses you, strange beauties give you advice on nerves and morals, while old Chinese doctors give you a pulse. The same message arrives at different objects, and each completed thing is different. In fact, from the point of view of each object, they did what should be done.
Third, polymorphism can achieve a consistent and appropriate method name. Although each object responds in a proper way to "dear, I love You", I still want to implement different versions of the method.
Polymorphism mainly consists of two aspects:
Overloading of operators: the same operator can function on multiple object types.
Function name overloading: The same function name can act on different object types and produce different effects.
18.2.7 Pieces
The operation of Object-oriented software is carried out with the occurrence of one event, which is called "event-driven". For example, when you appreciate flash animations, there is actually a "go to Frame" event, in which Flash Player will present the contents of each frame, so you can see the picture.
Similarly, when you click on a button, a button event occurs, and the script in the button event is executed, which may take you to a particular scene, a specific frame, or link to a URL.
In object-oriented program design, the entire software is event-driven, which means that if nothing happens, your program will move nowhere, but there is always something going on in the program, and even if all the other events do not happen, there will be time to pass this event at all times.
In the actual development in the later chapters of this book, you will see the practical application of all the above object-oriented concepts.
18.3 Good programming style
Although you will be developing advanced object-oriented software, some of the good programming styles that have been summed up in the process-oriented era will not be obsolete at any time (at least for the foreseeable future). This section will teach you the universal rules that are not mandatory, but adherence to them will undoubtedly make your life easier.
Good style means programming in an easy to maintain way. Your code should be easy enough to enable anyone to understand it. This is not to say that other people need to look at the code you've written (which can happen, of course), but that when you need to debug or modify the error, you can quickly understand what you've developed. It is always easy to lose self-control by trying to build something that ignores the beneficial finishing work. Hasty actions will cause infinite annoyance, so you should always try to follow a good programming style.
Of course, "good" is not easy to get, "good" usually means a lot of work. Here, good means: good name, less repetition, always annotation, and separation of code and data.
18.3.1 a good name.
What is a good name? The concept of good names in the world of programming is very different from the concept of good names in our daily lives. In our daily life, a good name often means a lot of scrutiny: either expressing a parent's good wishes or a wonderful explanation in the dictionary. But a good name in everyday life is bad for a program, and a name like that doesn't provide information other than the name.
In the world of programming, the standard for judging a good name is the ability to provide more information with the fewest characters. In Flash, what we can and need to name is very much, every instance of a button or movie clip, each instance of a text, may need to be named; every variable, every function, every class, must be named.
In Flash, when you name a thing, you should try to make the name reflect all the important information of the thing. For example: FISHCOUNTERMC is a good example of a movie clip that counts fish in a fish tank. Many days later, when you see the name again, you can get a lot of important information in an instant. First, a drill, we can know that the name refers to a movie clip (MC MovieClip), so the name is a movie clip instance name, second, we can see that this is a used to count the movie clip (according to counter), finally, We can infer that this counter should be to count the fish (according to fishes).
When naming a variable, it is useful to be able to reflect the variable's data type in the variable name. Childage_num as a variable to save the age of the child will be good, from the num suffix we can realize that this variable should be saved by the numeric data type.
Sometimes, in order to give things a more meaningful name, to send more information, you will find that the name is getting longer, this is not a good thing, too long name will also cause the difficulty of reading. Because too many long names are stacked together, you will not be able to see the logic of the program, so you should always be on the right side of everything, and many times you need to compromise between sending more information and preventing too long names.
18.3.2 Reduce duplication
To make things easier, each programming job should appear only once in your movie. If your same piece of code appears in two places, then your work on updating and modifying bugs will double. You'll learn a few ways to do this, such as saving a script in a library, saving it in a function, or introducing a movie from the outside. Anytime you plan to copy and paste code, a small voice should ring in your head-"Stop!" ”。 There is always a more concise way to wait for you.
Reducing duplication also means refining the code to do the same work with less code. Think about it, and when you go back and check your program for debugging bugs, every line of code you check must be translated into your mind, and fewer lines you'll read will feel better. Usually, you can do something with fewer steps or less code at any time. Compare the two code snippets in code 1 and Code 2 to achieve the same effect, but the code in code 2 is much more refined.
Code One:
On (release) {
SetProperty ("Highlight", _x, GetProperty ("highlight", _x) +10);
Telltarget ("highlight") {
gotoAndStop (GetProperty ("", _currentframe) +1);
}
}
Code two:
On (release) {
highlight._x+=10;
Highlight.nextframe ();
}
The script in code one implements the same effect as the script in code two, but adds unnecessary complexity. It doesn't mean anything more than the cult of a player who is a lot lower than you.
Admittedly, there is no best way to be legal, but reducing duplication and refining code is no doubt beneficial. Of course, you do not need to reduce the repetition, refining the code this is carried out too thoroughly. The requirements for streamlined code should not be heavier than readability. It's easy to lose self-control and end up with a bunch of code that you can't even read yourself. I will never Shang in a completed piece of code that works-because, really, that's the top priority. Second, your code is usually maintained by you, so it is most important to write code that you can read and understand. Do everything possible to use code that you can understand. If this sometimes means that your code is a bit verbose, it can only be done by it. As time goes on, slowly you will see that your code is gradually being shortened.
Sometimes, when I look at a program that was just a few months ago, I would also question the approach I was using-but only because I was always making progress. If you're going to wait until your technology becomes perfect, you'll have to wait too long. So just put it in and time will prove you can make progress.
18.3.3 always Comment
In Flash, comments are text with//start. Note In Flash is the line of code that is ignored. Note is not the characteristics of flash, turn on any of the computer books involving programming, you will find that there are comments on the importance of the exposition. Indeed, annotations are very important and cannot be overemphasized. Annotations enable you to know the function of each piece of code in months or even years, still able to continue to develop and maintain programs; to be able to read your code when necessary, he or she will look at your kindness and be thankful and swear to be a good boy (or a good girl) like you.
I think I am a bad boy, because I often do not have enough comment on my code until I let it run. But anyway, it's important for me not to keep this step going, because after a few days of writing it, I'll forget all about the code. Without annotations, the understanding of the code will become much more difficult. So take some time to annotate your code, even if you've finished your code and your enthusiasm is dropping. Compare code three without annotations and code four with the same but annotated code. Although you may not understand the details of the code at this time, if there are problems here, you will be able to easily identify the part that contains the problem.
Code three:
Onclipevent (keyUp) {
If Key.getascii () ==13 | Key.getascii () ==0) {
return;
if (Key.getascii () ==8) {
if (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 four:
Onclipevent (keyUp) {
Ignore these characters
if (Key.getascii () ==13 | Key.getascii () ==0) {
Return
}
If they dot repel the grid key
if (Key.getascii () ==8) {
Delete a space?
if (Cur.charat (cur.length-2) = = "") {
_root.wordthistime--;
}
Delete the last character
Cur=cur.slice (0, Cur.length-2) +MBCHR (8);
Did they modify a mistake?
if (_root.wrongplace[_root.place-1]== "X") {
_root.wrongplace.pop ();
_root.wrongs--;
}
Back one grid.
_root.place>0 && _root.place--;
Leave
Return
}
}
Code three is difficult to understand before it is annotated. Code four shows that a little bit of comment makes things clear, even if you don't understand the potential implications of the code.
18.3.4 separation of code and data
All programmers should strive to keep the code (simply the programming script) and the data (or the content of specific projects, such as text and graphics) separate. By keeping the code and data separate, you can easily migrate your programming results to other projects. Similarly, when you want to make significant changes to the content-say, redo the whole project in different languages-you just need to replace the data without touching (or destroying) the code. This is great thought but sometimes difficult to achieve.
Suppose your flash site has some graphic buttons that display a floating ToolTip when the user places his mouse pointer over the button. If you keep the code (the script that makes the ToolTip appear) and the data (the text that actually appears in the ToolTip) separates. You can easily transplant this feature into another language, and all you do is replace the ToolTip with text in another language. Ideally, you keep all the text of all tooltips in one place, which makes porting work much easier. The gist of this idea is that you should try to do as much as you can to make any significant changes to the code or to any one of the data that have no effect on the other.
You can see the separation of code data as a modular form. There are other modular forms-including Flash's Loadmovie (), which enable you to play an independent. swf file inside a larger movie. In addition to the code data separation mentioned, modularity has many other advantages. First, by modularity of your flash movies, users don't have to wait for the entire movie to be downloaded. They can have the option to download those parts that they are interested in. In addition, Modularity allows a project to be stripped clean into several separate parts, allowing these parts to be developed simultaneously. Think of a situation in which only one person can work if your entire movie is composed of only one basic document. Therefore, it can be seen that code data separation and some of its modular forms have many advantages, you should try to maintain a modular thinking to consider the problem.
18.4 ActionScript terminology
We already know a lot of ActionScript terminology, such as classes, objects, properties, methods, events, scripts, and so on. Some of the common terminology in ActionScript will be introduced in this section so that when I mention it later, you won't feel unfamiliar.
identifier -is a string that meets the requirements of a particular rule. Specifically, the first character of the string must be a letter, an underscore (_), or a dollar sign (
instance -refers to an object. An instance of a class is an object. Many people are always confused about the relationship between class, object and instance. Remember, the object is generated from the class to which it belongs. For example, when we create a student object, we say that it is instantiated from the student class.
function -is a reusable piece of code. A function to complete a specific task. You can pass arguments to a function, or you can return a value from a function.
parameter -is a placeholder for passing a value to a function. In the following area function, X and y are the two parameters of the function.
function Area (x,y) {
return x*y;
}
When you call the area function like this, you pass its arguments to the function with the required two values, which are calculated in the function and return the result of its operation to the call location.
Rectanglearea= area (2,3);
There are many other terms in ActionScript that I'll explain in the book when they're covered.