2. Creating the Paddle (a) Using the Rectangle Tool, draw the ...

hihatcloverSoftware and s/w Development

Jul 4, 2012 (6 years and 15 days ago)


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 change
the 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.A
good 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 important
to use exactly the same cases as used for the name here.This same name will be used to control
the paddle using ActionScript so the name of the object on the stage and the name in the code
must match.
(c) Now,some basic ActionScript is required.Create a new layer named “actions” where all of the
code 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 ne r t o t he paddl e which
//runs a f unct i on every time a frame passes
FRAME,movePaddle );
function movePaddle ( event:Event ):void{
//The paddl e f ol l ows t he mouse
mcPaddle.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 the
stage (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 the
mcPaddleC class has the same property parameters but not necessarily the same
values 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.These
can 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 paddle
to 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 to
the user.Add the following code to the onEnterFrame function.
//I f t he mouse goes of f t oo f ar t o t he l e f t
i f (mouseX < mcPaddle.width/2){
//Keep t he paddl e on s t age
//I f t he mouse goes of f t oo f ar t o t he r i g ht
i f (mouseX > stage.stageWidth − mcPaddle.width/2){
//Keep t he paddl e on s t age
In place of//INSERT CODE HERE,insert the correct coordinate code.Remember to complete
each instruction line with a semi-colon.You can use math equations and properties of the stage
if you feel it is necessary.This code should keep your paddle in bounds regardless of how large
the 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 ne r t o t he paddl e which
//runs a f unct i on every time a frame passes
FRAME,movePaddle );
Flash Tutorial:Brick Breaker Game 52
function movePaddle ( event:Event ):void{
//The paddl e f ol l ows t he mouse
mcPaddle.x = ∗∗∗
//Keeping t he paddl e i n t he s t age
//I f t he mouse goes of f t oo f ar t o t he l e f t
i f (mouseX < mcPaddle.width/2){
//Keep t he paddl e on s t age
//I f t he mouse goes of f t oo f ar t o t he r i g ht
i f (mouseX > stage.stageWidth − mcPaddle.width/2){
//Keep t he paddl e on s t age
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 power
and capabilities.To better understand the background of Flash,check out the
first of Colin Moock’s “Lost ActionScript Weeekend” videos (available at http:
//tv.adobe.com/#pg+16245 — scroll down and watch the video entitled “Course
1 Introduction”)
A more general history of Flash is documented at http://www.adobe.com/
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 pixel
white circle,change it into a Movie Clip symbol named mcBallC,and give the ball an instance
name of mcBall.
(b) Now,before actually creating the code for ball movement,two variables are required.They are the
x “speed variable” and the y “speed variable”.They are actually used to determine the number
of 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’s
good 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 ar i ab l e s are needed f or moving t he b a l l
var bal l XSpeed:Number = 8;//X Speed of t he Bal l
var bal l YSpeed:Number = 8;//Y Speed of t he Bal 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 ne r t o t he b a l l which
//runs a f unct i on every time a frame passes
FRAME,moveBall );
Note that the ActionScript lines above tell the program to run the moveBall function every time
the mcBall object enters a new frame (every 1/24
of a second according to the frame rate).To
do this,a moveBall function must be written.Add this function by including the code below.
function moveBall ( event:Event ):void{
mcBall.x += bal l XSpeed;
mcBall.y += bal l YSpeed;
Flash Tutorial:Brick Breaker Game 54

You might be wondering...
...how can a new frame be entered when there is only one frame on the
The concept of frames in Flash can appear confusing at first.Although only one
frame is used for the entire game,the frame rate is 24 frames per second.Because
no other frames have been created,the flash movie stays at this frame but the
FRAME event is raised every 1/24
of a second.At this point,even though
the 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 being
stopped by anything.The next step is to make the ball bounce off the walls.All that is necessary
is to multiply the x speed by -1 if it hits a vertical wall,and the same for the y speed with a
horizontal wall.Add the following code to the moveBall() function above the lines currently in the
//Bouncing t he b a l l of f of t he wal l s
i f ( mcBall.x >= ∗∗∗){
//i f t he b a l l hi t s t he r i g ht s i de
//of t he screen,then bounce of f
bal l XSpeed ∗= −1;
i f ( mcBall.x <= ∗∗∗){
//i f t he b a l l hi t s t he l e f t s i de
//of t he screen,then bounce of f
bal l XSpeed ∗= −1;
i f ( mcBall.y >= ∗∗∗){
//i f t he b a l l hi t s t he bottom
//then bounce up
bal l YSpeed ∗= −1;
i f ( mcBall.y <= ∗∗∗){
//i f t he b a l l hi t s t he t op
//then bounce down
bal l YSpeed ∗= −1;
Replace the four locations of ‘***’ with the correct conditions that would inform the program
that the ball has rached a side of the stage.The location of the mcBall is determined by its top
left 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 bounce
off the paddle.To add some excitement to the game,the ball should not keep moving at the
same angle the entire time.We’re going to make it change depending on which part of the paddle
it hits.Because this will require more calculation,we’re going to make a new function called
calcBallAngle().First add this code to the beginning of the moveBall() function.
i f ( mcBall.hitTestObject ( mcPaddle ) ){
cal cBal l Angl 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 ActionScript
for this frame.
function cal cBal l Angl e ( ):void{
//b al l Pos i t i on i s t he pos i t i on of t he b a l l i s on t he paddl e
var bal l Pos i t i on:Number = mcBall.x − mcPaddle.x;
//hi t Percent convert s b al l Pos i t i on i nt o a percent
//Al l t he way t o t he l e f t i s −.5
//Al l t he way t o t he r i g ht i s.5
//The cent er i s 0
var hi t Percent:Number =
( bal l Pos i t i on/( mcPaddle.width − mcBall.width) ) −.5;
//Gets t he hi t Percent and makes i t a l ar g e r number so t he
//b a l l ac t ual l y bounces
bal l XSpeed = hi t Per cent ∗ 10;
//Making t he b a l l bounce back up
bal l YSpeed ∗= −1;
4.Placing the Bricks on the Stage
(a) The first step to this is actually making the brick MovieClip.A plain white rectangle with
dimensions 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 for
ActionScript” option and then click OK.Exporting the brick will allow it to be added to the
stage 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 the
(b) Add a variable which will store the number of bricks to be placed on the stage to the beginning
of the ActionScript (below the variable declarations for the ball speed).The code required to do
this is var numBricks:Number = 7;.
(c) Also add the code for a placeBricks() function given below:
function pl aceBr i cks ( ):void{
//Loop pl aces t he b r i c k s onto t he s t age
f or ( var i:int =0;i <numBricks;i ++){
//cr eat i ng a v ar i ab l e which hol ds t he br i ck i nst ance
var br i ck:MovieClip = new mcBrickC( );
//s e t t i ng t he bri ck ’ s coordi nat es
var space:Number =
( stage.stageWidth − numBricks ∗ br i ck.width)
/( numBricks + 1);
br i ck.x = space + i ∗ ( br i ck.width + space );
br i ck.y = 20;
//add t he br i ck t o t he s t age
addChild ( br 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 and
save it in the same folder as your brick breaker.fla game file.This is the code required to handle
breaking the bricks.It is provided to simplify the game development but it is not too complicated
to understand.Open the file in Flash so you can see the code included.The code will appear
in the same area that the stage is displayed for.fla files (not the Actions panel used for.fla file
(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 Bri ck;
Flash Tutorial:Brick Breaker Game 58
(c) We also have to change our previous brick MovieClip,mcBrickC,to the class,Brick.This way,all
of the code in Brick.as will be used in the Brick MovieClip.To do this,right click the mcBrickC
MovieClip in your library and click on Properties.In the resulting pop-up window,change the
class from “mcBrickC” to “Brick”.
(d) In keeping with this modification,we now need to change the line in the placeBricks() function
var br i ck:MovieClip = new mcBrickC( );
var br i ck:Bri ck = new Bri ck ( );
(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 understanding
of 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,in
the placeBricks() function in the game code of the.fla file,the var brick:Brick = new Brick();line
creates a new brick and,at this instant,the Brick constructor function is run.This constructor
sets up two event listeners,one that calls a function to run when the brick is added to the stage
and 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 is
added to the stage.The most important part of this function is the initialization of the
variable.Understanding this is key to grasping a number of other commands in this code.Right
click on the word MovieClip in this line and select “View Help”.This should bring up a browser
window open to the MovieClip entry in the Flash CS4 Professional ActionScript 3.0 Language
Reference.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 the
MovieClip.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” immediately
below the “Public Properties” section heading.Now scroll through the list to find the entry for
root.The description states that the root is “the top-most display object”.In this case,of the
brick,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 root
property 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 a
variable from the game file is accessed and modified.
(l) Using this knowledge,you should now notice that there are several other variables modified by
root that do not actually exist in the.fla file code yet.These are brickAmt (lines 18 and
38) and gameOver (line 23).At this point,references in the code to these variables do nothing
but 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,
fromthe Brick.as file,that we need a brickAmt variable.It can be included by adding the following
line 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 which
is true when the game is over and false when it is not.To maintain consistency with the code in
Brick.as,this must be called gameOver.Insert this line in the same location as the last:
var gameOver:Boolean = f al se;
(c) Now we can better understand how the Brick.as code uses these variables.In line 18,the value
of brickAmt is incremented because the brick has been added to the stage.If the game is over,as
detected by checking the value of the gameOver variable (line 23),the brick will be removed from
the stage.Finally,if the ball hits the brick,the number of bricks is decremented (line 38) because
there 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 can
detect when this occurs by adding a listener that will check if the value of bricks is 0 whenever a
new frame is entered.This can be inserted into the beginCode() function.
FRAME,checkBri cks );
(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 checkBri cks ( event:Event ):void{
i f ( brickAmt == 0){
gameOver = true;
FRAME,checkBri cks );
FRAME,movePaddle );
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 this
does,test the game and play it until all the bricks have been broken.Observe that an Output
panel has opened in the same location as the Timeline panel.In this,an error will be listed.To
read it,close the game.It should say:
ArgumentError:Error#2109:Frame label win not found in scene Scene 1.
Fromthis,we can see that the programis looking for a frame with the label ‘win’.Because there is
no 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 also
infer (based on the use of ‘stop’ in the function name) that this function will direct the game to
stop at this frame (not to continue on to the next frame as it would be default).Therefore,it is
unnecessary 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 Timeline
panel and insert a blank keyframe immediately after the existing frame in Layer 1.Change the
name 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 the
code.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 and
that 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 permit
this.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 implement
this 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 will
therefore 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 click
by 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 mouse
event.To do this,change the beginCode function definition to:
function beginCode ( event:MouseEvent ):void{
stage.removeEventListener(MouseEvent.CLICK,beginCode );
If you test the movie,however,it looks a bit weird.The bricks appear only after clicking.This
can be easily fixed.Just take the placeBricks() out of the beginCode() function and put it at the
bottom of the code.
(c) Next,the player needs to know that they have to click the screen to start.To do this,add a
text box to the middle of the stage.Give it an instance game of txtStart,and make it a dynamic
text box by selecting this option from the drop down box below the instance name field in the
Properties panel.
(d) To include the clicking instructions when necessary,add this code at the end of the frame.
t xt St ar 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 xt St ar 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 there
and how does it compare?
Microsoft provides Silverlight which is more recent than Flash but has
the same purpose.The online Smashing Magazine provides a good
comparison of the two at http://www.smashingmagazine.com/2009/05/09/
Flash Tutorial:Brick Breaker Game 65