19
2 Brick Breaker Game Figure 1: From xkcd.com Flash Tutorial: Brick Breaker Game 47

2 Brick Breaker Game - Dalhousie University - web.cs.dal.caweb.cs.dal.ca/~prof1106/flash_tutorial2.pdf · 2 Brick Breaker Game Figure 1: From xkcd.com ... Test the movie to see how

Embed Size (px)

Citation preview

2 Brick Breaker Game

Figure 1: From xkcd.com

Flash Tutorial: Brick Breaker Game 47

1. Setting up the Game

(a) Create a new Flash File (Action Script 3.0). Ensure that the frame rate is set to 24 and changethe stage colour to black.

(b) Save this newly created file.

Flash Tutorial: Brick Breaker Game 48

2. Creating the Paddle

(a) Using the Rectangle Tool, draw the paddle and convert it into a MovieClip named mcPaddleC. Agood paddle size is 130x10. It should be positioned in approximately the lower third of the stage.

Flash Tutorial: Brick Breaker Game 49

(b) Next, give the paddle the instance name mcPaddle. Note that this is case sensitive so it is importantto use exactly the same cases as used for the name here. This same name will be used to controlthe paddle using ActionScript so the name of the object on the stage and the name in the codemust match.

(c) Now, some basic ActionScript is required. Create a new layer named “actions” where all of thecode will go. Right click on the current frame in the actions layer, select “Actions” from the

menu. In the text window that appears, type in this code:

function beginCode ( ) : void{//Adds a l i s t e n e r to the padd le which// runs a func t i on every time a frame passesmcPaddle . addEventListener (Event .ENTER FRAME, movePaddle ) ;

}

function movePaddle (event :Event ) : void{//The padd le f o l l o w s the mousemcPaddle .x = mouseX ;

}

beginCode ( ) ;

To close the ActionScript panel, double-click on the tab labeled “ACTIONS - FRAME” as indi-cated by the arrow in the figure below.

Flash Tutorial: Brick Breaker Game 50

'

&

$

%

Notice some features of ActionScript:

• a comment in a line begins with // and continues until the end of the line;

• instructions end with the semi-colon character;

• mcPaddle is the same name used for the instance of mcPaddleC that is on thestage (this is essential);

It is also useful to know that the properties that can be modified for the mcPaddle

object are the same as are shown in the properties panel. Any instance of themcPaddleC class has the same property parameters but not necessarily the samevalues for them.

Flash Tutorial: Brick Breaker Game 51

(d) Test the movie to see how the paddle moves with the mouse. There will be a few problems. Thesecan be solved with a proper understanding of the stage coordinates (shown in Figure 2d).

(e) First of all, the paddle is not centered with the mouse, but is left aligned with it. To fix this,you must modify the line mcPaddle.x = mouseX;. You must determine how to change the code.Think about the width property of the paddle. The new code should use the middle of the paddleto follow the mouse instead of the paddle’s x value.

(f) Another problem with this code is that the paddle sometimes runs off stage which is annoying tothe user. Add the following code to the onEnterFrame function.

// I f the mouse goes o f f too f a r to the l e f ti f (mouseX < mcPaddle . width / 2){

//Keep the padd le on s t a g e//INSERT CODE HERE

}// I f the mouse goes o f f too f a r to the r i g h ti f (mouseX > stage . stageWidth − mcPaddle . width / 2){

//Keep the padd le on s t a g e//INSERT CODE HERE

}

In place of //INSERT CODE HERE, insert the correct coordinate code. Remember to completeeach instruction line with a semi-colon. You can use math equations and properties of the stageif you feel it is necessary. This code should keep your paddle in bounds regardless of how largethe stage is or how wide the paddle is.

(g) After completing these steps, the code for the first actions layer frame should be as follows (with‘***’ replaced by the correct code as developed in the previous two steps).

function beginCode ( ) : void{//Adds a l i s t e n e r to the padd le which// runs a func t i on every time a frame passesmcPaddle . addEventListener (Event .ENTER FRAME, movePaddle ) ;

}

Flash Tutorial: Brick Breaker Game 52

