A foreign as2 airplane tutorial (1)

Source: Internet
Author: User
Tags gety types of tables

The author's own level should be very high, but in terms of the Game Model, this game does not have much innovation, and it is still infinite,
However, the idea is already quite complete. With such a good development habit, you won't be able to get started if you want to do something bigger.
The main purpose of this article is to introduce how to use object-oriented as2 to write games,
Therefore, from this perspective, this article is still quite excellent, especially when there is a shortage of domestic materials,
This kind of article can be said to be a good example of Carbon Delivery in the snow. I have translated this article. On the one hand, I have improved myself, and on the other hand, I have given it to a wide range of users.
Make some contributions to flasher ~~~~ (The article has been included in the Flash. You can download the source code here.
Http://www2.flash8.net/teach/2715.htm
)
(For the first time, I 've been turning over something outside China, so what's wrong with it.
By the way, if the author sent you an email saying that he was looking for emilmatthew to collect the copyright of the Chinese version, you would not know me,
Thank you ~~~ :)
)

This document is my first as2 game written using the OOP (Object-Oriented Programming) method.
This standard space hit enemy game has three enemy hosts and a firehose laser for gamers.
At first, there will be only one level, but the design can make it very convenient to increase the number of levels.
The game has basic scores and lifecycles.
Like other people struggling to implement the new actionscript2.0 syntax in Flash mx2004,
This document is also for the benefit of my personal learning.
I will follow a reasonable structure designed by traditional oop.
Thanks very much and respect squize from http://www.1coinplay.com for letting me use his little genie paper (?) As an example.

1. required documents.
2. Use events.
Three types of tables.
4. Interactive tables.
5. Test the initial code.
6. Iteration)
7. Test.
8 release.

**************************************** **************************************** *****
1 requirements:
Spaceship:
Move up, down, and left.
Use the Space key to launch a laser.

Enemy:
Move from right to left at a random height.
There are three instances.
When it removes the screen from the left, it returns to the right.

Background:
Move from left to right.
The foreground is faster than the background movement (parallax ))

LASER:
When the Space key is pressed, the flame is sprayed out of the ship.

Game:
If you hit an enemy, the gamer scores.
If a ship hits an enemy, its life will be lost.
If a player scores a victory, then the player wins and the game starts again.
If the number of lost lives exceeds three, the game ends and the player fails.

2 events used:
The events used represent (designed) requirements in charts. They show different events that may occur in the game, or all the different actions that may occur.

This is all you have to do. It's just a complete implementation (nut?) on a piece of paper ?),
This table provides a good prompt for the classes and methods that will be used.
After you finish this, you need to determine what classes you want to use and what attributes and Methods these classes need.

Class table:
The table of classes shows the relationships between classes.
In the following table, the spacecraft, enemies, laser, and background categories are included in the game category.
This means that the entities of those classes are declared in the game class.
This is called a combination or a "layer" link, which distinguishes it from the inheritance of a "is" link .?
The game classes are aggregated into my Flash files.

Class description:
Spacecraft
Attribute or method type description
Increment of the speed number x variable
Moveship () method uses buttons to move the spacecraft
Setshipx (x) setter _ x
Getshipx () getter returns the value of _ x
Setshipy (y) setter _ y
Getshipy () getter returns the value of _ y.

Enemy aircraft
Attribute or method type description
Increment of the enspeed number x variable
Moveen () method random mobile enemy planes
Setenx (x) setter _ x
Getenx () getter returns the value of _ x.
Seteny (y) setter _ y
Geteny () getter returns the _ y value.

Laser
Attribute or method type description
Fire () method start move when space key is pressed
Setlaserx (x) setter _ x
Getlaserx () getter returns the _ x value.
Setlasery (y) setter _ y
Getlasery () getter returns the _ y value.

Background
Attribute or method type description
Scroll () method shifts from right to left
Setbackx (x) setter _ x
Getbackx () getter returns the value of _ x.
Setbacky (y) setter _ y
Getbacky () getter returns the _ y value.

