2 Brick Breaker Game

Transcription

2 Brick Breaker Game
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 n e r t o t h e p a d d l e which
// runs a f u n c t i o n e v e r y tim e a frame p a s s e s
mcPaddle . addEventListener ( Event .ENTER FRAME, movePaddle ) ;
}
function movePaddle ( event : Event ) : void {
//The p a d d l e f o l l o w s t h e mouse
mcPaddle . x = mouseX ;
}
beginCode ( ) ;
To close the ActionScript panel, double-click on the tab labeled “ACTIONS - FRAME” as indicated 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 h e mouse g o e s o f f t o o f a r t o t h e l e f t
i f (mouseX < mcPaddle . width / 2 ) {
// Keep t h e p a d d l e on s t a g e
//INSERT CODE HERE
}
// I f t h e mouse g o e s o f f t o o f a r t o t h e r i g h t
i f (mouseX > stage . stageWidth − mcPaddle . width / 2 ) {
// Keep t h e p a d d l e on s t a g e
//INSERT CODE HERE
}
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 n e r t o t h e p a d d l e which
// runs a f u n c t i o n e v e r y tim e a frame p a s s e s
mcPaddle . addEventListener ( Event .ENTER FRAME, movePaddle ) ;
}
Flash Tutorial: Brick Breaker Game
52
function movePaddle ( event : Event ) : void {
//The p a d d l e f o l l o w s t h e mouse
mcPaddle . x = ∗∗∗
// Keeping t h e p a d d l e i n t h e s t a g e
}
// I f t h e mouse g o e s o f f t o o f a r t o t h e l e f t
i f (mouseX < mcPaddle . width / 2 ) {
// Keep t h e p a d d l e on s t a g e
∗∗∗
}
// I f t h e mouse g o e s o f f t o o f a r t o t h e r i g h t
i f (mouseX > stage . stageWidth − mcPaddle . width / 2 ) {
// Keep t h e p a d d l e 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 become 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/
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 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 a r i a b l e s a r e needed f o r moving t h e b a l l
var b a l l X S p e e d :Number = 8 ; //X Speed o f t h e B a l l
var b a l l Y S p e e d :Number = 8 ; //Y Speed o f t h e B a 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 t o t h e b a l l which
// runs a f u n c t i o n e v e r y time a frame p a s s e s
mcBall . addEventListener ( Event .ENTER 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/24th 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 += b a l l X S p e e d ;
mcBall . y += b a l l Y S p e e d ;
}
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
timeline?
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
ENTER FRAME event is raised every 1/24th 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
function:
// Bouncing t h e b a l l o f f o f t h e w a l l s
i f ( mcBall . x >= ∗ ∗ ∗ ) {
// i f t h e b a l l h i t s t h e r i g h t s i d e
// o f t h e s c r e e n , t h e n bounce o f f
b a l l X S p e e d ∗= −1;
}
i f ( mcBall . x <= ∗ ∗ ∗ ) {
// i f t h e b a l l h i t s t h e l e f t s i d e
// o f t h e s c r e e n , t h e n bounce o f f
b a l l X S p e e d ∗= −1;
}
i f ( mcBall . y >= ∗ ∗ ∗ ) {
// i f t h e b a l l h i t s t h e bottom
// t h e n bounce up
b a l l Y S p e e d ∗= −1;
}
i f ( mcBall . y <= ∗ ∗ ∗ ) {
// i f t h e b a l l h i t s t h e t o p
// t h e n bounce down
b a l l Y S p e e d ∗= −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 ) ) {
calcBallAngle ( ) ;
}
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 c a l c B a l l A n g l e ( ) : void {
// b a l l P o s i t i o n i s t h e p o s i t i o n o f t h e b a l l i s on t h e p a d d l e
var b a l l P o s i t i o n :Number = mcBall . x − mcPaddle . x ;
// h i t P e r c e n t c o n v e r t s b a l l P o s i t i o n i n t o a p e r c e n t
// A l l t h e way t o t h e l e f t i s −.5
// A l l t h e way t o t h e r i g h t i s . 5
//The c e n t e r i s 0
var h i t P e r c e n t :Number =
( b a l l P o s i t i o n / ( mcPaddle . width − mcBall . width ) ) − . 5 ;
// Gets t h e h i t P e r c e n t and makes i t a l a r g e r number so t h e
// b a l l a c t u a l l y b o u n c e s
ballXSpeed = h i t P e r c e n t ∗ 1 0 ;
// Making t h e b a l l bounce b a c k up
b a l l Y S p e e d ∗= −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
library).
(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 p l a c e B r i c k s ( ) : void {
// Loop p l a c e s t h e b r i c k s o nto t h e s t a g e
f o r ( var i : i n t =0; i <numBricks ; i ++){
// c r e a t i n g a v a r i a b l e which h o l d s t h e b r i c k i n s t a n c e
var b r i c k : MovieClip = new mcBrickC ( ) ;
// s e t t i n g t h e b r i c k ’ s c o o r d i n a t e s
var s p a c e :Number =
( stage . stageWidth − numBricks ∗ b r i c k . width )
/ ( numBricks + 1 ) ;
b r i c k . x = s p a c e + i ∗ ( b r i c k . width + s p a c e ) ;
brick .y = 20;
// add t h e b r i c k t o t h e s t a g e
addChild ( b r i c k ) ;
}
}
(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
ActionScript).
(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 B r i c k ;
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
from:
var b r i c k : MovieClip = new mcBrickC ( ) ;
to:
var b r i c k : B r i c k = new B r i c k ( ) ;
(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 root
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 ActionScript 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
using 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,
from the 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 : i n t = 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 a l s e ;
(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.
addEventListener ( Event .ENTER FRAME, c h e c k B r i c k s ) ;
(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 c h e c k B r i c k s ( event : Event ) : void {
i f ( brickAmt == 0 ) {
gameOver = t r u e ;
removeEventListener ( Event .ENTER FRAME, c h e c k B r i c k s ) ;
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 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.
...
From this, we can see that the program is 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.
ii.
iii.
iv.
v.
add a variable to keep track of the number of lives;
decrement this variable each time the ball hits the bottom of the stage;
move to the ‘lose’ frame when the number of lives is 0;
add a ‘lose’ frame;
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 ) ;
[ . . Code . . ]
}
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 x t S t a r t . text = ‘ ‘ C l i c k 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 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-vs-silverlight-what-suits-your-needs-best/.
&
%
Flash Tutorial: Brick Breaker Game
65