function movePaddle (event :Event ) : void{//The padd le f o l l o w s the mousemcPaddle .x = ∗∗∗//Keeping the padd le in the s t a g e

// I f the mouse goes o f f too f a r to the l e f ti f (mouseX < mcPaddle . width / 2){

//Keep the padd le on s t a g e∗∗∗

}// I f the mouse goes o f f too f a r to the r i g h ti f (mouseX > stage . stageWidth − mcPaddle . width / 2){

//Keep the padd le on s t a g e∗∗∗

}}

beginCode ( ) ;'

&

$

%

You might be wondering . . .. . . why is all this code necessary to make cool graphics and animations?ActionScript was not always such an integral part of Flash. It has recently be-come more central to the creation of flash animations to provide more powerand capabilities. To better understand the background of Flash, check out thefirst of Colin Moock’s “Lost ActionScript Weeekend” videos (available at http://tv.adobe.com/#pg+16245 — scroll down and watch the video entitled “Course1 Introduction”)A more general history of Flash is documented at http://www.adobe.com/macromedia/events/john_gay/.

Flash Tutorial: Brick Breaker Game 53

3. Programming the Ball

(a) The next step in creating a brick breaker game is making the ball. Make a small 10x10 pixelwhite circle, change it into a Movie Clip symbol named mcBallC, and give the ball an instancename of mcBall.

(b) Now, before actually creating the code for ball movement, two variables are required. They are thex “speed variable” and the y “speed variable”. They are actually used to determine the numberof pixels that the ball will move for each frame. Add the following code to the very beginning(line 1) of the code that was added to the actions frame for the paddle. To keep organized, it’sgood to keep all variables at the beginning of the code so that they are all in the same place.These values can be adjusted if you wish.

//These v a r i a b l e s are needed f o r moving the b a l lvar ballXSpeed :Number = 8 ; //X Speed o f the Ba l lvar ballYSpeed :Number = 8 ; //Y Speed o f the Ba l l

(c) To use these variables to make the ball move, add the following code to the beginCode() function:

//Adds a l i s t e n e r to the b a l l which// runs a func t i on every time a frame passesmcBall . addEventListener (Event .ENTER FRAME, moveBall ) ;

Note that the ActionScript lines above tell the program to run the moveBall function every timethe mcBall object enters a new frame (every 1/24th of a second according to the frame rate). Todo this, a moveBall function must be written. Add this function by including the code below.

function moveBall (event :Event ) : void{mcBall .x += ballXSpeed ;mcBall .y += ballYSpeed ;

}

Flash Tutorial: Brick Breaker Game 54

'

&

$

%

You might be wondering . . .. . . how can a new frame be entered when there is only one frame on thetimeline?The concept of frames in Flash can appear confusing at first. Although only oneframe is used for the entire game, the frame rate is 24 frames per second. Becauseno other frames have been created, the flash movie stays at this frame but theENTER FRAME event is raised every 1/24th of a second. At this point, even thoughthe playhead in the timeline doesn’t move, the frame is refreshed.

(d) When you test the movie, you should notice that the ball just moves diagonally without beingstopped by anything. The next step is to make the ball bounce off the walls. All that is necessaryis to multiply the x speed by -1 if it hits a vertical wall, and the same for the y speed with ahorizontal wall. Add the following code to the moveBall() function above the lines currently in thefunction:

//Bouncing the b a l l o f f o f the wa l l si f ( mcBall .x >= ∗∗∗){

// i f the b a l l h i t s the r i g h t s i d e// o f the screen , then bounce o f fballXSpeed ∗= −1;

}i f ( mcBall .x <= ∗∗∗){

// i f the b a l l h i t s the l e f t s i d e// o f the screen , then bounce o f fballXSpeed ∗= −1;

}i f ( mcBall .y >= ∗∗∗){

// i f the b a l l h i t s the bottom// then bounce upballYSpeed ∗= −1;

}i f ( mcBall .y <= ∗∗∗){

// i f the b a l l h i t s the top// then bounce downballYSpeed ∗= −1;

}

Replace the four locations of ‘***’ with the correct conditions that would inform the programthat the ball has rached a side of the stage. The location of the mcBall is determined by its topleft corner and this must be taken into account when determining the location of the ball.