Games
Attribute or method type description
Score number score of the player
Lives number the number of players
Checkcollisions () method Collision Detection
Checklives (lives) method stops the game if the life value is 0.
Checkscore () method: detects and displays scores

Interactive table
The interactive table describes the information transmitted through methods to meet our initial requirements.
I have no idea whether this plan is effective, because I don't know if flash can process combinations.
Game classes include other classes and are game managers.
However, I do not know whether a class can control a subclass (Instance) inherited from the movieclip class ).
Well, this is the plan. Let's see if it works.
The plan is not put in concrete. If they are invalid, You can discard them, modify them, or even start from the draft.
The most important thing is the process.
Identify the problem through the process and present it to us to solve the problem. This is like concatenating the plot of a movie.
You may come up with a script and aim at the needs of the audience.
Once you get this done, you will throw it aside and use instinct to direct it.
You know the background of the story because you have browsed the process of series plot. The same is true here:

The above is an interactive table I drew.
I even made some changes and realized something that was missing in the class table.
Just like the moveship method requires a direction (left, right, top, bottom) And I can pass a variable dir to which key is pressed.
Dir can be a string class ("Left") or a letter (1, 2, 3, 4). This is not important.

Test priority:
I created a new flash file and created a spaceship_mc (MC), connected it to the ship_mc in the library, and put "spaceship" into the connection (Link) as2 class option.
Then I wrote the following code in the interaction panel:
// Connect to spaceship_mc
Attachmovie ("ship_mc", "myship", getnexthighestdepth ());
// Declare Variables
VaR enarray: array; // It is empty now
VaR bulletarray: array; // null
VaR mygame = new game (myship, enarray, bulletarray );
// Game loop
_ Root. onenterframe = function (){
Mygame. moveship ("right ");
}
Then I wrote minimal code so that the classes wocould just compile
Then I write down the minimum amount of code so that it can be compiled.
Class game {
// A game class that controls the entire game and contains instances of other classes.
// Declare Variables

VaR ship: Spaceship;
VaR enemyarray: array;
VaR laserarray: array;
(Translator's note: it is best to use private to indicate the above, otherwise there will be no encapsulation significance)
// Constructor
Function game (_ ship: Spaceship, _ enarray: array, _ bullarray: array ){
Ship = _ ship;
Enemyarray = _ enarray;
Laserarray = _ bullarray;
}
(Translator's note: it is better to add "Void" to the end of the function in front of the header, which is more formal .)
}
Then, in the spaceship. As file, I write as follows:
Class spaceship extends movieclip {

}
Then compile, but there is no error.
But there should be some errors because the moveship method hasn't appeared yet? Hmm ?? (Translator's note: I do)
There is nothing in debugging.
Annoying error checking... Oh, okay...
Now I have to write the game. moveship method... I will write it down and test it...
I wrote the moveship method and realized that I had to write another one that can check which key was pressed and return the Dir variable of a sring class.
The chekckey method is used to detect keys.
// Game class
// How to check the buttons:
Function checkkey (): String {
If (key. isdown (key. Right )){
Dir = "right ";
}
If (key. isdown (key. Left )){
Dir = "Left ";
}
If (key. isdown (key. Up )){
Dir = "up ";
}
If (key. isdown (key. Down )){
Dir = "down ";
}
Return dir;
}
// Moveship Method
// 1. Check the buttons
// 2. Assign the variable dir every time you press the key and pass the Dir to the spaceship. Move method.
Function moveship (DIR: string ){
Ship. Move (DIR );
}
After compilation, an error is returned...
"Row 38: No 'move 'method ."
That's great. I got a mistake at the beginning. (The Translator's note, I'll try again) that's exactly what we're looking forward.
Now write down the ship. Move method to clear the error...
This is the idea of "test first" (written by the author: Here we are doing a little stuff, and the main purpose is
This is to try as2 programming. When you are working on your own projects, please be sure to use this mode .)
Implement the methods in a series of tests until they have a problem, and then write the method until it meets the requirements and then move to the next method.
How can I move a ship...

Class game {
// Declare Variables
VaR ship: Spaceship;
VaR enemyarray: array;
VaR laserarray: array;
VaR dir: string;
 
// ===== Constructor ======================
Function game (_ ship: Spaceship, _ enarray: array,
_ Bullarray: array ){
Ship = _ ship;
Enemyarray = _ enarray;
Laserarray = _ bullarray;
}
 
// ===== How to check the buttons ======
Function checkkey (): String {
If (key. isdown (key. Right )){
Dir = "right ";
}
Else if (key. isdown (key. Left )){
Dir = "Left ";
}
Else if (key. isdown (key. Up )){
Dir = "up ";
}
Else if (key. isdown (key. Down )){
Dir = "down ";
}
Else dir = "stop ";
// This takes effect.
// Trace (DIR + "-in game. checkey ");

Return dir;
}
 
// === Method of moving the spacecraft ====
// 1. Check the buttons
// 2. The direction allocated to the variable dir
// 3. Pass the Dir value of the variable to the spaceship. Move method.
Function moveship (DIR: string ){
Ship. Move (checkkey ());

}
} // The end of the game class
In the spacecraft:

Class spaceship extends movieclip {
VaR dir: string;
Function move (_ DIR: string ){
Dir = _ DIR;
If (DIR = "Left") _ x-= 20;
If (DIR = "right") _ x + = 20;
If (DIR = "up") _ y-= 20;
If (DIR = "down") _ y + = 20;
If (DIR = "stop "){
_ X + = 0;
_ Y + = 0;
}
}
} // The spaceship class ends.
I didn't have any trouble when I passed the Dir variable into the ship. Move method. Then I tried to directly use the checkkey method because it always returns the Dir. Of course, this works.
Then I have to add a stop in it... at any time when the keys are pressed, the movements of the spacecraft are a bit ridiculous. This state continues until I can smooth the movements later...
But I know that my design works.
I just want to pass the spaceship instance to the game constructor.
Then, haha, presto (for example, if sesame opens the door)... what is next? Well, maybe it's a laser bullet... Okay. Let's go.

 

Launch a laser bullet
It took me two days and I almost couldn't believe it. I keep launching wrong bullets... This is my first attempt to launch a laser bullet.
// In the game class:
// ======= Launch a laser bullet ========
Function firelaser_old (){
If (key. isdown (key. Space )){
// Set start pt of Laser
Laserarray [bulletnum]. _ y = ship. Gety ();
Laserarray [bulletnum]. _ x = ship. getx ();
// If space bar pressed set flag
Hasfired = true;
Bulletnum ++;
If (bulletnum> = 5 ){
Bulletnum = 0;
}
}
}
The above code is very close to the State at the end of my last day. The most practical problem is the movelaser method.
Oh, Haha, I put the laser bullet in the enterframe loop in my fla... a big mistake...
This must be placed in the onkeydown event of the FLA file. This is the current situation:

// In the actions Panel of the FLA File
Attachmovie ("ship_mc", "myship", getnexthighestdepth ());
VaR enarray = new array (3 );
VaR bulletarray = new array (5 );
// Connect to the bullet Array
For (VAR I = 0; I <5; I ++ ){
Attachmovie ("laser_mc", "laser" + I, 100 + I );
Bulletarray [I] = _ root ["laser" + I];
}
// Declare and initialize the entity of the game class
// Input the arrays of spacecraft, enemy planes, and bullets
VaR mygame = new game (myship, enarray, bulletarray );

// ======= Obtain the key value ====================== //
Somelistener = new object ();
Somelistener. onkeydown = function (){
Mygame. firelaser ();
 
};
Key. addlistener (somelistener );

// Game loop
_ Root. onenterframe = function (){
Mygame. checkkey ();
Mygame. moveship (DIR );
Mygame. movelaser ();
}
This is better, but it still does not get the correct bullet launch... The Space key is sent only after two keys are delayed.
Well, well, this is the movelaser method I used this time:
// =========== Move laser ================ //
Function movelaser_old (){
If (hasfired = true ){
Laserarray [bulletnum]. _ x + = 30;
}
If (laserarray [bulletnum]. _ x> stage. width)
{
Laserarray [bulletnum]. _ x =-10;
Hasfired = false;
}
} // ============================ //

The following is the method used to launch a laser bullet.
It operates very easily, get the location of the plane and pass it to the bullet.
Then the number of bullets increases. When the number is greater than 5, it is reinitialized to 0.
// =========== Fire laser ========== //
Function firelaser (){
If (key. isdown (key. Space )){
// Set start point
Laserarray [bulletnum]. _ y = ship. Gety ();
Laserarray [bulletnum]. _ x = ship. getx ();
// Increment the bullet number
++ Bulletnum;
// If more than 5 bullets, start again at 0
If (bulletnum> 5 ){
Bulletnum = 0;
}
}
}
The following is the final method for moving bullets, which is also very simple.
This process traverses all bullets. If a bullet can be provided, move it. It is still not perfect, but it can still be used together.
// ======= Move laser ========== //
Function movelaser (){
VaR bulleti = 0;
While (bulleti <6 ){
Laserarray [bulleti]. _ x + = 30;
Bulleti ++;
}
} // ======================= //

The following are the game categories created so far:

Class game {
// ========== Declare a variable
VaR ship: Spaceship;
VaR enemyarray: array;
VaR laserarray: array;
VaR dir: string;
VaR bulletnum: Number = 0;
 
// ===== Constructor ======================
Function game (_ ship: Spaceship, _ enarray: array,
_ Bullarray: array ){
Ship = _ ship;
Enemyarray = _ enarray;
Laserarray = _ bullarray;
}
 
// ==== Method of checking that the key is pressed ======
Function checkkey (): String {
If (key. isdown (key. Right )){
Dir = "right ";
}
Else if (key. isdown (key. Left )){
Dir = "Left ";
}
Else if (key. isdown (key. Up )){
Dir = "up ";
}
Else if (key. isdown (key. Down )){
Dir = "down ";
}
Else dir = "stop ";
 
Return dir;
}

// === Method of moving the spacecraft ====
// 1. Check the buttons
// 2. The direction allocated to the variable dir
// 3. Pass the Dir value of the variable to the spaceship. Move method.
Function moveship (DIR: string ){
Ship. Move (checkkey ());

}
 
// ============ Fired bullets ======== //
Function firelaser (){
If (key. isdown (key. Space )){
// Set the start position
Laserarray [bulletnum]. _ y = ship. Gety ();
Laserarray [bulletnum]. _ x = ship. getx ();
// Increase the number of bullets
++ Bulletnum;
// If the value is greater than 5, the number starts from 0 again.
If (bulletnum> 5 ){
Bulletnum = 0;
}
}
}
 
// ======= Mobile bullet ============ //
Function movelaser (){
VaR bulleti = 0;
While (bulleti <6 ){
Laserarray [bulleti]. _ x + = 30;
Bulleti ++;
}
} // ======================= //
 

} // ------ The game category ends -------//
 
The following are the spaceship class and its getx and Gety methods:

Class spaceship extends movieclip {
VaR dir: string;
// ===== Mobile ==============
Function move (_ DIR: string ){
Dir = _ DIR;
If (DIR = "Left") _ x-= 20;
If (DIR = "right") _ x + = 20;
If (DIR = "up") _ y-= 20;
If (DIR = "down") _ y + = 20;
If (DIR = "stop "){
_ X + = 0;
_ Y + = 0;
}
}
// ====== Get the X value ====
Function getx (): number {
Return _ x;
}
// ====== Obtain the Y value ====
Function Gety (): number {
Return _ y;
}
} // ==== End of the spaceship class

Here is the laser class:

Class laser extends movieclip {
// ========= Constructor ================ //
Function laser (X: Number, Y: Number ){
_ X = X;
_ Y = y;
}
}

Source code downloaded so far:

Let's go to the second part of this article.

 

 

 

 

 

 

 

 

 

 

 

 

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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