(e) Now the ball will just keep on bouncing off the walls. The next step is to make the ball bounceoff the paddle. To add some excitement to the game, the ball should not keep moving at thesame angle the entire time. We’re going to make it change depending on which part of the paddleit hits. Because this will require more calculation, we’re going to make a new function calledcalcBallAngle(). First add this code to the beginning of the moveBall() function.

i f ( mcBall . hitTestObject ( mcPaddle ) ){ca l cBa l lAng l e ( ) ;

}

This runs the calcBallAngle() function whenever the ball hits the paddle.

Flash Tutorial: Brick Breaker Game 55

(f) Below is the code for the calcBallAngle() function which must also be included in the ActionScriptfor this frame.

function ca l cBa l lAng l e ( ) : void{// b a l l P o s i t i o n i s the p o s i t i o n o f the b a l l i s on the padd levar b a l l P o s i t i o n :Number = mcBall .x − mcPaddle .x ;// h i tPercen t conver t s b a l l P o s i t i o n in t o a percent// A l l the way to the l e f t i s −.5// A l l the way to the r i g h t i s .5//The cen ter i s 0var h i tPercent :Number =

( b a l l P o s i t i o n / ( mcPaddle . width − mcBall . width ) ) − . 5 ;//Gets the h i tPercen t and makes i t a l a r g e r number so the// b a l l a c t u a l l y bouncesballXSpeed = hi tPercent ∗ 10 ;//Making the b a l l bounce back upballYSpeed ∗= −1;

}

4. Placing the Bricks on the Stage

(a) The first step to this is actually making the brick MovieClip. A plain white rectangle withdimensions of 55x20 pixels will suffice. When converting this to the mcBrickC MovieClip symbol,press the Advanced button on the “Convert to Symbol” window and choose the “Export forActionScript” option and then click OK. Exporting the brick will allow it to be added to thestage dynamically. A warning will appear but this is fine.

Flash Tutorial: Brick Breaker Game 56

Now the brick should appear in the library. Finally, delete the brick from the stage (but not thelibrary).

(b) Add a variable which will store the number of bricks to be placed on the stage to the beginningof the ActionScript (below the variable declarations for the ball speed). The code required to dothis is var numBricks:Number = 7;.

(c) Also add the code for a placeBricks() function given below:

function p la c eBr i ck s ( ) : void{//Loop p l a c e s the b r i c k s onto the s t a g ef o r (var i : int=0; i<numBricks ; i ++){

// c r ea t i n g a v a r i a b l e which ho l d s the b r i c k in s tancevar br i ck : MovieClip = new mcBrickC ( ) ;// s e t t i n g the br i ck ’ s coord ina t e svar space :Number =

( stage . stageWidth − numBricks ∗ br i ck . width )/ ( numBricks + 1 ) ;

b r i ck .x = space + i ∗ ( b r i ck . width + space ) ;b r i ck .y = 20 ;//add the b r i c k to the s t a g eaddChild ( b r i ck ) ;

}}

(d) Add the line placeBricks (); to the beginning of the beginCode() function.

Flash Tutorial: Brick Breaker Game 57

5. Breaking the Bricks

(a) Download the Brick.as file from http://users.cs.dal.ca/~adsett/downloads/Brick.as andsave it in the same folder as your brick breaker .fla game file. This is the code required to handlebreaking the bricks. It is provided to simplify the game development but it is not too complicatedto understand. Open the file in Flash so you can see the code included. The code will appearin the same area that the stage is displayed for .fla files (not the Actions panel used for .fla fileActionScript).

(b) Switch back to the .fla game file and add the lines below to the beginning of the ActionScript.This allows the game to interact with the code in the Brick.as file.

import Brick ;

Flash Tutorial: Brick Breaker Game 58

(c) We also have to change our previous brick MovieClip, mcBrickC, to the class, Brick. This way, allof the code in Brick.as will be used in the Brick MovieClip. To do this, right click the mcBrickCMovieClip in your library and click on Properties. In the resulting pop-up window, change theclass from “mcBrickC” to “Brick”.

(d) In keeping with this modification, we now need to change the line in the placeBricks() functionfrom:

var br i ck : MovieClip = new mcBrickC ( ) ;

to:

var br i ck : Brick = new Brick ( ) ;

(e) Test the movie to see that the bricks now “break” (vanish) when they are hit by the ball.

(f) Return to the Brick.as file. The next steps are provided to help you gain a better understandingof how ActionScript is being used to control the bricks.

(g) The beginning of the specific description of the Brick is on line 5 (public class Brick extends MovieClip {)).This means that the Brick class has all the functionality of any MovieClip but with more specifics.

(h) A special function, called the constructor, begins on line 8 and is given the same name as the class(Brick). Whenever a new brick is created, this function is automatically run once. For example, inthe placeBricks() function in the game code of the .fla file, the var brick:Brick = new Brick(); linecreates a new brick and, at this instant, the Brick constructor function is run. This constructorsets up two event listeners, one that calls a function to run when the brick is added to the stageand another that runs a function whenever a new frame is entered.

Flash Tutorial: Brick Breaker Game 59

(i) The beginClass function, which spans lines 15 to 20, is the function that runs when the brick isadded to the stage. The most important part of this function is the initialization of the root

variable. Understanding this is key to grasping a number of other commands in this code. Rightclick on the word MovieClip in this line and select “View Help”. This should bring up a browserwindow open to the MovieClip entry in the Flash CS4 Professional ActionScript 3.0 LanguageReference. In this article the MovieClip class is explained. Scroll down to the “Public Properties”section. The MovieClip(root) code is a request to obtain the value of the root property of theMovieClip. Despite this, notice that there is no root property listed amongst the public properties.

(j) The root property is missing because it is a property that is not unique to the MovieClip class.It has been inherited from another class. Select “Show Inherited Public Properties” immediatelybelow the “Public Properties” section heading. Now scroll through the list to find the entry forroot. The description states that the root is “the top-most display object”. In this case, of thebrick, the top-most display object is the stage.The actions in the .fla file are also part of the stage. Therefore, variables in the game file Ac-tionScript become properties of the stage and functions in the file become methods. The rootproperty provides access to these properties and methods.

(k) Go to line 32 of the Brick.as file. This line ( root .ballYSpeed ∗= −1;) changes the ballYSpeed

variable in the game file (in order for the ball to bounce off the brick it has hit). This is how avariable from the game file is accessed and modified.

(l) Using this knowledge, you should now notice that there are several other variables modified byusing root that do not actually exist in the .fla file code yet. These are brickAmt (lines 18 and38) and gameOver (line 23). At this point, references in the code to these variables do nothingbut they will be used to control winning and losing the game (the next part of this tutorial).

Flash Tutorial: Brick Breaker Game 60

6. Winning and Losing the Game

(a) To beat the game (or a level) the number of bricks on the stage must be monitored. We know,from the Brick.as file, that we need a brickAmt variable. It can be included by adding the followingline to the variable section (near the top) of the game code:

var brickAmt : int = 0 ;

(b) We also need to know when the game is over. To do this, we can use a boolean variable whichis true when the game is over and false when it is not. To maintain consistency with the code inBrick.as, this must be called gameOver. Insert this line in the same location as the last:

var gameOver : Boolean = fa l se ;

(c) Now we can better understand how the Brick.as code uses these variables. In line 18, the valueof brickAmt is incremented because the brick has been added to the stage. If the game is over, asdetected by checking the value of the gameOver variable (line 23), the brick will be removed fromthe stage. Finally, if the ball hits the brick, the number of bricks is decremented (line 38) becausethere will be one less brick on the stage.

(d) When brickAmt reaches 0, we know that the player has finished (and won) the game. We candetect when this occurs by adding a listener that will check if the value of bricks is 0 whenever anew frame is entered. This can be inserted into the beginCode() function.

addEventListener (Event .ENTER FRAME, checkBr icks ) ;

(e) The listener calls the checkBricks function when a new frame is entered. To define this function,place this ActionScript at the end of the code, but before the beginCode(); command.

function checkBr icks (event :Event ) : void{i f ( brickAmt == 0){

gameOver = true ;removeEventListener (Event .ENTER FRAME, checkBr icks ) ;mcPaddle . removeEventListener (Event .ENTER FRAME, movePaddle ) ;mcBall . removeEventListener (Event .ENTER FRAME, moveBall ) ;gotoAndStop ( ‘ win ’ ) ;

}}

Flash Tutorial: Brick Breaker Game 61

(f) Note the command gotoAndStop(‘win’); in the above code. To gain an understanding of what thisdoes, test the game and play it until all the bricks have been broken. Observe that an Outputpanel has opened in the same location as the Timeline panel. In this, an error will be listed. Toread it, close the game. It should say:

ArgumentError: Error #2109: Frame label win not found in scene Scene 1....

From this, we can see that the program is looking for a frame with the label ‘win’. Because there isno such frame in the game, an error occurs. It is called an argument error because the name ‘win’cause the problem when it was used as an argument for the gotoAndStop function. Evidently,this function controls the game by moving to the frame with the specified label. We can alsoinfer (based on the use of ‘stop’ in the function name) that this function will direct the game tostop at this frame (not to continue on to the next frame as it would be default). Therefore, it isunnecessary to include the line stop(); at the top of the code for this new frame.

(g) Now that we know what is needed, we can add it. Switch from the Output panel to the Timelinepanel and insert a blank keyframe immediately after the existing frame in Layer 1. Change thename of this frame to ‘win’ in the Properties panel.

(h) Go back to the previous frame on the actions layer and add the line stop(); to the very top of thecode. This will prevent the timeline from automatically progressing to the win frame.

Flash Tutorial: Brick Breaker Game 62

(i) On the new frame, add some text to communicate to the player that they have won the game andthat they may click to play again.

(j) If the user is to be able to click to play the game again, there must be ActionScript to permitthis. Add a new blank keyframe to the actions layer as well. In this frame add the following code:

stage . addEventListener (MouseEvent .CLICK, resetGame ) ;

function resetGame (event :MouseEvent ) : void{stage . removeEventListener (MouseEvent .CLICK, resetGame ) ;gotoAndPlay ( 1 ) ;

}

The gotoAndPlay(1); command moves the game back to the first frame where the game is played.

(k) Now that winning the game is possible, it must also be possible to lose. The steps to implementthis functionality are not complicated. Several things are necessary:

i. add a variable to keep track of the number of lives;ii. decrement this variable each time the ball hits the bottom of the stage;iii. move to the ‘lose’ frame when the number of lives is 0;iv. add a ‘lose’ frame;v. add code to the ‘lose’ frame to allow the user to click to play the game again (note that the

resetGame function has already been implemented in the code for the ‘win’ frame and willtherefore not need to be implemented again).

Using the knowledge acquired in the previous steps, add the capability to lose to the game.

Flash Tutorial: Brick Breaker Game 63

7. Finishing Touches

(a) To start the game only when the user first clicks on the screen, add a listener for a mouse clickby replacing the line beginCode(); with:

stage . addEventListener (MouseEvent .CLICK, beginCode ) ;

(b) In keeping with this, we have to change the beginCode() function itself so it will accept a mouseevent. To do this, change the beginCode function definition to:

function beginCode (event :MouseEvent ) : void{stage . removeEventListener (MouseEvent .CLICK, beginCode ) ;[ . . Code . . ]

}

If you test the movie, however, it looks a bit weird. The bricks appear only after clicking. Thiscan be easily fixed. Just take the placeBricks() out of the beginCode() function and put it at thebottom of the code.

(c) Next, the player needs to know that they have to click the screen to start. To do this, add atext box to the middle of the stage. Give it an instance game of txtStart, and make it a dynamictext box by selecting this option from the drop down box below the instance name field in theProperties panel.

(d) To include the clicking instructions when necessary, add this code at the end of the frame.

t x t S t a r t . text = ‘ ‘ Cl i ck To Begin ’ ’ ;

and, to clear this text once the game begins, add the following code to the beginCode() function:

t x t S t a r t . text = ’ ’ ;

Flash Tutorial: Brick Breaker Game 64

'

&

$

%

You might be wondering . . .. . . now that I’ve worked with the basics of Flash, what else is out thereand how does it compare?Microsoft provides Silverlight which is more recent than Flash but hasthe same purpose. The online Smashing Magazine provides a goodcomparison of the two at http://www.smashingmagazine.com/2009/05/09/flash-vs-silverlight-what-suits-your-needs-best/.

Flash Tutorial: Brick Breaker Game 65